diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000000000..39b4a6eacaa2a8 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,62 @@ +### What does this PR do? + + + + + +- [ ] Documentation or TypeScript types (it's okay to leave the rest blank in this case) +- [ ] Code changes + +### How did you verify your code works? + + + + + + + + + + + + + + + + + + diff --git a/.github/workflows/bun-linux-aarch64.yml b/.github/workflows/bun-linux-aarch64.yml index aaeda6c4e16215..d29fa0b7bcfedd 100644 --- a/.github/workflows/bun-linux-aarch64.yml +++ b/.github/workflows/bun-linux-aarch64.yml @@ -36,7 +36,7 @@ jobs: arch: aarch64 build_arch: arm64 runner: linux-arm64 - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-linux-arm64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-linux-arm64-lto.tar.gz" webkit_basename: "bun-webkit-linux-arm64-lto" build_machine_arch: aarch64 diff --git a/.github/workflows/bun-linux-build.yml b/.github/workflows/bun-linux-build.yml index 9ad92e6b19e6cd..f4b288d8efc0c4 100644 --- a/.github/workflows/bun-linux-build.yml +++ b/.github/workflows/bun-linux-build.yml @@ -46,7 +46,7 @@ jobs: arch: x86_64 build_arch: amd64 runner: big-ubuntu - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-linux-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-linux-amd64-lto.tar.gz" webkit_basename: "bun-webkit-linux-amd64-lto" build_machine_arch: x86_64 - cpu: nehalem @@ -54,7 +54,7 @@ jobs: arch: x86_64 build_arch: amd64 runner: big-ubuntu - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-linux-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-linux-amd64-lto.tar.gz" webkit_basename: "bun-webkit-linux-amd64-lto" build_machine_arch: x86_64 diff --git a/.github/workflows/bun-mac-aarch64.yml b/.github/workflows/bun-mac-aarch64.yml index 7fa73017c0f866..52258374e4cdc1 100644 --- a/.github/workflows/bun-mac-aarch64.yml +++ b/.github/workflows/bun-mac-aarch64.yml @@ -117,7 +117,7 @@ jobs: # obj: bun-obj-darwin-x64-baseline # runner: macos-11 # artifact: bun-obj-darwin-x64-baseline - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: true # compile_obj: false # - cpu: haswell @@ -126,7 +126,7 @@ jobs: # obj: bun-obj-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: true # compile_obj: false # - cpu: nehalem @@ -135,7 +135,7 @@ jobs: # obj: bun-obj-darwin-x64-baseline # runner: macos-11 # artifact: bun-obj-darwin-x64-baseline - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: false # compile_obj: true # - cpu: haswell @@ -144,7 +144,7 @@ jobs: # obj: bun-obj-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: false # compile_obj: true - cpu: native @@ -152,7 +152,7 @@ jobs: tag: bun-darwin-aarch64 obj: bun-obj-darwin-aarch64 artifact: bun-obj-darwin-aarch64 - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-arm64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-arm64-lto.tar.gz" runner: macos-arm64 dependencies: true compile_obj: true @@ -257,7 +257,7 @@ jobs: # package: bun-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64-baseline - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # - cpu: haswell # arch: x86_64 # tag: bun-darwin-x64 @@ -265,14 +265,14 @@ jobs: # package: bun-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" - cpu: native arch: aarch64 tag: bun-darwin-aarch64 obj: bun-obj-darwin-aarch64 package: bun-darwin-aarch64 artifact: bun-obj-darwin-aarch64 - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-arm64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-arm64-lto.tar.gz" runner: macos-arm64 steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/bun-mac-x64-baseline.yml b/.github/workflows/bun-mac-x64-baseline.yml index bd75ec20212e42..049a966918a35d 100644 --- a/.github/workflows/bun-mac-x64-baseline.yml +++ b/.github/workflows/bun-mac-x64-baseline.yml @@ -117,7 +117,7 @@ jobs: obj: bun-obj-darwin-x64-baseline runner: macos-11 artifact: bun-obj-darwin-x64-baseline - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" dependencies: true compile_obj: false # - cpu: haswell @@ -126,7 +126,7 @@ jobs: # obj: bun-obj-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: true # compile_obj: false - cpu: nehalem @@ -135,7 +135,7 @@ jobs: obj: bun-obj-darwin-x64-baseline runner: macos-11 artifact: bun-obj-darwin-x64-baseline - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" dependencies: false compile_obj: true # - cpu: haswell @@ -144,7 +144,7 @@ jobs: # obj: bun-obj-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: false # compile_obj: true # - cpu: native @@ -152,7 +152,7 @@ jobs: # tag: bun-darwin-aarch64 # obj: bun-obj-darwin-aarch64 # artifact: bun-obj-darwin-aarch64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # runner: macos-arm64 # dependencies: true # compile_obj: true @@ -258,7 +258,7 @@ jobs: package: bun-darwin-x64 runner: macos-11 artifact: bun-obj-darwin-x64-baseline - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # - cpu: haswell # arch: x86_64 # tag: bun-darwin-x64 @@ -266,14 +266,14 @@ jobs: # package: bun-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # - cpu: native # arch: aarch64 # tag: bun-darwin-aarch64 # obj: bun-obj-darwin-aarch64 # package: bun-darwin-aarch64 # artifact: bun-obj-darwin-aarch64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # runner: macos-arm64 steps: - uses: actions/checkout@v3 diff --git a/.github/workflows/bun-mac-x64.yml b/.github/workflows/bun-mac-x64.yml index 371486effedf8d..4289c578f31cfa 100644 --- a/.github/workflows/bun-mac-x64.yml +++ b/.github/workflows/bun-mac-x64.yml @@ -117,7 +117,7 @@ jobs: # obj: bun-obj-darwin-x64-baseline # runner: macos-11 # artifact: bun-obj-darwin-x64-baseline - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: true # compile_obj: false - cpu: haswell @@ -126,7 +126,7 @@ jobs: obj: bun-obj-darwin-x64 runner: macos-11 artifact: bun-obj-darwin-x64 - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" dependencies: true compile_obj: false # - cpu: nehalem @@ -135,7 +135,7 @@ jobs: # obj: bun-obj-darwin-x64-baseline # runner: macos-11 # artifact: bun-obj-darwin-x64-baseline - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # dependencies: false # compile_obj: true - cpu: haswell @@ -144,7 +144,7 @@ jobs: obj: bun-obj-darwin-x64 runner: macos-11 artifact: bun-obj-darwin-x64 - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" dependencies: false compile_obj: true # - cpu: native @@ -152,7 +152,7 @@ jobs: # tag: bun-darwin-aarch64 # obj: bun-obj-darwin-aarch64 # artifact: bun-obj-darwin-aarch64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-arm64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-arm64-lto.tar.gz" # runner: macos-arm64 # dependencies: true # compile_obj: true @@ -260,7 +260,7 @@ jobs: # package: bun-darwin-x64 # runner: macos-11 # artifact: bun-obj-darwin-x64-baseline - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" - cpu: haswell arch: x86_64 tag: bun-darwin-x64 @@ -268,14 +268,14 @@ jobs: package: bun-darwin-x64 runner: macos-11 artifact: bun-obj-darwin-x64 - webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-amd64-lto.tar.gz" + webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-amd64-lto.tar.gz" # - cpu: native # arch: aarch64 # tag: bun-darwin-aarch64 # obj: bun-obj-darwin-aarch64 # package: bun-darwin-aarch64 # artifact: bun-obj-darwin-aarch64 - # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-july23/bun-webkit-macos-arm64-lto.tar.gz" + # webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-aug3-2/bun-webkit-macos-arm64-lto.tar.gz" # runner: macos-arm64 steps: - uses: actions/checkout@v3 diff --git a/.gitignore b/.gitignore index eb970e815ce903..f5823c7885d350 100644 --- a/.gitignore +++ b/.gitignore @@ -122,6 +122,9 @@ cold-jsc-start.d /test.ts -src/js/out/modules_dev +src/js/out/modules* +src/js/out/functions* +src/js/out/tmp +src/js/out/DebugPath.h make-dev-stats.csv diff --git a/Dockerfile b/Dockerfile index 304bf680d961cc..9042ea80211c23 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ ARG ARCH=x86_64 ARG BUILD_MACHINE_ARCH=x86_64 ARG TRIPLET=${ARCH}-linux-gnu ARG BUILDARCH=amd64 -ARG WEBKIT_TAG=2023-july23 +ARG WEBKIT_TAG=2023-aug3-2 ARG ZIG_TAG=jul1 ARG ZIG_VERSION="0.11.0-dev.4006+bf827d0b5" ARG WEBKIT_BASENAME="bun-webkit-linux-$BUILDARCH" diff --git a/Makefile b/Makefile index 3de9de27695d08..070d03ec46e5c8 100644 --- a/Makefile +++ b/Makefile @@ -6,8 +6,6 @@ BUN_AUTO_UPDATER_REPO = Jarred-Sumner/bun-releases-for-updater CMAKE_CXX_COMPILER_LAUNCHER_FLAG := - - # 'make' command will trigger the help target .DEFAULT_GOAL := help @@ -20,7 +18,7 @@ CPU_TARGET ?= native MARCH_NATIVE = -mtune=$(CPU_TARGET) NATIVE_OR_OLD_MARCH = -MMD_IF_LOCAL = +MMD_IF_LOCAL = DEFAULT_MIN_MACOS_VERSION= ARCH_NAME := DOCKER_BUILDARCH = @@ -556,22 +554,13 @@ tinycc: PYTHON=$(shell which python 2>/dev/null || which python3 2>/dev/null || which python2 2>/dev/null) -.PHONY: builtins -builtins: - NODE_ENV=production bun src/js/builtins/codegen/index.ts --minify - .PHONY: esm -esm: - NODE_ENV=production bun src/js/build-esm.ts +js: + NODE_ENV=production bun src/js/_codegen/index.ts esm-debug: BUN_DEBUG_QUIET_LOGS=1 NODE_ENV=production bun-debug src/js/build-esm.ts -.PHONY: generate-builtins -generate-builtins: builtins - - - BUN_TYPES_REPO_PATH ?= $(realpath packages/bun-types) ifeq ($(DEBUG),true) @@ -714,44 +703,44 @@ dev-build-obj-wasm: .PHONY: dev-wasm dev-wasm: dev-build-obj-wasm - emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \ - -g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \ + emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init', '_getTests']" \ + -g2 -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \ $(BUN_DEPS_DIR)/libmimalloc.a.wasm \ - packages/debug-bun-freestanding-wasm32/bun-wasm.o $(OPTIMIZATION_LEVEL) --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \ + packages/debug-bun-freestanding-wasm32/bun-wasm.o --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \ -o packages/debug-bun-freestanding-wasm32/bun-wasm.wasm - cp packages/debug-bun-freestanding-wasm32/bun-wasm.wasm src/api/demo/public/bun-wasm.wasm + cp packages/debug-bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm .PHONY: build-obj-wasm build-obj-wasm: $(ZIG) build bun-wasm -Doptimize=ReleaseFast -Dtarget=wasm32-freestanding - emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \ - -g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \ + emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init', '_getTests']" \ + -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \ $(BUN_DEPS_DIR)/libmimalloc.a.wasm \ packages/bun-freestanding-wasm32/bun-wasm.o $(OPTIMIZATION_LEVEL) --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \ -o packages/bun-freestanding-wasm32/bun-wasm.wasm - cp packages/bun-freestanding-wasm32/bun-wasm.wasm src/api/demo/public/bun-wasm.wasm + cp packages/bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm .PHONY: build-obj-wasm-small build-obj-wasm-small: - $(ZIG) build bun-wasm -Doptimize=ReleaseSmall -Dtarget=wasm32-freestanding - emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \ - -g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \ + $(ZIG) build bun-wasm -Doptimize=ReleaseFast -Dtarget=wasm32-freestanding + emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init', '_getTests']" \ + -Oz -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \ $(BUN_DEPS_DIR)/libmimalloc.a.wasm \ packages/bun-freestanding-wasm32/bun-wasm.o -Oz --no-entry --allow-undefined -s ASSERTIONS=0 -s ALLOW_MEMORY_GROWTH=1 -s WASM_BIGINT=1 \ -o packages/bun-freestanding-wasm32/bun-wasm.wasm - cp packages/bun-freestanding-wasm32/bun-wasm.wasm src/api/demo/public/bun-wasm.wasm + cp packages/bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm .PHONY: wasm -wasm: api build-obj-wasm-small +wasm: api mimalloc-wasm build-obj-wasm-small @rm -rf packages/bun-wasm/*.{d.ts,js,wasm,cjs,mjs,tsbuildinfo} @cp packages/bun-freestanding-wasm32/bun-wasm.wasm packages/bun-wasm/bun.wasm @cp src/api/schema.d.ts packages/bun-wasm/schema.d.ts @cp src/api/schema.js packages/bun-wasm/schema.js @cd packages/bun-wasm && $(NPM_CLIENT) run tsc -- -p . - @$(ESBUILD) --sourcemap=external --external:fs --define:process.env.NODE_ENV='"production"' --outdir=packages/bun-wasm --target=esnext --bundle packages/bun-wasm/index.ts --format=esm --minify 2> /dev/null + @bun build --sourcemap=external --external=fs --outdir=packages/bun-wasm --target=browser --minify ./packages/bun-wasm/index.ts @mv packages/bun-wasm/index.js packages/bun-wasm/index.mjs @mv packages/bun-wasm/index.js.map packages/bun-wasm/index.mjs.map - @$(ESBUILD) --sourcemap=external --external:fs --define:process.env.NODE_ENV='"production"' --outdir=packages/bun-wasm --target=esnext --bundle packages/bun-wasm/index.ts --format=cjs --minify --platform=node 2> /dev/null + @$(ESBUILD) --sourcemap=external --external:fs --outdir=packages/bun-wasm --target=esnext --bundle packages/bun-wasm/index.ts --format=cjs --minify --platform=node 2> /dev/null @mv packages/bun-wasm/index.js packages/bun-wasm/index.cjs @mv packages/bun-wasm/index.js.map packages/bun-wasm/index.cjs.map @rm -rf packages/bun-wasm/*.tsbuildinfo @@ -1118,7 +1107,7 @@ dev-obj-linux: $(ZIG) build obj -Dtarget=x86_64-linux-gnu -Dcpu="$(CPU_TARGET)" .PHONY: dev -dev: mkdir-dev esm dev-obj link ## compile zig changes + link bun +dev: mkdir-dev dev-obj link ## compile zig changes + link bun mkdir-dev: mkdir -p $(DEBUG_PACKAGE_DIR) @@ -1203,6 +1192,7 @@ jsc-build-mac-compile: -DPORT="JSCOnly" \ -DENABLE_STATIC_JSC=ON \ -DENABLE_SINGLE_THREADED_VM_ENTRY_SCOPE=ON \ + -DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \ -DCMAKE_BUILD_TYPE=Release \ -DUSE_THIN_ARCHIVES=OFF \ -DBUN_FAST_TLS=ON \ @@ -1225,6 +1215,7 @@ jsc-build-mac-compile-lto: -DPORT="JSCOnly" \ -DENABLE_STATIC_JSC=ON \ -DENABLE_SINGLE_THREADED_VM_ENTRY_SCOPE=ON \ + -DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \ -DCMAKE_BUILD_TYPE=Release \ -DUSE_THIN_ARCHIVES=OFF \ -DBUN_FAST_TLS=ON \ @@ -1252,6 +1243,7 @@ jsc-build-mac-compile-debug: -DUSE_THIN_ARCHIVES=OFF \ -DENABLE_FTL_JIT=ON \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ + -DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \ -G Ninja \ $(CMAKE_FLAGS_WITHOUT_RELEASE) \ -DPTHREAD_JIT_PERMISSIONS_API=1 \ @@ -1275,6 +1267,7 @@ jsc-build-linux-compile-config: -DENABLE_FTL_JIT=ON \ -DENABLE_REMOTE_INSPECTOR=ON \ -DJSEXPORT_PRIVATE=WTF_EXPORT_DECLARATION \ + -DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \ -USE_VISIBILITY_ATTRIBUTE=1 \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -G Ninja \ @@ -1386,7 +1379,8 @@ mimalloc: mimalloc-wasm: - cd $(BUN_DEPS_DIR)/mimalloc; emcmake cmake -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=ON .; emmake make; + rm -rf $(BUN_DEPS_DIR)/mimalloc/CMakeCache* $(BUN_DEPS_DIR)/mimalloc/CMakeFiles + cd $(BUN_DEPS_DIR)/mimalloc; emcmake cmake -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -GNinja -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=OFF .; emmake cmake --build .; cp $(BUN_DEPS_DIR)/mimalloc/$(MIMALLOC_INPUT_PATH) $(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE).wasm # alias for link, incase anyone still types that @@ -1914,11 +1908,11 @@ bun: vendor identifier-cache build-obj bun-link-lld-release bun-codesign-release .PHONY: regenerate-bindings regenerate-bindings: ## compile src/js/builtins + all c++ code, does not link - @make clean-bindings builtins + @make clean-bindings js @make bindings -j$(CPU_COUNT) .PHONY: setup -setup: vendor-dev identifier-cache clean-bindings +setup: vendor-dev identifier-cache clean-bindings js make jsc-check make bindings -j$(CPU_COUNT) @echo "" diff --git a/bench/hot-module-reloading/css-stress-test/tsconfig.json b/bench/hot-module-reloading/css-stress-test/tsconfig.json index 289c8f710e3991..718c2366c42bde 100644 --- a/bench/hot-module-reloading/css-stress-test/tsconfig.json +++ b/bench/hot-module-reloading/css-stress-test/tsconfig.json @@ -5,4 +5,4 @@ "jsx": "react-jsx", "paths": {} } -} \ No newline at end of file +} diff --git a/bench/snippets/private.mjs b/bench/snippets/private.mjs new file mode 100644 index 00000000000000..ca75c6e07aabe4 --- /dev/null +++ b/bench/snippets/private.mjs @@ -0,0 +1,80 @@ +import { bench, run } from "../node_modules/mitata/src/cli.mjs"; +// This is a benchmark of the performance impact of using private properties. + +bench("Polyfillprivate", () => { + "use strict"; + var __classPrivateFieldGet = + (this && this.__classPrivateFieldGet) || + function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + var __classPrivateFieldSet = + (this && this.__classPrivateFieldSet) || + function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; + }; + var _Foo_state, _Foo_inc; + class Foo { + constructor() { + _Foo_state.set(this, 1); + _Foo_inc.set(this, 13); + } + run() { + let n = 1000000; + while (n-- > 0) { + __classPrivateFieldSet( + this, + _Foo_state, + __classPrivateFieldGet(this, _Foo_state, "f") + __classPrivateFieldGet(this, _Foo_inc, "f"), + "f", + ); + } + return n; + } + } + (_Foo_state = new WeakMap()), (_Foo_inc = new WeakMap()); + new Foo().run(); +}); + +bench("NativePrivates", () => { + class Foo { + #state = 1; + #inc = 13; + + run() { + let n = 1000000; + while (n-- > 0) { + this.#state += this.#inc; + } + return n; + } + } + + new Foo().run(); +}); + +bench("ConventionalPrivates", () => { + class Foo { + _state = 1; + _inc = 13; + + run() { + let n = 1000000; + while (n-- > 0) { + this._state += this._inc; + } + return n; + } + } + + new Foo().run(); +}); + +await run(); diff --git a/bench/snippets/request-response-clone.mjs b/bench/snippets/request-response-clone.mjs new file mode 100644 index 00000000000000..05a98065602ab7 --- /dev/null +++ b/bench/snippets/request-response-clone.mjs @@ -0,0 +1,15 @@ +// This mostly exists to check for a memory leak in response.clone() +import { bench, run } from "./runner.mjs"; + +const req = new Request("http://localhost:3000/"); +const resp = await fetch("http://example.com"); + +bench("req.clone().url", () => { + return req.clone().url; +}); + +bench("resp.clone().url", () => { + return resp.clone().url; +}); + +await run(); diff --git a/bench/snippets/resposne-constructor.mjs b/bench/snippets/resposne-constructor.mjs new file mode 100644 index 00000000000000..a15892804c463b --- /dev/null +++ b/bench/snippets/resposne-constructor.mjs @@ -0,0 +1 @@ +for (let i = 0; i < 9999999; i++) new Request("http://aaaaaaaaaaaaaaaaaaaaa"); diff --git a/bench/snippets/webcrypto.mjs b/bench/snippets/webcrypto.mjs new file mode 100644 index 00000000000000..2d1256cf8fd28a --- /dev/null +++ b/bench/snippets/webcrypto.mjs @@ -0,0 +1,20 @@ +import { group } from "mitata"; +import { bench, run } from "./runner.mjs"; + +const sizes = [ + ["small (63 bytes)", 63], + ["medium (4096 bytes)", 4096], + ["large (64 MB)", 64 * 1024 * 1024], +]; +for (let [name, size] of sizes) { + group(name, () => { + var buf = new Uint8Array(size); + for (let algorithm of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) { + bench(algorithm, async () => { + await crypto.subtle.digest(algorithm, buf); + }); + } + }); +} + +await run(); diff --git a/bench/websocket-server/README.md b/bench/websocket-server/README.md index 2578c8d51ba5b6..c583e54bab5aeb 100644 --- a/bench/websocket-server/README.md +++ b/bench/websocket-server/README.md @@ -2,7 +2,7 @@ This benchmarks a websocket server intended as a simple but very active chat room. -First, start the server. By default, it will wait for 16 clients which the client script will handle. +First, start the server. By default, it will wait for 32 clients which the client script will handle. Run in Bun (`Bun.serve`): @@ -19,10 +19,10 @@ node ./chat-server.node.mjs Run in Deno (`Deno.serve`): ```bash -deno run -A --unstable ./chat-server.deno.mjs +deno run -A ./chat-server.deno.mjs ``` -Then, run the client script. By default, it will connect 16 clients. This client script can run in Bun, Node, or Deno +Then, run the client script. By default, it will connect 32 clients. This client script can run in Bun, Node, or Deno ```bash node ./chat-client.mjs diff --git a/build.zig b/build.zig index 569a6bdd2a0bdb..4a20d8481d02d5 100644 --- a/build.zig +++ b/build.zig @@ -182,7 +182,7 @@ pub fn build(b: *Build) !void { is_debug_build = optimize == OptimizeMode.Debug; const bun_executable_name = if (optimize == std.builtin.OptimizeMode.Debug) "bun-debug" else "bun"; const root_src = if (target.getOsTag() == std.Target.Os.Tag.freestanding) - "src/main_wasm.zig" + "root_wasm.zig" else "root.zig"; @@ -322,7 +322,7 @@ pub fn build(b: *Build) !void { const wasm = b.step("bun-wasm", "Build WASM"); var wasm_step = b.addStaticLibrary(.{ .name = "bun-wasm", - .root_source_file = FileSource.relative("src/main_wasm.zig"), + .root_source_file = FileSource.relative("root_wasm.zig"), .target = target, .optimize = optimize, }); @@ -332,6 +332,8 @@ pub fn build(b: *Build) !void { // wasm_step.link_emit_relocs = true; // wasm_step.single_threaded = true; try configureObjectStep(b, wasm_step, @TypeOf(target), target, obj.main_pkg_path.?); + var build_opts = default_build_options; + wasm_step.addOptions("build_options", build_opts.step(b)); } { diff --git a/bun.lockb b/bun.lockb index ac7b5dac53b062..76f7802823d59a 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/completions/bun.zsh b/completions/bun.zsh index a8f66b4fa30613..59df1db47b045f 100644 --- a/completions/bun.zsh +++ b/completions/bun.zsh @@ -49,7 +49,7 @@ _bun() { '--production[Don'"'"'t install devDependencies]' \ '--frozen-lockfile[Disallow changes to lockfile]' \ '--optional[Add dependency to optionalDependencies]' \ - '--development[Add dependency to devDependencies]' \ + '--dev[Add dependency to devDependencies]' \ '-d[Add dependency to devDependencies]' \ '-p[Don'"'"'t install devDependencies]' \ '--no-save[]' \ @@ -91,7 +91,7 @@ _bun() { '--production[Don'"'"'t install devDependencies]' \ '--frozen-lockfile[Disallow changes to lockfile]' \ '--optional[Add dependency to optionalDependencies]' \ - '--development[Add dependency to devDependencies]' \ + '--dev[Add dependency to devDependencies]' \ '-d[Add dependency to devDependencies]' \ '-p[Don'"'"'t install devDependencies]' \ '--no-save[]' \ @@ -127,7 +127,7 @@ _bun() { '--production[Don'"'"'t install devDependencies]' \ '--frozen-lockfile[Disallow changes to lockfile]' \ '--optional[Add dependency to optionalDependencies]' \ - '--development[Add dependency to devDependencies]' \ + '--dev[Add dependency to devDependencies]' \ '-d[Add dependency to devDependencies]' \ '-p[Don'"'"'t install devDependencies]' \ '--no-save[]' \ diff --git a/docs/api/binary-data.md b/docs/api/binary-data.md index 71b02338ff9962..77a54a7620a833 100644 --- a/docs/api/binary-data.md +++ b/docs/api/binary-data.md @@ -927,7 +927,7 @@ Buffer.from(Bun.readableStreamToArrayBuffer(stream)); new Response(stream).text(); // with Bun function -await Bun.readableStreamToString(stream); +await Bun.readableStreamToText(stream); ``` #### To `number[]` diff --git a/docs/api/file-io.md b/docs/api/file-io.md index be9cf0991caecd..e141c8b1718910 100644 --- a/docs/api/file-io.md +++ b/docs/api/file-io.md @@ -1,8 +1,8 @@ {% callout %} - + -**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir`, you can use Bun's [nearly complete](/docs/runtime/nodejs-apis#node_fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module. +**Note** — The `Bun.file` and `Bun.write` APIs documented on this page are heavily optimized and represent the recommended way to perform file-system tasks using Bun. For operations that are not yet available with `Bun.file`, such as `mkdir`, you can use Bun's [nearly complete](/docs/runtime/nodejs-apis#node-fs) implementation of the [`node:fs`](https://nodejs.org/api/fs.html) module. {% /callout %} diff --git a/docs/api/globals.md b/docs/api/globals.md index 370dd3800927d9..fe7cd60c64ae21 100644 --- a/docs/api/globals.md +++ b/docs/api/globals.md @@ -34,7 +34,7 @@ Bun implements the following globals. - [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) - Node.js -- See [Node.js > `Buffer`](/docs/runtime/nodejs-apis#node_buffer) +- See [Node.js > `Buffer`](/docs/runtime/nodejs-apis#node-buffer) --- @@ -172,7 +172,7 @@ Bun implements the following globals. - [`global`](https://nodejs.org/api/globals.html#global) - Node.js -- See [Node.js > `global`](/docs/runtime/nodejs-apis#node_global). +- See [Node.js > `global`](/docs/runtime/nodejs-apis#global). --- @@ -220,7 +220,7 @@ Bun implements the following globals. - [`process`](https://nodejs.org/api/process.html) - Node.js -- See [Node.js > `process`](/docs/runtime/nodejs-apis#node_process) +- See [Node.js > `process`](/docs/runtime/nodejs-apis#node-process) --- diff --git a/docs/api/hashing.md b/docs/api/hashing.md index 3c15e1346f44fe..13a285693fe9c8 100644 --- a/docs/api/hashing.md +++ b/docs/api/hashing.md @@ -77,7 +77,7 @@ The standard `Bun.hash` functions uses [Wyhash](https://github.com/wangyi-fudan/ ```ts Bun.hash("some data here"); -// 976213160445840 +// 11562320457524636935n ``` The input can be a string, `TypedArray`, `DataView`, `ArrayBuffer`, or `SharedArrayBuffer`. @@ -91,14 +91,14 @@ Bun.hash(arr.buffer); Bun.hash(new DataView(arr.buffer)); ``` -Optionally, an integer seed can be specified as the second parameter. +Optionally, an integer seed can be specified as the second parameter. For 64-bit hashes seeds above `Number.MAX_SAFE_INTEGER` should be given as BigInt to avoid loss of precision. ```ts Bun.hash("some data here", 1234); -// 1173484059023252 +// 15724820720172937558n ``` -Additional hashing algorithms are available as properties on `Bun.hash`. The API is the same for each. +Additional hashing algorithms are available as properties on `Bun.hash`. The API is the same for each, only changing the return type from number for 32-bit hashes to bigint for 64-bit hashes. ```ts Bun.hash.wyhash("data", 1234); // equivalent to Bun.hash() @@ -107,6 +107,7 @@ Bun.hash.adler32("data", 1234); Bun.hash.cityHash32("data", 1234); Bun.hash.cityHash64("data", 1234); Bun.hash.murmur32v3("data", 1234); +Bun.hash.murmur32v2("data", 1234); Bun.hash.murmur64v2("data", 1234); ``` diff --git a/docs/api/import-meta.md b/docs/api/import-meta.md index 8e148fffaacc6f..3c22308ce4b312 100644 --- a/docs/api/import-meta.md +++ b/docs/api/import-meta.md @@ -19,17 +19,17 @@ import.meta.resolveSync("zod") --- - `import.meta.dir` -- Absolute path to the directory containing the current fil, e.g. `/path/to/project`. Equivalent to `__dirname` in Node.js. +- Absolute path to the directory containing the current file, e.g. `/path/to/project`. Equivalent to `__dirname` in CommonJS modules (and Node.js) --- - `import.meta.file` -- The name of the current file, e.g. `index.tsx`. Equivalent to `__filename` in Node.js. +- The name of the current file, e.g. `index.tsx` --- - `import.meta.path` -- Absolute path to the current file, e.g. `/path/to/project/index.tx`. +- Absolute path to the current file, e.g. `/path/to/project/index.tx`. Equivalent to `__filename` in CommonJS modules (and Node.js) --- diff --git a/docs/api/spawn.md b/docs/api/spawn.md index 1ef81f1b7ec875..b040272b5dc6cb 100644 --- a/docs/api/spawn.md +++ b/docs/api/spawn.md @@ -12,7 +12,7 @@ The second argument to `Bun.spawn` is a parameters object that can be used to co ```ts const proc = Bun.spawn(["echo", "hello"], { - cwd: "./path/to/subdir", // specify a working direcory + cwd: "./path/to/subdir", // specify a working directory env: { ...process.env, FOO: "bar" }, // specify environment variables onExit(proc, exitCode, signalCode, error) { // exit handler diff --git a/docs/api/streams.md b/docs/api/streams.md index 210090927b1ca9..f0fa75f29dbdc4 100644 --- a/docs/api/streams.md +++ b/docs/api/streams.md @@ -1,6 +1,6 @@ Streams are an important abstraction for working with binary data without loading it all into memory at once. They are commonly used for reading and writing files, sending and receiving network requests, and processing large amounts of data. -Bun implements the Web APIs [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) and [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). +Bun implements the Web APIs [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) and [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream). {% callout %} Bun also implements the `node:stream` module, including [`Readable`](https://nodejs.org/api/stream.html#stream_readable_streams), [`Writable`](https://nodejs.org/api/stream.html#stream_writable_streams), and [`Duplex`](https://nodejs.org/api/stream.html#stream_duplex_and_transform_streams). For complete documentation, refer to the [Node.js docs](https://nodejs.org/api/stream.html). diff --git a/docs/bundler/index.md b/docs/bundler/index.md index da1c3ecaeea339..bfbed2077c9667 100644 --- a/docs/bundler/index.md +++ b/docs/bundler/index.md @@ -482,7 +482,7 @@ n/a {% /codetabs %} -Bun implements a univeral plugin system for both Bun's runtime and bundler. Refer to the [plugin documentation](/docs/bundler/plugins) for complete documentation. +Bun implements a universal plugin system for both Bun's runtime and bundler. Refer to the [plugin documentation](/docs/bundler/plugins) for complete documentation. - -## `--preload` - -To consume this plugin, add this file to the `preload` option in your [`bunfig.toml`](/docs/runtime/configuration). Bun automatically loads the files/modules specified in `preload` before running a file. - -```toml -preload = ["./yamlPlugin.ts"] -``` - -To preload files during `bun test`: - -```toml -[test] -preload = ["./loader.ts"] -``` - -{% details summary="Usage without preload" %} - -Alternatively, you can import this file manually at the top of your project's entrypoint, before any application code is imported. - -```ts#app.ts -import "./yamlPlugin.ts"; -import { config } from "./config.yml"; - -console.log(config); -``` - -{% /details %} - -## Third-party plugins - -By convention, third-party plugins intended for consumption should export a factory function that accepts some configuration and returns a plugin object. - -```ts -import { plugin } from "bun"; -import fooPlugin from "bun-plugin-foo"; - -plugin( - fooPlugin({ - // configuration - }), -); - -// application code -``` - -Bun's plugin API is based on [esbuild](https://esbuild.github.io/plugins). Only [a subset](/docs/bundler/vs-esbuild#plugin-api) of the esbuild API is implemented, but some esbuild plugins "just work" in Bun, like the official [MDX loader](https://mdxjs.com/packages/esbuild/): - -```jsx -import { plugin } from "bun"; -import mdx from "@mdx-js/esbuild"; - -plugin(mdx()); - -import { renderToStaticMarkup } from "react-dom/server"; -import Foo from "./bar.mdx"; -console.log(renderToStaticMarkup()); -``` - -## Loaders - - - - - - - - - -Plugins are primarily used to extend Bun with loaders for additional file types. Let's look at a simple plugin that implements a loader for `.yaml` files. - -```ts#yamlPlugin.ts -import { plugin } from "bun"; - -plugin({ - name: "YAML", - async setup(build) { - const { load } = await import("js-yaml"); - const { readFileSync } = await import("fs"); - - // when a .yaml file is imported... - build.onLoad({ filter: /\.(yaml|yml)$/ }, (args) => { - - // read and parse the file - const text = readFileSync(args.path, "utf8"); - const exports = load(text) as Record; - - // and returns it as a module - return { - exports, - loader: "object", // special loader for JS objects - }; - }); - }, -}); -``` - -With this plugin, data can be directly imported from `.yaml` files. - -{% codetabs %} - -```ts#index.ts -import "./yamlPlugin.ts" -import {name, releaseYear} from "./data.yml" - -console.log(name, releaseYear); -``` - -```yaml#data.yml -name: Fast X -releaseYear: 2023 -``` - -{% /codetabs %} - -Note that the returned object has a `loader` property. This tells Bun which of its internal loaders should be used to handle the result. Even though we're implementing a loader for `.yaml`, the result must still be understandable by one of Bun's built-in loaders. It's loaders all the way down. - -In this case we're using `"object"`—a built-in loader (intended for use by plugins) that converts a plain JavaScript object to an equivalent ES module. Any of Bun's built-in loaders are supported; these same loaders are used by Bun internally for handling files of various kinds. The table below is a quick reference; refer to [Bundler > Loaders](/docs/bundler/loaders) for complete documentation. - -{% table %} - -- Loader -- Extensions -- Output - ---- - -- `js` -- `.mjs` `.cjs` -- Transpile to JavaScript files - ---- - -- `jsx` -- `.js` `.jsx` -- Transform JSX then transpile - ---- - -- `ts` -- `.ts` `.mts` `cts` -- Transform TypeScript then transpile - ---- - -- `tsx` -- `.tsx` -- Transform TypeScript, JSX, then transpile - ---- - -- `toml` -- `.toml` -- Parse using Bun's built-in TOML parser - ---- - -- `json` -- `.json` -- Parse using Bun's built-in JSON parser - ---- - -- `napi` -- `.node` -- Import a native Node.js addon - ---- - -- `wasm` -- `.wasm` -- Import a native Node.js addon - ---- - -- `object` -- _none_ -- A special loader intended for plugins that converts a plain JavaScript object to an equivalent ES module. Each key in the object corresponds to a named export. - -{% /callout %} - -Loading a YAML file is useful, but plugins support more than just data loading. Let's look at a plugin that lets Bun import `*.svelte` files. - -```ts#sveltePlugin.ts -import { plugin } from "bun"; - -await plugin({ - name: "svelte loader", - async setup(build) { - const { compile } = await import("svelte/compiler"); - const { readFileSync } = await import("fs"); - - // when a .svelte file is imported... - build.onLoad({ filter: /\.svelte$/ }, ({ path }) => { - - // read and compile it with the Svelte compiler - const file = readFileSync(path, "utf8"); - const contents = compile(file, { - filename: path, - generate: "ssr", - }).js.code; - - // and return the compiled source code as "js" - return { - contents, - loader: "js", - }; - }); - }, -}); -``` - -> Note: in a production implementation, you'd want to cache the compiled output and include additional error handling. - -The object returned from `build.onLoad` contains the compiled source code in `contents` and specifies `"js"` as its loader. That tells Bun to consider the returned `contents` to be a JavaScript module and transpile it using Bun's built-in `js` loader. - -With this plugin, Svelte components can now be directly imported and consumed. - -```js -import "./sveltePlugin.ts"; -import MySvelteComponent from "./component.svelte"; - -console.log(mySvelteComponent.render()); -``` - -## Reading `Bun.build`'s config - -Plugins can read and write to the [build config](/docs/bundler#api) with `build.config`. - -```ts -Bun.build({ - entrypoints: ["./app.ts"], - outdir: "./dist", - sourcemap: "external", - plugins: [ - { - name: "demo", - setup(build) { - console.log(build.config.sourcemap); // "external" - - build.config.minify = true; // enable minification - - // `plugins` is readonly - console.log(`Number of plugins: ${build.config.plugins.length}`); - }, - }, - ], -}); -``` - -## Reference - -```ts -namespace Bun { - function plugin(plugin: { name: string; setup: (build: PluginBuilder) => void }): void; -} - -type PluginBuilder = { - onResolve: ( - args: { filter: RegExp; namespace?: string }, - callback: (args: { path: string; importer: string }) => { - path: string; - namespace?: string; - } | void, - ) => void; - onLoad: ( - args: { filter: RegExp; namespace?: string }, - callback: (args: { path: string }) => { - loader?: Loader; - contents?: string; - exports?: Record; - }, - ) => void; - config: BuildConfig; -}; - -type Loader = "js" | "jsx" | "ts" | "tsx" | "json" | "toml" | "object"; -``` - -The `onLoad` method optionally accepts a `namespace` in addition to the `filter` regex. This namespace will be be used to prefix the import in transpiled code; for instance, a loader with a `filter: /\.yaml$/` and `namespace: "yaml:"` will transform an import from `./myfile.yaml` into `yaml:./myfile.yaml`. diff --git a/docs/bundler/vs-esbuild.md b/docs/bundler/vs-esbuild.md index 5ccde1a1f7f75b..463fcc13aa9723 100644 --- a/docs/bundler/vs-esbuild.md +++ b/docs/bundler/vs-esbuild.md @@ -897,7 +897,7 @@ const myPlugin: BunPlugin = { }; ``` -The `builder` object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use [`config`](/docs/bundler/plugins#reading-bunbuilds-config) (same thing but with Bun's `BuildConfig` format) instead. +The `builder` object provides some methods for hooking into parts of the bundling process. Bun implements `onResolve` and `onLoad`; it does not yet implement the esbuild hooks `onStart`, `onEnd`, and `onDispose`, and `resolve` utilities. `initialOptions` is partially implemented, being read-only and only having a subset of esbuild's options; use [`config`](/docs/bundler/plugins#reading-the-config) (same thing but with Bun's `BuildConfig` format) instead. ```ts import type { BunPlugin } from "bun"; diff --git a/docs/cli/install.md b/docs/cli/install.md index 584350a42fa694..9b323a8aa82bd7 100644 --- a/docs/cli/install.md +++ b/docs/cli/install.md @@ -40,7 +40,7 @@ On Linux, `bun install` tends to install packages 20-100x faster than `npm insta Running `bun install` will: - **Install** all `dependencies`, `devDependencies`, and `optionalDependencies`. Bun does not install `peerDependencies` by default. -- **Run** your project's `{pre|post}install` scripts at the appropriate time. For security reasons Bun _does not execute_ lifecycle scripts of installed dependencies. +- **Run** your project's `{pre|post}install` and `{pre|post}prepare` scripts at the appropriate time. For security reasons Bun _does not execute_ lifecycle scripts of installed dependencies. - **Write** a `bun.lockb` lockfile to the project root. To install in production mode (i.e. without `devDependencies`): @@ -114,7 +114,7 @@ $ bun add zod@latest To add a package as a dev dependency (`"devDependencies"`): ```bash -$ bun add --development @types/react +$ bun add --dev @types/react $ bun add -d @types/react ``` diff --git a/docs/cli/run.md b/docs/cli/run.md index 60061ee5c2493a..3680573b06a10f 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -126,4 +126,4 @@ Under the hood Bun uses the [JavaScriptCore engine](https://developer.apple.com/ {% image src="/images/bun-run-speed.jpeg" caption="Bun vs Node.js vs Deno running Hello World" /%} - + diff --git a/docs/ecosystem/elysia.md b/docs/ecosystem/elysia.md index b5225e6ce02bba..60dafe98125ce0 100644 --- a/docs/ecosystem/elysia.md +++ b/docs/ecosystem/elysia.md @@ -1,7 +1,7 @@ [Elysia](https://elysiajs.com) is a Bun-first performance focused web framework that takes full advantage of Bun's HTTP, file system, and hot reloading APIs. Designed with TypeScript in mind, you don't need to understand TypeScript to gain the benefit of TypeScript with Elysia. The library understands what you want and automatically infers the type from your code. -:zap: Elysia is [one of the fastest Bun web frameworks](https://github.com/SaltyAom/bun-http-framework-benchmark) +⚡️ Elysia is [one of the fastest Bun web frameworks](https://github.com/SaltyAom/bun-http-framework-benchmark) ```ts#server.ts import { Elysia } from 'elysia' @@ -9,7 +9,7 @@ import { Elysia } from 'elysia' const app = new Elysia() .get('/', () => 'Hello Elysia') .listen(8080) - + console.log(`🦊 Elysia is running at on port ${app.server.port}...`) ``` diff --git a/docs/ecosystem/express.md b/docs/ecosystem/express.md index bbca048abf170e..8f1fccae105dbf 100644 --- a/docs/ecosystem/express.md +++ b/docs/ecosystem/express.md @@ -22,7 +22,7 @@ app.listen(port, () => { Bun implements the [`node:http`](https://nodejs.org/api/http.html) and [`node:https`](https://nodejs.org/api/https.html) modules that these libraries rely on. These modules can also be used directly, though [`Bun.serve`](/docs/api/http) is recommended for most use cases. {% callout %} -**Note** — Refer to the [Runtime > Node.js APIs](/docs/runtime/nodejs-apis#node_http) page for more detailed compatibility information. +**Note** — Refer to the [Runtime > Node.js APIs](/docs/runtime/nodejs-apis#node-http) page for more detailed compatibility information. {% /callout %} ```ts diff --git a/docs/ecosystem/hono.md b/docs/ecosystem/hono.md index c89dce9f7f89d4..e96fbc5c910f25 100644 --- a/docs/ecosystem/hono.md +++ b/docs/ecosystem/hono.md @@ -1,15 +1,16 @@ [Hono](https://github.com/honojs/hono) is a lightweight ultrafast web framework designed for the edge. ```ts -import { Hono } from 'hono' -const app = new Hono() +import { Hono } from "hono"; +const app = new Hono(); -app.get('/', (c) => c.text('Hono!')) +app.get("/", c => c.text("Hono!")); -export default app +export default app; ``` Get started with `bun create` or follow Hono's [Bun quickstart](https://hono.dev/getting-started/bun). + ```bash $ bun create hono ./myapp $ cd myapp diff --git a/docs/guides/binary/arraybuffer-to-array.md b/docs/guides/binary/arraybuffer-to-array.md new file mode 100644 index 00000000000000..688030b0a0d15d --- /dev/null +++ b/docs/guides/binary/arraybuffer-to-array.md @@ -0,0 +1,27 @@ +--- +name: Convert an ArrayBuffer to an array of numbers +--- + +To retrieve the contents of an `ArrayBuffer` as an array of numbers, create a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) over of the buffer. and use the [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) method to convert it to an array. + +```ts +const buf = new ArrayBuffer(64); +const arr = new Uint8Array(buf); +arr.length; // 64 +arr[0]; // 0 (instantiated with all zeros) +``` + +--- + +The `Uint8Array` class supports array indexing and iteration. However if you wish to convert the instance to a regular `Array`, use `Array.from()`. (This will likely be slower than using the `Uint8Array` directly.) + +```ts +const buf = new ArrayBuffer(64); +const uintArr = new Uint8Array(buf); +const regularArr = Array.from(uintArr); +// number[] +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/arraybuffer-to-blob.md b/docs/guides/binary/arraybuffer-to-blob.md new file mode 100644 index 00000000000000..53795282e6613b --- /dev/null +++ b/docs/guides/binary/arraybuffer-to-blob.md @@ -0,0 +1,24 @@ +--- +name: Convert an ArrayBuffer to a Blob +--- + +A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) can be constructed from an array of "chunks", where each chunk is a string, binary data structure, or another `Blob`. + +```ts +const buf = new ArrayBuffer(64); +const blob = new Blob([buf]); +``` + +--- + +By default the `type` of the resulting `Blob` will be unset. This can be set manually. + +```ts +const buf = new ArrayBuffer(64); +const blob = new Blob([buf], { type: "application/octet-stream" }); +blob.type; // => "application/octet-stream" +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/arraybuffer-to-buffer.md b/docs/guides/binary/arraybuffer-to-buffer.md new file mode 100644 index 00000000000000..4aeb54e697acad --- /dev/null +++ b/docs/guides/binary/arraybuffer-to-buffer.md @@ -0,0 +1,25 @@ +--- +name: Convert an ArrayBuffer to a Buffer +--- + +The Node.js [`Buffer`](https://nodejs.org/api/buffer.html) API predates the introduction of `ArrayBuffer` into the JavaScript language. Bun implements both. + +Use the static `Buffer.from()` method to create a `Buffer` from an `ArrayBuffer`. + +```ts +const arrBuffer = new ArrayBuffer(64); +const nodeBuffer = Buffer.from(arrBuffer); +``` + +--- + +To create a `Buffer` that only views a portion of the underlying buffer, pass the offset and length to the constructor. + +```ts +const arrBuffer = new ArrayBuffer(64); +const nodeBuffer = Buffer.from(arrBuffer, 0, 16); // view first 16 bytes +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/arraybuffer-to-string.md b/docs/guides/binary/arraybuffer-to-string.md new file mode 100644 index 00000000000000..13bb83122b2fe1 --- /dev/null +++ b/docs/guides/binary/arraybuffer-to-string.md @@ -0,0 +1,15 @@ +--- +name: Convert an ArrayBuffer to a string +--- + +Bun implements the Web-standard [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) class for converting between binary data types and strings. + +```ts +const buf = new ArrayBuffer(64); +const decoder = new TextDecoder(); +const str = decoder.decode(buf); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/arraybuffer-to-typedarray.md b/docs/guides/binary/arraybuffer-to-typedarray.md new file mode 100644 index 00000000000000..a4e823d8f7e77b --- /dev/null +++ b/docs/guides/binary/arraybuffer-to-typedarray.md @@ -0,0 +1,39 @@ +--- +name: Convert an ArrayBuffer to a Uint8Array +--- + +A `Uint8Array` is a _typed array_, meaning it is a mechanism for viewing the data in an underlying `ArrayBuffer`. + +```ts +const buffer = new ArrayBuffer(64); +const arr = new Uint8Array(buffer); +``` + +--- + +Instances of other typed arrays can be created similarly. + +```ts +const buffer = new ArrayBuffer(64); + +const arr1 = new Uint8Array(buffer); +const arr2 = new Uint16Array(buffer); +const arr3 = new Uint32Array(buffer); +const arr4 = new Float32Array(buffer); +const arr5 = new Float64Array(buffer); +const arr6 = new BigInt64Array(buffer); +const arr7 = new BigUint64Array(buffer); +``` + +--- + +To create a typed array that only views a portion of the underlying buffer, pass the offset and length to the constructor. + +```ts +const buffer = new ArrayBuffer(64); +const arr = new Uint8Array(buffer, 0, 16); // view first 16 bytes +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/binary/blob-to-arraybuffer.md b/docs/guides/binary/blob-to-arraybuffer.md new file mode 100644 index 00000000000000..18e3f1235da7d8 --- /dev/null +++ b/docs/guides/binary/blob-to-arraybuffer.md @@ -0,0 +1,14 @@ +--- +name: Convert a Blob to an ArrayBuffer +--- + +The [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) class provides a number of methods for consuming its contents in different formats, including `.arrayBuffer()`. + +```ts +const blob = new Blob(["hello world"]); +const buf = await blob.arrayBuffer(); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/blob-to-dataview.md b/docs/guides/binary/blob-to-dataview.md new file mode 100644 index 00000000000000..7d874c1f6e0a77 --- /dev/null +++ b/docs/guides/binary/blob-to-dataview.md @@ -0,0 +1,14 @@ +--- +name: Convert a Blob to a DataView +--- + +The [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) class provides a number of methods for consuming its contents in different formats. This snippets reads the contents to an `ArrayBuffer`, then creates a `DataView` from the buffer. + +```ts +const blob = new Blob(["hello world"]); +const arr = new DataView(await blob.arrayBuffer()); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/blob-to-stream.md b/docs/guides/binary/blob-to-stream.md new file mode 100644 index 00000000000000..37a916ab38479e --- /dev/null +++ b/docs/guides/binary/blob-to-stream.md @@ -0,0 +1,14 @@ +--- +name: Convert a Blob to a ReadableStream +--- + +The [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) class provides a number of methods for consuming its contents in different formats, inluding `.stream()`. This returns `Promise`. + +```ts +const blob = new Blob(["hello world"]); +const stream = await blob.stream(); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/blob-to-string.md b/docs/guides/binary/blob-to-string.md new file mode 100644 index 00000000000000..05692c32e8419e --- /dev/null +++ b/docs/guides/binary/blob-to-string.md @@ -0,0 +1,15 @@ +--- +name: Convert a Blob to a string +--- + +The [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) class provides a number of methods for consuming its contents in different formats, inluding `.text()`. + +```ts +const blob = new Blob(["hello world"]); +const str = await blob.text(); +// => "hello world" +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/blob-to-typedarray.md b/docs/guides/binary/blob-to-typedarray.md new file mode 100644 index 00000000000000..efedad02fcb41d --- /dev/null +++ b/docs/guides/binary/blob-to-typedarray.md @@ -0,0 +1,14 @@ +--- +name: Convert a Blob to a Uint8Array +--- + +The [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) class provides a number of methods for consuming its contents in different formats. This snippets reads the contents to an `ArrayBuffer`, then creates a `Uint8Array` from the buffer. + +```ts +const blob = new Blob(["hello world"]); +const arr = new Uint8Array(await blob.arrayBuffer()); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/buffer-to-arraybuffer.md b/docs/guides/binary/buffer-to-arraybuffer.md new file mode 100644 index 00000000000000..56ba78a00a832f --- /dev/null +++ b/docs/guides/binary/buffer-to-arraybuffer.md @@ -0,0 +1,14 @@ +--- +name: Convert a Buffer to an ArrayBuffer +--- + +The Node.js [`Buffer`](https://nodejs.org/api/buffer.html) class provides a way to view and manipulate data in an underlying `ArrayBuffer`, which is available via the `buffer` property. + +```ts +const nodeBuf = Buffer.alloc(64); +const arrBuf = nodeBuf.buffer; +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/buffer-to-blob.md b/docs/guides/binary/buffer-to-blob.md new file mode 100644 index 00000000000000..9f59c9f687a076 --- /dev/null +++ b/docs/guides/binary/buffer-to-blob.md @@ -0,0 +1,14 @@ +--- +name: Convert a Buffer to a blob +--- + +A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) can be constructed from an array of "chunks", where each chunk is a string, binary data structure (including `Buffer`), or another `Blob`. + +```ts +const buf = Buffer.from("hello"); +const blob = new Blob([buf]); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/buffer-to-readablestream.md b/docs/guides/binary/buffer-to-readablestream.md new file mode 100644 index 00000000000000..fbb03df5079323 --- /dev/null +++ b/docs/guides/binary/buffer-to-readablestream.md @@ -0,0 +1,41 @@ +--- +name: Convert a Buffer to a ReadableStream +--- + +The naive approach to creating a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) from a [`Buffer`](https://nodejs.org/api/buffer.html) is to use the `ReadableStream` constructor and enqueue the entire array as a single chunk. For a large buffer, this may be undesirable as this approach does not "streaming" the data in smaller chunks. + +```ts +const buf = Buffer.from("hello world"); +const stream = new ReadableStream({ + start(controller) { + controller.enqueue(buf); + controller.close(); + }, +}); +``` + +--- + +To stream the data in smaller chunks, first create a `Blob` instance from the `Buffer`. Then use the [`Blob.stream()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/stream) method to create a `ReadableStream` that streams the data in chunks of a specified size. + +```ts +const buf = Buffer.from("hello world"); +const blob = new Blob([buf]); +const stream = blob.stream(); +``` + +--- + +The chunk size can be set by passing a number to the `.stream()` method. + +```ts +const buf = Buffer.from("hello world"); +const blob = new Blob([buf]); + +// set chunk size of 1024 bytes +const stream = blob.stream(1024); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/buffer-to-string.md b/docs/guides/binary/buffer-to-string.md new file mode 100644 index 00000000000000..f900cd6a3b0860 --- /dev/null +++ b/docs/guides/binary/buffer-to-string.md @@ -0,0 +1,25 @@ +--- +name: Convert a Buffer to a string +--- + +The [`Buffer`](https://nodejs.org/api/buffer.html) class provides a built-in `.toString()` method that converts a `Buffer` to a string. + +```ts +const buf = Buffer.from("hello"); +const str = buf.toString(); +// => "hello" +``` + +--- + +You can optionally specify an encoding and byte range. + +```ts +const buf = Buffer.from("hello world!"); +const str = buf.toString("utf8", 0, 5); +// => "hello" +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/buffer-to-typedarray.md b/docs/guides/binary/buffer-to-typedarray.md new file mode 100644 index 00000000000000..c59d77218ac465 --- /dev/null +++ b/docs/guides/binary/buffer-to-typedarray.md @@ -0,0 +1,14 @@ +--- +name: Convert a Buffer to a Uint8Array +--- + +The Node.js [`Buffer`](https://nodejs.org/api/buffer.html) class extends [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), so no conversion is needed. All properties and methods on `Uint8Array` are available on `Buffer`. + +```ts +const buf = Buffer.alloc(64); +buf instanceof Uint8Array; // => true +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/dataview-to-string.md b/docs/guides/binary/dataview-to-string.md new file mode 100644 index 00000000000000..0151eaa58d3d64 --- /dev/null +++ b/docs/guides/binary/dataview-to-string.md @@ -0,0 +1,15 @@ +--- +name: Convert a Uint8Array to a string +--- + +If a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) contains ASCII-encoded text, you can convert it to a string using the [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) class. + +```ts +const dv: DataView = ...; +const decoder = new TextDecoder(); +const str = decoder.decode(dv); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/index.json b/docs/guides/binary/index.json new file mode 100644 index 00000000000000..0ddf3da4959e7e --- /dev/null +++ b/docs/guides/binary/index.json @@ -0,0 +1,4 @@ +{ + "name": "Binary data", + "description": "A collection of guides for converting between binary data formats with Bun" +} diff --git a/docs/guides/binary/typedarray-to-arraybuffer.md b/docs/guides/binary/typedarray-to-arraybuffer.md new file mode 100644 index 00000000000000..2458b21c0ddb60 --- /dev/null +++ b/docs/guides/binary/typedarray-to-arraybuffer.md @@ -0,0 +1,25 @@ +--- +name: Convert a Uint8Array to an ArrayBuffer +--- + +A [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) is a _typed array_ class, meaning it is a mechanism for viewing data in an underlying `ArrayBuffer`. The underlying `ArrayBuffer` is accessible via the `buffer` property. + +```ts +const arr = new Uint8Array(64); +arr.buffer; // => ArrayBuffer(64) +``` + +--- + +The `Uint8Array` may be a view over a _subset_ of the data in the underlying `ArrayBuffer`. In this case, the `buffer` property will return the entire buffer, and the `byteOffset` and `byteLength` properties will indicate the subset. + +```ts +const arr = new Uint8Array(64, 16, 32); +arr.buffer; // => ArrayBuffer(64) +arr.byteOffset; // => 16 +arr.byteLength; // => 32 +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/typedarray-to-blob.md b/docs/guides/binary/typedarray-to-blob.md new file mode 100644 index 00000000000000..e2ca301b8bca80 --- /dev/null +++ b/docs/guides/binary/typedarray-to-blob.md @@ -0,0 +1,16 @@ +--- +name: Convert a Uint8Array to a Blob +--- + +A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) can be constructed from an array of "chunks", where each chunk is a string, binary data structure (including `Uint8Array`), or another `Blob`. + +```ts +const arr = new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f]); +const blob = new Blob([arr]); +console.log(await blob.text()); +// => "hello" +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/typedarray-to-buffer.md b/docs/guides/binary/typedarray-to-buffer.md new file mode 100644 index 00000000000000..e4013644aae1e8 --- /dev/null +++ b/docs/guides/binary/typedarray-to-buffer.md @@ -0,0 +1,14 @@ +--- +name: Convert a Uint8Array to a Buffer +--- + +The [`Buffer`](https://nodejs.org/api/buffer.html) class extends [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) with a number of additional methods. Use `Buffer.from()` to create a `Buffer` instance from a `Uint8Array`. + +```ts +const arr: Uint8Array = ... +const buf = Buffer.from(arr); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/typedarray-to-dataview.md b/docs/guides/binary/typedarray-to-dataview.md new file mode 100644 index 00000000000000..dfef2166bde9d4 --- /dev/null +++ b/docs/guides/binary/typedarray-to-dataview.md @@ -0,0 +1,14 @@ +--- +name: Convert a Uint8Array to a DataView +--- + +A [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) is a _typed array_ class, meaning it is a mechanism for viewing data in an underlying `ArrayBuffer`. The following snippet creates a [`DataView`] instance over the same range of data as the `Uint8Array`. + +```ts +const arr: Uint8Array = ... +const dv = new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/typedarray-to-readablestream.md b/docs/guides/binary/typedarray-to-readablestream.md new file mode 100644 index 00000000000000..3be9e29d524bf9 --- /dev/null +++ b/docs/guides/binary/typedarray-to-readablestream.md @@ -0,0 +1,41 @@ +--- +name: Convert a Uint8Array to a ReadableStream +--- + +The naive approach to creating a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) from a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) is to use the [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) constructor and enqueue the entire array as a single chunk. For larger chunks, this may be undesirable as it isn't actually "streaming" the data. + +```ts +const arr = new Uint8Array(64); +const stream = new ReadableStream({ + start(controller) { + controller.enqueue(arr); + controller.close(); + }, +}); +``` + +--- + +To stream the data in smaller chunks, first create a `Blob` instance from the `Uint8Array`. Then use the [`Blob.stream()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob/stream) method to create a `ReadableStream` that streams the data in chunks of a specified size. + +```ts +const arr = new Uint8Array(64); +const blob = new Blob([arr]); +const stream = blob.stream(); +``` + +--- + +The chunk size can be set by passing a number to the `.stream()` method. + +```ts +const arr = new Uint8Array(64); +const blob = new Blob([arr]); + +// set chunk size of 1024 bytes +const stream = blob.stream(1024); +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/binary/typedarray-to-string.md b/docs/guides/binary/typedarray-to-string.md new file mode 100644 index 00000000000000..9c5703420c05da --- /dev/null +++ b/docs/guides/binary/typedarray-to-string.md @@ -0,0 +1,16 @@ +--- +name: Convert a Uint8Array to a string +--- + +Bun implements the Web-standard [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) class for converting from binary data types like `Uint8Array` and strings. + +```ts +const arr = new Uint8Array([104, 101, 108, 108, 111]); +const decoder = new TextDecoder(); +const str = decoder.decode(buf); +// => "hello" +``` + +--- + +See [Docs > API > Binary Data](/docs/api/binary-data#conversion) for complete documentation on manipulating binary data with Bun. diff --git a/docs/guides/ecosystem/discordjs.md b/docs/guides/ecosystem/discordjs.md new file mode 100644 index 00000000000000..7d9541861150fc --- /dev/null +++ b/docs/guides/ecosystem/discordjs.md @@ -0,0 +1,77 @@ +--- +name: Create a Discord bot +--- + +Discord.js works [out of the box](https://bun.sh/blog/bun-v0.6.7) with Bun. Let's write a simple bot. First create a directory and initialize it with `bun init`. + +```bash +mkdir my-bot +cd my-bot +bun init +``` + +--- + +Now install Discord.js. + +```bash +bun add discord.js +``` + +--- + +Before we go further, we need to go to the [Discord developer portal](https://discord.com/developers/applications), login/signup, create a new _Application_, then create a new _Bot_ within that application. Follow the [official guide](https://discordjs.guide/preparations/setting-up-a-bot-application.html#creating-your-bot) for step-by-step instructions. + +--- + +Once complete, you'll be presented with your bot's _private key_. Let's add this to a file called `.env.local`. Bun automatically reads this file and loads it into `process.env`. + +{% callout %} +This is an example token that has already been invalidated. +{% /callout %} + +```txt#.env.local +DISCORD_TOKEN=NzkyNzE1NDU0MTk2MDg4ODQy.X-hvzA.Ovy4MCQywSkoMRRclStW4xAYK7I +``` + +--- + +Be sure to add `.env.local` to your `.gitignore`! It is dangerous to check your bot's private key into version control. + +```txt#.gitignore +node_modules +.env.local +``` + +--- + +Now let's actually write our bot in a new file called `bot.ts`. + +```ts#bot.ts +// import discord.js +import {Client, Events, GatewayIntentBits} from 'discord.js'; + +// create a new Client instance +const client = new Client({intents: [GatewayIntentBits.Guilds]}); + +// listen for the client to be ready +client.once(Events.ClientReady, (c) => { + console.log(`Ready! Logged in as ${c.user.tag}`); +}); + +// login with the token from .env.local +client.login(process.env.DISCORD_TOKEN); +``` + +--- + +Now we can run our bot with `bun run`. It may take a several seconds for the client to initialize the first time you run the file. + +```bash +$ bun run bot.ts +Ready! Logged in as my-bot#1234 +``` + +--- + +You're up and running with a bare-bones Discord.js bot! This is a basic guide to setting up your bot with Bun; we recommend the [official Discord docs](https://discordjs.guide/) for complete information on the `discord.js` API. diff --git a/docs/guides/ecosystem/elysia.md b/docs/guides/ecosystem/elysia.md new file mode 100644 index 00000000000000..ae1a8e37b92ba0 --- /dev/null +++ b/docs/guides/ecosystem/elysia.md @@ -0,0 +1,31 @@ +--- +name: Build an HTTP server using Elysia and Bun +--- + +[Elysia](https://elysiajs.com) is a Bun-first performance focused web framework that takes full advantage of Bun's HTTP, file system, and hot reloading APIs. Get started with `bun create`. + +```bash +$ bun create elysia myapp +$ cd myapp +$ bun run dev +``` + +--- + +To define a simple HTTP route and start a server with Elysia: + +```ts#server.ts +import { Elysia } from 'elysia' + +const app = new Elysia() + .get('/', () => 'Hello Elysia') + .listen(8080) + +console.log(`🦊 Elysia is running at on port ${app.server.port}...`) +``` + +--- + +Elysia is a full-featured server framework with Express-like syntax, type inference, middleware, file uploads, and plugins for JWT authentication, tRPC, and more. It's also is one of the [fastest Bun web frameworks](https://github.com/SaltyAom/bun-http-framework-benchmark). + +Refer to the Elysia [documentation](https://elysiajs.com/quick-start.html) for more information. diff --git a/docs/guides/ecosystem/express.md b/docs/guides/ecosystem/express.md new file mode 100644 index 00000000000000..6042b17e4412cf --- /dev/null +++ b/docs/guides/ecosystem/express.md @@ -0,0 +1,40 @@ +--- +name: Build an HTTP server using Express and Bun +--- + +Express and other major Node.js HTTP libraries should work out of the box. Bun implements the [`node:http`](https://nodejs.org/api/http.html) and [`node:https`](https://nodejs.org/api/https.html) modules that these libraries rely on. + +{% callout %} +Refer to the [Runtime > Node.js APIs](/docs/runtime/nodejs-apis#node-http) page for more detailed compatibility information. +{% /callout %} + +```sh +$ bun add express +``` + +--- + +To define a simple HTTP route and start a server with Express: + +```ts#server.ts +import express from "express"; + +const app = express(); +const port = 8080; + +app.get("/", (req, res) => { + res.send("Hello World!"); +}); + +app.listen(port, () => { + console.log(`Listening on port ${port}...`); +}); +``` + +--- + +To start the server on `localhost`: + +```sh +$ bun server.ts +``` diff --git a/docs/guides/ecosystem/hono.md b/docs/guides/ecosystem/hono.md new file mode 100644 index 00000000000000..6d928a655db255 --- /dev/null +++ b/docs/guides/ecosystem/hono.md @@ -0,0 +1,39 @@ +--- +name: Build an HTTP server using Hono and Bun +--- + +[Hono](https://github.com/honojs/hono) is a lightweight ultrafast web framework designed for the edge. + +```ts +import { Hono } from "hono"; +const app = new Hono(); + +app.get("/", c => c.text("Hono!")); + +export default app; +``` + +--- + +Use `create-hono` to get started with one of Hono's project templates. Select `bun` when prompted for a template. + +```bash +$ bunx create-hono myapp +✔ Which template do you want to use? › bun +cloned honojs/starter#main to /path/to/myapp +✔ Copied project files +$ cd myapp +$ bun install +``` + +--- + +Then start the dev server and visit [localhost:3000](http://localhost:3000). + +```bash +$ bun run dev +``` + +--- + +Refer to Hono's guide on [getting started with Bun](https://hono.dev/getting-started/bun) for more information. diff --git a/docs/guides/ecosystem/index.json b/docs/guides/ecosystem/index.json new file mode 100644 index 00000000000000..4099acec339582 --- /dev/null +++ b/docs/guides/ecosystem/index.json @@ -0,0 +1,4 @@ +{ + "name": "Ecosystem", + "description": "A collection of guides for using various tools and frameworks with Bun" +} diff --git a/docs/guides/ecosystem/mongoose.md b/docs/guides/ecosystem/mongoose.md new file mode 100644 index 00000000000000..bfcb957cc8709c --- /dev/null +++ b/docs/guides/ecosystem/mongoose.md @@ -0,0 +1,80 @@ +--- +name: Read and write data to MongoDB using Mongoose and Bun +--- + +MongoDB and Mongoose work out of the box with Bun. This guide assumes you've already installed MongoDB and are running it as background process/service on your development machine. Follow [this guide](https://www.mongodb.com/docs/manual/installation/) for details. + +--- + +Once MongoDB is running, create a directory and initialize it with `bun init`. + +```bash +mkdir mongoose-app +cd mongoose-app +bun init +``` + +--- + +Then add Mongoose as a dependency. + +```bash +bun add mongoose +``` + +--- + +In `schema.ts` we'll declare and export a simple `Animal` model. + +```ts#schema.ts +import * as mongoose from 'mongoose'; + +const animalSchema = new mongoose.Schema( + { + name: {type: String, required: true}, + sound: {type: String, required: true}, + } +); + +export type Animal = mongoose.InferSchemaType; +export const Animal = mongoose.model('Kitten', animalSchema); +``` + +--- + +Now from `index.ts` we can import `Animal`, connect to MongoDB, and add some data to our database. + +```ts#index.ts +import * as mongoose from 'mongoose'; +import {Animal} from './schema'; + +// connect to database +await mongoose.connect('mongodb://127.0.0.1:27017/mongoose-app'); + +// create new Animal +const cow = new Animal({ + name: 'Cow', + sound: 'Moo', +}); +await cow.save(); // saves to the database + +// read all Animals +const animals = await Animal.find(); +animals[0].speak(); // logs "Moo!" + +// disconect +await mongoose.disconnect(); +``` + +--- + +Lets run this with `bun run`. + +```bash +$ bun run index.ts +Moo! +``` + +--- + +This is a simple introduction to using Mongoose with TypeScript and Bun. As you build your application, refer to the official [MongoDB](https://docs.mongodb.com/) and [Mongoose](https://mongoosejs.com/docs/) sites for complete documentation. diff --git a/docs/guides/ecosystem/nextjs.md b/docs/guides/ecosystem/nextjs.md new file mode 100644 index 00000000000000..b8b45ca594b856 --- /dev/null +++ b/docs/guides/ecosystem/nextjs.md @@ -0,0 +1,31 @@ +--- +name: Build an app with Next.js and Bun +--- + +{% callout %} +Next.js currently relies on Node.js APIs that Bun does not yet implement. The guide below uses Bun to initialize a project and install dependencies, but it uses Node.js to run the dev server. +{% /callout %} + +--- + +Initialize a Next.js app with `create-next-app`. This automatically installs dependencies using `npm`. + +```sh +$ bunx create-next-app +✔ What is your project named? … my-app +✔ Would you like to use TypeScript with this project? … No / Yes +✔ Would you like to use ESLint with this project? … No / Yes +✔ Would you like to use `src/` directory with this project? … No / Yes +✔ Would you like to use experimental `app/` directory with this project? … No / Yes +✔ What import alias would you like configured? … @/* +Creating a new Next.js app in /path/to/my-app. +``` + +--- + +To start the dev server, run `bun run dev` from the project root. + +```sh +$ cd my-app +$ bun run dev +``` diff --git a/docs/guides/ecosystem/prisma.md b/docs/guides/ecosystem/prisma.md new file mode 100644 index 00000000000000..e697e2133ae4b6 --- /dev/null +++ b/docs/guides/ecosystem/prisma.md @@ -0,0 +1,110 @@ +--- +name: Get started using Prisma +--- + +Prisma works out of the box with Bun. First, create a directory and initialize it with `bun init`. + +```bash +mkdir prisma-app +cd prisma-app +bun init +``` + +--- + +Then add Prisma as a dependency. + +```bash +bun add prisma +``` + +--- + +We'll use the Prisma CLI with `bunx` to initialize our schema and migration directory. For simplicity we'll be using an in-memory SQLite database. + +```bash +bunx prisma init --datasource-provider sqlite +``` + +--- + +Open `prisma/schema.prisma` and add a simple `User` model. + +```prisma-diff#prisma/schema.prisma + generator client { + provider = "prisma-client-js" + } + + datasource db { + provider = "sqlite" + url = env("DATABASE_URL") + } + ++ model User { ++ id Int @id @default(autoincrement()) ++ email String @unique ++ name String? ++ } +``` + +--- + +Then generate and run initial migration. + +This will generate a `.sql` migration file in `prisma/migrations`, create a new SQLite instance, and execute the migration against the new instance. + +```bash +bunx prisma migrate dev --name init +``` + +--- + +Prisma automatically generates our _Prisma client_ whenever we execute a new migration. The client provides a fully typed API for reading and writing from our database. + +It can be imported from `@prisma/client`. + +```ts#src/index.ts +import {PrismaClient} from "@prisma/client"; +``` + +--- + +Let's write a simple script to create a new user, then count the number of users in the database. + +```ts#index.ts +import { PrismaClient } from "@prisma/client"; + +const prisma = new PrismaClient(); + +// create a new user +await prisma.user.create({ + data: { + name: "John Dough", + email: `john-${Math.random()}@example.com`, + }, +}); + +// count the number of users +const count = await prisma.user.count(); +console.log(`There are ${count} users in the database.`); +``` + +--- + +Let's run this script with `bun run`. Each time we run it, a new user is created. + +```bash +$ bun run index.ts +Created john-0.12802932895402364@example.com +There are 1 users in the database. +$ bun run index.ts +Created john-0.8671308799782803@example.com +There are 2 users in the database. +$ bun run index.ts +Created john-0.4465968383115295@example.com +There are 3 users in the database. +``` + +--- + +That's it! Now that you've set up Prisma using Bun, we recommend referring to the [official Prisma docs](https://www.prisma.io/docs/concepts/components/prisma-client) as you continue to develop your application. diff --git a/docs/guides/ecosystem/react.md b/docs/guides/ecosystem/react.md new file mode 100644 index 00000000000000..b712e210e36b97 --- /dev/null +++ b/docs/guides/ecosystem/react.md @@ -0,0 +1,30 @@ +--- +name: Use React and JSX +--- + +React just works with Bun. Bun supports `.jsx` and `.tsx` files out of the box. Bun's internal transpiler converts JSX syntax into vanilla JavaScript before execution. + +```tsx#react.tsx +function Component(props: {message: string}) { + return ( + +

{props.message}

+ + ); +} + +console.log(); +``` + +--- + +Bun implements special logging for JSX to make debugging easier. + +```bash +$ bun run react.tsx + +``` + +--- + +Refer to [Runtime > JSX](/docs/runtime/jsx) for complete documentation on configuring JSX. diff --git a/docs/guides/ecosystem/ssr-react.md b/docs/guides/ecosystem/ssr-react.md new file mode 100644 index 00000000000000..59d37db46d35e3 --- /dev/null +++ b/docs/guides/ecosystem/ssr-react.md @@ -0,0 +1,42 @@ +--- +name: Server-side render (SSR) a React component +--- + +To render a React component to an HTML stream server-side (SSR): + +```tsx +import { renderToReadableStream } from "react-dom/server"; + +function Component(props: { message: string }) { + return ( + +

{props.message}

+ + ); +} + +const stream = await renderToReadableStream( + , +); +``` + +--- + +Combining this with `Bun.serve()`, we get a simple SSR HTTP server: + +```tsx +Bun.serve({ + async fetch() { + const stream = await renderToReadableStream( + , + ); + return new Response(stream, { + headers: { "Content-Type": "text/html" }, + }); + }, +}); +``` + +--- + +React `18.3` and later includes an [SSR optimization](https://github.com/facebook/react/pull/25597) that takes advantage of Bun's "direct" `ReadableStream` implementation. diff --git a/docs/guides/ecosystem/stric.md b/docs/guides/ecosystem/stric.md new file mode 100644 index 00000000000000..15ef72cc6e034b --- /dev/null +++ b/docs/guides/ecosystem/stric.md @@ -0,0 +1,53 @@ +--- +name: Build an HTTP server using StricJS and Bun +--- + +[StricJS](https://github.com/bunsvr) is a Bun framework for building high-performance web applications and APIs. + +- **Fast** — Stric is one of the fastest Bun frameworks. See [benchmark](https://github.com/bunsvr/benchmark) for more details. +- **Minimal** — The basic components like `@stricjs/router` and `@stricjs/utils` are under 50kB and require no external dependencies. +- **Extensible** — Stric includes with a plugin system, dependency injection, and optional optimizations for handling requests. + +--- + +Use `bun init` to create an empty project. + +```bash +$ mkdir myapp +$ cd myapp +$ bun init +$ bun add @stricjs/router +``` + +--- + +To implement a simple HTTP server with StricJS: + +```ts#index.ts +import { Router } from '@stricjs/router'; + +export default new Router() + .get('/', () => new Response('Hi')); +``` + +--- + +To serve static files from `/public/*`: + +```ts#index.ts +export default new Router() + .get('/', () => new Response('Hi')) + .get('/public/*', stream('.')); +``` + +--- + +Run the file in watch mode to start the development server. + +```bash +$ bun --watch run index.ts +``` + +--- + +For more info, see Stric's [documentation](https://stricjs.gitbook.io/docs). diff --git a/docs/guides/ecosystem/vite.md b/docs/guides/ecosystem/vite.md new file mode 100644 index 00000000000000..857e11aae65d10 --- /dev/null +++ b/docs/guides/ecosystem/vite.md @@ -0,0 +1,71 @@ +--- +name: Build a frontend using Vite and Bun +--- + +{% callout %} +While Vite currently works with Bun, it has not been heavily optimized, nor has Vite been adapted to use Bun's bundler, module resolver, or transpiler. +{% /callout %} + +--- + +Vite works out of the box with Bun (v0.7 and later). Get started with one of Vite's templates. + +```bash +$ bunx create-vite my-app +✔ Select a framework: › React +✔ Select a variant: › TypeScript + SWC +Scaffolding project in /path/to/my-app... +``` + +--- + +Then `cd` into the project directory and install dependencies. + +```bash +cd my-app +bun install +``` + +--- + +Start the development server with the `vite` CLI using `bunx`. + +The `--bun` flag tells Bun to run Vite's CLI using `bun` instead of `node`; by default Bun respects Vite's `#!/usr/bin/env node` [shebang line](). After Bun 1.0 this flag will no longer be necessary. + +```bash +bunx --bun vite +``` + +--- + +To simplify this command, update the `"dev"` script in `package.json` to the following. + +```json-diff#package.json + "scripts": { +- "dev": "vite", ++ "dev": "bunx --bun vite", + "build": "vite build", + "serve": "vite preview" + }, + // ... +``` + +--- + +Now you can start the development server with `bun run dev`. + +```bash +bun run dev +``` + +--- + +The following command will build your app for production. + +```sh +$ bunx --bun vite build +``` + +--- + +This is a stripped down guide to get you started with Vite + Bun. For more information, see the [Vite documentation](https://vitejs.dev/guide/). diff --git a/docs/guides/http/fetch.md b/docs/guides/http/fetch.md new file mode 100644 index 00000000000000..7b1c0fb8df6287 --- /dev/null +++ b/docs/guides/http/fetch.md @@ -0,0 +1,24 @@ +--- +name: Send an HTTP request using fetch +--- + +Bun implements the Web-standard [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API for sending HTTP requests. To send a simple `GET` request to a URL: + +```ts +const response = await fetch("https://bun.sh"); +const html = await response.text(); // HTML string +``` + +--- + +To send a `POST` request to an API endpoint. + +```ts +const response = await fetch("https://bun.sh/api", { + method: "POST", + body: JSON.stringify({ message: "Hello from Bun!" }), + headers: { "Content-Type": "application/json" }, +}); + +const body = await response.json(); +``` diff --git a/docs/guides/http/file-uploads.md b/docs/guides/http/file-uploads.md new file mode 100644 index 00000000000000..a708a238a77e45 --- /dev/null +++ b/docs/guides/http/file-uploads.md @@ -0,0 +1,94 @@ +--- +name: Upload files via HTTP using FormData +--- + +To upload files via HTTP with Bun, use the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) API. Let's start with a HTTP server that serves a simple HTML web form. + +```ts#index.ts +const server = Bun.serve({ + port: 4000, + async fetch(req) { + const url = new URL(req.url); + + // return index.html for root path + if (url.pathname === "/") + return new Response(Bun.file("index.html"), { + headers: { + "Content-Type": "text/html", + }, + }); + + return new Response("Not Found", { status: 404 }); + }, +}); + +console.log(`Listening on http://localhost:${server.port}`); +``` + +--- + +We can define our HTML form in another file, `index.html`. + +```html#index.html + + + + + Form + + +
+ + + +
+ + +``` + +--- + +At this point, we can run the server and visit [`localhost:4000`](http://localhost:4000) to see our form. + +```bash +$ bun run index.ts +Listening on http://localhost:4000 +``` + +--- + +Our form will send a `POST` request to the `/action` endpoint with the form data. Let's handle that request in our server. + +First we use the [`.formData()`](https://developer.mozilla.org/en-US/docs/Web/API/Request/formData) method on the incoming `Request` to asynchonously parse its contents to a `FormData` instance. Then we can use the [`.get()`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/get) method to extract the value of the `name` and `profilePicture` fields. Here `name` corresponds to a `string` and `profilePicture` is a `Blob`. + +Finally, we write the `Blob` to disk using [`Bun.write()`](/docs/api/file-io#writing-files-bun-write). + +```ts-diff#index.ts +const server = Bun.serve({ + port: 4000, + async fetch(req) { + const url = new URL(req.url); + + // return index.html for root path + if (url.pathname === "/") + return new Response(Bun.file("index.html"), { + headers: { + "Content-Type": "text/html", + }, + }); + ++ // parse formdata at /action ++ if (url.pathname === '/action') { ++ const formdata = await req.formData(); ++ const name = formdata.get('name'); ++ const profilePicture = formdata.get('profilePicture');+ ++ if (!profilePicture) throw new Error('Must upload a profile picture.'); ++ // write profilePicture to disk ++ await Bun.write('profilePicture.png', profilePicture); ++ return new Response("Success"); ++ } + + return new Response("Not Found", { status: 404 }); + }, +}); +``` diff --git a/docs/guides/http/hot.md b/docs/guides/http/hot.md new file mode 100644 index 00000000000000..c033e5be5c7b90 --- /dev/null +++ b/docs/guides/http/hot.md @@ -0,0 +1,55 @@ +--- +name: Hot reload an HTTP server +--- + +Bun supports the [`--hot`](/docs/runtime/hot#hot-mode) flag to run a file with hot reloading enabled. When any module or file changes, Bun re-runs the file. + +```sh +bun --hot run index.ts +``` + +--- + +To avoid re-running `Bun.serve()` during `--hot` reloads, you should assign the `Server` instance as a property of `globalThis`. The `globalThis` object survives hot reloads. + +```ts +import { type Serve, type Server } from "bun"; + +// make TypeScript happy +declare global { + var server: Server; +} + +// define server parameters +const serveOptions: Serve = { + port: 3000, + fetch(req) { + return new Response(`Hello world`); + }, +}; + +if (!globalThis.server) { + globalThis.server = Bun.serve(serveOptions); +} else { + globalThis.server.reload(serveOptions); +} +``` + +--- + +To avoid manually calling `server.reload()`, you can use start a server with Bun's [object syntax](/docs/runtime/hot#http-servers). If you `export default` a plain object with a `fetch` handler defined, then run this file with Bun, Bun will start an HTTP server as if you'd passed this object into `Bun.serve()`. + +With this approach, Bun automatically reloads the server when reloads happen. + +See [HTTP > Hot Reloading](<[/docs/api/http](https://bun.sh/docs/api/http#hot-reloading)>) for full docs. + +```ts +import { type Serve } from "bun"; + +export default { + port: 3000, + fetch(req) { + return new Response(`Hello world`); + }, +} satisfies Serve; +``` diff --git a/docs/guides/http/index.json b/docs/guides/http/index.json new file mode 100644 index 00000000000000..d018e1bdd3ede9 --- /dev/null +++ b/docs/guides/http/index.json @@ -0,0 +1,4 @@ +{ + "name": "HTTP", + "description": "A collection of guides for building HTTP servers with Bun" +} diff --git a/docs/guides/http/simple.md b/docs/guides/http/simple.md new file mode 100644 index 00000000000000..be5147541def6d --- /dev/null +++ b/docs/guides/http/simple.md @@ -0,0 +1,18 @@ +--- +name: Write a simple HTTP server +--- + +This starts an HTTP server listening on port `3000`. It responds to all requests with a `Response` with status `200` and body `"Welcome to Bun!"`. + +See [`Bun.serve`](/docs/api/http) for details. + +```ts +const server = Bun.serve({ + port: 3000, + fetch(request) { + return new Response("Welcome to Bun!"); + }, +}); + +console.log(`Listening on localhost:\${server.port}`); +``` diff --git a/docs/guides/http/stream-file.md b/docs/guides/http/stream-file.md new file mode 100644 index 00000000000000..ab16acf4257a5a --- /dev/null +++ b/docs/guides/http/stream-file.md @@ -0,0 +1,48 @@ +--- +name: Stream a file as an HTTP Response +--- + +This snippet reads a file from disk using [`Bun.file()`](/docs/api/file-io#reading-files-bun-file). This returns a `BunFile` instance, which can be passed directly into the `new Response` constructor. + +```ts +const path = "/path/to/file.txt"; +const file = Bun.file(path); +const resp = new Response(file); +``` + +--- + +The `Content-Type` is read from the file and automatically set on the `Response`. + +```ts +new Response(Bun.file("./package.json")).headers.get("Content-Type"); +// => application/json;charset=utf-8 + +new Response(Bun.file("./test.txt")).headers.get("Content-Type"); +// => text/plain;charset=utf-8 + +new Response(Bun.file("./index.tsx")).headers.get("Content-Type"); +// => text/javascript;charset=utf-8 + +new Response(Bun.file("./img.png")).headers.get("Content-Type"); +// => image/png +``` + +--- + +Putting it all together with [`Bun.serve()`](/docs/api/http#bun-serve). + +```ts +// static file server +Bun.serve({ + async fetch(req) { + const path = new URL(req.url).pathname; + const file = Bun.file(path); + return new Response(file); + }, +}); +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/http/tls.md b/docs/guides/http/tls.md new file mode 100644 index 00000000000000..a7e59dfea90b0c --- /dev/null +++ b/docs/guides/http/tls.md @@ -0,0 +1,30 @@ +--- +name: Configure TLS on an HTTP server +--- + +Set the `tls` key to configure TLS. Both `key` and `cert` are required. The `key` should be the contents of your private key; `cert` should be the contents of your issued certificate. Use [`Bun.file()`](/docs/api/file-io#reading-files-bun-file) to read the contents. + +```ts +const server = Bun.serve({ + fetch: (request) => new Response("Welcome to Bun!"), + tls: { + cert: Bun.file("cert.pem"), + key: Bun.file("key.pem"), + }, +}); +``` + +--- + +By default Bun trusts the default Mozilla-curated list of well-known root CAs. To override this list, pass an array of certificates as `ca`. + +```ts +const server = Bun.serve({ + fetch: (request) => new Response("Welcome to Bun!"), + tls: { + cert: Bun.file("cert.pem"), + key: Bun.file("key.pem"), + ca: [Bun.file("ca1.pem"), Bun.file("ca2.pem")], + }, +}); +``` diff --git a/docs/guides/install/add-dev.md b/docs/guides/install/add-dev.md new file mode 100644 index 00000000000000..3f7b74f9c73bd9 --- /dev/null +++ b/docs/guides/install/add-dev.md @@ -0,0 +1,26 @@ +--- +name: Add a development dependency +--- + +To add an npm package as a development dependency, use `bun add --development`. + +```sh +$ bun add zod --dev +$ bun add zod -d # shorthand +``` + +--- + +This will add the package to `devDependencies` in `package.json`. + +```json-diff +{ + "devDependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-git.md b/docs/guides/install/add-git.md new file mode 100644 index 00000000000000..c98bc29a854ce8 --- /dev/null +++ b/docs/guides/install/add-git.md @@ -0,0 +1,36 @@ +--- +name: Add a Git dependency +--- + +Bun supports directly adding GitHub repositories as dependencies of your project. + +```sh +$ bun add github:lodash/lodash +``` + +--- + +This will add the following line to your `package.json`: + +```json-diff#package.json +{ + "dependencies": { ++ "lodash": "github:lodash/lodash" + } +} +``` + +--- + +Bun supports a number of protocols for specifying Git dependencies. + +```sh +$ bun add git+https://github.com/lodash/lodash.git +$ bun add git+ssh://github.com/lodash/lodash.git#4.17.21 +$ bun add git@github.com:lodash/lodash.git +$ bun add github:colinhacks/zod +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-optional.md b/docs/guides/install/add-optional.md new file mode 100644 index 00000000000000..6d02c23e20708a --- /dev/null +++ b/docs/guides/install/add-optional.md @@ -0,0 +1,25 @@ +--- +name: Add an optional dependency +--- + +To add an npm package as a peer dependency, use the `--optional` flag. + +```sh +$ bun add zod --optional +``` + +--- + +This will add the package to `optionalDependencies` in `package.json`. + +```json-diff +{ + "optionalDependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-peer.md b/docs/guides/install/add-peer.md new file mode 100644 index 00000000000000..78d5c86b358503 --- /dev/null +++ b/docs/guides/install/add-peer.md @@ -0,0 +1,17 @@ +--- +name: Add a peer dependency +--- + +To add an npm package as a peer dependency, directly modify the `peerDependencies` object in your package.json. Running `bun install` will not install peer dependencies. + +```json-diff +{ + "peerDependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add-tarball.md b/docs/guides/install/add-tarball.md new file mode 100644 index 00000000000000..f09dbbbfa50d72 --- /dev/null +++ b/docs/guides/install/add-tarball.md @@ -0,0 +1,33 @@ +--- +name: Add a tarball dependency +--- + +Bun's package manager can install any publicly available tarball URL as a dependency of your project. + +```sh +$ bun add zod@https://registry.npmjs.org/zod/-/zod-3.21.4.tgz +``` + +--- + +Running this command will download, extract, and install the tarball to your project's `node_modules` directory. It will also add the following line to your `package.json`: + +```json-diff#package.json +{ + "dependencies": { ++ "zod": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz" + } +} +``` + +--- + +The package `"zod"` can now be imported as usual. + +```ts +import { z } from "zod"; +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/add.md b/docs/guides/install/add.md new file mode 100644 index 00000000000000..dfb88e5e46b43a --- /dev/null +++ b/docs/guides/install/add.md @@ -0,0 +1,42 @@ +--- +name: Add a dependency +--- + +To add an npm package as a dependency, use `bun add`. + +```sh +$ bun add zod +``` + +--- + +This will add the package to `dependencies` in `package.json`. By default, the `^` range specifier will be used, to indicate that any future minor or patch versions are acceptable. + +```json-diff +{ + "dependencies": { ++ "zod": "^3.0.0" + } +} +``` + +--- + +To "pin" to the `latest` version of the package, use `--exact`. This will add the package to `dependencies` without the `^`, pinning your project to the exact version you installed. + +```sh +$ bun add zod --exact +``` + +--- + +To specify an exact version or a tag: + +```sh +$ bun add zod@3.0.0 +$ bun add zod@next +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/cicd.md b/docs/guides/install/cicd.md new file mode 100644 index 00000000000000..4be29925d41ecb --- /dev/null +++ b/docs/guides/install/cicd.md @@ -0,0 +1,41 @@ +--- +name: Install dependencies with Bun in GitHub Actions +--- + +Use the official [`setup-bun`](https://github.com/oven-sh/setup-bun) GitHub Action to install `bun` in your GitHub Actions runner. + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: actions/checkout@v3 ++ - uses: oven-sh/setup-bun@v1 + + # run any `bun` or `bunx` command ++ - run: bun install +``` + +--- + +To specify a version of Bun to install: + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: oven-sh/setup-bun@v1 ++ with: ++ version: 0.7.0 # or "canary" +``` + +--- + +Refer to the [README.md](https://github.com/oven-sh/setup-bun) for complete documentation of the `setup-bun` GitHub Action. diff --git a/docs/guides/install/custom-registry.md b/docs/guides/install/custom-registry.md new file mode 100644 index 00000000000000..64b3cf76b6c9a9 --- /dev/null +++ b/docs/guides/install/custom-registry.md @@ -0,0 +1,30 @@ +--- +name: Override the default npm registry for bun install +--- + +The default registry is `registry.npmjs.org`. This can be globally configured in `bunfig.toml`. + +```toml#bunfig.toml +[install] +# set default registry as a string +registry = "https://registry.npmjs.org" + +# if needed, set a token +registry = { url = "https://registry.npmjs.org", token = "123456" } + +# if needed, set a username/password +registry = "https://username:password@registry.npmjs.org" +``` + +--- + +Your `bunfig.toml` can reference environment variables. Bun automatically loads environment variables from `.env.local`, `.env.[NODE_ENV]`, and `.env`. See [Docs > Environment variables](/docs/cli/run#environment-variables) for more information. + +```toml#bunfig.toml +[install] +registry = { url = "https://registry.npmjs.org", token = "$npm_token" } +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/index.json b/docs/guides/install/index.json new file mode 100644 index 00000000000000..017ef2845d76bc --- /dev/null +++ b/docs/guides/install/index.json @@ -0,0 +1,4 @@ +{ + "name": "Package manager", + "description": "A collection of guides for managing dependencies with Bun's package manager" +} diff --git a/docs/guides/install/npm-alias.md b/docs/guides/install/npm-alias.md new file mode 100644 index 00000000000000..0b38d8c71605e7 --- /dev/null +++ b/docs/guides/install/npm-alias.md @@ -0,0 +1,23 @@ +--- +name: Install a package under a different name +--- + +To install an npm package under an alias: + +```sh +$ bun add my-custom-name@npm:zod +``` + +--- + +The `zod` package can now be imported as `my-custom-name`. + +```ts +import { z } from "my-custom-name"; + +z.string(); +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/registry-scope.md b/docs/guides/install/registry-scope.md new file mode 100644 index 00000000000000..48f7dee79a1695 --- /dev/null +++ b/docs/guides/install/registry-scope.md @@ -0,0 +1,32 @@ +--- +name: Configure a private registry for an organization scope with bun install +--- + +Bun does not read `.npmrc` files; instead private registries are configured via `bunfig.toml`. To configure a registry for a particular npm scope: + +```toml#bunfig.toml +[install.scopes] +# as a string +"@myorg1" = "https://username:password@registry.myorg.com/" + +# as an object with username/password +# you can reference environment variables +"@myorg2" = { username = "myusername", password = "$npm_pass", url = "https://registry.myorg.com/" } + +# as an object with token +"@myorg3" = { token = "$npm_token", url = "https://registry.myorg.com/" } + +``` + +--- + +Your `bunfig.toml` can reference environment variables. Bun automatically loads environment variables from `.env.local`, `.env.[NODE_ENV]`, and `.env`. See [Docs > Environment variables](/docs/cli/run#environment-variables) for more information. + +```toml#bunfig.toml +[install.scopes] +"@myorg3" = { token = "$npm_token", url = "https://registry.myorg.com/" } +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/workspaces.md b/docs/guides/install/workspaces.md new file mode 100644 index 00000000000000..7c359b28554470 --- /dev/null +++ b/docs/guides/install/workspaces.md @@ -0,0 +1,68 @@ +--- +name: Configuring a monorepo using workspaces +--- + +Bun's package manager supports npm `"workspaces"`. This allows you to split a codebase into multiple distinct "packages" that live in the same repository, can depend on each other, and (when possible) share a `node_modules` directory. + +--- + +The root `package.json` should not contain any `"dependencies"`, `"devDependencies"`, etc. Each individual package should be self-contained and declare its own dependencies. Similarly, it's conventional to declare `"private": true` to avoid accidentally publishing the root package to `npm`. + +```json#package.json +{ + "name": "my-monorepo", + "private": true, + "workspaces": [ + "packages/*" + ] +} +``` + +--- + +It's common to place all packages in a `packages` directory. The `"workspaces"` field in package.json supports glob patterns, so you can use `packages/*` to indicate that each subdirectory of `packages` should be considered separate _package_ (also known as a workspace). + +```txt +. +├── package.json +├── node_modules +└── packages + ├── stuff-a + │ └── package.json + └── stuff-b + └── package.json +``` + +--- + +To add one workspace as a dependency of another, modify its `package.json`. Here were adding `stuff-a` as a dependency of `stuff-b`. + +```json#packages/stuff-b/package.json +{ + "name": "stuff-b", + "dependencies": { ++ "stuff-a": "*" + } +} +``` + +--- + +Once added, run `bun install` from the project root to install dependencies for all workspaces. + +```sh +$ bun install +``` + +--- + +To add npm dependencies to a particular workspace, just `cd` to the appropriate directory and run `bun add` commands as you would normally. Bun will detect that you are in a workspace and hoist the dependency as needed. + +```sh +$ cd packages/stuff-a +$ bun add zod +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/install/yarnlock.md b/docs/guides/install/yarnlock.md new file mode 100644 index 00000000000000..898df634d87b5b --- /dev/null +++ b/docs/guides/install/yarnlock.md @@ -0,0 +1,42 @@ +--- +name: Generate a human-readable lockfile +--- + +By default Bun generates a binary `bun.lockb` file when you run `bun install`. In some cases, it's preferable to generate a human-readable lockfile instead. + +--- + +Use the `--yarn` flag to generate a Yarn-compatible `yarn.lock` file (in addition to `bun.lockb`). + +```sh +$ bun install --yarn +``` + +--- + +To set this as the default behavior, add the following to your `bunfig.toml` file. + +```toml#bunfig.toml +[install] +print = "yarn" +``` + +--- + +To print a Yarn lockfile to your console without writing it to disk, just "run" your `bun.lockb` with `bun`. + +```sh +$ bun bun.lockb +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 +# bun ./bun.lockb --hash: 9BFBF11D86084AAB-9418b03ff880c569-390CE6459EACEC9A... + +abab@^2.0.6: + version "2.0.6" + resolved "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz" + integrity sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvH... +``` + +--- + +See [Docs > Package manager](/docs/cli/install) for complete documentation of Bun's package manager. diff --git a/docs/guides/process/argv.md b/docs/guides/process/argv.md new file mode 100644 index 00000000000000..f9f3c77e4865a1 --- /dev/null +++ b/docs/guides/process/argv.md @@ -0,0 +1,22 @@ +--- +name: Parse command-line arguments +--- + +The _argument vector_ is the list of arguments passed to the program when it is run. It is available as `Bun.argv`. + +```ts#cli.ts +console.log(Bun.argv); +``` + +--- + +Running this file with arguments results in the following: + +```sh +$ bun run cli.tsx --flag1 --flag2 value +[ '/path/to/bun', '/path/to/cli.ts', '--flag1', '--flag2', 'value' ] +``` + +--- + +To parse `argv` into a more useful format, consider using [minimist](https://github.com/minimistjs/minimist) or [commander](https://github.com/tj/commander.js). diff --git a/docs/guides/process/ctrl-c.md b/docs/guides/process/ctrl-c.md new file mode 100644 index 00000000000000..b880cf62c03c04 --- /dev/null +++ b/docs/guides/process/ctrl-c.md @@ -0,0 +1,16 @@ +--- +name: Listen for CTRL+C +--- + +The `ctrl+c` shortcut sends an _interrupt signal_ to the running process. This signal can be intercepted by listening for the `SIGINT` event. If you want to close the process, you must explicitly call `process.exit()`. + +```ts +process.on("SIGINT", () => { + console.log("Ctrl-C was pressed"); + process.exit(); +}); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/process/index.json b/docs/guides/process/index.json new file mode 100644 index 00000000000000..df0384544b2864 --- /dev/null +++ b/docs/guides/process/index.json @@ -0,0 +1,4 @@ +{ + "name": "Processes", + "description": "A collection of guides for inspecting the current process and creating child processes with Bun" +} diff --git a/docs/guides/process/nanoseconds.md b/docs/guides/process/nanoseconds.md new file mode 100644 index 00000000000000..b8aee81235d6a2 --- /dev/null +++ b/docs/guides/process/nanoseconds.md @@ -0,0 +1,13 @@ +--- +name: Get the process uptime in nanoseconds +--- + +Use `Bun.nanoseconds()` to get the total number of nanoseconds the `bun` process has been alive. + +```ts +Bun.nanoseconds(); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/process/os-signals.md b/docs/guides/process/os-signals.md new file mode 100644 index 00000000000000..ae7b9896fc109a --- /dev/null +++ b/docs/guides/process/os-signals.md @@ -0,0 +1,39 @@ +--- +name: Listen to OS signals +--- + +Bun supports the Node.js `process` global, including the `process.on()` method for listening to OS signals. + +```ts +process.on("SIGINT", () => { + console.log("Received SIGINT"); +}); +``` + +--- + +If you don't know which signal to listen for, you listen to the umbrella `"exit"` event. + +```ts +process.on("exit", (code) => { + console.log(`Process exited with code ${code}`); +}); +``` + +--- + +If you don't know which signal to listen for, you listen to the [`"beforeExit"`](https://nodejs.org/api/process.html#event-beforeexit) and [`"exit"`](https://nodejs.org/api/process.html#event-exit) events. + +```ts +process.on("beforeExit", (code) => { + console.log(`Event loop is empty!`); +}); + +process.on("exit", (code) => { + console.log(`Process is exiting with code ${code}`); +}); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/process/spawn-stderr.md b/docs/guides/process/spawn-stderr.md new file mode 100644 index 00000000000000..9e9e8da99be30e --- /dev/null +++ b/docs/guides/process/spawn-stderr.md @@ -0,0 +1,31 @@ +--- +name: Read stderr from a child process +--- + +When using [`Bun.spawn()`](/docs/api/spawn), the child process inherits the `stderr` of the spawning process. If instead you'd prefer to read and handle `stderr`, set the `stderr` option to `"pipe"`. + +```ts +const proc = Bun.spawn(["echo", "hello"], { + stderr: "pipe", +}); +proc.stderr; // => ReadableStream +``` + +--- + +To read `stderr` until the child process exits, use the [`Bun.readableStreamToText()`](/docs/api/utils#bun-readablestreamto) convenience function. + +```ts +const proc = Bun.spawn(["echo", "hello"], { + stderr: "pipe", +}); + +const errors: string = await Bun.readableStreamToText(proc.stderr); +if (errors) { + // handle errors +} +``` + +--- + +See [Docs > API > Child processes](/docs/api/spawn) for complete documentation. diff --git a/docs/guides/process/spawn-stdout.md b/docs/guides/process/spawn-stdout.md new file mode 100644 index 00000000000000..e73fe59a0eb6ad --- /dev/null +++ b/docs/guides/process/spawn-stdout.md @@ -0,0 +1,26 @@ +--- +name: Read stdout from a child process +--- + +When using [`Bun.spawn()`](/docs/api/spawn), the `stdout` of the child process can be consumed as a `ReadableStream` via `proc.stdout`. + +```ts +const proc = Bun.spawn(["echo", "hello"]); + +const output = await new Response(proc.stdout).text(); +output; // => "hello" +``` + +--- + +To instead pipe the `stdout` of the child process to `stdout` of the parent process, set "inherit". + +```ts +const proc = Bun.spawn(["echo", "hello"], { + stdout: "inherit", +}); +``` + +--- + +See [Docs > API > Child processes](/docs/api/spawn) for complete documentation. diff --git a/docs/guides/process/spawn.md b/docs/guides/process/spawn.md new file mode 100644 index 00000000000000..f0fca8e8abe3e5 --- /dev/null +++ b/docs/guides/process/spawn.md @@ -0,0 +1,41 @@ +--- +name: Spawn a child process +--- + +Use [`Bun.spawn()`](/docs/api/spawn) to spawn a child process. + +```ts +const proc = Bun.spawn(["echo", "hello"]); + +// await completion +await proc.exited; +``` + +--- + +The second argument accepts a configuration object. + +```ts +const proc = Bun.spawn("echo", ["Hello, world!"], { + cwd: "/tmp", + env: { FOO: "bar" }, + onExit(proc, exitCode, signalCode, error) { + // exit handler + }, +}); +``` + +--- + +By default, the `stdout` of the child process can be consumed as a `ReadableStream` using `proc.stdout`. + +```ts +const proc = Bun.spawn(["echo", "hello"]); + +const output = await new Response(proc.stdout).text(); +output; // => "hello" +``` + +--- + +See [Docs > API > Child processes](/docs/api/spawn) for complete documentation. diff --git a/docs/guides/process/stdin.md b/docs/guides/process/stdin.md new file mode 100644 index 00000000000000..c19c9e1065390a --- /dev/null +++ b/docs/guides/process/stdin.md @@ -0,0 +1,54 @@ +--- +name: Read from stdin +--- + +For CLI tools, it's often useful to read from `stdin`. In Bun, the `console` object is an `AsyncIterable` that yields lines from `stdin`. + +```ts#index.ts +const prompt = "Type something: "; +process.stdout.write(prompt); +for await (const line of console) { + console.log(`You typed: ${line}`); + process.stdout.write(prompt); +} +``` + +--- + +Running this file results in a never-ending interactive prompt that echoes whatever the user types. + +```sh +$ bun run index.tsx +Type something: hello +You typed: hello +Type something: hello again +You typed: hello again +``` + +--- + +Bun also exposes stdin as a `BunFile` via `Bun.stdin`. This is useful for incrementally reading large inputs that are piped into the `bun` process. + +There is no guarantee that the chunks will be split line-by-line. + +```ts#stdin.ts +for await (const chunk of Bun.stdin.stream()) { + // chunk is Uint8Array + // this converts it to text (assumes ASCII encoding) + const chunkText = Buffer.from(chunk).toString(); + console.log(`Chunk: ${chunkText}`); +} +``` + +--- + +This will print the input that is piped into the `bun` process. + +```sh +$ echo "hello" | bun run stdin.ts +Chunk: hello +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/read-file/arraybuffer.md b/docs/guides/read-file/arraybuffer.md new file mode 100644 index 00000000000000..149b08d8eb0a30 --- /dev/null +++ b/docs/guides/read-file/arraybuffer.md @@ -0,0 +1,28 @@ +--- +name: Read a file to an ArrayBuffer +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob` and allows you to lazily read the file in a variety of formats. Use `.arrayBuffer()` to read the file as an `ArrayBuffer`. + +```ts +const path = "/path/to/package.json"; +const file = Bun.file(path); + +const buffer = await file.arrayBuffer(); +``` + +--- + +The binary content in the `ArrayBuffer` can then be read as a typed array, such as `Uint8Array`. + +```ts +const buffer = await file.arrayBuffer(); +const bytes = new Uint8Array(buffer); + +bytes[0]; +bytes.length; +``` + +--- + +Refer to the [Typed arrays](/docs/api/binary-data#typedarray) docs for more information on working with typed arrays in Bun. diff --git a/docs/guides/read-file/buffer.md b/docs/guides/read-file/buffer.md new file mode 100644 index 00000000000000..d27fa14894d7eb --- /dev/null +++ b/docs/guides/read-file/buffer.md @@ -0,0 +1,19 @@ +--- +name: Read a file to a Buffer +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob` and allows you to lazily read the file in a variety of formats. + +To read the file into a `Buffer` instance, first use `.arrayBuffer()` to consume the file as an `ArrayBuffer`, then use `Buffer.from()` to create a `Buffer` from the `ArrayBuffer`. + +```ts +const path = "/path/to/package.json"; +const file = Bun.file(path); + +const arrbuf = await file.arrayBuffer(); +const buffer = Buffer.from(arrbuf); +``` + +--- + +Refer to [Binary data > Buffer](/docs/api/binary-data#buffer) for more information on working with `Buffer` and other binary data formats in Bun. diff --git a/docs/guides/read-file/exists.md b/docs/guides/read-file/exists.md new file mode 100644 index 00000000000000..fd6cbbf9a418d8 --- /dev/null +++ b/docs/guides/read-file/exists.md @@ -0,0 +1,16 @@ +--- +name: Check if a file exists +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. Use the `.exists()` method to check if a file exists at the given path. + +```ts +const path = "/path/to/package.json"; +const file = Bun.file(path); + +file.exists(); // boolean; +``` + +--- + +Refer to [API > File I/O](/docs/api/file-io) for more information on working with `BunFile`. diff --git a/docs/guides/read-file/index.json b/docs/guides/read-file/index.json new file mode 100644 index 00000000000000..321fd96e29c024 --- /dev/null +++ b/docs/guides/read-file/index.json @@ -0,0 +1,4 @@ +{ + "name": "Reading files", + "description": "A collection of guides for reading files with Bun" +} diff --git a/docs/guides/read-file/json.md b/docs/guides/read-file/json.md new file mode 100644 index 00000000000000..e14fd560af3d0e --- /dev/null +++ b/docs/guides/read-file/json.md @@ -0,0 +1,17 @@ +--- +name: Read a JSON file +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob` and allows you to lazily read the file in a variety of formats. Use `.json()` to read and parse the contents of a `.json` file as a plain object. + +The MIME type of the `BunFile` will be set accordingly. + +```ts +const path = "/path/to/package.json"; +const file = Bun.file(path); + +const contents = await file.json(); +// { name: "my-package" } + +file.type; // => "application/json;charset=utf-8"; +``` diff --git a/docs/guides/read-file/mime.md b/docs/guides/read-file/mime.md new file mode 100644 index 00000000000000..44a8e686072bb2 --- /dev/null +++ b/docs/guides/read-file/mime.md @@ -0,0 +1,20 @@ +--- +name: Get the MIME type of a file +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob`, so use the `.type` property to read the MIME type. + +```ts +const file = Bun.file("./package.json"); +file.type; // application/json + +const file = Bun.file("./index.html"); +file.type; // text/html + +const file = Bun.file("./image.png"); +file.type; // image/png +``` + +--- + +Refer to [API > File I/O](/docs/api/file-io) for more information on working with `BunFile`. diff --git a/docs/guides/read-file/stream.md b/docs/guides/read-file/stream.md new file mode 100644 index 00000000000000..ac4bd9e2f12c0e --- /dev/null +++ b/docs/guides/read-file/stream.md @@ -0,0 +1,26 @@ +--- +name: Read a file as a ReadableStream +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob` and allows you to lazily read the file in a variety of formats. Use `.stream()` to consume the file incrementally as a `ReadableStream`. + +```ts +const path = "/path/to/package.json"; +const file = Bun.file(path); + +const stream = await file.stream(); +``` + +--- + +The chunks of the stream can be consumed as an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) using `for await`. + +```ts +for await (const chunk of stream) { + chunk; // => Uint8Array +} +``` + +--- + +Refer to the [Streams](/docs/api/streams) documentation for more information on working with streams in Bun. diff --git a/docs/guides/read-file/string.md b/docs/guides/read-file/string.md new file mode 100644 index 00000000000000..08cdfd95228ee0 --- /dev/null +++ b/docs/guides/read-file/string.md @@ -0,0 +1,22 @@ +--- +name: Read a file as a string +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob` and allows you to lazily read the file in a variety of formats. Use `.text()` to read the contents as a string. + +```ts +const path = "/path/to/file.txt"; +const file = Bun.file(path); + +const text = await file.text(); +// string +``` + +--- + +Any relative paths will be resolved relative to the project root (the nearest directory containing a `package.json` file). + +```ts +const path = "./file.txt"; +const file = Bun.file(path); +``` diff --git a/docs/guides/read-file/uint8array.md b/docs/guides/read-file/uint8array.md new file mode 100644 index 00000000000000..1afcaa79711f98 --- /dev/null +++ b/docs/guides/read-file/uint8array.md @@ -0,0 +1,22 @@ +--- +name: Read a file to a Uint8Array +--- + +The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `BunFile` class extends `Blob` and allows you to lazily read the file in a variety of formats. + +To read the file into a `Uint8Array` instance, retrieve the contents of the `BunFile` as an `ArrayBuffer` with `.arrayBuffer()`, then pass it into the `Uint8Array` constructor. + +```ts +const path = "/path/to/package.json"; +const file = Bun.file(path); + +const arrBuffer = await file.arrayBuffer(); +const byteArray = new Uint8Array(arrBuffer); + +byteArray[0]; // first byteArray +byteArray.length; // length of byteArray +``` + +--- + +Refer to [API > Binary data > Typed arrays](/docs/api/binary-data#typedarray) for more information on working with `Uint8Array` and other binary data formats in Bun. diff --git a/docs/guides/read-file/watch.md b/docs/guides/read-file/watch.md new file mode 100644 index 00000000000000..0c38a0ecef09db --- /dev/null +++ b/docs/guides/read-file/watch.md @@ -0,0 +1,68 @@ +--- +name: Watch a directory for changes +--- + +Bun implements the `node:fs` module, including the `fs.watch` function for listening for file system changes. + +This code block listens for changes to files in the current directory. By default this operation is _shallow_, meaning that changes to files in subdirectories will not be detected. + +```ts +import { watch } from "fs"; + +const watcher = watch(import.meta.dir, (event, filename) => { + console.log(`Detected ${event} in ${filename}`); +}); +``` + +--- + +To listen to changes in subdirectories, pass the `recursive: true` option to `fs.watch`. + +```ts +import { watch } from "fs"; + +const watcher = watch( + import.meta.dir, + { recursive: true }, + (event, filename) => { + console.log(`Detected ${event} in ${filename}`); + }, +); +``` + +--- + +Using the `node:fs/promises` module, you can listen for changes using `for await...of` instead of a callback. + +```ts +import { watch } from "fs/promises"; + +const watcher = watch(import.meta.dir); +for await (const event of watcher) { + console.log(`Detected ${event.eventType} in ${event.filename}`); +} +``` + +--- + +To stop listening for changes, call `watcher.close()`. It's common to do this when the process receives a `SIGINT` signal, such as when the user presses Ctrl-C. + +```ts +import { watch } from "fs"; + +const watcher = watch(import.meta.dir, (event, filename) => { + console.log(`Detected ${event} in ${filename}`); +}); + +process.on("SIGINT", () => { + // close watcher when Ctrl-C is pressed + console.log("Closing watcher..."); + watcher.close(); + + process.exit(0); +}); +``` + +--- + +Refer to [API > Binary data > Typed arrays](/docs/api/binary-data#typedarray) for more information on working with `Uint8Array` and other binary data formats in Bun. diff --git a/docs/guides/runtime/cicd.md b/docs/guides/runtime/cicd.md new file mode 100644 index 00000000000000..6dfef2ddd8ef99 --- /dev/null +++ b/docs/guides/runtime/cicd.md @@ -0,0 +1,43 @@ +--- +name: Install and run Bun in GitHub Actions +--- + +Use the official [`setup-bun`](https://github.com/oven-sh/setup-bun) GitHub Action to install `bun` in your GitHub Actions runner. + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: actions/checkout@v3 ++ - uses: oven-sh/setup-bun@v1 + + # run any `bun` or `bunx` command ++ - run: bun install ++ - run: bun index.ts ++ - run: bun run build +``` + +--- + +To specify a version of Bun to install: + +```yaml-diff#workflow.yml +name: my-workflow +jobs: + my-job: + name: my-job + runs-on: ubuntu-latest + steps: + # ... + - uses: oven-sh/setup-bun@v1 ++ with: ++ version: 0.7.0 # or "canary" +``` + +--- + +Refer to the [README.md](https://github.com/oven-sh/setup-bun) for complete documentation of the `setup-bun` GitHub Action. diff --git a/docs/guides/runtime/import-json.md b/docs/guides/runtime/import-json.md new file mode 100644 index 00000000000000..3db2daaea1c331 --- /dev/null +++ b/docs/guides/runtime/import-json.md @@ -0,0 +1,32 @@ +--- +name: Import a JSON file +--- + +Bun natively supports `.json` imports. + +```json#package.json +{ + "name": "bun", + "version": "1.0.0", + "author": { + "name": "John Dough", + "email": "john@dough.com" + } +} +``` + +--- + +Import the file like any other source file. + +```ts +import data from "./package.json"; + +data.name; // => "bun" +data.version; // => "1.0.0" +data.author.name; // => "John Dough" +``` + +--- + +See [Docs > Runtime > TypeScript](/docs/runtime/typescript) for more information on using TypeScript with Bun. diff --git a/docs/guides/runtime/import-toml.md b/docs/guides/runtime/import-toml.md new file mode 100644 index 00000000000000..2a2e47aa49cc3c --- /dev/null +++ b/docs/guides/runtime/import-toml.md @@ -0,0 +1,30 @@ +--- +name: Import a TOML file +--- + +Bun natively supports importing `.toml` files. + +```toml#data.toml +name = "bun" +version = "1.0.0" + +[author] +name = "John Dough" +email = "john@dough.com" +``` + +--- + +Import the file like any other source file. + +```ts +import data from "./data.toml"; + +data.name; // => "bun" +data.version; // => "1.0.0" +data.author.name; // => "John Dough" +``` + +--- + +See [Docs > Runtime > TypeScript](/docs/runtime/typescript) for more information on using TypeScript with Bun. diff --git a/docs/guides/runtime/index.json b/docs/guides/runtime/index.json new file mode 100644 index 00000000000000..fad27c69def455 --- /dev/null +++ b/docs/guides/runtime/index.json @@ -0,0 +1,4 @@ +{ + "name": "Runtime", + "description": "A collection of guides for executing code with the Bun runtime" +} diff --git a/docs/guides/runtime/read-env.md b/docs/guides/runtime/read-env.md new file mode 100644 index 00000000000000..512f731dda5415 --- /dev/null +++ b/docs/guides/runtime/read-env.md @@ -0,0 +1,32 @@ +--- +name: Read environment variables +--- + +The current environment variables can be accessed via `process.env`. + +```ts +process.env.API_TOKEN; // => "secret" +``` + +--- + +Bun also exposes these variables via `Bun.env`, which is a simple alias of `process.env`. + +```ts +Bun.env.API_TOKEN; // => "secret" +``` + +--- + +To print all currently-set environment variables to the command line, run `bun run env`. This is useful for debugging. + +```sh +$ bun run env +BAZ=stuff +FOOBAR=aaaaaa + +``` + +--- + +See [Docs > Runtime > Environment variables](/docs/cli/run#environment-variables) for more information on using environment variables with Bun. diff --git a/docs/guides/runtime/set-env.md b/docs/guides/runtime/set-env.md new file mode 100644 index 00000000000000..97cac348848143 --- /dev/null +++ b/docs/guides/runtime/set-env.md @@ -0,0 +1,37 @@ +--- +name: Set environment variables +--- + +The current environment variables can be accessed via `process.env` or `Bun.env`. + +```ts +Bun.env.API_TOKEN; // => "secret" +process.env.API_TOKEN; // => "secret" +``` + +--- + +Set these variables in a `.env` file. + +Bun reads the following files automatically (listed in order of increasing precedence). + +- `.env` +- `.env.production` or `.env.development` (depending on value of `NODE_ENV`) +- `.env.local` + +```txt#.env +FOO=hello +BAR=world +``` + +--- + +Variables can also be set via the command line. + +```sh +$ FOO=helloworld bun run dev +``` + +--- + +See [Docs > Runtime > Environment variables](/docs/cli/run#environment-variables) for more information on using environment variables with Bun. diff --git a/docs/guides/runtime/tsconfig-paths.md b/docs/guides/runtime/tsconfig-paths.md new file mode 100644 index 00000000000000..5c3f591f594a84 --- /dev/null +++ b/docs/guides/runtime/tsconfig-paths.md @@ -0,0 +1,29 @@ +--- +name: Re-map import paths +--- + +Bun reads the `paths` field in your `tsconfig.json` to re-write import paths. This is useful for aliasing package names or avoiding long relative paths. + +```json +{ + "compilerOptions": { + "paths": { + "my-custom-name": "zod", + "@components/*": "./src/components/*" + } + } +} +``` + +--- + +With the above `tsconfig.json`, the following imports will be re-written: + +```ts +import { z } from "my-custom-name"; // imports from "zod" +import { Button } from "@components/Button"; // imports from "./src/components/Button" +``` + +--- + +See [Docs > Runtime > TypeScript](/docs/runtime/typescript) for more information on using TypeScript with Bun. diff --git a/docs/guides/streams/index.json b/docs/guides/streams/index.json new file mode 100644 index 00000000000000..da6ff26297814f --- /dev/null +++ b/docs/guides/streams/index.json @@ -0,0 +1,4 @@ +{ + "name": "Streams", + "description": "A collection of guides for manipulating streams with Bun" +} diff --git a/docs/guides/streams/to-array.md b/docs/guides/streams/to-array.md new file mode 100644 index 00000000000000..bca40cf12ad427 --- /dev/null +++ b/docs/guides/streams/to-array.md @@ -0,0 +1,14 @@ +--- +name: Convert a ReadableStream to an array of chunks +--- + +Bun provides a number of convenience functions for reading the contents of a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) into different formats. The `Bun.readableStreamToArray` function reads the contents of a `ReadableStream` to an array of chunks. + +```ts +const stream = new ReadableStream(); +const str = await Bun.readableStreamToArray(stream); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils#bun-readablestreamto) for documentation on Bun's other `ReadableStream` conversion functions. diff --git a/docs/guides/streams/to-arraybuffer.md b/docs/guides/streams/to-arraybuffer.md new file mode 100644 index 00000000000000..b20d96a04c4efc --- /dev/null +++ b/docs/guides/streams/to-arraybuffer.md @@ -0,0 +1,14 @@ +--- +name: Convert a ReadableStream to an ArrayBuffer +--- + +Bun provides a number of convenience functions for reading the contents of a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) into different formats. + +```ts +const stream = new ReadableStream(); +const buf = await Bun.readableStreamToArrayBuffer(stream); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils#bun-readablestreamto) for documentation on Bun's other `ReadableStream` conversion functions. diff --git a/docs/guides/streams/to-blob.md b/docs/guides/streams/to-blob.md new file mode 100644 index 00000000000000..3380dca3842e78 --- /dev/null +++ b/docs/guides/streams/to-blob.md @@ -0,0 +1,14 @@ +--- +name: Convert a ReadableStream to a Blob +--- + +Bun provides a number of convenience functions for reading the contents of a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) into different formats. + +```ts +const stream = new ReadableStream(); +const blob = await Bun.readableStreamToBlob(stream); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils#bun-readablestreamto) for documentation on Bun's other `ReadableStream` conversion functions. diff --git a/docs/guides/streams/to-buffer.md b/docs/guides/streams/to-buffer.md new file mode 100644 index 00000000000000..d6450d644e49b7 --- /dev/null +++ b/docs/guides/streams/to-buffer.md @@ -0,0 +1,15 @@ +--- +name: Convert a ReadableStream to a Buffer +--- + +Bun provides a number of convenience functions for reading the contents of a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) into different formats. This snippet reads the contents of a `ReadableStream` to an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), then creates a [`Buffer`](https://nodejs.org/api/buffer.html) that points to it. + +```ts +const stream = new ReadableStream(); +const arrBuf = await Bun.readableStreamToArrayBuffer(stream); +const nodeBuf = Buffer.from(arrBuf); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils#bun-readablestreamto) for documentation on Bun's other `ReadableStream` conversion functions. diff --git a/docs/guides/streams/to-json.md b/docs/guides/streams/to-json.md new file mode 100644 index 00000000000000..cf9e7c71ee76b9 --- /dev/null +++ b/docs/guides/streams/to-json.md @@ -0,0 +1,14 @@ +--- +name: Convert a ReadableStream to a JSON +--- + +Bun provides a number of convenience functions for reading the contents of a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) into different formats. + +```ts +const stream = new ReadableStream(); +const json = await Bun.readableStreamToJSON(stream); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils#bun-readablestreamto) for documentation on Bun's other `ReadableStream` conversion functions. diff --git a/docs/guides/streams/to-string.md b/docs/guides/streams/to-string.md new file mode 100644 index 00000000000000..309f45c52d7a0c --- /dev/null +++ b/docs/guides/streams/to-string.md @@ -0,0 +1,14 @@ +--- +name: Convert a ReadableStream to a string +--- + +Bun provides a number of convenience functions for reading the contents of a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) into different formats. + +```ts +const stream = new ReadableStream(); +const str = await Bun.readableStreamToText(stream); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils#bun-readablestreamto) for documentation on Bun's other `ReadableStream` conversion functions. diff --git a/docs/guides/streams/to-typedarray.md b/docs/guides/streams/to-typedarray.md new file mode 100644 index 00000000000000..faa18e4ad2ddc8 --- /dev/null +++ b/docs/guides/streams/to-typedarray.md @@ -0,0 +1,15 @@ +--- +name: Convert a ReadableStream to a Uint8Array +--- + +Bun provides a number of convenience functions for reading the contents of a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) into different formats. This snippet reads the contents of a `ReadableStream` to an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), then creates a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) that points to the buffer. + +```ts +const stream = new ReadableStream(); +const buf = await Bun.readableStreamToArrayBuffer(stream); +const uint8 = new Uint8Array(buf); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils#bun-readablestreamto) for documentation on Bun's other `ReadableStream` conversion functions. diff --git a/docs/guides/util/base64.md b/docs/guides/util/base64.md new file mode 100644 index 00000000000000..bbc8f090639646 --- /dev/null +++ b/docs/guides/util/base64.md @@ -0,0 +1,15 @@ +--- +name: Encode and decode base64 strings +--- + +Bun implements the Web-standard [`atob`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob) and [`btoa`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa) functions for encoding and decoding base64 strings. + +```ts +const data = "hello world"; +const encoded = btoa(data); // => "aGVsbG8gd29ybGQ=" +const decoded = atob(encoded); // => "hello world" +``` + +--- + +See [Docs > Web APIs](/docs/runtime/web-apis) for a complete breakdown of the Web APIs implemented in Bun. diff --git a/docs/guides/util/deep-equals.md b/docs/guides/util/deep-equals.md new file mode 100644 index 00000000000000..9d8dc74d4ef362 --- /dev/null +++ b/docs/guides/util/deep-equals.md @@ -0,0 +1,39 @@ +--- +name: Check if two objects are deeply equal +--- + +Check if two objects are deeply equal. This is used internally by `expect().toEqual()` in Bun's [test runner](/docs/test/writing). + +```ts#index.ts +const a = { a: 1, b: 2, c: { d: 3 } }; +const b = { a: 1, b: 2, c: { d: 3 } }; + +Bun.deepEquals(a, b); // true +``` + +--- + +Pass `true` as a third argument to enable strict mode. This is used internally by `expect().toStrictEqual()` in Bun's [test runner](/docs/test/writing). + +The following examples would return `true` in non-strict mode but `false` in strict mode. + +```ts +// undefined values +Bun.deepEquals({}, { a: undefined }, true); // false + +// undefined in arrays +Bun.deepEquals(["asdf"], ["asdf", undefined], true); // false + +// sparse arrays +Bun.deepEquals([, 1], [undefined, 1], true); // false + +// object literals vs instances w/ same properties +class Foo { + a = 1; +} +Bun.deepEquals(new Foo(), { a: 1 }, true); // false +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/deflate.md b/docs/guides/util/deflate.md new file mode 100644 index 00000000000000..91dd8925ab8612 --- /dev/null +++ b/docs/guides/util/deflate.md @@ -0,0 +1,18 @@ +--- +name: Compress and decompress data with DEFLATE +--- + +Use `Bun.deflateSync()` to compress a `Uint8Array` with DEFLATE. + +```ts +const data = Buffer.from("Hello, world!"); +const compressed = Bun.deflateSync("Hello, world!"); +// => Uint8Array + +const decompressed = Bun.inflateSync(compressed); +// => Uint8Array +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/entrypoint.md b/docs/guides/util/entrypoint.md new file mode 100644 index 00000000000000..e53d4c9a13572d --- /dev/null +++ b/docs/guides/util/entrypoint.md @@ -0,0 +1,17 @@ +--- +name: Check if the current file is the entrypoint +--- + +Bun provides a handful of module-specific utilities on the [`import.meta`](/docs/api/import-meta) object. Use `import.meta.main` to check if the current file is the entrypoint of the current process. + +```ts#index.ts +if(import.meta.main){ + // this file is directly executed with `bun run` +}else{ + // this file is being imported by another file +} +``` + +--- + +See [Docs > API > import.meta](/docs/api/import-meta) for complete documentation. diff --git a/docs/guides/util/escape-html.md b/docs/guides/util/escape-html.md new file mode 100644 index 00000000000000..4d88fb85766f2c --- /dev/null +++ b/docs/guides/util/escape-html.md @@ -0,0 +1,22 @@ +--- +name: Escape an HTML string +--- + +The `Bun.escapeHTML()` utility can be used to escape HTML characters in a string. The following replacements are made. + +- `"` becomes `"""` +- `&` becomes `"&"` +- `'` becomes `"'"` +- `<` becomes `"<"` +- `>` becomes `">"` + +This function is optimized for large input. Non-string types will be converted to a string before escaping. + +```ts +Bun.escapeHTML(""); +// <script>alert('Hello World!')</script> +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/file-url-to-path.md b/docs/guides/util/file-url-to-path.md new file mode 100644 index 00000000000000..0464504a69e3bd --- /dev/null +++ b/docs/guides/util/file-url-to-path.md @@ -0,0 +1,14 @@ +--- +name: Convert a file URL to an absolute path +--- + +Use `Bun.fileURLToPath()` to convert a `file://` URL to an absolute path. + +```ts +Bun.fileURLToPath("file:///path/to/file.txt"); +// => "/path/to/file.txt" +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/gzip.md b/docs/guides/util/gzip.md new file mode 100644 index 00000000000000..c755b7c8bd43fb --- /dev/null +++ b/docs/guides/util/gzip.md @@ -0,0 +1,18 @@ +--- +name: Compress and decompress data with gzip +--- + +Use `Bun.gzipSync()` to compress a `Uint8Array` with gzip. + +```ts +const data = Buffer.from("Hello, world!"); +const compressed = Bun.gzipSync("Hello, world!"); +// => Uint8Array + +const decompressed = Bun.gunzipSync(compressed); +// => Uint8Array +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/hash-a-password.md b/docs/guides/util/hash-a-password.md new file mode 100644 index 00000000000000..6941bfcfee0092 --- /dev/null +++ b/docs/guides/util/hash-a-password.md @@ -0,0 +1,54 @@ +--- +name: Hash a password +--- + +The `Bun.password.hash()` function provides a fast, built-in mechanism for securely hashing passwords in Bun. No third-party dependencies are required. + +```ts +const password = "super-secure-pa$$word"; + +const hash = await Bun.password.hash(password); +// => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh6E8DQRhEXg/M/SqYCNu6gVdRRNs$GzJ8PuBi+K+BVojzPfS5mjnC8OpLGtv8KJqF99eP6a4 +``` + +--- + +By default this uses the [Argon2id](https://en.wikipedia.org/wiki/Argon2) algorithm. Pass a second argument to `Bun.hash.password()` to use a different algorithm or configure the hashing parameters. + +```ts +const password = "super-secure-pa$$word"; + +// use argon2 (default) +const argonHash = await Bun.password.hash(password, { + memoryCost: 4, // memory usage in kibibytes + timeCost: 3, // the number of iterations +}); +``` + +--- + +Bun also implements the [bcrypt](https://en.wikipedia.org/wiki/Bcrypt) algorithm. Specify `algorithm: "bcrypt"` to use it. + +```ts +// use bcrypt +const bcryptHash = await Bun.password.hash(password, { + algorithm: "bcrypt", + cost: 4, // number between 4-31 +}); +``` + +--- + +To verify a password, use `Bun.password.verify()`. The algorithm and its parameters are stored in the hash itself, so there's no need to re-specify any configuration. + +```ts +const password = "super-secure-pa$$word"; +const hash = await Bun.password.hash(password); + +const isMatch = await Bun.password.verify(password, hash); +// => true +``` + +--- + +See [Docs > API > Hashing](/docs/api/hashing#bun-password) for complete documentation. diff --git a/docs/guides/util/import-meta-dir.md b/docs/guides/util/import-meta-dir.md new file mode 100644 index 00000000000000..edfa023724f1e1 --- /dev/null +++ b/docs/guides/util/import-meta-dir.md @@ -0,0 +1,13 @@ +--- +name: Get the directory of the current file +--- + +Bun provides a handful of module-specific utilities on the [`import.meta`](/docs/api/import-meta) object. + +```ts#/a/b/c.ts +import.meta.dir; // => "/a/b" +``` + +--- + +See [Docs > API > import.meta](/docs/api/import-meta) for complete documentation. diff --git a/docs/guides/util/import-meta-file.md b/docs/guides/util/import-meta-file.md new file mode 100644 index 00000000000000..8edf262b25c2e9 --- /dev/null +++ b/docs/guides/util/import-meta-file.md @@ -0,0 +1,13 @@ +--- +name: Get the file name of the current file +--- + +Bun provides a handful of module-specific utilities on the [`import.meta`](/docs/api/import-meta) object. Use `import.meta.file` to retreive the name of the current file. + +```ts#/a/b/c.ts +import.meta.file; // => "c.ts" +``` + +--- + +See [Docs > API > import.meta](/docs/api/import-meta) for complete documentation. diff --git a/docs/guides/util/import-meta-path.md b/docs/guides/util/import-meta-path.md new file mode 100644 index 00000000000000..b93670a387054b --- /dev/null +++ b/docs/guides/util/import-meta-path.md @@ -0,0 +1,13 @@ +--- +name: Get the absolute path of the current file +--- + +Bun provides a handful of module-specific utilities on the [`import.meta`](/docs/api/import-meta) object. Use `import.meta.path` to retreive the absolute path of the current file. + +```ts#/a/b/c.ts +import.meta.path; // => "/a/b/c.ts" +``` + +--- + +See [Docs > API > import.meta](/docs/api/import-meta) for complete documentation. diff --git a/docs/guides/util/index.json b/docs/guides/util/index.json new file mode 100644 index 00000000000000..7e988ae252d368 --- /dev/null +++ b/docs/guides/util/index.json @@ -0,0 +1,4 @@ +{ + "name": "Utilities", + "description": "A collection of guides relating to Bun's array of built-in utility functions" +} diff --git a/docs/guides/util/main.md b/docs/guides/util/main.md new file mode 100644 index 00000000000000..e34fcd8f7b0e30 --- /dev/null +++ b/docs/guides/util/main.md @@ -0,0 +1,32 @@ +--- +name: Get the absolute path to the current entrypoint +--- + +The `Bun.main` property contains the absolute path to the current entrypoint. + +{% codetabs %} + +```ts#foo.ts +console.log(Bun.main); +``` + +```ts#index.ts +import "./foo.ts"; +``` + +{% /codetabs %} + +--- + +The printed path corresponds to the file that is executed with `bun run`. + +```sh +$ bun run index.ts +/path/to/index.ts +$ bun run foo.ts +/path/to/foo.ts +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/path-to-file-url.md b/docs/guides/util/path-to-file-url.md new file mode 100644 index 00000000000000..202be61eb032bd --- /dev/null +++ b/docs/guides/util/path-to-file-url.md @@ -0,0 +1,14 @@ +--- +name: Convert an absolute path to a file URL +--- + +Use `Bun.pathToFileURL()` to convert an absolute path to a `file://` URL. + +```ts +Bun.pathToFileURL("/path/to/file.txt"); +// => "file:///path/to/file.txt" +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/sleep.md b/docs/guides/util/sleep.md new file mode 100644 index 00000000000000..dbc39c05715b04 --- /dev/null +++ b/docs/guides/util/sleep.md @@ -0,0 +1,22 @@ +--- +name: Sleep for a fixed number of milliseconds +--- + +The `Bun.sleep` method provides a convenient way to create a void `Promise` that resolves in a fixed number of milliseconds. + +```ts +// sleep for 1 second +await Bun.sleep(1000); +``` + +--- + +Internally, this is equivalent to the following snippet that uses [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout). + +```ts +await new Promise((resolve) => setTimeout(resolve, ms)); +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/util/version.md b/docs/guides/util/version.md new file mode 100644 index 00000000000000..c1f5b8bfaafdeb --- /dev/null +++ b/docs/guides/util/version.md @@ -0,0 +1,21 @@ +--- +name: Get the current Bun version +--- + +Get the current version of Bun in a semver format. + +```ts#index.ts +Bun.version; // => "0.6.15" +``` + +--- + +Get the exact `git` commit of [`oven-sh/bun`](https://github.com/oven-sh/bun) that was compiled to produce this Bun binary. + +```ts#index.ts +Bun.revision; // => "49231b2cb9aa48497ab966fc0bb6b742dacc4994" +``` + +--- + +See [Docs > API > Utils](/docs/api/utils) for more useful utilities. diff --git a/docs/guides/websocket/compression.md b/docs/guides/websocket/compression.md new file mode 100644 index 00000000000000..e98d8f0c983f88 --- /dev/null +++ b/docs/guides/websocket/compression.md @@ -0,0 +1,31 @@ +--- +name: Enable compression for WebSocket messages +--- + +Per-message compression can be enabled with the `perMessageDeflate` parameter. When set, all messages will be compressed using the [permessage-deflate](https://tools.ietf.org/html/rfc7692) WebSocket extension. + +```ts +Bun.serve({ + // ... + websocket: { + // enable compression + perMessageDeflate: true, + }, +}); +``` + +--- + +To enable compression for individual messages, pass `true` as the second parameter to `ws.send()`. + +```ts +Bun.serve({ + // ... + websocket: { + async message(ws, message) { + // send a compressed message + ws.send("Hello world!", true); + }, + }, +}); +``` diff --git a/docs/guides/websocket/context.md b/docs/guides/websocket/context.md new file mode 100644 index 00000000000000..9e387d685b8c3a --- /dev/null +++ b/docs/guides/websocket/context.md @@ -0,0 +1,72 @@ +--- +name: Set per-socket contextual data on a WebSocket +--- + +When building a WebSocket server, it's typically necessary to store some identifying information or context associated with each connected client. + +With [Bun.serve()](/docs/api/websockets#contextual-data), this "contextual data" is set when the connection is initially upgraded by passing a `data` parameter in the `server.upgrade()` call. + +```ts +Bun.serve<{ socketId: number }>({ + fetch(req, server) { + const success = server.upgrade(req, { + data: { + socketId: Math.random(), + }, + }); + if (success) return undefined; + + // handle HTTP request normally + // ... + }, + websocket: { + // define websocket handlers + async message(ws, message) { + // the contextual dta is available as the `data` property + // on the WebSocket instance + console.log(`Received ${message} from ${ws.data.socketId}}`); + }, + }, +}); +``` + +--- + +It's common to read cookies/headers from the incoming request to identify the connecting client. + +```ts +type WebSocketData = { + createdAt: number; + token: string; + userId: string; +}; + +// TypeScript: specify the type of `data` +Bun.serve({ + async fetch(req, server) { + // use a library to parse cookies + const cookies = parseCookies(req.headers.get("Cookie")); + const token = cookies["X-Token"]; + const user = await getUserFromToken(ws.data.authToken); + + const upgraded = server.upgrade(req, { + data: { + createdAt: Date.now(), + token: cookies["X-Token"], + userId: user.id, + }, + }); + + if (upgraded) return undefined; + }, + websocket: { + async message(ws, message) { + // save the message to a database + await saveMessageToDatabase({ + message: String(message), + userId: ws.data.userId, + }); + }, + }, +}); +``` diff --git a/docs/guides/websocket/index.json b/docs/guides/websocket/index.json new file mode 100644 index 00000000000000..cb4d71b1ad1e8c --- /dev/null +++ b/docs/guides/websocket/index.json @@ -0,0 +1,4 @@ +{ + "name": "WebSocket", + "description": "A collection of guides relating to building WebSocket servers with Bun" +} diff --git a/docs/guides/websocket/pubsub.md b/docs/guides/websocket/pubsub.md new file mode 100644 index 00000000000000..7403d4d2f5e7cb --- /dev/null +++ b/docs/guides/websocket/pubsub.md @@ -0,0 +1,38 @@ +--- +name: Build a publish-subscribe WebSocket server +--- + +Bun's server-side `WebSocket` API provides a native pub-sub API. Sockets can be subscribed to a set of named channels using `socket.subscribe()`; messages can be published to a channel using `socket.publish(, )`. + +This code snippet implements a simple single-channel chat server. + +```ts +const server = Bun.serve<{ username: string }>({ + fetch(req, server) { + const cookies = req.headers.get("cookie"); + const username = getUsernameFromCookies(cookies); + const success = server.upgrade(req, { data: { username } }); + if (success) return undefined; + + return new Response("Hello world"); + }, + websocket: { + open(ws) { + const msg = `${ws.data.username} has entered the chat`; + ws.subscribe("the-group-chat"); + ws.publish("the-group-chat", msg); + }, + message(ws, message) { + // the server re-broadcasts incoming messages to everyone + ws.publish("the-group-chat", `${ws.data.username}: ${message}`); + }, + close(ws) { + const msg = `${ws.data.username} has left the chat`; + ws.publish("the-group-chat", msg); + ws.unsubscribe("the-group-chat"); + }, + }, +}); + +console.log(`Listening on ${server.hostname}:${server.port}`); +``` diff --git a/docs/guides/websocket/simple.md b/docs/guides/websocket/simple.md new file mode 100644 index 00000000000000..5aabf2fdf40db9 --- /dev/null +++ b/docs/guides/websocket/simple.md @@ -0,0 +1,33 @@ +--- +name: Build a simple WebSocket server +--- + +Start a simple WebSocket server using [`Bun.serve`](/docs/api/http). + +Inside `fetch`, we attempt to upgrade incoming `ws:` or `wss:` requests to WebSocket connections. + +```ts +const server = Bun.serve<{ authToken: string }>({ + fetch(req, server) { + const success = server.upgrade(req); + if (success) { + // Bun automatically returns a 101 Switching Protocols + // if the upgrade succeeds + return undefined; + } + + // handle HTTP request normally + return new Response("Hello world!"); + }, + websocket: { + // this is called when a message is received + async message(ws, message) { + console.log(`Received ${message}`); + // send back a message + ws.send(`You said: ${message}`); + }, + }, +}); + +console.log(`Listening on localhost:\${server.port}`); +``` diff --git a/docs/guides/websocket/upgrade.md b/docs/guides/websocket/upgrade.md new file mode 100644 index 00000000000000..cec8c38025eb2a --- /dev/null +++ b/docs/guides/websocket/upgrade.md @@ -0,0 +1,28 @@ +--- +name: Upgrade an HTTP request to a WebSocket connection +--- + +Inside `fetch`, use the `server.upgrade()` function to upgrade an incoming `Request` to a WebSocket connection. Bun automatically returns a 101 Switching Protocols response if the upgrade succeeds. + +Refer to the [WebSocket docs](/docs/api/websockets) for more information on building WebSocket servers. + +```ts +const server = Bun.serve<{ authToken: string }>({ + fetch(req, server) { + const success = server.upgrade(req); + if (success) { + // Bun automatically returns a 101 Switching Protocols + // if the upgrade succeeds + return undefined; + } + + // handle HTTP request normally + return new Response("Hello world!"); + }, + websocket: { + // define websocket handlers + }, +}); + +console.log(`Listening on localhost:\${server.port}`); +``` diff --git a/docs/guides/write-file/basic.md b/docs/guides/write-file/basic.md new file mode 100644 index 00000000000000..66f180a40be6c8 --- /dev/null +++ b/docs/guides/write-file/basic.md @@ -0,0 +1,44 @@ +--- +name: Write a string to a file +--- + +This code snippet writes a string to disk at a particular _absolute path_. + +It uses the fast [`Bun.write()`](/docs/api/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_; the second is the _data_ to write. + +```ts +const path = "/path/to/file.txt"; +await Bun.write(path, "Lorem ipsum"); +``` + +--- + +Any relative paths will be resolved relative to the project root (the nearest directory containing a `package.json` file). + +```ts +const path = "./file.txt"; +await Bun.write(path, "Lorem ipsum"); +``` + +--- + +You can pass a `BunFile` as the destination. `Bun.write()` will write the data to its associated path. + +```ts +const path = Bun.file("./file.txt"); +await Bun.write(path, "Lorem ipsum"); +``` + +--- + +`Bun.write()` returns the number of bytes written to disk. + +```ts +const path = "./file.txt"; +const bytes = await Bun.write(path, "Lorem ipsum"); +// => 11 +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/write-file/blob.md b/docs/guides/write-file/blob.md new file mode 100644 index 00000000000000..a923190bfa3ce5 --- /dev/null +++ b/docs/guides/write-file/blob.md @@ -0,0 +1,28 @@ +--- +name: Write a Blob to a file +--- + +This code snippet writes a `Blob` to disk at a particular path. + +It uses the fast [`Bun.write()`](/docs/api/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. + +```ts +const path = "/path/to/file.txt"; +await Bun.write(path, "Lorem ipsum"); +``` + +--- + +The `BunFile` class extends `Blob`, so you can pass a `BunFile` directly into `Bun.write()` as well. + +```ts +const path = "./out.txt"; +const data = Bun.file("./in.txt"); + +// write the contents of ./in.txt to ./out.txt +await Bun.write(path, data); +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/write-file/cat.md b/docs/guides/write-file/cat.md new file mode 100644 index 00000000000000..a9f9a0ba68418e --- /dev/null +++ b/docs/guides/write-file/cat.md @@ -0,0 +1,17 @@ +--- +name: Write a file to stdout +--- + +Bun exposes `stdout` as a `BunFile` with the `Bun.stdout` property. This can be used as a destination for [`Bun.write()`](/docs/api/file-io#writing-files-bun-write). + +This code writes a file to `stdout` similar to the `cat` command in Unix. + +```ts#cat.ts +const path = "/path/to/file.txt"; +const file = Bun.file(path); +await Bun.write(Bun.stdout, file); +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/write-file/file-cp.md b/docs/guides/write-file/file-cp.md new file mode 100644 index 00000000000000..b8910e269a4422 --- /dev/null +++ b/docs/guides/write-file/file-cp.md @@ -0,0 +1,16 @@ +--- +name: Copy a file to another location +--- + +This code snippet copies a file to another location on disk. + +It uses the fast [`Bun.write()`](/docs/api/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. + +```ts +const file = Bun.file("/path/to/original.txt"); +await Bun.write("/path/to/copy.txt", file); +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/write-file/filesink.md b/docs/guides/write-file/filesink.md new file mode 100644 index 00000000000000..10ea792ee69daf --- /dev/null +++ b/docs/guides/write-file/filesink.md @@ -0,0 +1,52 @@ +--- +name: Write a file incrementally +--- + +Bun provides an API for incrementally writing to a file. This is useful for writing large files, or for writing to a file over a long period of time. + +Call `.writer()` on a `BunFile` to retrieve a `FileSink` instance. This instance can be used to efficiently buffer data and periodically "flush" it to disk. You can write & flush many times. + +```ts +const file = Bun.file("/path/to/file.txt"); +const writer = file.writer(); + +writer.write("lorem"); +writer.write("ipsum"); +writer.write("dolor"); + +writer.flush(); + +// continue writing & flushing +``` + +--- + +The `.write()` method can accept strings or binary data. + +```ts +w.write("hello"); +w.write(Buffer.from("there")); +w.write(new Uint8Array([0, 255, 128])); +writer.flush(); +``` + +--- + +The `FileSink` will also auto-flush when its internal buffer is full. You can configure the buffer size with the `highWaterMark` option. + +```ts +const file = Bun.file("/path/to/file.txt"); +const writer = file.writer({ highWaterMark: 1024 * 1024 }); // 1MB +``` + +--- + +When you're done writing to the file, call `.end()` to auto-flush the buffer and close the file. + +```ts +writer.end(); +``` + +--- + +Full documentation: [FileSink](/docs/api/file-io#incremental-writing-with-filesink). diff --git a/docs/guides/write-file/index.json b/docs/guides/write-file/index.json new file mode 100644 index 00000000000000..dea48e215f358b --- /dev/null +++ b/docs/guides/write-file/index.json @@ -0,0 +1,4 @@ +{ + "name": "Writing files", + "description": "A collection of guides for writing files with Bun" +} diff --git a/docs/guides/write-file/response.md b/docs/guides/write-file/response.md new file mode 100644 index 00000000000000..fb2bd79eba573f --- /dev/null +++ b/docs/guides/write-file/response.md @@ -0,0 +1,17 @@ +--- +name: Write a Response to a file +--- + +This code snippet writes a `Response` to disk at a particular path. Bun will consume the `Response` body according to its `Content-Type` header. + +It uses the fast [`Bun.write()`](/docs/api/file-io#writing-files-bun-write) API to efficiently write data to disk. The first argument is a _destination_, like an absolute path or `BunFile` instance. The second argument is the _data_ to write. + +```ts +const result = await fetch("https://bun.sh"); +const path = "./file.txt"; +await Bun.write(path, result); +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/write-file/stdout.md b/docs/guides/write-file/stdout.md new file mode 100644 index 00000000000000..00fa11a6073333 --- /dev/null +++ b/docs/guides/write-file/stdout.md @@ -0,0 +1,21 @@ +--- +name: Write to stdout +--- + +The `console.log` function writes to `stdout`. It will automatically append a line break at the end of the printed data. + +```ts +console.log("Lorem ipsum"); +``` + +--- + +For more advanced use cases, Bun exposes `stdout` as a `BunFile` via the `Bun.stdout` property. This can be used as a destination for [`Bun.write()`](/docs/api/file-io#writing-files-bun-write). + +```ts +await Bun.write(Bun.stdout, "Lorem ipsum"); +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/write-file/stream.md b/docs/guides/write-file/stream.md new file mode 100644 index 00000000000000..efb7efd8a5d24b --- /dev/null +++ b/docs/guides/write-file/stream.md @@ -0,0 +1,17 @@ +--- +name: Write a ReadableStream to a file +--- + +To write a `ReadableStream` to disk, first create a `Response` instance from the stream. This `Response` can then be written to disk using [`Bun.write()`](/docs/api/file-io#writing-files-bun-write). + +```ts +const stream: ReadableStream = ...; +const path = "./file.txt"; +const response = new Response(stream); + +await Bun.write(path, response); +``` + +--- + +See [Docs > API > File I/O](/docs/api/file-io#writing-files-bun-write) for complete documentation of `Bun.write()`. diff --git a/docs/guides/write-file/unlink.md b/docs/guides/write-file/unlink.md new file mode 100644 index 00000000000000..ba0cbe8b1d3611 --- /dev/null +++ b/docs/guides/write-file/unlink.md @@ -0,0 +1,23 @@ +--- +name: Delete a file +--- + +To synchronously delete a file with Bun, use the `unlinkSync` function from the [`node:fs`](https://nodejs.org/api/fs.html#fs_fs_unlink_path_callback) module. (Currently, there is no `Bun` API for deleting files.) + +```ts +import { unlinkSync } from "node:fs"; + +const path = "/path/to/file.txt"; +unlinkSync(path); +``` + +--- + +To remove a file asynchronously, use the `unlink` function from the [`node:fs/promises`](https://nodejs.org/api/fs.html#fs_fspromises_unlink_path) module. + +```ts +import { unlink } from "node:fs/promises"; + +const path = "/path/to/file.txt"; +await unlink(path); +``` diff --git a/docs/install/cache.md b/docs/install/cache.md index 6bd13d04ad7109..bb22e545d88a8c 100644 --- a/docs/install/cache.md +++ b/docs/install/cache.md @@ -19,7 +19,7 @@ disableManifest = false ## Minimizing re-downloads -Bun strives to avoid re-downloading packages mutiple times. When installing a package, if the cache already contains a version in the range specified by `package.json`, Bun will use the cached package instead of downloading it again. +Bun strives to avoid re-downloading packages multiple times. When installing a package, if the cache already contains a version in the range specified by `package.json`, Bun will use the cached package instead of downloading it again. {% details summary="Installation details" %} If the semver version has pre-release suffix (`1.0.0-beta.0`) or a build suffix (`1.0.0+20220101`), it is replaced with a hash of that value instead, to reduce the chances of errors associated with long file paths. diff --git a/docs/install/index.md b/docs/install/index.md index 162a4abacf1f77..540ade9f032dd5 100644 --- a/docs/install/index.md +++ b/docs/install/index.md @@ -114,7 +114,7 @@ $ bun add zod@latest To add a package as a dev dependency (`"devDependencies"`): ```bash -$ bun add --development @types/react +$ bun add --dev @types/react $ bun add -d @types/react ``` diff --git a/docs/nav.ts b/docs/nav.ts index 13af7b20ec8734..4b3a67ec0a36f1 100644 --- a/docs/nav.ts +++ b/docs/nav.ts @@ -38,6 +38,11 @@ export default { page("templates", "Templates", { description: "Hit the ground running with one of Bun's official templates, or download a template from GitHub.", }), + page("guides", "Guides", { + description: "A set of walkthrough guides and code snippets for performing common tasks with Bun", + href: "/guides", + }), + // page("typescript", "TypeScript"), // divider("CLI"), @@ -105,6 +110,9 @@ export default { page("runtime/nodejs-apis", "Node.js compatibility", { description: `Bun aims for full Node.js compatibility. This page tracks the current compatibility status.`, }), + page("runtime/plugins", "Plugins", { + description: `Implement custom loaders and module resolution logic with Bun's plugin system.`, + }), // page("runtime/nodejs", "Node.js compatibility", { // description: `Track the status of Bun's API compatibility with Node.js.`, @@ -202,6 +210,9 @@ export default { page("test/dom", "DOM testing", { description: "Write headless tests for UI and React/Vue/Svelte/Lit components with happy-dom", }), + page("test/coverage", "Code coverage", { + description: "Generate code coverage reports with `bun test --coverage`", + }), divider("Package runner"), page("cli/bunx", "`bunx`", { @@ -210,30 +221,29 @@ export default { // page("runtime/nodejs", "Node.js APIs"), - divider("Ecosystem"), + // divider("Ecosystem"), // page("ecosystem/react", "React", { // description: `The Bun runtime supports JSX syntax out of the box and optimizes server-side rendering.`, // }), - page("ecosystem/express", "Express", { - description: `Servers built with Express and other major Node.js HTTP libraries work out of the box.`, - }), - page("ecosystem/elysia", "Elysia", { - description: `Get started with Elysia, a Bun-native framework designed for the edge.`, - }), - page("ecosystem/hono", "Hono", { - description: `Hono is an ultra-fast, Bun-friendly web framework designed for edge environments.`, - }), + // page("ecosystem/express", "Express", { + // description: `Servers built with Express and other major Node.js HTTP libraries work out of the box.`, + // }), + // page("ecosystem/elysia", "Elysia", { + // description: `Get started with Elysia, a Bun-native framework designed for the edge.`, + // }), + // page("ecosystem/hono", "Hono", { + // description: `Hono is an ultra-fast, Bun-friendly web framework designed for edge environments.`, + // }), // page("ecosystem/buchta", "Buchta", { // description: `Buchta is a Bun-native fullstack framework for Svelte and Preact apps.`, // }), - page("ecosystem/stric", "Stric", { - description: `Stric is a minimalist, fast web framework for Bun.`, - }), - - page("ecosystem/awesome", "Awesome", { - href: "https://github.com/apvarun/awesome-bun", - description: ``, - }), + // page("ecosystem/stric", "Stric", { + // description: `Stric is a minimalist, fast web framework for Bun.`, + // }), + // page("ecosystem/awesome", "Awesome", { + // href: "https://github.com/apvarun/awesome-bun", + // description: ``, + // }), divider("API"), page("api/http", "HTTP server", { diff --git a/docs/runtime/autoimport.md b/docs/runtime/autoimport.md index 70af18e1f737ff..d1472302496679 100644 --- a/docs/runtime/autoimport.md +++ b/docs/runtime/autoimport.md @@ -4,7 +4,7 @@ If no `node_modules` directory is found in the working directory or higher, Bun will abandon Node.js-style module resolution in favor of the **Bun module resolution algorithm**. -Under Bun-style module resolution, all imported packages are auto-installed on the fly into a [global module cache](/docs/cli/install#global-cache) during execution (the same cache used by [`bun install`](/docs/cli/install)). +Under Bun-style module resolution, all imported packages are auto-installed on the fly into a [global module cache](/docs/install/cache) during execution (the same cache used by [`bun install`](/docs/cli/install)). ```ts import { foo } from "foo"; // install `latest` version diff --git a/docs/runtime/bun-apis.md b/docs/runtime/bun-apis.md index c4cd534e75ff2c..6907e802dc599b 100644 --- a/docs/runtime/bun-apis.md +++ b/docs/runtime/bun-apis.md @@ -95,6 +95,6 @@ Click the link in the right column to jump to the associated documentation. --- - Utilities -- [`Bun.version`](/docs/api/utils#bun-version) [`Bun.revision`](/docs/api/utils#bun-revision) [`Bun.env`](/docs/api/utils#bun-env) [`Bun.main`](/docs/api/utils#bun-main) [`Bun.sleep()`](/docs/api/utils#bun-sleep) [`Bun.sleepSync()`](/docs/api/utils#bun-sleepsync) [`Bun.which()`](/docs/api/utils#bun-which) [`Bun.peek()`](/docs/api/utils#bun-peek) [`Bun.openInEditor()`](/docs/api/utils#bun-openineditor) [`Bun.deepEquals()`](/docs/api/utils#bun-deepequals) [`Bun.escapeHTML()`](/docs/api/utils#bun-escapehtlm) [`Bun.enableANSIColors()`](/docs/api/utils#bun-enableansicolors) [`Bun.fileURLToPath()`](/docs/api/utils#bun-fileurltopath) [`Bun.pathToFileURL()`](/docs/api/utils#bun-pathtofileurl) [`Bun.gzipSync()`](/docs/api/utils#bun-gzipsync) [`Bun.gunzipSync()`](/docs/api/utils#bun-gunzipsync) [`Bun.deflateSync()`](/docs/api/utils#bun-deflatesync) [`Bun.inflateSync()`](/docs/api/utils#bun-inflatesync) [`Bun.inspect()`](/docs/api/utils#bun-inspect) [`Bun.nanoseconds()`](/docs/api/utils#bun-nanoseconds) [`Bun.readableStreamTo*()`](/docs/api/utils#bun-readablestreamto) [`Bun.resolveSync()`](/docs/api/utils#bun-resolvesync) +- [`Bun.version`](/docs/api/utils#bun-version) [`Bun.revision`](/docs/api/utils#bun-revision) [`Bun.env`](/docs/api/utils#bun-env) [`Bun.main`](/docs/api/utils#bun-main) [`Bun.sleep()`](/docs/api/utils#bun-sleep) [`Bun.sleepSync()`](/docs/api/utils#bun-sleepsync) [`Bun.which()`](/docs/api/utils#bun-which) [`Bun.peek()`](/docs/api/utils#bun-peek) [`Bun.openInEditor()`](/docs/api/utils#bun-openineditor) [`Bun.deepEquals()`](/docs/api/utils#bun-deepequals) [`Bun.escapeHTML()`](/docs/api/utils#bun-escapehtml) [`Bun.fileURLToPath()`](/docs/api/utils#bun-fileurltopath) [`Bun.pathToFileURL()`](/docs/api/utils#bun-pathtofileurl) [`Bun.gzipSync()`](/docs/api/utils#bun-gzipsync) [`Bun.gunzipSync()`](/docs/api/utils#bun-gunzipsync) [`Bun.deflateSync()`](/docs/api/utils#bun-deflatesync) [`Bun.inflateSync()`](/docs/api/utils#bun-inflatesync) [`Bun.inspect()`](/docs/api/utils#bun-inspect) [`Bun.nanoseconds()`](/docs/api/utils#bun-nanoseconds) [`Bun.readableStreamTo*()`](/docs/api/utils#bun-readablestreamto) [`Bun.resolveSync()`](/docs/api/utils#bun-resolvesync) {% /table %} diff --git a/docs/runtime/index.md b/docs/runtime/index.md index 90d2000066a483..a10ac0cff7bd2a 100644 --- a/docs/runtime/index.md +++ b/docs/runtime/index.md @@ -6,7 +6,7 @@ Bun is designed to start fast and run fast. It's transpiler and runtime are writ {% image src="/images/bun-run-speed.jpeg" caption="Bun vs Node.js vs Deno running Hello World" /%} - + Performance sensitive APIs like `Buffer`, `fetch`, and `Response` are heavily profiled and optimized. Under the hood Bun uses the [JavaScriptCore engine](https://developer.apple.com/documentation/javascriptcore), which is developed by Apple for Safari. It starts and runs faster than V8, the engine used by Node.js and Chromium-based browsers. diff --git a/docs/runtime/jsx.md b/docs/runtime/jsx.md index ecf250c8274a4f..053c8b01c102a8 100644 --- a/docs/runtime/jsx.md +++ b/docs/runtime/jsx.md @@ -77,7 +77,7 @@ How JSX constructs are transformed into vanilla JavaScript internally. The table ); ``` - The `jsxDEV` variable name is a convention used by React. The `DEV` suffix is a visible way to indicate that the code is intended for use in development. The development version of React is slowers and includes additional validity checks & debugging tools. + The `jsxDEV` variable name is a convention used by React. The `DEV` suffix is a visible way to indicate that the code is intended for use in development. The development version of React is slower and includes additional validity checks & debugging tools. --- diff --git a/docs/runtime/modules.md b/docs/runtime/modules.md index 42f2a08e6a69fb..207315804339c9 100644 --- a/docs/runtime/modules.md +++ b/docs/runtime/modules.md @@ -98,22 +98,24 @@ import { stuff } from "foo"; The full specification of this algorithm are officially documented in the [Node.js documentation](https://nodejs.org/api/modules.html); we won't rehash it here. Briefly: if you import `from "foo"`, Bun scans up the file system for a `node_modules` directory containing the package `foo`. -Once it finds the `foo` package, Bun reads the `package.json` to determine how the package should be imported. Unless `"type": "module"` is specified, Bun assumes the package is using CommonJS and transpiles into a synchronous ES module internally. To determine the package's entrypoint, Bun first reads the `exports` field in and checks the following conditions in order: +Once it finds the `foo` package, Bun reads the `package.json` to determine how the package should be imported. To determine the package's entrypoint, Bun first reads the `exports` field and checks for the following conditions. ```jsonc#package.json { "name": "foo", "exports": { - "bun": "./index.js", // highest priority + "bun": "./index.js", "worker": "./index.js", - "module": "./index.js", "node": "./index.js", + "require": "./index.js", # if importer is CommonJS + "import": "./index.mjs", # if importer is ES module "default": "./index.js", - "browser": "./index.js" // lowest priority } } ``` +Whichever one of these conditions occurs _first_ in the `package.json` is used to determine the package's entrypoint. + Bun respects subpath [`"exports"`](https://nodejs.org/api/packages.html#subpath-exports) and [`"imports"`](https://nodejs.org/api/packages.html#imports). Specifying any subpath in the `"exports"` map will prevent other subpaths from being importable. ```jsonc#package.json diff --git a/docs/runtime/nodejs-apis.md b/docs/runtime/nodejs-apis.md index dad8489c075321..67a6bf4987f889 100644 --- a/docs/runtime/nodejs-apis.md +++ b/docs/runtime/nodejs-apis.md @@ -4,7 +4,171 @@ This page is updated regularly to reflect compatibility status of the latest ver ## Built-in modules -{% block className="ScrollFrame" %} +### [`node:assert`](https://nodejs.org/api/assert.html) + +🟢 Fully implemented. + +### [`node:async_hooks`](https://nodejs.org/api/async_hooks.html) + +🔴 Not implemented. + +### [`node:buffer`](https://nodejs.org/api/buffer.html) + +🟢 Fully implemented. + +### [`node:child_process`](https://nodejs.org/api/child_process.html) + +🟡 Missing IPC, `Stream` stdio, `proc.gid`, `proc.uid`, advanced serialization. + +### [`node:cluster`](https://nodejs.org/api/cluster.html) + +🔴 Not implemented. + +### [`node:console`](https://nodejs.org/api/console.html) + +🟢 Recommended to use `console` global instead + +### [`node:crypto`](https://nodejs.org/api/crypto.html) + +🟡 Missing `crypto.Certificate` `crypto.ECDH` `crypto.KeyObject` `crypto.X509Certificate` `crypto.checkPrime{Sync}` `crypto.createPrivateKey` `crypto.createPublicKey` `crypto.createSecretKey` `crypto.diffieHellman` `crypto.generateKey{Sync}` `crypto.generateKeyPair{Sync}` `crypto.generatePrime{Sync}` `crypto.getCipherInfo` `crypto.{get|set}Fips` `crypto.hkdf` `crypto.hkdfSync` `crypto.secureHeapUsed` `crypto.setEngine` `crypto.sign` `crypto.verify`. Some methods are not optimized yet. + +### [`node:dgram`](https://nodejs.org/api/dgram.html) + +🔴 Not implemented. + +### [`node:diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) + +🟢 Fully implemented. + +### [`node:dns`](https://nodejs.org/api/dns.html) + +🟢 Fully implemented. + +### [`node:domain`](https://nodejs.org/api/domain.html) + +🟢 Fully implemented. + +### [`node:events`](https://nodejs.org/api/events.html) + +🟡 Missing `EventEmitterAsyncResource` `events.on`. + +### [`node:fs`](https://nodejs.org/api/fs.html) + +🟡 Missing `fs.fdatasync{Sync}` `fs.opendir{Sync}` `fs.{watchFile|unwatchFile}` `fs.{cp|cpSync}`. `fs.promises.open` incorrectly returns a file descriptor instead of a `FileHandle`. + +### [`node:http`](https://nodejs.org/api/http.html) + +🟢 Fully implemented. + +### [`node:http2`](https://nodejs.org/api/http2.html) + +🔴 Not implemented. + +### [`node:https`](https://nodejs.org/api/https.html) + +🟢 Fully implemented. + +### [`node:inspector`](https://nodejs.org/api/inspector.html) + +🔴 Not implemented. + +### [`node:module`](https://nodejs.org/api/module.html) + +🟢 Fully implemented. + +### [`node:net`](https://nodejs.org/api/net.html) + +🟡 Missing `net.{get|set}DefaultAutoSelectFamily` `net.SocketAddress` `net.BlockList`. + +### [`node:os`](https://nodejs.org/api/os.html) + +🟢 Fully implemented. + +### [`node:path`](https://nodejs.org/api/path.html) + +🟢 Fully implemented. + +### [`node:perf_hooks`](https://nodejs.org/api/perf_hooks.html) + +🟡 Only `perf_hooks.performance.now()` and `perf_hooks.performance.timeOrigin` are implemented. Recommended to use `performance` global instead of `perf_hooks.performance`. + +### [`node:process`](https://nodejs.org/api/process.html) + +🟡 See `Globals > process`. + +### [`node:punycode`](https://nodejs.org/api/punycode.html) + +🟢 Fully implemented. _Deprecated by Node.js._ + +### [`node:querystring`](https://nodejs.org/api/querystring.html) + +🟢 Fully implemented. + +### [`node:readline`](https://nodejs.org/api/readline.html) + +🟢 Fully implemented. + +### [`node:repl`](https://nodejs.org/api/repl.html) + +🔴 Not implemented. + +### [`node:stream`](https://nodejs.org/api/stream.html) + +🟢 Fully implemented. + +### [`node:string_decoder`](https://nodejs.org/api/string_decoder.html) + +🟢 Fully implemented. + +### [`node:sys`](https://nodejs.org/api/util.html) + +🟡 See `node:util`. + +### [`node:timers`](https://nodejs.org/api/timers.html) + +🟢 Recommended to use global `setTimeout`, et. al. instead. + +### [`node:tls`](https://nodejs.org/api/tls.html) + +🟡 Missing `tls.createSecurePair` + +### [`node:trace_events`](https://nodejs.org/api/tracing.html) + +🔴 Not implemented. + +### [`node:tty`](https://nodejs.org/api/tty.html) + +🟡 Missing `tty.ReadStream` and `tty.WriteStream`. + +### [`node:url`](https://nodejs.org/api/url.html) + +🟡 Missing `url.domainTo{ASCII|Unicode}`. Recommended to use `URL` and `URLSearchParams` globals instead. + +### [`node:util`](https://nodejs.org/api/util.html) + +🟡 Missing `util.MIMEParams` `util.MIMEType` `util.formatWithOptions()` `util.getSystemErrorMap()` `util.getSystemErrorName()` `util.parseArgs()` `util.stripVTControlCharacters()` `util.transferableAbortController()` `util.transferableAbortSignal()`. + +### [`node:v8`](https://nodejs.org/api/v8.html) + +🔴 `serialize` and `deserialize` use JavaScriptCore's wire format instead of V8's. Otherwise, not implemented. For profiling, use [`bun:jsc`](/docs/project/benchmarking#bunjsc) instead. + +### [`node:vm`](https://nodejs.org/api/vm.html) + +🟡 Core functionality works, but VM modules are not implemented. `ShadowRealm` can be used. + +### [`node:wasi`](https://nodejs.org/api/wasi.html) + +🟡 Partially implemented. + +### [`node:worker_threads`](https://nodejs.org/api/worker_threads.html) + +🟢 Fully implemented. + +### [`node:zlib`](https://nodejs.org/api/zlib.html) + +🟡 Missing `zlib.brotli*` + + ## Globals The table below lists all globals implemented by Node.js and Bun's current compatibility status. -{% table %} +### [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) + +🟢 Fully implemented. + +### [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) + +🟢 Fully implemented. + +### [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + +🟢 Fully implemented. + +### [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) + +🟡 Incomplete implementation of `base64` and `base64url` encodings. + +### [`ByteLengthQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy) + +🟢 Fully implemented. + +### [`__dirname`](https://nodejs.org/api/globals.html#__dirname) + +🟢 Fully implemented. + +### [`__filename`](https://nodejs.org/api/globals.html#__filename) + +🟢 Fully implemented. + +### [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/atob) + +🟢 Fully implemented. + +### [`BroadcastChannel`](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel) + +🟢 Fully implemented. + +### [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/btoa) + +🟢 Fully implemented. + +### [`clearImmediate()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearImmediate) + +🟢 Fully implemented. + +### [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearInterval) + +🟢 Fully implemented. + +### [`clearTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearTimeout) + +🟢 Fully implemented. + +### [`CompressionStream`](https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream) + +🔴 Not implemented. + +### [`console`](https://developer.mozilla.org/en-US/docs/Web/API/console) + +🟢 Fully implemented. + +### [`CountQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/CountQueuingStrategy) + +🟢 Fully implemented. + +### [`Crypto`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) + +🟢 Fully implemented. + +### [`SubtleCrypto (crypto)`](https://developer.mozilla.org/en-US/docs/Web/API/crypto) + +🟢 Fully implemented. + +### [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) + +🟢 Fully implemented. + +### [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) + +🟢 Fully implemented. + +### [`DecompressionStream`](https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream) + +🔴 Not implemented. + +### [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) + +🟢 Fully implemented. + +### [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +🟢 Fully implemented. + +### [`exports`](https://nodejs.org/api/globals.html#exports) + +🟢 Fully implemented. + +### [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) + +🟢 Fully implemented. + +### [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) + +🟢 Fully implemented. Added in Bun 0.5.7. + +### [`global`](https://nodejs.org/api/globals.html#global) + +🟢 Implemented. This is an object containing all objects in the global namespace. It's rarely referenced directly, as its contents are available without an additional prefix, e.g. `__dirname` instead of `global.__dirname`. + +### [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) + +🟢 Aliases to `global`. + +### [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) + +🟢 Fully implemented. + +### [`MessageChannel`](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel) + +🟢 Fully implemented. + +### [`MessageEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent) + +🟢 Fully implemented. + +### [`MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) + +🟢 Fully implemented. + +### [`module`](https://nodejs.org/api/globals.html#module) + +🟢 Fully implemented. + +### [`PerformanceEntry`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry) + +🔴 Not implemented. + +### [`PerformanceMark`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMark) + +🔴 Not implemented. + +### [`PerformanceMeasure`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure) + +🔴 Not implemented. + +### [`PerformanceObserver`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver) + +🔴 Not implemented. + +### [`PerformanceObserverEntryList`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList) + +🔴 Not implemented. + +### [`PerformanceResourceTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming) + +🔴 Not implemented. + +### [`performance`](https://developer.mozilla.org/en-US/docs/Web/API/performance) + +🟢 Fully implemented. + +### [`process`](https://nodejs.org/api/process.html) + +🟡 Missing `process.allowedNodeEnvironmentFlags` `process.channel()` `process.connected` `process.constrainedMemory()` `process.disconnect()` `process.getActiveResourcesInfo/setActiveResourcesInfo()` `process.setuid/setgid/setegid/seteuid/setgroups()` `process.hasUncaughtExceptionCaptureCallback` `process.initGroups()` `process.report` `process.resourceUsage()` `process.send()`. + +### [`queueMicrotask()`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) + +🟢 Fully implemented. + +### [`ReadableByteStreamController`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController) + +🟢 Fully implemented. + +### [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) + +🟢 Fully implemented. + +### [`ReadableStreamBYOBReader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader) + +🔴 Not implemented. + +### [`ReadableStreamBYOBRequest`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBRequest) + +🔴 Not implemented. + +### [`ReadableStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController) + +🟢 Fully implemented. + +### [`ReadableStreamDefaultReader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) + +🟢 Fully implemented. + +### [`require()`](https://nodejs.org/api/globals.html#require) + +🟢 Fully implemented, as well as [`require.main`](https://nodejs.org/api/modules.html#requiremain), [`require.cache`](https://nodejs.org/api/modules.html#requirecache), and [`require.resolve`](https://nodejs.org/api/modules.html#requireresolverequest-options) + +### [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) + +🟢 Fully implemented. + +### [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) + +🟢 Fully implemented. + +### [`setImmediate()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate) + +🟢 Fully implemented. + +### [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval) + +🟢 Fully implemented. + +### [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) + +🟢 Fully implemented. + +### [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) + +🟢 Fully implemented. + +### [`SubtleCrypto`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) + +🟢 Fully implemented. + +### [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) + +🟢 Fully implemented. + +### [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) + +🟢 Fully implemented. + +### [`TextDecoderStream`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoderStream) + +🔴 Not implemented. + +### [`TextEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder) + +🟢 Fully implemented. + +### [`TextEncoderStream`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoderStream) + +🔴 Not implemented. + +### [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) + +🟢 Fully implemented. + +### [`TransformStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStreamDefaultController) + +🟢 Fully implemented. + +### [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) + +🟢 Fully implemented. + +### [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) + +🟢 Fully implemented. + +### [`WebAssembly`](https://nodejs.org/api/globals.html#webassembly) + +🟢 Fully implemented. + +### [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) + +🟢 Fully implemented. + +### [`WritableStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultController) + +🟢 Fully implemented. + +### [`WritableStreamDefaultWriter`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter) + +🟢 Fully implemented. + + diff --git a/docs/runtime/plugins.md b/docs/runtime/plugins.md new file mode 100644 index 00000000000000..39eea327866e3a --- /dev/null +++ b/docs/runtime/plugins.md @@ -0,0 +1,276 @@ +{% callout %} +**Note** — Introduced in Bun v0.1.11. +{% /callout %} + +Bun provides a universal plugin API that can be used to extend both the _runtime_ and [_bundler_](/docs/bundler). + +Plugins intercept imports and perform custom loading logic: reading files, transpiling code, etc. They can be used to add support for additional file types, like `.scss` or `.yaml`. In the context of Bun's bundler, plugins can be used to implement framework-level features like CSS extraction, macros, and client-server code co-location. + +## Usage + +A plugin is defined as simple JavaScript object containing a `name` property and a `setup` function. Register a plugin with Bun using the `plugin` function. + +```tsx#myPlugin.ts +import { plugin, type BunPlugin } from "bun"; + +const myPlugin: BunPlugin = { + name: "Custom loader", + setup(build) { + // implementation + }, +}; +``` + +Plugins have to be registered before any other code runs! To achieve this, use the `preload` option in your [`bunfig.toml`](/docs/runtime/configuration). Bun automatically loads the files/modules specified in `preload` before running a file. + +```toml +preload = ["./myPlugin.ts"] +``` + +To preload files before `bun test`: + +```toml +[test] +preload = ["./myPlugin.ts"] +``` + +## Third-party plugins + +By convention, third-party plugins intended for consumption should export a factory function that accepts some configuration and returns a plugin object. + +```ts +import { plugin } from "bun"; +import fooPlugin from "bun-plugin-foo"; + +plugin( + fooPlugin({ + // configuration + }), +); +``` + +Bun's plugin API is based on [esbuild](https://esbuild.github.io/plugins). Only [a subset](/docs/bundler/vs-esbuild#plugin-api) of the esbuild API is implemented, but some esbuild plugins "just work" in Bun, like the official [MDX loader](https://mdxjs.com/packages/esbuild/): + +```jsx +import { plugin } from "bun"; +import mdx from "@mdx-js/esbuild"; + +plugin(mdx()); +``` + +## Loaders + +Plugins are primarily used to extend Bun with loaders for additional file types. Let's look at a simple plugin that implements a loader for `.yaml` files. + +```ts#yamlPlugin.ts +import { plugin } from "bun"; + +plugin({ + name: "YAML", + async setup(build) { + const { load } = await import("js-yaml"); + const { readFileSync } = await import("fs"); + + // when a .yaml file is imported... + build.onLoad({ filter: /\.(yaml|yml)$/ }, (args) => { + + // read and parse the file + const text = readFileSync(args.path, "utf8"); + const exports = load(text) as Record; + + // and returns it as a module + return { + exports, + loader: "object", // special loader for JS objects + }; + }); + }, +}); +``` + +With this plugin, data can be directly imported from `.yaml` files. + +{% codetabs %} + +```ts#index.ts +import "./yamlPlugin.ts" +import {name, releaseYear} from "./data.yml" + +console.log(name, releaseYear); +``` + +```yaml#data.yml +name: Fast X +releaseYear: 2023 +``` + +{% /codetabs %} + +Note that the returned object has a `loader` property. This tells Bun which of its internal loaders should be used to handle the result. Even though we're implementing a loader for `.yaml`, the result must still be understandable by one of Bun's built-in loaders. It's loaders all the way down. + +In this case we're using `"object"`—a built-in loader (intended for use by plugins) that converts a plain JavaScript object to an equivalent ES module. Any of Bun's built-in loaders are supported; these same loaders are used by Bun internally for handling files of various kinds. The table below is a quick reference; refer to [Bundler > Loaders](/docs/bundler/loaders) for complete documentation. + +{% table %} + +- Loader +- Extensions +- Output + +--- + +- `js` +- `.mjs` `.cjs` +- Transpile to JavaScript files + +--- + +- `jsx` +- `.js` `.jsx` +- Transform JSX then transpile + +--- + +- `ts` +- `.ts` `.mts` `cts` +- Transform TypeScript then transpile + +--- + +- `tsx` +- `.tsx` +- Transform TypeScript, JSX, then transpile + +--- + +- `toml` +- `.toml` +- Parse using Bun's built-in TOML parser + +--- + +- `json` +- `.json` +- Parse using Bun's built-in JSON parser + +--- + +- `napi` +- `.node` +- Import a native Node.js addon + +--- + +- `wasm` +- `.wasm` +- Import a native Node.js addon + +--- + +- `object` +- _none_ +- A special loader intended for plugins that converts a plain JavaScript object to an equivalent ES module. Each key in the object corresponds to a named export. + +{% /callout %} + +Loading a YAML file is useful, but plugins support more than just data loading. Let's look at a plugin that lets Bun import `*.svelte` files. + +```ts#sveltePlugin.ts +import { plugin } from "bun"; + +await plugin({ + name: "svelte loader", + async setup(build) { + const { compile } = await import("svelte/compiler"); + const { readFileSync } = await import("fs"); + + // when a .svelte file is imported... + build.onLoad({ filter: /\.svelte$/ }, ({ path }) => { + + // read and compile it with the Svelte compiler + const file = readFileSync(path, "utf8"); + const contents = compile(file, { + filename: path, + generate: "ssr", + }).js.code; + + // and return the compiled source code as "js" + return { + contents, + loader: "js", + }; + }); + }, +}); +``` + +> Note: in a production implementation, you'd want to cache the compiled output and include additional error handling. + +The object returned from `build.onLoad` contains the compiled source code in `contents` and specifies `"js"` as its loader. That tells Bun to consider the returned `contents` to be a JavaScript module and transpile it using Bun's built-in `js` loader. + +With this plugin, Svelte components can now be directly imported and consumed. + +```js +import "./sveltePlugin.ts"; +import MySvelteComponent from "./component.svelte"; + +console.log(mySvelteComponent.render()); +``` + +## Reading the config + +Plugins can read and write to the [build config](/docs/bundler#api) with `build.config`. + +```ts +Bun.build({ + entrypoints: ["./app.ts"], + outdir: "./dist", + sourcemap: "external", + plugins: [ + { + name: "demo", + setup(build) { + console.log(build.config.sourcemap); // "external" + + build.config.minify = true; // enable minification + + // `plugins` is readonly + console.log(`Number of plugins: ${build.config.plugins.length}`); + }, + }, + ], +}); +``` + +## Reference + +```ts +namespace Bun { + function plugin(plugin: { + name: string; + setup: (build: PluginBuilder) => void; + }): void; +} + +type PluginBuilder = { + onResolve: ( + args: { filter: RegExp; namespace?: string }, + callback: (args: { path: string; importer: string }) => { + path: string; + namespace?: string; + } | void, + ) => void; + onLoad: ( + args: { filter: RegExp; namespace?: string }, + callback: (args: { path: string }) => { + loader?: Loader; + contents?: string; + exports?: Record; + }, + ) => void; + config: BuildConfig; +}; + +type Loader = "js" | "jsx" | "ts" | "tsx" | "json" | "toml" | "object"; +``` + +The `onLoad` method optionally accepts a `namespace` in addition to the `filter` regex. This namespace will be be used to prefix the import in transpiled code; for instance, a loader with a `filter: /\.yaml$/` and `namespace: "yaml:"` will transform an import from `./myfile.yaml` into `yaml:./myfile.yaml`. diff --git a/docs/runtime/web-apis.md b/docs/runtime/web-apis.md index 366fa7819944e6..98c822274fdb42 100644 --- a/docs/runtime/web-apis.md +++ b/docs/runtime/web-apis.md @@ -17,7 +17,7 @@ The following Web APIs are partially or completely supported. --- - Web Workers -- [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) [`self.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage) [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone). Missing `MessagePort`, `MessageChannel`, `BroadcastChannel`. +- [`Worker`](https://developer.mozilla.org/en-US/docs/Web/API/Worker) [`self.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope/postMessage) [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) [`MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) [`MessageChannel`](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel), [`BroadcastChannel`](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel). --- diff --git a/docs/test/coverage.md b/docs/test/coverage.md new file mode 100644 index 00000000000000..229da41f2c45e1 --- /dev/null +++ b/docs/test/coverage.md @@ -0,0 +1,57 @@ +`bun:test` supports seeing which lines of code are covered by tests. To use this feature, pass `--coverage` to the CLI: + +```sh +bun test --coverage +``` + +It will print out a coverage report to the console: + +```js +-------------|---------|---------|------------------- +File | % Funcs | % Lines | Uncovered Line #s +-------------|---------|---------|------------------- +All files | 38.89 | 42.11 | + index-0.ts | 33.33 | 36.84 | 10-15,19-24 + index-1.ts | 33.33 | 36.84 | 10-15,19-24 + index-10.ts | 33.33 | 36.84 | 10-15,19-24 + index-2.ts | 33.33 | 36.84 | 10-15,19-24 + index-3.ts | 33.33 | 36.84 | 10-15,19-24 + index-4.ts | 33.33 | 36.84 | 10-15,19-24 + index-5.ts | 33.33 | 36.84 | 10-15,19-24 + index-6.ts | 33.33 | 36.84 | 10-15,19-24 + index-7.ts | 33.33 | 36.84 | 10-15,19-24 + index-8.ts | 33.33 | 36.84 | 10-15,19-24 + index-9.ts | 33.33 | 36.84 | 10-15,19-24 + index.ts | 100.00 | 100.00 | +-------------|---------|---------|------------------- +``` + +If coverage is below a threshold, `bun:test` will exit with a non-zero exit code to indicate the failure. + +### Configuring coverage + +`bunfig.toml` supports configuring coverage: + +```toml +[test] + +# Always enable coverage +coverage = true + +# Anything less than 90% coverage will fail the test +# coverageThreshold = 0.9 +coverageThreshold = { line = 0.9, function = 0.9 } + + +# Don't include .test.* files in coverage reports +coverageSkipTestFiles = true + +# Disable sourcemap support in coverage reports +# By default, coverage reports will automatically use Bun's internal sourcemap. +# You probably don't want to configure this +# coverageIgnoreSourcemaps = false +``` + +`coverageThreshold` can be either a number or an object with `line` and `function` keys. When a number, it is treated as both the line and function threshold. + +Coverage support was added in Bun v0.7.3. diff --git a/docs/test/writing.md b/docs/test/writing.md index e5e3fe1b0e6169..a99af8b90c5555 100644 --- a/docs/test/writing.md +++ b/docs/test/writing.md @@ -101,7 +101,7 @@ test.todo("fix this", () => { }); ``` -To exlusively run tests marked as _todo_, use `bun test --todo`. +To exclusively run tests marked as _todo_, use `bun test --todo`. ```sh $ bun test --todo diff --git a/examples/hashing.js b/examples/hashing.js index cf4772ffe33905..3f23d1312314d6 100644 --- a/examples/hashing.js +++ b/examples/hashing.js @@ -1,18 +1,19 @@ -// Accepts a string, TypedArray, or Blob (file blob supported is not implemented but planned) +// Accepts a string, TypedArray, or Blob (file blob support is not implemented but planned) const input = "hello world".repeat(400); // Bun.hash() defaults to Wyhash because it's fast console.log(Bun.hash(input)); console.log(Bun.hash.wyhash(input)); -// and returns a number -// all of these hashing functions return numbers, not typed arrays. -console.log(Bun.hash.adler32(input)); -console.log(Bun.hash.crc32(input)); -console.log(Bun.hash.cityHash32(input)); -console.log(Bun.hash.cityHash64(input)); -console.log(Bun.hash.murmur32v3(input)); -console.log(Bun.hash.murmur64v2(input)); +// and returns a bigint +// all of these hashing functions return number if 32-bit or bigint if 64-bit, not typed arrays. +console.log(Bun.hash.adler32(input)); // number +console.log(Bun.hash.crc32(input)); // number +console.log(Bun.hash.cityHash32(input)); // number +console.log(Bun.hash.cityHash64(input)); // bigint +console.log(Bun.hash.murmur32v3(input)); // number +console.log(Bun.hash.murmur32v2(input)); // number +console.log(Bun.hash.murmur64v2(input)); // bigint // Second argument accepts a seed where relevant console.log(Bun.hash(input, 12345)); diff --git a/examples/macros/matchInFile.tsx b/examples/macros/matchInFile.tsx index e434d1decce2ce..4793661d99addf 100644 --- a/examples/macros/matchInFile.tsx +++ b/examples/macros/matchInFile.tsx @@ -1,12 +1,12 @@ // macro code -export function matchInFile(callExpression: BunAST.CallExpression) { +export async function matchInFile(callExpression: BunAST.CallExpression) { const [filePathNode, matcherNode] = callExpression.arguments; let filePath: string; filePath = filePathNode.get(); let matcher: RegExp; matcher = matcherNode.get(); - const file: string = Bun.readFile(Bun.cwd + filePath); + const file: string = await Bun.file(Bun.cwd + filePath).text(); return ( diff --git a/package.json b/package.json index 9da688e5fccba4..4697689f9c46b0 100644 --- a/package.json +++ b/package.json @@ -22,10 +22,9 @@ }, "devDependencies": { "@types/react": "^18.0.25", - "@types/ws": "^8.5.5", "@typescript-eslint/eslint-plugin": "^5.31.0", "@typescript-eslint/parser": "^5.31.0", - "bun-webkit": "0.0.1-3a53c6af693c5f387de752b0c793ac1ab5f0a164" + "bun-webkit": "0.0.1-74609640b2a7c5a1588b824f870d1b0ff91bfd8e" }, "version": "0.0.0", "prettier": "./.prettierrc.cjs" diff --git a/packages/bun-types/async_hooks.d.ts b/packages/bun-types/async_hooks.d.ts index e69de29bb2d1d6..43de681caf8834 100644 --- a/packages/bun-types/async_hooks.d.ts +++ b/packages/bun-types/async_hooks.d.ts @@ -0,0 +1,554 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * `AsyncLocalStorage` tracks async context + * * `process.getActiveResourcesInfo()` tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v0.7.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v0.7.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?( + asyncId: number, + type: string, + triggerAsyncId: number, + resource: object, + ): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v0.7.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v0.7.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v0.7.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v0.7.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v0.7.0 + */ + class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v0.7.0 + * @experimental + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v0.7.0 + * @experimental + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): ( + fn: (...args: TArgs) => R, + ...args: TArgs + ) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v0.7.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v0.7.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v0.7.0 + */ + run( + store: T, + callback: (...args: TArgs) => R, + ...args: TArgs + ): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v0.7.0 + * @experimental + */ + exit( + callback: (...args: TArgs) => R, + ...args: TArgs + ): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v0.7.0 + * @experimental + */ + enterWith(store: T): void; + } +} + +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/packages/bun-types/bun-test.d.ts b/packages/bun-types/bun-test.d.ts index 5182f7e93986b7..790d8bfea53080 100644 --- a/packages/bun-types/bun-test.d.ts +++ b/packages/bun-types/bun-test.d.ts @@ -169,6 +169,25 @@ declare module "bun:test" { * @param condition if these tests should be skipped */ skipIf(condition: boolean): (label: string, fn: () => void) => void; + /** + * Returns a function that runs for each item in `table`. + * + * @param table Array of Arrays with the arguments that are passed into the test fn for each row. + */ + each>( + table: ReadonlyArray, + ): ( + label: string, + fn: (...args: T) => void | Promise, + options?: number | TestOptions, + ) => void; + each( + table: ReadonlyArray, + ): ( + label: string, + fn: (arg: T) => void | Promise, + options?: number | TestOptions, + ) => void; }; /** * Describes a group of related tests. @@ -395,6 +414,25 @@ declare module "bun:test" { | ((done: (err?: unknown) => void) => void), options?: number | TestOptions, ) => void; + /** + * Returns a function that runs for each item in `table`. + * + * @param table Array of Arrays with the arguments that are passed into the test fn for each row. + */ + each>( + table: ReadonlyArray, + ): ( + label: string, + fn: (...args: T) => void | Promise, + options?: number | TestOptions, + ) => void; + each( + table: ReadonlyArray, + ): ( + label: string, + fn: (arg: T, done: (err?: unknown) => void) => void | Promise, + options?: number | TestOptions, + ) => void; }; /** * Runs a test. @@ -426,7 +464,7 @@ declare module "bun:test" { * @param actual the actual value */ export const expect: { - (actual: unknown): Expect; + (actual?: unknown): Expect; any: ( constructor: ((..._: any[]) => any) | { new (..._: any[]): any }, ) => Expect; @@ -468,6 +506,30 @@ declare module "bun:test" { * expect(Promise.reject("error")).rejects.toBe("error"); */ rejects: Expect; + /** + * Assertion which passes. + * + * @link https://jest-extended.jestcommunity.dev/docs/matchers/pass + * @example + * expect().pass(); + * expect().pass("message is optional"); + * expect().not.pass(); + * expect().not.pass("hi"); + * + * @param message the message to display if the test fails (optional) + */ + pass: (message?: string) => void; + /** + * Assertion which fails. + * + * @link https://jest-extended.jestcommunity.dev/docs/matchers/fail + * @example + * expect().fail(); + * expect().fail("message is optional"); + * expect().not.fail(); + * expect().not.fail("hi"); + */ + fail: (message?: string) => void; /** * Asserts that a value equals what is expected. * @@ -957,6 +1019,23 @@ declare module "bun:test" { * @param expected the expected substring */ toInclude(expected: string): void; + /** + * Asserts that a value includes a `string` {times} times. + * @param expected the expected substring + * @param times the number of times the substring should occur + */ + toIncludeRepeated(expected: string, times: number): void; + /** + * Checks whether a value satisfies a custom condition. + * @param {Function} predicate - The custom condition to be satisfied. It should be a function that takes a value as an argument (in this case the value from expect) and returns a boolean. + * @example + * expect(1).toSatisfy((val) => val > 0); + * expect("foo").toSatisfy((val) => val === "foo"); + * expect("bar").not.toSatisfy((val) => val === "bun"); + * @link https://vitest.dev/api/expect.html#tosatisfy + * @link https://jest-extended.jestcommunity.dev/docs/matchers/toSatisfy + */ + toSatisfy(predicate: (value: T) => boolean): void; /** * Asserts that a value starts with a `string`. * diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index efd8a91b685235..20f247d91c84e9 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -3179,6 +3179,11 @@ declare module "bun" { const plugin: BunRegisterPlugin; + /** + * Is the current global scope the main thread? + */ + const isMainThread: boolean; + interface Socket { /** * Write `data` to the socket diff --git a/packages/bun-types/diagnostics_channel.d.ts b/packages/bun-types/diagnostics_channel.d.ts new file mode 100644 index 00000000000000..afc63c922b3cf3 --- /dev/null +++ b/packages/bun-types/diagnostics_channel.d.ts @@ -0,0 +1,254 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since Bun v0.7.2 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "async_hooks"; + // type AsyncLocalStorage = import("async_hooks").AsyncLocalStorage; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since Bun v0.7.2 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since Bun v0.7.2 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since Bun v0.7.2 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since Bun v0.7.2 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe( + name: string | symbol, + onMessage: ChannelListener, + ): boolean; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since Bun v0.7.2 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since Bun v0.7.2 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since Bun v0.7.2 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since Bun v0.7.2 + * @deprecated Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since Bun v0.7.2 + * @deprecated Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + bindStore( + store: AsyncLocalStorage, + transform?: TransformCallback, + ): void; + unbindStore(store: AsyncLocalStorage): void; + runStores( + context: unknown, + fn: (...args: unknown[]) => unknown, + receiver?: unknown, + ...args: unknown[] + ): any; + } + type TransformCallback = (value: T) => unknown; + type TracingChannelSubscribers = { + start?: ChannelListener; + end?: ChannelListener; + asyncStart?: ChannelListener; + asyncEnd?: ChannelListener; + error?: ChannelListener; + }; + type TracingChannels = { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + }; + class TracingChannel implements TracingChannels { + readonly start: Channel; + readonly end: Channel; + readonly asyncStart: Channel; + readonly asyncEnd: Channel; + readonly error: Channel; + subscribe(subscribers: TracingChannelSubscribers): void; + unsubscribe(subscribers: TracingChannelSubscribers): boolean; + traceSync( + fn: (...values: any[]) => T, + context?: any, + thisArg?: any, + ...args: any[] + ): any; + tracePromise( + fn: (...values: any[]) => Promise, + context?: any, + thisArg?: any, + ...args: any[] + ): Promise; + traceCallback( + fn: (...values: any[]) => T, + position?: number, + context?: any, + thisArg?: any, + ...args: any[] + ): any; + } + function tracingChannel( + nameOrChannels: string | TracingChannels, + ): TracingChannel; +} + +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/packages/bun-types/globals.d.ts b/packages/bun-types/globals.d.ts index 885294b0d7541f..71403eb805e71f 100644 --- a/packages/bun-types/globals.d.ts +++ b/packages/bun-types/globals.d.ts @@ -2,7 +2,7 @@ * "blob" is not supported yet */ type BinaryType = "nodebuffer" | "arraybuffer" | "blob"; -type Transferable = ArrayBuffer; +type Transferable = ArrayBuffer | MessagePort; type MessageEventSource = undefined; type Encoding = "utf-8" | "windows-1252" | "utf-16"; type Platform = @@ -366,6 +366,179 @@ declare function structuredClone( options?: StructuredSerializeOptions, ): T; +declare var MessagePort: typeof import("worker_threads").MessagePort; +declare type MessagePort = import("worker_threads").MessagePort; +declare var MessageChannel: typeof import("worker_threads").MessageChannel; +declare type MessageChannel = import("worker_threads").MessageChannel; +declare var BroadcastChannel: typeof import("worker_threads").BroadcastChannel; +declare type BroadcastChannel = import("worker_threads").BroadcastChannel; + +interface AbstractWorkerEventMap { + error: ErrorEvent; +} + +interface WorkerEventMap extends AbstractWorkerEventMap { + message: MessageEvent; + messageerror: MessageEvent; + close: CloseEvent; + open: Event; +} + +interface AbstractWorker { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorker/error_event) */ + onerror: ((this: AbstractWorker, ev: ErrorEvent) => any) | null; + addEventListener( + type: K, + listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; +} + +/** + * Bun's Web Worker constructor supports some extra options on top of the API browsers have. + */ +interface WorkerOptions { + /** + * A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of + * the worker, which is mainly useful for debugging purposes. + */ + name?: string; + + /** + * Use less memory, but make the worker slower. + * + * Internally, this sets the heap size configuration in JavaScriptCore to be + * the small heap instead of the large heap. + */ + smol?: boolean; + + /** + * When `true`, the worker will keep the parent thread alive until the worker is terminated or `unref`'d. + * When `false`, the worker will not keep the parent thread alive. + * + * By default, this is `false`. + */ + ref?: boolean; + + /** + * In Bun, this does nothing. + */ + type?: string; + + /** + * List of arguments which would be stringified and appended to + * `Bun.argv` / `process.argv` in the worker. This is mostly similar to the `data` + * but the values will be available on the global `Bun.argv` as if they + * were passed as CLI options to the script. + */ + // argv?: any[] | undefined; + + /** If `true` and the first argument is a string, interpret the first argument to the constructor as a script that is executed once the worker is online. */ + // eval?: boolean | undefined; + + /** + * If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env. + */ + env?: + | Record + | typeof import("node:worker_threads")["SHARE_ENV"] + | undefined; + + /** + * In Bun, this does nothing. + */ + credentials?: string; + + /** + * @default true + */ + // trackUnmanagedFds?: boolean; + + // resourceLimits?: import("worker_threads").ResourceLimits; +} + +interface Worker extends EventTarget, AbstractWorker { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/message_event) */ + onmessage: ((this: Worker, ev: MessageEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/messageerror_event) */ + onmessageerror: ((this: Worker, ev: MessageEvent) => any) | null; + /** + * Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/postMessage) + */ + postMessage(message: any, transfer: Transferable[]): void; + postMessage(message: any, options?: StructuredSerializeOptions): void; + /** + * Aborts worker's associated global environment. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/terminate) + */ + terminate(): void; + addEventListener( + type: K, + listener: (this: Worker, ev: WorkerEventMap[K]) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: (this: Worker, ev: WorkerEventMap[K]) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; + + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default + * behavior). If the worker is `ref()`ed, calling `ref()` again has + * no effect. + * @since v10.5.0 + */ + ref(): void; + /** + * Calling `unref()` on a worker allows the thread to exit if this is the only + * active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect. + * @since v10.5.0 + */ + unref(): void; + + threadId: number; +} + +declare var Worker: { + prototype: Worker; + new (scriptURL: string | URL, options?: WorkerOptions): Worker; + /** + * This is the cloned value of the `data` property passed to `new Worker()` + * + * This is Bun's equivalent of `workerData` in Node.js. + */ + data: any; +}; + interface EncodeIntoResult { /** * The read Unicode code units of input. @@ -560,7 +733,7 @@ declare module "node:process" { interface BlobInterface { text(): Promise; arrayBuffer(): Promise; - json(): Promise; + json(): Promise; formData(): Promise; } @@ -699,14 +872,7 @@ declare var FormData: { new (): FormData; }; -declare class Blob implements BlobInterface { - /** - * Create a new [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - * - * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects - * @param `options` - An object containing properties to be added to the [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - */ - constructor(parts?: BlobPart[], options?: BlobPropertyBag); +declare interface Blob { /** * Create a new view **without 🚫 copying** the underlying data. * @@ -763,7 +929,7 @@ declare class Blob implements BlobInterface { * This first decodes the data from UTF-8, then parses it as JSON. * */ - json(): Promise; + json(): Promise; /** * Read the data from the blob as a {@link FormData} object. @@ -782,6 +948,16 @@ declare class Blob implements BlobInterface { type: string; readonly size: number; } +declare var Blob: { + prototype: Blob; + /** + * Create a new [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + * + * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects + * @param `options` - An object containing properties to be added to the [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + */ + new (parts?: BlobPart[], options?: BlobPropertyBag): Blob; +}; interface ResponseInit { headers?: HeadersInit; @@ -920,7 +1096,7 @@ declare class Response implements BlobInterface { * This first decodes the data from UTF-8, then parses it as JSON. * */ - json(): Promise; + json(): Promise; /** * Read the data from the Response as a Blob. @@ -1181,7 +1357,7 @@ declare class Request implements BlobInterface { * This first decodes the data from UTF-8, then parses it as JSON. * */ - json(): Promise; + json(): Promise; /** * Consume the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) body as a `Blob`. @@ -1468,24 +1644,6 @@ declare class ShadowRealm { evaluate(sourceText: string): any; } -interface Blob { - /** - * Read the contents of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) as a JSON object - * @warn in browsers, this function is only available for `Response` and `Request` - */ - json(): Promise; - /** - * Read the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) as a UTF-8 string - * @link https://developer.mozilla.org/en-US/docs/Web/API/Blob/text - */ - text(): Promise; - /** - * Read the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) as an ArrayBuffer object - * @link https://developer.mozilla.org/en-US/docs/Web/API/Blob/arrayBuffer - */ - arrayBuffer(): Promise; -} - declare var performance: { /** * Milliseconds since Bun.js started @@ -1891,6 +2049,8 @@ interface MessageEvent extends Event { readonly lastEventId: string; /** Returns the origin of the message, for server-sent events and cross-document messaging. */ readonly origin: string; + /** Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. */ + readonly ports: ReadonlyArray; readonly source: MessageEventSource; /** @deprecated */ initMessageEvent( @@ -3494,43 +3654,17 @@ declare module "*.txt" { export = text; } +declare module "*.toml" { + var contents: unknown; + export = contents; +} + interface EventSourceEventMap { error: Event; message: MessageEvent; open: Event; } -interface Worker extends EventTarget { - onerror: ((this: Worker, ev: ErrorEvent) => any) | null; - onmessage: ((this: Worker, ev: MessageEvent) => any) | null; - onmessageerror: ((this: Worker, ev: MessageEvent) => any) | null; - - addEventListener( - type: K, - listener: (this: Worker, ev: WorkerEventMap[K]) => any, - options?: boolean | AddEventListenerOptions, - ): void; - - removeEventListener( - type: K, - listener: (this: Worker, ev: WorkerEventMap[K]) => any, - options?: boolean | EventListenerOptions, - ): void; - - terminate(): void; - - postMessage(message: any, transfer?: Transferable[]): void; - - /** - * Keep the process alive until the worker is terminated or `unref`'d - */ - ref(): void; - /** - * Undo a previous `ref()` - */ - unref(): void; -} - /** * Post a message to the parent thread. * @@ -3538,44 +3672,6 @@ interface Worker extends EventTarget { */ declare function postMessage(message: any, transfer?: Transferable[]): void; -declare var Worker: { - prototype: Worker; - new (stringUrl: string | URL, options?: WorkerOptions): Worker; -}; - -interface WorkerOptions { - name?: string; - - /** - * Use less memory, but make the worker slower. - * - * Internally, this sets the heap size configuration in JavaScriptCore to be - * the small heap instead of the large heap. - */ - smol?: boolean; - - /** - * When `true`, the worker will keep the parent thread alive until the worker is terminated or `unref`'d. - * When `false`, the worker will not keep the parent thread alive. - * - * By default, this is `false`. - */ - ref?: boolean; - - /** - * Does nothing in Bun - */ - type?: string -} - -interface WorkerEventMap { - message: MessageEvent; - messageerror: MessageEvent; - error: ErrorEvent; - open: Event; - close: Event; -} - interface EventSource extends EventTarget { onerror: ((this: EventSource, ev: ErrorEvent) => any) | null; onmessage: ((this: EventSource, ev: MessageEvent) => any) | null; @@ -3648,3 +3744,31 @@ declare var EventSource: { readonly CONNECTING: number; readonly OPEN: number; }; + +interface PromiseConstructor { + /** + * Create a deferred promise, with exposed `resolve` and `reject` methods which can be called + * separately. + * + * This is useful when you want to return a Promise and have code outside the Promise + * resolve or reject it. + * + * ## Example + * ```ts + * const { promise, resolve, reject } = Promise.withResolvers(); + * + * setTimeout(() => { + * resolve("Hello world!"); + * }, 1000); + * + * await promise; // "Hello world!" + * ``` + * + * `Promise.withResolvers()` is a [stage3 proposal](https://github.com/tc39/proposal-promise-with-resolvers). + */ + withResolvers(): { + promise: Promise; + resolve: (value?: T | PromiseLike) => void; + reject: (reason?: any) => void; + }; +} diff --git a/packages/bun-types/index.d.ts b/packages/bun-types/index.d.ts index 981a4dbc72eb6a..e5f866c2102fde 100644 --- a/packages/bun-types/index.d.ts +++ b/packages/bun-types/index.d.ts @@ -6,6 +6,7 @@ /// /// /// +/// /// /// /// @@ -13,6 +14,7 @@ /// /// /// +/// /// /// /// @@ -42,4 +44,7 @@ /// /// /// +/// +/// +/// /// diff --git a/packages/bun-types/perf_hooks.d.ts b/packages/bun-types/perf_hooks.d.ts index 792223e6b1f550..587602a2652b35 100644 --- a/packages/bun-types/perf_hooks.d.ts +++ b/packages/bun-types/perf_hooks.d.ts @@ -145,16 +145,19 @@ declare module "perf_hooks" { // */ // readonly v8Start: number; // } - // interface EventLoopUtilization { - // idle: number; - // active: number; - // utilization: number; - // } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } // /** // * @param util1 The result of a previous call to eventLoopUtilization() // * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 // */ - // type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; + type EventLoopUtilityFunction = ( + util1?: EventLoopUtilization, + util2?: EventLoopUtilization, + ) => EventLoopUtilization; // interface MarkOptions { // /** // * Additional optional detail to include with the mark. diff --git a/packages/bun-types/tests/broadcast.test-d.ts b/packages/bun-types/tests/broadcast.test-d.ts new file mode 100644 index 00000000000000..ea5f8cb054eec0 --- /dev/null +++ b/packages/bun-types/tests/broadcast.test-d.ts @@ -0,0 +1,11 @@ +const channel = new BroadcastChannel("my-channel"); +const message = { hello: "world" }; + +channel.onmessage = event => { + console.log(event.data); // { hello: "world" } +}; +channel.postMessage(message); + +const error = new Error("hello world"); +const clone = structuredClone(error); +console.log(clone.message); // "hello world" diff --git a/packages/bun-types/tests/diag.test-d.ts b/packages/bun-types/tests/diag.test-d.ts new file mode 100644 index 00000000000000..35f41ce050664d --- /dev/null +++ b/packages/bun-types/tests/diag.test-d.ts @@ -0,0 +1,12 @@ +import diagnostics_channel from "diagnostics_channel"; + +// Create a channel object +const channel = diagnostics_channel.channel("my-channel"); + +// Subscribe to the channel +channel.subscribe((message, name) => { + console.log("Received message:", message); +}); + +// Publish a message to the channel +channel.publish({ some: "data" }); diff --git a/packages/bun-types/tests/fs.test-d.ts b/packages/bun-types/tests/fs.test-d.ts index 3acfafa76b616a..a752889df82024 100644 --- a/packages/bun-types/tests/fs.test-d.ts +++ b/packages/bun-types/tests/fs.test-d.ts @@ -13,3 +13,5 @@ watch(".", (eventType, filename) => { console.log(`filename = ${filename}`); } }); + +Bun.file("sdf").exists(); diff --git a/packages/bun-types/tests/globals.test-d.ts b/packages/bun-types/tests/globals.test-d.ts index 64b37be139716f..a5441f20120e09 100644 --- a/packages/bun-types/tests/globals.test-d.ts +++ b/packages/bun-types/tests/globals.test-d.ts @@ -93,3 +93,6 @@ new Request("", { method: "POST" }); Bun.sleepSync(1); // sleep for 1 ms (not recommended) await Bun.sleep(1); // sleep for 1 ms (recommended) + +Blob; +WebSocket; diff --git a/packages/bun-types/tests/toml.test-d.ts b/packages/bun-types/tests/toml.test-d.ts new file mode 100644 index 00000000000000..eaf20e7829b80b --- /dev/null +++ b/packages/bun-types/tests/toml.test-d.ts @@ -0,0 +1,4 @@ +import { expectType } from "tsd"; +import data from "../../../bunfig.toml"; + +expectType(data); diff --git a/packages/bun-types/tests/worker.test-d.ts b/packages/bun-types/tests/worker.test-d.ts index 604e0a501c782d..dc457ccaa225de 100644 --- a/packages/bun-types/tests/worker.test-d.ts +++ b/packages/bun-types/tests/worker.test-d.ts @@ -1,14 +1,29 @@ -const worker = new Worker("./worker.ts"); -worker.addEventListener("message", (event: MessageEvent) => { - console.log("Message from worker:", event.data); +import { Worker as NodeWorker } from "node:worker_threads"; +import * as tsd from "tsd"; + +const webWorker = new Worker("./worker.js"); + +webWorker.addEventListener("message", event => { + tsd.expectType(event); +}); +webWorker.addEventListener("error", event => { + tsd.expectType(event); +}); +webWorker.addEventListener("messageerror", event => { + tsd.expectType(event); +}); + +const nodeWorker = new NodeWorker("./worker.ts"); +nodeWorker.on("message", event => { + console.log("Message from worker:", event); }); -worker.postMessage("Hello from main thread!"); +nodeWorker.postMessage("Hello from main thread!"); const workerURL = new URL("worker.ts", import.meta.url).href; const _worker2 = new Worker(workerURL); -worker.postMessage("hello"); -worker.onmessage = event => { +nodeWorker.postMessage("hello"); +webWorker.onmessage = event => { console.log(event.data); }; @@ -16,15 +31,20 @@ worker.onmessage = event => { postMessage({ hello: "world" }); // On the main thread -worker.postMessage({ hello: "world" }); +nodeWorker.postMessage({ hello: "world" }); // ...some time later -worker.terminate(); +nodeWorker.terminate(); // Bun.pathToFileURL const _worker3 = new Worker(new URL("worker.ts", import.meta.url).href, { ref: true, smol: true, + credentials: "", + name: "a name", + env: { + envValue: "hello", + }, }); -export { worker, _worker2, _worker3 }; +export { nodeWorker as worker, _worker2, _worker3 }; diff --git a/packages/bun-types/tests/ws.test-d.ts b/packages/bun-types/tests/ws.test-d.ts new file mode 100644 index 00000000000000..fdc4072af2403f --- /dev/null +++ b/packages/bun-types/tests/ws.test-d.ts @@ -0,0 +1,11 @@ +import { WebSocket, WebSocketServer } from "ws"; + +const ws = new WebSocket("ws://www.host.com/path"); + +ws.send("asdf"); + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: false, +}); +wss; diff --git a/packages/bun-types/tsconfig.json b/packages/bun-types/tsconfig.json index e346b31b43a3ab..ad946c2e0a0ec9 100644 --- a/packages/bun-types/tsconfig.json +++ b/packages/bun-types/tsconfig.json @@ -1,8 +1,6 @@ { "compilerOptions": { - "lib": [ - "ESNext" - ], + "lib": ["ESNext"], "skipLibCheck": false, "strict": true, "target": "esnext", @@ -10,7 +8,8 @@ "moduleResolution": "node", "allowSyntheticDefaultImports": true, "disableSolutionSearching": true, - "noUnusedLocals": true + "noUnusedLocals": true, + "outDir": "build" }, "exclude": [ "dist", diff --git a/packages/bun-types/node-vm.d.ts b/packages/bun-types/vm.d.ts similarity index 100% rename from packages/bun-types/node-vm.d.ts rename to packages/bun-types/vm.d.ts diff --git a/packages/bun-types/worker_threads.d.ts b/packages/bun-types/worker_threads.d.ts new file mode 100644 index 00000000000000..ddc59fec54f208 --- /dev/null +++ b/packages/bun-types/worker_threads.d.ts @@ -0,0 +1,748 @@ +/** + * The `worker_threads` module enables the use of threads that execute JavaScript + * in parallel. To access it: + * + * ```js + * const worker = require('worker_threads'); + * ``` + * + * Workers (threads) are useful for performing CPU-intensive JavaScript operations. + * They do not help much with I/O-intensive work. The Node.js built-in + * asynchronous I/O operations are more efficient than Workers can be. + * + * Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do + * so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer`instances. + * + * ```js + * const { + * Worker, isMainThread, parentPort, workerData + * } = require('worker_threads'); + * + * if (isMainThread) { + * module.exports = function parseJSAsync(script) { + * return new Promise((resolve, reject) => { + * const worker = new Worker(__filename, { + * workerData: script + * }); + * worker.on('message', resolve); + * worker.on('error', reject); + * worker.on('exit', (code) => { + * if (code !== 0) + * reject(new Error(`Worker stopped with exit code ${code}`)); + * }); + * }); + * }; + * } else { + * const { parse } = require('some-js-parsing-library'); + * const script = workerData; + * parentPort.postMessage(parse(script)); + * } + * ``` + * + * The above example spawns a Worker thread for each `parseJSAsync()` call. In + * practice, use a pool of Workers for these kinds of tasks. Otherwise, the + * overhead of creating Workers would likely exceed their benefit. + * + * When implementing a worker pool, use the `AsyncResource` API to inform + * diagnostic tools (e.g. to provide asynchronous stack traces) about the + * correlation between tasks and their outcomes. See `"Using AsyncResource for a Worker thread pool"` in the `async_hooks` documentation for an example implementation. + * + * Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options, + * specifically `argv` and `execArgv` options. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/worker_threads.js) + */ +declare module "worker_threads" { + // import { Blob } from "node:buffer"; + import { Readable, Writable } from "node:stream"; + import { Context } from "node:vm"; + import { EventEmitter } from "node:events"; + import { EventLoopUtilityFunction } from "node:perf_hooks"; + // import { FileHandle } from "node:fs/promises"; + // import { Readable, Writable } from "node:stream"; + import { URL } from "node:url"; + // import { X509Certificate } from "node:crypto"; + const isMainThread: boolean; + const parentPort: null | MessagePort; + const resourceLimits: ResourceLimits; + const SHARE_ENV: unique symbol; + const threadId: number; + const workerData: any; + + interface WorkerPerformance { + eventLoopUtilization: EventLoopUtilityFunction; + } + type TransferListItem = + | ArrayBuffer + | MessagePort + // | FileHandle + // | X509Certificate + | Blob; + /** + * Instances of the `worker.MessagePort` class represent one end of an + * asynchronous, two-way communications channel. It can be used to transfer + * structured data, memory regions and other `MessagePort`s between different `Worker` s. + * + * This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s. + * @since v10.5.0 + */ + class MessagePort extends EventEmitter { + /** + * Disables further sending of messages on either side of the connection. + * This method can be called when no further communication will happen over this`MessagePort`. + * + * The `'close' event` is emitted on both `MessagePort` instances that + * are part of the channel. + * @since v10.5.0 + */ + close(): void; + /** + * Sends a JavaScript value to the receiving side of this channel.`value` is transferred in a way which is compatible with + * the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). + * + * In particular, the significant differences to `JSON` are: + * + * * `value` may contain circular references. + * * `value` may contain instances of builtin JS types such as `RegExp`s,`BigInt`s, `Map`s, `Set`s, etc. + * * `value` may contain typed arrays, both using `ArrayBuffer`s + * and `SharedArrayBuffer`s. + * * `value` may contain [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) instances. + * * `value` may not contain native (C++-backed) objects other than: + * + * ```js + * const { MessageChannel } = require('worker_threads'); + * const { port1, port2 } = new MessageChannel(); + * + * port1.on('message', (message) => console.log(message)); + * + * const circularData = {}; + * circularData.foo = circularData; + * // Prints: { foo: [Circular] } + * port2.postMessage(circularData); + * ``` + * + * `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort` and `FileHandle` objects. + * After transferring, they are not usable on the sending side of the channel + * anymore (even if they are not contained in `value`). Unlike with `child processes`, transferring handles such as network sockets is currently + * not supported. + * + * If `value` contains [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances, those are accessible + * from either thread. They cannot be listed in `transferList`. + * + * `value` may still contain `ArrayBuffer` instances that are not in`transferList`; in that case, the underlying memory is copied rather than moved. + * + * ```js + * const { MessageChannel } = require('worker_threads'); + * const { port1, port2 } = new MessageChannel(); + * + * port1.on('message', (message) => console.log(message)); + * + * const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]); + * // This posts a copy of `uint8Array`: + * port2.postMessage(uint8Array); + * // This does not copy data, but renders `uint8Array` unusable: + * port2.postMessage(uint8Array, [ uint8Array.buffer ]); + * + * // The memory for the `sharedUint8Array` is accessible from both the + * // original and the copy received by `.on('message')`: + * const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4)); + * port2.postMessage(sharedUint8Array); + * + * // This transfers a freshly created message port to the receiver. + * // This can be used, for example, to create communication channels between + * // multiple `Worker` threads that are children of the same parent thread. + * const otherChannel = new MessageChannel(); + * port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]); + * ``` + * + * The message object is cloned immediately, and can be modified after + * posting without having side effects. + * + * For more information on the serialization and deserialization mechanisms + * behind this API, see the `serialization API of the v8 module`. + * @since v10.5.0 + */ + postMessage( + value: any, + transferList?: ReadonlyArray, + ): void; + /** + * Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does _not_ let the program exit if it's the only active handle left (the default + * behavior). If the port is `ref()`ed, calling `ref()` again has no effect. + * + * If listeners are attached or removed using `.on('message')`, the port + * is `ref()`ed and `unref()`ed automatically depending on whether + * listeners for the event exist. + * @since v10.5.0 + */ + ref(): void; + /** + * Calling `unref()` on a port allows the thread to exit if this is the only + * active handle in the event system. If the port is already `unref()`ed calling`unref()` again has no effect. + * + * If listeners are attached or removed using `.on('message')`, the port is`ref()`ed and `unref()`ed automatically depending on whether + * listeners for the event exist. + * @since v10.5.0 + */ + unref(): void; + /** + * Starts receiving messages on this `MessagePort`. When using this port + * as an event emitter, this is called automatically once `'message'`listeners are attached. + * + * This method exists for parity with the Web `MessagePort` API. In Node.js, + * it is only useful for ignoring messages when no event listener is present. + * Node.js also diverges in its handling of `.onmessage`. Setting it + * automatically calls `.start()`, but unsetting it lets messages queue up + * until a new handler is set or the port is discarded. + * @since v10.5.0 + */ + start(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "messageerror", listener: (error: Error) => void): this; + addListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: "messageerror", error: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "messageerror", listener: (error: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "messageerror", listener: (error: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener( + event: "messageerror", + listener: (error: Error) => void, + ): this; + prependListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener( + event: "messageerror", + listener: (error: Error) => void, + ): this; + prependOnceListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener( + event: "messageerror", + listener: (error: Error) => void, + ): this; + removeListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "messageerror", listener: (error: Error) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface WorkerOptions { + /** + * A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of + * the worker, which is mainly useful for debugging purposes. + */ + name?: string; + + /** + * Use less memory, but make the worker slower. + * + * Internally, this sets the heap size configuration in JavaScriptCore to be + * the small heap instead of the large heap. + */ + smol?: boolean; + + /** + * When `true`, the worker will keep the parent thread alive until the worker is terminated or `unref`'d. + * When `false`, the worker will not keep the parent thread alive. + * + * By default, this is `false`. + */ + ref?: boolean; + + /** + * In Bun, this does nothing. + */ + type?: string; + + /** + * List of arguments which would be stringified and appended to + * `Bun.argv` / `process.argv` in the worker. This is mostly similar to the `data` + * but the values will be available on the global `Bun.argv` as if they + * were passed as CLI options to the script. + */ + // argv?: any[] | undefined; + + /** If `true` and the first argument is a string, interpret the first argument to the constructor as a script that is executed once the worker is online. */ + // eval?: boolean | undefined; + + /** + * If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env. + */ + env?: + | Record + | typeof import("node:worker_threads")["SHARE_ENV"] + | undefined; + + /** + * In Bun, this does nothing. + */ + credentials?: string; + + /** + * @default true + */ + // trackUnmanagedFds?: boolean; + + workerData?: any; + + /** + * An array of objects that are transferred rather than cloned when being passed between threads. + */ + transferList?: import("worker_threads").TransferListItem[]; + + // resourceLimits?: import("worker_threads").ResourceLimits; + // stdin?: boolean | undefined; + // stdout?: boolean | undefined; + // stderr?: boolean | undefined; + // execArgv?: string[] | undefined; + } + interface ResourceLimits { + /** + * The maximum size of a heap space for recently created objects. + */ + maxYoungGenerationSizeMb?: number | undefined; + /** + * The maximum size of the main heap in MB. + */ + maxOldGenerationSizeMb?: number | undefined; + /** + * The size of a pre-allocated memory range used for generated code. + */ + codeRangeSizeMb?: number | undefined; + /** + * The default maximum stack size for the thread. Small values may lead to unusable Worker instances. + * @default 4 + */ + stackSizeMb?: number | undefined; + } + /** + * The `Worker` class represents an independent JavaScript execution thread. + * Most Node.js APIs are available inside of it. + * + * Notable differences inside a Worker environment are: + * + * * The `process.stdin`, `process.stdout` and `process.stderr` may be redirected by the parent thread. + * * The `require('worker_threads').isMainThread` property is set to `false`. + * * The `require('worker_threads').parentPort` message port is available. + * * `process.exit()` does not stop the whole program, just the single thread, + * and `process.abort()` is not available. + * * `process.chdir()` and `process` methods that set group or user ids + * are not available. + * * `process.env` is a copy of the parent thread's environment variables, + * unless otherwise specified. Changes to one copy are not visible in other + * threads, and are not visible to native add-ons (unless `worker.SHARE_ENV` is passed as the `env` option to the `Worker` constructor). + * * `process.title` cannot be modified. + * * Signals are not delivered through `process.on('...')`. + * * Execution may stop at any point as a result of `worker.terminate()` being invoked. + * * IPC channels from parent processes are not accessible. + * * The `trace_events` module is not supported. + * * Native add-ons can only be loaded from multiple threads if they fulfill `certain conditions`. + * + * Creating `Worker` instances inside of other `Worker`s is possible. + * + * Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `cluster module`, two-way communication can be + * achieved through inter-thread message passing. Internally, a `Worker` has a + * built-in pair of `MessagePort` s that are already associated with each other + * when the `Worker` is created. While the `MessagePort` object on the parent side + * is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event + * on the `Worker` object for the parent thread. + * + * To create custom messaging channels (which is encouraged over using the default + * global channel because it facilitates separation of concerns), users can create + * a `MessageChannel` object on either thread and pass one of the`MessagePort`s on that `MessageChannel` to the other thread through a + * pre-existing channel, such as the global one. + * + * See `port.postMessage()` for more information on how messages are passed, + * and what kind of JavaScript values can be successfully transported through + * the thread barrier. + * + * ```js + * const assert = require('assert'); + * const { + * Worker, MessageChannel, MessagePort, isMainThread, parentPort + * } = require('worker_threads'); + * if (isMainThread) { + * const worker = new Worker(__filename); + * const subChannel = new MessageChannel(); + * worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); + * subChannel.port2.on('message', (value) => { + * console.log('received:', value); + * }); + * } else { + * parentPort.once('message', (value) => { + * assert(value.hereIsYourPort instanceof MessagePort); + * value.hereIsYourPort.postMessage('the worker is sending this'); + * value.hereIsYourPort.close(); + * }); + * } + * ``` + * @since v10.5.0 + */ + class Worker extends EventEmitter { + /** + * If `stdin: true` was passed to the `Worker` constructor, this is a + * writable stream. The data written to this stream will be made available in + * the worker thread as `process.stdin`. + * @since v10.5.0 + */ + readonly stdin: Writable | null; + /** + * This is a readable stream which contains data written to `process.stdout` inside the worker thread. If `stdout: true` was not passed to the `Worker` constructor, then data is piped to the + * parent thread's `process.stdout` stream. + * @since v10.5.0 + */ + readonly stdout: Readable; + /** + * This is a readable stream which contains data written to `process.stderr` inside the worker thread. If `stderr: true` was not passed to the `Worker` constructor, then data is piped to the + * parent thread's `process.stderr` stream. + * @since v10.5.0 + */ + readonly stderr: Readable; + /** + * An integer identifier for the referenced thread. Inside the worker thread, + * it is available as `require('node:worker_threads').threadId`. + * This value is unique for each `Worker` instance inside a single process. + * @since v10.5.0 + */ + readonly threadId: number; + /** + * Provides the set of JS engine resource constraints for this Worker thread. + * If the `resourceLimits` option was passed to the `Worker` constructor, + * this matches its values. + * + * If the worker has stopped, the return value is an empty object. + * @since v13.2.0, v12.16.0 + */ + readonly resourceLimits?: ResourceLimits | undefined; + /** + * An object that can be used to query performance information from a worker + * instance. Similar to `perf_hooks.performance`. + * @since v15.1.0, v14.17.0, v12.22.0 + */ + readonly performance: WorkerPerformance; + /** + * @param filename The path to the Worker’s main script or module. + * Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../, + * or a WHATWG URL object using file: protocol. If options.eval is true, this is a string containing JavaScript code rather than a path. + */ + constructor(filename: string | URL, options?: WorkerOptions); + /** + * Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`. + * See `port.postMessage()` for more details. + * @since v10.5.0 + */ + postMessage( + value: any, + transferList?: ReadonlyArray, + ): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default + * behavior). If the worker is `ref()`ed, calling `ref()` again has + * no effect. + * @since v10.5.0 + */ + ref(): void; + /** + * Calling `unref()` on a worker allows the thread to exit if this is the only + * active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect. + * @since v10.5.0 + */ + unref(): void; + /** + * Stop all JavaScript execution in the worker thread as soon as possible. + * Returns a Promise for the exit code that is fulfilled when the `'exit' event` is emitted. + * @since v10.5.0 + */ + terminate(): Promise; + /** + * Returns a readable stream for a V8 snapshot of the current state of the Worker. + * See `v8.getHeapSnapshot()` for more details. + * + * If the Worker thread is no longer running, which may occur before the `'exit' event` is emitted, the returned `Promise` is rejected + * immediately with an `ERR_WORKER_NOT_RUNNING` error. + * @since v13.9.0, v12.17.0 + * @return A promise for a Readable Stream containing a V8 heap snapshot + */ + getHeapSnapshot(): Promise; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "messageerror", listener: (error: Error) => void): this; + addListener(event: "online", listener: () => void): this; + addListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + emit(event: "error", err: Error): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "messageerror", error: Error): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "messageerror", listener: (error: Error) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "messageerror", listener: (error: Error) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener( + event: "messageerror", + listener: (error: Error) => void, + ): this; + prependListener(event: "online", listener: () => void): this; + prependListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (exitCode: number) => void, + ): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener( + event: "messageerror", + listener: (error: Error) => void, + ): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener( + event: "messageerror", + listener: (error: Error) => void, + ): this; + removeListener(event: "online", listener: () => void): this; + removeListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + off(event: "error", listener: (err: Error) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "messageerror", listener: (error: Error) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface BroadcastChannelEventMap { + message: MessageEvent; + messageerror: MessageEvent; + } + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel) */ + interface BroadcastChannel extends EventTarget { + /** + * Returns the channel name (as passed to the constructor). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/name) + */ + readonly name: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/message_event) */ + onmessage: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/messageerror_event) */ + onmessageerror: ((this: BroadcastChannel, ev: MessageEvent) => any) | null; + /** + * Closes the BroadcastChannel object, opening it up to garbage collection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/close) + */ + close(): void; + /** + * Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/BroadcastChannel/postMessage) + */ + postMessage(message: any): void; + addEventListener( + type: K, + listener: ( + this: BroadcastChannel, + ev: BroadcastChannelEventMap[K], + ) => any, + options?: boolean | AddEventListenerOptions, + ): void; + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ): void; + removeEventListener( + type: K, + listener: ( + this: BroadcastChannel, + ev: BroadcastChannelEventMap[K], + ) => any, + options?: boolean | EventListenerOptions, + ): void; + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions, + ): void; + + /** + * Keep the process alive until the BroadcastChannel is closed or `unref`'d. + * BroadcastChannel is `ref`'d by default. + */ + ref(): void; + /** + * Undo a previous `ref()` + */ + unref(): void; + } + + var BroadcastChannel: { + prototype: BroadcastChannel; + new (name: string): BroadcastChannel; + }; + + function markAsUntransferable(object: object): void; + /** + * Transfer a `MessagePort` to a different `vm` Context. The original `port`object is rendered unusable, and the returned `MessagePort` instance + * takes its place. + * + * The returned `MessagePort` is an object in the target context and + * inherits from its global `Object` class. Objects passed to the [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) listener are also created in the + * target context + * and inherit from its global `Object` class. + * + * However, the created `MessagePort` no longer inherits from [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget), and only + * [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) can be used to receive + * events using it. + * @since v11.13.0 + * @param port The message port to transfer. + * @param contextifiedSandbox A `contextified` object as returned by the `vm.createContext()` method. + */ + function moveMessagePortToContext( + port: MessagePort, + contextifiedSandbox: Context, + ): MessagePort; + /** + * Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property + * that contains the message payload, corresponding to the oldest message in the`MessagePort`’s queue. + * + * ```js + * const { MessageChannel, receiveMessageOnPort } = require('worker_threads'); + * const { port1, port2 } = new MessageChannel(); + * port1.postMessage({ hello: 'world' }); + * + * console.log(receiveMessageOnPort(port2)); + * // Prints: { message: { hello: 'world' } } + * console.log(receiveMessageOnPort(port2)); + * // Prints: undefined + * ``` + * + * When this function is used, no `'message'` event is emitted and the`onmessage` listener is not invoked. + * @since v12.3.0 + */ + function receiveMessageOnPort(port: MessagePort): + | { + message: any; + } + | undefined; + type Serializable = string | object | number | boolean | bigint; + /** + * Within a worker thread, `worker.getEnvironmentData()` returns a clone + * of data passed to the spawning thread's `worker.setEnvironmentData()`. + * Every new `Worker` receives its own copy of the environment data + * automatically. + * + * ```js + * const { + * Worker, + * isMainThread, + * setEnvironmentData, + * getEnvironmentData, + * } = require('worker_threads'); + * + * if (isMainThread) { + * setEnvironmentData('Hello', 'World!'); + * const worker = new Worker(__filename); + * } else { + * console.log(getEnvironmentData('Hello')); // Prints 'World!'. + * } + * ``` + * @since v15.12.0, v14.18.0 + * @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. + */ + function getEnvironmentData(key: Serializable): Serializable; + /** + * The `worker.setEnvironmentData()` API sets the content of`worker.getEnvironmentData()` in the current thread and all new `Worker`instances spawned from the current context. + * @since v15.12.0, v14.18.0 + * @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key. + * @param value Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value + * for the `key` will be deleted. + */ + function setEnvironmentData(key: Serializable, value: Serializable): void; + + /** + * This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) + */ + interface MessageChannel { + /** + * Returns the first MessagePort object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) + */ + readonly port1: MessagePort; + /** + * Returns the second MessagePort object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) + */ + readonly port2: MessagePort; + } + + var MessageChannel: { + prototype: MessageChannel; + new (): MessageChannel; + }; + + interface MessagePortEventMap { + message: MessageEvent; + messageerror: MessageEvent; + } +} +declare module "node:worker_threads" { + export * from "worker_threads"; +} diff --git a/packages/bun-types/ws.d.ts b/packages/bun-types/ws.d.ts new file mode 100644 index 00000000000000..a14f87edd6e16d --- /dev/null +++ b/packages/bun-types/ws.d.ts @@ -0,0 +1,222 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since Bun v0.7.2 + * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js) + */ +declare module "ws" { + import { + IncomingMessage, + OutgoingHttpHeaders, + Server as HTTPServer, + } from "http"; + import { Duplex, EventEmitter } from "stream"; + // import {Server as HTTPServer} from "http"; + import { Server as HTTPSServer } from "https"; + var WebSocket: typeof global.WebSocket; + interface WebSocket extends globalThis.WebSocket {} + + type VerifyClientCallbackSync< + Request extends IncomingMessage = IncomingMessage, + > = (info: { origin: string; secure: boolean; req: Request }) => boolean; + type VerifyClientCallbackAsync< + Request extends IncomingMessage = IncomingMessage, + > = ( + info: { origin: string; secure: boolean; req: Request }, + callback: ( + res: boolean, + code?: number, + message?: string, + headers?: OutgoingHttpHeaders, + ) => void, + ) => void; + + interface WebSocketServerOptions< + U extends typeof WebSocket = typeof WebSocket, + V extends typeof IncomingMessage = typeof IncomingMessage, + > { + host?: string | undefined; + port?: number | undefined; + backlog?: number | undefined; + server?: HTTPServer | HTTPSServer | undefined; + verifyClient?: + | VerifyClientCallbackAsync> + | VerifyClientCallbackSync> + | undefined; + handleProtocols?: ( + protocols: Set, + request: InstanceType, + ) => string | false; + path?: string | undefined; + noServer?: boolean | undefined; + clientTracking?: boolean | undefined; + perMessageDeflate?: boolean; // | PerMessageDeflateOptions | undefined; + // maxPayload?: number | undefined; + // skipUTF8Validation?: boolean | undefined; + WebSocket?: U | undefined; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + // WebSocket Server + class WebSocketServer< + T extends typeof WebSocket = typeof WebSocket, + U extends typeof IncomingMessage = typeof IncomingMessage, + > extends EventEmitter { + options: WebSocketServerOptions; + path: string; + clients: Set>; + + constructor(options?: WebSocketServerOptions, callback?: () => void); + + address(): AddressInfo | string; + close(cb?: (err?: Error) => void): void; + handleUpgrade( + request: InstanceType, + socket: Duplex, + upgradeHead: Buffer, + callback: (client: InstanceType, request: InstanceType) => void, + ): void; + shouldHandle(request: InstanceType): boolean | Promise; + + // Events + on( + event: "connection", + cb: ( + this: WebSocketServer, + socket: InstanceType, + request: InstanceType, + ) => void, + ): this; + on( + event: "error", + cb: (this: WebSocketServer, error: Error) => void, + ): this; + on( + event: "headers", + cb: ( + this: WebSocketServer, + headers: string[], + request: InstanceType, + ) => void, + ): this; + on( + event: "close" | "listening", + cb: (this: WebSocketServer) => void, + ): this; + on( + event: string | symbol, + listener: (this: WebSocketServer, ...args: any[]) => void, + ): this; + + once( + event: "connection", + cb: ( + this: WebSocketServer, + socket: InstanceType, + request: InstanceType, + ) => void, + ): this; + once( + event: "error", + cb: (this: WebSocketServer, error: Error) => void, + ): this; + once( + event: "headers", + cb: ( + this: WebSocketServer, + headers: string[], + request: InstanceType, + ) => void, + ): this; + once( + event: "close" | "listening", + cb: (this: WebSocketServer) => void, + ): this; + once( + event: string | symbol, + listener: (this: WebSocketServer, ...args: any[]) => void, + ): this; + + off( + event: "connection", + cb: ( + this: WebSocketServer, + socket: InstanceType, + request: InstanceType, + ) => void, + ): this; + off( + event: "error", + cb: (this: WebSocketServer, error: Error) => void, + ): this; + off( + event: "headers", + cb: ( + this: WebSocketServer, + headers: string[], + request: InstanceType, + ) => void, + ): this; + off( + event: "close" | "listening", + cb: (this: WebSocketServer) => void, + ): this; + off( + event: string | symbol, + listener: (this: WebSocketServer, ...args: any[]) => void, + ): this; + + addListener( + event: "connection", + cb: (client: InstanceType, request: InstanceType) => void, + ): this; + addListener(event: "error", cb: (err: Error) => void): this; + addListener( + event: "headers", + cb: (headers: string[], request: InstanceType) => void, + ): this; + addListener(event: "close" | "listening", cb: () => void): this; + addListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + + removeListener( + event: "connection", + cb: (client: InstanceType, request: InstanceType) => void, + ): this; + removeListener(event: "error", cb: (err: Error) => void): this; + removeListener( + event: "headers", + cb: (headers: string[], request: InstanceType) => void, + ): this; + removeListener(event: "close" | "listening", cb: () => void): this; + removeListener( + event: string | symbol, + listener: (...args: any[]) => void, + ): this; + } +} diff --git a/packages/bun-wasm/index.ts b/packages/bun-wasm/index.ts index b72400661a9f6e..10a7b3aa4047d9 100644 --- a/packages/bun-wasm/index.ts +++ b/packages/bun-wasm/index.ts @@ -1,11 +1,14 @@ // @ts-nocheck import { ByteBuffer } from "peechy/bb"; import { + Loader as BunLoader, + TestKind, + decodeGetTestsResponse, decodeScanResult, decodeTransformResponse, + encodeGetTestsRequest, encodeScan, encodeTransform, - Loader as BunLoader, type ScanResult, type TransformResponse, } from "./schema"; @@ -15,9 +18,13 @@ export enum Loader { tsx = BunLoader.tsx, ts = BunLoader.ts, } - +const testKindMap = { + [TestKind.describe_fn]: "describe", + [TestKind.test_fn]: "test", +}; +const capturedErrors = []; +let captureErrors = false; export type { ScanResult, TransformResponse }; - function normalizeLoader(file_name: string, loader?: Loader): BunLoader { return ( (loader @@ -82,12 +89,22 @@ var scratch2: Uint8Array; const env = { console_log(slice: number) { + const text = Bun._wasmPtrLenToString(slice); + if (captureErrors) { + capturedErrors.push(text); + return; + } //@ts-ignore - console.log(Bun._wasmPtrLenToString(slice)); + console.log(text); }, console_error(slice: number) { //@ts-ignore - console.error(Bun._wasmPtrLenToString(slice)); + const text = Bun._wasmPtrLenToString(slice); + if (captureErrors) { + capturedErrors.push(text); + return; + } + console.error(text); }, console_warn(slice: number) { //@ts-ignore @@ -148,7 +165,6 @@ const env = { }, emscripten_notify_memory_growth() {}, }; - export class Bun { private static has_initialized = false; // @ts-ignore-line @@ -179,63 +195,115 @@ export class Bun { return Bun._decoder.decode(region); } - static async init(url, fetch = globalThis.fetch) { - // globalThis.sucraseTransform = sucraseTransform; + static async init(url, heapSize = 64_000_000, fetch = globalThis.fetch) { scratch = new Uint8Array(8096); if (Bun.has_initialized) { return; } - - if (globalThis?.WebAssembly?.instantiateStreaming) { - Bun.wasm_source = await globalThis.WebAssembly.instantiateStreaming( - fetch(url), - { env: env, wasi_snapshot_preview1: Wasi }, - ); - } else if (typeof window !== "undefined") { - const resp = await fetch(url); - Bun.wasm_source = await globalThis.WebAssembly.instantiate( - await resp.arrayBuffer(), - { + if (typeof process === "undefined") { + if (globalThis?.WebAssembly?.instantiateStreaming) { + Bun.wasm_source = await globalThis.WebAssembly.instantiateStreaming(fetch(url), { env: env, wasi_snapshot_preview1: Wasi, - }, - ); - // is it node? + }); + } else if (typeof window !== "undefined") { + const resp = await fetch(url); + Bun.wasm_source = await globalThis.WebAssembly.instantiate(await resp.arrayBuffer(), { + env: env, + wasi_snapshot_preview1: Wasi, + }); + // is it node? + } } else { //@ts-ignore const fs = await import("fs"); - Bun.wasm_source = await globalThis.WebAssembly.instantiate( - fs.readFileSync(url), - { - env: env, - wasi_snapshot_preview1: Wasi, - }, - ); + Bun.wasm_source = await globalThis.WebAssembly.instantiate(fs.readFileSync(url), { + env: env, + wasi_snapshot_preview1: Wasi, + }); } - const res = Bun.wasm_exports.init(); + const res = Bun.wasm_exports.init(heapSize); + if (res < 0) { - throw `[Bun] Failed to initialize WASM module: code ${res}`; + throw new Error(`[Bun] Failed to initialize WASM module: code ${res}`); } Bun.has_initialized = true; } - static transformSync( - content: Uint8Array | string, - file_name: string, - loader?: Loader, - ): TransformResponse { - if (!Bun.has_initialized) { - throw "Please run await Bun.init(wasm_url) before using this."; + static getTests(content: Uint8Array | string, filename = "my.test.tsx") { + const bb = new ByteBuffer(scratch); + bb.length = 0; + bb.index = 0; + const contents_buffer = content; + + encodeGetTestsRequest( + { + contents: contents_buffer, + path: filename, + }, + bb, + ); + + const data = bb.toUint8Array(); + + const input_ptr = Bun.wasm_exports.bun_malloc(data.length); + var buffer = Bun._wasmPtrToSlice(input_ptr); + buffer.set(data); + captureErrors = true; + try { + var resp_ptr = Bun.wasm_exports.getTests(input_ptr); + } catch (e) { + throw e; + } finally { + captureErrors = false; + Bun.wasm_exports.bun_free(input_ptr); + } + + if (Number(resp_ptr) === 0) { + if (capturedErrors.length) { + const err = capturedErrors.slice(); + capturedErrors.length = 0; + throw new Error(err.join("\n").trim()); + } + + throw new Error("Failed to parse"); + } + + if (capturedErrors.length) { + Bun.wasm_exports.bun_free(resp_ptr); + const err = capturedErrors.slice(); + capturedErrors.length = 0; + throw new Error(err.join("\n").trim()); + } + + var _bb = new ByteBuffer(Bun._wasmPtrToSlice(resp_ptr)); + + const response = decodeGetTestsResponse(_bb); + var tests = new Array(response.tests.length); + + for (var i = 0; i < response.tests.length; i++) { + tests[i] = { + name: new TextDecoder().decode( + response.contents.subarray( + response.tests[i].label.offset, + response.tests[i].label.offset + response.tests[i].label.length, + ), + ), + byteOffset: response.tests[i].byteOffset, + kind: testKindMap[response.tests[i].kind], + }; } - // if (process.env.NODE_ENV === "development") { - // console.time("[Bun] Transform " + file_name); - // } + Bun.wasm_exports.bun_free(resp_ptr); + + return tests; + } + static transformSync(content: Uint8Array | string, file_name: string, loader?: Loader): TransformResponse { const bb = new ByteBuffer(scratch); bb.length = 0; bb.index = 0; @@ -274,28 +342,14 @@ export class Bun { buffer.set(data); const resp_ptr = Bun.wasm_exports.transform(input_ptr); - var _bb = new ByteBuffer(Bun._wasmPtrToSlice(resp_ptr)); - const response = decodeTransformResponse(_bb); Bun.wasm_exports.bun_free(input_ptr); scratch = bb.data; return response; } - static scan( - content: Uint8Array | string, - file_name: string, - loader?: Loader, - ): ScanResult { - if (!Bun.has_initialized) { - throw "Please run await Bun.init(wasm_url) before using this."; - } - - // if (process.env.NODE_ENV === "development") { - // console.time("[Bun] Transform " + file_name); - // } - scratch.fill(0); + static scan(content: Uint8Array | string, file_name: string, loader?: Loader): ScanResult { const bb = new ByteBuffer(scratch); bb.length = 0; bb.index = 0; @@ -337,15 +391,5 @@ export class Bun { export const transformSync = Bun.transformSync; export const scan = Bun.scan; export const init = Bun.init; +export const getTests = Bun.getTests; export default Bun; - -if ("window" in globalThis && !("Bun" in globalThis)) { - // @ts-ignore-line - globalThis.Bun = Bun; -} - -//@ts-ignore -if (process.env.NODE_ENV === "development") { - //@ts-ignore - Bun.env = env; -} diff --git a/packages/bun-wasm/test/node.mjs b/packages/bun-wasm/test/node.mjs index 7890a5c6e12110..2699a1dad7af3a 100644 --- a/packages/bun-wasm/test/node.mjs +++ b/packages/bun-wasm/test/node.mjs @@ -1,28 +1,7 @@ -// This is not released yet because there are some memory bugs with the WASM build -// It causes syntax errors which don't make any sense -// Most likely, this is an issue with some code expecting 64 bit pointers -// That's also why this test just prints instead of using a test runner -import * as Bun from "../index.mjs"; +import { readFileSync } from "fs"; +import { init, getTests } from "../index.mjs"; -await Bun.init(new URL("../bun.wasm", import.meta.url)); +const buf = (process.argv.length > 2 ? readFileSync(process.argv.at(-1)) : "") || readFileSync(import.meta.url); +await init(new URL("../bun.wasm", import.meta.url)); -const buf = - (process.argv.length > 2 ? process.argv.at(-1) : "") || - new TextEncoder().encode(` - -export function hi() { - return
Hey
; -} - -`); -const result = Bun.transformSync(buf, "hi.jsx", "jsx"); -if (result.errors?.length) { - console.log(JSON.stringify(result.errors, null, 2)); - throw new Error("Failed"); -} - -if (!result.files.length) { - throw new Error("unexpectedly empty"); -} - -process.stdout.write(result.files[0].data); +console.log(getTests(buf)); diff --git a/root.zig b/root.zig index 0d00409ebf85a9..0fc0d3987a9938 100644 --- a/root.zig +++ b/root.zig @@ -17,3 +17,6 @@ pub const completions = struct { pub const zsh = @embedFile("./completions/bun.zsh"); pub const fish = @embedFile("./completions/bun.fish"); }; + +pub const JavaScriptCore = @import("./src/jsc.zig"); +pub const C = @import("./src/c.zig"); diff --git a/root_wasm.zig b/root_wasm.zig new file mode 100644 index 00000000000000..f04ceb015c9327 --- /dev/null +++ b/root_wasm.zig @@ -0,0 +1,26 @@ +pub usingnamespace @import("src/main_wasm.zig"); + +pub const bun = @import("src/bun.zig"); + +pub const content = struct { + pub const error_js_path = "packages/bun-error/dist/index.js"; + pub const error_js = @embedFile(error_js_path); + + pub const error_css_path = "packages/bun-error/dist/bun-error.css"; + pub const error_css_path_dev = "packages/bun-error/bun-error.css"; + + pub const error_css = @embedFile(error_css_path); +}; + +pub const completions = struct {}; +pub const is_bindgen = true; +pub const JavaScriptCore = struct { + pub fn markBinding(_: @import("std").builtin.SourceLocation) void { + unreachable; + } + + pub const ZigString = struct {}; +}; + +pub const C = struct {}; +pub const build_options = @import("build_options"); diff --git a/src/ArenaAllocator.zig b/src/ArenaAllocator.zig index 2ccb08d19aea53..c2d8718fd4d3a7 100644 --- a/src/ArenaAllocator.zig +++ b/src/ArenaAllocator.zig @@ -1,4 +1,3 @@ -/// TODO: delete this once we've upgraded Zig and https://github.com/ziglang/zig/pull/15985 is merged. const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; @@ -152,7 +151,7 @@ pub const ArenaAllocator = struct { return false; }; self.child_allocator.rawFree(first_alloc_buf, align_bits, @returnAddress()); - const node = @as(*BufNode, @ptrCast(@alignCast(new_ptr))); + const node: *BufNode = @ptrCast(@alignCast(new_ptr)); node.* = .{ .data = total_size }; self.state.buffer_list.first = node; } @@ -167,7 +166,7 @@ pub const ArenaAllocator = struct { const log2_align = comptime std.math.log2_int(usize, @alignOf(BufNode)); const ptr = self.child_allocator.rawAlloc(len, log2_align, @returnAddress()) orelse return null; - const buf_node = @as(*BufNode, @ptrCast(@alignCast(ptr))); + const buf_node: *BufNode = @ptrCast(@alignCast(ptr)); buf_node.* = .{ .data = len }; self.state.buffer_list.prepend(buf_node); self.state.end_index = 0; @@ -175,7 +174,7 @@ pub const ArenaAllocator = struct { } fn alloc(ctx: *anyopaque, n: usize, log2_ptr_align: u8, ra: usize) ?[*]u8 { - const self = @as(*ArenaAllocator, @ptrCast(@alignCast(ctx))); + const self: *ArenaAllocator = @ptrCast(@alignCast(ctx)); _ = ra; const ptr_align = @as(usize, 1) << @as(Allocator.Log2Align, @intCast(log2_ptr_align)); @@ -209,7 +208,7 @@ pub const ArenaAllocator = struct { } fn resize(ctx: *anyopaque, buf: []u8, log2_buf_align: u8, new_len: usize, ret_addr: usize) bool { - const self = @as(*ArenaAllocator, @ptrCast(@alignCast(ctx))); + const self: *ArenaAllocator = @ptrCast(@alignCast(ctx)); _ = log2_buf_align; _ = ret_addr; @@ -236,7 +235,7 @@ pub const ArenaAllocator = struct { _ = log2_buf_align; _ = ret_addr; - const self = @as(*ArenaAllocator, @ptrCast(@alignCast(ctx))); + const self: *ArenaAllocator = @ptrCast(@alignCast(ctx)); const cur_node = self.state.buffer_list.first orelse return; const cur_buf = @as([*]u8, @ptrCast(cur_node))[@sizeOf(BufNode)..cur_node.data]; diff --git a/src/__global.zig b/src/__global.zig index 7bcdaeeda44b31..9a33fff37b4b32 100644 --- a/src/__global.zig +++ b/src/__global.zig @@ -7,20 +7,26 @@ const StringTypes = @import("./string_types.zig"); const Mimalloc = @import("root").bun.Mimalloc; const bun = @import("root").bun; -const BASE_VERSION = "0.7"; - pub const build_id = std.fmt.parseInt(u64, std.mem.trim(u8, @embedFile("./build-id"), "\n \r\t"), 10) catch unreachable; +pub const version: @import("./install/semver.zig").Version = .{ + .major = 0, + .minor = 7, + .patch = build_id, +}; + +const version_string = std.fmt.comptimePrint("{d}.{d}.{d}", .{ version.major, version.minor, version.patch }); + pub const package_json_version = if (Environment.isDebug) - std.fmt.comptimePrint(BASE_VERSION ++ ".{d}_debug", .{build_id}) + version_string ++ "_debug" else - std.fmt.comptimePrint(BASE_VERSION ++ ".{d}", .{build_id}); + version_string; pub const package_json_version_with_sha = if (Environment.git_sha.len == 0) package_json_version else if (Environment.isDebug) - std.fmt.comptimePrint(BASE_VERSION ++ ".{d}_debug ({s})", .{ build_id, Environment.git_sha[0..@min(Environment.git_sha.len, 8)] }) + std.fmt.comptimePrint("{s}_debug ({s})", .{ version_string, Environment.git_sha[0..@min(Environment.git_sha.len, 8)] }) else - std.fmt.comptimePrint(BASE_VERSION ++ ".{d} ({s})", .{ build_id, Environment.git_sha[0..@min(Environment.git_sha.len, 8)] }); + std.fmt.comptimePrint("{s} ({s})", .{ version_string, Environment.git_sha[0..@min(Environment.git_sha.len, 8)] }); pub const os_name = if (Environment.isWindows) "win32" @@ -47,12 +53,6 @@ pub inline fn getStartTime() i128 { return @import("root").bun.start_time; } -pub const version: @import("./install/semver.zig").Version = .{ - .major = 0, - .minor = 6, - .patch = build_id, -}; - pub fn setThreadName(name: StringTypes.stringZ) void { if (Environment.isLinux) { _ = std.os.prctl(.SET_NAME, .{@intFromPtr(name.ptr)}) catch 0; diff --git a/src/api/schema.d.ts b/src/api/schema.d.ts index 2a86340ad66b95..a982b910d712f0 100644 --- a/src/api/schema.d.ts +++ b/src/api/schema.d.ts @@ -331,6 +331,16 @@ export const WebsocketCommandKindKeys: { 3: "build_with_file_path"; build_with_file_path: "build_with_file_path"; }; +export const enum TestKind { + test_fn = 1, + describe_fn = 2, +} +export const TestKindKeys: { + 1: "test_fn"; + test_fn: "test_fn"; + 2: "describe_fn"; + describe_fn: "describe_fn"; +}; export interface StackFrame { function_name: string; file: string; @@ -729,6 +739,22 @@ export interface ClientServerModuleManifest { contents: Uint8Array; } +export interface GetTestsRequest { + path: string; + contents: Uint8Array; +} + +export interface TestResponseItem { + byteOffset: int32; + label: StringPointer; + kind: TestKind; +} + +export interface GetTestsResponse { + tests: TestResponseItem[]; + contents: Uint8Array; +} + export declare function encodeStackFrame(message: StackFrame, bb: ByteBuffer): void; export declare function decodeStackFrame(buffer: ByteBuffer): StackFrame; export declare function encodeStackFramePosition(message: StackFramePosition, bb: ByteBuffer): void; @@ -847,3 +873,9 @@ export declare function encodeClientServerModule(message: ClientServerModule, bb export declare function decodeClientServerModule(buffer: ByteBuffer): ClientServerModule; export declare function encodeClientServerModuleManifest(message: ClientServerModuleManifest, bb: ByteBuffer): void; export declare function decodeClientServerModuleManifest(buffer: ByteBuffer): ClientServerModuleManifest; +export declare function encodeGetTestsRequest(message: GetTestsRequest, bb: ByteBuffer): void; +export declare function decodeGetTestsRequest(buffer: ByteBuffer): GetTestsRequest; +export declare function encodeTestResponseItem(message: TestResponseItem, bb: ByteBuffer): void; +export declare function decodeTestResponseItem(buffer: ByteBuffer): TestResponseItem; +export declare function encodeGetTestsResponse(message: GetTestsResponse, bb: ByteBuffer): void; +export declare function decodeGetTestsResponse(buffer: ByteBuffer): GetTestsResponse; diff --git a/src/api/schema.js b/src/api/schema.js index f1e68031ec85bc..b28c5669c2e3ab 100644 --- a/src/api/schema.js +++ b/src/api/schema.js @@ -3315,6 +3315,108 @@ function encodeClientServerModuleManifest(message, bb) { } } +function decodeGetTestsRequest(bb) { + var result = {}; + + result["path"] = bb.readString(); + result["contents"] = bb.readByteArray(); + return result; +} + +function encodeGetTestsRequest(message, bb) { + var value = message["path"]; + if (value != null) { + bb.writeString(value); + } else { + throw new Error('Missing required field "path"'); + } + + var value = message["contents"]; + if (value != null) { + bb.writeByteArray(value); + } else { + throw new Error('Missing required field "contents"'); + } +} +const TestKind = { + "1": 1, + "2": 2, + "test_fn": 1, + "describe_fn": 2, +}; +const TestKindKeys = { + "1": "test_fn", + "2": "describe_fn", + "test_fn": "test_fn", + "describe_fn": "describe_fn", +}; + +function decodeTestResponseItem(bb) { + var result = {}; + + result["byteOffset"] = bb.readInt32(); + result["label"] = decodeStringPointer(bb); + result["kind"] = TestKind[bb.readByte()]; + return result; +} + +function encodeTestResponseItem(message, bb) { + var value = message["byteOffset"]; + if (value != null) { + bb.writeInt32(value); + } else { + throw new Error('Missing required field "byteOffset"'); + } + + var value = message["label"]; + if (value != null) { + encodeStringPointer(value, bb); + } else { + throw new Error('Missing required field "label"'); + } + + var value = message["kind"]; + if (value != null) { + var encoded = TestKind[value]; + if (encoded === void 0) throw new Error("Invalid value " + JSON.stringify(value) + ' for enum "TestKind"'); + bb.writeByte(encoded); + } else { + throw new Error('Missing required field "kind"'); + } +} + +function decodeGetTestsResponse(bb) { + var result = {}; + + var length = bb.readVarUint(); + var values = (result["tests"] = Array(length)); + for (var i = 0; i < length; i++) values[i] = decodeTestResponseItem(bb); + result["contents"] = bb.readByteArray(); + return result; +} + +function encodeGetTestsResponse(message, bb) { + var value = message["tests"]; + if (value != null) { + var values = value, + n = values.length; + bb.writeVarUint(n); + for (var i = 0; i < n; i++) { + value = values[i]; + encodeTestResponseItem(value, bb); + } + } else { + throw new Error('Missing required field "tests"'); + } + + var value = message["contents"]; + if (value != null) { + bb.writeByteArray(value); + } else { + throw new Error('Missing required field "contents"'); + } +} + export { Loader }; export { LoaderKeys }; export { FrameworkEntryPointType }; @@ -3461,3 +3563,11 @@ export { decodeClientServerModule }; export { encodeClientServerModule }; export { decodeClientServerModuleManifest }; export { encodeClientServerModuleManifest }; +export { decodeGetTestsRequest }; +export { encodeGetTestsRequest }; +export { TestKind }; +export { TestKindKeys }; +export { decodeTestResponseItem }; +export { encodeTestResponseItem }; +export { decodeGetTestsResponse }; +export { encodeGetTestsResponse }; diff --git a/src/api/schema.peechy b/src/api/schema.peechy index a172606f7b2cce..53800e4f318b6e 100644 --- a/src/api/schema.peechy +++ b/src/api/schema.peechy @@ -609,3 +609,25 @@ struct ClientServerModuleManifest { StringPointer[] exportNames; byte[] contents; } + + +struct GetTestsRequest { + string path; + byte[] contents; +} + +smol TestKind { + test_fn = 1; + describe_fn = 2; +} + +struct TestResponseItem { + int32 byteOffset; + StringPointer label; + TestKind kind; +} + +struct GetTestsResponse { + TestResponseItem[] tests; + byte[] contents; +} \ No newline at end of file diff --git a/src/api/schema.zig b/src/api/schema.zig index 94f2d22df4e52c..de46a813b1fe49 100644 --- a/src/api/schema.zig +++ b/src/api/schema.zig @@ -3140,4 +3140,87 @@ pub const Api = struct { try writer.writeArray(u8, this.contents); } }; + + pub const GetTestsRequest = struct { + /// path + path: []const u8, + + /// contents + contents: []const u8, + + pub fn decode(reader: anytype) anyerror!GetTestsRequest { + var this = std.mem.zeroes(GetTestsRequest); + + this.path = try reader.readValue([]const u8); + this.contents = try reader.readArray(u8); + return this; + } + + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeValue(@TypeOf(this.path), this.path); + try writer.writeArray(u8, this.contents); + } + }; + + pub const TestKind = enum(u8) { + _none, + /// test_fn + test_fn, + + /// describe_fn + describe_fn, + + _, + + pub fn jsonStringify(self: *const @This(), opts: anytype, o: anytype) !void { + return try std.json.stringify(@tagName(self), opts, o); + } + }; + + pub const TestResponseItem = struct { + /// byteOffset + byte_offset: i32 = 0, + + /// label + label: StringPointer, + + /// kind + kind: TestKind, + + pub fn decode(reader: anytype) anyerror!TestResponseItem { + var this = std.mem.zeroes(TestResponseItem); + + this.byte_offset = try reader.readValue(i32); + this.label = try reader.readValue(StringPointer); + this.kind = try reader.readValue(TestKind); + return this; + } + + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeInt(this.byte_offset); + try writer.writeValue(@TypeOf(this.label), this.label); + try writer.writeEnum(this.kind); + } + }; + + pub const GetTestsResponse = struct { + /// tests + tests: []const TestResponseItem, + + /// contents + contents: []const u8, + + pub fn decode(reader: anytype) anyerror!GetTestsResponse { + var this = std.mem.zeroes(GetTestsResponse); + + this.tests = try reader.readArray(TestResponseItem); + this.contents = try reader.readArray(u8); + return this; + } + + pub fn encode(this: *const @This(), writer: anytype) anyerror!void { + try writer.writeArray(TestResponseItem, this.tests); + try writer.writeArray(u8, this.contents); + } + }; }; diff --git a/src/build-id b/src/build-id index d00491fd7e5bb6..b8626c4cff2849 100644 --- a/src/build-id +++ b/src/build-id @@ -1 +1 @@ -1 +4 diff --git a/src/bun.js/ResolveMessage.zig b/src/bun.js/ResolveMessage.zig index b9b2d7b06914b0..457a8ec4f9657a 100644 --- a/src/bun.js/ResolveMessage.zig +++ b/src/bun.js/ResolveMessage.zig @@ -35,6 +35,9 @@ pub const ResolveMessage = struct { return try std.fmt.allocPrint(allocator, "Cannot find module \"{s}\" from \"{s}\"", .{ specifier, referrer }); } }, + error.InvalidDataURL => { + return try std.fmt.allocPrint(allocator, "Cannot resolve invalid data URL \"{s}\" from \"{s}\"", .{ specifier, referrer }); + }, else => { if (Resolver.isPackagePath(specifier)) { return try std.fmt.allocPrint(allocator, "{s} while resolving package \"{s}\" from \"{s}\"", .{ @errorName(err), specifier, referrer }); diff --git a/src/bun.js/Strong.zig b/src/bun.js/Strong.zig new file mode 100644 index 00000000000000..d2ed3afbd3b379 --- /dev/null +++ b/src/bun.js/Strong.zig @@ -0,0 +1,114 @@ +const bun = @import("root").bun; +const JSC = bun.JSC; + +const StrongImpl = opaque { + pub fn init(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) *StrongImpl { + JSC.markBinding(@src()); + return Bun__StrongRef__new(globalThis, value); + } + + pub fn get(this: *StrongImpl) JSC.JSValue { + JSC.markBinding(@src()); + return Bun__StrongRef__get(this); + } + + pub fn set(this: *StrongImpl, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) void { + JSC.markBinding(@src()); + Bun__StrongRef__set(this, globalThis, value); + } + + pub fn clear(this: *StrongImpl) void { + JSC.markBinding(@src()); + Bun__StrongRef__clear(this); + } + + pub fn deinit( + this: *StrongImpl, + ) void { + JSC.markBinding(@src()); + Bun__StrongRef__delete(this); + } + + extern fn Bun__StrongRef__delete(this: *StrongImpl) void; + extern fn Bun__StrongRef__new(*JSC.JSGlobalObject, JSC.JSValue) *StrongImpl; + extern fn Bun__StrongRef__get(this: *StrongImpl) JSC.JSValue; + extern fn Bun__StrongRef__set(this: *StrongImpl, *JSC.JSGlobalObject, JSC.JSValue) void; + extern fn Bun__StrongRef__clear(this: *StrongImpl) void; +}; + +pub const Strong = struct { + ref: ?*StrongImpl = null, + globalThis: ?*JSC.JSGlobalObject = null, + + pub fn init() Strong { + return .{}; + } + + pub fn create( + value: JSC.JSValue, + globalThis: *JSC.JSGlobalObject, + ) Strong { + if (value != .zero) { + return .{ .ref = StrongImpl.init(globalThis, value), .globalThis = globalThis }; + } + + return .{ .globalThis = globalThis }; + } + + pub fn get(this: *Strong) ?JSC.JSValue { + var ref = this.ref orelse return null; + const result = ref.get(); + if (result == .zero) { + return null; + } + + return result; + } + + pub fn swap(this: *Strong) JSC.JSValue { + var ref = this.ref orelse return .zero; + const result = ref.get(); + if (result == .zero) { + return .zero; + } + + ref.clear(); + return result; + } + + pub fn has(this: *Strong) bool { + var ref = this.ref orelse return false; + return ref.get() != .zero; + } + + pub fn trySwap(this: *Strong) ?JSC.JSValue { + const result = this.swap(); + if (result == .zero) { + return null; + } + + return result; + } + + pub fn set(this: *Strong, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) void { + var ref: *StrongImpl = this.ref orelse { + if (value == .zero) return; + this.ref = StrongImpl.init(globalThis, value); + this.globalThis = globalThis; + return; + }; + this.globalThis = globalThis; + ref.set(globalThis, value); + } + + pub fn clear(this: *Strong) void { + var ref: *StrongImpl = this.ref orelse return; + ref.clear(); + } + + pub fn deinit(this: *Strong) void { + var ref: *StrongImpl = this.ref orelse return; + this.ref = null; + ref.deinit(); + } +}; diff --git a/src/bun.js/WebKit b/src/bun.js/WebKit index 284095ff91529d..74609640b2a7c5 160000 --- a/src/bun.js/WebKit +++ b/src/bun.js/WebKit @@ -1 +1 @@ -Subproject commit 284095ff91529df883cf5ab30d66048a3207bade +Subproject commit 74609640b2a7c5a1588b824f870d1b0ff91bfd8e diff --git a/src/bun.js/api/bun.zig b/src/bun.js/api/bun.zig index 85d2e7f8325730..fe0aafc25d0823 100644 --- a/src/bun.js/api/bun.zig +++ b/src/bun.js/api/bun.zig @@ -582,88 +582,6 @@ pub fn newPath( return Node.Path.create(ctx.ptr(), is_windows).asObjectRef(); } -pub fn readFileAsStringCallback( - ctx: js.JSContextRef, - buf_z: [:0]const u8, - exception: js.ExceptionRef, -) js.JSValueRef { - const path = buf_z.ptr[0..buf_z.len]; - var file = std.fs.cwd().openFileZ(buf_z, .{ .mode = .read_only }) catch |err| { - JSError(getAllocator(ctx), "Opening file {s} for path: \"{s}\"", .{ @errorName(err), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - }; - - defer file.close(); - - const stat = file.stat() catch |err| { - JSError(getAllocator(ctx), "Getting file size {s} for \"{s}\"", .{ @errorName(err), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - }; - - if (stat.kind != .file) { - JSError(getAllocator(ctx), "Can't read a {s} as a string (\"{s}\")", .{ @tagName(stat.kind), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - } - - var contents_buf = VirtualMachine.get().allocator.alloc(u8, stat.size + 2) catch unreachable; // OOM - defer VirtualMachine.get().allocator.free(contents_buf); - const contents_len = file.readAll(contents_buf) catch |err| { - JSError(getAllocator(ctx), "{s} reading file (\"{s}\")", .{ @errorName(err), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - }; - - contents_buf[contents_len] = 0; - - // Very slow to do it this way. We're copying the string twice. - // But it's important that this string is garbage collected instead of manually managed. - // We can't really recycle this one. - // TODO: use external string - return js.JSValueMakeString(ctx, js.JSStringCreateWithUTF8CString(contents_buf.ptr)); -} - -pub fn readFileAsBytesCallback( - ctx: js.JSContextRef, - buf_z: [:0]const u8, - exception: js.ExceptionRef, -) js.JSValueRef { - const path = buf_z.ptr[0..buf_z.len]; - const allocator = VirtualMachine.get().allocator; - - var file = std.fs.cwd().openFileZ(buf_z, .{ .mode = .read_only }) catch |err| { - JSError(allocator, "Opening file {s} for path: \"{s}\"", .{ @errorName(err), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - }; - - defer file.close(); - - const stat = file.stat() catch |err| { - JSError(allocator, "Getting file size {s} for \"{s}\"", .{ @errorName(err), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - }; - - if (stat.kind != .file) { - JSError(allocator, "Can't read a {s} as a string (\"{s}\")", .{ @tagName(stat.kind), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - } - - var contents_buf = allocator.alloc(u8, stat.size + 2) catch unreachable; // OOM - const contents_len = file.readAll(contents_buf) catch |err| { - JSError(allocator, "{s} reading file (\"{s}\")", .{ @errorName(err), path }, ctx, exception); - return js.JSValueMakeUndefined(ctx); - }; - - contents_buf[contents_len] = 0; - - var marked_array_buffer = allocator.create(MarkedArrayBuffer) catch unreachable; - marked_array_buffer.* = MarkedArrayBuffer.fromBytes( - contents_buf[0..contents_len], - allocator, - .Uint8Array, - ); - - return marked_array_buffer.toJSObjectRef(ctx, exception); -} - pub fn getRouteFiles( _: void, ctx: js.JSContextRef, @@ -783,40 +701,6 @@ pub fn openInEditor( return JSC.JSValue.jsUndefined().asObjectRef(); } -pub fn readFileAsBytes( - _: void, - ctx: js.JSContextRef, - _: js.JSObjectRef, - _: js.JSObjectRef, - arguments: []const js.JSValueRef, - exception: js.ExceptionRef, -) js.JSValueRef { - var buf: [bun.MAX_PATH_BYTES]u8 = undefined; - const path = getFilePath(ctx, arguments, &buf, exception) orelse return null; - buf[path.len] = 0; - - const buf_z: [:0]const u8 = buf[0..path.len :0]; - const result = readFileAsBytesCallback(ctx, buf_z, exception); - return result; -} - -pub fn readFileAsString( - _: void, - ctx: js.JSContextRef, - _: js.JSObjectRef, - _: js.JSObjectRef, - arguments: []const js.JSValueRef, - exception: js.ExceptionRef, -) js.JSValueRef { - var buf: [bun.MAX_PATH_BYTES]u8 = undefined; - const path = getFilePath(ctx, arguments, &buf, exception) orelse return null; - buf[path.len] = 0; - - const buf_z: [:0]const u8 = buf[0..path.len :0]; - const result = readFileAsStringCallback(ctx, buf_z, exception); - return result; -} - pub fn getPublicPath(to: string, origin: URL, comptime Writer: type, writer: Writer) void { return getPublicPathWithAssetPrefix(to, VirtualMachine.get().bundler.fs.top_level_dir, origin, VirtualMachine.get().bundler.options.routes.asset_prefix_path, comptime Writer, writer); } @@ -1108,27 +992,6 @@ comptime { } } -pub fn readAllStdinSync( - _: void, - ctx: js.JSContextRef, - _: js.JSObjectRef, - _: js.JSObjectRef, - _: []const js.JSValueRef, - exception: js.ExceptionRef, -) js.JSValueRef { - var stack = std.heap.stackFallback(2048, getAllocator(ctx)); - var allocator = stack.get(); - - var stdin = std.io.getStdIn(); - var result = stdin.readToEndAlloc(allocator, std.math.maxInt(u32)) catch |err| { - JSError(undefined, "{s} reading stdin", .{@errorName(err)}, ctx, exception); - return null; - }; - var out = ZigString.init(result); - out.detectEncoding(); - return out.toValueGC(ctx.ptr()).asObjectRef(); -} - var public_path_temp_str: [bun.MAX_PATH_BYTES]u8 = undefined; pub fn getPublicPathJS( @@ -1158,35 +1021,60 @@ pub const Class = NewClass( .read_only = true, }, .{ - .match = .{ - .rfn = &Router.deprecatedBunGlobalMatch, + // Private + // TODO: We should remove _Os, _Path, and make registerMacro and fs be private builtins + .DO_NOT_USE_OR_YOU_WILL_BE_FIRED_mimalloc_dump = .{ + .rfn = &dump_mimalloc, + .enumerable = false, }, - .sleepSync = .{ - .rfn = &sleepSync, + ._Os = .{ + .rfn = &Bun.newOs, + .enumerable = false, }, - // .fetch = .{ - // .rfn = &Fetch.call, - // }, + ._Path = .{ + .rfn = &Bun.newPath, + .enumerable = false, + }, + .registerMacro = .{ + .rfn = &Bun.registerMacro, + .enumerable = false, + }, + .fs = .{ + .rfn = &Bun.createNodeFS, + .enumerable = false, + }, + .jest = .{ + .rfn = &@import("../test/jest.zig").Jest.call, + .enumerable = false, + }, + + // TODO: remove these deprecated methods before 1.0 .getImportedStyles = .{ .rfn = &Bun.getImportedStyles, - }, - .inspect = .{ - .rfn = &Bun.inspect, + .enumerable = false, }, .getRouteFiles = .{ .rfn = &Bun.getRouteFiles, + .enumerable = false, }, - ._Os = .{ - .rfn = &Bun.newOs, - }, - ._Path = .{ - .rfn = &Bun.newPath, + .match = .{ + .rfn = &Router.deprecatedBunGlobalMatch, + .enumerable = false, }, .getRouteNames = .{ .rfn = &Bun.getRouteNames, + .enumerable = false, + }, + + // Public API + .sleepSync = .{ + .rfn = &sleepSync, }, - .readFile = .{ - .rfn = &Bun.readFileAsString, + // .fetch = .{ + // .rfn = &Fetch.call, + // }, + .inspect = .{ + .rfn = &Bun.inspect, }, .resolveSync = .{ .rfn = &Bun.resolveSync, @@ -1194,24 +1082,9 @@ pub const Class = NewClass( .resolve = .{ .rfn = &Bun.resolve, }, - .readFileBytes = .{ - .rfn = &Bun.readFileAsBytes, - }, .getPublicPath = .{ .rfn = &Bun.getPublicPathJS, }, - .registerMacro = .{ - .rfn = &Bun.registerMacro, - .enumerable = false, - }, - .fs = .{ - .rfn = &Bun.createNodeFS, - .enumerable = false, - }, - .jest = .{ - .rfn = &@import("../test/jest.zig").Jest.call, - .enumerable = false, - }, .indexOfLine = .{ .rfn = &Bun.indexOfLine, }, @@ -1233,9 +1106,6 @@ pub const Class = NewClass( .openInEditor = .{ .rfn = &Bun.openInEditor, }, - .readAllStdinSync = .{ - .rfn = &Bun.readAllStdinSync, - }, .serve = .{ .rfn = &Bun.serve, }, @@ -1251,9 +1121,6 @@ pub const Class = NewClass( .nanoseconds = .{ .rfn = &nanoseconds, }, - .DO_NOT_USE_OR_YOU_WILL_BE_FIRED_mimalloc_dump = .{ - .rfn = &dump_mimalloc, - }, .gzipSync = .{ .rfn = &JSC.wrapWithHasContainer(JSZlib, "gzipSync", false, false, true), }, @@ -1266,7 +1133,6 @@ pub const Class = NewClass( .inflateSync = .{ .rfn = &JSC.wrapWithHasContainer(JSZlib, "inflateSync", false, false, true), }, - .which = .{ .rfn = &which, }, @@ -1279,11 +1145,9 @@ pub const Class = NewClass( .build = .{ .rfn = &Bun.JSBundler.buildFn, }, - .listen = .{ .rfn = &JSC.wrapWithHasContainer(JSC.API.Listener, "listen", false, false, false), }, - .connect = .{ .rfn = &JSC.wrapWithHasContainer(JSC.API.Listener, "connect", false, false, false), }, @@ -1292,8 +1156,10 @@ pub const Class = NewClass( .main = .{ .get = getMain, }, + // TODO: decide what we want to do .cwd = .{ .get = getCWD, + .enumerable = false, }, .origin = .{ .get = getOrigin, @@ -1307,11 +1173,15 @@ pub const Class = NewClass( .stderr = .{ .get = getStderr, }, + // TODO: remove this before 1.0 .routesDir = .{ .get = getRoutesDir, + .enumerable = false, }, + // TODO: remove this before 1.0 .assetPrefix = .{ .get = getAssetPrefix, + .enumerable = false, }, .argv = .{ .get = getArgv, @@ -3322,24 +3192,24 @@ pub const Hash = struct { } else { var seed: u64 = 0; if (args.nextEat()) |arg| { - if (arg.isNumber()) { - seed = arg.toU32(); + if (arg.isNumber() or arg.isBigInt()) { + seed = arg.toUInt64NoTruncate(); } } if (comptime std.meta.trait.isNumber(@TypeOf(function_args[0]))) { - function_args[0] = @as(@TypeOf(function_args[0]), @intCast(seed)); + function_args[0] = @as(@TypeOf(function_args[0]), @truncate(seed)); function_args[1] = input; } else { - function_args[1] = @as(@TypeOf(function_args[1]), @intCast(seed)); function_args[0] = input; + function_args[1] = @as(@TypeOf(function_args[1]), @truncate(seed)); } const value = @call(.auto, Function, function_args); if (@TypeOf(value) == u32) { - return JSC.JSValue.jsNumber(@as(i32, @bitCast(value))).asObjectRef(); + return JSC.JSValue.jsNumber(@as(u32, @bitCast(value))).asObjectRef(); } - return JSC.JSValue.jsNumber(value).asObjectRef(); + return JSC.JSValue.fromUInt64NoTruncate(ctx.ptr(), value).asObjectRef(); } } }; diff --git a/src/bun.js/api/bun/dns_resolver.zig b/src/bun.js/api/bun/dns_resolver.zig index 4d961b54c332c1..ed76dc777bf5c9 100644 --- a/src/bun.js/api/bun/dns_resolver.zig +++ b/src/bun.js/api/bun/dns_resolver.zig @@ -16,6 +16,8 @@ const JSGlobalObject = JSC.JSGlobalObject; const c_ares = bun.c_ares; const GetAddrInfoAsyncCallback = fn (i32, ?*std.c.addrinfo, ?*anyopaque) callconv(.C) void; +const INET6_ADDRSTRLEN = if (bun.Environment.isWindows) 65 else 46; +const IANA_DNS_PORT = 53; const LibInfo = struct { // static int32_t (*getaddrinfo_async_start)(mach_port_t*, @@ -2015,6 +2017,89 @@ pub const DNSResolver = struct { return promise; } + pub fn getServers(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(.C) JSC.JSValue { + _ = callframe; + + var vm = globalThis.bunVM(); + var resolver = vm.rareData().globalDNSResolver(vm); + var channel: *c_ares.Channel = switch (resolver.getChannel()) { + .result => |res| res, + .err => |err| { + const system_error = JSC.SystemError{ + .errno = -1, + .code = bun.String.static(err.code()), + .message = bun.String.static(err.label()), + }; + + globalThis.throwValue(system_error.toErrorInstance(globalThis)); + return .zero; + }, + }; + + var servers: [*c]c_ares.struct_ares_addr_port_node = undefined; + const r = c_ares.ares_get_servers_ports(channel, &servers); + if (r != c_ares.ARES_SUCCESS) { + const err = c_ares.Error.get(r).?; + globalThis.throwValue(globalThis.createErrorInstance("ares_get_servers_ports error: {s}", .{err.label()})); + return .zero; + } + defer c_ares.ares_free_data(servers); + + const values = JSC.JSValue.createEmptyArray(globalThis, 0); + + var i: u32 = 0; + var cur = servers; + while (cur != null) : ({ + i += 1; + cur = cur.*.next; + }) { + // Formatting reference: https://nodejs.org/api/dns.html#dnsgetservers + // Brackets '[' and ']' consume 2 bytes, used for IPv6 format (e.g., '[2001:4860:4860::8888]:1053'). + // Port range is 6 bytes (e.g., ':65535'). + // Null terminator '\0' uses 1 byte. + var buf: [INET6_ADDRSTRLEN + 2 + 6 + 1]u8 = undefined; + const family = cur.*.family; + + const ip = if (family == std.os.AF.INET6) blk: { + break :blk c_ares.ares_inet_ntop(family, &cur.*.addr.addr6, buf[1..], @sizeOf(@TypeOf(buf)) - 1); + } else blk: { + break :blk c_ares.ares_inet_ntop(family, &cur.*.addr.addr4, buf[1..], @sizeOf(@TypeOf(buf)) - 1); + }; + if (ip == null) { + globalThis.throwValue(globalThis.createErrorInstance( + "ares_inet_ntop error: no more space to convert a network format address", + .{}, + )); + return .zero; + } + + var port = cur.*.tcp_port; + if (port == 0) { + port = cur.*.udp_port; + } + if (port == 0) { + port = IANA_DNS_PORT; + } + + const size = bun.len(bun.cast([*:0]u8, &buf)); + if (port == IANA_DNS_PORT) { + values.putIndex(globalThis, i, JSC.ZigString.init(buf[1..size]).withEncoding().toValueGC(globalThis)); + } else { + if (family == std.os.AF.INET6) { + buf[0] = '['; + buf[size] = ']'; + const port_slice = std.fmt.bufPrint(buf[size + 1 ..], ":{d}", .{port}) catch unreachable; + values.putIndex(globalThis, i, JSC.ZigString.init(buf[0 .. size + 1 + port_slice.len]).withEncoding().toValueGC(globalThis)); + } else { + const port_slice = std.fmt.bufPrint(buf[size..], ":{d}", .{port}) catch unreachable; + values.putIndex(globalThis, i, JSC.ZigString.init(buf[1 .. size + port_slice.len]).withEncoding().toValueGC(globalThis)); + } + } + } + + return values; + } + comptime { @export( resolve, @@ -2082,6 +2167,12 @@ pub const DNSResolver = struct { .name = "Bun__DNSResolver__resolveCname", }, ); + @export( + getServers, + .{ + .name = "Bun__DNSResolver__getServers", + }, + ); } // pub fn lookupService(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) callconv(.C) JSC.JSValue { // const arguments = callframe.arguments(3); diff --git a/src/bun.js/api/filesystem_router.zig b/src/bun.js/api/filesystem_router.zig index 216f66b7fa259f..edb666040f17b3 100644 --- a/src/bun.js/api/filesystem_router.zig +++ b/src/bun.js/api/filesystem_router.zig @@ -75,6 +75,8 @@ const DeprecatedGlobalRouter = struct { }; var path_: ?ZigString.Slice = null; + var req_url_slice: ZigString.Slice = .{}; + defer req_url_slice.deinit(); var pathname: string = ""; defer { if (path_) |path| { @@ -88,7 +90,8 @@ const DeprecatedGlobalRouter = struct { var url = URL.parse(path_.?.slice()); pathname = url.pathname; } else if (arg.as(Request)) |req| { - var url = URL.parse(req.url); + req_url_slice = req.url.toUTF8(bun.default_allocator); + var url = URL.parse(req_url_slice.slice()); pathname = url.pathname; } @@ -389,11 +392,11 @@ pub const FileSystemRouter = struct { if (argument.isCell()) { if (argument.as(JSC.WebCore.Request)) |req| { req.ensureURL() catch unreachable; - break :brk ZigString.Slice.fromUTF8NeverFree(req.url).clone(globalThis.allocator()) catch unreachable; + break :brk req.url.toUTF8(globalThis.allocator()); } if (argument.as(JSC.WebCore.Response)) |resp| { - break :brk ZigString.Slice.fromUTF8NeverFree(resp.url).clone(globalThis.allocator()) catch unreachable; + break :brk resp.url.toUTF8(globalThis.allocator()); } } diff --git a/src/bun.js/api/html_rewriter.zig b/src/bun.js/api/html_rewriter.zig index 92e9790c6c135a..f754e3e239516a 100644 --- a/src/bun.js/api/html_rewriter.zig +++ b/src/bun.js/api/html_rewriter.zig @@ -454,8 +454,8 @@ pub const HTMLRewriter = struct { result.body.init.headers = headers.cloneThis(global); } - result.url = bun.default_allocator.dupe(u8, original.url) catch unreachable; - result.status_text = bun.default_allocator.dupe(u8, original.status_text) catch unreachable; + result.url = original.url.clone(); + result.status_text = original.status_text.clone(); var input = original.body.value.useAsAnyBlob(); sink.input = input; diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 801745aee3b1ce..195d2a3f38e4f7 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -169,8 +169,7 @@ pub const ServerConfig = struct { const log = Output.scoped(.SSLConfig, false); pub fn asUSockets(this_: ?SSLConfig) uws.us_bun_socket_context_options_t { - var ctx_opts: uws.us_bun_socket_context_options_t = undefined; - @memset(@as([*]u8, @ptrCast(&ctx_opts))[0..@sizeOf(uws.us_bun_socket_context_options_t)], 0); + var ctx_opts: uws.us_bun_socket_context_options_t = .{}; if (this_) |ssl_config| { if (ssl_config.key_file_name != null) @@ -1069,7 +1068,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp byte_stream: ?*JSC.WebCore.ByteStream = null, /// Used in errors - pathname: []const u8 = "", + pathname: bun.String = bun.String.empty, /// Used either for temporary blob data or fallback /// When the response body is a temporary value @@ -1550,10 +1549,9 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp stream.unpipe(); } - if (this.pathname.len > 0) { - ctxLog("finalizeWithoutDeinit: this.pathname.len > 0 null", .{}); - this.allocator.free(bun.constStrToU8(this.pathname)); - this.pathname = ""; + if (!this.pathname.isEmpty()) { + this.pathname.deref(); + this.pathname = bun.String.empty; } // if we are waiting for the body yet and the request was not aborted we can safely clear the onData callback @@ -2235,7 +2233,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp request_object.uws_request = req; request_object.ensureURL() catch { - request_object.url = ""; + request_object.url = bun.String.empty; }; // we have to clone the request headers here since they will soon belong to a different request @@ -2244,7 +2242,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp } if (comptime debug_mode) { - ctx.pathname = bun.default_allocator.dupe(u8, request_object.url) catch unreachable; + ctx.pathname = request_object.url.clone(); } // This object dies after the stack frame is popped @@ -2596,15 +2594,28 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp runErrorHandlerWithStatusCode(this, value, 500); } - fn ensurePathname(this: *RequestContext) []const u8 { - if (this.pathname.len > 0) - return this.pathname; + const PathnameFormatter = struct { + ctx: *RequestContext, + + pub fn format(formatter: @This(), comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void { + var this = formatter.ctx; + + if (!this.pathname.isEmpty()) { + try this.pathname.format(fmt, opts, writer); + return; + } - if (!this.flags.has_abort_handler) { - return this.req.url(); + if (!this.flags.has_abort_handler) { + try writer.writeAll(this.req.url()); + return; + } + + try writer.writeAll("/"); } + }; - return "/"; + fn ensurePathname(this: *RequestContext) PathnameFormatter { + return .{ .ctx = this }; } pub inline fn shouldCloseConnection(this: *const RequestContext) bool { @@ -2625,7 +2636,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp vm.log, error.ExceptionOcurred, exception_list.toOwnedSlice() catch @panic("TODO"), - "{s} - {s} failed", + "{s} - {} failed", .{ @as(string, @tagName(this.method)), this.ensurePathname() }, ); } else { @@ -4900,8 +4911,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type { } existing_request = Request{ - .url = url.href, - .url_was_allocated = true, + .url = bun.String.create(url.href), .headers = headers, .body = JSC.WebCore.InitRequestBodyValue(body) catch unreachable, .method = method, @@ -4943,7 +4953,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type { } if (response_value.as(JSC.WebCore.Response)) |resp| { - resp.url = this.allocator.dupe(u8, existing_request.url) catch unreachable; + resp.url = existing_request.url.clone(); } return JSC.JSPromise.resolvedPromiseValue(ctx, response_value).asObjectRef(); } @@ -5295,7 +5305,6 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type { } request_object.* = .{ - .url = "", .method = ctx.method, .uws_request = req, .https = ssl_enabled, @@ -5398,7 +5407,6 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type { } request_object.* = .{ - .url = "", .method = ctx.method, .uws_request = req, .upgrader = ctx, diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig index f7b2eb343cc04b..c964c1d95a8932 100644 --- a/src/bun.js/base.zig +++ b/src/bun.js/base.zig @@ -266,58 +266,21 @@ pub const To = struct { // Recursion can stack overflow here if (comptime std.meta.trait.isSlice(Type)) { - const Child = std.meta.Child(Type); - - const prefill = 32; - if (value.len <= prefill) { - var array: [prefill]JSC.C.JSValueRef = undefined; - var i: u8 = 0; - const len = @min(@as(u8, @intCast(value.len)), prefill); - while (i < len and exception.* == null) : (i += 1) { - array[i] = if (comptime Child == JSC.C.JSValueRef) - value[i] - else - To.JS.withType(Child, value[i], context, exception); - } - - if (exception.* != null) { - return null; - } - - // TODO: this function copies to a MarkedArgumentsBuffer - // That copy is unnecessary. - const obj = JSC.C.JSObjectMakeArray(context, len, &array, exception); - - if (exception.* != null) { - return null; - } - return obj; - } - - { - var array = bun.default_allocator.alloc(JSC.C.JSValueRef, value.len) catch unreachable; - defer bun.default_allocator.free(array); - var i: usize = 0; - while (i < value.len and exception.* == null) : (i += 1) { - array[i] = if (comptime Child == JSC.C.JSValueRef) - value[i] - else - To.JS.withType(Child, value[i], context, exception); - } + const Child = comptime std.meta.Child(Type); - if (exception.* != null) { - return null; - } + var array = JSC.JSValue.createEmptyArray(context, value.len); + for (value, 0..) |item, i| { + array.putIndex( + context, + @truncate(i), + JSC.JSValue.c(To.JS.withType(Child, item, context, exception)), + ); - // TODO: this function copies to a MarkedArgumentsBuffer - // That copy is unnecessary. - const obj = JSC.C.JSObjectMakeArray(context, value.len, array.ptr, exception); if (exception.* != null) { return null; } - - return obj; } + return array.asObjectRef(); } if (comptime std.meta.trait.isZigString(Type)) { @@ -4004,78 +3967,7 @@ pub const FilePoll = struct { } }; -pub const Strong = extern struct { - ref: ?*JSC.napi.Ref = null, - - pub fn init() Strong { - return .{}; - } - - pub fn create( - value: JSC.JSValue, - globalThis: *JSC.JSGlobalObject, - ) Strong { - var str = Strong.init(); - if (value != .zero) - str.set(globalThis, value); - return str; - } - - pub fn get(this: *Strong) ?JSValue { - var ref = this.ref orelse return null; - const result = ref.get(); - if (result == .zero) { - return null; - } - - return result; - } - - pub fn swap(this: *Strong) JSValue { - var ref = this.ref orelse return .zero; - const result = ref.get(); - if (result == .zero) { - return .zero; - } - - ref.set(.zero); - return result; - } - - pub fn has(this: *Strong) bool { - var ref = this.ref orelse return false; - return ref.get() != .zero; - } - - pub fn trySwap(this: *Strong) ?JSValue { - const result = this.swap(); - if (result == .zero) { - return null; - } - - return result; - } - - pub fn set(this: *Strong, globalThis: *JSC.JSGlobalObject, value: JSValue) void { - var ref: *JSC.napi.Ref = this.ref orelse { - if (value == .zero) return; - this.ref = JSC.napi.Ref.create(globalThis, value); - return; - }; - ref.set(value); - } - - pub fn clear(this: *Strong) void { - var ref: *JSC.napi.Ref = this.ref orelse return; - ref.set(JSC.JSValue.zero); - } - - pub fn deinit(this: *Strong) void { - var ref: *JSC.napi.Ref = this.ref orelse return; - this.ref = null; - ref.destroy(); - } -}; +pub const Strong = @import("./Strong.zig").Strong; pub const BinaryType = enum { Buffer, diff --git a/src/bun.js/bindings/BunJSCModule.cpp b/src/bun.js/bindings/BunJSCModule.cpp deleted file mode 100644 index a145f51c5dde7b..00000000000000 --- a/src/bun.js/bindings/BunJSCModule.cpp +++ /dev/null @@ -1,641 +0,0 @@ -#include "root.h" - -#include "JavaScriptCore/JavaScript.h" -#include "wtf/FileSystem.h" -#include "wtf/MemoryFootprint.h" -#include "wtf/text/WTFString.h" -#include "JavaScriptCore/CodeBlock.h" -#include "JavaScriptCore/JSCInlines.h" -#include "JavaScriptCore/TestRunnerUtils.h" -#include "JavaScriptCore/JIT.h" -#include "JavaScriptCore/APICast.h" -#include "JavaScriptCore/JSBasePrivate.h" -#include "JavaScriptCore/ObjectConstructor.h" -#include "JavaScriptCore/AggregateError.h" -#include "JavaScriptCore/BytecodeIndex.h" -#include "JavaScriptCore/CallFrameInlines.h" -#include "JavaScriptCore/ClassInfo.h" -#include "JavaScriptCore/CodeBlock.h" -#include "JavaScriptCore/Completion.h" -#include "JavaScriptCore/Error.h" -#include "JavaScriptCore/ErrorInstance.h" -#include "JavaScriptCore/HeapSnapshotBuilder.h" -#include "JavaScriptCore/JSONObject.h" -#include "JavaScriptCore/DeferTermination.h" -#include "JavaScriptCore/SamplingProfiler.h" -#include "JavaScriptCore/VMTrapsInlines.h" -#include "SerializedScriptValue.h" -#include "ExceptionOr.h" - -#if ENABLE(REMOTE_INSPECTOR) -#include "JavaScriptCore/RemoteInspectorServer.h" -#endif - -#include "mimalloc.h" -#include "JSDOMConvertBase.h" - -using namespace JSC; -using namespace WTF; -using namespace WebCore; - -JSC_DECLARE_HOST_FUNCTION(functionStartRemoteDebugger); -JSC_DEFINE_HOST_FUNCTION(functionStartRemoteDebugger, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ -#if ENABLE(REMOTE_INSPECTOR) - static const char* defaultHost = "127.0.0.1\0"; - static uint16_t defaultPort = 9230; // node + 1 - auto& vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - - JSC::JSValue hostValue = callFrame->argument(0); - JSC::JSValue portValue = callFrame->argument(1); - const char* host = defaultHost; - if (hostValue.isString()) { - - auto str = hostValue.toWTFString(globalObject); - if (!str.isEmpty()) - host = toCString(str).data(); - } else if (!hostValue.isUndefined()) { - throwVMError(globalObject, scope, createTypeError(globalObject, "host must be a string"_s)); - return JSC::JSValue::encode(JSC::jsUndefined()); - } - - uint16_t port = defaultPort; - if (portValue.isNumber()) { - auto port_int = portValue.toUInt32(globalObject); - if (!(port_int > 0 && port_int < 65536)) { - throwVMError(globalObject, scope, createRangeError(globalObject, "port must be between 0 and 65535"_s)); - return JSC::JSValue::encode(JSC::jsUndefined()); - } - port = port_int; - } else if (!portValue.isUndefined()) { - throwVMError(globalObject, scope, createTypeError(globalObject, "port must be a number between 0 and 65535"_s)); - return JSC::JSValue::encode(JSC::jsUndefined()); - } - - globalObject->setInspectable(true); - auto& server = Inspector::RemoteInspectorServer::singleton(); - if (!server.start(reinterpret_cast(host), port)) { - throwVMError(globalObject, scope, createError(globalObject, "Failed to start server \""_s + host + ":"_s + port + "\". Is port already in use?"_s)); - return JSC::JSValue::encode(JSC::jsUndefined()); - } - - RELEASE_AND_RETURN(scope, JSC::JSValue::encode(JSC::jsUndefined())); -#else - auto& vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - throwVMError(globalObject, scope, createTypeError(globalObject, "Remote inspector is not enabled in this build of Bun"_s)); - return JSC::JSValue::encode(JSC::jsUndefined()); -#endif -} - -JSC_DECLARE_HOST_FUNCTION(functionDescribe); -JSC_DEFINE_HOST_FUNCTION(functionDescribe, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - VM& vm = globalObject->vm(); - if (callFrame->argumentCount() < 1) - return JSValue::encode(jsUndefined()); - return JSValue::encode(jsString(vm, toString(callFrame->argument(0)))); -} - -JSC_DECLARE_HOST_FUNCTION(functionDescribeArray); -JSC_DEFINE_HOST_FUNCTION(functionDescribeArray, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - if (callFrame->argumentCount() < 1) - return JSValue::encode(jsUndefined()); - VM& vm = globalObject->vm(); - JSObject* object = jsDynamicCast(callFrame->argument(0)); - if (!object) - return JSValue::encode(jsNontrivialString(vm, ""_s)); - return JSValue::encode(jsNontrivialString(vm, toString("butterfly()), "; public length: ", object->getArrayLength(), "; vector length: ", object->getVectorLength(), ">"))); -} - -JSC_DECLARE_HOST_FUNCTION(functionGCAndSweep); -JSC_DEFINE_HOST_FUNCTION(functionGCAndSweep, (JSGlobalObject * globalObject, CallFrame*)) -{ - VM& vm = globalObject->vm(); - JSLockHolder lock(vm); - vm.heap.collectNow(Sync, CollectionScope::Full); - return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection())); -} - -JSC_DECLARE_HOST_FUNCTION(functionFullGC); -JSC_DEFINE_HOST_FUNCTION(functionFullGC, (JSGlobalObject * globalObject, CallFrame*)) -{ - VM& vm = globalObject->vm(); - JSLockHolder lock(vm); - vm.heap.collectSync(CollectionScope::Full); - return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection())); -} - -JSC_DECLARE_HOST_FUNCTION(functionEdenGC); -JSC_DEFINE_HOST_FUNCTION(functionEdenGC, (JSGlobalObject * globalObject, CallFrame*)) -{ - VM& vm = globalObject->vm(); - JSLockHolder lock(vm); - vm.heap.collectSync(CollectionScope::Eden); - return JSValue::encode(jsNumber(vm.heap.sizeAfterLastEdenCollection())); -} - -JSC_DECLARE_HOST_FUNCTION(functionHeapSize); -JSC_DEFINE_HOST_FUNCTION(functionHeapSize, (JSGlobalObject * globalObject, CallFrame*)) -{ - VM& vm = globalObject->vm(); - JSLockHolder lock(vm); - return JSValue::encode(jsNumber(vm.heap.size())); -} - -class JSCMemoryFootprint : public JSDestructibleObject { - using Base = JSDestructibleObject; - -public: - template - static CompleteSubspace* subspaceFor(VM& vm) - { - return &vm.destructibleObjectSpace(); - } - - JSCMemoryFootprint(VM& vm, Structure* structure) - : Base(vm, structure) - { - } - - static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype) - { - return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info()); - } - - static JSCMemoryFootprint* create(VM& vm, JSGlobalObject* globalObject) - { - Structure* structure = createStructure(vm, globalObject, jsNull()); - JSCMemoryFootprint* footprint = new (NotNull, allocateCell(vm)) JSCMemoryFootprint(vm, structure); - footprint->finishCreation(vm); - return footprint; - } - - void finishCreation(VM& vm) - { - Base::finishCreation(vm); - - auto addProperty = [&](VM& vm, ASCIILiteral name, JSValue value) { - JSCMemoryFootprint::addProperty(vm, name, value); - }; - - size_t elapsed_msecs = 0; - size_t user_msecs = 0; - size_t system_msecs = 0; - size_t current_rss = 0; - size_t peak_rss = 0; - size_t current_commit = 0; - size_t peak_commit = 0; - size_t page_faults = 0; - - mi_process_info(&elapsed_msecs, &user_msecs, &system_msecs, - ¤t_rss, &peak_rss, - ¤t_commit, &peak_commit, &page_faults); - - addProperty(vm, "current"_s, jsNumber(current_rss)); - addProperty(vm, "peak"_s, jsNumber(peak_rss)); - addProperty(vm, "currentCommit"_s, jsNumber(current_commit)); - addProperty(vm, "peakCommit"_s, jsNumber(peak_commit)); - addProperty(vm, "pageFaults"_s, jsNumber(page_faults)); - } - - DECLARE_INFO; - -private: - void addProperty(VM& vm, ASCIILiteral name, JSValue value) - { - Identifier identifier = Identifier::fromString(vm, name); - putDirect(vm, identifier, value); - } -}; - -const ClassInfo JSCMemoryFootprint::s_info = { "MemoryFootprint"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSCMemoryFootprint) }; - -JSC_DECLARE_HOST_FUNCTION(functionMemoryUsageStatistics); -JSC_DEFINE_HOST_FUNCTION(functionMemoryUsageStatistics, (JSGlobalObject * globalObject, CallFrame*)) -{ - - auto& vm = globalObject->vm(); - JSC::DisallowGC disallowGC; - - // this is a C API function - auto* stats = toJS(JSGetMemoryUsageStatistics(toRef(globalObject))); - - if (JSValue heapSizeValue = stats->getDirect(vm, Identifier::fromString(vm, "heapSize"_s))) { - ASSERT(heapSizeValue.isNumber()); - if (heapSizeValue.toInt32(globalObject) == 0) { - vm.heap.collectNow(Sync, CollectionScope::Full); - stats = toJS(JSGetMemoryUsageStatistics(toRef(globalObject))); - } - } - - // This is missing from the C API - JSC::JSObject* protectedCounts = constructEmptyObject(globalObject); - auto typeCounts = *vm.heap.protectedObjectTypeCounts(); - for (auto& it : typeCounts) - protectedCounts->putDirect(vm, Identifier::fromLatin1(vm, it.key), jsNumber(it.value)); - - stats->putDirect(vm, Identifier::fromLatin1(vm, "protectedObjectTypeCounts"_s), protectedCounts); - return JSValue::encode(stats); -} - -JSC_DECLARE_HOST_FUNCTION(functionCreateMemoryFootprint); -JSC_DEFINE_HOST_FUNCTION(functionCreateMemoryFootprint, (JSGlobalObject * globalObject, CallFrame*)) -{ - VM& vm = globalObject->vm(); - JSLockHolder lock(vm); - return JSValue::encode(JSCMemoryFootprint::create(vm, globalObject)); -} - -JSC_DECLARE_HOST_FUNCTION(functionNeverInlineFunction); -JSC_DEFINE_HOST_FUNCTION(functionNeverInlineFunction, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - return JSValue::encode(setNeverInline(globalObject, callFrame)); -} - -extern "C" bool Bun__mkdirp(JSC::JSGlobalObject*, const char*); - -JSC_DECLARE_HOST_FUNCTION(functionStartSamplingProfiler); -JSC_DEFINE_HOST_FUNCTION(functionStartSamplingProfiler, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) -{ - JSC::VM& vm = globalObject->vm(); - JSC::SamplingProfiler& samplingProfiler = vm.ensureSamplingProfiler(WTF::Stopwatch::create()); - - JSC::JSValue directoryValue = callFrame->argument(0); - JSC::JSValue sampleValue = callFrame->argument(1); - - auto scope = DECLARE_THROW_SCOPE(vm); - if (directoryValue.isString()) { - auto path = directoryValue.toWTFString(globalObject); - if (!path.isEmpty()) { - StringPrintStream pathOut; - auto pathCString = toCString(String(path)); - if (!Bun__mkdirp(globalObject, pathCString.data())) { - throwVMError(globalObject, scope, createTypeError(globalObject, "directory couldn't be created"_s)); - return JSC::JSValue::encode(jsUndefined()); - } - - Options::samplingProfilerPath() = pathCString.data(); - samplingProfiler.registerForReportAtExit(); - } - } - if (sampleValue.isNumber()) { - unsigned sampleInterval = sampleValue.toUInt32(globalObject); - samplingProfiler.setTimingInterval(Seconds::fromMicroseconds(sampleInterval)); - } - - samplingProfiler.noticeCurrentThreadAsJSCExecutionThread(); - samplingProfiler.start(); - return JSC::JSValue::encode(jsUndefined()); -} - -JSC_DECLARE_HOST_FUNCTION(functionSamplingProfilerStackTraces); -JSC_DEFINE_HOST_FUNCTION(functionSamplingProfilerStackTraces, (JSC::JSGlobalObject * globalObject, JSC::CallFrame*)) -{ - JSC::VM& vm = globalObject->vm(); - JSC::DeferTermination deferScope(vm); - auto scope = DECLARE_THROW_SCOPE(vm); - - if (!vm.samplingProfiler()) - return JSC::JSValue::encode(throwException(globalObject, scope, createError(globalObject, "Sampling profiler was never started"_s))); - - WTF::String jsonString = vm.samplingProfiler()->stackTracesAsJSON(); - JSC::EncodedJSValue result = JSC::JSValue::encode(JSONParse(globalObject, jsonString)); - scope.releaseAssertNoException(); - return result; -} - -JSC_DECLARE_HOST_FUNCTION(functionGetRandomSeed); -JSC_DEFINE_HOST_FUNCTION(functionGetRandomSeed, (JSGlobalObject * globalObject, CallFrame*)) -{ - return JSValue::encode(jsNumber(globalObject->weakRandom().seed())); -} - -JSC_DECLARE_HOST_FUNCTION(functionSetRandomSeed); -JSC_DEFINE_HOST_FUNCTION(functionSetRandomSeed, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - VM& vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - - unsigned seed = callFrame->argument(0).toUInt32(globalObject); - RETURN_IF_EXCEPTION(scope, encodedJSValue()); - globalObject->weakRandom().setSeed(seed); - return JSValue::encode(jsUndefined()); -} - -JSC_DECLARE_HOST_FUNCTION(functionIsRope); -JSC_DEFINE_HOST_FUNCTION(functionIsRope, (JSGlobalObject*, CallFrame* callFrame)) -{ - JSValue argument = callFrame->argument(0); - if (!argument.isString()) - return JSValue::encode(jsBoolean(false)); - const StringImpl* impl = asString(argument)->tryGetValueImpl(); - return JSValue::encode(jsBoolean(!impl)); -} - -JSC_DECLARE_HOST_FUNCTION(functionCallerSourceOrigin); -JSC_DEFINE_HOST_FUNCTION(functionCallerSourceOrigin, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - VM& vm = globalObject->vm(); - SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm); - if (sourceOrigin.url().isNull()) - return JSValue::encode(jsNull()); - return JSValue::encode(jsString(vm, sourceOrigin.string())); -} - -JSC_DECLARE_HOST_FUNCTION(functionNoFTL); -JSC_DEFINE_HOST_FUNCTION(functionNoFTL, (JSGlobalObject*, CallFrame* callFrame)) -{ - if (callFrame->argumentCount()) { - FunctionExecutable* executable = getExecutableForFunction(callFrame->argument(0)); - if (executable) - executable->setNeverFTLOptimize(true); - } - return JSValue::encode(jsUndefined()); -} - -JSC_DECLARE_HOST_FUNCTION(functionNoOSRExitFuzzing); -JSC_DEFINE_HOST_FUNCTION(functionNoOSRExitFuzzing, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - return JSValue::encode(setCannotUseOSRExitFuzzing(globalObject, callFrame)); -} - -JSC_DECLARE_HOST_FUNCTION(functionOptimizeNextInvocation); -JSC_DEFINE_HOST_FUNCTION(functionOptimizeNextInvocation, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - return JSValue::encode(optimizeNextInvocation(globalObject, callFrame)); -} - -JSC_DECLARE_HOST_FUNCTION(functionNumberOfDFGCompiles); -JSC_DEFINE_HOST_FUNCTION(functionNumberOfDFGCompiles, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - return JSValue::encode(numberOfDFGCompiles(globalObject, callFrame)); -} - -JSC_DECLARE_HOST_FUNCTION(functionReleaseWeakRefs); -JSC_DEFINE_HOST_FUNCTION(functionReleaseWeakRefs, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - globalObject->vm().finalizeSynchronousJSExecution(); - return JSValue::encode(jsUndefined()); -} - -JSC_DECLARE_HOST_FUNCTION(functionTotalCompileTime); -JSC_DEFINE_HOST_FUNCTION(functionTotalCompileTime, (JSGlobalObject*, CallFrame*)) -{ - return JSValue::encode(jsNumber(JIT::totalCompileTime().milliseconds())); -} - -JSC_DECLARE_HOST_FUNCTION(functionGetProtectedObjects); -JSC_DEFINE_HOST_FUNCTION(functionGetProtectedObjects, (JSGlobalObject * globalObject, CallFrame*)) -{ - MarkedArgumentBuffer list; - size_t result = 0; - globalObject->vm().heap.forEachProtectedCell( - [&](JSCell* cell) { - list.append(cell); - }); - RELEASE_ASSERT(!list.hasOverflowed()); - return JSC::JSValue::encode(constructArray(globalObject, static_cast(nullptr), list)); -} - -JSC_DECLARE_HOST_FUNCTION(functionReoptimizationRetryCount); -JSC_DEFINE_HOST_FUNCTION(functionReoptimizationRetryCount, (JSGlobalObject*, CallFrame* callFrame)) -{ - if (callFrame->argumentCount() < 1) - return JSValue::encode(jsUndefined()); - - CodeBlock* block = getSomeBaselineCodeBlockForFunction(callFrame->argument(0)); - if (!block) - return JSValue::encode(jsNumber(0)); - - return JSValue::encode(jsNumber(block->reoptimizationRetryCounter())); -} - -extern "C" void Bun__drainMicrotasks(); - -JSC_DECLARE_HOST_FUNCTION(functionDrainMicrotasks); -JSC_DEFINE_HOST_FUNCTION(functionDrainMicrotasks, (JSGlobalObject * globalObject, CallFrame*)) -{ - VM& vm = globalObject->vm(); - vm.drainMicrotasks(); - Bun__drainMicrotasks(); - return JSValue::encode(jsUndefined()); -} - -JSC_DEFINE_HOST_FUNCTION(functionSetTimeZone, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - VM& vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - - if (callFrame->argumentCount() < 1) { - throwTypeError(globalObject, scope, "setTimeZone requires a timezone string"_s); - return encodedJSValue(); - } - - if (!callFrame->argument(0).isString()) { - throwTypeError(globalObject, scope, "setTimeZone requires a timezone string"_s); - return encodedJSValue(); - } - - String timeZoneName = callFrame->argument(0).toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, encodedJSValue()); - - double time = callFrame->argument(1).toNumber(globalObject); - RETURN_IF_EXCEPTION(scope, encodedJSValue()); - - if (!WTF::setTimeZoneOverride(timeZoneName)) { - throwTypeError(globalObject, scope, makeString("Invalid timezone: \""_s, timeZoneName, "\""_s)); - return encodedJSValue(); - } - vm.dateCache.resetIfNecessarySlow(); - WTF::Vector buffer; - WTF::getTimeZoneOverride(buffer); - WTF::String timeZoneString(buffer.data(), buffer.size()); - return JSValue::encode(jsString(vm, timeZoneString)); -} - -JSC_DEFINE_HOST_FUNCTION(functionRunProfiler, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - JSC::VM& vm = globalObject->vm(); - JSC::SamplingProfiler& samplingProfiler = vm.ensureSamplingProfiler(WTF::Stopwatch::create()); - - JSC::JSValue callbackValue = callFrame->argument(0); - auto throwScope = DECLARE_THROW_SCOPE(vm); - if (callbackValue.isUndefinedOrNull() || !callbackValue.isCallable()) { - throwException(globalObject, throwScope, createTypeError(globalObject, "First argument must be a function."_s)); - return JSValue::encode(JSValue {}); - } - - JSC::JSFunction* function = jsCast(callbackValue); - - JSC::JSValue sampleValue = callFrame->argument(1); - if (sampleValue.isNumber()) { - unsigned sampleInterval = sampleValue.toUInt32(globalObject); - samplingProfiler.setTimingInterval(Seconds::fromMicroseconds(sampleInterval)); - } - - JSC::CallData callData = JSC::getCallData(function); - MarkedArgumentBuffer args; - - samplingProfiler.noticeCurrentThreadAsJSCExecutionThread(); - samplingProfiler.start(); - JSC::call(globalObject, function, callData, JSC::jsUndefined(), args); - samplingProfiler.pause(); - if (throwScope.exception()) { - samplingProfiler.shutdown(); - samplingProfiler.clearData(); - return JSValue::encode(JSValue {}); - } - - StringPrintStream topFunctions; - samplingProfiler.reportTopFunctions(topFunctions); - - StringPrintStream byteCodes; - samplingProfiler.reportTopBytecodes(byteCodes); - - JSValue stackTraces = JSONParse(globalObject, samplingProfiler.stackTracesAsJSON()); - - samplingProfiler.shutdown(); - samplingProfiler.clearData(); - - JSObject* result = constructEmptyObject(globalObject, globalObject->objectPrototype(), 3); - result->putDirect(vm, Identifier::fromString(vm, "functions"_s), jsString(vm, topFunctions.toString())); - result->putDirect(vm, Identifier::fromString(vm, "bytecodes"_s), jsString(vm, byteCodes.toString())); - result->putDirect(vm, Identifier::fromString(vm, "stackTraces"_s), stackTraces); - - return JSValue::encode(result); -} - -JSC_DECLARE_HOST_FUNCTION(functionGenerateHeapSnapshotForDebugging); -JSC_DEFINE_HOST_FUNCTION(functionGenerateHeapSnapshotForDebugging, (JSGlobalObject * globalObject, CallFrame*)) -{ - VM& vm = globalObject->vm(); - JSLockHolder lock(vm); - DeferTermination deferScope(vm); - auto scope = DECLARE_THROW_SCOPE(vm); - String jsonString; - { - DeferGCForAWhile deferGC(vm); // Prevent concurrent GC from interfering with the full GC that the snapshot does. - - HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler(), HeapSnapshotBuilder::SnapshotType::GCDebuggingSnapshot); - snapshotBuilder.buildSnapshot(); - - jsonString = snapshotBuilder.json(); - } - scope.releaseAssertNoException(); - - return JSValue::encode(JSONParse(globalObject, WTFMove(jsonString))); -} - -JSC_DEFINE_HOST_FUNCTION(functionSerialize, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) -{ - auto* globalObject = jsCast(lexicalGlobalObject); - JSC::VM& vm = globalObject->vm(); - auto throwScope = DECLARE_THROW_SCOPE(vm); - - JSValue value = callFrame->argument(0); - JSValue optionsObject = callFrame->argument(1); - bool asNodeBuffer = false; - if (optionsObject.isObject()) { - JSC::JSObject* options = optionsObject.getObject(); - if (JSC::JSValue binaryTypeValue = options->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "binaryType"_s))) { - if (!binaryTypeValue.isString()) { - throwTypeError(globalObject, throwScope, "binaryType must be a string"_s); - return JSValue::encode(jsUndefined()); - } - - asNodeBuffer = binaryTypeValue.toWTFString(globalObject) == "nodebuffer"_s; - RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); - } - } - - Vector> transferList; - - ExceptionOr> serialized = SerializedScriptValue::create(*globalObject, value, WTFMove(transferList)); - - if (serialized.hasException()) { - WebCore::propagateException(*globalObject, throwScope, serialized.releaseException()); - return JSValue::encode(jsUndefined()); - } - - auto serializedValue = serialized.releaseReturnValue(); - auto arrayBuffer = serializedValue->toArrayBuffer(); - - if (asNodeBuffer) { - size_t byteLength = arrayBuffer->byteLength(); - JSC::JSUint8Array* uint8Array = JSC::JSUint8Array::create(lexicalGlobalObject, globalObject->JSBufferSubclassStructure(), WTFMove(arrayBuffer), 0, byteLength); - return JSValue::encode(uint8Array); - } - - if (arrayBuffer->isShared()) { - return JSValue::encode(JSArrayBuffer::create(vm, globalObject->arrayBufferStructureWithSharingMode(), WTFMove(arrayBuffer))); - } - - return JSValue::encode(JSArrayBuffer::create(vm, globalObject->arrayBufferStructure(), WTFMove(arrayBuffer))); -} -JSC_DEFINE_HOST_FUNCTION(functionDeserialize, (JSGlobalObject * globalObject, CallFrame* callFrame)) -{ - JSC::VM& vm = globalObject->vm(); - auto throwScope = DECLARE_THROW_SCOPE(vm); - JSValue value = callFrame->argument(0); - - JSValue result; - - if (auto* jsArrayBuffer = jsDynamicCast(value)) { - result = SerializedScriptValue::fromArrayBuffer(*globalObject, globalObject, jsArrayBuffer->impl(), 0, jsArrayBuffer->impl()->byteLength()); - } else if (auto* view = jsDynamicCast(value)) { - auto arrayBuffer = view->possiblySharedImpl()->possiblySharedBuffer(); - result = SerializedScriptValue::fromArrayBuffer(*globalObject, globalObject, arrayBuffer.get(), view->byteOffset(), view->byteLength()); - } else { - throwTypeError(globalObject, throwScope, "First argument must be an ArrayBuffer"_s); - return JSValue::encode(jsUndefined()); - } - - RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined())); - RELEASE_AND_RETURN(throwScope, JSValue::encode(result)); -} - -JSC::JSObject* createJSCModule(JSC::JSGlobalObject* globalObject) -{ - VM& vm = globalObject->vm(); - JSC::JSObject* object = nullptr; - - { - JSC::ObjectInitializationScope initializationScope(vm); - object = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 23); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "callerSourceOrigin"_s), 1, functionCallerSourceOrigin, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "describe"_s), 1, functionDescribe, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "describeArray"_s), 1, functionDescribeArray, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "drainMicrotasks"_s), 1, functionDrainMicrotasks, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "edenGC"_s), 1, functionEdenGC, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "fullGC"_s), 1, functionFullGC, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "gcAndSweep"_s), 1, functionGCAndSweep, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "getRandomSeed"_s), 1, functionGetRandomSeed, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "heapSize"_s), 1, functionHeapSize, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "heapStats"_s), 1, functionMemoryUsageStatistics, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "startSamplingProfiler"_s), 1, functionStartSamplingProfiler, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "samplingProfilerStackTraces"_s), 1, functionSamplingProfilerStackTraces, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "noInline"_s), 1, functionNeverInlineFunction, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "isRope"_s), 1, functionIsRope, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "memoryUsage"_s), 1, functionCreateMemoryFootprint, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "noFTL"_s), 1, functionNoFTL, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "noOSRExitFuzzing"_s), 1, functionNoOSRExitFuzzing, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "numberOfDFGCompiles"_s), 1, functionNumberOfDFGCompiles, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "optimizeNextInvocation"_s), 1, functionOptimizeNextInvocation, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "releaseWeakRefs"_s), 1, functionReleaseWeakRefs, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "reoptimizationRetryCount"_s), 1, functionReoptimizationRetryCount, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "setRandomSeed"_s), 1, functionSetRandomSeed, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "startRemoteDebugger"_s), 2, functionStartRemoteDebugger, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "totalCompileTime"_s), 1, functionTotalCompileTime, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "getProtectedObjects"_s), 1, functionGetProtectedObjects, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "generateHeapSnapshotForDebugging"_s), 0, functionGenerateHeapSnapshotForDebugging, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "profile"_s), 0, functionRunProfiler, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "setTimeZone"_s), 0, functionSetTimeZone, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "serialize"_s), 0, functionSerialize, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "deserialize"_s), 0, functionDeserialize, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete | 0); - } - - return object; -} diff --git a/src/bun.js/bindings/BunJSCModule.h b/src/bun.js/bindings/BunJSCModule.h deleted file mode 100644 index 7df47a56640ae4..00000000000000 --- a/src/bun.js/bindings/BunJSCModule.h +++ /dev/null @@ -1,4 +0,0 @@ -#include "root.h" -#include "JavaScriptCore/JSObject.h" - -JSC::JSObject* createJSCModule(JSC::JSGlobalObject* globalObject); \ No newline at end of file diff --git a/src/bun.js/bindings/BunString.cpp b/src/bun.js/bindings/BunString.cpp index 714f10080cdb53..09b545cba08807 100644 --- a/src/bun.js/bindings/BunString.cpp +++ b/src/bun.js/bindings/BunString.cpp @@ -6,6 +6,7 @@ #include "wtf/text/ExternalStringImpl.h" #include "GCDefferalContext.h" #include +#include using namespace JSC; @@ -25,11 +26,23 @@ extern "C" void Bun__WTFStringImpl__ref(WTF::StringImpl* impl) extern "C" bool BunString__fromJS(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue encodedValue, BunString* bunString) { + JSC::JSValue value = JSC::JSValue::decode(encodedValue); *bunString = Bun::toString(globalObject, value); return bunString->tag != BunStringTag::Dead; } +extern "C" BunString BunString__createAtom(const char* bytes, size_t length) +{ + if (simdutf::validate_ascii(bytes, length)) { + auto atom = makeAtomString(String(StringImpl::createWithoutCopying(bytes, length))); + atom.impl()->ref(); + return { BunStringTag::WTFStringImpl, { .wtf = atom.impl() } }; + } + + return { BunStringTag::Dead, {} }; +} + namespace Bun { JSC::JSValue toJS(JSC::JSGlobalObject* globalObject, BunString bunString) { @@ -83,6 +96,17 @@ BunString fromJS(JSC::JSGlobalObject* globalObject, JSValue value) return { BunStringTag::WTFStringImpl, { .wtf = wtfString.impl() } }; } +extern "C" void BunString__toThreadSafe(BunString* str) +{ + if (str->tag == BunStringTag::WTFStringImpl) { + auto impl = str->impl.wtf->isolatedCopy(); + if (impl.ptr() != str->impl.wtf) { + impl->ref(); + str->impl.wtf = &impl.leakRef(); + } + } +} + BunString toString(JSC::JSGlobalObject* globalObject, JSValue value) { return fromJS(globalObject, value); @@ -179,7 +203,6 @@ extern "C" BunString BunString__fromUTF16Unitialized(size_t length) if (UNLIKELY(!ptr)) return { BunStringTag::Dead }; - impl->ref(); return { BunStringTag::WTFStringImpl, { .wtf = &impl.leakRef() } }; } @@ -190,7 +213,6 @@ extern "C" BunString BunString__fromLatin1Unitialized(size_t length) auto impl = WTF::StringImpl::createUninitialized(latin1Length, ptr); if (UNLIKELY(!ptr)) return { BunStringTag::Dead }; - impl->ref(); return { BunStringTag::WTFStringImpl, { .wtf = &impl.leakRef() } }; } @@ -256,40 +278,28 @@ extern "C" EncodedJSValue BunString__createArray( auto& vm = globalObject->vm(); auto throwScope = DECLARE_THROW_SCOPE(vm); - // We must do this or Bun.gc(true) in a loop creating large arrays of strings will crash due to GC'ing. - MarkedArgumentBuffer arguments; - JSC::ObjectInitializationScope scope(vm); - GCDeferralContext context(vm); - - arguments.fill(length, [&](JSC::JSValue* value) { - const BunString* end = ptr + length; - while (ptr != end) { - *value++ = Bun::toJS(globalObject, *ptr++); - } - }); - - if (JSC::JSArray* array = JSC::JSArray::tryCreateUninitializedRestricted( - scope, - globalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous), - length)) { + // Using tryCreateUninitialized here breaks stuff.. + // https://github.com/oven-sh/bun/issues/3931 + JSC::JSArray* array = constructEmptyArray(globalObject, nullptr, length); + if (!array) { + JSC::throwOutOfMemoryError(globalObject, throwScope); + RELEASE_AND_RETURN(throwScope, JSValue::encode(JSC::JSValue())); + } - for (size_t i = 0; i < length; ++i) { - array->initializeIndex(scope, i, arguments.at(i)); - } - return JSValue::encode(array); + for (size_t i = 0; i < length; ++i) { + array->putDirectIndex(globalObject, i, Bun::toJS(globalObject, *ptr++)); } - JSC::throwOutOfMemoryError(globalObject, throwScope); - RELEASE_AND_RETURN(throwScope, JSValue::encode(JSC::JSValue())); + return JSValue::encode(array); } extern "C" void BunString__toWTFString(BunString* bunString) { if (bunString->tag == BunStringTag::ZigString) { - if (Zig::isTaggedUTF8Ptr(bunString->impl.zig.ptr)) { - bunString->impl.wtf = Zig::toStringCopy(bunString->impl.zig).impl(); - } else { + if (Zig::isTaggedExternalPtr(bunString->impl.zig.ptr)) { bunString->impl.wtf = Zig::toString(bunString->impl.zig).impl(); + } else { + bunString->impl.wtf = Zig::toStringCopy(bunString->impl.zig).impl(); } bunString->tag = BunStringTag::WTFStringImpl; @@ -299,6 +309,11 @@ extern "C" void BunString__toWTFString(BunString* bunString) } } +extern "C" BunString URL__getFileURLString(BunString* filePath) +{ + return Bun::toStringRef(WTF::URL::fileURLWithFileSystemPath(Bun::toWTFString(*filePath)).stringWithoutFragmentIdentifier()); +} + extern "C" WTF::URL* URL__fromJS(EncodedJSValue encodedValue, JSC::JSGlobalObject* globalObject) { auto throwScope = DECLARE_THROW_SCOPE(globalObject->vm()); @@ -335,7 +350,7 @@ extern "C" BunString URL__getHrefFromJS(EncodedJSValue encodedValue, JSC::JSGlob extern "C" BunString URL__getHref(BunString* input) { - auto str = Bun::toWTFString(*input); + auto&& str = Bun::toWTFString(*input); auto url = WTF::URL(str); if (!url.isValid() || url.isEmpty()) return { BunStringTag::Dead }; @@ -345,7 +360,7 @@ extern "C" BunString URL__getHref(BunString* input) extern "C" WTF::URL* URL__fromString(BunString* input) { - auto str = Bun::toWTFString(*input); + auto&& str = Bun::toWTFString(*input); auto url = WTF::URL(str); if (!url.isValid()) return nullptr; diff --git a/src/bun.js/bindings/BunWorkerGlobalScope.cpp b/src/bun.js/bindings/BunWorkerGlobalScope.cpp index 60b615e183e33d..ef1f70fdfeb026 100644 --- a/src/bun.js/bindings/BunWorkerGlobalScope.cpp +++ b/src/bun.js/bindings/BunWorkerGlobalScope.cpp @@ -1,10 +1,14 @@ #include "config.h" #include "BunWorkerGlobalScope.h" +#include "MessagePortChannelProviderImpl.h" -namespace Bun { -using namespace WebCore; +namespace WebCore { WTF_MAKE_ISO_ALLOCATED_IMPL(GlobalScope); +MessagePortChannelProvider& GlobalScope::messagePortChannelProvider() +{ + return *reinterpret_cast(&MessagePortChannelProviderImpl::singleton()); +} } \ No newline at end of file diff --git a/src/bun.js/bindings/BunWorkerGlobalScope.h b/src/bun.js/bindings/BunWorkerGlobalScope.h index 7672897168195b..fff50d6ec6b1bb 100644 --- a/src/bun.js/bindings/BunWorkerGlobalScope.h +++ b/src/bun.js/bindings/BunWorkerGlobalScope.h @@ -1,3 +1,5 @@ +#pragma once + #include "root.h" #include "EventTarget.h" @@ -7,8 +9,12 @@ #include #include -namespace Bun { -class GlobalScope final : public RefCounted, public EventTargetWithInlineData { +namespace WebCore { + +class MessagePortChannelProvider; +class MessagePortChannelProviderImpl; + +class GlobalScope : public RefCounted, public EventTargetWithInlineData { WTF_MAKE_ISO_ALLOCATED(GlobalScope); public: @@ -33,6 +39,11 @@ class GlobalScope final : public RefCounted, public EventTargetWith void derefEventTarget() final { deref(); } void eventListenersDidChange() final {} + MessagePortChannelProvider& messagePortChannelProvider(); + ScriptExecutionContext* m_context; + +private: + MessagePortChannelProviderImpl* m_messagePortChannelProvider; }; } \ No newline at end of file diff --git a/src/bun.js/bindings/CodeCoverage.cpp b/src/bun.js/bindings/CodeCoverage.cpp new file mode 100644 index 00000000000000..1cb3b6ba20adcc --- /dev/null +++ b/src/bun.js/bindings/CodeCoverage.cpp @@ -0,0 +1,44 @@ +#include "root.h" +#include "ZigSourceProvider.h" +#include + +using namespace JSC; + +extern "C" bool CodeCoverage__withBlocksAndFunctions( + JSC::VM* vmPtr, + JSC::SourceID sourceID, + void* ctx, + bool ignoreSourceMap, + void (*blockCallback)(void* ctx, JSC::BasicBlockRange* range, size_t len, size_t functionOffset, bool ignoreSourceMap)) +{ + + VM& vm = *vmPtr; + + auto basicBlocks = vm.controlFlowProfiler()->getBasicBlocksForSourceIDWithoutFunctionRange( + sourceID, vm); + + if (basicBlocks.isEmpty()) { + blockCallback(ctx, nullptr, 0, 0, ignoreSourceMap); + return true; + } + + size_t functionStartOffset = basicBlocks.size(); + + const Vector>& functionRanges = vm.functionHasExecutedCache()->getFunctionRanges(sourceID); + + basicBlocks.reserveCapacity(functionRanges.size() + basicBlocks.size()); + + for (const auto& functionRange : functionRanges) { + BasicBlockRange range; + range.m_hasExecuted = std::get<0>(functionRange); + range.m_startOffset = static_cast(std::get<1>(functionRange)); + range.m_endOffset = static_cast(std::get<2>(functionRange)); + range.m_executionCount = range.m_hasExecuted + ? 1 + : 0; // This is a hack. We don't actually count this. + basicBlocks.append(range); + } + + blockCallback(ctx, basicBlocks.data(), basicBlocks.size(), functionStartOffset, ignoreSourceMap); + return true; +} diff --git a/src/bun.js/bindings/CommonJSModuleRecord.cpp b/src/bun.js/bindings/CommonJSModuleRecord.cpp index bcae04500393be..a1f5781d706dd9 100644 --- a/src/bun.js/bindings/CommonJSModuleRecord.cpp +++ b/src/bun.js/bindings/CommonJSModuleRecord.cpp @@ -93,7 +93,7 @@ static bool canPerformFastEnumeration(Structure* s) return true; } -static bool evaluateCommonJSModuleOnce(JSC::VM& vm, Zig::GlobalObject* globalObject, JSCommonJSModule* moduleObject, JSString* dirname, JSString* filename, WTF::NakedPtr& exception) +static bool evaluateCommonJSModuleOnce(JSC::VM& vm, Zig::GlobalObject* globalObject, JSCommonJSModule* moduleObject, JSString* dirname, JSValue filename, WTF::NakedPtr& exception) { JSC::Structure* thisObjectStructure = globalObject->commonJSFunctionArgumentsStructure(); JSC::JSObject* thisObject = JSC::constructEmptyObject( @@ -395,7 +395,7 @@ class JSCommonJSModulePrototype final : public JSC::JSNonFinalObject { const JSC::ClassInfo JSCommonJSModulePrototype::s_info = { "Module"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSCommonJSModulePrototype) }; -void JSCommonJSModule::finishCreation(JSC::VM& vm, JSC::JSString* id, JSC::JSString* filename, JSC::JSString* dirname, JSC::JSSourceCode* sourceCode) +void JSCommonJSModule::finishCreation(JSC::VM& vm, JSC::JSString* id, JSValue filename, JSC::JSString* dirname, JSC::JSSourceCode* sourceCode) { Base::finishCreation(vm); ASSERT(inherits(vm, info())); @@ -421,7 +421,7 @@ JSCommonJSModule* JSCommonJSModule::create( JSC::VM& vm, JSC::Structure* structure, JSC::JSString* id, - JSC::JSString* filename, + JSValue filename, JSC::JSString* dirname, JSC::JSSourceCode* sourceCode) { @@ -489,60 +489,10 @@ bool JSCommonJSModule::evaluate( auto throwScope = DECLARE_THROW_SCOPE(vm); generator(globalObject, JSC::Identifier::fromString(vm, key), propertyNames, arguments); RETURN_IF_EXCEPTION(throwScope, false); - - bool needsPut = false; - auto getDefaultValue = [&]() -> JSValue { - size_t defaultValueIndex = propertyNames.find(vm.propertyNames->defaultKeyword); - auto cjsSymbol = Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s)); - - if (defaultValueIndex != notFound && propertyNames.contains(cjsSymbol)) { - JSValue current = arguments.at(defaultValueIndex); - needsPut = true; - return current; - } - - size_t count = propertyNames.size(); - JSValue existingDefaultObject = this->getIfPropertyExists(globalObject, WebCore::clientData(vm)->builtinNames().exportsPublicName()); - JSObject* defaultObject; - - if (existingDefaultObject && existingDefaultObject.isObject()) { - defaultObject = jsCast(existingDefaultObject); - } else { - defaultObject = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype()); - needsPut = true; - } - - for (size_t i = 0; i < count; ++i) { - auto prop = propertyNames[i]; - unsigned attributes = 0; - - JSValue value = arguments.at(i); - - if (prop.isSymbol()) { - attributes |= JSC::PropertyAttribute::DontEnum; - } - - if (value.isCell() && value.isCallable()) { - attributes |= JSC::PropertyAttribute::Function; - } - - defaultObject->putDirect(vm, prop, value, attributes); - } - - return defaultObject; - }; - - JSValue defaultValue = getDefaultValue(); - if (needsPut) { - unsigned attributes = 0; - - if (defaultValue.isCell() && defaultValue.isCallable()) { - attributes |= JSC::PropertyAttribute::Function; - } - - this->putDirect(vm, WebCore::clientData(vm)->builtinNames().exportsPublicName(), defaultValue, attributes); - } - + // This goes off of the assumption that you only call this `evaluate` using a generator that explicity + // assigns the `default` export first. + JSValue defaultValue = arguments.at(0); + this->putDirect(vm, WebCore::clientData(vm)->builtinNames().exportsPublicName(), defaultValue, 0); this->hasEvaluated = true; RELEASE_AND_RETURN(throwScope, true); } @@ -556,10 +506,6 @@ void JSCommonJSModule::toSyntheticSource(JSC::JSGlobalObject* globalObject, auto& vm = globalObject->vm(); - // This exists to tell ImportMetaObject.ts that this is a CommonJS module. - exportNames.append(Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s))); - exportValues.append(jsNumber(0)); - // Bun's intepretation of the "__esModule" annotation: // // - If a "default" export does not exist OR the __esModule annotation is not present, then we @@ -820,10 +766,11 @@ void RequireResolveFunctionPrototype::finishCreation(JSC::VM& vm) bool JSCommonJSModule::evaluate( Zig::GlobalObject* globalObject, const WTF::String& key, - ResolvedSource source) + ResolvedSource source, + bool isBuiltIn) { auto& vm = globalObject->vm(); - auto sourceProvider = Zig::SourceProvider::create(jsCast(globalObject), source, JSC::SourceProviderSourceType::Program); + auto sourceProvider = Zig::SourceProvider::create(jsCast(globalObject), source, JSC::SourceProviderSourceType::Program, isBuiltIn); this->ignoreESModuleAnnotation = source.tag == ResolvedSourceTagPackageJSONTypeModule; JSC::SourceCode rawInputSource( WTFMove(sourceProvider)); @@ -854,7 +801,8 @@ bool JSCommonJSModule::evaluate( std::optional createCommonJSModule( Zig::GlobalObject* globalObject, - ResolvedSource source) + ResolvedSource source, + bool isBuiltIn) { JSCommonJSModule* moduleObject; WTF::String sourceURL = toStringCopy(source.source_url); @@ -862,7 +810,7 @@ std::optional createCommonJSModule( JSValue specifierValue = Bun::toJS(globalObject, source.specifier); JSValue entry = globalObject->requireMap()->get(globalObject, specifierValue); - auto sourceProvider = Zig::SourceProvider::create(jsCast(globalObject), source, JSC::SourceProviderSourceType::Program); + auto sourceProvider = Zig::SourceProvider::create(jsCast(globalObject), source, JSC::SourceProviderSourceType::Program, isBuiltIn); bool ignoreESModuleAnnotation = source.tag == ResolvedSourceTagPackageJSONTypeModule; SourceOrigin sourceOrigin = sourceProvider->sourceOrigin(); diff --git a/src/bun.js/bindings/CommonJSModuleRecord.h b/src/bun.js/bindings/CommonJSModuleRecord.h index 20941f45418bf3..e38d2e083aaa34 100644 --- a/src/bun.js/bindings/CommonJSModuleRecord.h +++ b/src/bun.js/bindings/CommonJSModuleRecord.h @@ -1,3 +1,4 @@ +#pragma once #include "root.h" #include "headers-handwritten.h" @@ -22,7 +23,7 @@ class JSCommonJSModule final : public JSC::JSDestructibleObject { static constexpr unsigned StructureFlags = Base::StructureFlags | JSC::OverridesPut; mutable JSC::WriteBarrier m_id; - mutable JSC::WriteBarrier m_filename; + mutable JSC::WriteBarrier m_filename; mutable JSC::WriteBarrier m_dirname; mutable JSC::WriteBarrier m_paths; mutable JSC::WriteBarrier sourceCode; @@ -32,18 +33,22 @@ class JSCommonJSModule final : public JSC::JSDestructibleObject { ~JSCommonJSModule(); void finishCreation(JSC::VM& vm, - JSC::JSString* id, JSC::JSString* filename, + JSC::JSString* id, JSValue filename, JSC::JSString* dirname, JSC::JSSourceCode* sourceCode); static JSC::Structure* createStructure(JSC::JSGlobalObject* globalObject); - bool evaluate(Zig::GlobalObject* globalObject, const WTF::String& sourceURL, ResolvedSource resolvedSource); + bool evaluate(Zig::GlobalObject* globalObject, const WTF::String& sourceURL, ResolvedSource resolvedSource, bool isBuiltIn); + inline bool evaluate(Zig::GlobalObject* globalObject, const WTF::String& sourceURL, ResolvedSource resolvedSource) + { + return evaluate(globalObject, sourceURL, resolvedSource, false); + } bool evaluate(Zig::GlobalObject* globalObject, const WTF::String& key, const SyntheticSourceProvider::SyntheticSourceGenerator& generator); bool evaluate(Zig::GlobalObject* globalObject, const WTF::String& key, JSSourceCode* sourceCode); static JSCommonJSModule* create(JSC::VM& vm, JSC::Structure* structure, JSC::JSString* id, - JSC::JSString* filename, + JSValue filename, JSC::JSString* dirname, JSC::JSSourceCode* sourceCode); static JSCommonJSModule* create( @@ -96,7 +101,15 @@ JSC::Structure* createCommonJSModuleStructure( std::optional createCommonJSModule( Zig::GlobalObject* globalObject, - ResolvedSource source); + ResolvedSource source, + bool isBuiltIn); + +inline std::optional createCommonJSModule( + Zig::GlobalObject* globalObject, + ResolvedSource source) +{ + return createCommonJSModule(globalObject, source, false); +} class RequireResolveFunctionPrototype final : public JSC::JSNonFinalObject { public: diff --git a/src/bun.js/bindings/InternalModuleRegistry.cpp b/src/bun.js/bindings/InternalModuleRegistry.cpp new file mode 100644 index 00000000000000..8413605020b7d8 --- /dev/null +++ b/src/bun.js/bindings/InternalModuleRegistry.cpp @@ -0,0 +1,161 @@ +#include "InternalModuleRegistry.h" + +#include "ZigGlobalObject.h" +#include "JavaScriptCore/BuiltinUtils.h" +#include "JavaScriptCore/JSFunction.h" +#include "JavaScriptCore/LazyProperty.h" +#include "JavaScriptCore/LazyPropertyInlines.h" +#include "JavaScriptCore/VMTrapsInlines.h" +#include "JavaScriptCore/JSModuleLoader.h" + +#include "InternalModuleRegistryConstants.h" + +namespace Bun { + +extern "C" bool BunTest__shouldGenerateCodeCoverage(BunString sourceURL); +extern "C" void ByteRangeMapping__generate(BunString sourceURL, BunString code, int sourceID); + +static void maybeAddCodeCoverage(JSC::VM& vm, const JSC::SourceCode& code) +{ +#ifdef BUN_DEBUG + bool isCodeCoverageEnabled = !!vm.controlFlowProfiler(); + bool shouldGenerateCodeCoverage = isCodeCoverageEnabled && BunTest__shouldGenerateCodeCoverage(Bun::toString(code.provider()->sourceURL())); + if (shouldGenerateCodeCoverage) { + ByteRangeMapping__generate(Bun::toString(code.provider()->sourceURL()), Bun::toString(code.provider()->source().toStringWithoutCopying()), code.provider()->asID()); + } +#endif +} + +// The `INTERNAL_MODULE_REGISTRY_GENERATE` macro handles inlining code to compile and run a +// JS builtin that acts as a module. In debug mode, we use a different implementation that reads +// from the developer's filesystem. This allows reloading code without recompiling bindings. + +#define INTERNAL_MODULE_REGISTRY_GENERATE_(globalObject, vm, SOURCE, moduleName) \ + auto throwScope = DECLARE_THROW_SCOPE(vm); \ + auto&& origin = SourceOrigin(WTF::URL(makeString("builtin://"_s, moduleName))); \ + SourceCode source = JSC::makeSource(SOURCE, origin, moduleName); \ + maybeAddCodeCoverage(vm, source); \ + JSFunction* func \ + = JSFunction::create( \ + vm, \ + createBuiltinExecutable( \ + vm, source, \ + Identifier(), \ + ImplementationVisibility::Public, \ + ConstructorKind::None, \ + ConstructAbility::CannotConstruct) \ + ->link(vm, nullptr, source), \ + static_cast(globalObject)); \ + \ + RETURN_IF_EXCEPTION(throwScope, {}); \ + \ + JSC::MarkedArgumentBuffer argList; \ + JSValue result = JSC::call( \ + globalObject, \ + func, \ + JSC::getCallData(func), \ + globalObject, JSC::MarkedArgumentBuffer()); \ + \ + RETURN_IF_EXCEPTION(throwScope, {}); \ + ASSERT_INTERNAL_MODULE(result, moduleName); \ + return result; + +#if BUN_DEBUG +#include "../../src/js/out/DebugPath.h" +#define ASSERT_INTERNAL_MODULE(result, moduleName) \ + if (!result || !result.isCell() || !jsDynamicCast(result)) { \ + printf("Expected \"%s\" to export a JSObject. Bun is going to crash.", moduleName.utf8().data()); \ + } +JSValue initializeInternalModuleFromDisk( + JSGlobalObject* globalObject, + VM& vm, + WTF::String moduleName, + WTF::String fileBase, + WTF::String fallback) +{ + WTF::String file = makeString(BUN_DYNAMIC_JS_LOAD_PATH, "modules_dev/"_s, fileBase); + if (auto contents = WTF::FileSystemImpl::readEntireFile(file)) { + auto string = WTF::String::fromUTF8(contents.value()); + INTERNAL_MODULE_REGISTRY_GENERATE_(globalObject, vm, string, moduleName); + } else { + printf("bun-debug failed to load bundled version of \"%s\" at \"%s\" (was it deleted?)\n" + "Please run `make js` to rebundle these builtins.\n", + moduleName.utf8().data(), file.utf8().data()); + // Fallback to embedded source + INTERNAL_MODULE_REGISTRY_GENERATE_(globalObject, vm, fallback, moduleName); + } +} +#define INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, moduleId, filename, SOURCE) \ + return initializeInternalModuleFromDisk(globalObject, vm, moduleId, filename, SOURCE) +#else + +#define ASSERT_INTERNAL_MODULE(result, moduleName) \ + { \ + } +#define INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, moduleId, filename, SOURCE) \ + INTERNAL_MODULE_REGISTRY_GENERATE_(globalObject, vm, SOURCE, moduleId) +#endif + +const ClassInfo InternalModuleRegistry::s_info = { "InternalModuleRegistry"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(InternalModuleRegistry) }; + +InternalModuleRegistry::InternalModuleRegistry(VM& vm, Structure* structure) + : Base(vm, structure) +{ +} + +template +void InternalModuleRegistry::visitChildrenImpl(JSCell* cell, Visitor& visitor) +{ + auto* thisObject = jsCast(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitChildren(thisObject, visitor); +} + +DEFINE_VISIT_CHILDREN_WITH_MODIFIER(JS_EXPORT_PRIVATE, InternalModuleRegistry); + +InternalModuleRegistry* InternalModuleRegistry::create(VM& vm, Structure* structure) +{ + InternalModuleRegistry* registry = new (NotNull, allocateCell(vm)) InternalModuleRegistry(vm, structure); + for (uint8_t i = 0; i < BUN_INTERNAL_MODULE_COUNT; i++) { + registry->internalField(static_cast(i)) + .set(vm, registry, jsUndefined()); + } + return registry; +} + +Structure* InternalModuleRegistry::createStructure(VM& vm, JSGlobalObject* globalObject) +{ + return Structure::create(vm, globalObject, jsNull(), TypeInfo(InternalFieldTupleType, StructureFlags), info(), 0, 48); +} + +JSValue InternalModuleRegistry::requireId(JSGlobalObject* globalObject, VM& vm, Field id) +{ + auto value = internalField(id).get(); + if (!value || value.isUndefined()) { + value = createInternalModuleById(globalObject, vm, id); + internalField(id).set(vm, this, value); + } + return value; +} + +#include "../../../src/js/out/InternalModuleRegistry+createInternalModuleById.h" + +// This is called like @getInternalField(@internalModuleRegistry, 1) ?? @createInternalModuleById(1) +// so we want to write it to the internal field when loaded. +JSC_DEFINE_HOST_FUNCTION(InternalModuleRegistry::jsCreateInternalModuleById, (JSGlobalObject * lexicalGlobalObject, CallFrame* callframe)) +{ + auto& vm = lexicalGlobalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto id = callframe->argument(0).toUInt32(lexicalGlobalObject); + + auto registry = static_cast(lexicalGlobalObject)->internalModuleRegistry(); + auto mod = registry->createInternalModuleById(lexicalGlobalObject, vm, static_cast(id)); + RETURN_IF_EXCEPTION(throwScope, {}); + registry->internalField(static_cast(id)).set(vm, registry, mod); + return JSValue::encode(mod); +} + +} // namespace Bun + +#undef INTERNAL_MODULE_REGISTRY_GENERATE_ +#undef INTERNAL_MODULE_REGISTRY_GENERATE diff --git a/src/bun.js/bindings/InternalModuleRegistry.h b/src/bun.js/bindings/InternalModuleRegistry.h new file mode 100644 index 00000000000000..d14625e00eee2b --- /dev/null +++ b/src/bun.js/bindings/InternalModuleRegistry.h @@ -0,0 +1,59 @@ +#pragma once +#include "root.h" +#include "JavaScriptCore/JSInternalFieldObjectImpl.h" +#include "JavaScriptCore/JSInternalFieldObjectImplInlines.h" +#include "BunClientData.h" +#include "../../../src/js/out/InternalModuleRegistry+numberOfModules.h" + +namespace Bun { +using namespace JSC; + +// Internal module registry is an array of lazily initialized "modules". Module IDs are generated +// pre-build by `make js` and inlined into JS code and the C++ enum (InternalModuleRegistry::Field) +// This allows modules depending on each other to skip the module resolver. +// +// Modules come from two sources: +// - some are written in JS (src/js, there is a readme file that explain those files more. +// - others are native code (src/bun.js/modules), see _NativeModule.h in there. +class InternalModuleRegistry : public JSInternalFieldObjectImpl { +protected: + JS_EXPORT_PRIVATE InternalModuleRegistry(VM&, Structure*); + DECLARE_DEFAULT_FINISH_CREATION; + DECLARE_VISIT_CHILDREN_WITH_MODIFIER(JS_EXPORT_PRIVATE); + +public: + using Base = JSInternalFieldObjectImpl; + + DECLARE_EXPORT_INFO; + + enum Field : uint8_t { +#include "../../../src/js/out/InternalModuleRegistry+enum.h" + }; + const WriteBarrier& internalField(Field field) const { return Base::internalField(static_cast(field)); } + WriteBarrier& internalField(Field field) { return Base::internalField(static_cast(field)); } + + template + static GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + if constexpr (mode == JSC::SubspaceAccess::Concurrently) + return nullptr; + return WebCore::subspaceForImpl( + vm, + [](auto& spaces) { return spaces.m_clientSubspaceForInternalModuleRegistry.get(); }, + [](auto& spaces, auto&& space) { spaces.m_clientSubspaceForInternalModuleRegistry = std::forward(space); }, + [](auto& spaces) { return spaces.m_subspaceForInternalModuleRegistry.get(); }, + [](auto& spaces, auto&& space) { spaces.m_subspaceForInternalModuleRegistry = std::forward(space); }); + } + + static InternalModuleRegistry* create(VM& vm, Structure* structure); + static Structure* createStructure(VM& vm, JSGlobalObject* globalObject); + + JSValue requireId(JSGlobalObject* globalObject, VM& vm, Field id); + + static JSC_DECLARE_HOST_FUNCTION(jsCreateInternalModuleById); + +protected: + JSValue createInternalModuleById(JSGlobalObject* globalObject, VM& vm, Field id); +}; + +} // namespace Bun diff --git a/src/bun.js/bindings/JSBuffer.cpp b/src/bun.js/bindings/JSBuffer.cpp index e420e24ef12ab6..26047aa3daac77 100644 --- a/src/bun.js/bindings/JSBuffer.cpp +++ b/src/bun.js/bindings/JSBuffer.cpp @@ -949,7 +949,8 @@ static inline JSC::EncodedJSValue jsBufferPrototypeFunction_copyBody(JSC::JSGlob } targetStart = std::min(targetStart, targetEnd); - sourceStart = std::min(sourceStart, std::min(sourceEnd, sourceEndInit)); + sourceEnd = std::min(sourceEnd, sourceEndInit); + sourceStart = std::min(sourceStart, sourceEnd); auto sourceLength = sourceEnd - sourceStart; auto targetLength = targetEnd - targetStart; diff --git a/src/bun.js/bindings/JSCTaskScheduler.cpp b/src/bun.js/bindings/JSCTaskScheduler.cpp index 436be4c0aaea9c..b97b2e9d260788 100644 --- a/src/bun.js/bindings/JSCTaskScheduler.cpp +++ b/src/bun.js/bindings/JSCTaskScheduler.cpp @@ -24,9 +24,11 @@ class JSCDeferredWorkTask { Ticket ticket; Task task; - WTF_MAKE_FAST_ALLOCATED; + WTF_MAKE_ISO_ALLOCATED(JSCDeferredWorkTask); }; +WTF_MAKE_ISO_ALLOCATED_IMPL(JSCDeferredWorkTask); + static JSC::VM& getVM(Ticket ticket) { return ticket->scriptExecutionOwner.get()->vm(); diff --git a/src/bun.js/bindings/JSMockFunction.cpp b/src/bun.js/bindings/JSMockFunction.cpp index 4a9b936b40aada..a8bac7c56c2ffa 100644 --- a/src/bun.js/bindings/JSMockFunction.cpp +++ b/src/bun.js/bindings/JSMockFunction.cpp @@ -1435,19 +1435,3 @@ JSC_DEFINE_HOST_FUNCTION(jsMockFunctionWithImplementation, (JSC::JSGlobalObject return JSC::JSValue::encode(jsUndefined()); } } // namespace Bun - -namespace JSC { - -template -template -void JSInternalFieldObjectImpl::visitChildrenImpl(JSCell* cell, Visitor& visitor) -{ - auto* thisObject = jsCast(cell); - ASSERT_GC_OBJECT_INHERITS(thisObject, info()); - Base::visitChildren(thisObject, visitor); - visitor.appendValues(thisObject->m_internalFields, numberOfInternalFields); -} - -DEFINE_VISIT_CHILDREN_WITH_MODIFIER(template, JSInternalFieldObjectImpl); - -} // namespace JSC diff --git a/src/bun.js/bindings/JSSink+custom.h b/src/bun.js/bindings/JSSink+custom.h deleted file mode 100644 index 8b137891791fe9..00000000000000 --- a/src/bun.js/bindings/JSSink+custom.h +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/bun.js/bindings/ModuleLoader.cpp b/src/bun.js/bindings/ModuleLoader.cpp index ac5ca0b91a7270..2c8b956123b70f 100644 --- a/src/bun.js/bindings/ModuleLoader.cpp +++ b/src/bun.js/bindings/ModuleLoader.cpp @@ -27,15 +27,6 @@ #include "EventEmitter.h" #include "JSEventEmitter.h" -#include "../modules/BufferModule.h" -#include "../modules/EventsModule.h" -#include "../modules/ProcessModule.h" -#include "../modules/StringDecoderModule.h" -#include "../modules/ObjectModule.h" -#include "../modules/NodeModuleModule.h" -#include "../modules/TTYModule.h" -#include "../modules/ConstantsModule.h" -#include "node_util_types.h" #include "CommonJSModuleRecord.h" #include #include @@ -43,7 +34,13 @@ #include #include +#include "../modules/_NativeModule.h" +#include "../../js/out/NativeModuleImpl.h" + +#include "../modules/ObjectModule.h" + namespace Bun { +using namespace JSC; using namespace Zig; using namespace WebCore; @@ -67,14 +64,52 @@ static JSC::JSInternalPromise* resolvedInternalPromise(JSC::JSGlobalObject* glob return promise; } -using namespace JSC; +// Converts an object from InternalModuleRegistry into { ...obj, default: obj } +static JSC::SyntheticSourceProvider::SyntheticSourceGenerator +generateInternalModuleSourceCode(JSC::JSGlobalObject* globalObject, InternalModuleRegistry::Field moduleId) +{ + return [moduleId](JSC::JSGlobalObject* lexicalGlobalObject, + JSC::Identifier moduleKey, + Vector& exportNames, + JSC::MarkedArgumentBuffer& exportValues) -> void { + JSC::VM& vm = lexicalGlobalObject->vm(); + GlobalObject* globalObject = jsCast(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + + auto* object = jsCast(globalObject->internalModuleRegistry()->requireId(globalObject, vm, moduleId)); + if (!object) { + return; + } + RETURN_IF_EXCEPTION(throwScope, {}); + + JSC::EnsureStillAliveScope stillAlive(object); + + PropertyNameArray properties(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude); + object->getPropertyNames(globalObject, properties, DontEnumPropertiesMode::Exclude); + + RETURN_IF_EXCEPTION(throwScope, {}); + + auto len = properties.size() + 1; + exportNames.reserveCapacity(len); + exportValues.ensureCapacity(len); + + exportNames.append(vm.propertyNames->defaultKeyword); + exportValues.append(object); + + for (auto& entry : properties) { + exportNames.append(entry); + exportValues.append(object->get(globalObject, entry)); + } + }; +} static OnLoadResult handleOnLoadObjectResult(Zig::GlobalObject* globalObject, JSC::JSObject* object) { OnLoadResult result {}; result.type = OnLoadResultTypeObject; JSC::VM& vm = globalObject->vm(); - if (JSC::JSValue exportsValue = object->getIfPropertyExists(globalObject, JSC::Identifier::fromString(vm, "exports"_s))) { + auto& builtinNames = WebCore::builtinNames(vm); + if (JSC::JSValue exportsValue = object->getIfPropertyExists(globalObject, builtinNames.exportsPublicName())) { if (exportsValue.isObject()) { result.value.object = exportsValue; return result; @@ -352,6 +387,18 @@ extern "C" void Bun__onFulfillAsyncModule( return promise->reject(promise->globalObject(), exception); } + if (res->result.value.commonJSExportsLen) { + auto created = Bun::createCommonJSModule(jsCast(globalObject), res->result.value); + + if (created.has_value()) { + return promise->resolve(promise->globalObject(), JSSourceCode::create(vm, WTFMove(created.value()))); + } else { + auto* exception = scope.exception(); + scope.clearException(); + return promise->reject(promise->globalObject(), exception); + } + } + auto provider = Zig::SourceProvider::create(jsDynamicCast(globalObject), res->result.value); promise->resolve(promise->globalObject(), JSC::JSSourceCode::create(vm, JSC::SourceCode(provider))); } @@ -377,45 +424,37 @@ JSValue fetchCommonJSModule( return JSValue(); } - switch (res->result.value.tag) { - case SyntheticModuleType::Module: { - target->evaluate(globalObject, Bun::toWTFString(*specifier), generateNodeModuleModule); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); - } + auto tag = res->result.value.tag; + switch (tag) { +// Generated native module cases +#define CASE(str, name) \ + case SyntheticModuleType::name: { \ + target->evaluate(globalObject, Bun::toWTFString(*specifier), generateNativeModule_##name); \ + RETURN_IF_EXCEPTION(scope, {}); \ + RELEASE_AND_RETURN(scope, target); \ + } + BUN_FOREACH_NATIVE_MODULE(CASE) +#undef CASE - case SyntheticModuleType::Buffer: { - target->evaluate(globalObject, Bun::toWTFString(*specifier), generateBufferSourceCode); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); - } - case SyntheticModuleType::TTY: { - target->evaluate(globalObject, Bun::toWTFString(*specifier), generateTTYSourceCode); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); - } - case SyntheticModuleType::NodeUtilTypes: { - target->evaluate(globalObject, Bun::toWTFString(*specifier), Bun::generateNodeUtilTypesSourceCode); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); - } - case SyntheticModuleType::Process: { - target->evaluate(globalObject, Bun::toWTFString(*specifier), generateProcessSourceCode); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); - } - case SyntheticModuleType::Events: { - target->evaluate(globalObject, Bun::toWTFString(*specifier), generateEventsSourceCode); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); - } - case SyntheticModuleType::StringDecoder: { - target->evaluate(globalObject, Bun::toWTFString(*specifier), generateStringDecoderSourceCode); - RETURN_IF_EXCEPTION(scope, {}); - RELEASE_AND_RETURN(scope, target); + case SyntheticModuleType::ESM: { + RELEASE_AND_RETURN(scope, jsNumber(-1)); } + default: { - RELEASE_AND_RETURN(scope, jsNumber(-1)); + if (tag & SyntheticModuleType::InternalModuleRegistryFlag) { + constexpr auto mask = (SyntheticModuleType::InternalModuleRegistryFlag - 1); + auto result = globalObject->internalModuleRegistry()->requireId(globalObject, vm, static_cast(tag & mask)); + RETURN_IF_EXCEPTION(scope, {}); + + target->putDirect( + vm, + builtinNames.exportsPublicName(), + result, + JSC::PropertyAttribute::ReadOnly | 0); + RELEASE_AND_RETURN(scope, target); + } else { + RELEASE_AND_RETURN(scope, jsNumber(-1)); + } } } } @@ -484,7 +523,7 @@ JSValue fetchCommonJSModule( } template -static JSValue fetchSourceCode( +static JSValue fetchESMSourceCode( Zig::GlobalObject* globalObject, ErrorableResolvedSource* res, BunString* specifier, @@ -543,67 +582,31 @@ static JSValue fetchSourceCode( auto moduleKey = Bun::toWTFString(*specifier); - switch (res->result.value.tag) { - case SyntheticModuleType::Module: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(generateNodeModuleModule, - JSC::SourceOrigin(), WTFMove(moduleKey))); - - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); - } - - case SyntheticModuleType::Buffer: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(generateBufferSourceCode, - JSC::SourceOrigin(), WTFMove(moduleKey))); - - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); - } - case SyntheticModuleType::TTY: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(generateTTYSourceCode, - JSC::SourceOrigin(), WTFMove(moduleKey))); - - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); - } - case SyntheticModuleType::NodeUtilTypes: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(Bun::generateNodeUtilTypesSourceCode, - JSC::SourceOrigin(), WTFMove(moduleKey))); - - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); - } - case SyntheticModuleType::Process: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(generateProcessSourceCode, - JSC::SourceOrigin(), WTFMove(moduleKey))); - - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); - } - case SyntheticModuleType::Events: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(generateEventsSourceCode, - JSC::SourceOrigin(), WTFMove(moduleKey))); - - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); + auto tag = res->result.value.tag; + switch (tag) { + case SyntheticModuleType::ESM: { + auto&& provider = Zig::SourceProvider::create(globalObject, res->result.value, JSC::SourceProviderSourceType::Module, true); + return rejectOrResolve(JSSourceCode::create(vm, JSC::SourceCode(provider))); } - case SyntheticModuleType::StringDecoder: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(generateStringDecoderSourceCode, - JSC::SourceOrigin(), WTFMove(moduleKey))); - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); - } - case SyntheticModuleType::Constants: { - auto source = JSC::SourceCode( - JSC::SyntheticSourceProvider::create(generateConstantsSourceCode, - JSC::SourceOrigin(), WTFMove(moduleKey))); +#define CASE(str, name) \ + case (SyntheticModuleType::name): { \ + auto source = JSC::SourceCode(JSC::SyntheticSourceProvider::create(generateNativeModule_##name, JSC::SourceOrigin(), WTFMove(moduleKey))); \ + return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); \ + } + BUN_FOREACH_NATIVE_MODULE(CASE) +#undef CASE - return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); - } + // CommonJS modules from src/js/* default: { - auto&& provider = Zig::SourceProvider::create(globalObject, res->result.value, JSC::SourceProviderSourceType::Module, true); - return rejectOrResolve(JSC::JSSourceCode::create(vm, JSC::SourceCode(provider))); + if (tag & SyntheticModuleType::InternalModuleRegistryFlag) { + constexpr auto mask = (SyntheticModuleType::InternalModuleRegistryFlag - 1); + auto source = JSC::SourceCode(JSC::SyntheticSourceProvider::create(generateInternalModuleSourceCode(globalObject, static_cast(tag & mask)), JSC::SourceOrigin(URL(makeString("builtins://", moduleKey))), moduleKey)); + return rejectOrResolve(JSSourceCode::create(vm, WTFMove(source))); + } else { + auto&& provider = Zig::SourceProvider::create(globalObject, res->result.value, JSC::SourceProviderSourceType::Module, true); + return rejectOrResolve(JSC::JSSourceCode::create(vm, JSC::SourceCode(provider))); + } } } } @@ -703,36 +706,21 @@ extern "C" JSC::EncodedJSValue jsFunctionOnLoadObjectResultReject(JSC::JSGlobalO return JSValue::encode(reason); } -JSValue fetchSourceCodeSync( +JSValue fetchESMSourceCodeSync( Zig::GlobalObject* globalObject, ErrorableResolvedSource* res, BunString* specifier, BunString* referrer) { - return fetchSourceCode(globalObject, res, specifier, referrer); + return fetchESMSourceCode(globalObject, res, specifier, referrer); } -JSValue fetchSourceCodeAsync( +JSValue fetchESMSourceCodeAsync( Zig::GlobalObject* globalObject, ErrorableResolvedSource* res, BunString* specifier, BunString* referrer) { - return fetchSourceCode(globalObject, res, specifier, referrer); + return fetchESMSourceCode(globalObject, res, specifier, referrer); } } -namespace JSC { - -template -template -void JSInternalFieldObjectImpl::visitChildrenImpl(JSCell* cell, Visitor& visitor) -{ - auto* thisObject = jsCast(cell); - ASSERT_GC_OBJECT_INHERITS(thisObject, info()); - Base::visitChildren(thisObject, visitor); - visitor.appendValues(thisObject->m_internalFields, numberOfInternalFields); -} - -DEFINE_VISIT_CHILDREN_WITH_MODIFIER(template, JSInternalFieldObjectImpl); - -} // namespace JSC diff --git a/src/bun.js/bindings/ModuleLoader.h b/src/bun.js/bindings/ModuleLoader.h index 6eb04bf409f344..ee726ebcfe9614 100644 --- a/src/bun.js/bindings/ModuleLoader.h +++ b/src/bun.js/bindings/ModuleLoader.h @@ -81,13 +81,13 @@ class PendingVirtualModuleResult : public JSC::JSInternalFieldObjectImpl<3> { }; OnLoadResult handleOnLoadResultNotPromise(Zig::GlobalObject* globalObject, JSC::JSValue objectValue); -JSValue fetchSourceCodeSync( +JSValue fetchESMSourceCodeSync( Zig::GlobalObject* globalObject, ErrorableResolvedSource* res, BunString* specifier, BunString* referrer); -JSValue fetchSourceCodeAsync( +JSValue fetchESMSourceCodeAsync( Zig::GlobalObject* globalObject, ErrorableResolvedSource* res, BunString* specifier, @@ -100,4 +100,4 @@ JSValue fetchCommonJSModule( BunString* specifier, BunString* referrer); -} // namespace Bun \ No newline at end of file +} // namespace Bun diff --git a/src/bun.js/bindings/Process.cpp b/src/bun.js/bindings/Process.cpp index 78f473ec2042df..9a09eca66e33e1 100644 --- a/src/bun.js/bindings/Process.cpp +++ b/src/bun.js/bindings/Process.cpp @@ -397,7 +397,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionExit, Process__dispatchOnExit(zigGlobal, exitCode); Bun__Process__exit(zigGlobal, exitCode); - __builtin_unreachable(); + return JSC::JSValue::encode(jsUndefined()); } extern "C" uint64_t Bun__readOriginTimer(void*); @@ -882,7 +882,10 @@ 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); + + // SvelteKit compatibility hack + release->putDirect(vm, Identifier::fromString(vm, "name"_s), jsString(vm, WTF::String("node"_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); @@ -1153,7 +1156,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionReallyExit, (JSGlobalObject * globalObj zigGlobal = Bun__getDefaultGlobal(); } Bun__Process__exit(zigGlobal, exitCode); - __builtin_unreachable(); + return JSC::JSValue::encode(jsUndefined()); } template @@ -1313,7 +1316,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionCpuUsage, RELEASE_AND_RETURN(throwScope, JSC::JSValue::encode(result)); } -static int getRSS(size_t* rss) +int getRSS(size_t* rss) { #if defined(__APPLE__) mach_msg_type_number_t count; diff --git a/src/bun.js/bindings/Process.h b/src/bun.js/bindings/Process.h index 0ee6f424381b3d..ab344c7fe4231a 100644 --- a/src/bun.js/bindings/Process.h +++ b/src/bun.js/bindings/Process.h @@ -8,6 +8,9 @@ namespace Zig { +// TODO: find a better place for this +int getRSS(size_t* rss); + using namespace JSC; class Process : public WebCore::JSEventEmitter { diff --git a/src/bun.js/bindings/ProcessBindingConstants.cpp b/src/bun.js/bindings/ProcessBindingConstants.cpp new file mode 100644 index 00000000000000..36a4a7f9654abf --- /dev/null +++ b/src/bun.js/bindings/ProcessBindingConstants.cpp @@ -0,0 +1,1124 @@ +// Modelled off of https://github.com/nodejs/node/blob/main/src/node_constants.cc +// Note that if you change any of this code, you probably also have to change NodeConstantsModule.h +#include "ProcessBindingConstants.h" +#include "JavaScriptCore/ObjectConstructor.h" + +// These headers may not all be needed, but they are the ones node references. +// Most of the constants are defined with #if checks on existing #defines, instead of platform-checks +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef OPENSSL_NO_ENGINE +#include +#endif + +#if !defined(_MSC_VER) +#include +#endif + +#if defined(_WIN32) +#include // _S_IREAD _S_IWRITE +#ifndef S_IRUSR +#define S_IRUSR _S_IREAD +#endif // S_IRUSR +#ifndef S_IWUSR +#define S_IWUSR _S_IWRITE +#endif // S_IWUSR +#else +#include +#endif + +namespace Bun { +using namespace JSC; + +static JSValue processBindingConstantsGetOs(VM& vm, JSObject* bindingObject) +{ + auto globalObject = bindingObject->globalObject(); + auto osObj = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 1); + auto dlopenObj = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 1); + auto errnoObj = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 1); + auto signalsObj = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 1); + auto priorityObj = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 1); + osObj->putDirect(vm, Identifier::fromString(vm, "UV_UDP_REUSEADDR"_s), jsNumber(4)); + osObj->putDirect(vm, Identifier::fromString(vm, "dlopen"_s), dlopenObj); + osObj->putDirect(vm, Identifier::fromString(vm, "errno"_s), errnoObj); + osObj->putDirect(vm, Identifier::fromString(vm, "signals"_s), signalsObj); + osObj->putDirect(vm, Identifier::fromString(vm, "priority"_s), priorityObj); +#ifdef E2BIG + errnoObj->putDirect(vm, Identifier::fromString(vm, "E2BIG"_s), jsNumber(E2BIG)); +#endif +#ifdef EACCES + errnoObj->putDirect(vm, Identifier::fromString(vm, "EACCES"_s), jsNumber(EACCES)); +#endif +#ifdef EADDRINUSE + errnoObj->putDirect(vm, Identifier::fromString(vm, "EADDRINUSE"_s), jsNumber(EADDRINUSE)); +#endif +#ifdef EADDRNOTAVAIL + errnoObj->putDirect(vm, Identifier::fromString(vm, "EADDRNOTAVAIL"_s), jsNumber(EADDRNOTAVAIL)); +#endif +#ifdef EAFNOSUPPORT + errnoObj->putDirect(vm, Identifier::fromString(vm, "EAFNOSUPPORT"_s), jsNumber(EAFNOSUPPORT)); +#endif +#ifdef EAGAIN + errnoObj->putDirect(vm, Identifier::fromString(vm, "EAGAIN"_s), jsNumber(EAGAIN)); +#endif +#ifdef EALREADY + errnoObj->putDirect(vm, Identifier::fromString(vm, "EALREADY"_s), jsNumber(EALREADY)); +#endif +#ifdef EBADF + errnoObj->putDirect(vm, Identifier::fromString(vm, "EBADF"_s), jsNumber(EBADF)); +#endif +#ifdef EBADMSG + errnoObj->putDirect(vm, Identifier::fromString(vm, "EBADMSG"_s), jsNumber(EBADMSG)); +#endif +#ifdef EBUSY + errnoObj->putDirect(vm, Identifier::fromString(vm, "EBUSY"_s), jsNumber(EBUSY)); +#endif +#ifdef ECANCELED + errnoObj->putDirect(vm, Identifier::fromString(vm, "ECANCELED"_s), jsNumber(ECANCELED)); +#endif +#ifdef ECHILD + errnoObj->putDirect(vm, Identifier::fromString(vm, "ECHILD"_s), jsNumber(ECHILD)); +#endif +#ifdef ECONNABORTED + errnoObj->putDirect(vm, Identifier::fromString(vm, "ECONNABORTED"_s), jsNumber(ECONNABORTED)); +#endif +#ifdef ECONNREFUSED + errnoObj->putDirect(vm, Identifier::fromString(vm, "ECONNREFUSED"_s), jsNumber(ECONNREFUSED)); +#endif +#ifdef ECONNRESET + errnoObj->putDirect(vm, Identifier::fromString(vm, "ECONNRESET"_s), jsNumber(ECONNRESET)); +#endif +#ifdef EDEADLK + errnoObj->putDirect(vm, Identifier::fromString(vm, "EDEADLK"_s), jsNumber(EDEADLK)); +#endif +#ifdef EDESTADDRREQ + errnoObj->putDirect(vm, Identifier::fromString(vm, "EDESTADDRREQ"_s), jsNumber(EDESTADDRREQ)); +#endif +#ifdef EDOM + errnoObj->putDirect(vm, Identifier::fromString(vm, "EDOM"_s), jsNumber(EDOM)); +#endif +#ifdef EDQUOT + errnoObj->putDirect(vm, Identifier::fromString(vm, "EDQUOT"_s), jsNumber(EDQUOT)); +#endif +#ifdef EEXIST + errnoObj->putDirect(vm, Identifier::fromString(vm, "EEXIST"_s), jsNumber(EEXIST)); +#endif +#ifdef EFAULT + errnoObj->putDirect(vm, Identifier::fromString(vm, "EFAULT"_s), jsNumber(EFAULT)); +#endif +#ifdef EFBIG + errnoObj->putDirect(vm, Identifier::fromString(vm, "EFBIG"_s), jsNumber(EFBIG)); +#endif +#ifdef EHOSTUNREACH + errnoObj->putDirect(vm, Identifier::fromString(vm, "EHOSTUNREACH"_s), jsNumber(EHOSTUNREACH)); +#endif +#ifdef EIDRM + errnoObj->putDirect(vm, Identifier::fromString(vm, "EIDRM"_s), jsNumber(EIDRM)); +#endif +#ifdef EILSEQ + errnoObj->putDirect(vm, Identifier::fromString(vm, "EILSEQ"_s), jsNumber(EILSEQ)); +#endif +#ifdef EINPROGRESS + errnoObj->putDirect(vm, Identifier::fromString(vm, "EINPROGRESS"_s), jsNumber(EINPROGRESS)); +#endif +#ifdef EINTR + errnoObj->putDirect(vm, Identifier::fromString(vm, "EINTR"_s), jsNumber(EINTR)); +#endif +#ifdef EINVAL + errnoObj->putDirect(vm, Identifier::fromString(vm, "EINVAL"_s), jsNumber(EINVAL)); +#endif +#ifdef EIO + errnoObj->putDirect(vm, Identifier::fromString(vm, "EIO"_s), jsNumber(EIO)); +#endif +#ifdef EISCONN + errnoObj->putDirect(vm, Identifier::fromString(vm, "EISCONN"_s), jsNumber(EISCONN)); +#endif +#ifdef EISDIR + errnoObj->putDirect(vm, Identifier::fromString(vm, "EISDIR"_s), jsNumber(EISDIR)); +#endif +#ifdef ELOOP + errnoObj->putDirect(vm, Identifier::fromString(vm, "ELOOP"_s), jsNumber(ELOOP)); +#endif +#ifdef EMFILE + errnoObj->putDirect(vm, Identifier::fromString(vm, "EMFILE"_s), jsNumber(EMFILE)); +#endif +#ifdef EMLINK + errnoObj->putDirect(vm, Identifier::fromString(vm, "EMLINK"_s), jsNumber(EMLINK)); +#endif +#ifdef EMSGSIZE + errnoObj->putDirect(vm, Identifier::fromString(vm, "EMSGSIZE"_s), jsNumber(EMSGSIZE)); +#endif +#ifdef EMULTIHOP + errnoObj->putDirect(vm, Identifier::fromString(vm, "EMULTIHOP"_s), jsNumber(EMULTIHOP)); +#endif +#ifdef ENAMETOOLONG + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENAMETOOLONG"_s), jsNumber(ENAMETOOLONG)); +#endif +#ifdef ENETDOWN + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENETDOWN"_s), jsNumber(ENETDOWN)); +#endif +#ifdef ENETRESET + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENETRESET"_s), jsNumber(ENETRESET)); +#endif +#ifdef ENETUNREACH + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENETUNREACH"_s), jsNumber(ENETUNREACH)); +#endif +#ifdef ENFILE + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENFILE"_s), jsNumber(ENFILE)); +#endif +#ifdef ENOBUFS + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOBUFS"_s), jsNumber(ENOBUFS)); +#endif +#ifdef ENODATA + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENODATA"_s), jsNumber(ENODATA)); +#endif +#ifdef ENODEV + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENODEV"_s), jsNumber(ENODEV)); +#endif +#ifdef ENOENT + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOENT"_s), jsNumber(ENOENT)); +#endif +#ifdef ENOEXEC + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOEXEC"_s), jsNumber(ENOEXEC)); +#endif +#ifdef ENOLCK + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOLCK"_s), jsNumber(ENOLCK)); +#endif +#ifdef ENOLINK + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOLINK"_s), jsNumber(ENOLINK)); +#endif +#ifdef ENOMEM + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOMEM"_s), jsNumber(ENOMEM)); +#endif +#ifdef ENOMSG + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOMSG"_s), jsNumber(ENOMSG)); +#endif +#ifdef ENOPROTOOPT + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOPROTOOPT"_s), jsNumber(ENOPROTOOPT)); +#endif +#ifdef ENOSPC + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOSPC"_s), jsNumber(ENOSPC)); +#endif +#ifdef ENOSR + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOSR"_s), jsNumber(ENOSR)); +#endif +#ifdef ENOSTR + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOSTR"_s), jsNumber(ENOSTR)); +#endif +#ifdef ENOSYS + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOSYS"_s), jsNumber(ENOSYS)); +#endif +#ifdef ENOTCONN + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOTCONN"_s), jsNumber(ENOTCONN)); +#endif +#ifdef ENOTDIR + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOTDIR"_s), jsNumber(ENOTDIR)); +#endif +#ifdef ENOTEMPTY + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOTEMPTY"_s), jsNumber(ENOTEMPTY)); +#endif +#ifdef ENOTSOCK + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOTSOCK"_s), jsNumber(ENOTSOCK)); +#endif +#ifdef ENOTSUP + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOTSUP"_s), jsNumber(ENOTSUP)); +#endif +#ifdef ENOTTY + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENOTTY"_s), jsNumber(ENOTTY)); +#endif +#ifdef ENXIO + errnoObj->putDirect(vm, Identifier::fromString(vm, "ENXIO"_s), jsNumber(ENXIO)); +#endif +#ifdef EOPNOTSUPP + errnoObj->putDirect(vm, Identifier::fromString(vm, "EOPNOTSUPP"_s), jsNumber(EOPNOTSUPP)); +#endif +#ifdef EOVERFLOW + errnoObj->putDirect(vm, Identifier::fromString(vm, "EOVERFLOW"_s), jsNumber(EOVERFLOW)); +#endif +#ifdef EPERM + errnoObj->putDirect(vm, Identifier::fromString(vm, "EPERM"_s), jsNumber(EPERM)); +#endif +#ifdef EPIPE + errnoObj->putDirect(vm, Identifier::fromString(vm, "EPIPE"_s), jsNumber(EPIPE)); +#endif +#ifdef EPROTO + errnoObj->putDirect(vm, Identifier::fromString(vm, "EPROTO"_s), jsNumber(EPROTO)); +#endif +#ifdef EPROTONOSUPPORT + errnoObj->putDirect(vm, Identifier::fromString(vm, "EPROTONOSUPPORT"_s), jsNumber(EPROTONOSUPPORT)); +#endif +#ifdef EPROTOTYPE + errnoObj->putDirect(vm, Identifier::fromString(vm, "EPROTOTYPE"_s), jsNumber(EPROTOTYPE)); +#endif +#ifdef ERANGE + errnoObj->putDirect(vm, Identifier::fromString(vm, "ERANGE"_s), jsNumber(ERANGE)); +#endif +#ifdef EROFS + errnoObj->putDirect(vm, Identifier::fromString(vm, "EROFS"_s), jsNumber(EROFS)); +#endif +#ifdef ESPIPE + errnoObj->putDirect(vm, Identifier::fromString(vm, "ESPIPE"_s), jsNumber(ESPIPE)); +#endif +#ifdef ESRCH + errnoObj->putDirect(vm, Identifier::fromString(vm, "ESRCH"_s), jsNumber(ESRCH)); +#endif +#ifdef ESTALE + errnoObj->putDirect(vm, Identifier::fromString(vm, "ESTALE"_s), jsNumber(ESTALE)); +#endif +#ifdef ETIME + errnoObj->putDirect(vm, Identifier::fromString(vm, "ETIME"_s), jsNumber(ETIME)); +#endif +#ifdef ETIMEDOUT + errnoObj->putDirect(vm, Identifier::fromString(vm, "ETIMEDOUT"_s), jsNumber(ETIMEDOUT)); +#endif +#ifdef ETXTBSY + errnoObj->putDirect(vm, Identifier::fromString(vm, "ETXTBSY"_s), jsNumber(ETXTBSY)); +#endif +#ifdef EWOULDBLOCK + errnoObj->putDirect(vm, Identifier::fromString(vm, "EWOULDBLOCK"_s), jsNumber(EWOULDBLOCK)); +#endif +#ifdef EXDEV + errnoObj->putDirect(vm, Identifier::fromString(vm, "EXDEV"_s), jsNumber(EXDEV)); +#endif +#ifdef WSAEINTR + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEINTR"_s), jsNumber(WSAEINTR)); +#endif +#ifdef WSAEBADF + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEBADF"_s), jsNumber(WSAEBADF)); +#endif +#ifdef WSAEACCES + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEACCES"_s), jsNumber(WSAEACCES)); +#endif +#ifdef WSAEFAULT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEFAULT"_s), jsNumber(WSAEFAULT)); +#endif +#ifdef WSAEINVAL + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEINVAL"_s), jsNumber(WSAEINVAL)); +#endif +#ifdef WSAEMFILE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEMFILE"_s), jsNumber(WSAEMFILE)); +#endif +#ifdef WSAEWOULDBLOCK + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEWOULDBLOCK"_s), jsNumber(WSAEWOULDBLOCK)); +#endif +#ifdef WSAEINPROGRESS + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEINPROGRESS"_s), jsNumber(WSAEINPROGRESS)); +#endif +#ifdef WSAEALREADY + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEALREADY"_s), jsNumber(WSAEALREADY)); +#endif +#ifdef WSAENOTSOCK + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENOTSOCK"_s), jsNumber(WSAENOTSOCK)); +#endif +#ifdef WSAEDESTADDRREQ + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEDESTADDRREQ"_s), jsNumber(WSAEDESTADDRREQ)); +#endif +#ifdef WSAEMSGSIZE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEMSGSIZE"_s), jsNumber(WSAEMSGSIZE)); +#endif +#ifdef WSAEPROTOTYPE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEPROTOTYPE"_s), jsNumber(WSAEPROTOTYPE)); +#endif +#ifdef WSAENOPROTOOPT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENOPROTOOPT"_s), jsNumber(WSAENOPROTOOPT)); +#endif +#ifdef WSAEPROTONOSUPPORT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEPROTONOSUPPORT"_s), jsNumber(WSAEPROTONOSUPPORT)); +#endif +#ifdef WSAESOCKTNOSUPPORT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAESOCKTNOSUPPORT"_s), jsNumber(WSAESOCKTNOSUPPORT)); +#endif +#ifdef WSAEOPNOTSUPP + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEOPNOTSUPP"_s), jsNumber(WSAEOPNOTSUPP)); +#endif +#ifdef WSAEPFNOSUPPORT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEPFNOSUPPORT"_s), jsNumber(WSAEPFNOSUPPORT)); +#endif +#ifdef WSAEAFNOSUPPORT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEAFNOSUPPORT"_s), jsNumber(WSAEAFNOSUPPORT)); +#endif +#ifdef WSAEADDRINUSE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEADDRINUSE"_s), jsNumber(WSAEADDRINUSE)); +#endif +#ifdef WSAEADDRNOTAVAIL + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEADDRNOTAVAIL"_s), jsNumber(WSAEADDRNOTAVAIL)); +#endif +#ifdef WSAENETDOWN + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENETDOWN"_s), jsNumber(WSAENETDOWN)); +#endif +#ifdef WSAENETUNREACH + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENETUNREACH"_s), jsNumber(WSAENETUNREACH)); +#endif +#ifdef WSAENETRESET + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENETRESET"_s), jsNumber(WSAENETRESET)); +#endif +#ifdef WSAECONNABORTED + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAECONNABORTED"_s), jsNumber(WSAECONNABORTED)); +#endif +#ifdef WSAECONNRESET + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAECONNRESET"_s), jsNumber(WSAECONNRESET)); +#endif +#ifdef WSAENOBUFS + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENOBUFS"_s), jsNumber(WSAENOBUFS)); +#endif +#ifdef WSAEISCONN + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEISCONN"_s), jsNumber(WSAEISCONN)); +#endif +#ifdef WSAENOTCONN + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENOTCONN"_s), jsNumber(WSAENOTCONN)); +#endif +#ifdef WSAESHUTDOWN + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAESHUTDOWN"_s), jsNumber(WSAESHUTDOWN)); +#endif +#ifdef WSAETOOMANYREFS + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAETOOMANYREFS"_s), jsNumber(WSAETOOMANYREFS)); +#endif +#ifdef WSAETIMEDOUT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAETIMEDOUT"_s), jsNumber(WSAETIMEDOUT)); +#endif +#ifdef WSAECONNREFUSED + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAECONNREFUSED"_s), jsNumber(WSAECONNREFUSED)); +#endif +#ifdef WSAELOOP + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAELOOP"_s), jsNumber(WSAELOOP)); +#endif +#ifdef WSAENAMETOOLONG + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENAMETOOLONG"_s), jsNumber(WSAENAMETOOLONG)); +#endif +#ifdef WSAEHOSTDOWN + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEHOSTDOWN"_s), jsNumber(WSAEHOSTDOWN)); +#endif +#ifdef WSAEHOSTUNREACH + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEHOSTUNREACH"_s), jsNumber(WSAEHOSTUNREACH)); +#endif +#ifdef WSAENOTEMPTY + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENOTEMPTY"_s), jsNumber(WSAENOTEMPTY)); +#endif +#ifdef WSAEPROCLIM + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEPROCLIM"_s), jsNumber(WSAEPROCLIM)); +#endif +#ifdef WSAEUSERS + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEUSERS"_s), jsNumber(WSAEUSERS)); +#endif +#ifdef WSAEDQUOT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEDQUOT"_s), jsNumber(WSAEDQUOT)); +#endif +#ifdef WSAESTALE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAESTALE"_s), jsNumber(WSAESTALE)); +#endif +#ifdef WSAEREMOTE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEREMOTE"_s), jsNumber(WSAEREMOTE)); +#endif +#ifdef WSASYSNOTREADY + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSASYSNOTREADY"_s), jsNumber(WSASYSNOTREADY)); +#endif +#ifdef WSAVERNOTSUPPORTED + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAVERNOTSUPPORTED"_s), jsNumber(WSAVERNOTSUPPORTED)); +#endif +#ifdef WSANOTINITIALISED + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSANOTINITIALISED"_s), jsNumber(WSANOTINITIALISED)); +#endif +#ifdef WSAEDISCON + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEDISCON"_s), jsNumber(WSAEDISCON)); +#endif +#ifdef WSAENOMORE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAENOMORE"_s), jsNumber(WSAENOMORE)); +#endif +#ifdef WSAECANCELLED + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAECANCELLED"_s), jsNumber(WSAECANCELLED)); +#endif +#ifdef WSAEINVALIDPROCTABLE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEINVALIDPROCTABLE"_s), jsNumber(WSAEINVALIDPROCTABLE)); +#endif +#ifdef WSAEINVALIDPROVIDER + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEINVALIDPROVIDER"_s), jsNumber(WSAEINVALIDPROVIDER)); +#endif +#ifdef WSAEPROVIDERFAILEDINIT + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEPROVIDERFAILEDINIT"_s), jsNumber(WSAEPROVIDERFAILEDINIT)); +#endif +#ifdef WSASYSCALLFAILURE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSASYSCALLFAILURE"_s), jsNumber(WSASYSCALLFAILURE)); +#endif +#ifdef WSASERVICE_NOT_FOUND + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSASERVICE_NOT_FOUND"_s), jsNumber(WSASERVICE_NOT_FOUND)); +#endif +#ifdef WSATYPE_NOT_FOUND + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSATYPE_NOT_FOUND"_s), jsNumber(WSATYPE_NOT_FOUND)); +#endif +#ifdef WSA_E_NO_MORE + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSA_E_NO_MORE"_s), jsNumber(WSA_E_NO_MORE)); +#endif +#ifdef WSA_E_CANCELLED + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSA_E_CANCELLED"_s), jsNumber(WSA_E_CANCELLED)); +#endif +#ifdef WSAEREFUSED + errnoObj->putDirect(vm, Identifier::fromString(vm, "WSAEREFUSED"_s), jsNumber(WSAEREFUSED)); +#endif +#ifdef SIGHUP + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGHUP"_s), jsNumber(SIGHUP)); +#endif +#ifdef SIGINT + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGINT"_s), jsNumber(SIGINT)); +#endif +#ifdef SIGQUIT + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGQUIT"_s), jsNumber(SIGQUIT)); +#endif +#ifdef SIGILL + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGILL"_s), jsNumber(SIGILL)); +#endif +#ifdef SIGTRAP + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGTRAP"_s), jsNumber(SIGTRAP)); +#endif +#ifdef SIGABRT + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGABRT"_s), jsNumber(SIGABRT)); +#endif +#ifdef SIGIOT + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGIOT"_s), jsNumber(SIGIOT)); +#endif +#ifdef SIGBUS + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGBUS"_s), jsNumber(SIGBUS)); +#endif +#ifdef SIGFPE + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGFPE"_s), jsNumber(SIGFPE)); +#endif +#ifdef SIGKILL + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGKILL"_s), jsNumber(SIGKILL)); +#endif +#ifdef SIGUSR1 + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGUSR1"_s), jsNumber(SIGUSR1)); +#endif +#ifdef SIGSEGV + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGSEGV"_s), jsNumber(SIGSEGV)); +#endif +#ifdef SIGUSR2 + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGUSR2"_s), jsNumber(SIGUSR2)); +#endif +#ifdef SIGPIPE + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGPIPE"_s), jsNumber(SIGPIPE)); +#endif +#ifdef SIGALRM + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGALRM"_s), jsNumber(SIGALRM)); +#endif +#ifdef SIGTERM + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGTERM"_s), jsNumber(SIGTERM)); +#endif +#ifdef SIGCHLD + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGCHLD"_s), jsNumber(SIGCHLD)); +#endif +#ifdef SIGSTKFLT + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGSTKFLT"_s), jsNumber(SIGSTKFLT)); +#endif +#ifdef SIGCONT + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGCONT"_s), jsNumber(SIGCONT)); +#endif +#ifdef SIGSTOP + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGSTOP"_s), jsNumber(SIGSTOP)); +#endif +#ifdef SIGTSTP + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGTSTP"_s), jsNumber(SIGTSTP)); +#endif +#ifdef SIGBREAK + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGBREAK"_s), jsNumber(SIGBREAK)); +#endif +#ifdef SIGTTIN + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGTTIN"_s), jsNumber(SIGTTIN)); +#endif +#ifdef SIGTTOU + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGTTOU"_s), jsNumber(SIGTTOU)); +#endif +#ifdef SIGURG + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGURG"_s), jsNumber(SIGURG)); +#endif +#ifdef SIGXCPU + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGXCPU"_s), jsNumber(SIGXCPU)); +#endif +#ifdef SIGXFSZ + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGXFSZ"_s), jsNumber(SIGXFSZ)); +#endif +#ifdef SIGVTALRM + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGVTALRM"_s), jsNumber(SIGVTALRM)); +#endif +#ifdef SIGPROF + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGPROF"_s), jsNumber(SIGPROF)); +#endif +#ifdef SIGWINCH + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGWINCH"_s), jsNumber(SIGWINCH)); +#endif +#ifdef SIGIO + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGIO"_s), jsNumber(SIGIO)); +#endif +#ifdef SIGPOLL + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGPOLL"_s), jsNumber(SIGPOLL)); +#endif +#ifdef SIGLOST + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGLOST"_s), jsNumber(SIGLOST)); +#endif +#ifdef SIGPWR + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGPWR"_s), jsNumber(SIGPWR)); +#endif +#ifdef SIGINFO + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGINFO"_s), jsNumber(SIGINFO)); +#endif +#ifdef SIGSYS + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGSYS"_s), jsNumber(SIGSYS)); +#endif +#ifdef SIGUNUSED + signalsObj->putDirect(vm, Identifier::fromString(vm, "SIGUNUSED"_s), jsNumber(SIGUNUSED)); +#endif + priorityObj->putDirect(vm, Identifier::fromString(vm, "PRIORITY_LOW"_s), jsNumber(19)); + priorityObj->putDirect(vm, Identifier::fromString(vm, "PRIORITY_BELOW_NORMAL"_s), jsNumber(10)); + priorityObj->putDirect(vm, Identifier::fromString(vm, "PRIORITY_NORMAL"_s), jsNumber(0)); + priorityObj->putDirect(vm, Identifier::fromString(vm, "PRIORITY_ABOVE_NORMAL"_s), jsNumber(-7)); + priorityObj->putDirect(vm, Identifier::fromString(vm, "PRIORITY_HIGH"_s), jsNumber(-14)); + priorityObj->putDirect(vm, Identifier::fromString(vm, "PRIORITY_HIGHEST"_s), jsNumber(-20)); +#ifdef RTLD_LAZY + dlopenObj->putDirect(vm, Identifier::fromString(vm, "RTLD_LAZY"_s), jsNumber(RTLD_LAZY)); +#endif +#ifdef RTLD_NOW + dlopenObj->putDirect(vm, Identifier::fromString(vm, "RTLD_NOW"_s), jsNumber(RTLD_NOW)); +#endif +#ifdef RTLD_GLOBAL + dlopenObj->putDirect(vm, Identifier::fromString(vm, "RTLD_GLOBAL"_s), jsNumber(RTLD_GLOBAL)); +#endif +#ifdef RTLD_LOCAL + dlopenObj->putDirect(vm, Identifier::fromString(vm, "RTLD_LOCAL"_s), jsNumber(RTLD_LOCAL)); +#endif +#ifdef RTLD_DEEPBIND + dlopenObj->putDirect(vm, Identifier::fromString(vm, "RTLD_DEEPBIND"_s), jsNumber(RTLD_DEEPBIND)); +#endif + return osObj; +} + +static JSValue processBindingConstantsGetTrace(VM& vm, JSObject* bindingObject) +{ + auto globalObject = bindingObject->globalObject(); + auto object = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 26); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_BEGIN"_s)), jsNumber(66)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_END"_s)), jsNumber(69)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_COMPLETE"_s)), jsNumber(88)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_INSTANT"_s)), jsNumber(73)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_ASYNC_BEGIN"_s)), jsNumber(83)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_ASYNC_STEP_INTO"_s)), jsNumber(84)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_ASYNC_STEP_PAST"_s)), jsNumber(112)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_ASYNC_END"_s)), jsNumber(70)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN"_s)), jsNumber(98)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_NESTABLE_ASYNC_END"_s)), jsNumber(101)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT"_s)), jsNumber(110)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_FLOW_BEGIN"_s)), jsNumber(115)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_FLOW_STEP"_s)), jsNumber(116)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_FLOW_END"_s)), jsNumber(102)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_METADATA"_s)), jsNumber(77)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_COUNTER"_s)), jsNumber(67)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_SAMPLE"_s)), jsNumber(80)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_CREATE_OBJECT"_s)), jsNumber(78)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_SNAPSHOT_OBJECT"_s)), jsNumber(79)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_DELETE_OBJECT"_s)), jsNumber(68)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_MEMORY_DUMP"_s)), jsNumber(118)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_MARK"_s)), jsNumber(82)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_CLOCK_SYNC"_s)), jsNumber(99)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_ENTER_CONTEXT"_s)), jsNumber(40)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_LEAVE_CONTEXT"_s)), jsNumber(41)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TRACE_EVENT_PHASE_LINK_IDS"_s)), jsNumber(61)); + return object; +} + +static JSValue processBindingConstantsGetFs(VM& vm, JSObject* bindingObject) +{ + auto globalObject = bindingObject->globalObject(); + auto object = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 26); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_FS_SYMLINK_DIR"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_FS_SYMLINK_JUNCTION"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_RDONLY"_s)), jsNumber(O_RDONLY)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_WRONLY"_s)), jsNumber(O_WRONLY)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_RDWR"_s)), jsNumber(O_RDWR)); + + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_UNKNOWN"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_FILE"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_DIR"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_LINK"_s)), jsNumber(3)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_FIFO"_s)), jsNumber(4)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_SOCKET"_s)), jsNumber(5)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_CHAR"_s)), jsNumber(6)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_DIRENT_BLOCK"_s)), jsNumber(7)); + + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFMT"_s)), jsNumber(S_IFMT)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFREG"_s)), jsNumber(S_IFREG)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFDIR"_s)), jsNumber(S_IFDIR)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFCHR"_s)), jsNumber(S_IFCHR)); +#ifdef S_IFBLK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFBLK"_s)), jsNumber(S_IFBLK)); +#endif +#ifdef S_IFIFO + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFIFO"_s)), jsNumber(S_IFIFO)); +#endif +#ifdef S_IFLNK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFLNK"_s)), jsNumber(S_IFLNK)); +#endif +#ifdef S_IFSOCK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IFSOCK"_s)), jsNumber(S_IFSOCK)); +#endif +#ifdef O_CREAT + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_CREAT"_s)), jsNumber(O_CREAT)); +#endif +#ifdef O_EXCL + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_EXCL"_s)), jsNumber(O_EXCL)); +#endif + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_FS_O_FILEMAP"_s)), jsNumber(0)); + +#ifdef O_NOCTTY + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_NOCTTY"_s)), jsNumber(O_NOCTTY)); +#endif +#ifdef O_TRUNC + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_TRUNC"_s)), jsNumber(O_TRUNC)); +#endif +#ifdef O_APPEND + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_APPEND"_s)), jsNumber(O_APPEND)); +#endif +#ifdef O_DIRECTORY + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_DIRECTORY"_s)), jsNumber(O_DIRECTORY)); +#endif +#ifdef O_EXCL + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_EXCL"_s)), jsNumber(O_EXCL)); +#endif +#ifdef O_NOATIME + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_NOATIME"_s)), jsNumber(O_NOATIME)); +#endif +#ifdef O_NOFOLLOW + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_NOFOLLOW"_s)), jsNumber(O_NOFOLLOW)); +#endif +#ifdef O_SYNC + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_SYNC"_s)), jsNumber(O_SYNC)); +#endif +#ifdef O_DSYNC + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_DSYNC"_s)), jsNumber(O_DSYNC)); +#endif +#ifdef O_SYMLINK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_SYMLINK"_s)), jsNumber(O_SYMLINK)); +#endif +#ifdef O_DIRECT + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_DIRECT"_s)), jsNumber(O_DIRECT)); +#endif +#ifdef O_NONBLOCK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "O_NONBLOCK"_s)), jsNumber(O_NONBLOCK)); +#endif +#ifdef S_IRWXU + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IRWXU"_s)), jsNumber(S_IRWXU)); +#endif +#ifdef S_IRUSR + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IRUSR"_s)), jsNumber(S_IRUSR)); +#endif +#ifdef S_IWUSR + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IWUSR"_s)), jsNumber(S_IWUSR)); +#endif +#ifdef S_IXUSR + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IXUSR"_s)), jsNumber(S_IXUSR)); +#endif +#ifdef S_IRWXG + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IRWXG"_s)), jsNumber(S_IRWXG)); +#endif +#ifdef S_IRGRP + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IRGRP"_s)), jsNumber(S_IRGRP)); +#endif +#ifdef S_IWGRP + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IWGRP"_s)), jsNumber(S_IWGRP)); +#endif +#ifdef S_IXGRP + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IXGRP"_s)), jsNumber(S_IXGRP)); +#endif +#ifdef S_IRWXO + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IRWXO"_s)), jsNumber(S_IRWXO)); +#endif +#ifdef S_IROTH + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IROTH"_s)), jsNumber(S_IROTH)); +#endif +#ifdef S_IWOTH + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IWOTH"_s)), jsNumber(S_IWOTH)); +#endif +#ifdef S_IXOTH + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "S_IXOTH"_s)), jsNumber(S_IXOTH)); +#endif +#ifdef F_OK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "F_OK"_s)), jsNumber(F_OK)); +#endif +#ifdef R_OK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "R_OK"_s)), jsNumber(R_OK)); +#endif +#ifdef W_OK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "W_OK"_s)), jsNumber(W_OK)); +#endif +#ifdef X_OK + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "X_OK"_s)), jsNumber(X_OK)); +#endif + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_FS_COPYFILE_EXCL"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "COPYFILE_EXCL"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_FS_COPYFILE_FICLONE"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "COPYFILE_FICLONE"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UV_FS_COPYFILE_FICLONE_FORCE"_s)), jsNumber(4)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "COPYFILE_FICLONE_FORCE"_s)), jsNumber(4)); + return object; +} + +static JSValue processBindingConstantsGetCrypto(VM& vm, JSObject* bindingObject) +{ + auto globalObject = bindingObject->globalObject(); + auto object = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype()); +#ifdef OPENSSL_VERSION_NUMBER + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "OPENSSL_VERSION_NUMBER"_s)), jsNumber(OPENSSL_VERSION_NUMBER)); +#endif +#ifdef SSL_OP_ALL + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_ALL"_s)), jsNumber(SSL_OP_ALL)); +#endif +#ifdef SSL_OP_ALLOW_NO_DHE_KEX + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_ALLOW_NO_DHE_KEX"_s)), jsNumber(SSL_OP_ALLOW_NO_DHE_KEX)); +#endif +#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION"_s)), jsNumber(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)); +#endif +#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_CIPHER_SERVER_PREFERENCE"_s)), jsNumber(SSL_OP_CIPHER_SERVER_PREFERENCE)); +#endif +#ifdef SSL_OP_CISCO_ANYCONNECT + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_CISCO_ANYCONNECT"_s)), jsNumber(SSL_OP_CISCO_ANYCONNECT)); +#endif +#ifdef SSL_OP_COOKIE_EXCHANGE + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_COOKIE_EXCHANGE"_s)), jsNumber(SSL_OP_COOKIE_EXCHANGE)); +#endif +#ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_CRYPTOPRO_TLSEXT_BUG"_s)), jsNumber(SSL_OP_CRYPTOPRO_TLSEXT_BUG)); +#endif +#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS"_s)), jsNumber(SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)); +#endif +#ifdef SSL_OP_LEGACY_SERVER_CONNECT + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_LEGACY_SERVER_CONNECT"_s)), jsNumber(SSL_OP_LEGACY_SERVER_CONNECT)); +#endif +#ifdef SSL_OP_NO_COMPRESSION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_COMPRESSION"_s)), jsNumber(SSL_OP_NO_COMPRESSION)); +#endif +#ifdef SSL_OP_NO_ENCRYPT_THEN_MAC + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_ENCRYPT_THEN_MAC"_s)), jsNumber(SSL_OP_NO_ENCRYPT_THEN_MAC)); +#endif +#ifdef SSL_OP_NO_QUERY_MTU + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_QUERY_MTU"_s)), jsNumber(SSL_OP_NO_QUERY_MTU)); +#endif +#ifdef SSL_OP_NO_RENEGOTIATION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_RENEGOTIATION"_s)), jsNumber(SSL_OP_NO_RENEGOTIATION)); +#endif +#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION"_s)), jsNumber(SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)); +#endif +#ifdef SSL_OP_NO_SSLv2 + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_SSLv2"_s)), jsNumber(SSL_OP_NO_SSLv2)); +#endif +#ifdef SSL_OP_NO_SSLv3 + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_SSLv3"_s)), jsNumber(SSL_OP_NO_SSLv3)); +#endif +#ifdef SSL_OP_NO_TICKET + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_TICKET"_s)), jsNumber(SSL_OP_NO_TICKET)); +#endif +#ifdef SSL_OP_NO_TLSv1 + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_TLSv1"_s)), jsNumber(SSL_OP_NO_TLSv1)); +#endif +#ifdef SSL_OP_NO_TLSv1_1 + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_TLSv1_1"_s)), jsNumber(SSL_OP_NO_TLSv1_1)); +#endif +#ifdef SSL_OP_NO_TLSv1_2 + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_TLSv1_2"_s)), jsNumber(SSL_OP_NO_TLSv1_2)); +#endif +#ifdef SSL_OP_NO_TLSv1_3 + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_NO_TLSv1_3"_s)), jsNumber(SSL_OP_NO_TLSv1_3)); +#endif +#ifdef SSL_OP_PRIORITIZE_CHACHA + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_PRIORITIZE_CHACHA"_s)), jsNumber(SSL_OP_PRIORITIZE_CHACHA)); +#endif +#ifdef SSL_OP_TLS_ROLLBACK_BUG + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "SSL_OP_TLS_ROLLBACK_BUG"_s)), jsNumber(SSL_OP_TLS_ROLLBACK_BUG)); +#endif +#ifndef OPENSSL_NO_ENGINE +#ifdef ENGINE_METHOD_RSA + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_RSA"_s)), jsNumber(ENGINE_METHOD_RSA)); +#endif +#ifdef ENGINE_METHOD_DSA + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_DSA"_s)), jsNumber(ENGINE_METHOD_DSA)); +#endif +#ifdef ENGINE_METHOD_DH + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_DH"_s)), jsNumber(ENGINE_METHOD_DH)); +#endif +#ifdef ENGINE_METHOD_RAND + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_RAND"_s)), jsNumber(ENGINE_METHOD_RAND)); +#endif +#ifdef ENGINE_METHOD_EC + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_EC"_s)), jsNumber(ENGINE_METHOD_EC)); +#endif +#ifdef ENGINE_METHOD_CIPHERS + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_CIPHERS"_s)), jsNumber(ENGINE_METHOD_CIPHERS)); +#endif +#ifdef ENGINE_METHOD_DIGESTS + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_DIGESTS"_s)), jsNumber(ENGINE_METHOD_DIGESTS)); +#endif +#ifdef ENGINE_METHOD_PKEY_METHS + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_PKEY_METHS"_s)), jsNumber(ENGINE_METHOD_PKEY_METHS)); +#endif +#ifdef ENGINE_METHOD_PKEY_ASN1_METHS + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_PKEY_ASN1_METHS"_s)), jsNumber(ENGINE_METHOD_PKEY_ASN1_METHS)); +#endif +#ifdef ENGINE_METHOD_ALL + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_ALL"_s)), jsNumber(ENGINE_METHOD_ALL)); +#endif +#ifdef ENGINE_METHOD_NONE + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ENGINE_METHOD_NONE"_s)), jsNumber(ENGINE_METHOD_NONE)); +#endif +#endif // !OPENSSL_NO_ENGINE +#ifdef DH_CHECK_P_NOT_SAFE_PRIME + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "DH_CHECK_P_NOT_SAFE_PRIME"_s)), jsNumber(DH_CHECK_P_NOT_SAFE_PRIME)); +#endif +#ifdef DH_CHECK_P_NOT_PRIME + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "DH_CHECK_P_NOT_PRIME"_s)), jsNumber(DH_CHECK_P_NOT_PRIME)); +#endif +#ifdef DH_UNABLE_TO_CHECK_GENERATOR + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "DH_UNABLE_TO_CHECK_GENERATOR"_s)), jsNumber(DH_UNABLE_TO_CHECK_GENERATOR)); +#endif +#ifdef DH_NOT_SUITABLE_GENERATOR + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "DH_NOT_SUITABLE_GENERATOR"_s)), jsNumber(DH_NOT_SUITABLE_GENERATOR)); +#endif +#ifdef RSA_PKCS1_PADDING + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_PKCS1_PADDING"_s)), jsNumber(RSA_PKCS1_PADDING)); +#endif +#ifdef RSA_SSLV23_PADDING + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_SSLV23_PADDING"_s)), jsNumber(RSA_SSLV23_PADDING)); +#endif +#ifdef RSA_NO_PADDING + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_NO_PADDING"_s)), jsNumber(RSA_NO_PADDING)); +#endif +#ifdef RSA_PKCS1_OAEP_PADDING + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_PKCS1_OAEP_PADDING"_s)), jsNumber(RSA_PKCS1_OAEP_PADDING)); +#endif +#ifdef RSA_X931_PADDING + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_X931_PADDING"_s)), jsNumber(RSA_X931_PADDING)); +#endif +#ifdef RSA_PKCS1_PSS_PADDING + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_PKCS1_PSS_PADDING"_s)), jsNumber(RSA_PKCS1_PSS_PADDING)); +#endif +#ifdef RSA_PSS_SALTLEN_DIGEST + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_PSS_SALTLEN_DIGEST"_s)), jsNumber(RSA_PSS_SALTLEN_DIGEST)); +#endif +#ifdef RSA_PSS_SALTLEN_MAX_SIGN + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_PSS_SALTLEN_MAX_SIGN"_s)), jsNumber(RSA_PSS_SALTLEN_MAX_SIGN)); +#endif +#ifdef RSA_PSS_SALTLEN_AUTO + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "RSA_PSS_SALTLEN_AUTO"_s)), jsNumber(RSA_PSS_SALTLEN_AUTO)); +#endif + auto cipherList = String("TLS_AES_256_GCM_SHA384:" + "TLS_CHACHA20_POLY1305_SHA256:" + "TLS_AES_128_GCM_SHA256:" + "ECDHE-RSA-AES128-GCM-SHA256:" + "ECDHE-ECDSA-AES128-GCM-SHA256:" + "ECDHE-RSA-AES256-GCM-SHA384:" + "ECDHE-ECDSA-AES256-GCM-SHA384:" + "DHE-RSA-AES128-GCM-SHA256:" + "ECDHE-RSA-AES128-SHA256:" + "DHE-RSA-AES128-SHA256:" + "ECDHE-RSA-AES256-SHA384:" + "DHE-RSA-AES256-SHA384:" + "ECDHE-RSA-AES256-SHA256:" + "DHE-RSA-AES256-SHA256:" + "HIGH:" + "!aNULL:" + "!eNULL:" + "!EXPORT:" + "!DES:" + "!RC4:" + "!MD5:" + "!PSK:" + "!SRP:" + "!CAMELLIA"_s); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "defaultCoreCipherList"_s)), + jsString(vm, cipherList)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "defaultCipherList"_s)), + jsString(vm, cipherList)); +#ifdef TLS1_VERSION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TLS1_VERSION"_s)), jsNumber(TLS1_VERSION)); +#endif +#ifdef TLS1_1_VERSION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TLS1_1_VERSION"_s)), jsNumber(TLS1_1_VERSION)); +#endif +#ifdef TLS1_2_VERSION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TLS1_2_VERSION"_s)), jsNumber(TLS1_2_VERSION)); +#endif +#ifdef TLS1_3_VERSION + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "TLS1_3_VERSION"_s)), jsNumber(TLS1_3_VERSION)); +#endif + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "POINT_CONVERSION_COMPRESSED"_s)), jsNumber(POINT_CONVERSION_COMPRESSED)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "POINT_CONVERSION_UNCOMPRESSED"_s)), jsNumber(POINT_CONVERSION_UNCOMPRESSED)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "POINT_CONVERSION_HYBRID"_s)), jsNumber(POINT_CONVERSION_HYBRID)); + return object; +} + +static JSValue processBindingConstantsGetZlib(VM& vm, JSObject* bindingObject) +{ + auto globalObject = bindingObject->globalObject(); + auto object = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype()); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_NO_FLUSH"_s)), jsNumber(Z_NO_FLUSH)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_PARTIAL_FLUSH"_s)), jsNumber(Z_PARTIAL_FLUSH)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_SYNC_FLUSH"_s)), jsNumber(Z_SYNC_FLUSH)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_FULL_FLUSH"_s)), jsNumber(Z_FULL_FLUSH)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_FINISH"_s)), jsNumber(Z_FINISH)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_BLOCK"_s)), jsNumber(Z_BLOCK)); + + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_OK"_s)), jsNumber(Z_OK)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_STREAM_END"_s)), jsNumber(Z_STREAM_END)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_NEED_DICT"_s)), jsNumber(Z_NEED_DICT)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_ERRNO"_s)), jsNumber(Z_ERRNO)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_STREAM_ERROR"_s)), jsNumber(Z_STREAM_ERROR)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_DATA_ERROR"_s)), jsNumber(Z_DATA_ERROR)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MEM_ERROR"_s)), jsNumber(Z_MEM_ERROR)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_BUF_ERROR"_s)), jsNumber(Z_BUF_ERROR)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_VERSION_ERROR"_s)), jsNumber(Z_VERSION_ERROR)); + + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_NO_COMPRESSION"_s)), jsNumber(Z_NO_COMPRESSION)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_BEST_SPEED"_s)), jsNumber(Z_BEST_SPEED)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_BEST_COMPRESSION"_s)), jsNumber(Z_BEST_COMPRESSION)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_DEFAULT_COMPRESSION"_s)), jsNumber(Z_DEFAULT_COMPRESSION)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_FILTERED"_s)), jsNumber(Z_FILTERED)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_HUFFMAN_ONLY"_s)), jsNumber(Z_HUFFMAN_ONLY)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_RLE"_s)), jsNumber(Z_RLE)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_FIXED"_s)), jsNumber(Z_FIXED)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_DEFAULT_STRATEGY"_s)), jsNumber(Z_DEFAULT_STRATEGY)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "ZLIB_VERNUM"_s)), jsNumber(ZLIB_VERNUM)); + + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "DEFLATE"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "INFLATE"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "GZIP"_s)), jsNumber(3)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "GUNZIP"_s)), jsNumber(4)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "DEFLATERAW"_s)), jsNumber(5)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "INFLATERAW"_s)), jsNumber(6)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "UNZIP"_s)), jsNumber(7)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODE"_s)), jsNumber(8)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_ENCODE"_s)), jsNumber(9)); + + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MIN_WINDOWBITS"_s)), jsNumber(8)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MAX_WINDOWBITS"_s)), jsNumber(15)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_DEFAULT_WINDOWBITS"_s)), jsNumber(15)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MIN_CHUNK"_s)), jsNumber(64)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MAX_CHUNK"_s)), jsNumber(INFINITY)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_DEFAULT_CHUNK"_s)), jsNumber(16384)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MIN_MEMLEVEL"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MAX_MEMLEVEL"_s)), jsNumber(9)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_DEFAULT_MEMLEVEL"_s)), jsNumber(8)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MIN_LEVEL"_s)), jsNumber(-1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_MAX_LEVEL"_s)), jsNumber(9)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "Z_DEFAULT_LEVEL"_s)), jsNumber(-1)); + + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_OPERATION_PROCESS"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_OPERATION_FLUSH"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_OPERATION_FINISH"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_OPERATION_EMIT_METADATA"_s)), jsNumber(3)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_MODE"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MODE_GENERIC"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MODE_TEXT"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MODE_FONT"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DEFAULT_MODE"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_QUALITY"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MIN_QUALITY"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MAX_QUALITY"_s)), jsNumber(11)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DEFAULT_QUALITY"_s)), jsNumber(11)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_LGWIN"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MIN_WINDOW_BITS"_s)), jsNumber(10)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MAX_WINDOW_BITS"_s)), jsNumber(24)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_LARGE_MAX_WINDOW_BITS"_s)), jsNumber(30)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DEFAULT_WINDOW"_s)), jsNumber(22)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_LGBLOCK"_s)), jsNumber(3)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MIN_INPUT_BLOCK_BITS"_s)), jsNumber(16)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_MAX_INPUT_BLOCK_BITS"_s)), jsNumber(24)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING"_s)), jsNumber(4)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_SIZE_HINT"_s)), jsNumber(5)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_LARGE_WINDOW"_s)), jsNumber(6)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_NPOSTFIX"_s)), jsNumber(7)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_PARAM_NDIRECT"_s)), jsNumber(8)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_RESULT_ERROR"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_RESULT_SUCCESS"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT"_s)), jsNumber(3)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_PARAM_LARGE_WINDOW"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_NO_ERROR"_s)), jsNumber(0)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_SUCCESS"_s)), jsNumber(1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_NEEDS_MORE_INPUT"_s)), jsNumber(2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_NEEDS_MORE_OUTPUT"_s)), jsNumber(3)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE"_s)), jsNumber(-1)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_RESERVED"_s)), jsNumber(-2)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE"_s)), jsNumber(-3)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET"_s)), jsNumber(-4)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME"_s)), jsNumber(-5)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_CL_SPACE"_s)), jsNumber(-6)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE"_s)), jsNumber(-7)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT"_s)), jsNumber(-8)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1"_s)), jsNumber(-9)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2"_s)), jsNumber(-10)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_TRANSFORM"_s)), jsNumber(-11)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_DICTIONARY"_s)), jsNumber(-12)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS"_s)), jsNumber(-13)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_PADDING_1"_s)), jsNumber(-14)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_PADDING_2"_s)), jsNumber(-15)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_FORMAT_DISTANCE"_s)), jsNumber(-16)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET"_s)), jsNumber(-19)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_INVALID_ARGUMENTS"_s)), jsNumber(-20)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES"_s)), jsNumber(-21)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS"_s)), jsNumber(-22)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP"_s)), jsNumber(-25)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1"_s)), jsNumber(-26)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2"_s)), jsNumber(-27)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES"_s)), jsNumber(-30)); + object->putDirect(vm, PropertyName(Identifier::fromString(vm, "BROTLI_DECODER_ERROR_UNREACHABLE"_s)), jsNumber(-31)); + + return object; +} + +static const HashTableValue ProcessBindingConstantsValues[] = { + { "os"_s, static_cast(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, processBindingConstantsGetOs } }, + { "fs"_s, static_cast(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, processBindingConstantsGetFs } }, + { "crypto"_s, static_cast(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, processBindingConstantsGetCrypto } }, + { "zlib"_s, static_cast(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, processBindingConstantsGetZlib } }, + { "trace"_s, static_cast(PropertyAttribute::PropertyCallback), NoIntrinsic, { HashTableValue::LazyPropertyType, processBindingConstantsGetTrace } }, +}; + +const ClassInfo ProcessBindingConstants::s_info = { "ProcessBindingConstants"_s, Base::info(), nullptr, nullptr, CREATE_METHOD_TABLE(ProcessBindingConstants) }; + +ProcessBindingConstants* ProcessBindingConstants::create(VM& vm, Structure* structure) +{ + ProcessBindingConstants* obj = new (NotNull, allocateCell(vm)) ProcessBindingConstants(vm, structure); + obj->finishCreation(vm); + return obj; +} + +Structure* ProcessBindingConstants::createStructure(VM& vm, JSGlobalObject* globalObject) +{ + return Structure::create(vm, globalObject, jsNull(), TypeInfo(ObjectType, StructureFlags), ProcessBindingConstants::info()); +} + +void ProcessBindingConstants::finishCreation(JSC::VM& vm) +{ + Base::finishCreation(vm); + reifyStaticProperties(vm, ProcessBindingConstants::info(), ProcessBindingConstantsValues, *this); + ASSERT(inherits(vm, info())); +} + +template +void ProcessBindingConstants::visitChildrenImpl(JSCell* cell, Visitor& visitor) +{ + ProcessBindingConstants* thisObject = jsCast(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitChildren(thisObject, visitor); +} + +DEFINE_VISIT_CHILDREN(ProcessBindingConstants); + +} // namespace Bun diff --git a/src/bun.js/bindings/ProcessBindingConstants.h b/src/bun.js/bindings/ProcessBindingConstants.h new file mode 100644 index 00000000000000..5a9be7ce78c975 --- /dev/null +++ b/src/bun.js/bindings/ProcessBindingConstants.h @@ -0,0 +1,32 @@ +#include "root.h" + +namespace Bun { +using namespace JSC; + +// The object returned from process.binding('constants') +class ProcessBindingConstants final : public JSC::JSNonFinalObject { +public: + DECLARE_INFO; + DECLARE_VISIT_CHILDREN; + + using Base = JSC::JSNonFinalObject; + + static ProcessBindingConstants* create(JSC::VM& vm, JSC::Structure* structure); + static Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject); + + template + static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + return &vm.plainObjectSpace(); + } + +private: + void finishCreation(JSC::VM& vm); + + ProcessBindingConstants(JSC::VM& vm, JSC::Structure* structure) + : Base(vm, structure) + { + } +}; + +} // namespace Bun diff --git a/src/bun.js/bindings/RegularExpression.cpp b/src/bun.js/bindings/RegularExpression.cpp new file mode 100644 index 00000000000000..1c8df1bc05ebd8 --- /dev/null +++ b/src/bun.js/bindings/RegularExpression.cpp @@ -0,0 +1,35 @@ +#include "root.h" +#include "headers-handwritten.h" +#include "JavaScriptCore/RegularExpression.h" + +using namespace JSC; +using namespace JSC::Yarr; + +extern "C" RegularExpression* Yarr__RegularExpression__init(BunString pattern, uint16_t flags) +{ + return new RegularExpression(Bun::toWTFString(pattern), OptionSet(static_cast(flags))); +} +extern "C" void Yarr__RegularExpression__deinit(RegularExpression* re) +{ + delete re; +} +extern "C" bool Yarr__RegularExpression__isValid(RegularExpression* re) +{ + return re->isValid(); +} +extern "C" int Yarr__RegularExpression__matchedLength(RegularExpression* re) +{ + return re->matchedLength(); +} +extern "C" int Yarr__RegularExpression__searchRev(RegularExpression* re, BunString string) +{ + return re->searchRev(Bun::toWTFString(string)); +} +// extern "C" int Yarr__RegularExpression__match(RegularExpression* re, BunString string, int32_t start, int32_t* matchLength) +// { +// return re->match(Bun::toWTFString(string), start, matchLength); +// } +extern "C" int Yarr__RegularExpression__matches(RegularExpression* re, BunString string) +{ + return re->match(Bun::toWTFString(string), 0, 0); +} \ No newline at end of file diff --git a/src/bun.js/bindings/RegularExpression.zig b/src/bun.js/bindings/RegularExpression.zig new file mode 100644 index 00000000000000..9c3da4fa2717de --- /dev/null +++ b/src/bun.js/bindings/RegularExpression.zig @@ -0,0 +1,57 @@ +const bun = @import("root").bun; + +pub const RegularExpression = opaque { + pub const Flags = enum(u16) { + none = 0, + + hasIndices = 1 << 0, + global = 1 << 1, + ignoreCase = 1 << 2, + multiline = 1 << 3, + dotAll = 1 << 4, + unicode = 1 << 5, + unicodeSets = 1 << 6, + sticky = 1 << 7, + }; + + extern fn Yarr__RegularExpression__init(pattern: bun.String, flags: u16) *RegularExpression; + extern fn Yarr__RegularExpression__deinit(pattern: *RegularExpression) void; + extern fn Yarr__RegularExpression__isValid(this: *RegularExpression) bool; + extern fn Yarr__RegularExpression__matchedLength(this: *RegularExpression) i32; + extern fn Yarr__RegularExpression__searchRev(this: *RegularExpression) i32; + extern fn Yarr__RegularExpression__matches(this: *RegularExpression, string: bun.String) i32; + + pub inline fn init(pattern: bun.String, flags: Flags) !*RegularExpression { + var regex = Yarr__RegularExpression__init(pattern, @intFromEnum(flags)); + if (!regex.isValid()) { + regex.deinit(); + return error.InvalidRegex; + } + return regex; + } + + pub inline fn isValid(this: *RegularExpression) bool { + return Yarr__RegularExpression__isValid(this); + } + + // Reserving `match` for a full match result. + // pub inline fn match(this: *RegularExpression, str: bun.String, startFrom: i32) MatchResult { + // } + + // Simple boolean matcher + pub inline fn matches(this: *RegularExpression, str: bun.String) bool { + return Yarr__RegularExpression__matches(this, str) > 0; + } + + pub inline fn searchRev(this: *RegularExpression, str: bun.String) i32 { + return Yarr__RegularExpression__searchRev(this, str); + } + + pub inline fn matchedLength(this: *RegularExpression) i32 { + return Yarr__RegularExpression__matchedLength(this); + } + + pub inline fn deinit(this: *RegularExpression) void { + Yarr__RegularExpression__deinit(this); + } +}; diff --git a/src/bun.js/bindings/ScriptExecutionContext.cpp b/src/bun.js/bindings/ScriptExecutionContext.cpp index d93478ed8c0ad6..eab41d584f79bb 100644 --- a/src/bun.js/bindings/ScriptExecutionContext.cpp +++ b/src/bun.js/bindings/ScriptExecutionContext.cpp @@ -1,10 +1,12 @@ #include "root.h" #include "headers.h" #include "ScriptExecutionContext.h" +#include "MessagePort.h" #include "webcore/WebSocket.h" #include "libusockets.h" #include "_libusockets.h" +#include "BunClientData.h" extern "C" void Bun__startLoop(us_loop_t* loop); @@ -12,6 +14,9 @@ namespace WebCore { static std::atomic lastUniqueIdentifier = 0; +WTF_MAKE_ISO_ALLOCATED_IMPL(EventLoopTask); +WTF_MAKE_ISO_ALLOCATED_IMPL(ScriptExecutionContext); + static Lock allScriptExecutionContextsMapLock; static HashMap& allScriptExecutionContextsMap() WTF_REQUIRES_LOCK(allScriptExecutionContextsMapLock) { @@ -58,6 +63,33 @@ us_socket_context_t* ScriptExecutionContext::webSocketContextSSL() return m_ssl_client_websockets_ctx; } +extern "C" void Bun__eventLoop__incrementRefConcurrently(void* bunVM, int delta); + +void ScriptExecutionContext::refEventLoop() +{ + Bun__eventLoop__incrementRefConcurrently(WebCore::clientData(vm())->bunVM, 1); +} +void ScriptExecutionContext::unrefEventLoop() +{ + Bun__eventLoop__incrementRefConcurrently(WebCore::clientData(vm())->bunVM, -1); +} + +ScriptExecutionContext::~ScriptExecutionContext() +{ + checkConsistency(); + + { + Locker locker { allScriptExecutionContextsMapLock }; + ASSERT_WITH_MESSAGE(!allScriptExecutionContextsMap().contains(m_identifier), "A ScriptExecutionContext subclass instance implementing postTask should have already removed itself from the map"); + } + + auto postMessageCompletionHandlers = WTFMove(m_processMessageWithMessagePortsSoonHandlers); + for (auto& completionHandler : postMessageCompletionHandlers) + completionHandler(); + + while (auto* destructionObserver = m_destructionObservers.takeAny()) + destructionObserver->contextDestroyed(); +} bool ScriptExecutionContext::postTaskTo(ScriptExecutionContextIdentifier identifier, Function&& task) { @@ -71,6 +103,125 @@ bool ScriptExecutionContext::postTaskTo(ScriptExecutionContextIdentifier identif return true; } +void ScriptExecutionContext::didCreateDestructionObserver(ContextDestructionObserver& observer) +{ + ASSERT(!m_inScriptExecutionContextDestructor); + m_destructionObservers.add(&observer); +} + +void ScriptExecutionContext::willDestroyDestructionObserver(ContextDestructionObserver& observer) +{ + m_destructionObservers.remove(&observer); +} + +extern "C" void* Bun__getVM(); + +bool ScriptExecutionContext::isContextThread() +{ + auto clientData = WebCore::clientData(vm()); + return clientData->bunVM == Bun__getVM(); +} + +bool ScriptExecutionContext::ensureOnContextThread(ScriptExecutionContextIdentifier identifier, Function&& task) +{ + ScriptExecutionContext* context = nullptr; + { + Locker locker { allScriptExecutionContextsMapLock }; + context = allScriptExecutionContextsMap().get(identifier); + + if (!context) + return false; + + if (!context->isContextThread()) { + context->postTaskConcurrently(WTFMove(task)); + return true; + } + } + + task(*context); + return true; +} + +bool ScriptExecutionContext::ensureOnMainThread(Function&& task) +{ + Locker locker { allScriptExecutionContextsMapLock }; + auto* context = allScriptExecutionContextsMap().get(1); + + if (!context) { + return false; + } + + context->postTaskConcurrently(WTFMove(task)); + return true; +} + +void ScriptExecutionContext::processMessageWithMessagePortsSoon(CompletionHandler&& completionHandler) +{ + ASSERT(isContextThread()); + m_processMessageWithMessagePortsSoonHandlers.append(WTFMove(completionHandler)); + + if (m_willProcessMessageWithMessagePortsSoon) { + return; + } + + m_willProcessMessageWithMessagePortsSoon = true; + + postTask([](ScriptExecutionContext& context) { + context.dispatchMessagePortEvents(); + }); +} + +void ScriptExecutionContext::dispatchMessagePortEvents() +{ + ASSERT(isContextThread()); + checkConsistency(); + + ASSERT(m_willprocessMessageWithMessagePortsSoon); + m_willProcessMessageWithMessagePortsSoon = false; + + auto completionHandlers = std::exchange(m_processMessageWithMessagePortsSoonHandlers, Vector> {}); + + // Make a frozen copy of the ports so we can iterate while new ones might be added or destroyed. + for (auto* messagePort : copyToVector(m_messagePorts)) { + // The port may be destroyed, and another one created at the same address, + // but this is harmless. The worst that can happen as a result is that + // dispatchMessages() will be called needlessly. + if (m_messagePorts.contains(messagePort) && messagePort->started()) + messagePort->dispatchMessages(); + } + + for (auto& completionHandler : completionHandlers) + completionHandler(); +} + +void ScriptExecutionContext::checkConsistency() const +{ + for (auto* messagePort : m_messagePorts) + ASSERT(messagePort->scriptExecutionContext() == this); + + for (auto* destructionObserver : m_destructionObservers) + ASSERT(destructionObserver->scriptExecutionContext() == this); + + // for (auto* activeDOMObject : m_activeDOMObjects) { + // ASSERT(activeDOMObject->scriptExecutionContext() == this); + // activeDOMObject->assertSuspendIfNeededWasCalled(); + // } +} + +void ScriptExecutionContext::createdMessagePort(MessagePort& messagePort) +{ + ASSERT(isContextThread()); + + m_messagePorts.add(&messagePort); +} + +void ScriptExecutionContext::destroyedMessagePort(MessagePort& messagePort) +{ + ASSERT(isContextThread()); + + m_messagePorts.remove(&messagePort); +} + us_socket_context_t* ScriptExecutionContext::webSocketContextNoSSL() { if (!m_client_websockets_ctx) { diff --git a/src/bun.js/bindings/ScriptExecutionContext.h b/src/bun.js/bindings/ScriptExecutionContext.h index 520954c29b8d04..b32435240fcdc3 100644 --- a/src/bun.js/bindings/ScriptExecutionContext.h +++ b/src/bun.js/bindings/ScriptExecutionContext.h @@ -2,12 +2,15 @@ #include "root.h" #include "ActiveDOMObject.h" +#include "ContextDestructionObserver.h" +#include "BunBroadcastChannelRegistry.h" #include #include #include #include #include #include +#include #include "CachedScript.h" #include "wtf/URL.h" @@ -27,11 +30,12 @@ struct us_loop_t; namespace WebCore { class WebSocket; +class MessagePort; class ScriptExecutionContext; class EventLoopTask { - WTF_MAKE_FAST_ALLOCATED; + WTF_MAKE_ISO_ALLOCATED(EventLoopTask); public: enum CleanupTaskTag { CleanupTask }; @@ -71,12 +75,14 @@ class EventLoopTask { using ScriptExecutionContextIdentifier = uint32_t; class ScriptExecutionContext : public CanMakeWeakPtr { + WTF_MAKE_ISO_ALLOCATED(ScriptExecutionContext); public: ScriptExecutionContext(JSC::VM* vm, JSC::JSGlobalObject* globalObject) : m_vm(vm) , m_globalObject(globalObject) , m_identifier(0) + , m_broadcastChannelRegistry(BunBroadcastChannelRegistry::create()) { regenerateIdentifier(); } @@ -85,10 +91,13 @@ class ScriptExecutionContext : public CanMakeWeakPtr { : m_vm(vm) , m_globalObject(globalObject) , m_identifier(identifier) + , m_broadcastChannelRegistry(BunBroadcastChannelRegistry::create()) { addToContextsMap(); } + ~ScriptExecutionContext(); + static ScriptExecutionContextIdentifier generateIdentifier(); JSC::JSGlobalObject* jsGlobalObject() @@ -107,14 +116,17 @@ class ScriptExecutionContext : public CanMakeWeakPtr { } static ScriptExecutionContext* getScriptExecutionContext(ScriptExecutionContextIdentifier identifier); + void refEventLoop(); + void unrefEventLoop(); const WTF::URL& url() const { return m_url; } + bool isMainThread() const { return static_cast(m_identifier) == 1; } bool activeDOMObjectsAreSuspended() { return false; } bool activeDOMObjectsAreStopped() { return false; } - bool isContextThread() { return true; } + bool isContextThread(); bool isDocument() { return false; } bool isWorkerGlobalScope() { return true; } bool isJSExecutionForbidden() { return false; } @@ -137,7 +149,21 @@ class ScriptExecutionContext : public CanMakeWeakPtr { bool unwrapCryptoKey(const Vector& wrappedKey, Vector& key) { return false; } #endif - static bool postTaskTo(ScriptExecutionContextIdentifier identifier, Function&& task); + WEBCORE_EXPORT static bool postTaskTo(ScriptExecutionContextIdentifier identifier, Function&& task); + WEBCORE_EXPORT static bool ensureOnContextThread(ScriptExecutionContextIdentifier, Function&& task); + WEBCORE_EXPORT static bool ensureOnMainThread(Function&& task); + + WEBCORE_EXPORT JSC::JSGlobalObject* globalObject(); + + void didCreateDestructionObserver(ContextDestructionObserver&); + void willDestroyDestructionObserver(ContextDestructionObserver&); + + void processMessageWithMessagePortsSoon(CompletionHandler&&); + void createdMessagePort(MessagePort&); + void destroyedMessagePort(MessagePort&); + + void dispatchMessagePortEvents(); + void checkConsistency() const; void regenerateIdentifier(); void addToContextsMap(); @@ -187,12 +213,21 @@ class ScriptExecutionContext : public CanMakeWeakPtr { m_vm = &globalObject->vm(); } + BunBroadcastChannelRegistry& broadcastChannelRegistry() { return m_broadcastChannelRegistry; } + private: JSC::VM* m_vm = nullptr; JSC::JSGlobalObject* m_globalObject = nullptr; WTF::URL m_url = WTF::URL(); ScriptExecutionContextIdentifier m_identifier; + HashSet m_messagePorts; + HashSet m_destructionObservers; + Vector> m_processMessageWithMessagePortsSoonHandlers; + Ref m_broadcastChannelRegistry; + + bool m_willProcessMessageWithMessagePortsSoon { false }; + us_socket_context_t* webSocketContextSSL(); us_socket_context_t* webSocketContextNoSSL(); us_socket_context_t* connectedWebSocketKindClientSSL(); diff --git a/src/bun.js/bindings/Strong.cpp b/src/bun.js/bindings/Strong.cpp new file mode 100644 index 00000000000000..8ec63e3185cdd7 --- /dev/null +++ b/src/bun.js/bindings/Strong.cpp @@ -0,0 +1,53 @@ +#include "root.h" +#include +#include "BunClientData.h" + +namespace Bun { + +// We tried to pool these +// But it was very complicated +class StrongRef { + WTF_MAKE_ISO_ALLOCATED(StrongRef); + +public: + StrongRef(JSC::VM& vm, JSC::JSValue value) + : m_cell(vm, value) + { + } + + StrongRef() + : m_cell() + { + } + + JSC::Strong m_cell; +}; + +WTF_MAKE_ISO_ALLOCATED_IMPL(StrongRef); + +} + +extern "C" void Bun__StrongRef__delete(Bun::StrongRef* strongRef) +{ + delete strongRef; +} + +extern "C" Bun::StrongRef* Bun__StrongRef__new(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue encodedValue) +{ + return new Bun::StrongRef(globalObject->vm(), JSC::JSValue::decode(encodedValue)); +} + +extern "C" JSC::EncodedJSValue Bun__StrongRef__get(Bun::StrongRef* strongRef) +{ + return JSC::JSValue::encode(strongRef->m_cell.get()); +} + +extern "C" void Bun__StrongRef__set(Bun::StrongRef* strongRef, JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + strongRef->m_cell.set(globalObject->vm(), JSC::JSValue::decode(value)); +} + +extern "C" void Bun__StrongRef__clear(Bun::StrongRef* strongRef) +{ + strongRef->m_cell.clear(); +} diff --git a/src/bun.js/bindings/ZigGeneratedClasses.cpp b/src/bun.js/bindings/ZigGeneratedClasses.cpp index 2450101583cf5c..c2780bd7f38600 100644 --- a/src/bun.js/bindings/ZigGeneratedClasses.cpp +++ b/src/bun.js/bindings/ZigGeneratedClasses.cpp @@ -2693,9 +2693,15 @@ JSC_DECLARE_CUSTOM_GETTER(jsExpectConstructor); extern "C" void ExpectClass__finalize(void*); extern "C" JSC_DECLARE_HOST_FUNCTION(ExpectClass__call); +extern "C" EncodedJSValue ExpectPrototype__fail(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); +JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__failCallback); + extern "C" JSC::EncodedJSValue ExpectPrototype__getNot(void* ptr, JSC::EncodedJSValue thisValue, JSC::JSGlobalObject* lexicalGlobalObject); JSC_DECLARE_CUSTOM_GETTER(ExpectPrototype__notGetterWrap); +extern "C" EncodedJSValue ExpectPrototype___pass(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); +JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__passCallback); + extern "C" JSC::EncodedJSValue ExpectPrototype__getRejects(void* ptr, JSC::EncodedJSValue thisValue, JSC::JSGlobalObject* lexicalGlobalObject); JSC_DECLARE_CUSTOM_GETTER(ExpectPrototype__rejectsGetterWrap); @@ -2849,6 +2855,9 @@ JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toHaveReturnedWithCallback); extern "C" EncodedJSValue ExpectPrototype__toInclude(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toIncludeCallback); +extern "C" EncodedJSValue ExpectPrototype__toIncludeRepeated(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); +JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toIncludeRepeatedCallback); + extern "C" EncodedJSValue ExpectPrototype__toMatch(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toMatchCallback); @@ -2861,6 +2870,9 @@ JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toMatchObjectCallback); extern "C" EncodedJSValue ExpectPrototype__toMatchSnapshot(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toMatchSnapshotCallback); +extern "C" EncodedJSValue ExpectPrototype__toSatisfy(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); +JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toSatisfyCallback); + extern "C" EncodedJSValue ExpectPrototype__toStartWith(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toStartWithCallback); @@ -2879,7 +2891,9 @@ JSC_DECLARE_HOST_FUNCTION(ExpectPrototype__toThrowErrorMatchingSnapshotCallback) STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSExpectPrototype, JSExpectPrototype::Base); static const HashTableValue JSExpectPrototypeTableValues[] = { + { "fail"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__failCallback, 1 } }, { "not"_s, static_cast(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, ExpectPrototype__notGetterWrap, 0 } }, + { "pass"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__passCallback, 1 } }, { "rejects"_s, static_cast(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, ExpectPrototype__rejectsGetterWrap, 0 } }, { "resolves"_s, static_cast(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, ExpectPrototype__resolvesGetterWrap, 0 } }, { "toBe"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toBeCallback, 1 } }, @@ -2931,10 +2945,12 @@ static const HashTableValue JSExpectPrototypeTableValues[] = { { "toHaveReturnedTimes"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toHaveReturnedTimesCallback, 1 } }, { "toHaveReturnedWith"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toHaveReturnedWithCallback, 1 } }, { "toInclude"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toIncludeCallback, 1 } }, + { "toIncludeRepeated"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toIncludeRepeatedCallback, 2 } }, { "toMatch"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toMatchCallback, 1 } }, { "toMatchInlineSnapshot"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toMatchInlineSnapshotCallback, 1 } }, { "toMatchObject"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toMatchObjectCallback, 1 } }, { "toMatchSnapshot"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toMatchSnapshotCallback, 1 } }, + { "toSatisfy"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toSatisfyCallback, 1 } }, { "toStartWith"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toStartWithCallback, 1 } }, { "toStrictEqual"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toStrictEqualCallback, 1 } }, { "toThrow"_s, static_cast(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, ExpectPrototype__toThrowCallback, 1 } }, @@ -2956,6 +2972,33 @@ JSC_DEFINE_CUSTOM_GETTER(jsExpectConstructor, (JSGlobalObject * lexicalGlobalObj return JSValue::encode(globalObject->JSExpectConstructor()); } +JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__failCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = lexicalGlobalObject->vm(); + + JSExpect* thisObject = jsDynamicCast(callFrame->thisValue()); + + if (UNLIKELY(!thisObject)) { + auto throwScope = DECLARE_THROW_SCOPE(vm); + return throwVMTypeError(lexicalGlobalObject, throwScope); + } + + JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); + +#ifdef BUN_DEBUG + /** View the file name of the JS file that called this function + * from a debugger */ + SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm); + const char* fileName = sourceOrigin.string().utf8().data(); + static const char* lastFileName = nullptr; + if (lastFileName != fileName) { + lastFileName = fileName; + } +#endif + + return ExpectPrototype__fail(thisObject->wrapped(), lexicalGlobalObject, callFrame); +} + JSC_DEFINE_CUSTOM_GETTER(ExpectPrototype__notGetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) { auto& vm = lexicalGlobalObject->vm(); @@ -2968,6 +3011,33 @@ JSC_DEFINE_CUSTOM_GETTER(ExpectPrototype__notGetterWrap, (JSGlobalObject * lexic RELEASE_AND_RETURN(throwScope, result); } +JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__passCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = lexicalGlobalObject->vm(); + + JSExpect* thisObject = jsDynamicCast(callFrame->thisValue()); + + if (UNLIKELY(!thisObject)) { + auto throwScope = DECLARE_THROW_SCOPE(vm); + return throwVMTypeError(lexicalGlobalObject, throwScope); + } + + JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); + +#ifdef BUN_DEBUG + /** View the file name of the JS file that called this function + * from a debugger */ + SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm); + const char* fileName = sourceOrigin.string().utf8().data(); + static const char* lastFileName = nullptr; + if (lastFileName != fileName) { + lastFileName = fileName; + } +#endif + + return ExpectPrototype___pass(thisObject->wrapped(), lexicalGlobalObject, callFrame); +} + JSC_DEFINE_CUSTOM_GETTER(ExpectPrototype__rejectsGetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) { auto& vm = lexicalGlobalObject->vm(); @@ -4315,6 +4385,33 @@ JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__toIncludeCallback, (JSGlobalObject * l return ExpectPrototype__toInclude(thisObject->wrapped(), lexicalGlobalObject, callFrame); } +JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__toIncludeRepeatedCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = lexicalGlobalObject->vm(); + + JSExpect* thisObject = jsDynamicCast(callFrame->thisValue()); + + if (UNLIKELY(!thisObject)) { + auto throwScope = DECLARE_THROW_SCOPE(vm); + return throwVMTypeError(lexicalGlobalObject, throwScope); + } + + JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); + +#ifdef BUN_DEBUG + /** View the file name of the JS file that called this function + * from a debugger */ + SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm); + const char* fileName = sourceOrigin.string().utf8().data(); + static const char* lastFileName = nullptr; + if (lastFileName != fileName) { + lastFileName = fileName; + } +#endif + + return ExpectPrototype__toIncludeRepeated(thisObject->wrapped(), lexicalGlobalObject, callFrame); +} + JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__toMatchCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) { auto& vm = lexicalGlobalObject->vm(); @@ -4423,6 +4520,33 @@ JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__toMatchSnapshotCallback, (JSGlobalObje return ExpectPrototype__toMatchSnapshot(thisObject->wrapped(), lexicalGlobalObject, callFrame); } +JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__toSatisfyCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = lexicalGlobalObject->vm(); + + JSExpect* thisObject = jsDynamicCast(callFrame->thisValue()); + + if (UNLIKELY(!thisObject)) { + auto throwScope = DECLARE_THROW_SCOPE(vm); + return throwVMTypeError(lexicalGlobalObject, throwScope); + } + + JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject); + +#ifdef BUN_DEBUG + /** View the file name of the JS file that called this function + * from a debugger */ + SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm); + const char* fileName = sourceOrigin.string().utf8().data(); + static const char* lastFileName = nullptr; + if (lastFileName != fileName) { + lastFileName = fileName; + } +#endif + + return ExpectPrototype__toSatisfy(thisObject->wrapped(), lexicalGlobalObject, callFrame); +} + JSC_DEFINE_HOST_FUNCTION(ExpectPrototype__toStartWithCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) { auto& vm = lexicalGlobalObject->vm(); diff --git a/src/bun.js/bindings/ZigGeneratedCode.cpp b/src/bun.js/bindings/ZigGeneratedCode.cpp index 29f92bab0a759d..6a57e43eabfbfd 100644 --- a/src/bun.js/bindings/ZigGeneratedCode.cpp +++ b/src/bun.js/bindings/ZigGeneratedCode.cpp @@ -1,703 +1,670 @@ - #include "root.h" - #include "headers.h" - - #include - #include "DOMJITIDLConvert.h" - #include "DOMJITIDLType.h" - #include "DOMJITIDLTypeFilter.h" - #include "DOMJITHelpers.h" - #include - - #include "JSDOMConvertBufferSource.h" - - using namespace JSC; - using namespace WebCore; - - - /* -- BEGIN DOMCall DEFINITIONS -- */ - +#include "root.h" +#include "headers.h" -extern "C" JSC_DECLARE_HOST_FUNCTION(FFI__ptr__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(FFI__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, JSC::JSUint8Array*)); +#include +#include "DOMJITIDLConvert.h" +#include "DOMJITIDLType.h" +#include "DOMJITIDLTypeFilter.h" +#include "DOMJITHelpers.h" +#include -JSC_DEFINE_JIT_OPERATION(FFI__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, JSC::JSUint8Array* arg1)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return FFI__ptr__fastpath(lexicalGlobalObject, thisValue, arg1); -} -JSC_DEFINE_HOST_FUNCTION(FFI__ptr__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +#include "JSDOMConvertBufferSource.h" + +using namespace JSC; +using namespace WebCore; + +/* -- BEGIN DOMCall DEFINITIONS -- */ + +extern "C" JSC_DECLARE_HOST_FUNCTION(FFI__ptr__slowpathWrapper); +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(FFI__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, JSC::JSUint8Array*)); + +JSC_DEFINE_JIT_OPERATION(FFI__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, JSC::JSUint8Array* arg1)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return FFI__ptr__fastpath(lexicalGlobalObject, thisValue, arg1); +} +JSC_DEFINE_HOST_FUNCTION(FFI__ptr__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return FFI__ptr__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void FFI__ptr__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_ptr_signature( - FFI__ptr__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecDoubleReal, - JSC::SpecUint8Array - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 1, - String("ptr"_s), - FFI__ptr__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, FFI__ptr__slowpathWrapper, - &DOMJIT_ptr_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "ptr"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void FFI__ptr__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_ptr_signature( + FFI__ptr__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecDoubleReal, + JSC::SpecUint8Array); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 1, + String("ptr"_s), + FFI__ptr__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, FFI__ptr__slowpathWrapper, + &DOMJIT_ptr_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "ptr"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__u8__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__u8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__u8__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__u8__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__u8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__u8__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__u8__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__u8__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__u8__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_u8_signature( - Reader__u8__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt32Only, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("u8"_s), - Reader__u8__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u8__slowpathWrapper, - &DOMJIT_u8_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "u8"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__u8__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_u8_signature( + Reader__u8__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt32Only, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("u8"_s), + Reader__u8__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u8__slowpathWrapper, + &DOMJIT_u8_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "u8"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__u16__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__u16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__u16__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__u16__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__u16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__u16__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__u16__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__u16__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__u16__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_u16_signature( - Reader__u16__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt32Only, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("u16"_s), - Reader__u16__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u16__slowpathWrapper, - &DOMJIT_u16_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "u16"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__u16__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_u16_signature( + Reader__u16__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt32Only, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("u16"_s), + Reader__u16__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u16__slowpathWrapper, + &DOMJIT_u16_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "u16"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__u32__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__u32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__u32__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__u32__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__u32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__u32__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__u32__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__u32__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__u32__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_u32_signature( - Reader__u32__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt32Only, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("u32"_s), - Reader__u32__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u32__slowpathWrapper, - &DOMJIT_u32_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "u32"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__u32__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_u32_signature( + Reader__u32__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt32Only, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("u32"_s), + Reader__u32__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u32__slowpathWrapper, + &DOMJIT_u32_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "u32"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__ptr__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__ptr__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__ptr__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__ptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__ptr__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__ptr__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__ptr__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__ptr__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_ptr_signature( - Reader__ptr__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt52Any, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("ptr"_s), - Reader__ptr__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__ptr__slowpathWrapper, - &DOMJIT_ptr_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "ptr"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__ptr__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_ptr_signature( + Reader__ptr__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt52Any, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("ptr"_s), + Reader__ptr__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__ptr__slowpathWrapper, + &DOMJIT_ptr_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "ptr"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__i8__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__i8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__i8__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__i8__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__i8__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__i8__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__i8__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__i8__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__i8__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_i8_signature( - Reader__i8__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt32Only, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("i8"_s), - Reader__i8__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i8__slowpathWrapper, - &DOMJIT_i8_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "i8"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__i8__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_i8_signature( + Reader__i8__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt32Only, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("i8"_s), + Reader__i8__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i8__slowpathWrapper, + &DOMJIT_i8_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "i8"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__i16__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__i16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__i16__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__i16__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__i16__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__i16__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__i16__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__i16__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__i16__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_i16_signature( - Reader__i16__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt32Only, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("i16"_s), - Reader__i16__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i16__slowpathWrapper, - &DOMJIT_i16_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "i16"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__i16__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_i16_signature( + Reader__i16__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt32Only, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("i16"_s), + Reader__i16__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i16__slowpathWrapper, + &DOMJIT_i16_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "i16"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__i32__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__i32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__i32__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__i32__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__i32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__i32__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__i32__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__i32__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__i32__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_i32_signature( - Reader__i32__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt32Only, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("i32"_s), - Reader__i32__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i32__slowpathWrapper, - &DOMJIT_i32_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "i32"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__i32__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_i32_signature( + Reader__i32__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt32Only, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("i32"_s), + Reader__i32__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i32__slowpathWrapper, + &DOMJIT_i32_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "i32"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__i64__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__i64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__i64__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__i64__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__i64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__i64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__i64__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__i64__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__i64__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__i64__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_i64_signature( - Reader__i64__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecHeapTop, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("i64"_s), - Reader__i64__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i64__slowpathWrapper, - &DOMJIT_i64_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "i64"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__i64__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_i64_signature( + Reader__i64__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecHeapTop, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("i64"_s), + Reader__i64__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__i64__slowpathWrapper, + &DOMJIT_i64_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "i64"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__u64__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__u64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__u64__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__u64__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__u64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__u64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__u64__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__u64__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__u64__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__u64__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_u64_signature( - Reader__u64__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecHeapTop, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("u64"_s), - Reader__u64__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u64__slowpathWrapper, - &DOMJIT_u64_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "u64"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__u64__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_u64_signature( + Reader__u64__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecHeapTop, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("u64"_s), + Reader__u64__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__u64__slowpathWrapper, + &DOMJIT_u64_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "u64"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__intptr__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__intptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__intptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__intptr__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__intptr__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__intptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__intptr__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__intptr__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__intptr__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__intptr__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__intptr__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_intptr_signature( - Reader__intptr__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecInt52Any, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("intptr"_s), - Reader__intptr__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__intptr__slowpathWrapper, - &DOMJIT_intptr_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "intptr"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__intptr__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_intptr_signature( + Reader__intptr__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecInt52Any, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("intptr"_s), + Reader__intptr__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__intptr__slowpathWrapper, + &DOMJIT_intptr_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "intptr"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__f32__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__f32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__f32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__f32__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__f32__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__f32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__f32__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__f32__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__f32__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__f32__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__f32__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_f32_signature( - Reader__f32__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecDoubleReal, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("f32"_s), - Reader__f32__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__f32__slowpathWrapper, - &DOMJIT_f32_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "f32"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__f32__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_f32_signature( + Reader__f32__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecDoubleReal, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("f32"_s), + Reader__f32__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__f32__slowpathWrapper, + &DOMJIT_f32_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "f32"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Reader__f64__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__f64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t, int32_t)); - -JSC_DEFINE_JIT_OPERATION(Reader__f64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Reader__f64__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Reader__f64__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Reader__f64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t, int32_t)); + +JSC_DEFINE_JIT_OPERATION(Reader__f64__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, int64_t arg1, int32_t arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Reader__f64__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Reader__f64__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Reader__f64__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Reader__f64__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_f64_signature( - Reader__f64__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecDoubleReal, - JSC::SpecInt52Any, - JSC::SpecInt32Only - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("f64"_s), - Reader__f64__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__f64__slowpathWrapper, - &DOMJIT_f64_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "f64"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Reader__f64__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_f64_signature( + Reader__f64__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecDoubleReal, + JSC::SpecInt52Any, + JSC::SpecInt32Only); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("f64"_s), + Reader__f64__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Reader__f64__slowpathWrapper, + &DOMJIT_f64_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "f64"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Crypto__getRandomValues__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Crypto__getRandomValues__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, JSC::JSUint8Array*)); - -JSC_DEFINE_JIT_OPERATION(Crypto__getRandomValues__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, JSC::JSUint8Array* arg1)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Crypto__getRandomValues__fastpath(lexicalGlobalObject, thisValue, arg1); -} -JSC_DEFINE_HOST_FUNCTION(Crypto__getRandomValues__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Crypto__getRandomValues__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, JSC::JSUint8Array*)); + +JSC_DEFINE_JIT_OPERATION(Crypto__getRandomValues__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, JSC::JSUint8Array* arg1)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Crypto__getRandomValues__fastpath(lexicalGlobalObject, thisValue, arg1); +} +JSC_DEFINE_HOST_FUNCTION(Crypto__getRandomValues__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Crypto__getRandomValues__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Crypto__getRandomValues__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_getRandomValues_signature( - Crypto__getRandomValues__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecHeapTop, - JSC::SpecUint8Array - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 1, - String("getRandomValues"_s), - Crypto__getRandomValues__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Crypto__getRandomValues__slowpathWrapper, - &DOMJIT_getRandomValues_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "getRandomValues"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Crypto__getRandomValues__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_getRandomValues_signature( + Crypto__getRandomValues__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecHeapTop, + JSC::SpecUint8Array); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 1, + String("getRandomValues"_s), + Crypto__getRandomValues__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Crypto__getRandomValues__slowpathWrapper, + &DOMJIT_getRandomValues_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "getRandomValues"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Crypto__randomUUID__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Crypto__randomUUID__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue)); - -JSC_DEFINE_JIT_OPERATION(Crypto__randomUUID__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Crypto__randomUUID__fastpath(lexicalGlobalObject, thisValue); -} -JSC_DEFINE_HOST_FUNCTION(Crypto__randomUUID__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Crypto__randomUUID__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue)); + +JSC_DEFINE_JIT_OPERATION(Crypto__randomUUID__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Crypto__randomUUID__fastpath(lexicalGlobalObject, thisValue); +} +JSC_DEFINE_HOST_FUNCTION(Crypto__randomUUID__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Crypto__randomUUID__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Crypto__randomUUID__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_randomUUID_signature( - Crypto__randomUUID__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecString); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 0, - String("randomUUID"_s), - Crypto__randomUUID__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Crypto__randomUUID__slowpathWrapper, - &DOMJIT_randomUUID_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "randomUUID"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); +extern "C" void Crypto__randomUUID__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_randomUUID_signature( + Crypto__randomUUID__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecString); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 0, + String("randomUUID"_s), + Crypto__randomUUID__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Crypto__randomUUID__slowpathWrapper, + &DOMJIT_randomUUID_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "randomUUID"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); } - - extern "C" JSC_DECLARE_HOST_FUNCTION(Crypto__timingSafeEqual__slowpathWrapper); -extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Crypto__timingSafeEqual__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, JSC::JSUint8Array*, JSC::JSUint8Array*)); - -JSC_DEFINE_JIT_OPERATION(Crypto__timingSafeEqual__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject* lexicalGlobalObject, void* thisValue, JSC::JSUint8Array* arg1, JSC::JSUint8Array* arg2)) { -VM& vm = JSC::getVM(lexicalGlobalObject); -IGNORE_WARNINGS_BEGIN("frame-address") -CallFrame* callFrame = DECLARE_CALL_FRAME(vm); -IGNORE_WARNINGS_END -JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); -return Crypto__timingSafeEqual__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); -} -JSC_DEFINE_HOST_FUNCTION(Crypto__timingSafeEqual__slowpathWrapper, (JSC::JSGlobalObject *globalObject, JSC::CallFrame* frame)) { +extern "C" JSC_DECLARE_JIT_OPERATION_WITHOUT_WTF_INTERNAL(Crypto__timingSafeEqual__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, JSC::JSUint8Array*, JSC::JSUint8Array*)); + +JSC_DEFINE_JIT_OPERATION(Crypto__timingSafeEqual__fastpathWrapper, EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, void* thisValue, JSC::JSUint8Array* arg1, JSC::JSUint8Array* arg2)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + IGNORE_WARNINGS_BEGIN("frame-address") + CallFrame* callFrame = DECLARE_CALL_FRAME(vm); + IGNORE_WARNINGS_END + JSC::JITOperationPrologueCallFrameTracer tracer(vm, callFrame); + return Crypto__timingSafeEqual__fastpath(lexicalGlobalObject, thisValue, arg1, arg2); +} +JSC_DEFINE_HOST_FUNCTION(Crypto__timingSafeEqual__slowpathWrapper, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* frame)) +{ return Crypto__timingSafeEqual__slowpath(globalObject, JSValue::encode(frame->thisValue()), reinterpret_cast(frame->addressOfArgumentsStart()), frame->argumentCount()); } -extern "C" void Crypto__timingSafeEqual__put(JSC::JSGlobalObject *globalObject, JSC::EncodedJSValue value) { - JSC::JSObject *thisObject = JSC::jsCast(JSC::JSValue::decode(value)); - static const JSC::DOMJIT::Signature DOMJIT_timingSafeEqual_signature( - Crypto__timingSafeEqual__fastpathWrapper, - thisObject->classInfo(), -JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), - JSC::SpecHeapTop, - JSC::SpecUint8Array, - JSC::SpecUint8Array - ); - JSFunction* function = JSFunction::create( - globalObject->vm(), - globalObject, - 2, - String("timingSafeEqual"_s), - Crypto__timingSafeEqual__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Crypto__timingSafeEqual__slowpathWrapper, - &DOMJIT_timingSafeEqual_signature - ); - thisObject->putDirect( - globalObject->vm(), - Identifier::fromString(globalObject->vm(), "timingSafeEqual"_s), - function, - JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0 - ); -} - - - /* -- END DOMCall DEFINITIONS-- */ - +extern "C" void Crypto__timingSafeEqual__put(JSC::JSGlobalObject* globalObject, JSC::EncodedJSValue value) +{ + JSC::JSObject* thisObject = JSC::jsCast(JSC::JSValue::decode(value)); + static const JSC::DOMJIT::Signature DOMJIT_timingSafeEqual_signature( + Crypto__timingSafeEqual__fastpathWrapper, + thisObject->classInfo(), + JSC::DOMJIT::Effect::forReadWrite(JSC::DOMJIT::HeapRange::top(), JSC::DOMJIT::HeapRange::top()), + JSC::SpecHeapTop, + JSC::SpecUint8Array, + JSC::SpecUint8Array); + JSFunction* function = JSFunction::create( + globalObject->vm(), + globalObject, + 2, + String("timingSafeEqual"_s), + Crypto__timingSafeEqual__slowpathWrapper, ImplementationVisibility::Public, NoIntrinsic, Crypto__timingSafeEqual__slowpathWrapper, + &DOMJIT_timingSafeEqual_signature); + thisObject->putDirect( + globalObject->vm(), + Identifier::fromString(globalObject->vm(), "timingSafeEqual"_s), + function, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | 0); +} + +/* -- END DOMCall DEFINITIONS-- */ diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index 946e368dd7b034..3de7d3daa9a8ee 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -105,7 +105,6 @@ #include "JavaScriptCore/FunctionPrototype.h" #include "napi.h" #include "JSSQLStatement.h" -#include "BunJSCModule.h" #include "ModuleLoader.h" #include "NodeVMScript.h" #include "ProcessIdentifier.h" @@ -119,6 +118,9 @@ #include "DOMIsoSubspaces.h" #include "BunWorkerGlobalScope.h" #include "JSWorker.h" +#include "JSMessageChannel.h" +#include "JSMessagePort.h" +#include "JSBroadcastChannel.h" #if ENABLE(REMOTE_INSPECTOR) #include "JavaScriptCore/RemoteInspectorServer.h" @@ -127,6 +129,7 @@ using namespace Bun; extern "C" JSC::EncodedJSValue Bun__fetch(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); +extern "C" JSC::EncodedJSValue Bun__canonicalizeIP(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame); using JSGlobalObject = JSC::JSGlobalObject; @@ -215,6 +218,8 @@ constexpr size_t DEFAULT_ERROR_STACK_TRACE_LIMIT = 10; // #include static bool has_loaded_jsc = false; +Structure* createMemoryFootprintStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject); + namespace WebCore { class Base64Utilities { public: @@ -223,16 +228,16 @@ class Base64Utilities { if (encodedString.isNull()) return String(); - auto decodedData = base64Decode(encodedString, Base64DecodeMode::DefaultValidatePaddingAndIgnoreWhitespace); + auto decodedData = base64DecodeToString(encodedString, Base64DecodeMode::DefaultValidatePaddingAndIgnoreWhitespace); if (!decodedData) return Exception { InvalidCharacterError }; - return String(decodedData->data(), decodedData->size()); + return decodedData; } }; } - +extern "C" WebCore::Worker* WebWorker__getParentWorker(void*); extern "C" void JSCInitialize(const char* envp[], size_t envc, void (*onCrash)(const char* ptr, size_t length)) { if (has_loaded_jsc) @@ -258,6 +263,8 @@ extern "C" void JSCInitialize(const char* envp[], size_t envc, void (*onCrash)(c JSC::Options::useJITCage() = false; JSC::Options::useShadowRealm() = true; JSC::Options::useResizableArrayBuffer() = true; + JSC::Options::usePromiseWithResolversMethod() = true; + #ifdef BUN_DEBUG JSC::Options::showPrivateScriptsInStackTraces() = true; #endif @@ -422,7 +429,7 @@ static String computeErrorInfo(JSC::VM& vm, Vector& stackTrace, unsi } extern "C" JSC__JSGlobalObject* Zig__GlobalObject__create(JSClassRef* globalObjectClass, int count, - void* console_client, int32_t executionContextId, bool miniMode) + void* console_client, int32_t executionContextId, bool miniMode, void* worker_ptr) { auto heapSize = miniMode ? JSC::HeapType::Small : JSC::HeapType::Large; @@ -441,6 +448,20 @@ extern "C" JSC__JSGlobalObject* Zig__GlobalObject__create(JSClassRef* globalObje vm, Zig::GlobalObject::createStructure(vm, JSC::JSGlobalObject::create(vm, JSC::JSGlobalObject::createStructure(vm, JSC::jsNull())), JSC::jsNull()), static_cast(executionContextId)); + + if (auto* worker = static_cast(worker_ptr)) { + auto& options = worker->options(); + if (options.bun.env) { + auto map = *options.bun.env; + auto size = map.size(); + auto env = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), size > 63 ? 63 : size); + for (auto k : map) { + env->putDirect(vm, JSC::Identifier::fromString(vm, WTFMove(k.key)), JSC::jsString(vm, WTFMove(k.value))); + } + map.clear(); + globalObject->m_processEnvObject.set(vm, globalObject, env); + } + } } else { globalObject = Zig::GlobalObject::create( vm, @@ -485,7 +506,7 @@ JSC_DEFINE_HOST_FUNCTION(functionFulfillModuleSync, res.result.err.code = 0; res.result.err.ptr = nullptr; - JSValue result = Bun::fetchSourceCodeSync( + JSValue result = Bun::fetchESMSourceCodeSync( reinterpret_cast(globalObject), &res, &specifier, @@ -715,6 +736,7 @@ GlobalObject::GlobalObject(JSC::VM& vm, JSC::Structure* structure) , m_scriptExecutionContext(new WebCore::ScriptExecutionContext(&vm, this)) , globalEventScope(*new Bun::GlobalScope(m_scriptExecutionContext)) { + // m_scriptExecutionContext = globalEventScope.m_context; mockModule = Bun::JSMockModule::create(this); globalEventScope.m_context = m_scriptExecutionContext; } @@ -729,6 +751,7 @@ GlobalObject::GlobalObject(JSC::VM& vm, JSC::Structure* structure, WebCore::Scri , m_scriptExecutionContext(new WebCore::ScriptExecutionContext(&vm, this, contextId)) , globalEventScope(*new Bun::GlobalScope(m_scriptExecutionContext)) { + // m_scriptExecutionContext = globalEventScope.m_context; mockModule = Bun::JSMockModule::create(this); globalEventScope.m_context = m_scriptExecutionContext; } @@ -861,28 +884,6 @@ JSC_DEFINE_CUSTOM_GETTER(JSDOMURL_getter, WebCore::JSDOMURL::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); } -JSC_DECLARE_CUSTOM_GETTER(JSErrorEvent_getter); - -JSC_DEFINE_CUSTOM_GETTER(JSErrorEvent_getter, - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) -{ - Zig::GlobalObject* thisObject = JSC::jsCast(lexicalGlobalObject); - return JSC::JSValue::encode( - WebCore::JSErrorEvent::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); -} - -JSC_DECLARE_CUSTOM_GETTER(JSCloseEvent_getter); - -JSC_DEFINE_CUSTOM_GETTER(JSCloseEvent_getter, - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) -{ - Zig::GlobalObject* thisObject = JSC::jsCast(lexicalGlobalObject); - return JSC::JSValue::encode( - WebCore::JSCloseEvent::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); -} - JSC_DEFINE_CUSTOM_GETTER(JSBuffer_privateGetter, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName)) @@ -928,38 +929,32 @@ WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSDOMFormData); WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSWorker); WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSWorker); -JSC_DECLARE_CUSTOM_GETTER(JSEvent_getter); +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSMessageChannel); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSMessageChannel); -JSC_DEFINE_CUSTOM_GETTER(JSEvent_getter, - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) -{ - Zig::GlobalObject* thisObject = JSC::jsCast(lexicalGlobalObject); - return JSC::JSValue::encode( - WebCore::JSEvent::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); -} +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSMessagePort); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSMessagePort); -JSC_DECLARE_CUSTOM_GETTER(JSCustomEvent_getter); +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSBroadcastChannel); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSBroadcastChannel); -JSC_DEFINE_CUSTOM_GETTER(JSCustomEvent_getter, - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) -{ - Zig::GlobalObject* thisObject = JSC::jsCast(lexicalGlobalObject); - return JSC::JSValue::encode( - WebCore::JSCustomEvent::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); -} +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSEvent); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSEvent); -JSC_DECLARE_CUSTOM_GETTER(JSEventTarget_getter); +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSDOMException); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSDOMException); -JSC_DEFINE_CUSTOM_GETTER(JSEventTarget_getter, - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) -{ - Zig::GlobalObject* thisObject = JSC::jsCast(lexicalGlobalObject); - return JSC::JSValue::encode( - WebCore::JSEventTarget::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); -} +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSEventTarget); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSEventTarget); + +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSCustomEvent); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSCustomEvent); + +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSErrorEvent); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSErrorEvent); + +WEBCORE_GENERATED_CONSTRUCTOR_GETTER(JSCloseEvent); +WEBCORE_GENERATED_CONSTRUCTOR_SETTER(JSCloseEvent); JSC_DECLARE_CUSTOM_GETTER(JSDOMAbortController_getter); @@ -983,17 +978,6 @@ JSC_DEFINE_CUSTOM_GETTER(JSDOMAbortSignal_getter, WebCore::JSAbortSignal::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); } -JSC_DECLARE_CUSTOM_GETTER(JSDOMException_getter); - -JSC_DEFINE_CUSTOM_GETTER(JSDOMException_getter, - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) -{ - Zig::GlobalObject* thisObject = JSC::jsCast(lexicalGlobalObject); - return JSC::JSValue::encode( - WebCore::JSDOMException::getConstructor(JSC::getVM(lexicalGlobalObject), thisObject)); -} - static JSC_DECLARE_CUSTOM_SETTER(property_lazyProcessSetter); static JSC_DECLARE_CUSTOM_GETTER(property_lazyProcessGetter); @@ -1282,13 +1266,14 @@ JSC_DEFINE_HOST_FUNCTION(functionStructuredClone, } } - ExceptionOr> serialized = SerializedScriptValue::create(*globalObject, value, WTFMove(transferList)); + Vector> ports; + ExceptionOr> serialized = SerializedScriptValue::create(*globalObject, value, WTFMove(transferList), ports); if (serialized.hasException()) { WebCore::propagateException(*globalObject, throwScope, serialized.releaseException()); return JSValue::encode(jsUndefined()); } - JSValue deserialized = serialized.releaseReturnValue()->deserialize(*globalObject, globalObject); + JSValue deserialized = serialized.releaseReturnValue()->deserialize(*globalObject, globalObject, ports); return JSValue::encode(deserialized); } @@ -1567,17 +1552,46 @@ JSC_DEFINE_HOST_FUNCTION(functionCallNotImplemented, return JSC::JSValue::encode(JSC::JSValue {}); } +JSC_DEFINE_HOST_FUNCTION(jsReceiveMessageOnPort, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + auto& vm = lexicalGlobalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + if (callFrame->argumentCount() < 1) { + throwTypeError(lexicalGlobalObject, scope, "receiveMessageOnPort needs 1 argument"_s); + return JSC::JSValue::encode(JSC::JSValue {}); + } + + auto port = callFrame->argument(0); + + if (!port.isObject()) { + throwTypeError(lexicalGlobalObject, scope, "the \"port\" argument must be a MessagePort instance"_s); + return JSC::JSValue::encode(jsUndefined()); + } + + if (auto* messagePort = jsDynamicCast(port)) { + return JSC::JSValue::encode(messagePort->wrapped().tryTakeMessage(lexicalGlobalObject)); + } else if (auto* broadcastChannel = jsDynamicCast(port)) { + // TODO: support broadcast channels + return JSC::JSValue::encode(jsUndefined()); + } + + throwTypeError(lexicalGlobalObject, scope, "the \"port\" argument must be a MessagePort instance"_s); + return JSC::JSValue::encode(jsUndefined()); +} + // we're trying out a new way to do this lazy loading +// this is $lazy() in js code static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad, (JSC::JSGlobalObject * lexicalGlobalObject, JSC::CallFrame* callFrame)) { -JSC: + Zig::GlobalObject* globalObject = reinterpret_cast(lexicalGlobalObject); + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); VM& vm = globalObject->vm(); switch (callFrame->argumentCount()) { case 0: { - auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); JSC::throwTypeError(globalObject, scope, "lazyLoad needs 1 argument (a string)"_s); scope.release(); return JSC::JSValue::encode(JSC::JSValue {}); @@ -1587,7 +1601,6 @@ static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad, if (moduleName.isNumber()) { switch (moduleName.toInt32(globalObject)) { case 0: { - auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); JSC::throwTypeError(globalObject, scope, "lazyLoad expects a string"_s); scope.release(); return JSC::JSValue::encode(JSC::JSValue {}); @@ -1614,7 +1627,6 @@ static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad, auto string = moduleName.toWTFString(globalObject); if (string.isNull()) { - auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); JSC::throwTypeError(globalObject, scope, "lazyLoad expects a string"_s); scope.release(); return JSC::JSValue::encode(JSC::JSValue {}); @@ -1624,14 +1636,37 @@ static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad, return JSC::JSValue::encode(JSSQLStatementConstructor::create(vm, globalObject, JSSQLStatementConstructor::createStructure(vm, globalObject, globalObject->m_functionPrototype.get()))); } - if (string == "bun:jsc"_s) { - return JSC::JSValue::encode(createJSCModule(globalObject)); + if (string == "worker_threads"_s) { + + JSValue workerData = jsUndefined(); + JSValue threadId = jsNumber(0); + + if (auto* worker = WebWorker__getParentWorker(globalObject->bunVM())) { + auto& options = worker->options(); + if (worker && options.bun.data) { + auto ports = MessagePort::entanglePorts(*ScriptExecutionContext::getScriptExecutionContext(worker->clientIdentifier()), WTFMove(options.bun.dataMessagePorts)); + RefPtr serialized = WTFMove(options.bun.data); + JSValue deserialized = serialized->deserialize(*globalObject, globalObject, WTFMove(ports)); + RETURN_IF_EXCEPTION(scope, {}); + workerData = deserialized; + } + + threadId = jsNumber(worker->clientIdentifier()); + } + + JSArray* array = constructEmptyArray(globalObject, nullptr); + array->push(globalObject, workerData); + array->push(globalObject, threadId); + array->push(globalObject, JSFunction::create(vm, globalObject, 1, "receiveMessageOnPort"_s, jsReceiveMessageOnPort, ImplementationVisibility::Public, NoIntrinsic)); + + return JSC::JSValue::encode(array); } if (string == "pathToFileURL"_s) { return JSValue::encode( JSFunction::create(vm, globalObject, 1, pathToFileURLString, functionPathToFileURL, ImplementationVisibility::Public, NoIntrinsic)); } + if (string == "fileURLToPath"_s) { return JSValue::encode( JSFunction::create(vm, globalObject, 1, fileURLToPathString, functionFileURLToPath, ImplementationVisibility::Public, NoIntrinsic)); @@ -1655,18 +1690,20 @@ static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad, JSC::JSFunction::create(vm, globalObject, 0, "onEofChunk"_s, jsReadable_onEofChunk, ImplementationVisibility::Public), 0); return JSValue::encode(obj); } - - if (string == "createImportMeta"_s) { - Zig::ImportMetaObject* obj = Zig::ImportMetaObject::create(globalObject, callFrame->argument(1)); - return JSValue::encode(obj); + if (string == "events"_s) { + return JSValue::encode(WebCore::JSEventEmitter::getConstructor(vm, globalObject)); } + if (string == "internal/tls"_s) { + auto* obj = constructEmptyObject(globalObject); - if (string == "rootCertificates"_s) { auto sourceOrigin = callFrame->callerSourceOrigin(vm).url(); - bool isBuiltin = sourceOrigin.protocolIs("builtin"_s); - if (!isBuiltin) { - return JSC::JSValue::encode(JSC::jsUndefined()); - } + // expose for tests in debug mode only + // #ifndef BUN_DEBUG + // bool isBuiltin = sourceOrigin.protocolIs("builtin"_s); + // if (!isBuiltin) { + // return JSC::JSValue::encode(JSC::jsUndefined()); + // } + // #endif struct us_cert_string_t* out; auto size = us_raw_root_certs(&out); if (size < 0) { @@ -1678,7 +1715,12 @@ static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad, auto str = WTF::String::fromUTF8(raw.str, raw.len); rootCertificates->putDirectIndex(globalObject, i, JSC::jsString(vm, str)); } - return JSValue::encode(rootCertificates); + obj->putDirect( + vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "rootCertificates"_s)), rootCertificates, 0); + + obj->putDirect( + vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "canonicalizeIP"_s)), JSC::JSFunction::create(vm, globalObject, 1, "canonicalizeIP"_s, Bun__canonicalizeIP, ImplementationVisibility::Public, NoIntrinsic), 0); + return JSValue::encode(obj); } if (string == "masqueradesAsUndefined"_s) { @@ -1706,25 +1748,8 @@ static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad, return JSValue::encode(obj); } - if (string == "primordials"_s) { - auto sourceOrigin = callFrame->callerSourceOrigin(vm).url(); - bool isBuiltin = sourceOrigin.protocolIs("builtin"_s); - if (!isBuiltin) { - return JSC::JSValue::encode(JSC::jsUndefined()); - } - - auto* obj = globalObject->primordialsObject(); - return JSValue::encode(obj); - } - if (string == "async_hooks"_s) { auto* obj = constructEmptyObject(globalObject); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "get"_s)), - JSC::JSFunction::create(vm, asyncContextGetAsyncContextCodeGenerator(vm), globalObject), 0); - obj->putDirect( - vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "set"_s)), - JSC::JSFunction::create(vm, asyncContextSetAsyncContextCodeGenerator(vm), globalObject), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "cleanupLater"_s)), JSC::JSFunction::create(vm, globalObject, 0, "cleanupLater"_s, asyncHooksCleanupLater, ImplementationVisibility::Public), 0); @@ -2733,81 +2758,6 @@ JSC_DEFINE_HOST_FUNCTION(functionReadableStreamToArrayBuffer, (JSGlobalObject * return ZigGlobalObject__readableStreamToArrayBufferBody(reinterpret_cast(globalObject), JSValue::encode(readableStreamValue)); } -class BunPrimordialsObject final : public JSNonFinalObject { -public: - using Base = JSC::JSNonFinalObject; - static constexpr unsigned StructureFlags = Base::StructureFlags | OverridesGetOwnPropertySlot | GetOwnPropertySlotMayBeWrongAboutDontEnum; - static BunPrimordialsObject* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) - { - BunPrimordialsObject* ptr = new (NotNull, JSC::allocateCell(vm)) BunPrimordialsObject(vm, globalObject, structure); - ptr->finishCreation(vm); - return ptr; - } - - template - static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) - { - STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(BunPrimordialsObject, Base); - return &vm.plainObjectSpace(); - } - - static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) - { - return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); - } - - static bool getOwnPropertySlot(JSObject* object, JSGlobalObject* globalObject, PropertyName propertyName, PropertySlot& slot) - { - JSC::VM& vm = globalObject->vm(); - - auto str = String(propertyName.publicName()); - SymbolImpl* symbol = vm.propertyNames->builtinNames().lookUpPrivateName(str); - if (!symbol) { - return false; - } - - auto identifier = JSC::Identifier::fromUid(vm, symbol); - if (auto value = globalObject->getIfPropertyExists(globalObject, identifier)) { - slot.setValue(globalObject, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly, value); - return true; - } else if (auto value = vm.bytecodeIntrinsicRegistry().lookup(identifier)) { - auto name = identifier.string(); - String functionText; - bool isFunction = false; - // this is...terrible code - if (name.characters8()[0] >= 'A' && name.characters8()[0] <= 'Z') { - functionText = makeString("(function () { return @"_s, name, ";\n})\n"_s); - } else if (name.characters8()[0] == 'p' || name.characters8()[0] == 't' || name.characters8()[0] == 'g') { - isFunction = true; - functionText = makeString("(function (arg1, arg2) { return @"_s, name, "(arg1, arg2);\n})\n"_s); - } else { - isFunction = true; - functionText = makeString("(function (arg1) { return @"_s, name, "(arg1);\n})\n"_s); - } - - SourceCode source = makeSource(WTFMove(functionText), {}); - JSFunction* func = JSFunction::create(vm, createBuiltinExecutable(vm, source, Identifier::fromString(vm, name), ImplementationVisibility::Public, ConstructorKind::None, ConstructAbility::CannotConstruct)->link(vm, nullptr, source), globalObject); - - slot.setValue( - globalObject, - PropertyAttribute::ReadOnly | PropertyAttribute::DontDelete | 0, - isFunction ? JSValue(func) : JSC::call(globalObject, func, JSC::getCallData(func), globalObject, JSC::MarkedArgumentBuffer())); - - return true; - } - return false; - } - - DECLARE_INFO - - BunPrimordialsObject(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) - : JSC::JSNonFinalObject(vm, structure) - { - } -}; - -const ClassInfo BunPrimordialsObject::s_info = { "Primordials"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(BunPrimordialsObject) }; - JSC_DEFINE_HOST_FUNCTION(jsFunctionPerformMicrotask, (JSGlobalObject * globalObject, CallFrame* callframe)) { auto& vm = globalObject->vm(); @@ -2876,6 +2826,7 @@ extern "C" EncodedJSValue Bun__DNSResolver__resolveCaa(JSGlobalObject*, JSC::Cal extern "C" EncodedJSValue Bun__DNSResolver__resolveNs(JSGlobalObject*, JSC::CallFrame*); extern "C" EncodedJSValue Bun__DNSResolver__resolvePtr(JSGlobalObject*, JSC::CallFrame*); extern "C" EncodedJSValue Bun__DNSResolver__resolveCname(JSGlobalObject*, JSC::CallFrame*); +extern "C" EncodedJSValue Bun__DNSResolver__getServers(JSGlobalObject*, JSC::CallFrame*); JSC_DEFINE_HOST_FUNCTION(jsFunctionPerformMicrotaskVariadic, (JSGlobalObject * globalObject, CallFrame* callframe)) { @@ -3193,6 +3144,13 @@ void GlobalObject::finishCreation(VM& vm) init.set(Bun::createCommonJSModuleStructure(reinterpret_cast(init.owner))); }); + m_memoryFootprintStructure.initLater( + [](const JSC::LazyProperty::Initializer& init) { + init.set( + createMemoryFootprintStructure( + init.vm, reinterpret_cast(init.owner))); + }); + m_commonJSFunctionArgumentsStructure.initLater( [](const Initializer& init) { auto* globalObject = reinterpret_cast(init.owner); @@ -3260,6 +3218,8 @@ void GlobalObject::finishCreation(VM& vm) JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DontDelete | 0); dnsObject->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "resolveCname"_s), 2, Bun__DNSResolver__resolveCname, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DontDelete | 0); + dnsObject->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "getServers"_s), 2, Bun__DNSResolver__getServers, ImplementationVisibility::Public, NoIntrinsic, + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DontDelete | 0); init.set(dnsObject); }); @@ -3267,10 +3227,6 @@ void GlobalObject::finishCreation(VM& vm) [](const Initializer& init) { init.set(JSWeakMap::create(init.vm, init.owner->weakMapStructure())); }); - // m_asyncHooksContext.initLater( - // [](const Initializer& init) { - // init.set(JSC::JSMap::create(init.vm, init.owner->mapStructure())); - // }); m_JSBufferSubclassStructure.initLater( [](const Initializer& init) { @@ -3363,14 +3319,6 @@ void GlobalObject::finishCreation(VM& vm) toJS>(*init.owner, global, global.crypto).getObject()); }); - m_primordialsObject.initLater( - [](const JSC::LazyProperty::Initializer& init) { - auto& global = *reinterpret_cast(init.owner); - BunPrimordialsObject* object = BunPrimordialsObject::create(init.vm, reinterpret_cast(init.owner), - BunPrimordialsObject::createStructure(init.vm, init.owner, init.owner->objectPrototype())); - init.set(object); - }); - m_NapiClassStructure.initLater( [](LazyClassStructure::Initializer& init) { init.setStructure(Zig::NapiClass::createStructure(init.vm, init.global, init.global->functionPrototype())); @@ -3457,6 +3405,7 @@ void GlobalObject::finishCreation(VM& vm) init.owner->globalScope(), JSFunction::createStructure(init.vm, init.owner, RequireFunctionPrototype::create(init.owner)))); }); + m_requireResolveFunctionUnbound.initLater( [](const JSC::LazyProperty::Initializer& init) { init.set( @@ -3467,6 +3416,22 @@ void GlobalObject::finishCreation(VM& vm) JSFunction::createStructure(init.vm, init.owner, RequireResolveFunctionPrototype::create(init.owner)))); }); + m_internalModuleRegistry.initLater( + [](const JSC::LazyProperty::Initializer& init) { + init.set( + InternalModuleRegistry::create( + init.vm, + InternalModuleRegistry::createStructure(init.vm, init.owner))); + }); + + m_processBindingConstants.initLater( + [](const JSC::LazyProperty::Initializer& init) { + init.set( + ProcessBindingConstants::create( + init.vm, + ProcessBindingConstants::createStructure(init.vm, init.owner))); + }); + m_importMetaObjectStructure.initLater( [](const JSC::LazyProperty::Initializer& init) { init.set(Zig::ImportMetaObject::createStructure(init.vm, init.owner)); @@ -3607,7 +3572,6 @@ void GlobalObject::finishCreation(VM& vm) consoleObject->putDirectBuiltinFunction(vm, this, clientData->builtinNames().writePublicName(), consoleObjectWriteCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::ReadOnly | PropertyAttribute::DontDelete); } -extern "C" WebCore::Worker* WebWorker__getParentWorker(void*); JSC_DEFINE_HOST_FUNCTION(jsFunctionPostMessage, (JSC::JSGlobalObject * leixcalGlobalObject, JSC::CallFrame* callFrame)) { @@ -3651,26 +3615,28 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionPostMessage, } } - ExceptionOr> serialized = SerializedScriptValue::create(*globalObject, value, WTFMove(transferList)); + Vector> ports; + ExceptionOr> serialized = SerializedScriptValue::create(*globalObject, value, WTFMove(transferList), ports, SerializationForStorage::No, SerializationContext::WorkerPostMessage); if (serialized.hasException()) { WebCore::propagateException(*globalObject, throwScope, serialized.releaseException()); return JSValue::encode(jsUndefined()); } - RefPtr message = serialized.releaseReturnValue(); - ScriptExecutionContext::postTaskTo(context->identifier(), [message = WTFMove(message), protectedThis = Ref { *worker }](ScriptExecutionContext& context) { + ExceptionOr> disentangledPorts = MessagePort::disentanglePorts(WTFMove(ports)); + if (disentangledPorts.hasException()) { + WebCore::propagateException(*globalObject, throwScope, serialized.releaseException()); + return JSValue::encode(jsUndefined()); + } + + MessageWithMessagePorts messageWithMessagePorts { serialized.releaseReturnValue(), disentangledPorts.releaseReturnValue() }; + + ScriptExecutionContext::postTaskTo(context->identifier(), [message = messageWithMessagePorts, protectedThis = Ref { *worker }, ports](ScriptExecutionContext& context) mutable { Zig::GlobalObject* globalObject = jsCast(context.jsGlobalObject()); - bool didFail = false; - JSValue value = message->deserialize(*globalObject, globalObject, SerializationErrorMode::NonThrowing, &didFail); - if (didFail) { - protectedThis->dispatchEvent(MessageEvent::create(eventNames().messageerrorEvent, MessageEvent::Init {}, MessageEvent::IsTrusted::Yes)); - return; - } + auto ports = MessagePort::entanglePorts(context, WTFMove(message.transferredPorts)); + auto event = MessageEvent::create(*globalObject, message.message.releaseNonNull(), std::nullopt, WTFMove(ports)); - WebCore::MessageEvent::Init init; - init.data = value; - protectedThis->dispatchEvent(MessageEvent::create(eventNames().messageEvent, WTFMove(init), MessageEvent::IsTrusted::Yes)); + protectedThis->dispatchEvent(event.event); }); return JSValue::encode(jsUndefined()); @@ -4069,7 +4035,6 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DontDelete | 0 }); static NeverDestroyed BunLazyString(MAKE_STATIC_STRING_IMPL("Bun.lazy")); - static NeverDestroyed CommonJSSymbolKey(MAKE_STATIC_STRING_IMPL("CommonJS")); JSC::Identifier BunLazyIdentifier = JSC::Identifier::fromUid(vm.symbolRegistry().symbolForKey(BunLazyString)); JSC::JSFunction* lazyLoadFunction = JSC::JSFunction::create(vm, this, 0, BunLazyString, functionLazyLoad, ImplementationVisibility::Public); @@ -4099,7 +4064,6 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) extraStaticGlobals.uncheckedAppend(GlobalPropertyInfo(builtinNames.getInternalWritableStreamPrivateName(), JSFunction::create(vm, this, 1, String(), getInternalWritableStream, ImplementationVisibility::Public), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly)); extraStaticGlobals.uncheckedAppend(GlobalPropertyInfo(builtinNames.createWritableStreamFromInternalPrivateName(), JSFunction::create(vm, this, 1, String(), createWritableStreamFromInternal, ImplementationVisibility::Public), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly)); extraStaticGlobals.uncheckedAppend(GlobalPropertyInfo(builtinNames.fulfillModuleSyncPrivateName(), JSFunction::create(vm, this, 1, String(), functionFulfillModuleSync, ImplementationVisibility::Public), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function)); - extraStaticGlobals.uncheckedAppend(GlobalPropertyInfo(builtinNames.commonJSSymbolPrivateName(), JSC::Symbol::create(vm, vm.symbolRegistry().symbolForKey(CommonJSSymbolKey)), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly)); extraStaticGlobals.uncheckedAppend(GlobalPropertyInfo(builtinNames.directPrivateName(), JSFunction::create(vm, this, 1, String(), functionGetDirectStreamDetails, ImplementationVisibility::Public), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function)); extraStaticGlobals.uncheckedAppend(GlobalPropertyInfo(vm.propertyNames->builtinNames().ArrayBufferPrivateName(), arrayBufferConstructor(), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly)); @@ -4117,8 +4081,12 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) putDirectBuiltinFunction(vm, this, builtinNames.requireESMPrivateName(), importMetaObjectRequireESMCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectBuiltinFunction(vm, this, builtinNames.loadCJS2ESMPrivateName(), importMetaObjectLoadCJS2ESMCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectBuiltinFunction(vm, this, builtinNames.internalRequirePrivateName(), importMetaObjectInternalRequireCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); + putDirectBuiltinFunction(vm, this, builtinNames.requireNativeModulePrivateName(), moduleRequireNativeModuleCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectNativeFunction(vm, this, builtinNames.createUninitializedArrayBufferPrivateName(), 1, functionCreateUninitializedArrayBuffer, ImplementationVisibility::Public, NoIntrinsic, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function); putDirectNativeFunction(vm, this, builtinNames.resolveSyncPrivateName(), 1, functionImportMeta__resolveSyncPrivate, ImplementationVisibility::Public, NoIntrinsic, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function); + putDirectNativeFunction(vm, this, builtinNames.createInternalModuleByIdPrivateName(), 1, InternalModuleRegistry::jsCreateInternalModuleById, ImplementationVisibility::Public, NoIntrinsic, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function); + putDirect(vm, builtinNames.internalModuleRegistryPrivateName(), this->internalModuleRegistry(), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); + putDirect(vm, builtinNames.processBindingConstantsPrivateName(), this->processBindingConstants(), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "process"_s), JSC::CustomGetterSetter::create(vm, property_lazyProcessGetter, property_lazyProcessSetter), JSC::PropertyAttribute::CustomAccessor | 0); @@ -4165,30 +4133,12 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "Blob"_s), JSC::CustomGetterSetter::create(vm, JSBlob_getter, JSBlob_setter), JSC::PropertyAttribute::DontDelete | 0); - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "DOMException"_s), JSC::CustomGetterSetter::create(vm, JSDOMException_getter, nullptr), - JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "Event"_s), JSC::CustomGetterSetter::create(vm, JSEvent_getter, nullptr), - JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "EventTarget"_s), JSC::CustomGetterSetter::create(vm, JSEventTarget_getter, nullptr), - JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "AbortController"_s), JSC::CustomGetterSetter::create(vm, JSDOMAbortController_getter, nullptr), JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "AbortSignal"_s), JSC::CustomGetterSetter::create(vm, JSDOMAbortSignal_getter, nullptr), JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "CustomEvent"_s), JSC::CustomGetterSetter::create(vm, JSCustomEvent_getter, nullptr), - JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "ErrorEvent"_s), JSC::CustomGetterSetter::create(vm, JSErrorEvent_getter, nullptr), - JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "CloseEvent"_s), JSC::CustomGetterSetter::create(vm, JSCloseEvent_getter, nullptr), - JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - putDirectCustomAccessor(vm, JSC::Identifier::fromString(vm, "$_BunCommonJSModule_$"_s), JSC::CustomGetterSetter::create(vm, BunCommonJSModule_getter, nullptr), JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); @@ -4206,12 +4156,21 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) putDirectCustomAccessor(vm, static_cast(vm.clientData)->builtinNames().BufferPrivateName(), realBufferAccessor, JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly); - PUT_WEBCORE_GENERATED_CONSTRUCTOR("TextEncoder"_s, JSTextEncoder); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("BroadcastChannel"_s, JSBroadcastChannel); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("CloseEvent"_s, JSCloseEvent); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("CustomEvent"_s, JSCustomEvent); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("DOMException"_s, JSDOMException); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("ErrorEvent"_s, JSErrorEvent); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("Event"_s, JSEvent); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("EventTarget"_s, JSEventTarget); PUT_WEBCORE_GENERATED_CONSTRUCTOR("FormData"_s, JSDOMFormData); - PUT_WEBCORE_GENERATED_CONSTRUCTOR("MessageEvent"_s, JSMessageEvent); - PUT_WEBCORE_GENERATED_CONSTRUCTOR("WebSocket"_s, JSWebSocket); PUT_WEBCORE_GENERATED_CONSTRUCTOR("Headers"_s, JSFetchHeaders); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("MessageChannel"_s, JSMessageChannel); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("MessageEvent"_s, JSMessageEvent); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("MessagePort"_s, JSMessagePort); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("TextEncoder"_s, JSTextEncoder); PUT_WEBCORE_GENERATED_CONSTRUCTOR("URLSearchParams"_s, JSURLSearchParams); + PUT_WEBCORE_GENERATED_CONSTRUCTOR("WebSocket"_s, JSWebSocket); PUT_WEBCORE_GENERATED_CONSTRUCTOR("Worker"_s, JSWorker); putDirectCustomAccessor(vm, builtinNames.TransformStreamPublicName(), CustomGetterSetter::create(vm, jsServiceWorkerGlobalScope_TransformStreamConstructor, nullptr), attributesForStructure(static_cast(JSC::PropertyAttribute::DontEnum))); @@ -4450,6 +4409,16 @@ void GlobalObject::installAPIGlobals(JSClassRef* globals, int count, JSC::VM& vm | 0); } + { + + JSC::Identifier identifier = JSC::Identifier::fromString(vm, "isMainThread"_s); + object->putDirect(vm, identifier, + jsBoolean(scriptExecutionContext()->isMainThread()), + JSC::PropertyAttribute::DontDelete + | JSC::PropertyAttribute::ReadOnly + | 0); + } + { JSC::Identifier identifier = JSC::Identifier::fromString(vm, pathToFileURLString); @@ -4583,17 +4552,26 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor) visitor.append(thisObject->m_readableStreamToText); visitor.append(thisObject->m_readableStreamToFormData); - visitor.append(thisObject->m_JSTextDecoderSetterValue); - visitor.append(thisObject->m_JSResponseSetterValue); - visitor.append(thisObject->m_JSRequestSetterValue); visitor.append(thisObject->m_JSBlobSetterValue); - visitor.append(thisObject->m_JSMessageEventSetterValue); + visitor.append(thisObject->m_JSBroadcastChannelSetterValue); visitor.append(thisObject->m_JSBufferSetterValue); - visitor.append(thisObject->m_JSWebSocketSetterValue); + visitor.append(thisObject->m_JSCloseEventSetterValue); + visitor.append(thisObject->m_JSCustomEventSetterValue); + visitor.append(thisObject->m_JSDOMExceptionSetterValue); + visitor.append(thisObject->m_JSDOMFormDataSetterValue); + visitor.append(thisObject->m_JSErrorEventSetterValue); + visitor.append(thisObject->m_JSEventSetterValue); + visitor.append(thisObject->m_JSEventTargetSetterValue); visitor.append(thisObject->m_JSFetchHeadersSetterValue); + visitor.append(thisObject->m_JSMessageChannelSetterValue); + visitor.append(thisObject->m_JSMessageEventSetterValue); + visitor.append(thisObject->m_JSMessagePortSetterValue); + visitor.append(thisObject->m_JSRequestSetterValue); + visitor.append(thisObject->m_JSResponseSetterValue); + visitor.append(thisObject->m_JSTextDecoderSetterValue); visitor.append(thisObject->m_JSTextEncoderSetterValue); visitor.append(thisObject->m_JSURLSearchParamsSetterValue); - visitor.append(thisObject->m_JSDOMFormDataSetterValue); + visitor.append(thisObject->m_JSWebSocketSetterValue); visitor.append(thisObject->m_JSWorkerSetterValue); thisObject->m_JSArrayBufferSinkClassStructure.visit(visitor); @@ -4620,7 +4598,6 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor) thisObject->m_navigatorObject.visit(visitor); thisObject->m_nativeMicrotaskTrampoline.visit(visitor); thisObject->m_performanceObject.visit(visitor); - thisObject->m_primordialsObject.visit(visitor); thisObject->m_processEnvObject.visit(visitor); thisObject->m_processObject.visit(visitor); thisObject->m_subtleCryptoObject.visit(visitor); @@ -4631,8 +4608,10 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor) thisObject->m_requireFunctionUnbound.visit(visitor); thisObject->m_requireResolveFunctionUnbound.visit(visitor); + thisObject->m_processBindingConstants.visit(visitor); thisObject->m_importMetaObjectStructure.visit(visitor); thisObject->m_asyncBoundFunctionStructure.visit(visitor); + thisObject->m_internalModuleRegistry.visit(visitor); thisObject->m_dnsObject.visit(visitor); thisObject->m_lazyRequireCacheObject.visit(visitor); @@ -4641,6 +4620,7 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor) thisObject->m_lazyTestModuleObject.visit(visitor); thisObject->m_lazyPreloadTestModuleObject.visit(visitor); thisObject->m_commonJSModuleObjectStructure.visit(visitor); + thisObject->m_memoryFootprintStructure.visit(visitor); thisObject->m_lazyPasswordObject.visit(visitor); thisObject->m_commonJSFunctionArgumentsStructure.visit(visitor); thisObject->m_cachedGlobalObjectStructure.visit(visitor); @@ -4908,7 +4888,7 @@ JSC::JSInternalPromise* GlobalObject::moduleLoaderFetch(JSGlobalObject* globalOb res.result.err.code = 0; res.result.err.ptr = nullptr; - JSValue result = Bun::fetchSourceCodeAsync( + JSValue result = Bun::fetchESMSourceCodeAsync( reinterpret_cast(globalObject), &res, &moduleKeyBun, diff --git a/src/bun.js/bindings/ZigGlobalObject.h b/src/bun.js/bindings/ZigGlobalObject.h index e4364d248256da..1d82cd0f350c9b 100644 --- a/src/bun.js/bindings/ZigGlobalObject.h +++ b/src/bun.js/bindings/ZigGlobalObject.h @@ -42,12 +42,11 @@ class DOMWrapperWorld; #include "DOMConstructors.h" #include "BunPlugin.h" #include "JSMockFunction.h" - -namespace Bun { -class GlobalScope; -} +#include "InternalModuleRegistry.h" +#include "ProcessBindingConstants.h" namespace WebCore { +class GlobalScope; class SubtleCrypto; class EventTarget; } @@ -255,7 +254,6 @@ class GlobalObject : public JSC::JSGlobalObject { JSC::Structure* callSiteStructure() const { return m_callSiteStructure.getInitializedOnMainThread(this); } JSC::JSObject* performanceObject() { return m_performanceObject.getInitializedOnMainThread(this); } - JSC::JSObject* primordialsObject() { return m_primordialsObject.getInitializedOnMainThread(this); } JSC::JSFunction* performMicrotaskFunction() { return m_performMicrotaskFunction.getInitializedOnMainThread(this); } JSC::JSFunction* performMicrotaskVariadicFunction() { return m_performMicrotaskVariadicFunction.getInitializedOnMainThread(this); } @@ -264,6 +262,8 @@ class GlobalObject : public JSC::JSGlobalObject { JSObject* requireFunctionUnbound() { return m_requireFunctionUnbound.getInitializedOnMainThread(this); } JSObject* requireResolveFunctionUnbound() { return m_requireResolveFunctionUnbound.getInitializedOnMainThread(this); } + Bun::InternalModuleRegistry* internalModuleRegistry() { return m_internalModuleRegistry.getInitializedOnMainThread(this); } + Bun::ProcessBindingConstants* processBindingConstants() { return m_processBindingConstants.getInitializedOnMainThread(this); } JSObject* lazyRequireCacheObject() { return m_lazyRequireCacheObject.getInitializedOnMainThread(this); } @@ -378,18 +378,33 @@ class GlobalObject : public JSC::JSGlobalObject { mutable WriteBarrier m_readableStreamToJSON; mutable WriteBarrier m_readableStreamToText; mutable WriteBarrier m_readableStreamToFormData; + + mutable WriteBarrier m_BunCommonJSModuleValue; + mutable WriteBarrier m_JSBroadcastChannelSetterValue; mutable WriteBarrier m_JSBufferSetterValue; + mutable WriteBarrier m_JSCloseEventSetterValue; + mutable WriteBarrier m_JSCustomEventSetterValue; + mutable WriteBarrier m_JSDOMExceptionSetterValue; + mutable WriteBarrier m_JSDOMFormDataSetterValue; + mutable WriteBarrier m_JSErrorEventSetterValue; + mutable WriteBarrier m_JSEventSetterValue; + mutable WriteBarrier m_JSEventTargetSetterValue; mutable WriteBarrier m_JSFetchHeadersSetterValue; + mutable WriteBarrier m_JSMessageChannelSetterValue; mutable WriteBarrier m_JSMessageEventSetterValue; + mutable WriteBarrier m_JSMessagePortSetterValue; mutable WriteBarrier m_JSTextEncoderSetterValue; mutable WriteBarrier m_JSURLSearchParamsSetterValue; mutable WriteBarrier m_JSWebSocketSetterValue; - mutable WriteBarrier m_JSDOMFormDataSetterValue; mutable WriteBarrier m_JSWorkerSetterValue; - mutable WriteBarrier m_BunCommonJSModuleValue; mutable WriteBarrier m_thenables[promiseFunctionsSize + 1]; + Structure* memoryFootprintStructure() + { + return m_memoryFootprintStructure.getInitializedOnMainThread(this); + } + JSObject* navigatorObject(); JSFunction* nativeMicrotaskTrampoline() { return m_nativeMicrotaskTrampoline.getInitializedOnMainThread(this); } @@ -442,6 +457,8 @@ class GlobalObject : public JSC::JSGlobalObject { Bun::JSMockModule mockModule; + LazyProperty m_processEnvObject; + #include "ZigGeneratedClasses+lazyStructureHeader.h" private: @@ -504,8 +521,6 @@ class GlobalObject : public JSC::JSGlobalObject { LazyProperty m_JSHTTPSResponseControllerPrototype; LazyProperty m_navigatorObject; LazyProperty m_performanceObject; - LazyProperty m_primordialsObject; - LazyProperty m_processEnvObject; LazyProperty m_processObject; LazyProperty m_subtleCryptoObject; LazyProperty m_JSHTTPResponseController; @@ -522,9 +537,12 @@ class GlobalObject : public JSC::JSGlobalObject { LazyProperty m_cachedGlobalProxyStructure; LazyProperty m_commonJSModuleObjectStructure; LazyProperty m_commonJSFunctionArgumentsStructure; + LazyProperty m_memoryFootprintStructure; LazyProperty m_requireFunctionUnbound; LazyProperty m_requireResolveFunctionUnbound; + LazyProperty m_internalModuleRegistry; + LazyProperty m_processBindingConstants; LazyProperty m_importMetaObjectStructure; LazyProperty m_asyncBoundFunctionStructure; diff --git a/src/bun.js/bindings/ZigSourceProvider.cpp b/src/bun.js/bindings/ZigSourceProvider.cpp index a71e946deb524e..d11c748da53af1 100644 --- a/src/bun.js/bindings/ZigSourceProvider.cpp +++ b/src/bun.js/bindings/ZigSourceProvider.cpp @@ -58,11 +58,48 @@ static SourceOrigin toSourceOrigin(const String& sourceURL, bool isBuiltin) return SourceOrigin(WTF::URL::fileURLWithFileSystemPath(sourceURL)); } +void forEachSourceProvider(const WTF::Function& func) +{ + // if (sourceProviderMap == nullptr) { + // return; + // } + + // for (auto& pair : *sourceProviderMap) { + // auto sourceProvider = pair.value; + // if (sourceProvider) { + // func(sourceProvider); + // } + // } +} +extern "C" int ByteRangeMapping__getSourceID(void* mappings, BunString sourceURL); +extern "C" void* ByteRangeMapping__find(BunString sourceURL); +void* sourceMappingForSourceURL(const WTF::String& sourceURL) +{ + return ByteRangeMapping__find(Bun::toString(sourceURL)); +} + +extern "C" void ByteRangeMapping__generate(BunString sourceURL, BunString code, int sourceID); + +JSC::SourceID sourceIDForSourceURL(const WTF::String& sourceURL) +{ + void* mappings = ByteRangeMapping__find(Bun::toString(sourceURL)); + if (!mappings) { + return 0; + } + + return ByteRangeMapping__getSourceID(mappings, Bun::toString(sourceURL)); +} + +extern "C" bool BunTest__shouldGenerateCodeCoverage(BunString sourceURL); + Ref SourceProvider::create(Zig::GlobalObject* globalObject, ResolvedSource resolvedSource, JSC::SourceProviderSourceType sourceType, bool isBuiltin) { auto stringImpl = Bun::toWTFString(resolvedSource.source_code); auto sourceURLString = toStringCopy(resolvedSource.source_url); + bool isCodeCoverageEnabled = !!globalObject->vm().controlFlowProfiler(); + + bool shouldGenerateCodeCoverage = isCodeCoverageEnabled && !isBuiltin && BunTest__shouldGenerateCodeCoverage(Bun::toString(sourceURLString)); auto provider = adoptRef(*new SourceProvider( globalObject->isThreadLocalDefaultGlobalObject ? globalObject : nullptr, @@ -71,6 +108,10 @@ Ref SourceProvider::create(Zig::GlobalObject* globalObject, Reso sourceURLString.impl(), TextPosition(), sourceType)); + if (shouldGenerateCodeCoverage) { + ByteRangeMapping__generate(Bun::toString(provider->sourceURL()), Bun::toString(provider->source().toStringWithoutCopying()), provider->asID()); + } + return provider; } @@ -198,4 +239,4 @@ int SourceProvider::readCache(JSC::VM& vm, const JSC::SourceCode& sourceCode) // return 0; // } } -}; // namespace Zig \ No newline at end of file +}; // namespace Zig diff --git a/src/bun.js/bindings/ZigSourceProvider.h b/src/bun.js/bindings/ZigSourceProvider.h index c189cc4542f9a8..364e6ee2382760 100644 --- a/src/bun.js/bindings/ZigSourceProvider.h +++ b/src/bun.js/bindings/ZigSourceProvider.h @@ -22,6 +22,10 @@ namespace Zig { class GlobalObject; +void forEachSourceProvider(WTF::Function); +JSC::SourceID sourceIDForSourceURL(const WTF::String& sourceURL); +void* sourceMappingForSourceURL(const WTF::String& sourceURL); + class SourceProvider final : public JSC::SourceProvider { WTF_MAKE_FAST_ALLOCATED; using Base = JSC::SourceProvider; diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index 981a475a3635cf..201fc0959fe2ec 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -1404,7 +1404,7 @@ double JSC__JSValue__getLengthIfPropertyExistsInternal(JSC__JSValue value, JSC__ return 0; } - case JSC::JSType(JSDOMWrapperType): { + case WebCore::JSDOMWrapperType: { if (auto* headers = jsDynamicCast(cell)) return static_cast(jsCast(cell)->wrapped().size()); @@ -4552,3 +4552,12 @@ CPP_DECL void JSC__JSMap__set(JSC__JSMap* map, JSC__JSGlobalObject* arg1, JSC__J { map->set(arg1, JSC::JSValue::decode(JSValue2), JSC::JSValue::decode(JSValue3)); } + +CPP_DECL void JSC__VM__setControlFlowProfiler(JSC__VM* vm, bool isEnabled) +{ + if (isEnabled) { + vm->enableControlFlowProfiler(); + } else { + vm->disableControlFlowProfiler(); + } +} \ No newline at end of file diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index 924eb27a14db3a..3b6116a0db013a 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -102,8 +102,9 @@ pub const ZigString = extern struct { }; pub fn fromBytes(slice_: []const u8) ZigString { - if (!strings.isAllASCII(slice_)) - return fromUTF8(slice_); + if (!strings.isAllASCII(slice_)) { + return initUTF8(slice_); + } return init(slice_); } @@ -4751,8 +4752,8 @@ pub const JSValue = enum(JSValueReprInt) { /// It knows not to free it /// This mimicks the implementation in JavaScriptCore's C++ pub inline fn ensureStillAlive(this: JSValue) void { - if (this.isEmpty() or this.isNumber() or this.isBoolean() or this.isUndefinedOrNull()) return; - std.mem.doNotOptimizeAway(@as(C_API.JSObjectRef, @ptrCast(this.asVoid()))); + if (!this.isCell()) return; + std.mem.doNotOptimizeAway(this.asEncoded().asPtr); } pub inline fn asNullableVoid(this: JSValue) ?*anyopaque { @@ -4978,6 +4979,7 @@ pub const VM = extern struct { SmallHeap = 0, LargeHeap = 1, }; + pub fn create(heap_type: HeapType) *VM { return cppFn("create", .{@intFromEnum(heap_type)}); } @@ -4986,6 +4988,10 @@ pub const VM = extern struct { return cppFn("deinit", .{ vm, global_object }); } + pub fn setControlFlowProfiler(vm: *VM, enabled: bool) void { + return cppFn("setControlFlowProfiler", .{ vm, enabled }); + } + pub fn isJITEnabled() bool { return cppFn("isJITEnabled", .{}); } @@ -5093,7 +5099,7 @@ pub const VM = extern struct { return cppFn("blockBytesAllocated", .{vm}); } - pub const Extern = [_][]const u8{ "collectAsync", "externalMemorySize", "blockBytesAllocated", "heapSize", "releaseWeakRefs", "throwError", "deferGC", "holdAPILock", "runGC", "generateHeapSnapshot", "isJITEnabled", "deleteAllCode", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint", "setExecutionTimeLimit", "clearExecutionTimeLimit" }; + pub const Extern = [_][]const u8{ "setControlFlowProfiler", "collectAsync", "externalMemorySize", "blockBytesAllocated", "heapSize", "releaseWeakRefs", "throwError", "deferGC", "holdAPILock", "runGC", "generateHeapSnapshot", "isJITEnabled", "deleteAllCode", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint", "setExecutionTimeLimit", "clearExecutionTimeLimit" }; }; pub const ThrowScope = extern struct { @@ -5391,12 +5397,19 @@ pub const URL = opaque { extern fn URL__pathname(*URL) String; extern fn URL__getHrefFromJS(JSValue, *JSC.JSGlobalObject) String; extern fn URL__getHref(*String) String; + extern fn URL__getFileURLString(*String) String; pub fn hrefFromString(str: bun.String) String { JSC.markBinding(@src()); var input = str; return URL__getHref(&input); } + pub fn fileURLFromString(str: bun.String) String { + JSC.markBinding(@src()); + var input = str; + return URL__getFileURLString(&input); + } + /// This percent-encodes the URL, punycode-encodes the hostname, and returns the result /// If it fails, the tag is marked Dead pub fn hrefFromJS(value: JSValue, globalObject: *JSC.JSGlobalObject) String { diff --git a/src/bun.js/bindings/c-bindings.cpp b/src/bun.js/bindings/c-bindings.cpp index 0e837d04f63b85..ff4c8c4e7cd049 100644 --- a/src/bun.js/bindings/c-bindings.cpp +++ b/src/bun.js/bindings/c-bindings.cpp @@ -40,4 +40,12 @@ extern "C" void bun_ignore_sigpipe() { // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); +} +extern "C" ssize_t bun_sysconf__SC_CLK_TCK() +{ +#ifdef __APPLE__ + return sysconf(_SC_CLK_TCK); +#else + return 0; +#endif } \ No newline at end of file diff --git a/src/bun.js/bindings/exports.zig b/src/bun.js/bindings/exports.zig index 3a2cbcbddac638..265ada40a6b07f 100644 --- a/src/bun.js/bindings/exports.zig +++ b/src/bun.js/bindings/exports.zig @@ -46,8 +46,9 @@ pub const ZigGlobalObject = extern struct { console: *anyopaque, context_id: i32, mini_mode: bool, + worker_ptr: ?*anyopaque, ) *JSGlobalObject { - var global = shim.cppFn("create", .{ class_ref, count, console, context_id, mini_mode }); + var global = shim.cppFn("create", .{ class_ref, count, console, context_id, mini_mode, worker_ptr }); Backtrace.reloadHandlers() catch unreachable; return global; } @@ -209,34 +210,19 @@ pub const ResolvedSource = extern struct { pub const name = "ResolvedSource"; pub const namespace = shim.namespace; - specifier: bun.String, - source_code: bun.String, - source_url: ZigString, + specifier: bun.String = bun.String.empty, + source_code: bun.String = bun.String.empty, + source_url: ZigString = ZigString.Empty, commonjs_exports: ?[*]ZigString = null, commonjs_exports_len: u32 = 0, - hash: u32, + hash: u32 = 0, - allocator: ?*anyopaque, + allocator: ?*anyopaque = null, tag: Tag = Tag.javascript, - pub const Tag = enum(u64) { - javascript = 0, - package_json_type_module = 1, - wasm = 2, - object = 3, - file = 4, - - @"node:buffer" = 1024, - @"node:process" = 1025, - @"bun:events_native" = 1026, // native version of EventEmitter used for streams - @"node:string_decoder" = 1027, - @"node:module" = 1028, - @"node:tty" = 1029, - @"node:util/types" = 1030, - @"node:constants" = 1031, - }; + pub const Tag = @import("../../js/out/ResolvedSourceTag.zig").ResolvedSourceTag; }; const Mimalloc = @import("../../allocators/mimalloc.zig"); diff --git a/src/bun.js/bindings/generated_classes.zig b/src/bun.js/bindings/generated_classes.zig index 947be7a5197d1c..9cf63a2e1f3243 100644 --- a/src/bun.js/bindings/generated_classes.zig +++ b/src/bun.js/bindings/generated_classes.zig @@ -883,8 +883,12 @@ pub const JSExpect = struct { @compileLog("Expect.finalize is not a finalizer"); } + if (@TypeOf(Expect.fail) != CallbackType) + @compileLog("Expected Expect.fail to be a callback but received " ++ @typeName(@TypeOf(Expect.fail))); if (@TypeOf(Expect.getNot) != GetterTypeWithThisValue) @compileLog("Expected Expect.getNot to be a getter with thisValue"); + if (@TypeOf(Expect._pass) != CallbackType) + @compileLog("Expected Expect._pass to be a callback but received " ++ @typeName(@TypeOf(Expect._pass))); if (@TypeOf(Expect.getRejects) != GetterTypeWithThisValue) @compileLog("Expected Expect.getRejects to be a getter with thisValue"); if (@TypeOf(Expect.getResolves) != GetterTypeWithThisValue) @@ -987,6 +991,8 @@ pub const JSExpect = struct { @compileLog("Expected Expect.toHaveReturnedWith to be a callback but received " ++ @typeName(@TypeOf(Expect.toHaveReturnedWith))); if (@TypeOf(Expect.toInclude) != CallbackType) @compileLog("Expected Expect.toInclude to be a callback but received " ++ @typeName(@TypeOf(Expect.toInclude))); + if (@TypeOf(Expect.toIncludeRepeated) != CallbackType) + @compileLog("Expected Expect.toIncludeRepeated to be a callback but received " ++ @typeName(@TypeOf(Expect.toIncludeRepeated))); if (@TypeOf(Expect.toMatch) != CallbackType) @compileLog("Expected Expect.toMatch to be a callback but received " ++ @typeName(@TypeOf(Expect.toMatch))); if (@TypeOf(Expect.toMatchInlineSnapshot) != CallbackType) @@ -995,6 +1001,8 @@ pub const JSExpect = struct { @compileLog("Expected Expect.toMatchObject to be a callback but received " ++ @typeName(@TypeOf(Expect.toMatchObject))); if (@TypeOf(Expect.toMatchSnapshot) != CallbackType) @compileLog("Expected Expect.toMatchSnapshot to be a callback but received " ++ @typeName(@TypeOf(Expect.toMatchSnapshot))); + if (@TypeOf(Expect.toSatisfy) != CallbackType) + @compileLog("Expected Expect.toSatisfy to be a callback but received " ++ @typeName(@TypeOf(Expect.toSatisfy))); if (@TypeOf(Expect.toStartWith) != CallbackType) @compileLog("Expected Expect.toStartWith to be a callback but received " ++ @typeName(@TypeOf(Expect.toStartWith))); if (@TypeOf(Expect.toStrictEqual) != CallbackType) @@ -1037,6 +1045,7 @@ pub const JSExpect = struct { if (@TypeOf(Expect.call) != StaticCallbackType) @compileLog("Expected Expect.call to be a static callback"); if (!JSC.is_bindgen) { + @export(Expect._pass, .{ .name = "ExpectPrototype___pass" }); @export(Expect.addSnapshotSerializer, .{ .name = "ExpectClass__addSnapshotSerializer" }); @export(Expect.any, .{ .name = "ExpectClass__any" }); @export(Expect.anything, .{ .name = "ExpectClass__anything" }); @@ -1045,6 +1054,7 @@ pub const JSExpect = struct { @export(Expect.call, .{ .name = "ExpectClass__call" }); @export(Expect.constructor, .{ .name = "ExpectClass__construct" }); @export(Expect.extend, .{ .name = "ExpectClass__extend" }); + @export(Expect.fail, .{ .name = "ExpectPrototype__fail" }); @export(Expect.finalize, .{ .name = "ExpectClass__finalize" }); @export(Expect.getNot, .{ .name = "ExpectPrototype__getNot" }); @export(Expect.getRejects, .{ .name = "ExpectPrototype__getRejects" }); @@ -1105,10 +1115,12 @@ pub const JSExpect = struct { @export(Expect.toHaveReturnedTimes, .{ .name = "ExpectPrototype__toHaveReturnedTimes" }); @export(Expect.toHaveReturnedWith, .{ .name = "ExpectPrototype__toHaveReturnedWith" }); @export(Expect.toInclude, .{ .name = "ExpectPrototype__toInclude" }); + @export(Expect.toIncludeRepeated, .{ .name = "ExpectPrototype__toIncludeRepeated" }); @export(Expect.toMatch, .{ .name = "ExpectPrototype__toMatch" }); @export(Expect.toMatchInlineSnapshot, .{ .name = "ExpectPrototype__toMatchInlineSnapshot" }); @export(Expect.toMatchObject, .{ .name = "ExpectPrototype__toMatchObject" }); @export(Expect.toMatchSnapshot, .{ .name = "ExpectPrototype__toMatchSnapshot" }); + @export(Expect.toSatisfy, .{ .name = "ExpectPrototype__toSatisfy" }); @export(Expect.toStartWith, .{ .name = "ExpectPrototype__toStartWith" }); @export(Expect.toStrictEqual, .{ .name = "ExpectPrototype__toStrictEqual" }); @export(Expect.toThrow, .{ .name = "ExpectPrototype__toThrow" }); diff --git a/src/bun.js/bindings/headers-handwritten.h b/src/bun.js/bindings/headers-handwritten.h index df1bec554bbb02..e19be7abeb6bf5 100644 --- a/src/bun.js/bindings/headers-handwritten.h +++ b/src/bun.js/bindings/headers-handwritten.h @@ -70,9 +70,9 @@ typedef struct ResolvedSource { uint32_t commonJSExportsLen; uint32_t hash; void* allocator; - uint64_t tag; + uint32_t tag; } ResolvedSource; -static const uint64_t ResolvedSourceTagPackageJSONTypeModule = 1; +static const uint32_t ResolvedSourceTagPackageJSONTypeModule = 1; typedef union ErrorableResolvedSourceResult { ResolvedSource value; ZigErrorType err; @@ -264,18 +264,7 @@ typedef struct { bool shared; } Bun__ArrayBuffer; -enum SyntheticModuleType : uint64_t { - ObjectModule = 2, - - Buffer = 1024, - Process = 1025, - Events = 1026, - StringDecoder = 1027, - Module = 1028, - TTY = 1029, - NodeUtilTypes = 1030, - Constants = 1031, -}; +#include "../../../js/out/SyntheticModuleType.h" extern "C" const char* Bun__userAgent; diff --git a/src/bun.js/bindings/headers.h b/src/bun.js/bindings/headers.h index 05c708a48fd4d6..63ae6c3a46b9a5 100644 --- a/src/bun.js/bindings/headers.h +++ b/src/bun.js/bindings/headers.h @@ -428,6 +428,7 @@ CPP_DECL bool JSC__VM__isEntered(JSC__VM* arg0); CPP_DECL bool JSC__VM__isJITEnabled(); CPP_DECL void JSC__VM__releaseWeakRefs(JSC__VM* arg0); CPP_DECL JSC__JSValue JSC__VM__runGC(JSC__VM* arg0, bool arg1); +CPP_DECL void JSC__VM__setControlFlowProfiler(JSC__VM* arg0, bool arg1); CPP_DECL void JSC__VM__setExecutionForbidden(JSC__VM* arg0, bool arg1); CPP_DECL void JSC__VM__setExecutionTimeLimit(JSC__VM* arg0, double arg1); CPP_DECL void JSC__VM__shrinkFootprint(JSC__VM* arg0); @@ -578,7 +579,7 @@ ZIG_DECL JSC__JSValue Crypto__timingSafeEqual__slowpath(JSC__JSGlobalObject* arg #pragma mark - Zig::GlobalObject -CPP_DECL JSC__JSGlobalObject* Zig__GlobalObject__create(JSClassRef* arg0, int32_t arg1, void* arg2, int32_t arg3, bool arg4); +CPP_DECL JSC__JSGlobalObject* Zig__GlobalObject__create(JSClassRef* arg0, int32_t arg1, void* arg2, int32_t arg3, bool arg4, void* arg5); CPP_DECL void* Zig__GlobalObject__getModuleRegistryMap(JSC__JSGlobalObject* arg0); CPP_DECL bool Zig__GlobalObject__resetModuleRegistryMap(JSC__JSGlobalObject* arg0, void* arg1); diff --git a/src/bun.js/bindings/headers.zig b/src/bun.js/bindings/headers.zig index fbca33a30dde96..2b25c0f5b56361 100644 --- a/src/bun.js/bindings/headers.zig +++ b/src/bun.js/bindings/headers.zig @@ -322,6 +322,7 @@ pub extern fn JSC__VM__isEntered(arg0: *bindings.VM) bool; pub extern fn JSC__VM__isJITEnabled(...) bool; pub extern fn JSC__VM__releaseWeakRefs(arg0: *bindings.VM) void; pub extern fn JSC__VM__runGC(arg0: *bindings.VM, arg1: bool) JSC__JSValue; +pub extern fn JSC__VM__setControlFlowProfiler(arg0: *bindings.VM, arg1: bool) void; pub extern fn JSC__VM__setExecutionForbidden(arg0: *bindings.VM, arg1: bool) void; pub extern fn JSC__VM__setExecutionTimeLimit(arg0: *bindings.VM, arg1: f64) void; pub extern fn JSC__VM__shrinkFootprint(arg0: *bindings.VM) void; @@ -350,7 +351,7 @@ pub extern fn Reader__intptr__put(arg0: *bindings.JSGlobalObject, JSValue1: JSC_ pub extern fn Crypto__getRandomValues__put(arg0: *bindings.JSGlobalObject, JSValue1: JSC__JSValue) void; pub extern fn Crypto__randomUUID__put(arg0: *bindings.JSGlobalObject, JSValue1: JSC__JSValue) void; pub extern fn Crypto__timingSafeEqual__put(arg0: *bindings.JSGlobalObject, JSValue1: JSC__JSValue) void; -pub extern fn Zig__GlobalObject__create(arg0: [*c]JSClassRef, arg1: i32, arg2: ?*anyopaque, arg3: i32, arg4: bool) *bindings.JSGlobalObject; +pub extern fn Zig__GlobalObject__create(arg0: [*c]JSClassRef, arg1: i32, arg2: ?*anyopaque, arg3: i32, arg4: bool, arg5: ?*anyopaque) *bindings.JSGlobalObject; pub extern fn Zig__GlobalObject__getModuleRegistryMap(arg0: *bindings.JSGlobalObject) ?*anyopaque; pub extern fn Zig__GlobalObject__resetModuleRegistryMap(arg0: *bindings.JSGlobalObject, arg1: ?*anyopaque) bool; pub extern fn Bun__Path__create(arg0: *bindings.JSGlobalObject, arg1: bool) JSC__JSValue; diff --git a/src/bun.js/bindings/napi.cpp b/src/bun.js/bindings/napi.cpp index 6e47db8c4e4eca..c27bcf5337e6d7 100644 --- a/src/bun.js/bindings/napi.cpp +++ b/src/bun.js/bindings/napi.cpp @@ -170,6 +170,8 @@ typedef struct StackAllocatedCallFrame { extern "C" Zig::GlobalObject* Bun__getDefaultGlobal(); +WTF_MAKE_ISO_ALLOCATED_IMPL(NapiRef); + static uint32_t getPropertyAttributes(napi_property_attributes attributes) { uint32_t result = 0; @@ -951,7 +953,7 @@ extern "C" napi_status napi_delete_reference(napi_env env, napi_ref ref) extern "C" void napi_delete_reference_internal(napi_ref ref) { NapiRef* napiRef = toJS(ref); - napiRef->~NapiRef(); + delete napiRef; } extern "C" napi_status napi_is_detached_arraybuffer(napi_env env, diff --git a/src/bun.js/bindings/napi.h b/src/bun.js/bindings/napi.h index 874377cf04a290..5508039631e28a 100644 --- a/src/bun.js/bindings/napi.h +++ b/src/bun.js/bindings/napi.h @@ -62,7 +62,7 @@ class NapiFinalizer { }; class NapiRef : public RefCounted, public CanMakeWeakPtr { - WTF_MAKE_FAST_ALLOCATED; + WTF_MAKE_ISO_ALLOCATED(NapiRef); public: void ref(); diff --git a/src/bun.js/bindings/node_util_types.h b/src/bun.js/bindings/node_util_types.h deleted file mode 100644 index adf0cd0eaaa38b..00000000000000 --- a/src/bun.js/bindings/node_util_types.h +++ /dev/null @@ -1,11 +0,0 @@ -#include "JavaScriptCore/JSGlobalObject.h" -#include "ZigGlobalObject.h" - -namespace Bun { -using namespace WebCore; - -void generateNodeUtilTypesSourceCode(JSC::JSGlobalObject* lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector& exportNames, - JSC::MarkedArgumentBuffer& exportValues); -} diff --git a/src/bun.js/bindings/sqlite/JSSQLStatement.cpp b/src/bun.js/bindings/sqlite/JSSQLStatement.cpp index 58c08a5e2ee612..8519cb2e2e0402 100644 --- a/src/bun.js/bindings/sqlite/JSSQLStatement.cpp +++ b/src/bun.js/bindings/sqlite/JSSQLStatement.cpp @@ -175,6 +175,8 @@ class JSSQLStatement : public JSC::JSNonFinalObject { } DECLARE_VISIT_CHILDREN; DECLARE_EXPORT_INFO; + template void visitAdditionalChildren(Visitor&); + template static void visitOutputConstraints(JSCell*, Visitor&); // static void analyzeHeap(JSCell*, JSC::HeapAnalyzer&); @@ -263,6 +265,8 @@ static void initializeColumnNames(JSC::JSGlobalObject* lexicalGlobalObject, JSSQ if (LIKELY(!anyHoles)) { Structure* structure = globalObject.structureCache().emptyObjectStructureForPrototype(&globalObject, globalObject.objectPrototype(), columnNames->size()); + vm.writeBarrier(castedThis, structure); + for (const auto& propertyName : *columnNames) { structure = Structure::addPropertyTransition(vm, structure, propertyName, 0, offset); } @@ -423,8 +427,10 @@ static JSC::JSValue rebindObject(JSC::JSGlobalObject* globalObject, JSC::JSValue JSValue value; if (LIKELY(!slot.isTaintedByOpaqueObject())) value = slot.getValue(globalObject, propertyName); - else + else { value = target->get(globalObject, propertyName); + RETURN_IF_EXCEPTION(scope, JSValue()); + } // Ensure this gets freed on scope clear auto utf8 = WTF::String(propertyName.string()).utf8(); @@ -1075,76 +1081,57 @@ static inline JSC::JSValue constructResultObject(JSC::JSGlobalObject* lexicalGlo auto* stmt = castedThis->stmt; if (auto* structure = castedThis->_structure.get()) { - RELEASE_ASSERT(count <= 64); - // It looks a little silly doing these two loops right? - // - // The code that does putDirectOffset has to be very careful about time between GC allocations - // while the object is not fully initialized. - // - // So we do two loops - // 1. The first loop to fill all the values from SQLite into a MarkedVector. - // 2. The second loop to actually put them into the object. - - // This rowBuffer is a stack allocation. - MarkedVector rowBuffer; - - rowBuffer.fill(count, [&](JSValue* value) -> void { - // Loop 1. Fill the rowBuffer with values from SQLite - for (int i = 0; i < count; i++, value++) { - switch (sqlite3_column_type(stmt, i)) { - case SQLITE_INTEGER: { - // https://github.com/oven-sh/bun/issues/1536 - *value = jsNumber(sqlite3_column_int64(stmt, i)); - break; - } - case SQLITE_FLOAT: { - *value = jsNumber(sqlite3_column_double(stmt, i)); - break; - } - // > Note that the SQLITE_TEXT constant was also used in SQLite version - // > 2 for a completely different meaning. Software that links against - // > both SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, - // > not SQLITE_TEXT. - case SQLITE3_TEXT: { - size_t len = sqlite3_column_bytes(stmt, i); - const unsigned char* text = len > 0 ? sqlite3_column_text(stmt, i) : nullptr; - - if (len > 64) { - *value = JSC::JSValue::decode(Bun__encoding__toStringUTF8(text, len, lexicalGlobalObject)); - continue; - } - - *value = jsString(vm, WTF::String::fromUTF8(text, len)); - break; - } - case SQLITE_BLOB: { - size_t len = sqlite3_column_bytes(stmt, i); - const void* blob = len > 0 ? sqlite3_column_blob(stmt, i) : nullptr; - JSC::JSUint8Array* array = JSC::JSUint8Array::createUninitialized(lexicalGlobalObject, lexicalGlobalObject->m_typedArrayUint8.get(lexicalGlobalObject), len); + result = JSC::constructEmptyObject(vm, structure); - if (LIKELY(blob && len)) - memcpy(array->vector(), blob, len); + for (unsigned int i = 0; i < count; i++) { + JSValue value; - *value = array; + // Loop 1. Fill the rowBuffer with values from SQLite + switch (sqlite3_column_type(stmt, i)) { + case SQLITE_INTEGER: { + // https://github.com/oven-sh/bun/issues/1536 + value = jsNumber(sqlite3_column_int64(stmt, i)); + break; + } + case SQLITE_FLOAT: { + value = jsNumber(sqlite3_column_double(stmt, i)); + break; + } + // > Note that the SQLITE_TEXT constant was also used in SQLite version + // > 2 for a completely different meaning. Software that links against + // > both SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, + // > not SQLITE_TEXT. + case SQLITE3_TEXT: { + size_t len = sqlite3_column_bytes(stmt, i); + const unsigned char* text = len > 0 ? sqlite3_column_text(stmt, i) : nullptr; + + if (len > 64) { + value = JSC::JSValue::decode(Bun__encoding__toStringUTF8(text, len, lexicalGlobalObject)); break; - } - default: { - *value = jsNull(); + } else { + value = jsString(vm, WTF::String::fromUTF8(text, len)); break; } - } } - }); + case SQLITE_BLOB: { + size_t len = sqlite3_column_bytes(stmt, i); + const void* blob = len > 0 ? sqlite3_column_blob(stmt, i) : nullptr; + JSC::JSUint8Array* array = JSC::JSUint8Array::createUninitialized(lexicalGlobalObject, lexicalGlobalObject->m_typedArrayUint8.get(lexicalGlobalObject), len); - result = JSC::constructEmptyObject(vm, structure); + if (LIKELY(blob && len)) + memcpy(array->vector(), blob, len); - // TODO: Add .forEach to MarkedVector<>. When JSC assertions are enabled, this function will fail. - rowBuffer.fill(count, [&](JSValue* value) -> void { - // Loop 2. fill the rowBuffer with values from SQLite - for (unsigned int i = 0; i < count; i++, value++) { - result->putDirectOffset(vm, i, *value); + value = array; + break; + } + default: { + value = jsNull(); + break; } - }); + } + + result->putDirectOffset(vm, i, value); + } } else { if (count <= 64) { @@ -1218,11 +1205,11 @@ static inline JSC::JSArray* constructResultRow(JSC::JSGlobalObject* lexicalGloba switch (sqlite3_column_type(stmt, i)) { case SQLITE_INTEGER: { // https://github.com/oven-sh/bun/issues/1536 - result->initializeIndex(scope, i, jsNumber(sqlite3_column_int64(stmt, i))); + result->putDirectIndex(lexicalGlobalObject, i, jsNumber(sqlite3_column_int64(stmt, i))); break; } case SQLITE_FLOAT: { - result->initializeIndex(scope, i, jsNumber(sqlite3_column_double(stmt, i))); + result->putDirectIndex(lexicalGlobalObject, i, jsNumber(sqlite3_column_double(stmt, i))); break; } // > Note that the SQLITE_TEXT constant was also used in SQLite version @@ -1233,10 +1220,10 @@ static inline JSC::JSArray* constructResultRow(JSC::JSGlobalObject* lexicalGloba size_t len = sqlite3_column_bytes(stmt, i); const unsigned char* text = len > 0 ? sqlite3_column_text(stmt, i) : nullptr; if (UNLIKELY(text == nullptr || len == 0)) { - result->initializeIndex(scope, i, jsEmptyString(vm)); + result->putDirectIndex(lexicalGlobalObject, i, jsEmptyString(vm)); continue; } - result->initializeIndex(scope, i, len < 64 ? jsString(vm, WTF::String::fromUTF8(text, len)) : JSC::JSValue::decode(Bun__encoding__toStringUTF8(text, len, lexicalGlobalObject))); + result->putDirectIndex(lexicalGlobalObject, i, len < 64 ? jsString(vm, WTF::String::fromUTF8(text, len)) : JSC::JSValue::decode(Bun__encoding__toStringUTF8(text, len, lexicalGlobalObject))); break; } case SQLITE_BLOB: { @@ -1244,11 +1231,11 @@ static inline JSC::JSArray* constructResultRow(JSC::JSGlobalObject* lexicalGloba const void* blob = len > 0 ? sqlite3_column_blob(stmt, i) : nullptr; JSC::JSUint8Array* array = JSC::JSUint8Array::createUninitialized(lexicalGlobalObject, lexicalGlobalObject->m_typedArrayUint8.get(lexicalGlobalObject), len); memcpy(array->vector(), blob, len); - result->initializeIndex(scope, i, array); + result->putDirectIndex(lexicalGlobalObject, i, array); break; } default: { - result->initializeIndex(scope, i, jsNull()); + result->putDirectIndex(lexicalGlobalObject, i, jsNull()); break; } } @@ -1697,4 +1684,26 @@ void JSSQLStatement::visitChildrenImpl(JSCell* cell, Visitor& visitor) } DEFINE_VISIT_CHILDREN(JSSQLStatement); + +template +void JSSQLStatement::visitAdditionalChildren(Visitor& visitor) +{ + JSSQLStatement* thisObject = this; + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + + visitor.append(thisObject->_structure); + visitor.append(thisObject->_prototype); +} + +template +void JSSQLStatement::visitOutputConstraints(JSCell* cell, Visitor& visitor) +{ + auto* thisObject = jsCast(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitOutputConstraints(thisObject, visitor); + thisObject->visitAdditionalChildren(visitor); +} + +template void JSSQLStatement::visitOutputConstraints(JSCell*, AbstractSlotVisitor&); +template void JSSQLStatement::visitOutputConstraints(JSCell*, SlotVisitor&); } diff --git a/src/bun.js/bindings/webcore/BroadcastChannel.cpp b/src/bun.js/bindings/webcore/BroadcastChannel.cpp new file mode 100644 index 00000000000000..74ff150e62342a --- /dev/null +++ b/src/bun.js/bindings/webcore/BroadcastChannel.cpp @@ -0,0 +1,330 @@ +/* + * Copyright (C) 2021 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "BroadcastChannel.h" + +#include "BunClientData.h" +#include "BroadcastChannelRegistry.h" +#include "EventNames.h" +#include "EventTarget.h" +#include "MessageEvent.h" +// #include "Page.h" +// #include "PartitionedSecurityOrigin.h" +// #include "SecurityOrigin.h" +#include "SerializedScriptValue.h" +// #include "WorkerGlobalScope.h" +#include "BunWorkerGlobalScope.h" +// #include "WorkerLoaderProxy.h" +// #include "WorkerThread.h" +#include +#include +#include +#include +#include + +extern "C" void Bun__eventLoop__incrementRefConcurrently(void* bunVM, int delta); + +namespace WebCore { + +WTF_MAKE_ISO_ALLOCATED_IMPL(BroadcastChannel); + +static Lock allBroadcastChannelsLock; +static HashMap& allBroadcastChannels() WTF_REQUIRES_LOCK(allBroadcastChannelsLock) +{ + static NeverDestroyed> map; + return map; +} + +static Lock channelToContextIdentifierLock; +static HashMap& channelToContextIdentifier() +{ + ASSERT(isMainThread()); + static NeverDestroyed> map; + return map; +} + +// static PartitionedSecurityOrigin partitionedSecurityOriginFromContext(ScriptExecutionContext& context) +// { +// Ref securityOrigin { *context.securityOrigin() }; +// Ref topOrigin { context.settingsValues().broadcastChannelOriginPartitioningEnabled ? context.topOrigin() : securityOrigin.get() }; +// return { WTFMove(topOrigin), WTFMove(securityOrigin) }; +// } + +class BroadcastChannel::MainThreadBridge : public ThreadSafeRefCounted { +public: + static Ref create(BroadcastChannel& channel, const String& name, ScriptExecutionContext& context) + { + return adoptRef(*new MainThreadBridge(channel, name, context)); + } + + void registerChannel(ScriptExecutionContext&); + void unregisterChannel(); + void postMessage(Ref&&); + + String name() const { return m_name.isolatedCopy(); } + BroadcastChannelIdentifier identifier() const { return m_identifier; } + ScriptExecutionContextIdentifier contextId() const { return m_contextId; } + +private: + MainThreadBridge(BroadcastChannel&, const String& name, ScriptExecutionContext&); + + void ensureOnMainThread(Function&&); + + // WeakPtr m_broadcastChannel; + WeakPtr m_broadcastChannel; + const BroadcastChannelIdentifier m_identifier; + const String m_name; // Main thread only. + ScriptExecutionContextIdentifier m_contextId; + // PartitionedSecurityOrigin m_origin; // Main thread only. +}; + +BroadcastChannel::MainThreadBridge::MainThreadBridge(BroadcastChannel& channel, const String& name, ScriptExecutionContext& context) + : m_broadcastChannel(channel) + , m_identifier(BroadcastChannelIdentifier::generate()) + , m_name(name.isolatedCopy()) + , m_contextId(context.identifier()) +// , m_origin(partitionedSecurityOriginFromContext(*channel.scriptExecutionContext()).isolatedCopy()) +{ +} + +void BroadcastChannel::MainThreadBridge::ensureOnMainThread(Function&& task) +{ + ASSERT(m_broadcastChannel); + if (!m_broadcastChannel) + return; + + auto* context = m_broadcastChannel->scriptExecutionContext(); + if (!context) + return; + ASSERT(context->isContextThread()); + + Ref protectedThis { *this }; + + ScriptExecutionContext::ensureOnMainThread([protectedThis = WTFMove(protectedThis), task = WTFMove(task)](auto& context) { + task(nullptr); + }); +} + +void BroadcastChannel::MainThreadBridge::registerChannel(ScriptExecutionContext& context) +{ + Ref protectedThis { *this }; + + ScriptExecutionContext::ensureOnMainThread([protectedThis = WTFMove(protectedThis), contextId = context.identifier()](auto& context) mutable { + context.broadcastChannelRegistry().registerChannel(protectedThis->m_name, protectedThis->m_identifier); + channelToContextIdentifier().add(protectedThis->m_identifier, contextId); + }); +} + +void BroadcastChannel::MainThreadBridge::unregisterChannel() +{ + Ref protectedThis { *this }; + + ScriptExecutionContext::ensureOnMainThread([protectedThis = WTFMove(protectedThis)](auto& context) { + context.broadcastChannelRegistry().unregisterChannel(protectedThis->m_name, protectedThis->m_identifier); + channelToContextIdentifier().remove(protectedThis->m_identifier); + }); +} + +void BroadcastChannel::MainThreadBridge::postMessage(Ref&& message) +{ + Ref protectedThis { *this }; + + ScriptExecutionContext::ensureOnMainThread([protectedThis = WTFMove(protectedThis), message = WTFMove(message)](auto& context) mutable { + context.broadcastChannelRegistry().postMessage(protectedThis->m_name, protectedThis->m_identifier, WTFMove(message)); + }); +} + +BroadcastChannel::BroadcastChannel(ScriptExecutionContext& context, const String& name) + // : ActiveDOMObject(&context) + : ContextDestructionObserver(&context) + , m_mainThreadBridge(MainThreadBridge::create(*this, name, context)) + , m_contextId(context.identifier()) +{ + { + Locker locker { allBroadcastChannelsLock }; + allBroadcastChannels().add(m_mainThreadBridge->identifier(), this); + } + m_mainThreadBridge->registerChannel(context); + jsRef(context.jsGlobalObject()); +} + +BroadcastChannel::~BroadcastChannel() +{ + close(); + { + Locker locker { allBroadcastChannelsLock }; + allBroadcastChannels().remove(m_mainThreadBridge->identifier()); + } +} + +BroadcastChannelIdentifier BroadcastChannel::identifier() const +{ + return m_mainThreadBridge->identifier(); +} + +String BroadcastChannel::name() const +{ + return m_mainThreadBridge->name(); +} + +ScriptExecutionContextIdentifier BroadcastChannel::contextIdForBroadcastChannelId(BroadcastChannelIdentifier identifier) +{ + Locker locker { channelToContextIdentifierLock }; + return channelToContextIdentifier().get(identifier); +} + +ScriptExecutionContext* BroadcastChannel::scriptExecutionContext() const +{ + return ScriptExecutionContext::getScriptExecutionContext(m_mainThreadBridge->contextId()); +} + +ExceptionOr BroadcastChannel::postMessage(JSC::JSGlobalObject& globalObject, JSC::JSValue message) +{ + if (!isEligibleForMessaging()) + return {}; + + if (m_isClosed) + return Exception { InvalidStateError, "This BroadcastChannel is closed"_s }; + + Vector> ports; + auto messageData = SerializedScriptValue::create(globalObject, message, {}, ports, SerializationForStorage::No, SerializationContext::WorkerPostMessage); + if (messageData.hasException()) + return messageData.releaseException(); + ASSERT(ports.isEmpty()); + + m_mainThreadBridge->postMessage(messageData.releaseReturnValue()); + return {}; +} + +void BroadcastChannel::close() +{ + if (m_isClosed) + return; + + m_isClosed = true; + m_mainThreadBridge->unregisterChannel(); +} + +void BroadcastChannel::dispatchMessageTo(BroadcastChannelIdentifier channelIdentifier, Ref&& message) +{ + ASSERT(isMainThread()); + + auto contextIdentifier = channelToContextIdentifier().get(channelIdentifier); + if (!contextIdentifier) + return; + + ScriptExecutionContext::ensureOnContextThread(contextIdentifier, [channelIdentifier, message = WTFMove(message)](auto&) mutable { + RefPtr channel; + { + Locker locker { allBroadcastChannelsLock }; + channel = allBroadcastChannels().get(channelIdentifier); + } + if (channel) + channel->dispatchMessage(WTFMove(message)); + }); +} + +void BroadcastChannel::dispatchMessage(Ref&& message) +{ + if (!isEligibleForMessaging()) + return; + + if (m_isClosed) + return; + + ScriptExecutionContext::postTaskTo(contextIdForBroadcastChannelId(m_mainThreadBridge->identifier()), [this, message = WTFMove(message)](ScriptExecutionContext& context) mutable { + if (m_isClosed) + return; + + auto* globalObject = context.jsGlobalObject(); + if (!globalObject) + return; + + auto& vm = globalObject->vm(); + auto scope = DECLARE_CATCH_SCOPE(vm); + Vector> dummyPorts; + auto event = MessageEvent::create(*globalObject, WTFMove(message), {}, {}, std::nullopt, WTFMove(dummyPorts)); + if (UNLIKELY(scope.exception())) { + // Currently, we assume that the only way we can get here is if we have a termination. + RELEASE_ASSERT(vm.hasPendingTerminationException()); + return; + } + + dispatchEvent(event.event); + }); +} + +// const char* BroadcastChannel::activeDOMObjectName() const +// { +// return "BroadcastChannel"; +// } + +void BroadcastChannel::eventListenersDidChange() +{ + m_hasRelevantEventListener = hasEventListeners(eventNames().messageEvent); +} + +// bool BroadcastChannel::virtualHasPendingActivity() const +// { +// return !m_isClosed && m_hasRelevantEventListener; +// } + +bool BroadcastChannel::hasPendingActivity() const +{ + return !m_isClosed && m_hasRelevantEventListener; +} + +// https://html.spec.whatwg.org/#eligible-for-messaging +bool BroadcastChannel::isEligibleForMessaging() const +{ + auto* context = scriptExecutionContext(); + if (!context) + return false; + + // if (auto document = dynamicDowncast(*context)) + // return document->isFullyActive(); + + return true; + // return !downcast(*context).isClosing(); +} + +void BroadcastChannel::jsRef(JSGlobalObject* lexicalGlobalObject) +{ + if (!m_hasRef) { + m_hasRef = true; + Bun__eventLoop__incrementRefConcurrently(WebCore::clientData(lexicalGlobalObject->vm())->bunVM, 1); + } +} + +void BroadcastChannel::jsUnref(JSGlobalObject* lexicalGlobalObject) +{ + if (m_hasRef) { + m_hasRef = false; + Bun__eventLoop__incrementRefConcurrently(WebCore::clientData(lexicalGlobalObject->vm())->bunVM, -1); + } +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/BroadcastChannel.h b/src/bun.js/bindings/webcore/BroadcastChannel.h new file mode 100644 index 00000000000000..764f3db93b72af --- /dev/null +++ b/src/bun.js/bindings/webcore/BroadcastChannel.h @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2021 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "ActiveDOMObject.h" +#include "ContextDestructionObserver.h" +#include "BroadcastChannelIdentifier.h" +// #include "ClientOrigin.h" +#include "EventTarget.h" +#include "ExceptionOr.h" +#include +#include + +namespace JSC { +class JSGlobalObject; +class JSValue; +} + +namespace WebCore { + +class SerializedScriptValue; + +class BroadcastChannel : public RefCounted, public EventTarget /*, public ActiveDOMObject*/, public ContextDestructionObserver { + WTF_MAKE_ISO_ALLOCATED(BroadcastChannel); + +public: + static Ref create(ScriptExecutionContext& context, const String& name) + { + auto channel = adoptRef(*new BroadcastChannel(context, name)); + // channel->suspendIfNeeded(); + return channel; + } + ~BroadcastChannel(); + + using RefCounted::ref; + using RefCounted::deref; + + BroadcastChannelIdentifier identifier() const; + String name() const; + + ExceptionOr postMessage(JSC::JSGlobalObject&, JSC::JSValue message); + void close(); + + WEBCORE_EXPORT static void dispatchMessageTo(BroadcastChannelIdentifier, Ref&&); + + static ScriptExecutionContextIdentifier contextIdForBroadcastChannelId(BroadcastChannelIdentifier); + + bool hasPendingActivity() const; + + void jsRef(JSGlobalObject*); + void jsUnref(JSGlobalObject*); + +private: + BroadcastChannel(ScriptExecutionContext&, const String& name); + + void dispatchMessage(Ref&&); + + bool isEligibleForMessaging() const; + + // EventTarget + EventTargetInterface eventTargetInterface() const final { return BroadcastChannelEventTargetInterfaceType; } + ScriptExecutionContext* scriptExecutionContext() const; + void refEventTarget() final { RefCounted::ref(); } + void derefEventTarget() final { RefCounted::deref(); } + void eventListenersDidChange() final; + + EventTargetData* eventTargetData() final { return &m_eventTargetData; } + EventTargetData* eventTargetDataConcurrently() final { return &m_eventTargetData; } + EventTargetData& ensureEventTargetData() final { return m_eventTargetData; } + + EventTargetData m_eventTargetData; + + // ActiveDOMObject + // const char* activeDOMObjectName() const final; + // bool virtualHasPendingActivity() const final; + // void stop() final { close(); } + + class MainThreadBridge; + Ref m_mainThreadBridge; + bool m_isClosed { false }; + bool m_hasRelevantEventListener { false }; + bool m_hasRef { false }; + ScriptExecutionContextIdentifier m_contextId; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/BroadcastChannelIdentifier.h b/src/bun.js/bindings/webcore/BroadcastChannelIdentifier.h new file mode 100644 index 00000000000000..acddb06d57cd76 --- /dev/null +++ b/src/bun.js/bindings/webcore/BroadcastChannelIdentifier.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2021 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include + +namespace WebCore { + +enum BroadcastChannelIdentifierType {}; +using BroadcastChannelIdentifier = AtomicObjectIdentifier; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/BroadcastChannelRegistry.h b/src/bun.js/bindings/webcore/BroadcastChannelRegistry.h new file mode 100644 index 00000000000000..70abf842ac9417 --- /dev/null +++ b/src/bun.js/bindings/webcore/BroadcastChannelRegistry.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2021 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "BroadcastChannelIdentifier.h" +#include +#include + +namespace WebCore { + +struct PartitionedSecurityOrigin; +class SerializedScriptValue; + +class BroadcastChannelRegistry : public RefCounted { +public: + virtual ~BroadcastChannelRegistry() {} + virtual void registerChannel(const String& name, BroadcastChannelIdentifier) = 0; + virtual void unregisterChannel(const String& name, BroadcastChannelIdentifier) = 0; + virtual void postMessage(const String& name, BroadcastChannelIdentifier source, Ref&&) = 0; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/BunBroadcastChannelRegistry.cpp b/src/bun.js/bindings/webcore/BunBroadcastChannelRegistry.cpp new file mode 100644 index 00000000000000..258d297170bded --- /dev/null +++ b/src/bun.js/bindings/webcore/BunBroadcastChannelRegistry.cpp @@ -0,0 +1,52 @@ +#include "config.h" + +#include "BunBroadcastChannelRegistry.h" +#include "webcore/BroadcastChannel.h" +#include "webcore/MessageWithMessagePorts.h" +#include + +namespace WebCore { + +void BunBroadcastChannelRegistry::registerChannel(const String& name, BroadcastChannelIdentifier identifier) +{ + auto& channels = m_channelsForName.ensure(name, [] { return Vector {}; }).iterator->value; + channels.append(identifier); +} + +void BunBroadcastChannelRegistry::unregisterChannel(const String& name, BroadcastChannelIdentifier identifier) +{ + auto channels = m_channelsForName.find(name); + if (channels == m_channelsForName.end()) + return; + + auto& channelIds = channels->value; + channelIds.removeFirst(identifier); +} + +void BunBroadcastChannelRegistry::postMessage(const String& name, BroadcastChannelIdentifier source, Ref&& message) +{ + postMessageLocally(name, source, message.copyRef()); +} + +void BunBroadcastChannelRegistry::postMessageLocally(const String& name, BroadcastChannelIdentifier sourceInProcess, Ref&& message) +{ + auto channels = m_channelsForName.find(name); + if (channels == m_channelsForName.end()) + return; + + auto& channelIds = channels->value; + for (auto& channelId : channelIds) { + if (channelId == sourceInProcess) + continue; + + BroadcastChannel::dispatchMessageTo(channelId, message.copyRef()); + } +} + +void BunBroadcastChannelRegistry::postMessageToRemote(const String& name, MessageWithMessagePorts&& message) +{ + // auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler)); + // PartitionedSecurityOrigin origin { clientOrigin.topOrigin.securityOrigin(), clientOrigin.clientOrigin.securityOrigin() }; + // postMessageLocally(origin, name, std::nullopt, *message.message, callbackAggregator.copyRef()); +} +} diff --git a/src/bun.js/bindings/webcore/BunBroadcastChannelRegistry.h b/src/bun.js/bindings/webcore/BunBroadcastChannelRegistry.h new file mode 100644 index 00000000000000..5576b732e5c89a --- /dev/null +++ b/src/bun.js/bindings/webcore/BunBroadcastChannelRegistry.h @@ -0,0 +1,33 @@ +#pragma once + +#include "BroadcastChannelRegistry.h" +#include "wtf/CallbackAggregator.h" +#include "wtf/Vector.h" +#include "wtf/HashMap.h" + +namespace WebCore { + +struct MessageWithMessagePorts; + +class BunBroadcastChannelRegistry final : public BroadcastChannelRegistry { +public: + BunBroadcastChannelRegistry() = default; + static Ref create() + { + return adoptRef(*new BunBroadcastChannelRegistry); + } + + void registerChannel(const String& name, BroadcastChannelIdentifier) final; + void unregisterChannel(const String& name, BroadcastChannelIdentifier) final; + void postMessage(const String& name, BroadcastChannelIdentifier source, Ref&&) final; + + // void didReceivedMessage(IPC::Connection&, IPC::Decoder&); + + HashMap> m_channelsForName; + +private: + void postMessageToRemote(const String& name, MessageWithMessagePorts&&); + void postMessageLocally(const String& name, BroadcastChannelIdentifier sourceInProgress, Ref&&); +}; + +} diff --git a/src/bun.js/bindings/webcore/ContextDestructionObserver.cpp b/src/bun.js/bindings/webcore/ContextDestructionObserver.cpp new file mode 100644 index 00000000000000..72e6a85c497529 --- /dev/null +++ b/src/bun.js/bindings/webcore/ContextDestructionObserver.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "config.h" +#include "ContextDestructionObserver.h" + +#include "ScriptExecutionContext.h" + +namespace WebCore { + +ContextDestructionObserver::ContextDestructionObserver(ScriptExecutionContext* scriptExecutionContext) + : m_context(nullptr) +{ + observeContext(scriptExecutionContext); +} + +ContextDestructionObserver::~ContextDestructionObserver() +{ + observeContext(nullptr); +} + +void ContextDestructionObserver::observeContext(ScriptExecutionContext* scriptExecutionContext) +{ + if (m_context) { + ASSERT(m_context->isContextThread()); + m_context->willDestroyDestructionObserver(*this); + } + + m_context = scriptExecutionContext; + + if (m_context) { + ASSERT(m_context->isContextThread()); + m_context->didCreateDestructionObserver(*this); + } +} + +void ContextDestructionObserver::contextDestroyed() +{ + m_context = nullptr; +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/ContextDestructionObserver.h b/src/bun.js/bindings/webcore/ContextDestructionObserver.h index ccf20f301e2e8d..7408b5f2728680 100644 --- a/src/bun.js/bindings/webcore/ContextDestructionObserver.h +++ b/src/bun.js/bindings/webcore/ContextDestructionObserver.h @@ -4,29 +4,23 @@ #include "root.h" -#include "ScriptExecutionContext.h" - namespace WebCore { -// TODO: +class ScriptExecutionContext; + class ContextDestructionObserver { public: - WEBCORE_EXPORT void contextDestroyed() {} + WEBCORE_EXPORT virtual void contextDestroyed(); ScriptExecutionContext* scriptExecutionContext() const { return m_context; } - ContextDestructionObserver(ScriptExecutionContext* context) - : m_context(context) - { - } - ContextDestructionObserver(ContextDestructionObserver& context) - : m_context(context.m_context) - { - } +protected: + WEBCORE_EXPORT ContextDestructionObserver(ScriptExecutionContext*); + WEBCORE_EXPORT virtual ~ContextDestructionObserver(); + void observeContext(ScriptExecutionContext*); private: - int m_junk = 0; ScriptExecutionContext* m_context; }; diff --git a/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h b/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h index 740c6d9a9e6ec4..a81b845772cd46 100644 --- a/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h +++ b/src/bun.js/bindings/webcore/DOMClientIsoSubspaces.h @@ -40,6 +40,7 @@ class DOMClientIsoSubspaces { std::unique_ptr m_clientSubspaceForAsyncContextFrame; std::unique_ptr m_clientSubspaceForMockWithImplementationCleanupData; std::unique_ptr m_clientSubspaceForProcessObject; + std::unique_ptr m_clientSubspaceForInternalModuleRegistry; #include "ZigGeneratedClasses+DOMClientIsoSubspaces.h" /* --- bun --- */ @@ -410,7 +411,7 @@ class DOMClientIsoSubspaces { // std::unique_ptr m_clientSubspaceForAnimationEvent; // std::unique_ptr m_clientSubspaceForAttr; // std::unique_ptr m_clientSubspaceForBeforeUnloadEvent; - // std::unique_ptr m_clientSubspaceForBroadcastChannel; + std::unique_ptr m_clientSubspaceForBroadcastChannel; // std::unique_ptr m_clientSubspaceForCDATASection; // std::unique_ptr m_clientSubspaceForCharacterData; // std::unique_ptr m_clientSubspaceForClipboardEvent; @@ -443,9 +444,9 @@ class DOMClientIsoSubspaces { // std::unique_ptr m_clientSubspaceForIdleDeadline; // std::unique_ptr m_clientSubspaceForInputEvent; // std::unique_ptr m_clientSubspaceForKeyboardEvent; - // std::unique_ptr m_clientSubspaceForMessageChannel; + std::unique_ptr m_clientSubspaceForMessageChannel; std::unique_ptr m_clientSubspaceForMessageEvent; - // std::unique_ptr m_clientSubspaceForMessagePort; + std::unique_ptr m_clientSubspaceForMessagePort; // std::unique_ptr m_clientSubspaceForMouseEvent; // std::unique_ptr m_clientSubspaceForMutationEvent; // std::unique_ptr m_clientSubspaceForMutationObserver; diff --git a/src/bun.js/bindings/webcore/DOMIsoSubspaces.h b/src/bun.js/bindings/webcore/DOMIsoSubspaces.h index 52be5872aba30d..c67112388c9030 100644 --- a/src/bun.js/bindings/webcore/DOMIsoSubspaces.h +++ b/src/bun.js/bindings/webcore/DOMIsoSubspaces.h @@ -40,6 +40,7 @@ class DOMIsoSubspaces { std::unique_ptr m_subspaceForAsyncContextFrame; std::unique_ptr m_subspaceForMockWithImplementationCleanupData; std::unique_ptr m_subspaceForProcessObject; + std::unique_ptr m_subspaceForInternalModuleRegistry; #include "ZigGeneratedClasses+DOMIsoSubspaces.h" /*-- BUN --*/ @@ -401,7 +402,7 @@ class DOMIsoSubspaces { // std::unique_ptr m_subspaceForAnimationEvent; // std::unique_ptr m_subspaceForAttr; // std::unique_ptr m_subspaceForBeforeUnloadEvent; - // std::unique_ptr m_subspaceForBroadcastChannel; + std::unique_ptr m_subspaceForBroadcastChannel; // std::unique_ptr m_subspaceForCDATASection; // std::unique_ptr m_subspaceForCharacterData; // std::unique_ptr m_subspaceForClipboardEvent; @@ -409,7 +410,6 @@ class DOMIsoSubspaces { // std::unique_ptr m_subspaceForCompositionEvent; // std::unique_ptr m_subspaceForCustomElementRegistry; std::unique_ptr m_subspaceForCustomEvent; - // std::unique_ptr m_subspaceForDOMException; // std::unique_ptr m_subspaceForDOMImplementation; // std::unique_ptr m_subspaceForDOMPoint; // std::unique_ptr m_subspaceForDOMPointReadOnly; @@ -436,9 +436,9 @@ class DOMIsoSubspaces { // std::unique_ptr m_subspaceForIdleDeadline; // std::unique_ptr m_subspaceForInputEvent; // std::unique_ptr m_subspaceForKeyboardEvent; - // std::unique_ptr m_subspaceForMessageChannel; + std::unique_ptr m_subspaceForMessageChannel; std::unique_ptr m_subspaceForMessageEvent; - // std::unique_ptr m_subspaceForMessagePort; + std::unique_ptr m_subspaceForMessagePort; // std::unique_ptr m_subspaceForMouseEvent; // std::unique_ptr m_subspaceForMutationEvent; // std::unique_ptr m_subspaceForMutationObserver; diff --git a/src/bun.js/bindings/webcore/EventListenerMap.cpp b/src/bun.js/bindings/webcore/EventListenerMap.cpp index 5014cfa00dde6f..540f498e0084bc 100644 --- a/src/bun.js/bindings/webcore/EventListenerMap.cpp +++ b/src/bun.js/bindings/webcore/EventListenerMap.cpp @@ -41,7 +41,6 @@ #include #include - namespace WebCore { EventListenerMap::EventListenerMap() = default; @@ -168,7 +167,7 @@ EventListenerVector* EventListenerMap::find(const AtomString& eventType) static void removeFirstListenerCreatedFromMarkup(EventListenerVector& listenerVector) { - bool foundListener = listenerVector.removeFirstMatching([] (const auto& registeredListener) { + bool foundListener = listenerVector.removeFirstMatching([](const auto& registeredListener) { if (JSEventListener::wasCreatedFromMarkup(registeredListener->callback())) { registeredListener->markAsRemoved(); return true; diff --git a/src/bun.js/bindings/webcore/EventListenerMap.h b/src/bun.js/bindings/webcore/EventListenerMap.h index 572f999f9e2416..690afd133cc339 100644 --- a/src/bun.js/bindings/webcore/EventListenerMap.h +++ b/src/bun.js/bindings/webcore/EventListenerMap.h @@ -65,7 +65,7 @@ class EventListenerMap { void removeFirstEventListenerCreatedFromMarkup(const AtomString& eventType); void copyEventListenersNotCreatedFromMarkupToTarget(EventTarget*); - + template void visitJSEventListeners(Visitor&); Lock& lock() { return m_lock; } diff --git a/src/bun.js/bindings/webcore/EventTargetFactory.cpp b/src/bun.js/bindings/webcore/EventTargetFactory.cpp index 97e66977be6e81..809cceda922574 100644 --- a/src/bun.js/bindings/webcore/EventTargetFactory.cpp +++ b/src/bun.js/bindings/webcore/EventTargetFactory.cpp @@ -57,8 +57,8 @@ JSC::JSValue toJS(JSC::JSGlobalObject* state, JSDOMGlobalObject* globalObject, E // case BaseAudioContextEventTargetInterfaceType: // return toJS(state, globalObject, static_cast(impl)); // #endif - // case BroadcastChannelEventTargetInterfaceType: - // return toJS(state, globalObject, static_cast(impl)); + case BroadcastChannelEventTargetInterfaceType: + return toJS(state, globalObject, static_cast(impl)); // case ClipboardEventTargetInterfaceType: // return toJS(state, globalObject, static_cast(impl)); // case DOMApplicationCacheEventTargetInterfaceType: @@ -117,8 +117,8 @@ JSC::JSValue toJS(JSC::JSGlobalObject* state, JSDOMGlobalObject* globalObject, E // case MediaStreamTrackEventTargetInterfaceType: // return toJS(state, globalObject, static_cast(impl)); // #endif - // case MessagePortEventTargetInterfaceType: - // return toJS(state, globalObject, static_cast(impl)); + case MessagePortEventTargetInterfaceType: + return toJS(state, globalObject, static_cast(impl)); // case NodeEventTargetInterfaceType: // return toJS(state, globalObject, static_cast(impl)); // #if ENABLE(NOTIFICATIONS) diff --git a/src/bun.js/bindings/webcore/EventTargetHeaders.h b/src/bun.js/bindings/webcore/EventTargetHeaders.h index b36e49a66dce04..6c81e59fd0142a 100644 --- a/src/bun.js/bindings/webcore/EventTargetHeaders.h +++ b/src/bun.js/bindings/webcore/EventTargetHeaders.h @@ -46,7 +46,7 @@ // #include "BaseAudioContext.h" // #include "JSBaseAudioContext.h" // #endif -// #include "BroadcastChannel.h" +#include "BroadcastChannel.h" // #include "Clipboard.h" // #include "DOMApplicationCache.h" // #include "DOMWindow.h" @@ -59,7 +59,7 @@ // #include "IDBOpenDBRequest.h" // #include "IDBRequest.h" // #include "IDBTransaction.h" -// #include "JSBroadcastChannel.h" +#include "JSBroadcastChannel.h" // #include "JSClipboard.h" // #include "JSDOMApplicationCache.h" // #include "JSDOMWindow.h" @@ -106,8 +106,8 @@ // #include "JSMediaStreamTrack.h" // #include "MediaStreamTrack.h" // #endif -// #include "MessagePort.h" -// #include "JSMessagePort.h" +#include "MessagePort.h" +#include "JSMessagePort.h" // #include "JSNode.h" #include "Node.h" // #if ENABLE(NOTIFICATIONS) diff --git a/src/bun.js/bindings/webcore/FetchHeaders.cpp b/src/bun.js/bindings/webcore/FetchHeaders.cpp index 02a3c8b3a6251f..f54214733c0b5c 100644 --- a/src/bun.js/bindings/webcore/FetchHeaders.cpp +++ b/src/bun.js/bindings/webcore/FetchHeaders.cpp @@ -28,6 +28,7 @@ #include "config.h" #include "FetchHeaders.h" +#include "HTTPHeaderNames.h" #include "HTTPParsers.h" @@ -261,30 +262,48 @@ void FetchHeaders::filterAndFill(const HTTPHeaderMap& headers, Guard guard) } } -static NeverDestroyed setCookieLowercaseString(MAKE_STATIC_STRING_IMPL("set-cookie")); - std::optional> FetchHeaders::Iterator::next() { if (m_keys.isEmpty() || m_updateCounter != m_headers->m_updateCounter) { + bool hasSetCookie = !m_headers->getSetCookieHeaders().isEmpty(); m_keys.resize(0); - m_keys.reserveCapacity(m_headers->m_headers.size()); + m_keys.reserveCapacity(m_headers->m_headers.size() + (hasSetCookie ? 1 : 0)); for (auto& header : m_headers->m_headers) m_keys.uncheckedAppend(header.asciiLowerCaseName()); std::sort(m_keys.begin(), m_keys.end(), WTF::codePointCompareLessThan); + if (hasSetCookie) + m_keys.uncheckedAppend(String()); + + m_currentIndex += m_cookieIndex; + if (hasSetCookie) { + size_t setCookieKeyIndex = m_keys.size() - 1; + if (m_currentIndex < setCookieKeyIndex) + m_cookieIndex = 0; + else { + m_cookieIndex = std::min(m_currentIndex - setCookieKeyIndex, m_headers->getSetCookieHeaders().size()); + m_currentIndex -= m_cookieIndex; + } + } else + m_cookieIndex = 0; + m_updateCounter = m_headers->m_updateCounter; - m_cookieIndex = 0; } auto& setCookieHeaders = m_headers->m_headers.getSetCookieHeaders(); while (m_currentIndex < m_keys.size()) { - auto key = m_keys[m_currentIndex++]; + auto key = m_keys[m_currentIndex]; - if (!setCookieHeaders.isEmpty() && key == setCookieLowercaseString) { - auto cookie = setCookieHeaders[m_cookieIndex++]; - return KeyValuePair { WTFMove(key), WTFMove(cookie) }; + if (key.isNull()) { + if (m_cookieIndex < setCookieHeaders.size()) { + String value = setCookieHeaders[m_cookieIndex++]; + return KeyValuePair { WTF::staticHeaderNames[static_cast(HTTPHeaderName::SetCookie)], WTFMove(value) }; + } + m_currentIndex++; + continue; } + m_currentIndex++; auto value = m_headers->m_headers.get(key); if (!value.isNull()) return KeyValuePair { WTFMove(key), WTFMove(value) }; diff --git a/src/bun.js/bindings/webcore/HTTPHeaderMap.cpp b/src/bun.js/bindings/webcore/HTTPHeaderMap.cpp index 013aad750441fd..99fc9cf13e5e14 100644 --- a/src/bun.js/bindings/webcore/HTTPHeaderMap.cpp +++ b/src/bun.js/bindings/webcore/HTTPHeaderMap.cpp @@ -236,15 +236,7 @@ String HTTPHeaderMap::get(HTTPHeaderName name) const void HTTPHeaderMap::set(HTTPHeaderName name, const String& value) { if (name == HTTPHeaderName::SetCookie) { - auto cookieName = extractCookieName(value); - size_t length = m_setCookieHeaders.size(); - const auto& cookies = m_setCookieHeaders.data(); - for (size_t i = 0; i < length; ++i) { - if (extractCookieName(cookies[i]) == cookieName) { - m_setCookieHeaders[i] = value; - return; - } - } + m_setCookieHeaders.clear(); m_setCookieHeaders.append(value); return; } diff --git a/src/bun.js/bindings/webcore/HTTPHeaderMap.h b/src/bun.js/bindings/webcore/HTTPHeaderMap.h index 13fc806cb5e194..42fdbf41a6a764 100644 --- a/src/bun.js/bindings/webcore/HTTPHeaderMap.h +++ b/src/bun.js/bindings/webcore/HTTPHeaderMap.h @@ -69,12 +69,9 @@ class HTTPHeaderMap { : m_table(table) , m_commonHeadersIt(commonHeadersIt) , m_uncommonHeadersIt(uncommonHeadersIt) - , m_setCookiesIter(setCookiesIter) { if (!updateKeyValue(m_commonHeadersIt)) { - if (!updateSetCookieHeaderPosition(setCookiesIter)) { - updateKeyValue(m_uncommonHeadersIt); - } + updateKeyValue(m_uncommonHeadersIt); } } @@ -107,9 +104,6 @@ class HTTPHeaderMap { if (m_commonHeadersIt != m_table.m_commonHeaders.end()) { if (updateKeyValue(++m_commonHeadersIt)) return *this; - } else if (m_setCookiesIter != m_table.m_setCookieHeaders.end()) { - if (updateSetCookieHeaderPosition(++m_setCookiesIter)) - return *this; } else { ++m_uncommonHeadersIt; } @@ -122,7 +116,7 @@ class HTTPHeaderMap { bool operator!=(const HTTPHeaderMapConstIterator &other) const { return !(*this == other); } bool operator==(const HTTPHeaderMapConstIterator &other) const { - return m_commonHeadersIt == other.m_commonHeadersIt && m_uncommonHeadersIt == other.m_uncommonHeadersIt && m_setCookiesIter == other.m_setCookiesIter; + return m_commonHeadersIt == other.m_commonHeadersIt && m_uncommonHeadersIt == other.m_uncommonHeadersIt; } private: @@ -145,22 +139,9 @@ class HTTPHeaderMap { return true; } - bool updateSetCookieHeaderPosition(Vector::const_iterator cookieI) - { - if (cookieI == m_table.m_setCookieHeaders.end()) { - return false; - } - - m_keyValue.key = httpHeaderNameString(HTTPHeaderName::SetCookie).toStringWithoutCopying(); - m_keyValue.keyAsHTTPHeaderName = HTTPHeaderName::SetCookie; - m_keyValue.value = *cookieI; - return true; - } - const HTTPHeaderMap &m_table; CommonHeadersVector::const_iterator m_commonHeadersIt; UncommonHeadersVector::const_iterator m_uncommonHeadersIt; - Vector::const_iterator m_setCookiesIter; KeyValue m_keyValue; }; typedef HTTPHeaderMapConstIterator const_iterator; @@ -178,14 +159,12 @@ class HTTPHeaderMap { { m_commonHeaders.clear(); m_uncommonHeaders.clear(); - m_setCookieHeaders.clear(); } void shrinkToFit() { m_commonHeaders.shrinkToFit(); m_uncommonHeaders.shrinkToFit(); - m_setCookieHeaders.shrinkToFit(); } WEBCORE_EXPORT String get(const String &name) const; diff --git a/src/bun.js/bindings/webcore/HTTPParsers.cpp b/src/bun.js/bindings/webcore/HTTPParsers.cpp index f2c4ff989c70d9..66aec49254fdac 100644 --- a/src/bun.js/bindings/webcore/HTTPParsers.cpp +++ b/src/bun.js/bindings/webcore/HTTPParsers.cpp @@ -543,7 +543,7 @@ XSSProtectionDisposition parseXSSProtectionHeader(const String& header, String& ContentTypeOptionsDisposition parseContentTypeOptionsHeader(StringView header) { StringView leftToken = header.left(header.find(',')); - if (equalLettersIgnoringASCIICase(leftToken.trim(isJSONOrHTTPWhitespace), "nosniff"_s)) + if (equalLettersIgnoringASCIICase(leftToken.trim(isASCIIWhitespaceWithoutFF), "nosniff"_s)) return ContentTypeOptionsDisposition::Nosniff; return ContentTypeOptionsDisposition::None; } @@ -602,7 +602,7 @@ XFrameOptionsDisposition parseXFrameOptionsHeader(StringView header) // return result; // for (auto value : StringView(headerValue).split(',')) { -// auto trimmedValue = value.trim(isJSONOrHTTPWhitespace); +// auto trimmedValue = value.trim(isASCIIWhitespaceWithoutFF); // if (trimmedValue == "\"cache\""_s) // result.add(ClearSiteDataValue::Cache); // else if (trimmedValue == "\"cookies\""_s) @@ -632,7 +632,7 @@ bool parseRange(StringView range, RangeAllowWhitespace allowWhitespace, long lon if (!startsWithLettersIgnoringASCIICase(range, "bytes"_s)) return false; - auto byteRange = range.substring(bytesLength).trim(isJSONOrHTTPWhitespace); + auto byteRange = range.substring(bytesLength).trim(isASCIIWhitespaceWithoutFF); if (!byteRange.startsWith('=')) return false; @@ -962,7 +962,7 @@ bool isSafeMethod(const String& method) CrossOriginResourcePolicy parseCrossOriginResourcePolicyHeader(StringView header) { - auto trimmedHeader = header.trim(isJSONOrHTTPWhitespace); + auto trimmedHeader = header.trim(isASCIIWhitespaceWithoutFF); if (trimmedHeader.isEmpty()) return CrossOriginResourcePolicy::None; diff --git a/src/bun.js/bindings/webcore/JSBroadcastChannel.cpp b/src/bun.js/bindings/webcore/JSBroadcastChannel.cpp new file mode 100644 index 00000000000000..694044ccaf8a8d --- /dev/null +++ b/src/bun.js/bindings/webcore/JSBroadcastChannel.cpp @@ -0,0 +1,426 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "JSBroadcastChannel.h" + +#include "ActiveDOMObject.h" +#include "EventNames.h" +#include "ExtendedDOMClientIsoSubspaces.h" +#include "ExtendedDOMIsoSubspaces.h" +#include "IDLTypes.h" +#include "JSDOMAttribute.h" +#include "JSDOMBinding.h" +#include "JSDOMConstructor.h" +#include "JSDOMConvertAny.h" +#include "JSDOMConvertBase.h" +#include "JSDOMConvertInterface.h" +#include "JSDOMConvertStrings.h" +#include "JSDOMExceptionHandling.h" +#include "JSDOMGlobalObjectInlines.h" +#include "JSDOMOperation.h" +#include "JSDOMWrapperCache.h" +#include "JSEventListener.h" +#include "ScriptExecutionContext.h" +#include "WebCoreJSClientData.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WebCore { +using namespace JSC; + +// Functions + +static JSC_DECLARE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_postMessage); +static JSC_DECLARE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_close); +static JSC_DECLARE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_ref); +static JSC_DECLARE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_unref); + +// Attributes + +static JSC_DECLARE_CUSTOM_GETTER(jsBroadcastChannelConstructor); +static JSC_DECLARE_CUSTOM_GETTER(jsBroadcastChannel_name); +static JSC_DECLARE_CUSTOM_GETTER(jsBroadcastChannel_onmessage); +static JSC_DECLARE_CUSTOM_SETTER(setJSBroadcastChannel_onmessage); +static JSC_DECLARE_CUSTOM_GETTER(jsBroadcastChannel_onmessageerror); +static JSC_DECLARE_CUSTOM_SETTER(setJSBroadcastChannel_onmessageerror); + +class JSBroadcastChannelPrototype final : public JSC::JSNonFinalObject { +public: + using Base = JSC::JSNonFinalObject; + static JSBroadcastChannelPrototype* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) + { + JSBroadcastChannelPrototype* ptr = new (NotNull, JSC::allocateCell(vm)) JSBroadcastChannelPrototype(vm, globalObject, structure); + ptr->finishCreation(vm); + return ptr; + } + + DECLARE_INFO; + template + static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSBroadcastChannelPrototype, Base); + return &vm.plainObjectSpace(); + } + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); + } + +private: + JSBroadcastChannelPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) + : JSC::JSNonFinalObject(vm, structure) + { + } + + void finishCreation(JSC::VM&); +}; +STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSBroadcastChannelPrototype, JSBroadcastChannelPrototype::Base); + +using JSBroadcastChannelDOMConstructor = JSDOMConstructor; + +template<> EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSBroadcastChannelDOMConstructor::construct(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame) +{ + VM& vm = lexicalGlobalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* castedThis = jsCast(callFrame->jsCallee()); + ASSERT(castedThis); + if (UNLIKELY(callFrame->argumentCount() < 1)) + return throwVMError(lexicalGlobalObject, throwScope, createNotEnoughArgumentsError(lexicalGlobalObject)); + auto* context = castedThis->scriptExecutionContext(); + if (UNLIKELY(!context)) + return throwConstructorScriptExecutionContextUnavailableError(*lexicalGlobalObject, throwScope, "BroadcastChannel"); + EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); + auto name = convert(*lexicalGlobalObject, argument0.value()); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + auto object = BroadcastChannel::create(*context, WTFMove(name)); + if constexpr (IsExceptionOr) + RETURN_IF_EXCEPTION(throwScope, {}); + static_assert(TypeOrExceptionOrUnderlyingType::isRef); + auto jsValue = toJSNewlyCreated>(*lexicalGlobalObject, *castedThis->globalObject(), throwScope, WTFMove(object)); + if constexpr (IsExceptionOr) + RETURN_IF_EXCEPTION(throwScope, {}); + setSubclassStructureIfNeeded(lexicalGlobalObject, callFrame, asObject(jsValue)); + RETURN_IF_EXCEPTION(throwScope, {}); + return JSValue::encode(jsValue); +} +JSC_ANNOTATE_HOST_FUNCTION(JSBroadcastChannelDOMConstructorConstruct, JSBroadcastChannelDOMConstructor::construct); + +template<> const ClassInfo JSBroadcastChannelDOMConstructor::s_info = { "BroadcastChannel"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSBroadcastChannelDOMConstructor) }; + +template<> JSValue JSBroadcastChannelDOMConstructor::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject) +{ + return JSEventTarget::getConstructor(vm, &globalObject); +} + +template<> void JSBroadcastChannelDOMConstructor::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject) +{ + putDirect(vm, vm.propertyNames->length, jsNumber(1), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + JSString* nameString = jsNontrivialString(vm, "BroadcastChannel"_s); + m_originalName.set(vm, this, nameString); + putDirect(vm, vm.propertyNames->name, nameString, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + putDirect(vm, vm.propertyNames->prototype, JSBroadcastChannel::prototype(vm, globalObject), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete); +} + +/* Hash table for prototype */ + +static const HashTableValue JSBroadcastChannelPrototypeTableValues[] = { + { "constructor"_s, static_cast(PropertyAttribute::DontEnum), NoIntrinsic, { HashTableValue::GetterSetterType, jsBroadcastChannelConstructor, 0 } }, + { "name"_s, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsBroadcastChannel_name, 0 } }, + { "onmessage"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsBroadcastChannel_onmessage, setJSBroadcastChannel_onmessage } }, + { "onmessageerror"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsBroadcastChannel_onmessageerror, setJSBroadcastChannel_onmessageerror } }, + { "postMessage"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsBroadcastChannelPrototypeFunction_postMessage, 1 } }, + { "close"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsBroadcastChannelPrototypeFunction_close, 0 } }, + { "ref"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsBroadcastChannelPrototypeFunction_ref, 0 } }, + { "unref"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsBroadcastChannelPrototypeFunction_unref, 0 } }, +}; + +const ClassInfo JSBroadcastChannelPrototype::s_info = { "BroadcastChannel"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSBroadcastChannelPrototype) }; + +void JSBroadcastChannelPrototype::finishCreation(VM& vm) +{ + Base::finishCreation(vm); + reifyStaticProperties(vm, JSBroadcastChannel::info(), JSBroadcastChannelPrototypeTableValues, *this); + JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); +} + +const ClassInfo JSBroadcastChannel::s_info = { "BroadcastChannel"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSBroadcastChannel) }; + +JSBroadcastChannel::JSBroadcastChannel(Structure* structure, JSDOMGlobalObject& globalObject, Ref&& impl) + : JSEventTarget(structure, globalObject, WTFMove(impl)) +{ +} + +// static_assert(std::is_base_of::value, "Interface is marked as [ActiveDOMObject] but implementation class does not subclass ActiveDOMObject."); + +JSObject* JSBroadcastChannel::createPrototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + auto* structure = JSBroadcastChannelPrototype::createStructure(vm, &globalObject, JSEventTarget::prototype(vm, globalObject)); + structure->setMayBePrototype(true); + return JSBroadcastChannelPrototype::create(vm, &globalObject, structure); +} + +JSObject* JSBroadcastChannel::prototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + return getDOMPrototype(vm, globalObject); +} + +JSValue JSBroadcastChannel::getConstructor(VM& vm, const JSGlobalObject* globalObject) +{ + return getDOMConstructor(vm, *jsCast(globalObject)); +} + +JSC_DEFINE_CUSTOM_GETTER(jsBroadcastChannelConstructor, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* prototype = jsDynamicCast(JSValue::decode(thisValue)); + if (UNLIKELY(!prototype)) + return throwVMTypeError(lexicalGlobalObject, throwScope); + return JSValue::encode(JSBroadcastChannel::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); +} + +static inline JSValue jsBroadcastChannel_nameGetter(JSGlobalObject& lexicalGlobalObject, JSBroadcastChannel& thisObject) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto& impl = thisObject.wrapped(); + RELEASE_AND_RETURN(throwScope, (toJS(lexicalGlobalObject, throwScope, impl.name()))); +} + +JSC_DEFINE_CUSTOM_GETTER(jsBroadcastChannel_name, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +static inline JSValue jsBroadcastChannel_onmessageGetter(JSGlobalObject& lexicalGlobalObject, JSBroadcastChannel& thisObject) +{ + UNUSED_PARAM(lexicalGlobalObject); + return eventHandlerAttribute(thisObject.wrapped(), eventNames().messageEvent, worldForDOMObject(thisObject)); +} + +JSC_DEFINE_CUSTOM_GETTER(jsBroadcastChannel_onmessage, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +static inline bool setJSBroadcastChannel_onmessageSetter(JSGlobalObject& lexicalGlobalObject, JSBroadcastChannel& thisObject, JSValue value) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + UNUSED_PARAM(vm); + setEventHandlerAttribute(thisObject.wrapped(), eventNames().messageEvent, value, thisObject); + vm.writeBarrier(&thisObject, value); + ensureStillAliveHere(value); + + return true; +} + +JSC_DEFINE_CUSTOM_SETTER(setJSBroadcastChannel_onmessage, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue, PropertyName attributeName)) +{ + return IDLAttribute::set(*lexicalGlobalObject, thisValue, encodedValue, attributeName); +} + +static inline JSValue jsBroadcastChannel_onmessageerrorGetter(JSGlobalObject& lexicalGlobalObject, JSBroadcastChannel& thisObject) +{ + UNUSED_PARAM(lexicalGlobalObject); + return eventHandlerAttribute(thisObject.wrapped(), eventNames().messageerrorEvent, worldForDOMObject(thisObject)); +} + +JSC_DEFINE_CUSTOM_GETTER(jsBroadcastChannel_onmessageerror, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +static inline bool setJSBroadcastChannel_onmessageerrorSetter(JSGlobalObject& lexicalGlobalObject, JSBroadcastChannel& thisObject, JSValue value) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + UNUSED_PARAM(vm); + setEventHandlerAttribute(thisObject.wrapped(), eventNames().messageerrorEvent, value, thisObject); + vm.writeBarrier(&thisObject, value); + ensureStillAliveHere(value); + + return true; +} + +JSC_DEFINE_CUSTOM_SETTER(setJSBroadcastChannel_onmessageerror, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue, PropertyName attributeName)) +{ + return IDLAttribute::set(*lexicalGlobalObject, thisValue, encodedValue, attributeName); +} + +static inline JSC::EncodedJSValue jsBroadcastChannelPrototypeFunction_postMessageBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + if (UNLIKELY(callFrame->argumentCount() < 1)) + return throwVMError(lexicalGlobalObject, throwScope, createNotEnoughArgumentsError(lexicalGlobalObject)); + EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); + auto message = convert(*lexicalGlobalObject, argument0.value()); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.postMessage(*jsCast(lexicalGlobalObject), WTFMove(message)); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_postMessage, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "postMessage"); +} + +static inline JSC::EncodedJSValue jsBroadcastChannelPrototypeFunction_closeBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + impl.jsUnref(lexicalGlobalObject); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.close(); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_close, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "close"); +} + +static inline JSC::EncodedJSValue jsBroadcastChannelPrototypeFunction_refBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.jsRef(lexicalGlobalObject); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_ref, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "ref"); +} + +static inline JSC::EncodedJSValue jsBroadcastChannelPrototypeFunction_unrefBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.jsUnref(lexicalGlobalObject); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsBroadcastChannelPrototypeFunction_unref, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "unref"); +} + +JSC::GCClient::IsoSubspace* JSBroadcastChannel::subspaceForImpl(JSC::VM& vm) +{ + return WebCore::subspaceForImpl( + vm, + [](auto& spaces) { return spaces.m_clientSubspaceForBroadcastChannel.get(); }, + [](auto& spaces, auto&& space) { spaces.m_clientSubspaceForBroadcastChannel = std::forward(space); }, + [](auto& spaces) { return spaces.m_subspaceForBroadcastChannel.get(); }, + [](auto& spaces, auto&& space) { spaces.m_subspaceForBroadcastChannel = std::forward(space); }); +} + +void JSBroadcastChannel::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) +{ + auto* thisObject = jsCast(cell); + analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); + if (thisObject->scriptExecutionContext()) + analyzer.setLabelForCell(cell, "url "_s + thisObject->scriptExecutionContext()->url().string()); + Base::analyzeHeap(cell, analyzer); +} + +bool JSBroadcastChannelOwner::isReachableFromOpaqueRoots(JSC::Handle handle, void*, AbstractSlotVisitor& visitor, const char** reason) +{ + auto* jsBroadcastChannel = jsCast(handle.slot()->asCell()); + auto& wrapped = jsBroadcastChannel->wrapped(); + if (/*!wrapped.isContextStopped() && */ wrapped.hasPendingActivity()) { + if (UNLIKELY(reason)) + *reason = "ActiveDOMObject with pending activity"; + return true; + } + UNUSED_PARAM(visitor); + UNUSED_PARAM(reason); + return false; +} + +void JSBroadcastChannelOwner::finalize(JSC::Handle handle, void* context) +{ + auto* jsBroadcastChannel = static_cast(handle.slot()->asCell()); + auto& world = *static_cast(context); + uncacheWrapper(world, &jsBroadcastChannel->wrapped(), jsBroadcastChannel); +} + +#if ENABLE(BINDING_INTEGRITY) +#if PLATFORM(WIN) +#pragma warning(disable : 4483) +extern "C" { +extern void (*const __identifier("??_7BroadcastChannel@WebCore@@6B@")[])(); +} +#else +extern "C" { +extern void* _ZTVN7WebCore16BroadcastChannelE[]; +} +#endif +#endif + +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref&& impl) +{ + + if constexpr (std::is_polymorphic_v) { +#if ENABLE(BINDING_INTEGRITY) + const void* actualVTablePointer = getVTablePointer(impl.ptr()); +#if PLATFORM(WIN) + void* expectedVTablePointer = __identifier("??_7BroadcastChannel@WebCore@@6B@"); +#else + void* expectedVTablePointer = &_ZTVN7WebCore16BroadcastChannelE[2]; +#endif + + // If you hit this assertion you either have a use after free bug, or + // BroadcastChannel has subclasses. If BroadcastChannel has subclasses that get passed + // to toJS() we currently require BroadcastChannel you to opt out of binding hardening + // by adding the SkipVTableValidation attribute to the interface IDL definition + RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); +#endif + } + return createWrapper(globalObject, WTFMove(impl)); +} + +JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, BroadcastChannel& impl) +{ + return wrap(lexicalGlobalObject, globalObject, impl); +} + +BroadcastChannel* JSBroadcastChannel::toWrapped(JSC::VM&, JSC::JSValue value) +{ + if (auto* wrapper = jsDynamicCast(value)) + return &wrapper->wrapped(); + return nullptr; +} + +} diff --git a/src/bun.js/bindings/webcore/JSBroadcastChannel.h b/src/bun.js/bindings/webcore/JSBroadcastChannel.h new file mode 100644 index 00000000000000..9154d49910283a --- /dev/null +++ b/src/bun.js/bindings/webcore/JSBroadcastChannel.h @@ -0,0 +1,99 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#pragma once + +#include "BroadcastChannel.h" +#include "JSDOMWrapper.h" +#include "JSEventTarget.h" +#include + +namespace WebCore { + +class JSBroadcastChannel : public JSEventTarget { +public: + using Base = JSEventTarget; + using DOMWrapped = BroadcastChannel; + static JSBroadcastChannel* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, Ref&& impl) + { + JSBroadcastChannel* ptr = new (NotNull, JSC::allocateCell(globalObject->vm())) JSBroadcastChannel(structure, *globalObject, WTFMove(impl)); + ptr->finishCreation(globalObject->vm()); + return ptr; + } + + static JSC::JSObject* createPrototype(JSC::VM&, JSDOMGlobalObject&); + static JSC::JSObject* prototype(JSC::VM&, JSDOMGlobalObject&); + static BroadcastChannel* toWrapped(JSC::VM&, JSC::JSValue); + + DECLARE_INFO; + + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info(), JSC::NonArray); + } + + static JSC::JSValue getConstructor(JSC::VM&, const JSC::JSGlobalObject*); + template static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + if constexpr (mode == JSC::SubspaceAccess::Concurrently) + return nullptr; + return subspaceForImpl(vm); + } + static JSC::GCClient::IsoSubspace* subspaceForImpl(JSC::VM& vm); + static void analyzeHeap(JSCell*, JSC::HeapAnalyzer&); + BroadcastChannel& wrapped() const + { + return static_cast(Base::wrapped()); + } + +protected: + JSBroadcastChannel(JSC::Structure*, JSDOMGlobalObject&, Ref&&); + + DECLARE_DEFAULT_FINISH_CREATION; +}; + +class JSBroadcastChannelOwner final : public JSC::WeakHandleOwner { +public: + bool isReachableFromOpaqueRoots(JSC::Handle, void* context, JSC::AbstractSlotVisitor&, const char**) final; + void finalize(JSC::Handle, void* context) final; +}; + +inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld&, BroadcastChannel*) +{ + static NeverDestroyed owner; + return &owner.get(); +} + +inline void* wrapperKey(BroadcastChannel* wrappableObject) +{ + return wrappableObject; +} + +JSC::JSValue toJS(JSC::JSGlobalObject*, JSDOMGlobalObject*, BroadcastChannel&); +inline JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, BroadcastChannel* impl) { return impl ? toJS(lexicalGlobalObject, globalObject, *impl) : JSC::jsNull(); } +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject*, Ref&&); +inline JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, RefPtr&& impl) { return impl ? toJSNewlyCreated(lexicalGlobalObject, globalObject, impl.releaseNonNull()) : JSC::jsNull(); } + +template<> struct JSDOMWrapperConverterTraits { + using WrapperClass = JSBroadcastChannel; + using ToWrappedReturnType = BroadcastChannel*; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/JSFetchHeaders.cpp b/src/bun.js/bindings/webcore/JSFetchHeaders.cpp index bb9a14833f6f71..08b5d8ee6bc006 100644 --- a/src/bun.js/bindings/webcore/JSFetchHeaders.cpp +++ b/src/bun.js/bindings/webcore/JSFetchHeaders.cpp @@ -258,28 +258,15 @@ JSC_DEFINE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_getSetCookie, (JSGlobal return JSValue::encode(JSC::constructEmptyArray(lexicalGlobalObject, nullptr, 0)); } - JSC::JSArray* array = nullptr; - GCDeferralContext deferralContext(lexicalGlobalObject->vm()); - JSC::ObjectInitializationScope initializationScope(lexicalGlobalObject->vm()); - if ((array = JSC::JSArray::tryCreateUninitializedRestricted( - initializationScope, &deferralContext, - lexicalGlobalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous), - count))) { - for (unsigned i = 0; i < count; ++i) { - array->initializeIndex(initializationScope, i, jsString(vm, values[i])); - RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined())); - } - } else { - array = constructEmptyArray(lexicalGlobalObject, nullptr, count); - RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined())); - if (!array) { - throwOutOfMemoryError(lexicalGlobalObject, scope); - return JSValue::encode(jsUndefined()); - } - for (unsigned i = 0; i < count; ++i) { - array->putDirectIndex(lexicalGlobalObject, i, jsString(vm, values[i])); - RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined())); - } + JSC::JSArray* array = constructEmptyArray(lexicalGlobalObject, nullptr, count); + RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined())); + if (UNLIKELY(!array)) { + throwOutOfMemoryError(lexicalGlobalObject, scope); + return JSValue::encode(jsUndefined()); + } + + for (unsigned i = 0; i < count; ++i) { + array->putDirectIndex(lexicalGlobalObject, i, jsString(vm, values[i])); RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined())); } @@ -302,7 +289,7 @@ static const HashTableValue JSFetchHeadersPrototypeTableValues[] = { { "forEach"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsFetchHeadersPrototypeFunction_forEach, 1 } }, { "toJSON"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsFetchHeadersPrototypeFunction_toJSON, 0 } }, { "count"_s, static_cast(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, jsFetchHeadersGetterCount, 0 } }, - // { "getSetCookie"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsFetchHeadersPrototypeFunction_getSetCookie, 0 } }, + { "getSetCookie"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsFetchHeadersPrototypeFunction_getSetCookie, 0 } }, }; const ClassInfo JSFetchHeadersPrototype::s_info = { "Headers"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSFetchHeadersPrototype) }; @@ -434,7 +421,7 @@ static inline JSC::EncodedJSValue jsFetchHeadersPrototypeFunction_toJSONBody(JSC for (auto it = vec.begin(); it != vec.end(); ++it) { auto& name = it->key; auto& value = it->value; - obj->putDirect(vm, Identifier::fromString(vm, WTFMove(name.convertToASCIILowercase())), jsString(vm, value), 0); + obj->putDirect(vm, Identifier::fromString(vm, name.convertToASCIILowercase()), jsString(vm, value), 0); } } diff --git a/src/bun.js/bindings/webcore/JSMessageChannel.cpp b/src/bun.js/bindings/webcore/JSMessageChannel.cpp new file mode 100644 index 00000000000000..2082bd9a8d35e6 --- /dev/null +++ b/src/bun.js/bindings/webcore/JSMessageChannel.cpp @@ -0,0 +1,323 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" + +#if ENABLE(CHANNEL_MESSAGING) + +#include "JSMessageChannel.h" + +#include "ActiveDOMObject.h" +#include "ExtendedDOMClientIsoSubspaces.h" +#include "ExtendedDOMIsoSubspaces.h" +#include "JSDOMAttribute.h" +#include "JSDOMBinding.h" +#include "JSDOMConstructor.h" +#include "JSDOMConvertInterface.h" +#include "JSDOMExceptionHandling.h" +#include "JSDOMGlobalObject.h" +#include "JSDOMGlobalObjectInlines.h" +#include "JSDOMWrapperCache.h" +#include "JSMessagePort.h" +#include "ScriptExecutionContext.h" +#include "WebCoreJSClientData.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WebCore { +using namespace JSC; + +// Attributes + +static JSC_DECLARE_CUSTOM_GETTER(jsMessageChannelConstructor); +static JSC_DECLARE_CUSTOM_GETTER(jsMessageChannel_port1); +static JSC_DECLARE_CUSTOM_GETTER(jsMessageChannel_port2); + +class JSMessageChannelPrototype final : public JSC::JSNonFinalObject { +public: + using Base = JSC::JSNonFinalObject; + static JSMessageChannelPrototype* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) + { + JSMessageChannelPrototype* ptr = new (NotNull, JSC::allocateCell(vm)) JSMessageChannelPrototype(vm, globalObject, structure); + ptr->finishCreation(vm); + return ptr; + } + + DECLARE_INFO; + template + static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSMessageChannelPrototype, Base); + return &vm.plainObjectSpace(); + } + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); + } + +private: + JSMessageChannelPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) + : JSC::JSNonFinalObject(vm, structure) + { + } + + void finishCreation(JSC::VM&); +}; +STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSMessageChannelPrototype, JSMessageChannelPrototype::Base); + +using JSMessageChannelDOMConstructor = JSDOMConstructor; + +template<> EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSMessageChannelDOMConstructor::construct(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame) +{ + VM& vm = lexicalGlobalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* castedThis = jsCast(callFrame->jsCallee()); + ASSERT(castedThis); + auto* context = castedThis->scriptExecutionContext(); + if (UNLIKELY(!context)) + return throwConstructorScriptExecutionContextUnavailableError(*lexicalGlobalObject, throwScope, "MessageChannel"); + auto object = MessageChannel::create(*context); + if constexpr (IsExceptionOr) + RETURN_IF_EXCEPTION(throwScope, {}); + static_assert(TypeOrExceptionOrUnderlyingType::isRef); + auto jsValue = toJSNewlyCreated>(*lexicalGlobalObject, *castedThis->globalObject(), throwScope, WTFMove(object)); + if constexpr (IsExceptionOr) + RETURN_IF_EXCEPTION(throwScope, {}); + setSubclassStructureIfNeeded(lexicalGlobalObject, callFrame, asObject(jsValue)); + RETURN_IF_EXCEPTION(throwScope, {}); + return JSValue::encode(jsValue); +} +JSC_ANNOTATE_HOST_FUNCTION(JSMessageChannelDOMConstructorConstruct, JSMessageChannelDOMConstructor::construct); + +template<> const ClassInfo JSMessageChannelDOMConstructor::s_info = { "MessageChannel"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSMessageChannelDOMConstructor) }; + +template<> JSValue JSMessageChannelDOMConstructor::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject) +{ + UNUSED_PARAM(vm); + return globalObject.functionPrototype(); +} + +template<> void JSMessageChannelDOMConstructor::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject) +{ + putDirect(vm, vm.propertyNames->length, jsNumber(0), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + JSString* nameString = jsNontrivialString(vm, "MessageChannel"_s); + m_originalName.set(vm, this, nameString); + putDirect(vm, vm.propertyNames->name, nameString, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + putDirect(vm, vm.propertyNames->prototype, JSMessageChannel::prototype(vm, globalObject), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete); +} + +/* Hash table for prototype */ + +static const HashTableValue JSMessageChannelPrototypeTableValues[] = { + { "constructor"_s, static_cast(PropertyAttribute::DontEnum), NoIntrinsic, { HashTableValue::GetterSetterType, jsMessageChannelConstructor, 0 } }, + { "port1"_s, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsMessageChannel_port1, 0 } }, + { "port2"_s, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsMessageChannel_port2, 0 } }, +}; + +const ClassInfo JSMessageChannelPrototype::s_info = { "MessageChannel"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSMessageChannelPrototype) }; + +void JSMessageChannelPrototype::finishCreation(VM& vm) +{ + Base::finishCreation(vm); + reifyStaticProperties(vm, JSMessageChannel::info(), JSMessageChannelPrototypeTableValues, *this); + JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); +} + +const ClassInfo JSMessageChannel::s_info = { "MessageChannel"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSMessageChannel) }; + +JSMessageChannel::JSMessageChannel(Structure* structure, JSDOMGlobalObject& globalObject, Ref&& impl) + : JSDOMWrapper(structure, globalObject, WTFMove(impl)) +{ +} + +// static_assert(!std::is_base_of::value, "Interface is not marked as [ActiveDOMObject] even though implementation class subclasses ActiveDOMObject."); + +JSObject* JSMessageChannel::createPrototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + auto* structure = JSMessageChannelPrototype::createStructure(vm, &globalObject, globalObject.objectPrototype()); + structure->setMayBePrototype(true); + return JSMessageChannelPrototype::create(vm, &globalObject, structure); +} + +JSObject* JSMessageChannel::prototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + return getDOMPrototype(vm, globalObject); +} + +JSValue JSMessageChannel::getConstructor(VM& vm, const JSGlobalObject* globalObject) +{ + return getDOMConstructor(vm, *jsCast(globalObject)); +} + +void JSMessageChannel::destroy(JSC::JSCell* cell) +{ + JSMessageChannel* thisObject = static_cast(cell); + thisObject->JSMessageChannel::~JSMessageChannel(); +} + +JSC_DEFINE_CUSTOM_GETTER(jsMessageChannelConstructor, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* prototype = jsDynamicCast(JSValue::decode(thisValue)); + if (UNLIKELY(!prototype)) + return throwVMTypeError(lexicalGlobalObject, throwScope); + return JSValue::encode(JSMessageChannel::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); +} + +static inline JSValue jsMessageChannel_port1Getter(JSGlobalObject& lexicalGlobalObject, JSMessageChannel& thisObject) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto& impl = thisObject.wrapped(); + RELEASE_AND_RETURN(throwScope, (toJS>(lexicalGlobalObject, *thisObject.globalObject(), throwScope, impl.port1()))); +} + +JSC_DEFINE_CUSTOM_GETTER(jsMessageChannel_port1, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +static inline JSValue jsMessageChannel_port2Getter(JSGlobalObject& lexicalGlobalObject, JSMessageChannel& thisObject) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto& impl = thisObject.wrapped(); + RELEASE_AND_RETURN(throwScope, (toJS>(lexicalGlobalObject, *thisObject.globalObject(), throwScope, impl.port2()))); +} + +JSC_DEFINE_CUSTOM_GETTER(jsMessageChannel_port2, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +JSC::GCClient::IsoSubspace* JSMessageChannel::subspaceForImpl(JSC::VM& vm) +{ + return WebCore::subspaceForImpl( + vm, + [](auto& spaces) { return spaces.m_clientSubspaceForMessageChannel.get(); }, + [](auto& spaces, auto&& space) { spaces.m_clientSubspaceForMessageChannel = std::forward(space); }, + [](auto& spaces) { return spaces.m_subspaceForMessageChannel.get(); }, + [](auto& spaces, auto&& space) { spaces.m_subspaceForMessageChannel = std::forward(space); }); +} + +template +void JSMessageChannel::visitChildrenImpl(JSCell* cell, Visitor& visitor) +{ + auto* thisObject = jsCast(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitChildren(thisObject, visitor); + thisObject->visitAdditionalChildren(visitor); +} + +DEFINE_VISIT_CHILDREN(JSMessageChannel); + +template +void JSMessageChannel::visitOutputConstraints(JSCell* cell, Visitor& visitor) +{ + auto* thisObject = jsCast(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitOutputConstraints(thisObject, visitor); + thisObject->visitAdditionalChildren(visitor); +} + +template void JSMessageChannel::visitOutputConstraints(JSCell*, AbstractSlotVisitor&); +template void JSMessageChannel::visitOutputConstraints(JSCell*, SlotVisitor&); +void JSMessageChannel::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) +{ + auto* thisObject = jsCast(cell); + analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); + if (thisObject->scriptExecutionContext()) + analyzer.setLabelForCell(cell, "url "_s + thisObject->scriptExecutionContext()->url().string()); + Base::analyzeHeap(cell, analyzer); +} + +bool JSMessageChannelOwner::isReachableFromOpaqueRoots(JSC::Handle handle, void*, AbstractSlotVisitor& visitor, const char** reason) +{ + UNUSED_PARAM(handle); + UNUSED_PARAM(visitor); + UNUSED_PARAM(reason); + return false; +} + +void JSMessageChannelOwner::finalize(JSC::Handle handle, void* context) +{ + auto* jsMessageChannel = static_cast(handle.slot()->asCell()); + auto& world = *static_cast(context); + uncacheWrapper(world, &jsMessageChannel->wrapped(), jsMessageChannel); +} + +#if ENABLE(BINDING_INTEGRITY) +#if PLATFORM(WIN) +#pragma warning(disable : 4483) +extern "C" { +extern void (*const __identifier("??_7MessageChannel@WebCore@@6B@")[])(); +} +#else +extern "C" { +extern void* _ZTVN7WebCore14MessageChannelE[]; +} +#endif +#endif + +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref&& impl) +{ + + if constexpr (std::is_polymorphic_v) { +#if ENABLE(BINDING_INTEGRITY) + const void* actualVTablePointer = getVTablePointer(impl.ptr()); +#if PLATFORM(WIN) + void* expectedVTablePointer = __identifier("??_7MessageChannel@WebCore@@6B@"); +#else + void* expectedVTablePointer = &_ZTVN7WebCore14MessageChannelE[2]; +#endif + + // If you hit this assertion you either have a use after free bug, or + // MessageChannel has subclasses. If MessageChannel has subclasses that get passed + // to toJS() we currently require MessageChannel you to opt out of binding hardening + // by adding the SkipVTableValidation attribute to the interface IDL definition + RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); +#endif + } + return createWrapper(globalObject, WTFMove(impl)); +} + +JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, MessageChannel& impl) +{ + return wrap(lexicalGlobalObject, globalObject, impl); +} + +MessageChannel* JSMessageChannel::toWrapped(JSC::VM&, JSC::JSValue value) +{ + if (auto* wrapper = jsDynamicCast(value)) + return &wrapper->wrapped(); + return nullptr; +} + +} + +#endif // ENABLE(CHANNEL_MESSAGING) diff --git a/src/bun.js/bindings/webcore/JSMessageChannel.h b/src/bun.js/bindings/webcore/JSMessageChannel.h new file mode 100644 index 00000000000000..551be7459b52f6 --- /dev/null +++ b/src/bun.js/bindings/webcore/JSMessageChannel.h @@ -0,0 +1,102 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#pragma once + +#if ENABLE(CHANNEL_MESSAGING) + +#include "JSDOMWrapper.h" +#include "MessageChannel.h" +#include + +namespace WebCore { + +class JSMessageChannel : public JSDOMWrapper { +public: + using Base = JSDOMWrapper; + static JSMessageChannel* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, Ref&& impl) + { + JSMessageChannel* ptr = new (NotNull, JSC::allocateCell(globalObject->vm())) JSMessageChannel(structure, *globalObject, WTFMove(impl)); + ptr->finishCreation(globalObject->vm()); + return ptr; + } + + static JSC::JSObject* createPrototype(JSC::VM&, JSDOMGlobalObject&); + static JSC::JSObject* prototype(JSC::VM&, JSDOMGlobalObject&); + static MessageChannel* toWrapped(JSC::VM&, JSC::JSValue); + static void destroy(JSC::JSCell*); + + DECLARE_INFO; + + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info(), JSC::NonArray); + } + + static JSC::JSValue getConstructor(JSC::VM&, const JSC::JSGlobalObject*); + template static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + if constexpr (mode == JSC::SubspaceAccess::Concurrently) + return nullptr; + return subspaceForImpl(vm); + } + static JSC::GCClient::IsoSubspace* subspaceForImpl(JSC::VM& vm); + DECLARE_VISIT_CHILDREN; + template void visitAdditionalChildren(Visitor&); + + template static void visitOutputConstraints(JSCell*, Visitor&); + static void analyzeHeap(JSCell*, JSC::HeapAnalyzer&); + +protected: + JSMessageChannel(JSC::Structure*, JSDOMGlobalObject&, Ref&&); + + DECLARE_DEFAULT_FINISH_CREATION; +}; + +class JSMessageChannelOwner final : public JSC::WeakHandleOwner { +public: + bool isReachableFromOpaqueRoots(JSC::Handle, void* context, JSC::AbstractSlotVisitor&, const char**) final; + void finalize(JSC::Handle, void* context) final; +}; + +inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld&, MessageChannel*) +{ + static NeverDestroyed owner; + return &owner.get(); +} + +inline void* wrapperKey(MessageChannel* wrappableObject) +{ + return wrappableObject; +} + +JSC::JSValue toJS(JSC::JSGlobalObject*, JSDOMGlobalObject*, MessageChannel&); +inline JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, MessageChannel* impl) { return impl ? toJS(lexicalGlobalObject, globalObject, *impl) : JSC::jsNull(); } +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject*, Ref&&); +inline JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, RefPtr&& impl) { return impl ? toJSNewlyCreated(lexicalGlobalObject, globalObject, impl.releaseNonNull()) : JSC::jsNull(); } + +template<> struct JSDOMWrapperConverterTraits { + using WrapperClass = JSMessageChannel; + using ToWrappedReturnType = MessageChannel*; +}; + +} // namespace WebCore + +#endif // ENABLE(CHANNEL_MESSAGING) diff --git a/src/bun.js/bindings/webcore/JSMessageChannelCustom.cpp b/src/bun.js/bindings/webcore/JSMessageChannelCustom.cpp new file mode 100644 index 00000000000000..75b0740485e7c1 --- /dev/null +++ b/src/bun.js/bindings/webcore/JSMessageChannelCustom.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2008-2021 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(CHANNEL_MESSAGING) + +#include "DOMWrapperWorld.h" +#include "JSMessageChannel.h" +// #include "JSNodeCustom.h" +#include "MessagePort.h" +// #include "WebCoreOpaqueRootInlines.h" +#include + +namespace WebCore { + +template +void JSMessageChannel::visitAdditionalChildren(Visitor& visitor) +{ + visitor.addOpaqueRoot(WTF::getPtr(wrapped().port1())); + visitor.addOpaqueRoot(WTF::getPtr(wrapped().port2())); + // addWebCoreOpaqueRoot(visitor, wrapped().port1()); + // addWebCoreOpaqueRoot(visitor, wrapped().port2()); +} + +DEFINE_VISIT_ADDITIONAL_CHILDREN(JSMessageChannel); + +} // namespace WebCore + +#endif // ENABLE(CHANNEL_MESSAGING) diff --git a/src/bun.js/bindings/webcore/JSMessageEvent.cpp b/src/bun.js/bindings/webcore/JSMessageEvent.cpp index e797e3af25947c..68414fe468015d 100644 --- a/src/bun.js/bindings/webcore/JSMessageEvent.cpp +++ b/src/bun.js/bindings/webcore/JSMessageEvent.cpp @@ -41,7 +41,7 @@ #include "JSDOMGlobalObjectInlines.h" #include "JSDOMOperation.h" #include "JSDOMWrapperCache.h" -// #include "JSMessagePort.h" +#include "JSMessagePort.h" #include "JSServiceWorker.h" #include "JSWindowProxy.h" #include "ScriptExecutionContext.h" @@ -143,18 +143,18 @@ template<> MessageEvent::Init convertDictionary(JSGlobalObje RETURN_IF_EXCEPTION(throwScope, {}); } else result.origin = emptyString(); - // JSValue portsValue; - // if (isNullOrUndefined) - // portsValue = jsUndefined(); - // else { - // portsValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "ports"_s)); - // RETURN_IF_EXCEPTION(throwScope, { }); - // } - // if (!portsValue.isUndefined()) { - // result.ports = convert>>(lexicalGlobalObject, portsValue); - // RETURN_IF_EXCEPTION(throwScope, { }); - // } else - // result.ports = Converter>>::ReturnType{ }; + JSValue portsValue; + if (isNullOrUndefined) + portsValue = jsUndefined(); + else { + portsValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "ports"_s)); + RETURN_IF_EXCEPTION(throwScope, {}); + } + if (!portsValue.isUndefined()) { + result.ports = convert>>(lexicalGlobalObject, portsValue); + RETURN_IF_EXCEPTION(throwScope, {}); + } else + result.ports = Converter>>::ReturnType {}; JSValue sourceValue; if (isNullOrUndefined) sourceValue = jsUndefined(); @@ -352,7 +352,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsMessageEvent_lastEventId, (JSGlobalObject * lexicalGl static inline JSValue jsMessageEvent_sourceGetter(JSGlobalObject& lexicalGlobalObject, JSMessageEvent& thisObject) { auto& vm = JSC::getVM(&lexicalGlobalObject); - return lexicalGlobalObject.globalThis(); + return jsNull(); // auto throwScope = DECLARE_THROW_SCOPE(vm); // auto& impl = thisObject.wrapped(); // RELEASE_AND_RETURN(throwScope, (toJS, IDLInterface, IDLInterface>>>(lexicalGlobalObject, *thisObject.globalObject(), throwScope, impl.source()))); @@ -377,9 +377,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsMessageEvent_data, (JSGlobalObject * lexicalGlobalObj static inline JSValue jsMessageEvent_portsGetter(JSGlobalObject& lexicalGlobalObject, JSMessageEvent& thisObject) { UNUSED_PARAM(lexicalGlobalObject); - // TODO: - return JSArray::create(lexicalGlobalObject.vm(), lexicalGlobalObject.arrayStructureForIndexingTypeDuringAllocation(ArrayWithContiguous), 0); - // return thisObject.ports(lexicalGlobalObject); + return thisObject.ports(lexicalGlobalObject); } JSC_DEFINE_CUSTOM_GETTER(jsMessageEvent_ports, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) @@ -416,13 +414,12 @@ static inline JSC::EncodedJSValue jsMessageEventPrototypeFunction_initMessageEve RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); EnsureStillAliveScope argument6 = callFrame->argument(6); auto source = WebCore::MessageEventSource(); - // RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); - // EnsureStillAliveScope argument7 = callFrame->argument(7); - // auto messagePorts = JSArray::create(lexicalGlobalObject.vm(), lexicalGlobalObject->arrayStructureForIndexingTypeDuringAllocation(ArrayWithContiguous), 0); - // auto messagePorts = Converter>>::ReturnType {}; + // auto source = argument6.value().isUndefined() ? std::nullopt : convert, IDLInterface, IDLInterface>>>(*lexicalGlobalObject, argument6.value()); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + EnsureStillAliveScope argument7 = callFrame->argument(7); + auto messagePorts = argument7.value().isUndefined() ? Converter>>::ReturnType {} : convert>>(*lexicalGlobalObject, argument7.value()); RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); - // RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.initMessageEvent(WTFMove(type), WTFMove(bubbles), WTFMove(cancelable), WTFMove(data), WTFMove(originArg), WTFMove(lastEventId), WTFMove(source), WTFMove(messagePorts)); }))); - RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.initMessageEvent(WTFMove(type), WTFMove(bubbles), WTFMove(cancelable), WTFMove(data), WTFMove(originArg), WTFMove(lastEventId), WTFMove(source)); }))); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.initMessageEvent(WTFMove(type), WTFMove(bubbles), WTFMove(cancelable), WTFMove(data), WTFMove(originArg), WTFMove(lastEventId), WTFMove(source), WTFMove(messagePorts)); }))); } JSC_DEFINE_HOST_FUNCTION(jsMessageEventPrototypeFunction_initMessageEvent, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) @@ -474,7 +471,7 @@ void JSMessageEvent::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) auto* thisObject = jsCast(cell); analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); if (thisObject->scriptExecutionContext()) - analyzer.setLabelForCell(cell, "url " + thisObject->scriptExecutionContext()->url().string()); + analyzer.setLabelForCell(cell, "url "_s + thisObject->scriptExecutionContext()->url().string()); Base::analyzeHeap(cell, analyzer); } diff --git a/src/bun.js/bindings/webcore/JSMessageEvent.h b/src/bun.js/bindings/webcore/JSMessageEvent.h index 85424d9ec40207..8f48568f771cf4 100644 --- a/src/bun.js/bindings/webcore/JSMessageEvent.h +++ b/src/bun.js/bindings/webcore/JSMessageEvent.h @@ -70,6 +70,7 @@ class JSMessageEvent : public JSEvent { { return static_cast(Base::wrapped()); } + protected: JSMessageEvent(JSC::Structure*, JSDOMGlobalObject&, Ref&&); @@ -87,5 +88,4 @@ template<> struct JSDOMWrapperConverterTraits { }; template<> MessageEvent::Init convertDictionary(JSC::JSGlobalObject&, JSC::JSValue); - } // namespace WebCore diff --git a/src/bun.js/bindings/webcore/JSMessageEventCustom.cpp b/src/bun.js/bindings/webcore/JSMessageEventCustom.cpp index 66390f86bb2894..772a1b3c4ca911 100644 --- a/src/bun.js/bindings/webcore/JSMessageEventCustom.cpp +++ b/src/bun.js/bindings/webcore/JSMessageEventCustom.cpp @@ -45,26 +45,21 @@ namespace WebCore { JSC::JSValue JSMessageEvent::ports(JSC::JSGlobalObject& lexicalGlobalObject) const { - return JSC::jsUndefined(); + auto throwScope = DECLARE_THROW_SCOPE(lexicalGlobalObject.vm()); + return cachedPropertyValue(lexicalGlobalObject, *this, wrapped().cachedPorts(), [&] { + JSC::JSValue ports = toJS>>(lexicalGlobalObject, *globalObject(), throwScope, wrapped().ports()); + return ports; + }); } -// auto throwScope = DECLARE_THROW_SCOPE(lexicalGlobalObject.vm()); -// return cachedPropertyValue(lexicalGlobalObject, *this, wrapped().cachedPorts(), [&] { -// JSC::JSValue ports = toJS>>(lexicalGlobalObject, *globalObject(), throwScope, wrapped().ports()); -// return ports; -// }); -// } JSC::JSValue JSMessageEvent::data(JSC::JSGlobalObject& lexicalGlobalObject) const { - return cachedPropertyValue(lexicalGlobalObject, *this, wrapped().cachedData(), [this, &lexicalGlobalObject] { + auto throwScope = DECLARE_THROW_SCOPE(lexicalGlobalObject.vm()); + return cachedPropertyValue(throwScope, lexicalGlobalObject, *this, wrapped().cachedData(), [this, &lexicalGlobalObject](JSC::ThrowScope&) { return WTF::switchOn( - wrapped().data(), [this](MessageEvent::JSValueTag) -> JSC::JSValue { return wrapped().jsData().getValue(JSC::jsNull()); }, - // [this, &lexicalGlobalObject](const Ref& data) { - // // FIXME: Is it best to handle errors by returning null rather than throwing an exception? - // return data->deserialize(lexicalGlobalObject, globalObject(), wrapped().ports(), SerializationErrorMode::NonThrowing); }, - [&lexicalGlobalObject](const String& data) { return toJS(lexicalGlobalObject, data); }, - // [this, &lexicalGlobalObject](const Ref& data) { return toJS>(lexicalGlobalObject, *globalObject(), data); }, - [this, &lexicalGlobalObject](const Ref& data) { return toJS>(lexicalGlobalObject, *globalObject(), data); }); + wrapped().data(), [this](MessageEvent::JSValueTag) -> JSC::JSValue { return wrapped().jsData().getValue(JSC::jsNull()); }, [this, &lexicalGlobalObject](const Ref& data) { + // FIXME: Is it best to handle errors by returning null rather than throwing an exception? + return data->deserialize(lexicalGlobalObject, globalObject(), wrapped().ports(), SerializationErrorMode::NonThrowing); }, [&lexicalGlobalObject](const String& data) { return toJS(lexicalGlobalObject, data); }, [this, &lexicalGlobalObject](const Ref& data) { return toJS>(lexicalGlobalObject, *globalObject(), data); }); }); } diff --git a/src/bun.js/bindings/webcore/JSMessagePort.cpp b/src/bun.js/bindings/webcore/JSMessagePort.cpp new file mode 100644 index 00000000000000..b70167e555dc6d --- /dev/null +++ b/src/bun.js/bindings/webcore/JSMessagePort.cpp @@ -0,0 +1,496 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "JSMessagePort.h" + +#include "ActiveDOMObject.h" +#include "EventNames.h" +#include "ExtendedDOMClientIsoSubspaces.h" +#include "ExtendedDOMIsoSubspaces.h" +#include "IDLTypes.h" +#include "JSDOMAttribute.h" +#include "JSDOMBinding.h" +#include "JSDOMConstructorNotConstructable.h" +#include "JSDOMConvertAny.h" +#include "JSDOMConvertBase.h" +#include "JSDOMConvertDictionary.h" +#include "JSDOMConvertObject.h" +#include "JSDOMConvertSequences.h" +#include "JSDOMExceptionHandling.h" +#include "JSDOMGlobalObjectInlines.h" +#include "JSDOMOperation.h" +#include "JSDOMWrapperCache.h" +#include "JSEventListener.h" +#include "JSStructuredSerializeOptions.h" +#include "ScriptExecutionContext.h" +#include "WebCoreJSClientData.h" +// #include "WebCoreOpaqueRootInlines.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace WebCore { +using namespace JSC; + +// Functions + +static JSC_DECLARE_HOST_FUNCTION(jsMessagePortPrototypeFunction_postMessage); +static JSC_DECLARE_HOST_FUNCTION(jsMessagePortPrototypeFunction_start); +static JSC_DECLARE_HOST_FUNCTION(jsMessagePortPrototypeFunction_close); +static JSC_DECLARE_HOST_FUNCTION(jsMessagePortPrototypeFunction_ref); +static JSC_DECLARE_HOST_FUNCTION(jsMessagePortPrototypeFunction_unref); +static JSC_DECLARE_HOST_FUNCTION(jsMessagePortPrototypeFunction_hasRef); + +// Attributes + +static JSC_DECLARE_CUSTOM_GETTER(jsMessagePortConstructor); +static JSC_DECLARE_CUSTOM_GETTER(jsMessagePort_onmessage); +static JSC_DECLARE_CUSTOM_SETTER(setJSMessagePort_onmessage); +static JSC_DECLARE_CUSTOM_GETTER(jsMessagePort_onmessageerror); +static JSC_DECLARE_CUSTOM_SETTER(setJSMessagePort_onmessageerror); + +class JSMessagePortPrototype final : public JSC::JSNonFinalObject { +public: + using Base = JSC::JSNonFinalObject; + static JSMessagePortPrototype* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) + { + JSMessagePortPrototype* ptr = new (NotNull, JSC::allocateCell(vm)) JSMessagePortPrototype(vm, globalObject, structure); + ptr->finishCreation(vm); + return ptr; + } + + DECLARE_INFO; + template + static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSMessagePortPrototype, Base); + return &vm.plainObjectSpace(); + } + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); + } + +private: + JSMessagePortPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) + : JSC::JSNonFinalObject(vm, structure) + { + } + + void finishCreation(JSC::VM&); +}; +STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSMessagePortPrototype, JSMessagePortPrototype::Base); + +using JSMessagePortDOMConstructor = JSDOMConstructorNotConstructable; + +template<> const ClassInfo JSMessagePortDOMConstructor::s_info = { "MessagePort"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSMessagePortDOMConstructor) }; + +template<> JSValue JSMessagePortDOMConstructor::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject) +{ + return JSEventTarget::getConstructor(vm, &globalObject); +} + +template<> void JSMessagePortDOMConstructor::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject) +{ + putDirect(vm, vm.propertyNames->length, jsNumber(0), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + JSString* nameString = jsNontrivialString(vm, "MessagePort"_s); + m_originalName.set(vm, this, nameString); + putDirect(vm, vm.propertyNames->name, nameString, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); + putDirect(vm, vm.propertyNames->prototype, JSMessagePort::prototype(vm, globalObject), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete); +} + +/* Hash table for prototype */ + +static const HashTableValue JSMessagePortPrototypeTableValues[] = { + { "constructor"_s, static_cast(PropertyAttribute::DontEnum), NoIntrinsic, { HashTableValue::GetterSetterType, jsMessagePortConstructor, 0 } }, + { "onmessage"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsMessagePort_onmessage, setJSMessagePort_onmessage } }, + { "onmessageerror"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsMessagePort_onmessageerror, setJSMessagePort_onmessageerror } }, + { "postMessage"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsMessagePortPrototypeFunction_postMessage, 1 } }, + { "start"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsMessagePortPrototypeFunction_start, 0 } }, + { "close"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsMessagePortPrototypeFunction_close, 0 } }, + { "ref"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsMessagePortPrototypeFunction_ref, 0 } }, + { "unref"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsMessagePortPrototypeFunction_unref, 0 } }, + { "hasRef"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsMessagePortPrototypeFunction_hasRef, 0 } }, +}; + +const ClassInfo JSMessagePortPrototype::s_info = { "MessagePort"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSMessagePortPrototype) }; + +void JSMessagePortPrototype::finishCreation(VM& vm) +{ + Base::finishCreation(vm); + reifyStaticProperties(vm, JSMessagePort::info(), JSMessagePortPrototypeTableValues, *this); + JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); +} + +const ClassInfo JSMessagePort::s_info = { "MessagePort"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSMessagePort) }; + +JSMessagePort::JSMessagePort(Structure* structure, JSDOMGlobalObject& globalObject, Ref&& impl) + : JSEventTarget(structure, globalObject, WTFMove(impl)) +{ +} + +// static_assert(std::is_base_of::value, "Interface is marked as [ActiveDOMObject] but implementation class does not subclass ActiveDOMObject."); + +JSObject* JSMessagePort::createPrototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + auto* structure = JSMessagePortPrototype::createStructure(vm, &globalObject, JSEventTarget::prototype(vm, globalObject)); + structure->setMayBePrototype(true); + return JSMessagePortPrototype::create(vm, &globalObject, structure); +} + +JSObject* JSMessagePort::prototype(VM& vm, JSDOMGlobalObject& globalObject) +{ + return getDOMPrototype(vm, globalObject); +} + +JSValue JSMessagePort::getConstructor(VM& vm, const JSGlobalObject* globalObject) +{ + return getDOMConstructor(vm, *jsCast(globalObject)); +} + +JSC_DEFINE_CUSTOM_GETTER(jsMessagePortConstructor, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName)) +{ + VM& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + auto* prototype = jsDynamicCast(JSValue::decode(thisValue)); + if (UNLIKELY(!prototype)) + return throwVMTypeError(lexicalGlobalObject, throwScope); + return JSValue::encode(JSMessagePort::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); +} + +static inline JSValue jsMessagePort_onmessageGetter(JSGlobalObject& lexicalGlobalObject, JSMessagePort& thisObject) +{ + UNUSED_PARAM(lexicalGlobalObject); + return eventHandlerAttribute(thisObject.wrapped(), eventNames().messageEvent, worldForDOMObject(thisObject)); +} + +JSC_DEFINE_CUSTOM_GETTER(jsMessagePort_onmessage, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +static inline bool setJSMessagePort_onmessageSetter(JSGlobalObject& lexicalGlobalObject, JSMessagePort& thisObject, JSValue value) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + UNUSED_PARAM(vm); + setEventHandlerAttribute(thisObject.wrapped(), eventNames().messageEvent, value, thisObject); + vm.writeBarrier(&thisObject, value); + ensureStillAliveHere(value); + + thisObject.wrapped().jsRef(&lexicalGlobalObject); + + return true; +} + +JSC_DEFINE_CUSTOM_SETTER(setJSMessagePort_onmessage, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue, PropertyName attributeName)) +{ + return IDLAttribute::set(*lexicalGlobalObject, thisValue, encodedValue, attributeName); +} + +static inline JSValue jsMessagePort_onmessageerrorGetter(JSGlobalObject& lexicalGlobalObject, JSMessagePort& thisObject) +{ + UNUSED_PARAM(lexicalGlobalObject); + return eventHandlerAttribute(thisObject.wrapped(), eventNames().messageerrorEvent, worldForDOMObject(thisObject)); +} + +JSC_DEFINE_CUSTOM_GETTER(jsMessagePort_onmessageerror, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName)) +{ + return IDLAttribute::get(*lexicalGlobalObject, thisValue, attributeName); +} + +static inline bool setJSMessagePort_onmessageerrorSetter(JSGlobalObject& lexicalGlobalObject, JSMessagePort& thisObject, JSValue value) +{ + auto& vm = JSC::getVM(&lexicalGlobalObject); + UNUSED_PARAM(vm); + setEventHandlerAttribute(thisObject.wrapped(), eventNames().messageerrorEvent, value, thisObject); + vm.writeBarrier(&thisObject, value); + ensureStillAliveHere(value); + + thisObject.wrapped().jsRef(&lexicalGlobalObject); + + return true; +} + +JSC_DEFINE_CUSTOM_SETTER(setJSMessagePort_onmessageerror, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue, PropertyName attributeName)) +{ + return IDLAttribute::set(*lexicalGlobalObject, thisValue, encodedValue, attributeName); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_postMessage1Body(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); + auto message = convert(*lexicalGlobalObject, argument0.value()); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + EnsureStillAliveScope argument1 = callFrame->uncheckedArgument(1); + auto transfer = convert>(*lexicalGlobalObject, argument1.value()); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.postMessage(*jsCast(lexicalGlobalObject), WTFMove(message), WTFMove(transfer)); }))); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_postMessage2Body(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); + auto message = convert(*lexicalGlobalObject, argument0.value()); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + EnsureStillAliveScope argument1 = callFrame->argument(1); + auto options = convert>(*lexicalGlobalObject, argument1.value()); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.postMessage(*jsCast(lexicalGlobalObject), WTFMove(message), WTFMove(options)); }))); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_postMessageOverloadDispatcher(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + size_t argsCount = std::min(2, callFrame->argumentCount()); + if (argsCount == 1) { + RELEASE_AND_RETURN(throwScope, (jsMessagePortPrototypeFunction_postMessage2Body(lexicalGlobalObject, callFrame, castedThis))); + } + if (argsCount == 2) { + JSValue distinguishingArg = callFrame->uncheckedArgument(1); + if (distinguishingArg.isUndefined()) + RELEASE_AND_RETURN(throwScope, (jsMessagePortPrototypeFunction_postMessage2Body(lexicalGlobalObject, callFrame, castedThis))); + if (distinguishingArg.isUndefinedOrNull()) + RELEASE_AND_RETURN(throwScope, (jsMessagePortPrototypeFunction_postMessage2Body(lexicalGlobalObject, callFrame, castedThis))); + { + bool success = hasIteratorMethod(lexicalGlobalObject, distinguishingArg); + RETURN_IF_EXCEPTION(throwScope, {}); + if (success) + RELEASE_AND_RETURN(throwScope, (jsMessagePortPrototypeFunction_postMessage1Body(lexicalGlobalObject, callFrame, castedThis))); + } + if (distinguishingArg.isObject()) + RELEASE_AND_RETURN(throwScope, (jsMessagePortPrototypeFunction_postMessage2Body(lexicalGlobalObject, callFrame, castedThis))); + } + return argsCount < 1 ? throwVMError(lexicalGlobalObject, throwScope, createNotEnoughArgumentsError(lexicalGlobalObject)) : throwVMTypeError(lexicalGlobalObject, throwScope); +} + +JSC_DEFINE_HOST_FUNCTION(jsMessagePortPrototypeFunction_postMessage, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "postMessage"); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_startBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.start(); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsMessagePortPrototypeFunction_start, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "start"); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_closeBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + impl.jsUnref(lexicalGlobalObject); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.close(); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsMessagePortPrototypeFunction_close, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "close"); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_refBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.jsRef(lexicalGlobalObject); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsMessagePortPrototypeFunction_ref, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "ref"); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_unrefBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS(*lexicalGlobalObject, throwScope, [&]() -> decltype(auto) { return impl.jsUnref(lexicalGlobalObject); }))); +} + +JSC_DEFINE_HOST_FUNCTION(jsMessagePortPrototypeFunction_unref, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "unref"); +} + +static inline JSC::EncodedJSValue jsMessagePortPrototypeFunction_hasRefBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation::ClassParameter castedThis) +{ + auto& vm = JSC::getVM(lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + UNUSED_PARAM(throwScope); + UNUSED_PARAM(callFrame); + auto& impl = castedThis->wrapped(); + return JSValue::encode(jsBoolean(impl.jsHasRef())); +} + +JSC_DEFINE_HOST_FUNCTION(jsMessagePortPrototypeFunction_hasRef, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame)) +{ + return IDLOperation::call(*lexicalGlobalObject, *callFrame, "hasRef"); +} + +JSC::GCClient::IsoSubspace* JSMessagePort::subspaceForImpl(JSC::VM& vm) +{ + return WebCore::subspaceForImpl( + vm, + [](auto& spaces) { return spaces.m_clientSubspaceForMessagePort.get(); }, + [](auto& spaces, auto&& space) { spaces.m_clientSubspaceForMessagePort = std::forward(space); }, + [](auto& spaces) { return spaces.m_subspaceForMessagePort.get(); }, + [](auto& spaces, auto&& space) { spaces.m_subspaceForMessagePort = std::forward(space); }); +} + +template +void JSMessagePort::visitChildrenImpl(JSCell* cell, Visitor& visitor) +{ + auto* thisObject = jsCast(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitChildren(thisObject, visitor); + thisObject->visitAdditionalChildren(visitor); +} + +DEFINE_VISIT_CHILDREN(JSMessagePort); + +template +void JSMessagePort::visitOutputConstraints(JSCell* cell, Visitor& visitor) +{ + auto* thisObject = jsCast(cell); + ASSERT_GC_OBJECT_INHERITS(thisObject, info()); + Base::visitOutputConstraints(thisObject, visitor); + thisObject->visitAdditionalChildren(visitor); +} + +template void JSMessagePort::visitOutputConstraints(JSCell*, AbstractSlotVisitor&); +template void JSMessagePort::visitOutputConstraints(JSCell*, SlotVisitor&); +void JSMessagePort::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) +{ + auto* thisObject = jsCast(cell); + analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); + if (thisObject->scriptExecutionContext()) + analyzer.setLabelForCell(cell, "url "_s + thisObject->scriptExecutionContext()->url().string()); + Base::analyzeHeap(cell, analyzer); +} + +bool JSMessagePortOwner::isReachableFromOpaqueRoots(JSC::Handle handle, void*, AbstractSlotVisitor& visitor, const char** reason) +{ + auto* jsMessagePort = jsCast(handle.slot()->asCell()); + auto& wrapped = jsMessagePort->wrapped(); + if (wrapped.hasPendingActivity()) { + if (UNLIKELY(reason)) + *reason = "ActiveDOMObject with pending activity"; + return true; + } + MessagePort* owner = &jsMessagePort->wrapped(); + if (UNLIKELY(reason)) + *reason = "Reachable from MessagePort"; + + return visitor.containsOpaqueRoot(owner); +} + +void JSMessagePortOwner::finalize(JSC::Handle handle, void* context) +{ + auto* jsMessagePort = static_cast(handle.slot()->asCell()); + auto& world = *static_cast(context); + uncacheWrapper(world, &jsMessagePort->wrapped(), jsMessagePort); +} + +#if ENABLE(BINDING_INTEGRITY) +#if PLATFORM(WIN) +#pragma warning(disable : 4483) +extern "C" { +extern void (*const __identifier("??_7MessagePort@WebCore@@6B@")[])(); +} +#else +extern "C" { +extern void* _ZTVN7WebCore11MessagePortE[]; +} +#endif +#endif + +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref&& impl) +{ + + if constexpr (std::is_polymorphic_v) { +#if ENABLE(BINDING_INTEGRITY) + const void* actualVTablePointer = getVTablePointer(impl.ptr()); +#if PLATFORM(WIN) + void* expectedVTablePointer = __identifier("??_7MessagePort@WebCore@@6B@"); +#else + void* expectedVTablePointer = &_ZTVN7WebCore11MessagePortE[2]; +#endif + + // If you hit this assertion you either have a use after free bug, or + // MessagePort has subclasses. If MessagePort has subclasses that get passed + // to toJS() we currently require MessagePort you to opt out of binding hardening + // by adding the SkipVTableValidation attribute to the interface IDL definition + RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); +#endif + } + return createWrapper(globalObject, WTFMove(impl)); +} + +JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, MessagePort& impl) +{ + return wrap(lexicalGlobalObject, globalObject, impl); +} + +MessagePort* JSMessagePort::toWrapped(JSC::VM&, JSC::JSValue value) +{ + if (auto* wrapper = jsDynamicCast(value)) + return &wrapper->wrapped(); + return nullptr; +} + +} diff --git a/src/bun.js/bindings/webcore/JSMessagePort.h b/src/bun.js/bindings/webcore/JSMessagePort.h new file mode 100644 index 00000000000000..44c928050e6e93 --- /dev/null +++ b/src/bun.js/bindings/webcore/JSMessagePort.h @@ -0,0 +1,103 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#pragma once + +#include "JSDOMWrapper.h" +#include "JSEventTarget.h" +#include "MessagePort.h" +#include + +namespace WebCore { + +class WEBCORE_EXPORT JSMessagePort : public JSEventTarget { +public: + using Base = JSEventTarget; + using DOMWrapped = MessagePort; + static JSMessagePort* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, Ref&& impl) + { + JSMessagePort* ptr = new (NotNull, JSC::allocateCell(globalObject->vm())) JSMessagePort(structure, *globalObject, WTFMove(impl)); + ptr->finishCreation(globalObject->vm()); + return ptr; + } + + static JSC::JSObject* createPrototype(JSC::VM&, JSDOMGlobalObject&); + static JSC::JSObject* prototype(JSC::VM&, JSDOMGlobalObject&); + static MessagePort* toWrapped(JSC::VM&, JSC::JSValue); + + DECLARE_INFO; + + static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) + { + return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info(), JSC::NonArray); + } + + static JSC::JSValue getConstructor(JSC::VM&, const JSC::JSGlobalObject*); + template static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) + { + if constexpr (mode == JSC::SubspaceAccess::Concurrently) + return nullptr; + return subspaceForImpl(vm); + } + static JSC::GCClient::IsoSubspace* subspaceForImpl(JSC::VM& vm); + DECLARE_VISIT_CHILDREN; + template void visitAdditionalChildren(Visitor&); + + template static void visitOutputConstraints(JSCell*, Visitor&); + static void analyzeHeap(JSCell*, JSC::HeapAnalyzer&); + MessagePort& wrapped() const + { + return static_cast(Base::wrapped()); + } + +protected: + JSMessagePort(JSC::Structure*, JSDOMGlobalObject&, Ref&&); + + DECLARE_DEFAULT_FINISH_CREATION; +}; + +class WEBCORE_EXPORT JSMessagePortOwner final : public JSC::WeakHandleOwner { +public: + bool isReachableFromOpaqueRoots(JSC::Handle, void* context, JSC::AbstractSlotVisitor&, const char**) final; + void finalize(JSC::Handle, void* context) final; +}; + +inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld&, MessagePort*) +{ + static NeverDestroyed owner; + return &owner.get(); +} + +inline void* wrapperKey(MessagePort* wrappableObject) +{ + return wrappableObject; +} + +WEBCORE_EXPORT JSC::JSValue toJS(JSC::JSGlobalObject*, JSDOMGlobalObject*, MessagePort&); +inline JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, MessagePort* impl) { return impl ? toJS(lexicalGlobalObject, globalObject, *impl) : JSC::jsNull(); } +JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject*, Ref&&); +inline JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, RefPtr&& impl) { return impl ? toJSNewlyCreated(lexicalGlobalObject, globalObject, impl.releaseNonNull()) : JSC::jsNull(); } + +template<> struct JSDOMWrapperConverterTraits { + using WrapperClass = JSMessagePort; + using ToWrappedReturnType = MessagePort*; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/JSMessagePortCustom.cpp b/src/bun.js/bindings/webcore/JSMessagePortCustom.cpp new file mode 100644 index 00000000000000..56031dd60e2887 --- /dev/null +++ b/src/bun.js/bindings/webcore/JSMessagePortCustom.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2008-2021 Apple Inc. All Rights Reserved. + * Copyright (C) 2011 Google Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSMessagePort.h" +// #include "WebCoreOpaqueRootInlines.h" + +namespace WebCore { +using namespace JSC; + +template +void JSMessagePort::visitAdditionalChildren(Visitor& visitor) +{ + // If we have a locally entangled port, we can directly mark it as reachable. Ports that are remotely entangled are marked in-use by markActiveObjectsForContext(). + if (auto* port = wrapped().locallyEntangledPort()) { + visitor.addOpaqueRoot(port); + // addWebCoreOpaqueRoot(visitor, *port); + } +} + +DEFINE_VISIT_ADDITIONAL_CHILDREN(JSMessagePort); + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/JSStructuredSerializeOptions.cpp b/src/bun.js/bindings/webcore/JSStructuredSerializeOptions.cpp new file mode 100644 index 00000000000000..4311426e6e9561 --- /dev/null +++ b/src/bun.js/bindings/webcore/JSStructuredSerializeOptions.cpp @@ -0,0 +1,58 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "config.h" +#include "JSStructuredSerializeOptions.h" + +#include "JSDOMConvertObject.h" +#include "JSDOMConvertSequences.h" +#include +#include + +namespace WebCore { +using namespace JSC; + +template<> StructuredSerializeOptions convertDictionary(JSGlobalObject& lexicalGlobalObject, JSValue value) +{ + VM& vm = JSC::getVM(&lexicalGlobalObject); + auto throwScope = DECLARE_THROW_SCOPE(vm); + bool isNullOrUndefined = value.isUndefinedOrNull(); + auto* object = isNullOrUndefined ? nullptr : value.getObject(); + if (UNLIKELY(!isNullOrUndefined && !object)) { + throwTypeError(&lexicalGlobalObject, throwScope); + return {}; + } + StructuredSerializeOptions result; + JSValue transferValue; + if (isNullOrUndefined) + transferValue = jsUndefined(); + else { + transferValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "transfer"_s)); + RETURN_IF_EXCEPTION(throwScope, {}); + } + if (!transferValue.isUndefined()) { + result.transfer = convert>(lexicalGlobalObject, transferValue); + RETURN_IF_EXCEPTION(throwScope, {}); + } else + result.transfer = Converter>::ReturnType {}; + return result; +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/JSStructuredSerializeOptions.h b/src/bun.js/bindings/webcore/JSStructuredSerializeOptions.h new file mode 100644 index 00000000000000..8fc8fddd0a16c0 --- /dev/null +++ b/src/bun.js/bindings/webcore/JSStructuredSerializeOptions.h @@ -0,0 +1,30 @@ +/* + This file is part of the WebKit open source project. + This file has been generated by generate-bindings.pl. DO NOT MODIFY! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#pragma once + +#include "JSDOMConvertDictionary.h" +#include "StructuredSerializeOptions.h" + +namespace WebCore { + +template<> StructuredSerializeOptions convertDictionary(JSC::JSGlobalObject&, JSC::JSValue); + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/JSValueInWrappedObject.h b/src/bun.js/bindings/webcore/JSValueInWrappedObject.h index d05fdb8fdccee3..d11796912580ea 100644 --- a/src/bun.js/bindings/webcore/JSValueInWrappedObject.h +++ b/src/bun.js/bindings/webcore/JSValueInWrappedObject.h @@ -61,6 +61,7 @@ class JSValueInWrappedObject { JSC::Weak m_cell {}; }; +JSC::JSValue cachedPropertyValue(JSC::ThrowScope&, JSC::JSGlobalObject&, const JSDOMObject& owner, JSValueInWrappedObject& cacheSlot, const Function&); JSC::JSValue cachedPropertyValue(JSC::JSGlobalObject&, const JSDOMObject& owner, JSValueInWrappedObject& cacheSlot, const Function&); inline JSValueInWrappedObject::JSValueInWrappedObject(JSC::JSValue value) @@ -132,4 +133,17 @@ inline JSC::JSValue cachedPropertyValue(JSC::JSGlobalObject& lexicalGlobalObject return cachedValue.getValue(); } +inline JSC::JSValue cachedPropertyValue(JSC::ThrowScope& throwScope, JSC::JSGlobalObject& lexicalGlobalObject, const JSDOMObject& owner, JSValueInWrappedObject& cachedValue, const Function& function) +{ + if (cachedValue && isWorldCompatible(lexicalGlobalObject, cachedValue.getValue())) + return cachedValue.getValue(); + + auto value = function(throwScope); + RETURN_IF_EXCEPTION(throwScope, {}); + + cachedValue.set(lexicalGlobalObject.vm(), &owner, cloneAcrossWorlds(lexicalGlobalObject, owner, value)); + ASSERT(isWorldCompatible(lexicalGlobalObject, cachedValue.getValue())); + return cachedValue.getValue(); +} + } // namespace WebCore diff --git a/src/bun.js/bindings/webcore/JSWorker.cpp b/src/bun.js/bindings/webcore/JSWorker.cpp index 4ddd97520ad615..ce114978d534df 100644 --- a/src/bun.js/bindings/webcore/JSWorker.cpp +++ b/src/bun.js/bindings/webcore/JSWorker.cpp @@ -55,6 +55,7 @@ #include #include #include +#include "SerializedScriptValue.h" namespace WebCore { using namespace JSC; @@ -127,7 +128,7 @@ template<> EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSWorkerDOMConstructor::const EnsureStillAliveScope argument1 = callFrame->argument(1); auto options = WorkerOptions {}; - options.bun.unref = true; + options.bun.unref = false; if (JSObject* optionsObject = JSC::jsDynamicCast(argument1.value())) { if (auto nameValue = optionsObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "name"_s))) { @@ -137,16 +138,93 @@ template<> EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSWorkerDOMConstructor::const } } - if (auto* bunObject = optionsObject) { - if (auto miniModeValue = bunObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "smol"_s))) { - options.bun.mini = miniModeValue.toBoolean(lexicalGlobalObject); - RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + if (auto miniModeValue = optionsObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "smol"_s))) { + options.bun.mini = miniModeValue.toBoolean(lexicalGlobalObject); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + } + + if (auto ref = optionsObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "ref"_s))) { + options.bun.unref = !ref.toBoolean(lexicalGlobalObject); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + } + + auto workerData = optionsObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "workerData"_s)); + if (!workerData) { + workerData = optionsObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "data"_s)); + } + + if (workerData) { + Vector> ports; + Vector> transferList; + + if (JSValue transferListValue = optionsObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "transferList"_s))) { + if (transferListValue.isObject()) { + JSC::JSObject* transferListObject = transferListValue.getObject(); + if (auto* transferListArray = jsDynamicCast(transferListObject)) { + for (unsigned i = 0; i < transferListArray->length(); i++) { + JSC::JSValue transferListValue = transferListArray->get(lexicalGlobalObject, i); + if (transferListValue.isObject()) { + JSC::JSObject* transferListObject = transferListValue.getObject(); + transferList.append(JSC::Strong(vm, transferListObject)); + } + } + } + } } - if (auto ref = bunObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "ref"_s))) { - options.bun.unref = !ref.toBoolean(lexicalGlobalObject); - RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + ExceptionOr> serialized = SerializedScriptValue::create(*lexicalGlobalObject, workerData, WTFMove(transferList), ports, SerializationForStorage::No, SerializationContext::WorkerPostMessage); + if (serialized.hasException()) { + WebCore::propagateException(*lexicalGlobalObject, throwScope, serialized.releaseException()); + return encodedJSValue(); + } + + Vector transferredPorts; + + if (!ports.isEmpty()) { + auto disentangleResult = MessagePort::disentanglePorts(WTFMove(ports)); + if (disentangleResult.hasException()) { + WebCore::propagateException(*lexicalGlobalObject, throwScope, disentangleResult.releaseException()); + return encodedJSValue(); + } + transferredPorts = disentangleResult.releaseReturnValue(); + } + + options.bun.data = WTFMove(serialized.releaseReturnValue()); + options.bun.dataMessagePorts = WTFMove(transferredPorts); + } + + auto* globalObject = jsCast(lexicalGlobalObject); + auto envValue = optionsObject->getIfPropertyExists(lexicalGlobalObject, Identifier::fromString(vm, "env"_s)); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + JSObject* envObject = nullptr; + + if (envValue && envValue.isCell()) { + envObject = jsDynamicCast(envValue); + } else if (globalObject->m_processEnvObject.isInitialized()) { + envObject = globalObject->processEnvObject(); + } + + if (envObject) { + if (!envObject->staticPropertiesReified()) { + envObject->reifyAllStaticProperties(globalObject); + RETURN_IF_EXCEPTION(throwScope, {}); } + + JSC::PropertyNameArray keys(vm, JSC::PropertyNameMode::Strings, JSC::PrivateSymbolMode::Exclude); + envObject->methodTable()->getOwnPropertyNames(envObject, lexicalGlobalObject, keys, JSC::DontEnumPropertiesMode::Exclude); + RETURN_IF_EXCEPTION(throwScope, {}); + + HashMap env; + + for (const auto& key : keys) { + JSValue value = envObject->get(lexicalGlobalObject, key); + RETURN_IF_EXCEPTION(throwScope, {}); + String str = value.toWTFString(lexicalGlobalObject).isolatedCopy(); + RETURN_IF_EXCEPTION(throwScope, {}); + env.add(key.impl()->isolatedCopy(), str); + } + + options.bun.env = std::make_unique>(WTFMove(env)); } } @@ -188,16 +266,31 @@ template<> void JSWorkerDOMConstructor::initializeProperties(VM& vm, JSDOMGlobal putDirect(vm, vm.propertyNames->prototype, JSWorker::prototype(vm, globalObject), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete); } +JSC_DEFINE_CUSTOM_GETTER(jsWorker_threadIdGetter, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName)) +{ + auto* castedThis = jsDynamicCast(JSValue::decode(thisValue)); + if (UNLIKELY(!castedThis)) + return JSValue::encode(jsUndefined()); + + // Main thread starts at 1 + // so we say it's 0 + // + // Note that we cannot use posix thread ids here because we don't know their thread id until the thread starts + // + return JSValue::encode(jsNumber(castedThis->wrapped().clientIdentifier() - 1)); +} + /* Hash table for prototype */ static const HashTableValue JSWorkerPrototypeTableValues[] = { { "constructor"_s, static_cast(PropertyAttribute::DontEnum), NoIntrinsic, { HashTableValue::GetterSetterType, jsWorkerConstructor, 0 } }, + { "onerror"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsWorker_onerror, setJSWorker_onerror } }, { "onmessage"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsWorker_onmessage, setJSWorker_onmessage } }, { "onmessageerror"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsWorker_onmessageerror, setJSWorker_onmessageerror } }, - { "onerror"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute, NoIntrinsic, { HashTableValue::GetterSetterType, jsWorker_onerror, setJSWorker_onerror } }, - { "terminate"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsWorkerPrototypeFunction_terminate, 0 } }, { "postMessage"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsWorkerPrototypeFunction_postMessage, 1 } }, { "ref"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsWorkerPrototypeFunction_ref, 0 } }, + { "terminate"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsWorkerPrototypeFunction_terminate, 0 } }, + { "threadId"_s, JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete, NoIntrinsic, { HashTableValue::GetterSetterType, jsWorker_threadIdGetter, nullptr } }, { "unref"_s, static_cast(JSC::PropertyAttribute::Function), NoIntrinsic, { HashTableValue::NativeFunctionType, jsWorkerPrototypeFunction_unref, 0 } }, }; diff --git a/src/bun.js/bindings/webcore/MessageChannel.cpp b/src/bun.js/bindings/webcore/MessageChannel.cpp new file mode 100644 index 00000000000000..67407b9c0417fb --- /dev/null +++ b/src/bun.js/bindings/webcore/MessageChannel.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "config.h" +#include "MessageChannel.h" + +#include "MessagePort.h" +#include "MessagePortChannelProvider.h" +#include "ScriptExecutionContext.h" + +namespace WebCore { + +static std::pair, Ref> generateMessagePorts(ScriptExecutionContext& context) +{ + MessagePortIdentifier id1 = { ProcessIdent::identifier(), PortIdentifier::generate() }; + MessagePortIdentifier id2 = { ProcessIdent::identifier(), PortIdentifier::generate() }; + + return { MessagePort::create(context, id1, id2), MessagePort::create(context, id2, id1) }; +} + +Ref MessageChannel::create(ScriptExecutionContext& context) +{ + return adoptRef(*new MessageChannel(context)); +} + +MessageChannel::MessageChannel(ScriptExecutionContext& context) + : m_ports(generateMessagePorts(context)) +{ + if (!context.activeDOMObjectsAreStopped()) { + ASSERT(!port1().isDetached()); + ASSERT(!port2().isDetached()); + MessagePortChannelProvider::fromContext(context).createNewMessagePortChannel(port1().identifier(), port2().identifier()); + } else { + ASSERT(port1().isDetached()); + ASSERT(port2().isDetached()); + } +} + +MessageChannel::~MessageChannel() = default; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessageChannel.h b/src/bun.js/bindings/webcore/MessageChannel.h new file mode 100644 index 00000000000000..1cc936094430f1 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessageChannel.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#pragma once + +#include +#include + +namespace WebCore { + +class MessagePort; +class ScriptExecutionContext; + +class MessageChannel : public RefCounted { +public: + static Ref create(ScriptExecutionContext&); + ~MessageChannel(); + + MessagePort& port1() const { return m_ports.first; } + MessagePort& port2() const { return m_ports.second; } + +private: + explicit MessageChannel(ScriptExecutionContext&); + + std::pair, Ref> m_ports; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessageEvent.cpp b/src/bun.js/bindings/webcore/MessageEvent.cpp index b210f4cec32b0b..b5a96a4a2e208b 100644 --- a/src/bun.js/bindings/webcore/MessageEvent.cpp +++ b/src/bun.js/bindings/webcore/MessageEvent.cpp @@ -30,7 +30,10 @@ // #include "Blob.h" #include "EventNames.h" +#include "JSDOMConvert.h" +#include "JSMessageEvent.h" #include + // #include namespace WebCore { @@ -47,29 +50,29 @@ inline MessageEvent::MessageEvent(const AtomString& type, Init&& initializer, Is , m_origin(initializer.origin) , m_lastEventId(initializer.lastEventId) , m_source(WTFMove(initializer.source)) - // , m_ports(WTFMove(initializer.ports)) + , m_ports(WTFMove(initializer.ports)) , m_jsData(initializer.data) { } -inline MessageEvent::MessageEvent(const AtomString& type, DataType&& data, const String& origin, const String& lastEventId, std::optional&& source /*, Vector>&& ports*/) +inline MessageEvent::MessageEvent(const AtomString& type, DataType&& data, const String& origin, const String& lastEventId, std::optional&& source, Vector>&& ports) : Event(type, CanBubble::No, IsCancelable::No) , m_data(WTFMove(data)) , m_origin(origin) , m_lastEventId(lastEventId) , m_source(WTFMove(source)) -// , m_ports(WTFMove(ports)) + , m_ports(WTFMove(ports)) { } -Ref MessageEvent::create(const AtomString& type, DataType&& data, const String& origin, const String& lastEventId, std::optional&& source /*, Vector>&& ports*/) +Ref MessageEvent::create(const AtomString& type, DataType&& data, const String& origin, const String& lastEventId, std::optional&& source, Vector>&& ports) { - return adoptRef(*new MessageEvent(type, WTFMove(data), origin, lastEventId, WTFMove(source) /*, /*WTFMove(ports)*/)); + return adoptRef(*new MessageEvent(type, WTFMove(data), origin, lastEventId, WTFMove(source), WTFMove(ports))); } -Ref MessageEvent::create(DataType&& data, const String& origin, const String& lastEventId, std::optional&& source /*, Vector>&& ports*/) +Ref MessageEvent::create(DataType&& data, const String& origin, const String& lastEventId, std::optional&& source, Vector>&& ports) { - return create(eventNames().messageEvent, WTFMove(data), origin, lastEventId, WTFMove(source) /*, /*WTFMove(ports)*/); + return create(eventNames().messageEvent, WTFMove(data), origin, lastEventId, WTFMove(source), WTFMove(ports)); } Ref MessageEvent::createForBindings() @@ -84,7 +87,32 @@ Ref MessageEvent::create(const AtomString& type, Init&& initialize MessageEvent::~MessageEvent() = default; -void MessageEvent::initMessageEvent(const AtomString& type, bool canBubble, bool cancelable, JSValue data, const String& origin, const String& lastEventId, std::optional&& source /*, Vector>&& ports*/) +auto MessageEvent::create(JSC::JSGlobalObject& globalObject, Ref&& data, std::optional&& source, Vector>&& ports) -> MessageEventWithStrongData +{ + return create(globalObject, WTFMove(data), {}, {}, WTFMove(source), WTFMove(ports)); +} + +auto MessageEvent::create(JSC::JSGlobalObject& globalObject, Ref&& data, const String& origin, const String& lastEventId, std::optional&& source, Vector>&& ports) -> MessageEventWithStrongData +{ + auto& vm = globalObject.vm(); + // Locker locker(vm.apiLock()); + + bool didFail = false; + + auto deserialized = data->deserialize(globalObject, &globalObject, ports, SerializationErrorMode::NonThrowing, &didFail); + JSC::Strong strongData(vm, deserialized); + + auto& eventType = didFail ? eventNames().messageerrorEvent : eventNames().messageEvent; + auto event = adoptRef(*new MessageEvent(eventType, WTFMove(data), origin, lastEventId, WTFMove(source), WTFMove(ports))); + JSC::Strong strongWrapper(vm, JSC::jsCast(toJS(&globalObject, JSC::jsCast(&globalObject), event.get()))); + // Since we've already deserialized the SerializedScriptValue, cache the result so we don't have to deserialize + // again the next time JSMessageEvent::data() gets called by the main world. + event->cachedData().set(vm, strongWrapper.get(), deserialized); + + return MessageEventWithStrongData { event, WTFMove(strongWrapper) }; +} + +void MessageEvent::initMessageEvent(const AtomString& type, bool canBubble, bool cancelable, JSValue data, const String& origin, const String& lastEventId, std::optional&& source, Vector>&& ports) { if (isBeingDispatched()) return; @@ -102,7 +130,7 @@ void MessageEvent::initMessageEvent(const AtomString& type, bool canBubble, bool m_origin = origin; m_lastEventId = lastEventId; m_source = WTFMove(source); - // m_ports = WTFMove(ports); + m_ports = WTFMove(ports); m_cachedPorts.clear(); } @@ -116,7 +144,7 @@ size_t MessageEvent::memoryCost() const Locker { m_concurrentDataAccessLock }; return WTF::switchOn( m_data, [](JSValueTag) -> size_t { return 0; }, - // [](const Ref& data) -> size_t { return data->memoryCost(); }, + [](const Ref& data) -> size_t { return data->memoryCost(); }, [](const String& string) -> size_t { return string.sizeInBytes(); }, // [](const Ref& blob) -> size_t { return blob->size(); }, [](const Ref& buffer) -> size_t { return buffer->byteLength(); }); diff --git a/src/bun.js/bindings/webcore/MessageEvent.h b/src/bun.js/bindings/webcore/MessageEvent.h index 4089e2ca1a08ba..184aa63a14585a 100644 --- a/src/bun.js/bindings/webcore/MessageEvent.h +++ b/src/bun.js/bindings/webcore/MessageEvent.h @@ -29,17 +29,16 @@ #include "Event.h" #include "JSValueInWrappedObject.h" -// #include "MessagePort.h" -// #include "SerializedScriptValue.h" +#include "MessagePort.h" +#include "SerializedScriptValue.h" +#include "MessagePort.h" +// #include "JSMessageEvent.h" // #include "ServiceWorker.h" // #include "WindowProxy.h" #include namespace WebCore { -class MessagePort : public RefCounted { -}; - class MessageEventSource { }; @@ -50,9 +49,10 @@ class MessageEvent final : public Event { struct JSValueTag { }; // using DataType = std::variant, String, Ref, Ref>; - using DataType = std::variant>; - static Ref create(const AtomString& type, DataType&&, const String& origin = {}, const String& lastEventId = {}, std::optional&& = std::nullopt /*, Vector>&& = {}*/); - static Ref create(DataType&&, const String& origin = {}, const String& lastEventId = {}, std::optional&& = std::nullopt /*, Vector>&& = {}*/); + using DataType = std::variant, String, Ref>; + static Ref create(const AtomString& type, DataType&&, const String& origin = {}, const String& lastEventId = {}, std::optional&& = std::nullopt, Vector>&& = {}); + static Ref create(DataType&&, const String& origin = {}, const String& lastEventId = {}, std::optional&& = std::nullopt, Vector>&& = {}); + static Ref createForBindings(); struct Init : EventInit { @@ -60,18 +60,27 @@ class MessageEvent final : public Event { String origin; String lastEventId; std::optional source; - // Vector> ports; + Vector> ports; }; static Ref create(const AtomString& type, Init&&, IsTrusted = IsTrusted::No); + struct MessageEventWithStrongData { + Ref event; + JSC::Strong strongWrapper; // Keep the wrapper alive until the event is fired, since it is what keeps `data` alive. + }; + + static MessageEventWithStrongData create(JSC::JSGlobalObject&, Ref&&, const String& origin = {}, const String& lastEventId = {}, std::optional&& = std::nullopt, Vector>&& = {}); + + static MessageEventWithStrongData create(JSC::JSGlobalObject&, Ref&&, std::optional&& = std::nullopt, Vector>&& = {}); + virtual ~MessageEvent(); - void initMessageEvent(const AtomString& type, bool canBubble, bool cancelable, JSC::JSValue data, const String& origin, const String& lastEventId, std::optional&& /*, Vector>&&*/); + void initMessageEvent(const AtomString& type, bool canBubble, bool cancelable, JSC::JSValue data, const String& origin, const String& lastEventId, std::optional&&, Vector>&&); const String& origin() const { return m_origin; } const String& lastEventId() const { return m_lastEventId; } const std::optional& source() const { return m_source; } - // const Vector>& ports() const { return m_ports; } + const Vector>& ports() const { return m_ports; } const DataType& data() const { return m_data; } @@ -84,7 +93,7 @@ class MessageEvent final : public Event { private: MessageEvent(); MessageEvent(const AtomString& type, Init&&, IsTrusted); - MessageEvent(const AtomString& type, DataType&&, const String& origin, const String& lastEventId = {}, std::optional&& = std::nullopt /*, Vector>&& = {}*/); + MessageEvent(const AtomString& type, DataType&&, const String& origin, const String& lastEventId = {}, std::optional&& = std::nullopt, Vector>&& = {}); EventInterface eventInterface() const final; @@ -92,7 +101,7 @@ class MessageEvent final : public Event { String m_origin; String m_lastEventId; std::optional m_source; - // Vector> m_ports; + Vector> m_ports; JSValueInWrappedObject m_jsData; JSValueInWrappedObject m_cachedData; diff --git a/src/bun.js/bindings/webcore/MessagePort.cpp b/src/bun.js/bindings/webcore/MessagePort.cpp new file mode 100644 index 00000000000000..2d94060f1330eb --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePort.cpp @@ -0,0 +1,449 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "config.h" +#include "MessagePort.h" + +#include "BunClientData.h" +// #include "Document.h" +#include "EventNames.h" +// #include "Logging.h" +#include "MessageEvent.h" +#include "BunWorkerGlobalScope.h" +#include "MessagePortChannelProvider.h" +#include "MessageWithMessagePorts.h" +#include "StructuredSerializeOptions.h" +#include "WebCoreOpaqueRoot.h" +// #include "WorkerGlobalScope.h" +// #include "WorkerThread.h" +#include "TaskSource.h" +#include +#include +#include +#include + +extern "C" void Bun__eventLoop__incrementRefConcurrently(void* bunVM, int delta); + +namespace WebCore { + +WTF_MAKE_ISO_ALLOCATED_IMPL(MessagePort); + +static Lock allMessagePortsLock; +static HashMap& allMessagePorts() WTF_REQUIRES_LOCK(allMessagePortsLock) +{ + static NeverDestroyed> map; + return map; +} + +static HashMap& portToContextIdentifier() WTF_REQUIRES_LOCK(allMessagePortsLock) +{ + static NeverDestroyed> map; + return map; +} + +void MessagePort::ref() const +{ + ++m_refCount; +} + +void MessagePort::deref() const +{ + // This custom deref() function ensures that as long as the lock to allMessagePortsLock is taken, no MessagePort will be destroyed. + // This allows notifyMessageAvailable to easily query the map and manipulate MessagePort instances. + + if (!--m_refCount) { + Locker locker { allMessagePortsLock }; + + if (m_refCount) + return; + + auto iterator = allMessagePorts().find(m_identifier); + if (iterator != allMessagePorts().end() && iterator->value == this) { + allMessagePorts().remove(iterator); + portToContextIdentifier().remove(m_identifier); + } + + delete this; + } +} + +bool MessagePort::hasPendingActivity() const +{ + return m_refCount > 0; +} + +bool MessagePort::isMessagePortAliveForTesting(const MessagePortIdentifier& identifier) +{ + Locker locker { allMessagePortsLock }; + return allMessagePorts().contains(identifier); +} + +ScriptExecutionContextIdentifier MessagePort::contextIdForMessagePortId(MessagePortIdentifier messagePortId) +{ + Locker locker { allMessagePortsLock }; + return portToContextIdentifier().get(messagePortId); +} + +void MessagePort::notifyMessageAvailable(const MessagePortIdentifier& identifier) +{ + ScriptExecutionContextIdentifier scriptExecutionContextIdentifier; + { + Locker locker { allMessagePortsLock }; + scriptExecutionContextIdentifier = portToContextIdentifier().get(identifier); + } + if (!scriptExecutionContextIdentifier) + return; + + ScriptExecutionContext::ensureOnContextThread(scriptExecutionContextIdentifier, [identifier](auto&) { + RefPtr port; + { + Locker locker { allMessagePortsLock }; + port = allMessagePorts().get(identifier); + } + if (port) + port->messageAvailable(); + }); +} + +Ref MessagePort::create(ScriptExecutionContext& scriptExecutionContext, const MessagePortIdentifier& local, const MessagePortIdentifier& remote) +{ + auto messagePort = adoptRef(*new MessagePort(scriptExecutionContext, local, remote)); + // messagePort->suspendIfNeeded(); + return messagePort; +} + +MessagePort::MessagePort(ScriptExecutionContext& scriptExecutionContext, const MessagePortIdentifier& local, const MessagePortIdentifier& remote) + // : ActiveDOMObject(&scriptExecutionContext) + : ContextDestructionObserver(&scriptExecutionContext) + , m_identifier(local) + , m_remoteIdentifier(remote) +{ + LOG(MessagePorts, "Created MessagePort %s (%p) in process %" PRIu64, m_identifier.logString().utf8().data(), this, ProcessIdent::identifier().toUInt64()); + + Locker locker { allMessagePortsLock }; + allMessagePorts().set(m_identifier, this); + portToContextIdentifier().set(m_identifier, scriptExecutionContext.identifier()); + + // Make sure the WeakPtrFactory gets initialized eagerly on the thread the MessagePort gets constructed on for thread-safety reasons. + initializeWeakPtrFactory(); + + scriptExecutionContext.createdMessagePort(*this); + + // Don't need to call processMessageWithMessagePortsSoon() here, because the port will not be opened until start() is invoked. +} + +MessagePort::~MessagePort() +{ + LOG(MessagePorts, "Destroyed MessagePort %s (%p) in process %" PRIu64, m_identifier.logString().utf8().data(), this, ProcessIdent::identifier().toUInt64()); + + ASSERT(allMessagePortsLock.isLocked()); + + if (m_entangled) + close(); + + if (auto contextId = portToContextIdentifier().get(m_identifier)) + ScriptExecutionContext::getScriptExecutionContext(contextId)->destroyedMessagePort(*this); +} + +void MessagePort::entangle() +{ + MessagePortChannelProvider::fromContext(*scriptExecutionContext()).entangleLocalPortInThisProcessToRemote(m_identifier, m_remoteIdentifier); +} + +ExceptionOr MessagePort::postMessage(JSC::JSGlobalObject& state, JSC::JSValue messageValue, StructuredSerializeOptions&& options) +{ + LOG(MessagePorts, "Attempting to post message to port %s (to be received by port %s)", m_identifier.logString().utf8().data(), m_remoteIdentifier.logString().utf8().data()); + + Vector> ports; + auto messageData = SerializedScriptValue::create(state, messageValue, WTFMove(options.transfer), ports, SerializationForStorage::No, SerializationContext::WorkerPostMessage); + if (messageData.hasException()) + return messageData.releaseException(); + + if (!isEntangled()) + return {}; + ASSERT(scriptExecutionContext()); + + Vector transferredPorts; + // Make sure we aren't connected to any of the passed-in ports. + if (!ports.isEmpty()) { + for (auto& port : ports) { + if (port->identifier() == m_identifier || port->identifier() == m_remoteIdentifier) + return Exception { DataCloneError }; + } + + auto disentangleResult = MessagePort::disentanglePorts(WTFMove(ports)); + if (disentangleResult.hasException()) + return disentangleResult.releaseException(); + transferredPorts = disentangleResult.releaseReturnValue(); + } + + MessageWithMessagePorts message { messageData.releaseReturnValue(), WTFMove(transferredPorts) }; + + LOG(MessagePorts, "Actually posting message to port %s (to be received by port %s)", m_identifier.logString().utf8().data(), m_remoteIdentifier.logString().utf8().data()); + + ScriptExecutionContextIdentifier contextId = contextIdForMessagePortId(m_remoteIdentifier); + + MessagePortChannelProvider::fromContext(*ScriptExecutionContext::getScriptExecutionContext(contextId)).postMessageToRemote(WTFMove(message), m_remoteIdentifier); + + return {}; +} + +TransferredMessagePort MessagePort::disentangle() +{ + ASSERT(m_entangled); + m_entangled = false; + + auto& context = *scriptExecutionContext(); + MessagePortChannelProvider::fromContext(context).messagePortDisentangled(m_identifier); + + // We can't receive any messages or generate any events after this, so remove ourselves from the list of active ports. + context.destroyedMessagePort(*this); + // context.willDestroyActiveDOMObject(*this); + context.willDestroyDestructionObserver(*this); + + observeContext(nullptr); + + return { identifier(), remoteIdentifier() }; +} + +// Invoked to notify us that there are messages available for this port. +// This code may be called from another thread, and so should not call any non-threadsafe APIs (i.e. should not call into the entangled channel or access mutable variables). +void MessagePort::messageAvailable() +{ + // This MessagePort object might be disentangled because the port is being transferred, + // in which case we'll notify it that messages are available once a new end point is created. + auto* context = scriptExecutionContext(); + if (!context || context->activeDOMObjectsAreSuspended()) + return; + + context->processMessageWithMessagePortsSoon([pendingActivity = Ref { *this }] {}); +} + +void MessagePort::start() +{ + // Do nothing if we've been cloned or closed. + if (!isEntangled()) + return; + + ASSERT(scriptExecutionContext()); + if (m_started) + return; + + m_started = true; + scriptExecutionContext()->processMessageWithMessagePortsSoon([pendingActivity = Ref { *this }] {}); +} + +void MessagePort::close() +{ + if (m_isDetached) + return; + m_isDetached = true; + + MessagePortChannelProvider::singleton().messagePortClosed(m_identifier); + + removeAllEventListeners(); +} + +void MessagePort::dispatchMessages() +{ + // Messages for contexts that are not fully active get dispatched too, but JSAbstractEventListener::handleEvent() doesn't call handlers for these. + // The HTML5 spec specifies that any messages sent to a document that is not fully active should be dropped, so this behavior is OK. + ASSERT(started()); + + auto* context = scriptExecutionContext(); + if (!context || context->activeDOMObjectsAreSuspended() || !isEntangled()) + return; + + auto messagesTakenHandler = [this, protectedThis = Ref { *this }](Vector&& messages, CompletionHandler&& completionCallback) mutable { + auto scopeExit = makeScopeExit(WTFMove(completionCallback)); + + LOG(MessagePorts, "MessagePort %s (%p) dispatching %zu messages", m_identifier.logString().utf8().data(), this, messages.size()); + + auto* context = scriptExecutionContext(); + if (!context || !context->jsGlobalObject()) + return; + + ASSERT(context->isContextThread()); + + // bool contextIsWorker = is(*context); + for (auto& message : messages) { + // close() in Worker onmessage handler should prevent next message from dispatching. + // if (contextIsWorker && downcast(*context).isClosing()) + // return; + + auto ports = MessagePort::entanglePorts(*context, WTFMove(message.transferredPorts)); + + // Per specification, each MessagePort object has a task source called the port message queue. + // queueTaskKeepingObjectAlive(context, *this, TaskSource::PostedMessageQueue, [this, event = WTFMove(event)] { + // dispatchEvent(event.event); + // }); + + ScriptExecutionContext::postTaskTo(contextIdForMessagePortId(m_identifier), [protectedThis = Ref { *this }, ports = WTFMove(ports), message = WTFMove(message)](ScriptExecutionContext& context) mutable { + auto event = MessageEvent::create(*context.jsGlobalObject(), message.message.releaseNonNull(), {}, {}, {}, WTFMove(ports)); + protectedThis->dispatchEvent(event.event); + }); + } + }; + + MessagePortChannelProvider::fromContext(*context).takeAllMessagesForPort(m_identifier, WTFMove(messagesTakenHandler)); +} + +JSValue MessagePort::tryTakeMessage(JSGlobalObject* lexicalGlobalObject) +{ + auto* context = scriptExecutionContext(); + if (!context || context->activeDOMObjectsAreSuspended() || !isEntangled()) + return jsUndefined(); + + std::optional messageWithPorts = MessagePortChannelProvider::fromContext(*context).tryTakeMessageForPort(m_identifier); + + if (!messageWithPorts) + return jsUndefined(); + + auto ports = MessagePort::entanglePorts(*context, WTFMove(messageWithPorts->transferredPorts)); + auto message = messageWithPorts->message.releaseNonNull(); + return message->deserialize(*lexicalGlobalObject, lexicalGlobalObject, WTFMove(ports), SerializationErrorMode::NonThrowing); +} + +void MessagePort::dispatchEvent(Event& event) +{ + if (m_isDetached) { + return; + } + + // auto* context = scriptExecutionContext(); + // if (is(*context) && downcast(*context).isClosing()) + // return; + + EventTarget::dispatchEvent(event); +} + +// https://html.spec.whatwg.org/multipage/web-messaging.html#ports-and-garbage-collection +// bool MessagePort::virtualHasPendingActivity() const +// { +// // If the ScriptExecutionContext has been shut down on this object close()'ed, we can GC. +// auto* context = scriptExecutionContext(); +// if (!context || m_isDetached) +// return false; + +// // If this MessagePort has no message event handler then there is no point in keeping it alive. +// if (!m_hasMessageEventListener) +// return false; + +// return m_entangled; +// } + +MessagePort* MessagePort::locallyEntangledPort() +{ + // FIXME: As the header describes, this is an optional optimization. + // Even in the new async model we should be able to get it right. + return nullptr; +} + +ExceptionOr> MessagePort::disentanglePorts(Vector>&& ports) +{ + if (ports.isEmpty()) + return Vector {}; + + // Walk the incoming array - if there are any duplicate ports, or null ports or cloned ports, throw an error (per section 8.3.3 of the HTML5 spec). + HashSet portSet; + for (auto& port : ports) { + if (!port || !port->m_entangled || !portSet.add(port.get()).isNewEntry) + return Exception { DataCloneError }; + } + + // Passed-in ports passed validity checks, so we can disentangle them. + return WTF::map(ports, [](auto& port) { + return port->disentangle(); + }); +} + +Vector> MessagePort::entanglePorts(ScriptExecutionContext& context, Vector&& transferredPorts) +{ + LOG(MessagePorts, "Entangling %zu transferred ports to ScriptExecutionContext %s (%p)", transferredPorts.size(), context.url().string().utf8().data(), &context); + + if (transferredPorts.isEmpty()) + return {}; + + return WTF::map(transferredPorts, [&](auto& port) -> RefPtr { + return MessagePort::entangle(context, WTFMove(port)); + }); +} + +Ref MessagePort::entangle(ScriptExecutionContext& context, TransferredMessagePort&& transferredPort) +{ + auto port = MessagePort::create(context, transferredPort.first, transferredPort.second); + port->entangle(); + return port; +} + +bool MessagePort::addEventListener(const AtomString& eventType, Ref&& listener, const AddEventListenerOptions& options) +{ + if (eventType == eventNames().messageEvent) { + if (listener->isAttribute()) + start(); + m_hasMessageEventListener = true; + } + + return EventTarget::addEventListener(eventType, WTFMove(listener), options); +} + +bool MessagePort::removeEventListener(const AtomString& eventType, EventListener& listener, const EventListenerOptions& options) +{ + auto result = EventTarget::removeEventListener(eventType, listener, options); + + if (!hasEventListeners(eventNames().messageEvent)) + m_hasMessageEventListener = false; + + return result; +} + +// const char* MessagePort::activeDOMObjectName() const +// { +// return "MessagePort"; +// } + +WebCoreOpaqueRoot root(MessagePort* port) +{ + return WebCoreOpaqueRoot { port }; +} + +void MessagePort::jsRef(JSGlobalObject* lexicalGlobalObject) +{ + if (!m_hasRef) { + m_hasRef = true; + Bun__eventLoop__incrementRefConcurrently(WebCore::clientData(lexicalGlobalObject->vm())->bunVM, 1); + } +} + +void MessagePort::jsUnref(JSGlobalObject* lexicalGlobalObject) +{ + if (m_hasRef) { + m_hasRef = false; + Bun__eventLoop__incrementRefConcurrently(WebCore::clientData(lexicalGlobalObject->vm())->bunVM, -1); + } +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePort.h b/src/bun.js/bindings/webcore/MessagePort.h new file mode 100644 index 00000000000000..fe577f93efef3b --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePort.h @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#pragma once + +#include "ActiveDOMObject.h" +#include "EventTarget.h" +#include "ExceptionOr.h" +#include "MessagePortChannel.h" +#include "MessagePortIdentifier.h" +#include "MessageWithMessagePorts.h" +#include + +namespace JSC { +class CallFrame; +class JSObject; +class JSValue; +} + +namespace WebCore { + +class LocalFrame; +class WebCoreOpaqueRoot; + +struct StructuredSerializeOptions; + +class MessagePort final : /* public ActiveDOMObject, */ public ContextDestructionObserver, public EventTarget { + WTF_MAKE_NONCOPYABLE(MessagePort); + WTF_MAKE_ISO_ALLOCATED(MessagePort); + +public: + static Ref create(ScriptExecutionContext&, const MessagePortIdentifier& local, const MessagePortIdentifier& remote); + virtual ~MessagePort(); + + ExceptionOr postMessage(JSC::JSGlobalObject&, JSC::JSValue message, StructuredSerializeOptions&&); + + void start(); + void close(); + void entangle(); + + // Returns nullptr if the passed-in vector is empty. + static ExceptionOr> disentanglePorts(Vector>&&); + static Vector> entanglePorts(ScriptExecutionContext&, Vector&&); + + WEBCORE_EXPORT static bool isMessagePortAliveForTesting(const MessagePortIdentifier&); + WEBCORE_EXPORT static void notifyMessageAvailable(const MessagePortIdentifier&); + + WEBCORE_EXPORT void messageAvailable(); + bool started() const { return m_started; } + bool isDetached() const { return m_isDetached; } + + void dispatchMessages(); + + // Returns null if there is no entangled port, or if the entangled port is run by a different thread. + // This is used solely to enable a GC optimization. Some platforms may not be able to determine ownership + // of the remote port (since it may live cross-process) - those platforms may always return null. + MessagePort* locallyEntangledPort(); + + const MessagePortIdentifier& identifier() const { return m_identifier; } + const MessagePortIdentifier& remoteIdentifier() const { return m_remoteIdentifier; } + + WEBCORE_EXPORT void ref() const; + WEBCORE_EXPORT void deref() const; + + // EventTarget. + EventTargetInterface eventTargetInterface() const final + { + return MessagePortEventTargetInterfaceType; + } + ScriptExecutionContext* scriptExecutionContext() const final { return ScriptExecutionContext::getScriptExecutionContext(contextIdForMessagePortId(m_identifier)); } + void refEventTarget() final { ref(); } + void derefEventTarget() final { deref(); } + + void dispatchEvent(Event&) final; + + JSValue tryTakeMessage(JSGlobalObject*); + + TransferredMessagePort disentangle(); + static Ref entangle(ScriptExecutionContext&, TransferredMessagePort&&); + + bool hasPendingActivity() const; + + static ScriptExecutionContextIdentifier contextIdForMessagePortId(MessagePortIdentifier); + + void jsRef(JSGlobalObject*); + void jsUnref(JSGlobalObject*); + bool jsHasRef() { return m_hasRef; } + +private: + explicit MessagePort(ScriptExecutionContext&, const MessagePortIdentifier& local, const MessagePortIdentifier& remote); + + bool addEventListener(const AtomString& eventType, Ref&&, const AddEventListenerOptions&) final; + bool removeEventListener(const AtomString& eventType, EventListener&, const EventListenerOptions&) final; + + // ActiveDOMObject + // const char* activeDOMObjectName() const final; + // void contextDestroyed() final; + // void stop() final { close(); } + // bool virtualHasPendingActivity() const final; + + EventTargetData* eventTargetData() final { return &m_eventTargetData; } + EventTargetData* eventTargetDataConcurrently() final { return &m_eventTargetData; } + EventTargetData& ensureEventTargetData() final { return m_eventTargetData; } + + EventTargetData m_eventTargetData; + + // A port starts out its life entangled, and remains entangled until it is detached or is cloned. + bool isEntangled() const { return !m_isDetached && m_entangled; } + + bool m_started { false }; + bool m_isDetached { false }; + bool m_entangled { true }; + bool m_hasMessageEventListener { false }; + + MessagePortIdentifier m_identifier; + MessagePortIdentifier m_remoteIdentifier; + + mutable std::atomic m_refCount { 1 }; + + bool m_hasRef { false }; +}; + +WebCoreOpaqueRoot root(MessagePort*); + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannel.cpp b/src/bun.js/bindings/webcore/MessagePortChannel.cpp new file mode 100644 index 00000000000000..03167920488911 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannel.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "MessagePortChannel.h" + +// #include "Logging.h" +#include "MessagePortChannelRegistry.h" +#include +#include + +namespace WebCore { + +Ref MessagePortChannel::create(MessagePortChannelRegistry& registry, const MessagePortIdentifier& port1, const MessagePortIdentifier& port2) +{ + return adoptRef(*new MessagePortChannel(registry, port1, port2)); +} + +MessagePortChannel::MessagePortChannel(MessagePortChannelRegistry& registry, const MessagePortIdentifier& port1, const MessagePortIdentifier& port2) + : m_registry(registry) +{ + relaxAdoptionRequirement(); + + m_ports[0] = port1; + m_processes[0] = port1.processIdentifier; + m_entangledToProcessProtectors[0] = this; + m_ports[1] = port2; + m_processes[1] = port2.processIdentifier; + m_entangledToProcessProtectors[1] = this; + + m_registry.messagePortChannelCreated(*this); +} + +MessagePortChannel::~MessagePortChannel() +{ + m_registry.messagePortChannelDestroyed(*this); +} + +std::optional MessagePortChannel::processForPort(const MessagePortIdentifier& port) +{ + ASSERT(port == m_ports[0] || port == m_ports[1]); + size_t i = port == m_ports[0] ? 0 : 1; + return m_processes[i]; +} + +bool MessagePortChannel::includesPort(const MessagePortIdentifier& port) +{ + return m_ports[0] == port || m_ports[1] == port; +} + +void MessagePortChannel::entanglePortWithProcess(const MessagePortIdentifier& port, ProcessIdentifier process) +{ + ASSERT(port == m_ports[0] || port == m_ports[1]); + size_t i = port == m_ports[0] ? 0 : 1; + + LOG(MessagePorts, "MessagePortChannel %s (%p) entangling port %s (that port has %zu messages available)", logString().utf8().data(), this, port.logString().utf8().data(), m_pendingMessages[i].size()); + + ASSERT(!m_processes[i] || *m_processes[i] == process); + m_processes[i] = process; + m_entangledToProcessProtectors[i] = this; + m_pendingMessagePortTransfers[i].remove(this); +} + +void MessagePortChannel::disentanglePort(const MessagePortIdentifier& port) +{ + LOG(MessagePorts, "MessagePortChannel %s (%p) disentangling port %s", logString().utf8().data(), this, port.logString().utf8().data()); + + ASSERT(port == m_ports[0] || port == m_ports[1]); + size_t i = port == m_ports[0] ? 0 : 1; + + ASSERT(m_processes[i] || m_isClosed[i]); + m_processes[i] = std::nullopt; + m_pendingMessagePortTransfers[i].add(this); + + // This set of steps is to guarantee that the lock is unlocked before the + // last ref to this object is released. + auto protectedThis = WTFMove(m_entangledToProcessProtectors[i]); +} + +void MessagePortChannel::closePort(const MessagePortIdentifier& port) +{ + ASSERT(port == m_ports[0] || port == m_ports[1]); + size_t i = port == m_ports[0] ? 0 : 1; + + m_processes[i] = std::nullopt; + m_isClosed[i] = true; + + // This set of steps is to guarantee that the lock is unlocked before the + // last ref to this object is released. + Ref protectedThis { *this }; + + m_pendingMessages[i].clear(); + m_pendingMessagePortTransfers[i].clear(); + m_pendingMessageProtectors[i] = nullptr; + m_entangledToProcessProtectors[i] = nullptr; +} + +bool MessagePortChannel::postMessageToRemote(MessageWithMessagePorts&& message, const MessagePortIdentifier& remoteTarget) +{ + ASSERT(remoteTarget == m_ports[0] || remoteTarget == m_ports[1]); + size_t i = remoteTarget == m_ports[0] ? 0 : 1; + + m_pendingMessages[i].append(WTFMove(message)); + LOG(MessagePorts, "MessagePortChannel %s (%p) now has %zu messages pending on port %s", logString().utf8().data(), this, m_pendingMessages[i].size(), remoteTarget.logString().utf8().data()); + + if (m_pendingMessages[i].size() == 1) { + m_pendingMessageProtectors[i] = this; + return true; + } + + ASSERT(m_pendingMessageProtectors[i] == this); + return false; +} + +void MessagePortChannel::takeAllMessagesForPort(const MessagePortIdentifier& port, CompletionHandler&&, CompletionHandler&&)>&& callback) +{ + LOG(MessagePorts, "MessagePortChannel %p taking all messages for port %s", this, port.logString().utf8().data()); + + ASSERT(port == m_ports[0] || port == m_ports[1]); + size_t i = port == m_ports[0] ? 0 : 1; + + if (m_pendingMessages[i].isEmpty()) { + callback({}, [] {}); + return; + } + + ASSERT(m_pendingMessageProtectors[i]); + + Vector result; + result.swap(m_pendingMessages[i]); + + ++m_messageBatchesInFlight; + + LOG(MessagePorts, "There are %zu messages to take for port %s. Taking them now, messages in flight is now %" PRIu64, result.size(), port.logString().utf8().data(), m_messageBatchesInFlight); + + auto size = result.size(); + callback(WTFMove(result), [size, this, port, protectedThis = WTFMove(m_pendingMessageProtectors[i])] { + UNUSED_PARAM(port); +#if LOG_DISABLED + UNUSED_PARAM(size); +#endif + --m_messageBatchesInFlight; + LOG(MessagePorts, "Message port channel %s was notified that a batch of %zu message port messages targeted for port %s just completed dispatch, in flight is now %" PRIu64, logString().utf8().data(), size, port.logString().utf8().data(), m_messageBatchesInFlight); + }); +} + +std::optional MessagePortChannel::tryTakeMessageForPort(const MessagePortIdentifier port) +{ + ASSERT(port == m_ports[0] || port == m_ports[1]); + size_t i = port == m_ports[0] ? 0 : 1; + + if (m_pendingMessages[i].isEmpty()) + return std::nullopt; + + auto message = m_pendingMessages[i].first(); + m_pendingMessages[i].remove(0); + return WTFMove(message); +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannel.h b/src/bun.js/bindings/webcore/MessagePortChannel.h new file mode 100644 index 00000000000000..ebe27fd5893be3 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannel.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "MessagePortChannelProvider.h" +#include "MessagePortIdentifier.h" +#include "MessageWithMessagePorts.h" +#include "ProcessIdentifier.h" +#include +#include +#include + +namespace WebCore { + +class MessagePortChannelRegistry; + +class MessagePortChannel : public RefCounted { +public: + static Ref create(MessagePortChannelRegistry&, const MessagePortIdentifier& port1, const MessagePortIdentifier& port2); + + ~MessagePortChannel(); + + const MessagePortIdentifier& port1() const { return m_ports[0]; } + const MessagePortIdentifier& port2() const { return m_ports[1]; } + + WEBCORE_EXPORT std::optional processForPort(const MessagePortIdentifier&); + bool includesPort(const MessagePortIdentifier&); + void entanglePortWithProcess(const MessagePortIdentifier&, ProcessIdentifier); + void disentanglePort(const MessagePortIdentifier&); + void closePort(const MessagePortIdentifier&); + bool postMessageToRemote(MessageWithMessagePorts&&, const MessagePortIdentifier& remoteTarget); + + void takeAllMessagesForPort(const MessagePortIdentifier&, CompletionHandler&&, CompletionHandler&&)>&&); + std::optional tryTakeMessageForPort(const MessagePortIdentifier); + + WEBCORE_EXPORT bool hasAnyMessagesPendingOrInFlight() const; + + uint64_t beingTransferredCount(); + +#if !LOG_DISABLED + String logString() const + { + return makeString(m_ports[0].logString(), ":", m_ports[1].logString()); + } +#endif + +private: + MessagePortChannel(MessagePortChannelRegistry&, const MessagePortIdentifier& port1, const MessagePortIdentifier& port2); + + MessagePortIdentifier m_ports[2]; + bool m_isClosed[2] { false, false }; + std::optional m_processes[2]; + RefPtr m_entangledToProcessProtectors[2]; + Vector m_pendingMessages[2]; + HashSet> m_pendingMessagePortTransfers[2]; + RefPtr m_pendingMessageProtectors[2]; + uint64_t m_messageBatchesInFlight { 0 }; + + MessagePortChannelRegistry& m_registry; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannelProvider.cpp b/src/bun.js/bindings/webcore/MessagePortChannelProvider.cpp new file mode 100644 index 00000000000000..7675a2e7504d59 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannelProvider.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +// #include "MessagePortChannelProvider.h" + +// #include "Document.h" +#include "MessagePortChannelProviderImpl.h" +// #include "WorkerGlobalScope.h" +// #include "WorkletGlobalScope.h" +#include + +namespace WebCore { + +static MessagePortChannelProviderImpl* globalProvider; + +MessagePortChannelProvider& MessagePortChannelProvider::singleton() +{ + ASSERT(isMainThread()); + static std::once_flag onceFlag; + std::call_once(onceFlag, [] { + if (!globalProvider) + globalProvider = new MessagePortChannelProviderImpl; + }); + + return *globalProvider; +} + +// void MessagePortChannelProvider::setSharedProvider(MessagePortChannelProvider& provider) +// { +// RELEASE_ASSERT(isMainThread()); +// RELEASE_ASSERT(!globalProvider); +// globalProvider = &provider; +// } + +MessagePortChannelProvider& MessagePortChannelProvider::fromContext(ScriptExecutionContext& context) +{ + // if (auto document = dynamicDowncast(context)) + // return document->messagePortChannelProvider(); + + // if (auto workletScope = dynamicDowncast(context)) + // return workletScope->messagePortChannelProvider(); + + return jsCast(context.jsGlobalObject())->globalEventScope.messagePortChannelProvider(); +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannelProvider.h b/src/bun.js/bindings/webcore/MessagePortChannelProvider.h new file mode 100644 index 00000000000000..26ddfd460c1db3 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannelProvider.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "ProcessIdentifier.h" +#include "BunWorkerGlobalScope.h" +#include "MessageWithMessagePorts.h" +#include +#include + +namespace WebCore { + +class ScriptExecutionContext; +struct MessagePortIdentifier; +struct MessageWithMessagePorts; + +class MessagePortChannelProvider { +public: + static MessagePortChannelProvider& fromContext(ScriptExecutionContext&); + static MessagePortChannelProvider& singleton(); + // WEBCORE_EXPORT static void setSharedProvider(MessagePortChannelProvider&); + + virtual ~MessagePortChannelProvider() {} + + // Operations that WebProcesses perform + virtual void createNewMessagePortChannel(const MessagePortIdentifier& local, const MessagePortIdentifier& remote) = 0; + virtual void entangleLocalPortInThisProcessToRemote(const MessagePortIdentifier& local, const MessagePortIdentifier& remote) = 0; + virtual void messagePortDisentangled(const MessagePortIdentifier& local) = 0; + virtual void messagePortClosed(const MessagePortIdentifier& local) = 0; + + virtual void takeAllMessagesForPort(const MessagePortIdentifier&, CompletionHandler&&, CompletionHandler&&)>&&) = 0; + virtual std::optional tryTakeMessageForPort(const MessagePortIdentifier&) = 0; + + virtual void postMessageToRemote(MessageWithMessagePorts&&, const MessagePortIdentifier& remoteTarget) = 0; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannelProviderImpl.cpp b/src/bun.js/bindings/webcore/MessagePortChannelProviderImpl.cpp new file mode 100644 index 00000000000000..4fc0dddc56b347 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannelProviderImpl.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "MessagePortChannelProviderImpl.h" + +#include "MessagePort.h" +#include +#include + +namespace WebCore { + +MessagePortChannelProviderImpl::MessagePortChannelProviderImpl() +{ +} + +MessagePortChannelProviderImpl::~MessagePortChannelProviderImpl() +{ + ASSERT_NOT_REACHED(); +} + +void MessagePortChannelProviderImpl::createNewMessagePortChannel(const MessagePortIdentifier& local, const MessagePortIdentifier& remote) +{ + m_registry.didCreateMessagePortChannel(local, remote); +} + +void MessagePortChannelProviderImpl::entangleLocalPortInThisProcessToRemote(const MessagePortIdentifier& local, const MessagePortIdentifier& remote) +{ + m_registry.didEntangleLocalToRemote(local, remote, ProcessIdent::identifier()); +} + +void MessagePortChannelProviderImpl::messagePortDisentangled(const MessagePortIdentifier& local) +{ + m_registry.didDisentangleMessagePort(local); +} + +void MessagePortChannelProviderImpl::messagePortClosed(const MessagePortIdentifier& local) +{ + m_registry.didCloseMessagePort(local); +} + +void MessagePortChannelProviderImpl::postMessageToRemote(MessageWithMessagePorts&& message, const MessagePortIdentifier& remoteTarget) +{ + if (m_registry.didPostMessageToRemote(WTFMove(message), remoteTarget)) + MessagePort::notifyMessageAvailable(remoteTarget); +} + +void MessagePortChannelProviderImpl::takeAllMessagesForPort(const MessagePortIdentifier& port, CompletionHandler&&, CompletionHandler&&)>&& outerCallback) +{ + // It is the responsibility of outerCallback to get itself to the appropriate thread (e.g. WebWorker thread) + auto callback = [outerCallback = WTFMove(outerCallback)](Vector&& messages, CompletionHandler&& messageDeliveryCallback) mutable { + ASSERT(isMainThread()); + outerCallback(WTFMove(messages), WTFMove(messageDeliveryCallback)); + }; + + m_registry.takeAllMessagesForPort(port, WTFMove(callback)); +} + +std::optional MessagePortChannelProviderImpl::tryTakeMessageForPort(const MessagePortIdentifier& port) +{ + return m_registry.tryTakeMessageForPort(port); +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannelProviderImpl.h b/src/bun.js/bindings/webcore/MessagePortChannelProviderImpl.h new file mode 100644 index 00000000000000..17429b0d5e6ffb --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannelProviderImpl.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "MessagePortChannelProvider.h" +#include "MessagePortChannelRegistry.h" +#include "MessageWithMessagePorts.h" + +namespace WebCore { + +class MessagePortChannelProviderImpl final : public MessagePortChannelProvider { +public: + MessagePortChannelProviderImpl(); + ~MessagePortChannelProviderImpl() final; + +private: + void createNewMessagePortChannel(const MessagePortIdentifier& local, const MessagePortIdentifier& remote) final; + void entangleLocalPortInThisProcessToRemote(const MessagePortIdentifier& local, const MessagePortIdentifier& remote) final; + void messagePortDisentangled(const MessagePortIdentifier& local) final; + void messagePortClosed(const MessagePortIdentifier& local) final; + void postMessageToRemote(MessageWithMessagePorts&&, const MessagePortIdentifier& remoteTarget) final; + void takeAllMessagesForPort(const MessagePortIdentifier&, CompletionHandler&&, CompletionHandler&&)>&&) final; + std::optional tryTakeMessageForPort(const MessagePortIdentifier&) final; + + MessagePortChannelRegistry m_registry; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannelRegistry.cpp b/src/bun.js/bindings/webcore/MessagePortChannelRegistry.cpp new file mode 100644 index 00000000000000..5096357f208733 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannelRegistry.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "MessagePortChannelRegistry.h" + +// #include "Logging.h" +#include +#include + +namespace WebCore { + +MessagePortChannelRegistry::MessagePortChannelRegistry() = default; + +MessagePortChannelRegistry::~MessagePortChannelRegistry() +{ + ASSERT(m_openChannels.isEmpty()); +} + +void MessagePortChannelRegistry::didCreateMessagePortChannel(const MessagePortIdentifier& port1, const MessagePortIdentifier& port2) +{ + LOG(MessagePorts, "Registry: Creating MessagePortChannel %p linking %s and %s", this, port1.logString().utf8().data(), port2.logString().utf8().data()); + ASSERT(isMainThread()); + + MessagePortChannel::create(*this, port1, port2); +} + +void MessagePortChannelRegistry::messagePortChannelCreated(MessagePortChannel& channel) +{ + ASSERT(isMainThread()); + + auto result = m_openChannels.ensure(channel.port1(), [channel = &channel] { + return channel; + }); + ASSERT(result.isNewEntry); + + result = m_openChannels.ensure(channel.port2(), [channel = &channel] { + return channel; + }); + ASSERT(result.isNewEntry); +} + +void MessagePortChannelRegistry::messagePortChannelDestroyed(MessagePortChannel& channel) +{ + ASSERT(isMainThread()); + + ASSERT(m_openChannels.get(channel.port1()) == &channel); + ASSERT(m_openChannels.get(channel.port2()) == &channel); + + m_openChannels.remove(channel.port1()); + m_openChannels.remove(channel.port2()); + + LOG(MessagePorts, "Registry: After removing channel %s there are %u channels left in the registry:", channel.logString().utf8().data(), m_openChannels.size()); +} + +void MessagePortChannelRegistry::didEntangleLocalToRemote(const MessagePortIdentifier& local, const MessagePortIdentifier& remote, ProcessIdentifier process) +{ + ASSERT(isMainThread()); + + // The channel might be gone if the remote side was closed. + auto* channel = m_openChannels.get(local); + if (!channel) + return; + + ASSERT_UNUSED(remote, channel->includesPort(remote)); + + channel->entanglePortWithProcess(local, process); +} + +void MessagePortChannelRegistry::didDisentangleMessagePort(const MessagePortIdentifier& port) +{ + ASSERT(isMainThread()); + + // The channel might be gone if the remote side was closed. + auto* channel = m_openChannels.get(port); + if (!channel) + return; + + channel->disentanglePort(port); +} + +void MessagePortChannelRegistry::didCloseMessagePort(const MessagePortIdentifier& port) +{ + ASSERT(isMainThread()); + + LOG(MessagePorts, "Registry: MessagePort %s closed in registry", port.logString().utf8().data()); + + auto* channel = m_openChannels.get(port); + if (!channel) + return; + +#ifndef NDEBUG + if (channel && channel->hasAnyMessagesPendingOrInFlight()) + LOG(MessagePorts, "Registry: (Note) The channel closed for port %s had messages pending or in flight", port.logString().utf8().data()); +#endif + + channel->closePort(port); + + // FIXME: When making message ports be multi-process, this should probably push a notification + // to the remaining port to tell it this port closed. +} + +bool MessagePortChannelRegistry::didPostMessageToRemote(MessageWithMessagePorts&& message, const MessagePortIdentifier& remoteTarget) +{ + ASSERT(isMainThread()); + + LOG(MessagePorts, "Registry: Posting message to MessagePort %s in registry", remoteTarget.logString().utf8().data()); + + // The channel might be gone if the remote side was closed. + auto* channel = m_openChannels.get(remoteTarget); + if (!channel) { + LOG(MessagePorts, "Registry: Could not find MessagePortChannel for port %s; It was probably closed. Message will be dropped.", remoteTarget.logString().utf8().data()); + return false; + } + + return channel->postMessageToRemote(WTFMove(message), remoteTarget); +} + +void MessagePortChannelRegistry::takeAllMessagesForPort(const MessagePortIdentifier& port, CompletionHandler&&, CompletionHandler&&)>&& callback) +{ + ASSERT(isMainThread()); + + LOG(MessagePorts, "Registry: Taking all messages for MessagePort %s", port.logString().utf8().data()); + + // The channel might be gone if the remote side was closed. + auto* channel = m_openChannels.get(port); + if (!channel) { + callback({}, [] {}); + return; + } + + channel->takeAllMessagesForPort(port, WTFMove(callback)); +} + +std::optional MessagePortChannelRegistry::tryTakeMessageForPort(const MessagePortIdentifier& port) +{ + ASSERT(isMainThread()); + + LOG(MessagePorts, "Registry: Trying to take a message for MessagePort %s", port.logString().utf8().data()); + + // The channel might be gone if the remote side was closed. + auto* channel = m_openChannels.get(port); + if (!channel) + return std::nullopt; + + return channel->tryTakeMessageForPort(port); +} + +MessagePortChannel* MessagePortChannelRegistry::existingChannelContainingPort(const MessagePortIdentifier& port) +{ + ASSERT(isMainThread()); + + return m_openChannels.get(port); +} + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortChannelRegistry.h b/src/bun.js/bindings/webcore/MessagePortChannelRegistry.h new file mode 100644 index 00000000000000..43880ea913e4f5 --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortChannelRegistry.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "MessagePortChannel.h" +#include "MessagePortChannelProvider.h" +#include "MessagePortIdentifier.h" +#include "ProcessIdentifier.h" +#include + +namespace WebCore { + +class MessagePortChannelRegistry { +public: + WEBCORE_EXPORT MessagePortChannelRegistry(); + + WEBCORE_EXPORT ~MessagePortChannelRegistry(); + + WEBCORE_EXPORT void didCreateMessagePortChannel(const MessagePortIdentifier& port1, const MessagePortIdentifier& port2); + WEBCORE_EXPORT void didEntangleLocalToRemote(const MessagePortIdentifier& local, const MessagePortIdentifier& remote, ProcessIdentifier); + WEBCORE_EXPORT void didDisentangleMessagePort(const MessagePortIdentifier& local); + WEBCORE_EXPORT void didCloseMessagePort(const MessagePortIdentifier& local); + WEBCORE_EXPORT bool didPostMessageToRemote(MessageWithMessagePorts&&, const MessagePortIdentifier& remoteTarget); + WEBCORE_EXPORT void takeAllMessagesForPort(const MessagePortIdentifier&, CompletionHandler&&, CompletionHandler&&)>&&); + WEBCORE_EXPORT std::optional tryTakeMessageForPort(const MessagePortIdentifier&); + + WEBCORE_EXPORT MessagePortChannel* existingChannelContainingPort(const MessagePortIdentifier&); + + WEBCORE_EXPORT void messagePortChannelCreated(MessagePortChannel&); + WEBCORE_EXPORT void messagePortChannelDestroyed(MessagePortChannel&); + +private: + HashMap m_openChannels; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/MessagePortIdentifier.h b/src/bun.js/bindings/webcore/MessagePortIdentifier.h new file mode 100644 index 00000000000000..eac8546de6ac2e --- /dev/null +++ b/src/bun.js/bindings/webcore/MessagePortIdentifier.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "PortIdentifier.h" +#include "ProcessIdentifier.h" +#include +#include + +namespace WebCore { + +struct MessagePortIdentifier { + ProcessIdentifier processIdentifier; + PortIdentifier portIdentifier; + +#if !LOG_DISABLED + String logString() const; +#endif +}; + +inline void add(Hasher& hasher, const MessagePortIdentifier& identifier) +{ + add(hasher, identifier.processIdentifier, identifier.portIdentifier); +} + +inline bool operator==(const MessagePortIdentifier& a, const MessagePortIdentifier& b) +{ + return a.processIdentifier == b.processIdentifier && a.portIdentifier == b.portIdentifier; +} + +#if !LOG_DISABLED + +inline String MessagePortIdentifier::logString() const +{ + return makeString(processIdentifier.toUInt64(), '-', portIdentifier.toUInt64()); +} + +#endif + +} // namespace WebCore + +namespace WTF { + +struct MessagePortIdentifierHash { + static unsigned hash(const WebCore::MessagePortIdentifier& key) { return computeHash(key); } + static bool equal(const WebCore::MessagePortIdentifier& a, const WebCore::MessagePortIdentifier& b) { return a == b; } + static const bool safeToCompareToEmptyOrDeleted = true; +}; + +template<> struct HashTraits : GenericHashTraits { + static WebCore::MessagePortIdentifier emptyValue() { return {}; } + + static void constructDeletedValue(WebCore::MessagePortIdentifier& slot) { new (NotNull, &slot.processIdentifier) WebCore::ProcessIdentifier(WTF::HashTableDeletedValue); } + + static bool isDeletedValue(const WebCore::MessagePortIdentifier& slot) { return slot.processIdentifier.isHashTableDeletedValue(); } +}; + +template<> struct DefaultHash : MessagePortIdentifierHash {}; + +} // namespace WTF diff --git a/src/bun.js/bindings/webcore/MessageWithMessagePorts.h b/src/bun.js/bindings/webcore/MessageWithMessagePorts.h new file mode 100644 index 00000000000000..a986bfb4c9efaf --- /dev/null +++ b/src/bun.js/bindings/webcore/MessageWithMessagePorts.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2018 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "SerializedScriptValue.h" +#include "TransferredMessagePort.h" +#include + +namespace WebCore { + +struct MessageWithMessagePorts { + RefPtr message; + Vector transferredPorts; +}; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/ParsedContentType.cpp b/src/bun.js/bindings/webcore/ParsedContentType.cpp index c4773b3ee91693..38e0f532c17d03 100644 --- a/src/bun.js/bindings/webcore/ParsedContentType.cpp +++ b/src/bun.js/bindings/webcore/ParsedContentType.cpp @@ -40,7 +40,7 @@ namespace WebCore { static void skipSpaces(StringView input, unsigned& startIndex) { - while (startIndex < input.length() && isJSONOrHTTPWhitespace(input[startIndex])) + while (startIndex < input.length() && isASCIIWhitespaceWithoutFF(input[startIndex])) ++startIndex; } @@ -78,7 +78,7 @@ static StringView parseToken(StringView input, unsigned& startIndex, CharacterMe while (input[tokenEnd - 1] == ' ') --tokenEnd; } else { - while (isJSONOrHTTPWhitespace(input[tokenEnd - 1])) + while (isASCIIWhitespaceWithoutFF(input[tokenEnd - 1])) --tokenEnd; } } @@ -328,7 +328,7 @@ bool ParsedContentType::parseContentType(Mode mode) std::optional ParsedContentType::create(const String& contentType, Mode mode) { - ParsedContentType parsedContentType(mode == Mode::Rfc2045 ? contentType : contentType.trim(isJSONOrHTTPWhitespace)); + ParsedContentType parsedContentType(mode == Mode::Rfc2045 ? contentType : contentType.trim(isASCIIWhitespaceWithoutFF)); if (!parsedContentType.parseContentType(mode)) return std::nullopt; return { WTFMove(parsedContentType) }; @@ -368,7 +368,7 @@ void ParsedContentType::setContentType(String&& contentRange, Mode mode) { m_mimeType = WTFMove(contentRange); if (mode == Mode::MimeSniff) - m_mimeType = StringView(m_mimeType).trim(isJSONOrHTTPWhitespace).convertToASCIILowercase(); + m_mimeType = StringView(m_mimeType).trim(isASCIIWhitespaceWithoutFF).convertToASCIILowercase(); else m_mimeType = m_mimeType.trim(deprecatedIsSpaceOrNewline); } diff --git a/src/bun.js/bindings/webcore/PortIdentifier.h b/src/bun.js/bindings/webcore/PortIdentifier.h new file mode 100644 index 00000000000000..8b77e792ebc93c --- /dev/null +++ b/src/bun.js/bindings/webcore/PortIdentifier.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2023 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "ProcessIdentifier.h" + +namespace WebCore { + +enum PortIdentifierType {}; +using PortIdentifier = AtomicObjectIdentifier; + +} diff --git a/src/bun.js/bindings/webcore/SerializedScriptValue.cpp b/src/bun.js/bindings/webcore/SerializedScriptValue.cpp index e80bc9493601cb..9b9f04aa8a89ae 100644 --- a/src/bun.js/bindings/webcore/SerializedScriptValue.cpp +++ b/src/bun.js/bindings/webcore/SerializedScriptValue.cpp @@ -38,6 +38,7 @@ #include "CryptoKeyRaw.h" // #include "IDBValue.h" // #include "ImageBitmapBacking.h" +// #include "JSAudioWorkletGlobalScope.h" // #include "JSBlob.h" #include "JSCryptoKey.h" #include "JSDOMBinding.h" @@ -54,7 +55,7 @@ // #include "JSIDBSerializationGlobalObject.h" // #include "JSImageBitmap.h" // #include "JSImageData.h" -// #include "JSMessagePort.h" +#include "JSMessagePort.h" // #include "JSNavigator.h" // #include "JSRTCCertificate.h" // #include "JSRTCDataChannel.h" @@ -70,6 +71,7 @@ #include #include #include +#include #include #include #include @@ -227,6 +229,7 @@ enum SerializationTag { WebCodecsVideoFrameTag = 53, #endif ResizableArrayBufferTag = 54, + ErrorInstanceTag = 55, Bun__BlobTag = 254, // bun types start at 254 and decrease with each addition @@ -249,6 +252,95 @@ enum ArrayBufferViewSubtag { BigUint64ArrayTag = 11, }; +// static bool isTypeExposedToGlobalObject(JSC::JSGlobalObject& globalObject, SerializationTag tag) +// { +// #if ENABLE(WEB_AUDIO) +// if (!jsDynamicCast(&globalObject)) +// return true; + +// // Only built-in JS types are exposed to audio worklets. +// switch (tag) { +// case ArrayTag: +// case ObjectTag: +// case UndefinedTag: +// case NullTag: +// case IntTag: +// case ZeroTag: +// case OneTag: +// case FalseTag: +// case TrueTag: +// case DoubleTag: +// case DateTag: +// case StringTag: +// case EmptyStringTag: +// case RegExpTag: +// case ObjectReferenceTag: +// case ArrayBufferTag: +// case ArrayBufferViewTag: +// case ArrayBufferTransferTag: +// case TrueObjectTag: +// case FalseObjectTag: +// case StringObjectTag: +// case EmptyStringObjectTag: +// case NumberObjectTag: +// case SetObjectTag: +// case MapObjectTag: +// case NonMapPropertiesTag: +// case NonSetPropertiesTag: +// case SharedArrayBufferTag: +// #if ENABLE(WEBASSEMBLY) +// case WasmModuleTag: +// #endif +// case BigIntTag: +// case BigIntObjectTag: +// #if ENABLE(WEBASSEMBLY) +// case WasmMemoryTag: +// #endif +// case ResizableArrayBufferTag: +// case ErrorInstanceTag: +// case ErrorTag: +// case MessagePortReferenceTag: +// return true; +// case FileTag: +// case FileListTag: +// case ImageDataTag: +// case BlobTag: +// #if ENABLE(WEB_CRYPTO) +// case CryptoKeyTag: +// #endif +// case DOMPointReadOnlyTag: +// case DOMPointTag: +// case DOMRectReadOnlyTag: +// case DOMRectTag: +// case DOMMatrixReadOnlyTag: +// case DOMMatrixTag: +// case DOMQuadTag: +// case ImageBitmapTransferTag: +// #if ENABLE(WEB_RTC) +// case RTCCertificateTag: +// #endif +// case ImageBitmapTag: +// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) +// case OffscreenCanvasTransferTag: +// #endif +// #if ENABLE(WEB_RTC) +// case RTCDataChannelTransferTag: +// #endif +// case DOMExceptionTag: +// #if ENABLE(WEB_CODECS) +// case WebCodecsEncodedVideoChunkTag: +// case WebCodecsVideoFrameTag: +// #endif +// break; +// } +// return false; +// #else +// UNUSED_PARAM(globalObject); +// UNUSED_PARAM(tag); +// return true; +// #endif +// } + static unsigned typedArrayElementSize(ArrayBufferViewSubtag tag) { switch (tag) { @@ -273,6 +365,55 @@ static unsigned typedArrayElementSize(ArrayBufferViewSubtag tag) } } +enum class SerializableErrorType : uint8_t { + Error, + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError, + Last = URIError +}; + +static SerializableErrorType errorNameToSerializableErrorType(const String& name) +{ + if (equalLettersIgnoringASCIICase(name, "evalerror"_s)) + return SerializableErrorType::EvalError; + if (equalLettersIgnoringASCIICase(name, "rangeerror"_s)) + return SerializableErrorType::RangeError; + if (equalLettersIgnoringASCIICase(name, "referenceerror"_s)) + return SerializableErrorType::ReferenceError; + if (equalLettersIgnoringASCIICase(name, "syntaxerror"_s)) + return SerializableErrorType::SyntaxError; + if (equalLettersIgnoringASCIICase(name, "typeerror"_s)) + return SerializableErrorType::TypeError; + if (equalLettersIgnoringASCIICase(name, "urierror"_s)) + return SerializableErrorType::URIError; + return SerializableErrorType::Error; +} + +static ErrorType toErrorType(SerializableErrorType value) +{ + switch (value) { + case SerializableErrorType::Error: + return ErrorType::Error; + case SerializableErrorType::EvalError: + return ErrorType::EvalError; + case SerializableErrorType::RangeError: + return ErrorType::RangeError; + case SerializableErrorType::ReferenceError: + return ErrorType::ReferenceError; + case SerializableErrorType::SyntaxError: + return ErrorType::SyntaxError; + case SerializableErrorType::TypeError: + return ErrorType::TypeError; + case SerializableErrorType::URIError: + return ErrorType::URIError; + } + return ErrorType::Error; +} + enum class PredefinedColorSpaceTag : uint8_t { SRGB = 0 #if ENABLE(PREDEFINED_COLOR_SPACE_DISPLAY_P3) @@ -396,14 +537,16 @@ const uint8_t cryptoKeyOKPOpNameTagMaximumValue = 1; * Version 10. changed the length (and offsets) of ArrayBuffers (and ArrayBufferViews) from 32 to 64 bits. * Version 11. added support for Blob's memory cost. * Version 12. added support for agent cluster ID. + * Version 13. added support for ErrorInstance objects. */ -static const unsigned CurrentVersion = 12; -static const unsigned TerminatorTag = 0xFFFFFFFF; -static const unsigned StringPoolTag = 0xFFFFFFFE; -static const unsigned NonIndexPropertiesTag = 0xFFFFFFFD; +static constexpr unsigned CurrentVersion = 13; +static constexpr unsigned TerminatorTag = 0xFFFFFFFF; +static constexpr unsigned StringPoolTag = 0xFFFFFFFE; +static constexpr unsigned NonIndexPropertiesTag = 0xFFFFFFFD; +static constexpr uint32_t ImageDataPoolTag = 0xFFFFFFFE; // The high bit of a StringData's length determines the character size. -static const unsigned StringDataIs8BitFlag = 0x80000000; +static constexpr unsigned StringDataIs8BitFlag = 0x80000000; /* * Object serialization is performed according to the following grammar, all tags @@ -715,7 +858,7 @@ class CloneSerializer : CloneBase { // return serializer.serialize(value); // } - static SerializationReturnCode serialize(JSGlobalObject* lexicalGlobalObject, JSValue value, Vector>& arrayBuffers, + static SerializationReturnCode serialize(JSGlobalObject* lexicalGlobalObject, JSValue value, Vector>& messagePorts, Vector>& arrayBuffers, #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) const Vector>& offscreenCanvases, #endif @@ -733,7 +876,7 @@ class CloneSerializer : CloneBase { Vector& out, SerializationContext context, ArrayBufferContentsArray& sharedBuffers, SerializationForStorage forStorage) { - CloneSerializer serializer(lexicalGlobalObject, arrayBuffers, + CloneSerializer serializer(lexicalGlobalObject, messagePorts, arrayBuffers, #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) offscreenCanvases, #endif @@ -815,7 +958,7 @@ class CloneSerializer : CloneBase { // #endif // } - CloneSerializer(JSGlobalObject* lexicalGlobalObject, Vector>& arrayBuffers, + CloneSerializer(JSGlobalObject* lexicalGlobalObject, Vector>& messagePorts, Vector>& arrayBuffers, #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) const Vector>& offscreenCanvases, #endif @@ -847,6 +990,7 @@ class CloneSerializer : CloneBase { , m_forStorage(forStorage) { write(CurrentVersion); + fillTransferMap(messagePorts, m_transferredMessagePorts); fillTransferMap(arrayBuffers, m_transferredArrayBuffers); #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) fillTransferMap(offscreenCanvases, m_transferredOffscreenCanvases); @@ -1483,8 +1627,14 @@ class CloneSerializer : CloneBase { // } // if (auto* data = JSImageData::toWrapped(vm, obj)) { // write(ImageDataTag); - // write(data->width()); - // write(data->height()); + // auto addResult = m_imageDataPool.add(*data, m_imageDataPool.size()); + // if (!addResult.isNewEntry) { + // write(ImageDataPoolTag); + // writeImageDataIndex(addResult.iterator->value); + // return true; + // } + // write(static_cast(data->width())); + // write(static_cast(data->height())); // CheckedUint32 dataLength = data->data().length(); // if (dataLength.hasOverflowed()) { // code = SerializationReturnCode::DataCloneError; @@ -1501,17 +1651,74 @@ class CloneSerializer : CloneBase { write(String::fromLatin1(JSC::Yarr::flagsString(regExp->regExp()->flags()).data())); return true; } - // if (obj->inherits()) { - // auto index = m_transferredMessagePorts.find(obj); - // if (index != m_transferredMessagePorts.end()) { - // write(MessagePortReferenceTag); - // write(index->value); - // return true; - // } - // // MessagePort object could not be found in transferred message ports - // code = SerializationReturnCode::ValidationError; - // return true; - // } + if (auto* errorInstance = jsDynamicCast(obj)) { + auto& vm = m_lexicalGlobalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + auto errorTypeValue = errorInstance->get(m_lexicalGlobalObject, vm.propertyNames->name); + RETURN_IF_EXCEPTION(scope, false); + auto errorTypeString = errorTypeValue.toWTFString(m_lexicalGlobalObject); + RETURN_IF_EXCEPTION(scope, false); + + String message; + PropertyDescriptor messageDescriptor; + if (errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->message, messageDescriptor) && messageDescriptor.isDataDescriptor()) { + EXCEPTION_ASSERT(!scope.exception()); + message = messageDescriptor.value().toWTFString(m_lexicalGlobalObject); + } + RETURN_IF_EXCEPTION(scope, false); + + unsigned line = 0; + PropertyDescriptor lineDescriptor; + if (errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->line, lineDescriptor) && lineDescriptor.isDataDescriptor()) { + EXCEPTION_ASSERT(!scope.exception()); + line = lineDescriptor.value().toNumber(m_lexicalGlobalObject); + } + RETURN_IF_EXCEPTION(scope, false); + + unsigned column = 0; + PropertyDescriptor columnDescriptor; + if (errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->column, columnDescriptor) && columnDescriptor.isDataDescriptor()) { + EXCEPTION_ASSERT(!scope.exception()); + column = columnDescriptor.value().toNumber(m_lexicalGlobalObject); + } + RETURN_IF_EXCEPTION(scope, false); + + String sourceURL; + PropertyDescriptor sourceURLDescriptor; + if (errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->sourceURL, sourceURLDescriptor) && sourceURLDescriptor.isDataDescriptor()) { + EXCEPTION_ASSERT(!scope.exception()); + sourceURL = sourceURLDescriptor.value().toWTFString(m_lexicalGlobalObject); + } + RETURN_IF_EXCEPTION(scope, false); + + String stack; + PropertyDescriptor stackDescriptor; + if (errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->stack, stackDescriptor) && stackDescriptor.isDataDescriptor()) { + EXCEPTION_ASSERT(!scope.exception()); + stack = stackDescriptor.value().toWTFString(m_lexicalGlobalObject); + } + RETURN_IF_EXCEPTION(scope, false); + + write(ErrorInstanceTag); + write(errorNameToSerializableErrorType(errorTypeString)); + writeNullableString(message); + write(line); + write(column); + writeNullableString(sourceURL); + writeNullableString(stack); + return true; + } + if (obj->inherits()) { + auto index = m_transferredMessagePorts.find(obj); + if (index != m_transferredMessagePorts.end()) { + write(MessagePortReferenceTag); + write(index->value); + return true; + } + // MessagePort object could not be found in transferred message ports + code = SerializationReturnCode::ValidationError; + return true; + } if (auto* arrayBuffer = toPossiblySharedArrayBuffer(vm, obj)) { if (arrayBuffer->isDetached()) { code = SerializationReturnCode::ValidationError; @@ -1570,7 +1777,7 @@ class CloneSerializer : CloneBase { write(CryptoKeyTag); Vector serializedKey; // Vector dummyBlobHandles; - // Vector> dummyMessagePorts; + Vector> dummyMessagePorts; Vector> dummyArrayBuffers; #if ENABLE(WEB_CODECS) Vector> dummyVideoChunks; @@ -1597,7 +1804,7 @@ class CloneSerializer : CloneBase { // dummyMemoryHandles, // #endif // dummyBlobHandles, serializedKey, SerializationContext::Default, dummySharedBuffers, m_forStorage); - CloneSerializer rawKeySerializer(m_lexicalGlobalObject, dummyArrayBuffers, + CloneSerializer rawKeySerializer(m_lexicalGlobalObject, dummyMessagePorts, dummyArrayBuffers, #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) {}, #endif @@ -1764,6 +1971,11 @@ class CloneSerializer : CloneBase { } #endif + void write(bool b) + { + writeLittleEndian(m_buffer, static_cast(b)); + } + void write(uint8_t c) { writeLittleEndian(m_buffer, c); @@ -1804,6 +2016,11 @@ class CloneSerializer : CloneBase { writeConstantPoolIndex(m_constantPool, i); } + // void writeImageDataIndex(unsigned i) + // { + // writeConstantPoolIndex(m_imageDataPool, i); + // } + void writeObjectIndex(unsigned i) { writeConstantPoolIndex(m_objectPool, i); @@ -1862,6 +2079,14 @@ class CloneSerializer : CloneBase { write(Identifier::fromString(m_lexicalGlobalObject->vm(), str)); } + void writeNullableString(const String& str) + { + bool isNull = str.isNull(); + write(isNull); + if (!isNull) + write(Identifier::fromString(m_lexicalGlobalObject->vm(), str)); + } + void write(const Vector& vector) { uint32_t size = vector.size(); @@ -2073,6 +2298,11 @@ class CloneSerializer : CloneBase { } } + void write(SerializableErrorType errorType) + { + write(enumToUnderlyingType(errorType)); + } + void write(const CryptoKey* key) { write(currentKeyFormatVersion); @@ -2171,6 +2401,8 @@ class CloneSerializer : CloneBase { #endif typedef HashMap, uint32_t, IdentifierRepHash> StringConstantPool; StringConstantPool m_constantPool; + // using ImageDataPool = HashMap, uint32_t>; + // ImageDataPool m_imageDataPool; Identifier m_emptyIdentifier; SerializationContext m_context; ArrayBufferContentsArray& m_sharedBuffers; @@ -2518,7 +2750,7 @@ class CloneDeserializer : CloneBase { // return deserializer.deserialize(); // } - static DeserializationResult deserialize(JSGlobalObject* lexicalGlobalObject, JSGlobalObject* globalObject + static DeserializationResult deserialize(JSGlobalObject* lexicalGlobalObject, JSGlobalObject* globalObject, const Vector>& messagePorts #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) , Vector>&& detachedOffscreenCanvases @@ -2541,7 +2773,7 @@ class CloneDeserializer : CloneBase { { if (!buffer.size()) return std::make_pair(jsNull(), SerializationReturnCode::UnspecifiedError); - CloneDeserializer deserializer(lexicalGlobalObject, globalObject, arrayBufferContentsArray, std::span { buffer.begin(), buffer.end() }, blobURLs, blobFilePaths, sharedBuffers + CloneDeserializer deserializer(lexicalGlobalObject, globalObject, messagePorts, arrayBufferContentsArray, std::span { buffer.begin(), buffer.end() }, blobURLs, blobFilePaths, sharedBuffers #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) , WTFMove(detachedOffscreenCanvases) @@ -2675,7 +2907,7 @@ class CloneDeserializer : CloneBase { // m_version = 0xFFFFFFFF; // } - CloneDeserializer(JSGlobalObject* lexicalGlobalObject, JSGlobalObject* globalObject, ArrayBufferContentsArray* arrayBufferContents, const std::span& buffer + CloneDeserializer(JSGlobalObject* lexicalGlobalObject, JSGlobalObject* globalObject, const Vector>& messagePorts, ArrayBufferContentsArray* arrayBufferContents, const std::span& buffer #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) , Vector>&& detachedOffscreenCanvases = {} @@ -2700,6 +2932,7 @@ class CloneDeserializer : CloneBase { , m_ptr(buffer.data()) , m_end(buffer.data() + buffer.size()) , m_version(0xFFFFFFFF) + , m_messagePorts(messagePorts) , m_arrayBufferContents(arrayBufferContents) , m_arrayBuffers(arrayBufferContents ? arrayBufferContents->size() : 0) #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) @@ -2781,7 +3014,7 @@ class CloneDeserializer : CloneBase { // m_version = 0xFFFFFFFF; // } - CloneDeserializer(JSGlobalObject* lexicalGlobalObject, JSGlobalObject* globalObject, ArrayBufferContentsArray* arrayBufferContents, const std::span& buffer, const Vector& blobURLs, const Vector blobFilePaths, ArrayBufferContentsArray* sharedBuffers + CloneDeserializer(JSGlobalObject* lexicalGlobalObject, JSGlobalObject* globalObject, const Vector>& messagePorts, ArrayBufferContentsArray* arrayBufferContents, const std::span& buffer, const Vector& blobURLs, const Vector blobFilePaths, ArrayBufferContentsArray* sharedBuffers #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) , Vector>&& detachedOffscreenCanvases @@ -2806,6 +3039,7 @@ class CloneDeserializer : CloneBase { , m_ptr(buffer.data()) , m_end(buffer.data() + buffer.size()) , m_version(0xFFFFFFFF) + , m_messagePorts(messagePorts) , m_arrayBufferContents(arrayBufferContents) , m_arrayBuffers(arrayBufferContents ? arrayBufferContents->size() : 0) , m_blobURLs(blobURLs) @@ -2877,6 +3111,15 @@ class CloneDeserializer : CloneBase { } #endif + bool read(bool& b) + { + int32_t integer; + if (!readLittleEndian(integer) || integer > 1) + return false; + b = !!integer; + return true; + } + bool read(uint32_t& i) { return readLittleEndian(i); @@ -2914,28 +3157,34 @@ class CloneDeserializer : CloneBase { return readLittleEndian(i); } - bool readStringIndex(uint32_t& i) + std::optional readStringIndex() { - return readConstantPoolIndex(m_constantPool, i); + return readConstantPoolIndex(m_constantPool); } - template bool readConstantPoolIndex(const T& constantPool, uint32_t& i) + // std::optional readImageDataIndex() + // { + // return readConstantPoolIndex(m_imageDataPool); + // } + + template std::optional readConstantPoolIndex(const T& constantPool) { if (constantPool.size() <= 0xFF) { uint8_t i8; if (!read(i8)) - return false; - i = i8; - return true; + return std::nullopt; + return i8; } if (constantPool.size() <= 0xFFFF) { uint16_t i16; if (!read(i16)) - return false; - i = i16; - return true; + return std::nullopt; + return i16; } - return read(i); + uint32_t i; + if (!read(i)) + return std::nullopt; + return i; } static bool readString(const uint8_t*& ptr, const uint8_t* end, String& str, unsigned length, bool is8Bit) @@ -2970,6 +3219,20 @@ class CloneDeserializer : CloneBase { return true; } + bool readNullableString(String& nullableString) + { + bool isNull; + if (!read(isNull)) + return false; + if (isNull) + return true; + CachedStringRef stringData; + if (!readStringData(stringData)) + return false; + nullableString = stringData->string(); + return true; + } + static bool readIdentifier(JSC::VM& vm, const uint8_t*& ptr, const uint8_t* end, Identifier& str, unsigned length, bool is8Bit) { if (length >= std::numeric_limits::max() / sizeof(UChar)) @@ -3020,16 +3283,12 @@ class CloneDeserializer : CloneBase { return false; } if (length == StringPoolTag) { - unsigned index = 0; - if (!readStringIndex(index)) { - fail(); - return false; - } - if (index >= m_constantPool.size()) { + auto index = readStringIndex(); + if (!index || *index >= m_constantPool.size()) { fail(); return false; } - cachedString = CachedStringRef(&m_constantPool, index); + cachedString = CachedStringRef(&m_constantPool, *index); return true; } bool is8Bit = length & StringDataIs8BitFlag; @@ -3056,16 +3315,12 @@ class CloneDeserializer : CloneBase { return false; } if (length == StringPoolTag) { - unsigned index = 0; - if (!readStringIndex(index)) { - fail(); - return false; - } - if (index >= m_constantPool.size()) { + auto index = readStringIndex(); + if (!index || *index >= m_constantPool.size()) { fail(); return false; } - cachedString = CachedStringRef(&m_constantPool, index); + cachedString = CachedStringRef(&m_constantPool, *index); return true; } bool is8Bit = length & StringDataIs8BitFlag; @@ -3756,6 +4011,16 @@ class CloneDeserializer : CloneBase { } #endif + bool read(SerializableErrorType& errorType) + { + std::underlying_type_t errorTypeInt; + if (!read(errorTypeInt) || errorTypeInt > enumToUnderlyingType(SerializableErrorType::Last)) + return false; + + errorType = static_cast(errorTypeInt); + return true; + } + template JSValue getJSValue(T&& nativeObj) { @@ -4191,6 +4456,8 @@ class CloneDeserializer : CloneBase { JSValue readTerminal() { SerializationTag tag = readTag(); + // if (!isTypeExposedToGlobalObject(*m_globalObject, tag)) + // return JSValue(); // read bun types if (auto value = StructuredCloneableDeserialize::fromTagDeserialize(tag, m_lexicalGlobalObject, m_ptr, m_end)) { @@ -4293,6 +4560,14 @@ class CloneDeserializer : CloneBase { // uint32_t width; // if (!read(width)) // return JSValue(); + // if (width == ImageDataPoolTag) { + // auto index = readImageDataIndex(); + // if (!index || *index >= m_imageDataPool.size()) { + // fail(); + // return JSValue(); + // } + // return getJSValue(m_imageDataPool[*index]); + // } // uint32_t height; // if (!read(height)) // return JSValue(); @@ -4329,6 +4604,7 @@ class CloneDeserializer : CloneBase { // memcpy(result.returnValue()->data().data(), bufferStart, length); // else // result.returnValue()->data().zeroFill(); + // m_imageDataPool.append(result.returnValue().copyRef()); // return getJSValue(result.releaseReturnValue()); // } // case BlobTag: { @@ -4383,23 +4659,56 @@ class CloneDeserializer : CloneBase { RegExp* regExp = RegExp::create(vm, pattern->string(), reFlags.value()); return RegExpObject::create(vm, m_globalObject->regExpStructure(), regExp); } + case ErrorInstanceTag: { + SerializableErrorType serializedErrorType; + if (!read(serializedErrorType)) { + fail(); + return JSValue(); + } + String message; + if (!readNullableString(message)) { + fail(); + return JSValue(); + } + uint32_t line; + if (!read(line)) { + fail(); + return JSValue(); + } + uint32_t column; + if (!read(column)) { + fail(); + return JSValue(); + } + String sourceURL; + if (!readNullableString(sourceURL)) { + fail(); + return JSValue(); + } + String stackString; + if (!readNullableString(stackString)) { + fail(); + return JSValue(); + } + return ErrorInstance::create(m_lexicalGlobalObject, WTFMove(message), toErrorType(serializedErrorType), line, column, WTFMove(sourceURL), WTFMove(stackString)); + } case ObjectReferenceTag: { - unsigned index = 0; - if (!readConstantPoolIndex(m_gcBuffer, index)) { + auto index = readConstantPoolIndex(m_gcBuffer); + if (!index) { fail(); return JSValue(); } - return m_gcBuffer.at(index); + return m_gcBuffer.at(*index); + } + case MessagePortReferenceTag: { + uint32_t index; + bool indexSuccessfullyRead = read(index); + if (!indexSuccessfullyRead || index >= m_messagePorts.size()) { + fail(); + return JSValue(); + } + return getJSValue(m_messagePorts[index].get()); } - // case MessagePortReferenceTag: { - // uint32_t index; - // bool indexSuccessfullyRead = read(index); - // if (!indexSuccessfullyRead || index >= m_messagePorts.size()) { - // fail(); - // return JSValue(); - // } - // return getJSValue(m_messagePorts[index].get()); - // } #if ENABLE(WEBASSEMBLY) case WasmModuleTag: { if (m_version >= 12) { @@ -4554,7 +4863,7 @@ class CloneDeserializer : CloneBase { JSValue cryptoKey; // Vector> dummyMessagePorts; // CloneDeserializer rawKeyDeserializer(m_lexicalGlobalObject, m_globalObject, dummyMessagePorts, nullptr, {}, serializedKey); - CloneDeserializer rawKeyDeserializer(m_lexicalGlobalObject, m_globalObject, nullptr, serializedKey); + CloneDeserializer rawKeyDeserializer(m_lexicalGlobalObject, m_globalObject, {}, nullptr, serializedKey); if (!rawKeyDeserializer.readCryptoKey(cryptoKey)) { fail(); return JSValue(); @@ -4625,7 +4934,8 @@ class CloneDeserializer : CloneBase { const uint8_t* const m_end; unsigned m_version; Vector m_constantPool; - // const Vector>& m_messagePorts; + // Vector> m_imageDataPool; + const Vector>& m_messagePorts; ArrayBufferContentsArray* m_arrayBufferContents; Vector> m_arrayBuffers; Vector m_blobURLs; @@ -5117,9 +5427,9 @@ static bool canDetachRTCDataChannels(const Vector>& channels RefPtr SerializedScriptValue::create(JSC::JSGlobalObject& globalObject, JSC::JSValue value, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext serializationContext) { - // Vector> dummyPorts; - // auto result = create(globalObject, value, {}, dummyPorts, forStorage, throwExceptions, serializationContext); - auto result = create(globalObject, value, {}, forStorage, throwExceptions, serializationContext); + Vector> dummyPorts; + auto result = create(globalObject, value, {}, dummyPorts, forStorage, throwExceptions, serializationContext); + // auto result = create(globalObject, value, {}, forStorage, throwExceptions, serializationContext); if (result.hasException()) return nullptr; return result.releaseReturnValue(); @@ -5130,13 +5440,13 @@ RefPtr SerializedScriptValue::create(JSC::JSGlobalObject& // return create(globalObject, value, WTFMove(transferList), messagePorts, forStorage, SerializationErrorMode::NonThrowing, serializationContext); // } -ExceptionOr> SerializedScriptValue::create(JSGlobalObject& globalObject, JSValue value, Vector>&& transferList, SerializationForStorage forStorage, SerializationContext serializationContext) +ExceptionOr> SerializedScriptValue::create(JSGlobalObject& globalObject, JSValue value, Vector>&& transferList, Vector>& messagePorts, SerializationForStorage forStorage, SerializationContext serializationContext) { - return create(globalObject, value, WTFMove(transferList), forStorage, SerializationErrorMode::Throwing, serializationContext); + return create(globalObject, value, WTFMove(transferList), messagePorts, forStorage, SerializationErrorMode::Throwing, serializationContext); } -// ExceptionOr> SerializedScriptValue::create(JSGlobalObject& lexicalGlobalObject, JSValue value, Vector>&& transferList, Vector>& messagePorts, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext context) -ExceptionOr> SerializedScriptValue::create(JSGlobalObject& lexicalGlobalObject, JSValue value, Vector>&& transferList, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext context) +// ExceptionOr> SerializedScriptValue::create(JSGlobalObject& lexicalGlobalObject, JSValue value, Vector>&& transferList, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext context) +ExceptionOr> SerializedScriptValue::create(JSGlobalObject& lexicalGlobalObject, JSValue value, Vector>&& transferList, Vector>& messagePorts, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext context) { VM& vm = lexicalGlobalObject.vm(); Vector> arrayBuffers; @@ -5166,12 +5476,12 @@ ExceptionOr> SerializedScriptValue::create(JSGlobalOb arrayBuffers.append(WTFMove(arrayBuffer)); continue; } - // if (auto port = JSMessagePort::toWrapped(vm, transferable.get())) { - // if (port->isDetached()) - // return Exception { DataCloneError, "MessagePort is detached"_s }; - // messagePorts.append(WTFMove(port)); - // continue; - // } + if (auto port = JSMessagePort::toWrapped(vm, transferable.get())) { + if (port->isDetached()) + return Exception { DataCloneError, "MessagePort is detached"_s }; + messagePorts.append(WTFMove(port)); + continue; + } // if (auto imageBitmap = JSImageBitmap::toWrapped(vm, transferable.get())) { // if (imageBitmap->isDetached()) @@ -5247,7 +5557,7 @@ ExceptionOr> SerializedScriptValue::create(JSGlobalOb // #endif // blobHandles, buffer, context, *sharedBuffers, forStorage); - auto code = CloneSerializer::serialize(&lexicalGlobalObject, value, arrayBuffers, + auto code = CloneSerializer::serialize(&lexicalGlobalObject, value, messagePorts, arrayBuffers, #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) offscreenCanvases, #endif @@ -5408,7 +5718,7 @@ JSC::JSValue SerializedScriptValue::fromArrayBuffer(JSC::JSGlobalObject& domGlob auto size = std::min(arrayBuffer->byteLength(), maxByteLength); auto span = std::span { data, size }; - auto result = CloneDeserializer::deserialize(&domGlobal, globalObject, nullptr, span, blobURLs, blobFiles, nullptr + auto result = CloneDeserializer::deserialize(&domGlobal, globalObject, {}, nullptr, span, blobURLs, blobFiles, nullptr #if ENABLE(WEBASSEMBLY) , nullptr, nullptr @@ -5437,71 +5747,24 @@ JSC::JSValue SerializedScriptValue::fromArrayBuffer(JSC::JSGlobalObject& domGlob // return deserialize(lexicalGlobalObject, globalObject, {}, throwExceptions, didFail); // } -// JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, JSGlobalObject* globalObject, const Vector>& messagePorts, SerializationErrorMode throwExceptions, bool* didFail) -// { -// Vector dummyBlobs; -// Vector dummyPaths; -// return deserialize(lexicalGlobalObject, globalObject, messagePorts, dummyBlobs, dummyPaths, throwExceptions, didFail); -// } +JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, JSGlobalObject* globalObject, const Vector>& messagePorts, SerializationErrorMode throwExceptions, bool* didFail) +{ + Vector dummyBlobs; + Vector dummyPaths; + return deserialize(lexicalGlobalObject, globalObject, messagePorts, dummyBlobs, dummyPaths, throwExceptions, didFail); +} JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, JSGlobalObject* globalObject, SerializationErrorMode throwExceptions, bool* didFail) { Vector dummyBlobs; Vector dummyPaths; - return deserialize(lexicalGlobalObject, globalObject, dummyBlobs, dummyPaths, throwExceptions, didFail); + Vector> dummyPorts; + return deserialize(lexicalGlobalObject, globalObject, dummyPorts, dummyBlobs, dummyPaths, throwExceptions, didFail); } -// JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, JSGlobalObject* globalObject, const Vector>& messagePorts, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode throwExceptions, bool* didFail) -// { -// DeserializationResult result = CloneDeserializer::deserialize(&lexicalGlobalObject, globalObject, messagePorts, WTFMove(m_backingStores) -// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) -// , -// WTFMove(m_detachedOffscreenCanvases) -// #endif -// #if ENABLE(WEB_RTC) -// , -// WTFMove(m_detachedRTCDataChannels) -// #endif -// , -// m_arrayBufferContentsArray.get(), m_data, blobURLs, blobFilePaths, m_sharedBufferContentsArray.get() -// #if ENABLE(WEBASSEMBLY) -// , -// m_wasmModulesArray.get(), m_wasmMemoryHandlesArray.get() -// #endif -// #if ENABLE(WEB_CODECS) -// , -// WTFMove(m_serializedVideoChunks), WTFMove(m_serializedVideoFrames) -// #endif -// ); -// if (didFail) -// *didFail = result.second != SerializationReturnCode::SuccessfullyCompleted; -// if (throwExceptions == SerializationErrorMode::Throwing) -// maybeThrowExceptionIfSerializationFailed(lexicalGlobalObject, result.second); -// return result.first ? result.first : jsNull(); -// } -JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, JSGlobalObject* globalObject, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode throwExceptions, bool* didFail) +JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, JSGlobalObject* globalObject, const Vector>& messagePorts, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode throwExceptions, bool* didFail) { - // DeserializationResult result = CloneDeserializer::deserialize(&lexicalGlobalObject, globalObject, messagePorts, WTFMove(m_backingStores) - // #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) - // , - // WTFMove(m_detachedOffscreenCanvases) - // #endif - // #if ENABLE(WEB_RTC) - // , - // WTFMove(m_detachedRTCDataChannels) - // #endif - // , - // m_arrayBufferContentsArray.get(), m_data, blobURLs, blobFilePaths, m_sharedBufferContentsArray.get() - // #if ENABLE(WEBASSEMBLY) - // , - // m_wasmModulesArray.get(), m_wasmMemoryHandlesArray.get() - // #endif - // #if ENABLE(WEB_CODECS) - // , - // WTFMove(m_serializedVideoChunks), WTFMove(m_serializedVideoFrames) - // #endif - // ); - DeserializationResult result = CloneDeserializer::deserialize(&lexicalGlobalObject, globalObject + DeserializationResult result = CloneDeserializer::deserialize(&lexicalGlobalObject, globalObject, messagePorts #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) , WTFMove(m_detachedOffscreenCanvases) @@ -5527,6 +5790,54 @@ JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, maybeThrowExceptionIfSerializationFailed(lexicalGlobalObject, result.second); return result.first ? result.first : jsNull(); } +// JSValue SerializedScriptValue::deserialize(JSGlobalObject& lexicalGlobalObject, JSGlobalObject* globalObject, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode throwExceptions, bool* didFail) +// { +// // DeserializationResult result = CloneDeserializer::deserialize(&lexicalGlobalObject, globalObject, messagePorts, WTFMove(m_backingStores) +// // #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) +// // , +// // WTFMove(m_detachedOffscreenCanvases) +// // #endif +// // #if ENABLE(WEB_RTC) +// // , +// // WTFMove(m_detachedRTCDataChannels) +// // #endif +// // , +// // m_arrayBufferContentsArray.get(), m_data, blobURLs, blobFilePaths, m_sharedBufferContentsArray.get() +// // #if ENABLE(WEBASSEMBLY) +// // , +// // m_wasmModulesArray.get(), m_wasmMemoryHandlesArray.get() +// // #endif +// // #if ENABLE(WEB_CODECS) +// // , +// // WTFMove(m_serializedVideoChunks), WTFMove(m_serializedVideoFrames) +// // #endif +// // ); +// DeserializationResult result = CloneDeserializer::deserialize(&lexicalGlobalObject, globalObject +// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS) +// , +// WTFMove(m_detachedOffscreenCanvases) +// #endif +// #if ENABLE(WEB_RTC) +// , +// WTFMove(m_detachedRTCDataChannels) +// #endif +// , +// m_arrayBufferContentsArray.get(), m_data, blobURLs, blobFilePaths, m_sharedBufferContentsArray.get() +// #if ENABLE(WEBASSEMBLY) +// , +// m_wasmModulesArray.get(), m_wasmMemoryHandlesArray.get() +// #endif +// #if ENABLE(WEB_CODECS) +// , +// WTFMove(m_serializedVideoChunks), WTFMove(m_serializedVideoFrames) +// #endif +// ); +// if (didFail) +// *didFail = result.second != SerializationReturnCode::SuccessfullyCompleted; +// if (throwExceptions == SerializationErrorMode::Throwing) +// maybeThrowExceptionIfSerializationFailed(lexicalGlobalObject, result.second); +// return result.first ? result.first : jsNull(); +// } JSValueRef SerializedScriptValue::deserialize(JSContextRef destinationContext, JSValueRef* exception) { diff --git a/src/bun.js/bindings/webcore/SerializedScriptValue.h b/src/bun.js/bindings/webcore/SerializedScriptValue.h index 189945d5277597..5d5e93854ba246 100644 --- a/src/bun.js/bindings/webcore/SerializedScriptValue.h +++ b/src/bun.js/bindings/webcore/SerializedScriptValue.h @@ -60,7 +60,7 @@ namespace WebCore { class DetachedOffscreenCanvas; #endif // class IDBValue; -// class MessagePort; +class MessagePort; // class ImageBitmapBacking; class CloneSerializer; class FragmentedSharedBuffer; @@ -87,8 +87,8 @@ class SerializedScriptValue : public ThreadSafeRefCounted public: static void writeBytesForBun(CloneSerializer*, const uint8_t*, uint32_t); - // WEBCORE_EXPORT static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, Vector>&, SerializationForStorage = SerializationForStorage::No, SerializationContext = SerializationContext::Default); - WEBCORE_EXPORT static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, SerializationForStorage = SerializationForStorage::No, SerializationContext = SerializationContext::Default); + WEBCORE_EXPORT static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, Vector>&, SerializationForStorage = SerializationForStorage::No, SerializationContext = SerializationContext::Default); + // WEBCORE_EXPORT static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, SerializationForStorage = SerializationForStorage::No, SerializationContext = SerializationContext::Default); WEBCORE_EXPORT static RefPtr create(JSC::JSGlobalObject&, JSC::JSValue, SerializationForStorage = SerializationForStorage::No, SerializationErrorMode = SerializationErrorMode::Throwing, SerializationContext = SerializationContext::Default); @@ -99,10 +99,10 @@ class SerializedScriptValue : public ThreadSafeRefCounted static Ref nullValue(); WEBCORE_EXPORT JSC::JSValue deserialize(JSC::JSGlobalObject&, JSC::JSGlobalObject*, SerializationErrorMode = SerializationErrorMode::Throwing, bool* didFail = nullptr); - // WEBCORE_EXPORT JSC::JSValue deserialize(JSC::JSGlobalObject&, JSC::JSGlobalObject*, const Vector>&, SerializationErrorMode = SerializationErrorMode::Throwing, bool* didFail = nullptr); + WEBCORE_EXPORT JSC::JSValue deserialize(JSC::JSGlobalObject&, JSC::JSGlobalObject*, const Vector>&, SerializationErrorMode = SerializationErrorMode::Throwing, bool* didFail = nullptr); - // JSC::JSValue deserialize(JSC::JSGlobalObject&, JSC::JSGlobalObject*, const Vector>&, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode = SerializationErrorMode::Throwing, bool* didFail = nullptr); - JSC::JSValue deserialize(JSC::JSGlobalObject&, JSC::JSGlobalObject*, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode = SerializationErrorMode::Throwing, bool* didFail = nullptr); + JSC::JSValue deserialize(JSC::JSGlobalObject&, JSC::JSGlobalObject*, const Vector>&, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode = SerializationErrorMode::Throwing, bool* didFail = nullptr); + // JSC::JSValue deserialize(JSC::JSGlobalObject&, JSC::JSGlobalObject*, const Vector& blobURLs, const Vector& blobFilePaths, SerializationErrorMode = SerializationErrorMode::Throwing, bool* didFail = nullptr); static uint32_t wireFormatVersion(); @@ -146,7 +146,7 @@ class SerializedScriptValue : public ThreadSafeRefCounted // Vector>&& = {}, Vector&& = {} // #endif // ); - static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, SerializationForStorage, SerializationErrorMode, SerializationContext); + static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, Vector>&, SerializationForStorage, SerializationErrorMode, SerializationContext); WEBCORE_EXPORT SerializedScriptValue(Vector&&, std::unique_ptr&& = nullptr #if ENABLE(WEB_RTC) , diff --git a/src/bun.js/bindings/webcore/TransferredMessagePort.h b/src/bun.js/bindings/webcore/TransferredMessagePort.h new file mode 100644 index 00000000000000..19aa63746f4384 --- /dev/null +++ b/src/bun.js/bindings/webcore/TransferredMessagePort.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2018-2022 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "MessagePortIdentifier.h" + +namespace WebCore { + +// When a message port is transferred, it is represented by a pair of identifiers. +// The first identifier is the port being transferred and the second is its remote port. +using TransferredMessagePort = std::pair; + +} // namespace WebCore diff --git a/src/bun.js/bindings/webcore/Worker.cpp b/src/bun.js/bindings/webcore/Worker.cpp index dfbc0e007abf30..92503bbbd3de63 100644 --- a/src/bun.js/bindings/webcore/Worker.cpp +++ b/src/bun.js/bindings/webcore/Worker.cpp @@ -61,7 +61,7 @@ #include "MessageEvent.h" #include #include "BunWorkerGlobalScope.h" - +#include "CloseEvent.h" namespace WebCore { WTF_MAKE_ISO_ALLOCATED_IMPL(Worker); @@ -185,31 +185,34 @@ ExceptionOr Worker::postMessage(JSC::JSGlobalObject& state, JSC::JSValue m if (m_wasTerminated) return Exception { InvalidStateError, "Worker has been terminated"_s }; - auto message = SerializedScriptValue::create(state, messageValue, WTFMove(options.transfer), SerializationForStorage::No, SerializationContext::WorkerPostMessage); - if (message.hasException()) - return message.releaseException(); + Vector> ports; + auto serialized = SerializedScriptValue::create(state, messageValue, WTFMove(options.transfer), ports, SerializationForStorage::No, SerializationContext::WorkerPostMessage); + if (serialized.hasException()) + return serialized.releaseException(); + + ExceptionOr> disentangledPorts = MessagePort::disentanglePorts(WTFMove(ports)); + if (disentangledPorts.hasException()) { + return disentangledPorts.releaseException(); + } - RefPtr result = message.releaseReturnValue(); + MessageWithMessagePorts messageWithMessagePorts { serialized.releaseReturnValue(), disentangledPorts.releaseReturnValue() }; - this->postTaskToWorkerGlobalScope([message = WTFMove(result)](auto& context) { + this->postTaskToWorkerGlobalScope([message = messageWithMessagePorts](auto& context) mutable { Zig::GlobalObject* globalObject = jsCast(context.jsGlobalObject()); - bool didFail = false; - JSValue value = message->deserialize(*globalObject, globalObject, SerializationErrorMode::NonThrowing, &didFail); - if (didFail) { - globalObject->globalEventScope.dispatchEvent(MessageEvent::create(eventNames().messageerrorEvent, MessageEvent::Init {}, MessageEvent::IsTrusted::Yes)); - return; - } + auto ports = MessagePort::entanglePorts(context, WTFMove(message.transferredPorts)); + auto event = MessageEvent::create(*globalObject, message.message.releaseNonNull(), std::nullopt, WTFMove(ports)); - WebCore::MessageEvent::Init init; - init.data = value; - globalObject->globalEventScope.dispatchEvent(MessageEvent::create(eventNames().messageEvent, WTFMove(init), MessageEvent::IsTrusted::Yes)); + globalObject->globalEventScope.dispatchEvent(event.event); }); return {}; } void Worker::terminate() { + if (m_wasTerminated) { + return; + } // m_contextProxy.terminateWorkerGlobalScope(); m_wasTerminated = true; WebWorker__terminate(impl_); @@ -285,7 +288,6 @@ void Worker::drainEvents() void Worker::dispatchOnline(Zig::GlobalObject* workerGlobalObject) { - auto* ctx = scriptExecutionContext(); if (ctx) { ScriptExecutionContext::postTaskTo(ctx->identifier(), [protectedThis = Ref { *this }](ScriptExecutionContext& context) -> void { @@ -339,19 +341,19 @@ void Worker::dispatchError(WTF::String message) protectedThis->dispatchEvent(event); }); } -void Worker::dispatchExit() +void Worker::dispatchExit(int32_t exitCode) { auto* ctx = scriptExecutionContext(); if (!ctx) return; - ScriptExecutionContext::postTaskTo(ctx->identifier(), [protectedThis = Ref { *this }](ScriptExecutionContext& context) -> void { + ScriptExecutionContext::postTaskTo(ctx->identifier(), [exitCode, protectedThis = Ref { *this }](ScriptExecutionContext& context) -> void { protectedThis->m_isOnline = false; protectedThis->m_isClosing = true; protectedThis->setKeepAlive(false); if (protectedThis->hasEventListeners(eventNames().closeEvent)) { - auto event = Event::create(eventNames().closeEvent, Event::CanBubble::No, Event::IsCancelable::No); + auto event = CloseEvent::create(exitCode == 0, static_cast(exitCode), exitCode == 0 ? "Worker terminated normally"_s : "Worker exited abnormally"_s); protectedThis->dispatchEvent(event); } }); @@ -377,6 +379,8 @@ void Worker::forEachWorker(const FunctiondispatchExit(exitCode); + if (globalObject) { auto* ctx = globalObject->scriptExecutionContext(); if (ctx) { @@ -398,8 +402,6 @@ extern "C" void WebWorker__dispatchExit(Zig::GlobalObject* globalObject, Worker* vm.notifyNeedTermination(); vm.deferredWorkTimer->doWork(vm); } - - worker->dispatchExit(); } extern "C" void WebWorker__dispatchOnline(Worker* worker, Zig::GlobalObject* globalObject) { diff --git a/src/bun.js/bindings/webcore/Worker.h b/src/bun.js/bindings/webcore/Worker.h index b0b8e0a2bc9acf..a296fa4a8d2acb 100644 --- a/src/bun.js/bindings/webcore/Worker.h +++ b/src/bun.js/bindings/webcore/Worker.h @@ -94,8 +94,10 @@ class Worker final : public RefCounted, public EventTargetWithInlineData void drainEvents(); void dispatchOnline(Zig::GlobalObject* workerGlobalObject); void dispatchError(WTF::String message); - void dispatchExit(); + void dispatchExit(int32_t exitCode); ScriptExecutionContext* scriptExecutionContext() const final { return ContextDestructionObserver::scriptExecutionContext(); } + ScriptExecutionContextIdentifier clientIdentifier() const { return m_clientIdentifier; } + WorkerOptions& options() { return m_options; } private: Worker(ScriptExecutionContext&, WorkerOptions&&); @@ -118,7 +120,7 @@ class Worker final : public RefCounted, public EventTargetWithInlineData static void networkStateChanged(bool isOnLine); // RefPtr m_scriptLoader; - const WorkerOptions m_options; + WorkerOptions m_options; String m_identifier; // WorkerGlobalScopeProxy& m_contextProxy; // The proxy outlives the worker to perform thread shutdown. // std::optional m_contentSecurityPolicyResponseHeaders; @@ -135,7 +137,6 @@ class Worker final : public RefCounted, public EventTargetWithInlineData bool m_isClosing { false }; const ScriptExecutionContextIdentifier m_clientIdentifier; void* impl_ { nullptr }; - size_t m_pendingActivityCount { 0 }; }; } // namespace WebCore diff --git a/src/bun.js/bindings/webcore/WorkerOptions.h b/src/bun.js/bindings/webcore/WorkerOptions.h index bc2ef6ff025c65..79eabef9856b62 100644 --- a/src/bun.js/bindings/webcore/WorkerOptions.h +++ b/src/bun.js/bindings/webcore/WorkerOptions.h @@ -1,12 +1,18 @@ #pragma once #include "root.h" +#include "SerializedScriptValue.h" +#include "TransferredMessagePort.h" +#include "MessagePort.h" namespace WebCore { struct BunOptions { bool mini { false }; bool unref { false }; + RefPtr data; + Vector dataMessagePorts; + std::unique_ptr> env { nullptr }; }; struct WorkerOptions { diff --git a/src/bun.js/bindings/webcrypto/CryptoAlgorithm.cpp b/src/bun.js/bindings/webcrypto/CryptoAlgorithm.cpp index ca3b97bff5a937..3c958bdfca40e7 100644 --- a/src/bun.js/bindings/webcrypto/CryptoAlgorithm.cpp +++ b/src/bun.js/bindings/webcrypto/CryptoAlgorithm.cpp @@ -95,10 +95,12 @@ ExceptionOr CryptoAlgorithm::getKeyLength(const CryptoAlgorithmParameter template static void dispatchAlgorithmOperation(WorkQueue& workQueue, ScriptExecutionContext& context, ResultCallbackType&& callback, CryptoAlgorithm::ExceptionCallback&& exceptionCallback, OperationType&& operation) { + context.refEventLoop(); workQueue.dispatch( [operation = WTFMove(operation), callback = WTFMove(callback), exceptionCallback = WTFMove(exceptionCallback), contextIdentifier = context.identifier()]() mutable { auto result = operation(); - ScriptExecutionContext::postTaskTo(contextIdentifier, [result = crossThreadCopy(WTFMove(result)), callback = WTFMove(callback), exceptionCallback = WTFMove(exceptionCallback)](auto&) mutable { + ScriptExecutionContext::postTaskTo(contextIdentifier, [result = crossThreadCopy(WTFMove(result)), callback = WTFMove(callback), exceptionCallback = WTFMove(exceptionCallback)](auto& context) mutable { + context.unrefEventLoop(); if (result.hasException()) { exceptionCallback(result.releaseException().code()); return; diff --git a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA1.cpp b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA1.cpp index f602467e023959..8a2a8829fadad2 100644 --- a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA1.cpp +++ b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA1.cpp @@ -51,10 +51,23 @@ void CryptoAlgorithmSHA1::digest(Vector&& message, VectorCallback&& cal return; } + if (message.size() < 64) { + auto moved = WTFMove(message); + digest->addBytes(moved.data(), moved.size()); + auto result = digest->computeHash(); + ScriptExecutionContext::postTaskTo(context.identifier(), [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + callback(result); + }); + return; + } + + context.refEventLoop(); + workQueue.dispatch([digest = WTFMove(digest), message = WTFMove(message), callback = WTFMove(callback), contextIdentifier = context.identifier()]() mutable { digest->addBytes(message.data(), message.size()); auto result = digest->computeHash(); - ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto& context) { + context.unrefEventLoop(); callback(result); }); }); diff --git a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA224.cpp b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA224.cpp index dfb8204b532068..3591215bf1e83d 100644 --- a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA224.cpp +++ b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA224.cpp @@ -51,10 +51,22 @@ void CryptoAlgorithmSHA224::digest(Vector&& message, VectorCallback&& c return; } + if (message.size() < 64) { + auto moved = WTFMove(message); + digest->addBytes(moved.data(), moved.size()); + auto result = digest->computeHash(); + ScriptExecutionContext::postTaskTo(context.identifier(), [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + callback(result); + }); + return; + } + + context.refEventLoop(); workQueue.dispatch([digest = WTFMove(digest), message = WTFMove(message), callback = WTFMove(callback), contextIdentifier = context.identifier()]() mutable { digest->addBytes(message.data(), message.size()); auto result = digest->computeHash(); - ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto& context) { + context.unrefEventLoop(); callback(result); }); }); diff --git a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA256.cpp b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA256.cpp index 216eccb5d0a318..c9bad917bbc114 100644 --- a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA256.cpp +++ b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA256.cpp @@ -51,10 +51,21 @@ void CryptoAlgorithmSHA256::digest(Vector&& message, VectorCallback&& c return; } + if (message.size() < 64) { + auto moved = WTFMove(message); + digest->addBytes(moved.data(), moved.size()); + auto result = digest->computeHash(); + ScriptExecutionContext::postTaskTo(context.identifier(), [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + callback(result); + }); + return; + } + context.refEventLoop(); workQueue.dispatch([digest = WTFMove(digest), message = WTFMove(message), callback = WTFMove(callback), contextIdentifier = context.identifier()]() mutable { digest->addBytes(message.data(), message.size()); auto result = digest->computeHash(); - ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto& context) { + context.unrefEventLoop(); callback(result); }); }); diff --git a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA384.cpp b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA384.cpp index 134e89bd8a4cf6..890d317b94918d 100644 --- a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA384.cpp +++ b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA384.cpp @@ -51,10 +51,23 @@ void CryptoAlgorithmSHA384::digest(Vector&& message, VectorCallback&& c return; } + if (message.size() < 64) { + auto moved = WTFMove(message); + digest->addBytes(moved.data(), moved.size()); + auto result = digest->computeHash(); + ScriptExecutionContext::postTaskTo(context.identifier(), [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + callback(result); + }); + return; + } + + context.refEventLoop(); + workQueue.dispatch([digest = WTFMove(digest), message = WTFMove(message), callback = WTFMove(callback), contextIdentifier = context.identifier()]() mutable { digest->addBytes(message.data(), message.size()); auto result = digest->computeHash(); - ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto& context) { + context.unrefEventLoop(); callback(result); }); }); diff --git a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA512.cpp b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA512.cpp index 016a47bf19a1a5..38a9fbe18ad328 100644 --- a/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA512.cpp +++ b/src/bun.js/bindings/webcrypto/CryptoAlgorithmSHA512.cpp @@ -51,10 +51,23 @@ void CryptoAlgorithmSHA512::digest(Vector&& message, VectorCallback&& c return; } + if (message.size() < 64) { + auto moved = WTFMove(message); + digest->addBytes(moved.data(), moved.size()); + auto result = digest->computeHash(); + ScriptExecutionContext::postTaskTo(context.identifier(), [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + callback(result); + }); + return; + } + + context.refEventLoop(); workQueue.dispatch([digest = WTFMove(digest), message = WTFMove(message), callback = WTFMove(callback), contextIdentifier = context.identifier()]() mutable { digest->addBytes(message.data(), message.size()); auto result = digest->computeHash(); - ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto&) { + + ScriptExecutionContext::postTaskTo(contextIdentifier, [callback = WTFMove(callback), result = WTFMove(result)](auto& context) { + context.unrefEventLoop(); callback(result); }); }); diff --git a/src/bun.js/event_loop.zig b/src/bun.js/event_loop.zig index 6688eaeea001ef..a59deb19d9d1f5 100644 --- a/src/bun.js/event_loop.zig +++ b/src/bun.js/event_loop.zig @@ -179,6 +179,40 @@ pub const AnyTask = struct { } }; +pub const ManagedTask = struct { + ctx: ?*anyopaque, + callback: *const (fn (*anyopaque) void), + + pub fn task(this: *ManagedTask) Task { + return Task.init(this); + } + + pub fn run(this: *ManagedTask) void { + @setRuntimeSafety(false); + var callback = this.callback; + var ctx = this.ctx; + callback(ctx.?); + bun.default_allocator.destroy(this); + } + + pub fn New(comptime Type: type, comptime Callback: anytype) type { + return struct { + pub fn init(ctx: *Type) Task { + var managed = bun.default_allocator.create(ManagedTask) catch @panic("out of memory!"); + managed.* = ManagedTask{ + .callback = wrap, + .ctx = ctx, + }; + return managed.task(); + } + + pub fn wrap(this: ?*anyopaque) void { + @call(.always_inline, Callback, .{@as(*Type, @ptrCast(@alignCast(this.?)))}); + } + }; + } +}; + pub const AnyTaskWithExtraContext = struct { ctx: ?*anyopaque, callback: *const (fn (*anyopaque, *anyopaque) void), @@ -267,6 +301,7 @@ pub const Task = TaggedPointerUnion(.{ CopyFilePromiseTask, WriteFileTask, AnyTask, + ManagedTask, napi_async_work, ThreadSafeFunction, CppTask, @@ -291,6 +326,20 @@ pub const ConcurrentTask = struct { manual_deinit, auto_deinit, }; + pub fn create(task: Task) *ConcurrentTask { + var created = bun.default_allocator.create(ConcurrentTask) catch @panic("out of memory!"); + created.* = .{ + .task = task, + .next = null, + .auto_delete = true, + }; + return created; + } + + pub fn fromCallback(ptr: anytype, comptime callback: anytype) *ConcurrentTask { + return create(ManagedTask.New(std.meta.Child(@TypeOf(ptr)), callback).init(ptr)); + } + pub fn from(this: *ConcurrentTask, of: anytype, auto_deinit: AutoDeinit) *ConcurrentTask { this.* = .{ .task = Task.init(of), @@ -520,6 +569,10 @@ pub const EventLoop = struct { var any: *AnyTask = task.get(AnyTask).?; any.run(); }, + @field(Task.Tag, typeBaseName(@typeName(ManagedTask))) => { + var any: *ManagedTask = task.get(ManagedTask).?; + any.run(); + }, @field(Task.Tag, typeBaseName(@typeName(CppTask))) => { var any: *CppTask = task.get(CppTask).?; any.run(global); @@ -566,14 +619,30 @@ pub const EventLoop = struct { this.tasks.ensureUnusedCapacity(count) catch unreachable; var writable = this.tasks.writableSlice(0); + + // Defer destruction of the ConcurrentTask to avoid issues with pointer aliasing + var to_destroy: ?*ConcurrentTask = null; + while (iter.next()) |task| { + if (to_destroy) |dest| { + bun.default_allocator.destroy(dest); + to_destroy = null; + } + + if (task.auto_delete) { + to_destroy = task; + } + writable[0] = task.task; writable = writable[1..]; this.tasks.count += 1; - if (task.auto_delete) bun.default_allocator.destroy(task); if (writable.len == 0) break; } + if (to_destroy) |dest| { + bun.default_allocator.destroy(dest); + } + return this.tasks.count - start_count; } diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index b48ade9789d762..741affa6ab1661 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -128,6 +128,7 @@ pub fn OpaqueWrap(comptime Context: type, comptime Function: fn (this: *Context) pub const bun_file_import_path = "/node_modules.server.bun"; const SourceMap = @import("../sourcemap/sourcemap.zig"); +const ParsedSourceMap = SourceMap.Mapping.ParsedSourceMap; const MappingList = SourceMap.Mapping.List; pub const SavedSourceMap = struct { @@ -138,7 +139,7 @@ pub const SavedSourceMap = struct { data: [*]u8, pub fn vlq(this: SavedMappings) []u8 { - return this.data[16..this.len()]; + return this.data[24..this.len()]; } pub inline fn len(this: SavedMappings) usize { @@ -149,12 +150,13 @@ pub const SavedSourceMap = struct { default_allocator.free(this.data[0..this.len()]); } - pub fn toMapping(this: SavedMappings, allocator: Allocator, path: string) anyerror!MappingList { + pub fn toMapping(this: SavedMappings, allocator: Allocator, path: string) anyerror!ParsedSourceMap { const result = SourceMap.Mapping.parse( allocator, - this.data[16..this.len()], + this.data[24..this.len()], @as(usize, @bitCast(this.data[8..16].*)), 1, + @as(usize, @bitCast(this.data[16..24].*)), ); switch (result) { .fail => |fail| { @@ -183,12 +185,14 @@ pub const SavedSourceMap = struct { } }; - pub const Value = TaggedPointerUnion(.{ MappingList, SavedMappings }); + pub const Value = TaggedPointerUnion(.{ ParsedSourceMap, SavedMappings }); pub const HashTable = std.HashMap(u64, *anyopaque, IdentityContext(u64), 80); /// This is a pointer to the map located on the VirtualMachine struct map: *HashTable, + mutex: bun.Lock = bun.Lock.init(), + pub fn onSourceMapChunk(this: *SavedSourceMap, chunk: SourceMap.Chunk, source: logger.Source) anyerror!void { try this.putMappings(source, chunk.buffer); } @@ -196,11 +200,13 @@ pub const SavedSourceMap = struct { pub const SourceMapHandler = js_printer.SourceMapHandler.For(SavedSourceMap, onSourceMapChunk); pub fn putMappings(this: *SavedSourceMap, source: logger.Source, mappings: MutableString) !void { + this.mutex.lock(); + defer this.mutex.unlock(); var entry = try this.map.getOrPut(bun.hash(source.path.text)); if (entry.found_existing) { var value = Value.from(entry.value_ptr.*); - if (value.get(MappingList)) |source_map_| { - var source_map: *MappingList = source_map_; + if (value.get(ParsedSourceMap)) |source_map_| { + var source_map: *ParsedSourceMap = source_map_; source_map.deinit(default_allocator); } else if (value.get(SavedMappings)) |saved_mappings| { var saved = SavedMappings{ .data = @as([*]u8, @ptrCast(saved_mappings)) }; @@ -212,16 +218,16 @@ pub const SavedSourceMap = struct { entry.value_ptr.* = Value.init(bun.cast(*SavedMappings, mappings.list.items.ptr)).ptr(); } - pub fn get(this: *SavedSourceMap, path: string) ?MappingList { + pub fn get(this: *SavedSourceMap, path: string) ?ParsedSourceMap { var mapping = this.map.getEntry(bun.hash(path)) orelse return null; switch (Value.from(mapping.value_ptr.*).tag()) { - (@field(Value.Tag, @typeName(MappingList))) => { - return Value.from(mapping.value_ptr.*).as(MappingList).*; + Value.Tag.ParsedSourceMap => { + return Value.from(mapping.value_ptr.*).as(ParsedSourceMap).*; }, Value.Tag.SavedMappings => { - var saved = SavedMappings{ .data = @as([*]u8, @ptrCast(Value.from(mapping.value_ptr.*).as(MappingList))) }; + var saved = SavedMappings{ .data = @as([*]u8, @ptrCast(Value.from(mapping.value_ptr.*).as(ParsedSourceMap))) }; defer saved.deinit(); - var result = default_allocator.create(MappingList) catch unreachable; + var result = default_allocator.create(ParsedSourceMap) catch unreachable; result.* = saved.toMapping(default_allocator, path) catch { _ = this.map.remove(mapping.key_ptr.*); return null; @@ -239,8 +245,11 @@ pub const SavedSourceMap = struct { line: i32, column: i32, ) ?SourceMap.Mapping { - var mappings = this.get(path) orelse return null; - return SourceMap.Mapping.find(mappings, line, column); + this.mutex.lock(); + defer this.mutex.unlock(); + + const parsed_mappings = this.get(path) orelse return null; + return SourceMap.Mapping.find(parsed_mappings.mappings, line, column); } }; const uws = @import("root").bun.uws; @@ -436,6 +445,8 @@ pub const VirtualMachine = struct { /// Used by bun:test to set global hooks for beforeAll, beforeEach, etc. is_in_preload: bool = false, + transpiler_store: JSC.RuntimeTranspilerStore, + /// The arguments used to launch the process _after_ the script name and bun and any flags applied to Bun /// "bun run foo --bar" /// ["--bar"] @@ -460,6 +471,7 @@ pub const VirtualMachine = struct { event_loop: *EventLoop = undefined, ref_strings: JSC.RefString.Map = undefined, + ref_strings_mutex: Lock = undefined, file_blobs: JSC.WebCore.Blob.Store.Map, source_mappings: SavedSourceMap = undefined, @@ -616,6 +628,13 @@ pub const VirtualMachine = struct { bun.reloadProcess(bun.default_allocator, !strings.eqlComptime(this.bundler.env.map.get("BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD") orelse "0", "true")); } + if (!strings.eqlComptime(this.bundler.env.map.get("BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD") orelse "0", "true")) { + Output.flush(); + Output.disableBuffering(); + Output.resetTerminalAll(); + Output.enableBuffering(); + } + this.global.reload(); this.pending_internal_promise = this.reloadEntryPoint(this.main) catch @panic("Failed to reload"); } @@ -741,6 +760,7 @@ pub const VirtualMachine = struct { this.macro_mode = true; this.event_loop = &this.macro_event_loop; Analytics.Features.macros = true; + this.transpiler_store.enabled = false; } pub fn disableMacroMode(this: *VirtualMachine) void { @@ -748,6 +768,7 @@ pub const VirtualMachine = struct { this.bundler.resolver.caches.fs.use_alternate_source_cache = false; this.macro_mode = false; this.event_loop = &this.regular_event_loop; + this.transpiler_store.enabled = true; } pub fn getAPIGlobals() []js.JSClassRef { @@ -810,7 +831,7 @@ pub const VirtualMachine = struct { pub inline fn isLoaded() bool { return VMHolder.vm != null; } - + const RuntimeTranspilerStore = JSC.RuntimeTranspilerStore; pub fn initWithModuleGraph( allocator: std.mem.Allocator, log: *logger.Log, @@ -830,6 +851,7 @@ pub const VirtualMachine = struct { vm.* = VirtualMachine{ .global = undefined, + .transpiler_store = RuntimeTranspilerStore.init(allocator), .allocator = allocator, .entry_point = ServerEntryPoint{}, .event_listeners = EventListenerMixin.Map.init(allocator), @@ -847,6 +869,7 @@ pub const VirtualMachine = struct { .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), .origin_timestamp = getOriginTimestamp(), .ref_strings = JSC.RefString.Map.init(allocator), + .ref_strings_mutex = Lock.init(), .file_blobs = JSC.WebCore.Blob.Store.Map.init(allocator), .standalone_module_graph = graph, .parser_arena = @import("root").bun.ArenaAllocator.init(allocator), @@ -887,6 +910,7 @@ pub const VirtualMachine = struct { vm.console, -1, false, + null, ); vm.regular_event_loop.global = vm.global; vm.regular_event_loop.virtual_machine = vm; @@ -932,6 +956,7 @@ pub const VirtualMachine = struct { vm.* = VirtualMachine{ .global = undefined, + .transpiler_store = RuntimeTranspilerStore.init(allocator), .allocator = allocator, .entry_point = ServerEntryPoint{}, .event_listeners = EventListenerMixin.Map.init(allocator), @@ -949,6 +974,7 @@ pub const VirtualMachine = struct { .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), .origin_timestamp = getOriginTimestamp(), .ref_strings = JSC.RefString.Map.init(allocator), + .ref_strings_mutex = Lock.init(), .file_blobs = JSC.WebCore.Blob.Store.Map.init(allocator), .parser_arena = @import("root").bun.ArenaAllocator.init(allocator), }; @@ -989,6 +1015,7 @@ pub const VirtualMachine = struct { vm.console, -1, smol, + null, ); vm.regular_event_loop.global = vm.global; vm.regular_event_loop.virtual_machine = vm; @@ -1034,6 +1061,7 @@ pub const VirtualMachine = struct { vm.* = VirtualMachine{ .global = undefined, .allocator = allocator, + .transpiler_store = RuntimeTranspilerStore.init(allocator), .entry_point = ServerEntryPoint{}, .event_listeners = EventListenerMixin.Map.init(allocator), .bundler = bundler, @@ -1050,6 +1078,7 @@ pub const VirtualMachine = struct { .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), .origin_timestamp = getOriginTimestamp(), .ref_strings = JSC.RefString.Map.init(allocator), + .ref_strings_mutex = Lock.init(), .file_blobs = JSC.WebCore.Blob.Store.Map.init(allocator), .parser_arena = @import("root").bun.ArenaAllocator.init(allocator), .standalone_module_graph = worker.parent.standalone_module_graph, @@ -1091,6 +1120,7 @@ pub const VirtualMachine = struct { vm.console, @as(i32, @intCast(worker.execution_context_id)), worker.mini, + worker.cpp_worker, ); vm.regular_event_loop.global = vm.global; vm.regular_event_loop.virtual_machine = vm; @@ -1135,6 +1165,8 @@ pub const VirtualMachine = struct { pub fn refCountedStringWithWasNew(this: *VirtualMachine, new: *bool, input_: []const u8, hash_: ?u32, comptime dupe: bool) *JSC.RefString { JSC.markBinding(@src()); const hash = hash_ orelse JSC.RefString.computeHash(input_); + this.ref_strings_mutex.lock(); + defer this.ref_strings_mutex.unlock(); var entry = this.ref_strings.getOrPut(hash) catch unreachable; if (!entry.found_existing) { @@ -1190,7 +1222,7 @@ pub const VirtualMachine = struct { ) anyerror!ResolvedSource { std.debug.assert(VirtualMachine.isLoaded()); - if (try ModuleLoader.fetchBuiltinModule(jsc_vm, _specifier, log, comptime flags.disableTranspiling())) |builtin| { + if (try ModuleLoader.fetchBuiltinModule(jsc_vm, _specifier)) |builtin| { return builtin; } var display_specifier = _specifier.toUTF8(bun.default_allocator); @@ -1762,7 +1794,9 @@ pub const VirtualMachine = struct { } pub fn reloadEntryPoint(this: *VirtualMachine, entry_path: []const u8) !*JSInternalPromise { + this.has_loaded = false; this.main = entry_path; + try this.entry_point.generate( this.allocator, this.bun_watcher != null, diff --git a/src/bun.js/module_loader.zig b/src/bun.js/module_loader.zig index 7543d5b8016f89..3932736fc26b32 100644 --- a/src/bun.js/module_loader.zig +++ b/src/bun.js/module_loader.zig @@ -150,14 +150,20 @@ inline fn jsSyntheticModule(comptime name: ResolvedSource.Tag, specifier: String }; } +const BunDebugHolder = struct { + pub var dir: ?std.fs.IterableDir = null; + pub var lock: bun.Lock = undefined; +}; + fn dumpSource(specifier: string, printer: anytype) !void { - const BunDebugHolder = struct { - pub var dir: ?std.fs.IterableDir = null; - }; if (BunDebugHolder.dir == null) { BunDebugHolder.dir = try std.fs.cwd().makeOpenPathIterable("/tmp/bun-debug-src/", .{}); + BunDebugHolder.lock = bun.Lock.init(); } + BunDebugHolder.lock.lock(); + defer BunDebugHolder.lock.unlock(); + if (std.fs.path.dirname(specifier)) |dir_path| { var parent = try BunDebugHolder.dir.?.dir.makeOpenPathIterable(dir_path[1..], .{}); defer parent.close(); @@ -167,6 +173,393 @@ fn dumpSource(specifier: string, printer: anytype) !void { } } +pub const RuntimeTranspilerStore = struct { + const debug = Output.scoped(.compile, false); + + generation_number: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), + store: TranspilerJob.Store, + enabled: bool = true, + + pub fn init(allocator: std.mem.Allocator) RuntimeTranspilerStore { + return RuntimeTranspilerStore{ + .store = TranspilerJob.Store.init(allocator), + }; + } + + pub fn transpile( + this: *RuntimeTranspilerStore, + vm: *JSC.VirtualMachine, + globalObject: *JSC.JSGlobalObject, + path: Fs.Path, + referrer: []const u8, + ) *anyopaque { + debug("transpile({s})", .{path.text}); + var job: *TranspilerJob = this.store.get(); + var owned_path = Fs.Path.init(bun.default_allocator.dupe(u8, path.text) catch unreachable); + var promise = JSC.JSInternalPromise.create(globalObject); + job.* = TranspilerJob{ + .path = owned_path, + .globalThis = globalObject, + .referrer = bun.default_allocator.dupe(u8, referrer) catch unreachable, + .vm = vm, + .log = logger.Log.init(bun.default_allocator), + .loader = vm.bundler.options.loader(owned_path.name.ext), + .promise = JSC.Strong.create(JSC.JSValue.fromCell(promise), globalObject), + .poll_ref = .{}, + .fetcher = TranspilerJob.Fetcher{ + .file = {}, + }, + }; + job.schedule(); + return promise; + } + + pub const TranspilerJob = struct { + path: Fs.Path, + referrer: []const u8, + loader: options.Loader, + promise: JSC.Strong = .{}, + vm: *JSC.VirtualMachine, + globalThis: *JSC.JSGlobalObject, + fetcher: Fetcher, + poll_ref: JSC.PollRef = .{}, + generation_number: u32 = 0, + log: logger.Log, + parse_error: ?anyerror = null, + resolved_source: ResolvedSource = ResolvedSource{}, + work_task: JSC.WorkPoolTask = .{ .callback = runFromWorkerThread }, + + pub const Store = bun.HiveArray(TranspilerJob, 64).Fallback; + + pub const Fetcher = union(enum) { + virtual_module: bun.String, + file: void, + + pub fn deinit(this: *@This()) void { + if (this.* == .virtual_module) { + this.virtual_module.deref(); + } + } + }; + + pub fn deinit(this: *TranspilerJob) void { + bun.default_allocator.free(this.path.text); + bun.default_allocator.free(this.referrer); + + this.poll_ref.disable(); + this.fetcher.deinit(); + this.loader = options.Loader.file; + this.path = Fs.Path.empty; + this.log.deinit(); + this.promise.deinit(); + this.globalThis = undefined; + } + + threadlocal var ast_memory_store: ?*js_ast.ASTMemoryAllocator = null; + threadlocal var source_code_printer: ?*js_printer.BufferPrinter = null; + + pub fn dispatchToMainThread(this: *TranspilerJob) void { + this.vm.eventLoop().enqueueTaskConcurrent( + JSC.ConcurrentTask.fromCallback(this, runFromJSThread), + ); + } + + pub fn runFromJSThread(this: *TranspilerJob) void { + var vm = this.vm; + var promise = this.promise.swap(); + var globalThis = this.globalThis; + this.poll_ref.unref(vm); + var specifier = if (this.parse_error == null) this.resolved_source.specifier else bun.String.create(this.path.text); + var referrer = bun.String.create(this.referrer); + var log = this.log; + this.log = logger.Log.init(bun.default_allocator); + var resolved_source = this.resolved_source; + resolved_source.source_url = specifier.toZigString(); + + resolved_source.tag = brk: { + if (resolved_source.commonjs_exports_len > 0) { + var actual_package_json: *PackageJSON = brk2: { + // this should already be cached virtually always so it's fine to do this + var dir_info = (vm.bundler.resolver.readDirInfo(this.path.name.dir) catch null) orelse + break :brk .javascript; + + break :brk2 dir_info.package_json orelse dir_info.enclosing_package_json; + } orelse break :brk .javascript; + + if (actual_package_json.module_type == .esm) { + break :brk ResolvedSource.Tag.package_json_type_module; + } + } + + break :brk ResolvedSource.Tag.javascript; + }; + + const parse_error = this.parse_error; + if (!vm.transpiler_store.store.hive.in(this)) { + this.promise.deinit(); + } + this.deinit(); + + _ = vm.transpiler_store.store.hive.put(this); + + ModuleLoader.AsyncModule.fulfill(globalThis, promise, resolved_source, parse_error, specifier, referrer, &log); + } + + pub fn schedule(this: *TranspilerJob) void { + this.poll_ref.ref(this.vm); + JSC.WorkPool.schedule(&this.work_task); + } + + pub fn runFromWorkerThread(work_task: *JSC.WorkPoolTask) void { + @fieldParentPtr(TranspilerJob, "work_task", work_task).run(); + } + + pub fn run(this: *TranspilerJob) void { + var arena = bun.ArenaAllocator.init(bun.default_allocator); + defer arena.deinit(); + + defer this.dispatchToMainThread(); + if (this.generation_number != this.vm.transpiler_store.generation_number.load(.Monotonic)) { + this.parse_error = error.TranspilerJobGenerationMismatch; + return; + } + + if (ast_memory_store == null) { + ast_memory_store = bun.default_allocator.create(js_ast.ASTMemoryAllocator) catch @panic("out of memory!"); + ast_memory_store.?.* = js_ast.ASTMemoryAllocator{ + .allocator = arena.allocator(), + .previous = null, + }; + } + + ast_memory_store.?.reset(); + ast_memory_store.?.allocator = arena.allocator(); + ast_memory_store.?.push(); + + const path = this.path; + const specifier = this.path.text; + const loader = this.loader; + this.log = logger.Log.init(bun.default_allocator); + + var vm = this.vm; + var bundler: bun.Bundler = undefined; + bundler = vm.bundler; + var allocator = arena.allocator(); + bundler.setAllocator(allocator); + bundler.setLog(&this.log); + bundler.resolver.opts = bundler.options; + bundler.macro_context = null; + bundler.linker.resolver = &bundler.resolver; + + var fd: ?StoredFileDescriptorType = null; + var package_json: ?*PackageJSON = null; + const hash = JSC.Watcher.getHash(path.text); + + if (vm.bun_dev_watcher) |watcher| { + if (watcher.indexOf(hash)) |index| { + const _fd = watcher.watchlist.items(.fd)[index]; + fd = if (_fd > 0) _fd else null; + package_json = watcher.watchlist.items(.package_json)[index]; + } + } else if (vm.bun_watcher) |watcher| { + if (watcher.indexOf(hash)) |index| { + const _fd = watcher.watchlist.items(.fd)[index]; + fd = if (_fd > 0) _fd else null; + package_json = watcher.watchlist.items(.package_json)[index]; + } + } + + // this should be a cheap lookup because 24 bytes == 8 * 3 so it's read 3 machine words + const is_node_override = strings.hasPrefixComptime(specifier, "/bun-vfs/node_modules/"); + + const macro_remappings = if (vm.macro_mode or !vm.has_any_macro_remappings or is_node_override) + MacroRemap{} + else + bundler.options.macro_remap; + + var fallback_source: logger.Source = undefined; + + // Usually, we want to close the input file automatically. + // + // If we're re-using the file descriptor from the fs watcher + // Do not close it because that will break the kqueue-based watcher + // + var should_close_input_file_fd = fd == null; + + var input_file_fd: StoredFileDescriptorType = 0; + var parse_options = Bundler.ParseOptions{ + .allocator = allocator, + .path = path, + .loader = loader, + .dirname_fd = 0, + .file_descriptor = fd, + .file_fd_ptr = &input_file_fd, + .file_hash = hash, + .macro_remappings = macro_remappings, + .jsx = bundler.options.jsx, + .virtual_source = null, + .dont_bundle_twice = true, + .allow_commonjs = true, + .inject_jest_globals = bundler.options.rewrite_jest_for_tests and + vm.main.len == path.text.len and + vm.main_hash == hash and + strings.eqlLong(vm.main, path.text, false), + }; + + defer { + if (should_close_input_file_fd and input_file_fd != 0) { + _ = bun.JSC.Node.Syscall.close(input_file_fd); + input_file_fd = 0; + } + } + + if (is_node_override) { + if (NodeFallbackModules.contentsFromPath(specifier)) |code| { + const fallback_path = Fs.Path.initWithNamespace(specifier, "node"); + fallback_source = logger.Source{ .path = fallback_path, .contents = code, .key_path = fallback_path }; + parse_options.virtual_source = &fallback_source; + } + } + + var parse_result: bun.bundler.ParseResult = bundler.parseMaybeReturnFileOnlyAllowSharedBuffer( + parse_options, + null, + false, + false, + ) orelse { + if (vm.isWatcherEnabled()) { + if (input_file_fd != 0) { + if (vm.bun_watcher != null and !is_node_override and std.fs.path.isAbsolute(path.text) and !strings.contains(path.text, "node_modules")) { + should_close_input_file_fd = false; + vm.bun_watcher.?.addFile( + input_file_fd, + path.text, + hash, + loader, + 0, + package_json, + true, + ) catch {}; + } + } + } + + this.parse_error = error.ParseError; + return; + }; + + if (vm.isWatcherEnabled()) { + if (input_file_fd != 0) { + if (vm.bun_watcher != null and !is_node_override and + std.fs.path.isAbsolute(path.text) and !strings.contains(path.text, "node_modules")) + { + should_close_input_file_fd = false; + vm.bun_watcher.?.addFile( + input_file_fd, + path.text, + hash, + loader, + 0, + package_json, + true, + ) catch {}; + } + } + } + + if (parse_result.already_bundled) { + this.resolved_source = ResolvedSource{ + .allocator = null, + .source_code = bun.String.createLatin1(parse_result.source.contents), + .specifier = String.create(specifier), + .source_url = ZigString.init(path.text), + // // TODO: change hash to a bitfield + // .hash = 1, + + // having JSC own the memory causes crashes + .hash = 0, + }; + return; + } + + for (parse_result.ast.import_records.slice()) |*import_record_| { + var import_record: *bun.ImportRecord = import_record_; + + if (JSC.HardcodedModule.Aliases.get(import_record.path.text)) |replacement| { + import_record.path.text = replacement.path; + import_record.tag = replacement.tag; + continue; + } + + if (bundler.options.rewrite_jest_for_tests) { + if (strings.eqlComptime( + import_record.path.text, + "@jest/globals", + ) or strings.eqlComptime( + import_record.path.text, + "vitest", + )) { + import_record.path.namespace = "bun"; + import_record.tag = .bun_test; + import_record.path.text = "test"; + continue; + } + } + + if (strings.hasPrefixComptime(import_record.path.text, "bun:")) { + import_record.path = Fs.Path.init(import_record.path.text["bun:".len..]); + import_record.path.namespace = "bun"; + + if (strings.eqlComptime(import_record.path.text, "test")) { + import_record.tag = .bun_test; + } + } + } + + if (source_code_printer == null) { + var writer = try js_printer.BufferWriter.init(bun.default_allocator); + source_code_printer = bun.default_allocator.create(js_printer.BufferPrinter) catch unreachable; + source_code_printer.?.* = js_printer.BufferPrinter.init(writer); + source_code_printer.?.ctx.append_null_byte = false; + } + + var printer = source_code_printer.?.*; + printer.ctx.reset(); + + { + defer source_code_printer.?.* = printer; + _ = bundler.printWithSourceMap( + parse_result, + @TypeOf(&printer), + &printer, + .esm_ascii, + SavedSourceMap.SourceMapHandler.init(&vm.source_mappings), + ) catch |err| { + this.parse_error = err; + return; + }; + } + + if (comptime Environment.dump_source) { + dumpSource(specifier, &printer) catch {}; + } + + this.resolved_source = ResolvedSource{ + .allocator = null, + .source_code = bun.String.createLatin1(printer.ctx.getWritten()), + .specifier = String.create(specifier), + .source_url = ZigString.init(path.text), + .commonjs_exports = null, + .commonjs_exports_len = if (parse_result.ast.exports_kind == .cjs) + std.math.maxInt(u32) + else + 0, + .hash = 0, + }; + } + }; +}; + pub const ModuleLoader = struct { const debug = Output.scoped(.ModuleLoader, true); pub const AsyncModule = struct { @@ -559,6 +952,46 @@ pub const ModuleLoader = struct { jsc_vm.allocator.destroy(this); } + pub fn fulfill( + globalThis: *JSC.JSGlobalObject, + promise: JSC.JSValue, + resolved_source: ResolvedSource, + err: ?anyerror, + specifier_: bun.String, + referrer_: bun.String, + log: *logger.Log, + ) void { + JSC.markBinding(@src()); + var specifier = specifier_; + var referrer = referrer_; + defer { + specifier.deref(); + referrer.deref(); + } + + var errorable: ErrorableResolvedSource = undefined; + if (err) |e| { + JSC.VirtualMachine.processFetchLog( + globalThis, + specifier, + referrer, + log, + &errorable, + e, + ); + } else { + errorable = ErrorableResolvedSource.ok(resolved_source); + } + log.deinit(); + + Bun__onFulfillAsyncModule( + promise, + &errorable, + &specifier, + &referrer, + ); + } + pub fn resolveError(this: *AsyncModule, vm: *JSC.VirtualMachine, import_record_id: u32, result: PackageResolveError) !void { var globalThis = this.globalThis; @@ -780,19 +1213,15 @@ pub const ModuleLoader = struct { var printer = VirtualMachine.source_code_printer.?.*; printer.ctx.reset(); - const written = brk: { + { defer VirtualMachine.source_code_printer.?.* = printer; - break :brk try jsc_vm.bundler.printWithSourceMap( + _ = try jsc_vm.bundler.printWithSourceMap( parse_result, @TypeOf(&printer), &printer, .esm_ascii, SavedSourceMap.SourceMapHandler.init(&jsc_vm.source_mappings), ); - }; - - if (written == 0) { - return error.PrintingErrorWriteFailed; } if (comptime Environment.dump_source) { @@ -911,6 +1340,9 @@ pub const ModuleLoader = struct { jsc_vm.transpiled_count += 1; jsc_vm.bundler.resetStore(); const hash = http.Watcher.getHash(path.text); + const is_main = jsc_vm.main.len == path.text.len and + jsc_vm.main_hash == hash and + strings.eqlLong(jsc_vm.main, path.text, false); var arena: bun.ArenaAllocator = undefined; @@ -937,7 +1369,8 @@ pub const ModuleLoader = struct { } } - var allocator = arena.allocator(); + // var allocator = arena.allocator(); + var allocator = bun.default_allocator; var fd: ?StoredFileDescriptorType = null; var package_json: ?*PackageJSON = null; @@ -1002,13 +1435,9 @@ pub const ModuleLoader = struct { .macro_remappings = macro_remappings, .jsx = jsc_vm.bundler.options.jsx, .virtual_source = virtual_source, - .hoist_bun_plugin = true, .dont_bundle_twice = true, .allow_commonjs = true, - .inject_jest_globals = jsc_vm.bundler.options.rewrite_jest_for_tests and - jsc_vm.main.len == path.text.len and - jsc_vm.main_hash == hash and - strings.eqlLong(jsc_vm.main, path.text, false), + .inject_jest_globals = jsc_vm.bundler.options.rewrite_jest_for_tests and is_main, }; defer { if (should_close_input_file_fd and input_file_fd != 0) { @@ -1122,12 +1551,6 @@ pub const ModuleLoader = struct { }; } - const has_bun_plugin = parse_result.ast.bun_plugin.hoisted_stmts.items.len > 0; - - if (has_bun_plugin) { - try ModuleLoader.runBunPlugin(jsc_vm, JSC.VirtualMachine.source_code_printer.?, &parse_result, ret); - } - const start_count = jsc_vm.bundler.linker.import_counter; // We _must_ link because: @@ -1180,7 +1603,7 @@ pub const ModuleLoader = struct { var printer = source_code_printer.*; printer.ctx.reset(); - const written = brk: { + _ = brk: { defer source_code_printer.* = printer; break :brk try jsc_vm.bundler.printWithSourceMap( parse_result, @@ -1191,26 +1614,6 @@ pub const ModuleLoader = struct { ); }; - if (written == 0) { - - // if it's an empty file but there were plugins - // we don't want it to break if you try to import from it - if (has_bun_plugin) { - return ResolvedSource{ - .allocator = null, - .source_code = String.static("// auto-generated plugin stub\nexport default undefined\n"), - .specifier = input_specifier, - .source_url = ZigString.init(path.text), - // // TODO: change hash to a bitfield - // .hash = 1, - - // having JSC own the memory causes crashes - .hash = 0, - }; - } - return error.PrintingErrorWriteFailed; - } - if (comptime Environment.dump_source) { try dumpSource(specifier, &printer); } @@ -1220,6 +1623,12 @@ pub const ModuleLoader = struct { out.* = ZigString.fromUTF8(name); } + defer { + if (is_main) { + jsc_vm.has_loaded = true; + } + } + if (jsc_vm.isWatcherEnabled()) { var resolved_source = jsc_vm.refCountedResolvedSource(printer.ctx.written, input_specifier, path.text, null, false); @@ -1340,16 +1749,10 @@ pub const ModuleLoader = struct { } return ResolvedSource{ .allocator = null, - .source_code = bun.String.static( - strings.append3( - bun.default_allocator, - JSC.Node.fs.constants_string, - @as(string, jsModuleFromFile(jsc_vm.load_builtins_from_path, "node/wasi.js")), - @as(string, jsModuleFromFile(jsc_vm.load_builtins_from_path, "bun/wasi-runner.js")), - ) catch unreachable, - ), + .source_code = bun.String.static(@embedFile("../js/wasi-runner.js")), .specifier = input_specifier, .source_url = ZigString.init(path.text), + .tag = .esm, .hash = 0, }; } @@ -1402,125 +1805,6 @@ pub const ModuleLoader = struct { } } - pub fn runBunPlugin( - jsc_vm: *VirtualMachine, - source_code_printer: *js_printer.BufferPrinter, - parse_result: *ParseResult, - ret: *ErrorableResolvedSource, - ) !void { - var printer = source_code_printer.*; - printer.ctx.reset(); - - defer printer.ctx.reset(); - // If we start transpiling in the middle of an existing transpilation session - // we will hit undefined memory bugs - // unless we disable resetting the store until we are done transpiling - const prev_disable_reset = js_ast.Stmt.Data.Store.disable_reset; - js_ast.Stmt.Data.Store.disable_reset = true; - js_ast.Expr.Data.Store.disable_reset = true; - - // flip the source code we use - // unless we're already transpiling a plugin - // that case could happen when - const was_printing_plugin = jsc_vm.is_printing_plugin; - const prev = jsc_vm.bundler.resolver.caches.fs.use_alternate_source_cache; - jsc_vm.is_printing_plugin = true; - defer { - js_ast.Stmt.Data.Store.disable_reset = prev_disable_reset; - js_ast.Expr.Data.Store.disable_reset = prev_disable_reset; - if (!was_printing_plugin) jsc_vm.bundler.resolver.caches.fs.use_alternate_source_cache = prev; - jsc_vm.is_printing_plugin = was_printing_plugin; - } - // we flip use_alternate_source_cache - if (!was_printing_plugin) jsc_vm.bundler.resolver.caches.fs.use_alternate_source_cache = !prev; - - // this is a bad idea, but it should work for now. - const original_name = parse_result.ast.symbols.mut(parse_result.ast.bun_plugin.ref.innerIndex()).original_name; - parse_result.ast.symbols.mut(parse_result.ast.bun_plugin.ref.innerIndex()).original_name = "globalThis.Bun.plugin"; - defer { - parse_result.ast.symbols.mut(parse_result.ast.bun_plugin.ref.innerIndex()).original_name = original_name; - } - const hoisted_stmts = parse_result.ast.bun_plugin.hoisted_stmts.items; - - var parts = [1]js_ast.Part{ - js_ast.Part{ - .stmts = hoisted_stmts, - }, - }; - var ast_copy = parse_result.ast; - ast_copy.import_records.set(try jsc_vm.allocator.dupe(ImportRecord, ast_copy.import_records.slice())); - defer ast_copy.import_records.deinitWithAllocator(jsc_vm.allocator); - ast_copy.parts.set(&parts); - ast_copy.prepend_part = null; - var temporary_source = parse_result.source; - var source_name = try std.fmt.allocPrint(jsc_vm.allocator, "{s}.plugin.{s}", .{ temporary_source.path.text, temporary_source.path.name.ext[1..] }); - temporary_source.path = Fs.Path.init(source_name); - - var temp_parse_result = parse_result.*; - temp_parse_result.ast = ast_copy; - - try jsc_vm.bundler.linker.link( - temporary_source.path, - &temp_parse_result, - jsc_vm.origin, - .absolute_path, - false, - true, - ); - - _ = brk: { - defer source_code_printer.* = printer; - break :brk try jsc_vm.bundler.printWithSourceMapMaybe( - temp_parse_result.ast, - &temporary_source, - @TypeOf(&printer), - &printer, - .esm_ascii, - true, - SavedSourceMap.SourceMapHandler.init(&jsc_vm.source_mappings), - ); - }; - const wrote = printer.ctx.getWritten(); - - if (wrote.len > 0) { - if (comptime Environment.dump_source) - try dumpSource(temporary_source.path.text, &printer); - - var exception = [1]JSC.JSValue{JSC.JSValue.zero}; - const promise = JSC.JSModuleLoader.evaluate( - jsc_vm.global, - wrote.ptr, - wrote.len, - temporary_source.path.text.ptr, - temporary_source.path.text.len, - parse_result.source.path.text.ptr, - parse_result.source.path.text.len, - JSC.JSValue.jsUndefined(), - &exception, - ); - if (!exception[0].isEmpty()) { - ret.* = JSC.ErrorableResolvedSource.err( - error.JSErrorObject, - exception[0].asVoid(), - ); - return error.PluginError; - } - - if (!promise.isEmptyOrUndefinedOrNull()) { - if (promise.asAnyPromise()) |promise_value| { - jsc_vm.waitForPromise(promise_value); - - if (promise_value.status(jsc_vm.global.vm()) == .Rejected) { - ret.* = JSC.ErrorableResolvedSource.err( - error.JSErrorObject, - promise_value.result(jsc_vm.global.vm()).asVoid(), - ); - return error.PluginError; - } - } - } - } - } pub fn normalizeSpecifier(jsc_vm: *VirtualMachine, slice_: string, string_to_use_for_source: *[]const u8) string { var slice = slice_; if (slice.len == 0) return slice; @@ -1574,7 +1858,11 @@ pub const ModuleLoader = struct { JSC.markBinding(@src()); var log = logger.Log.init(jsc_vm.bundler.allocator); defer log.deinit(); - if (ModuleLoader.fetchBuiltinModule(jsc_vm, specifier.*, &log, false) catch |err| { + + if (ModuleLoader.fetchBuiltinModule( + jsc_vm, + specifier.*, + ) catch |err| { if (err == error.AsyncModule) { unreachable; } @@ -1613,7 +1901,44 @@ pub const ModuleLoader = struct { &display_specifier, ); const path = Fs.Path.init(specifier); - const loader = jsc_vm.bundler.options.loaders.get(path.name.ext) orelse options.Loader.js; + + // Deliberately optional. + // The concurrent one only handles javascript-like loaders right now. + const loader: ?options.Loader = jsc_vm.bundler.options.loaders.get(path.name.ext); + + // We only run the transpiler concurrently when we can. + // Today, that's: + // + // Import Statements (import 'foo') + // Import Expressions (import('foo')) + // + if (comptime bun.FeatureFlags.concurrent_transpiler) { + const concurrent_loader = loader orelse .file; + if (allow_promise and (jsc_vm.has_loaded or jsc_vm.is_in_preload) and concurrent_loader.isJavaScriptLike() and + // Plugins make this complicated, + // TODO: allow running concurrently when no onLoad handlers match a plugin. + jsc_vm.plugin_runner == null and jsc_vm.transpiler_store.enabled) + { + if (!strings.eqlLong(specifier, jsc_vm.main, true)) { + return jsc_vm.transpiler_store.transpile( + jsc_vm, + globalObject, + path, + referrer_slice.slice(), + ); + } + } + } + + const synchronous_loader = loader orelse + // Unknown extensions are to be treated as file loader + if (jsc_vm.has_loaded or jsc_vm.is_in_preload) + options.Loader.file + else + // Unless it's potentially the main module + // This is important so that "bun run ./foo-i-have-no-extension" works + options.Loader.js; + var promise: ?*JSC.JSInternalPromise = null; ret.* = ErrorableResolvedSource.ok( ModuleLoader.transpileSourceCode( @@ -1623,7 +1948,7 @@ pub const ModuleLoader = struct { referrer_slice.slice(), specifier_ptr.*, path, - loader, + synchronous_loader, &log, null, ret, @@ -1668,7 +1993,7 @@ pub const ModuleLoader = struct { return globalObject.runOnLoadPlugins(bun.String.init(namespace), bun.String.init(after_namespace), .bun) orelse return JSValue.zero; } - pub fn fetchBuiltinModule(jsc_vm: *VirtualMachine, specifier: bun.String, log: *logger.Log, comptime disable_transpilying: bool) !?ResolvedSource { + pub fn fetchBuiltinModule(jsc_vm: *VirtualMachine, specifier: bun.String) !?ResolvedSource { if (jsc_vm.node_modules != null and specifier.eqlComptime(JSC.bun_file_import_path)) { // We kind of need an abstraction around this. // Basically we should subclass JSC::SourceCode with: @@ -1695,9 +2020,6 @@ pub const ModuleLoader = struct { }; } else if (HardcodedModule.Map.getWithEql(specifier, bun.String.eqlComptime)) |hardcoded| { switch (hardcoded) { - // This is all complicated because the imports have to be linked and we want to run the printer on it - // so it consistently handles bundled imports - // we can't take the shortcut of just directly importing the file, sadly. .@"bun:main" => { defer { if (jsc_vm.worker) |worker| { @@ -1705,189 +2027,82 @@ pub const ModuleLoader = struct { } } - if (comptime disable_transpilying) { - return ResolvedSource{ - .allocator = null, - .source_code = bun.String.init(jsc_vm.entry_point.source.contents), - .specifier = bun.String.init(bun.asByteSlice(JSC.VirtualMachine.main_file_name)), - .source_url = ZigString.init(bun.asByteSlice(JSC.VirtualMachine.main_file_name)), - .hash = 0, - }; - } - defer jsc_vm.transpiled_count += 1; - var arena: bun.ArenaAllocator = undefined; - - // Attempt to reuse the Arena from the parser when we can - // This code is potentially re-entrant, so only one Arena can be reused at a time - // That's why we have to check if the Arena is null - // - // Using an Arena here is a significant memory optimization when loading many files - if (jsc_vm.parser_arena) |shared| { - arena = shared; - jsc_vm.parser_arena = null; - _ = arena.reset(.retain_capacity); - } else { - arena = bun.ArenaAllocator.init(jsc_vm.allocator); - } - - defer { - if (jsc_vm.parser_arena == null) { - jsc_vm.parser_arena = arena; - } else { - arena.deinit(); - } - } - - var bundler = &jsc_vm.bundler; - var old = jsc_vm.bundler.log; - jsc_vm.bundler.log = log; - jsc_vm.bundler.linker.log = log; - jsc_vm.bundler.resolver.log = log; - defer { - jsc_vm.bundler.log = old; - jsc_vm.bundler.linker.log = old; - jsc_vm.bundler.resolver.log = old; - } - - var jsx = bundler.options.jsx; - jsx.parse = false; - var opts = js_parser.Parser.Options.init(jsx, .js); - opts.enable_legacy_bundling = false; - opts.legacy_transform_require_to_import = false; - opts.features.dynamic_require = true; - opts.can_import_from_bundle = bundler.options.node_modules_bundle != null; - opts.features.hot_module_reloading = false; - opts.features.top_level_await = true; - opts.features.react_fast_refresh = false; - opts.features.minify_identifiers = bundler.options.minify_identifiers; - opts.features.minify_syntax = bundler.options.minify_syntax; - opts.filepath_hash_for_hmr = 0; - opts.warn_about_unbundled_modules = false; - opts.macro_context = &jsc_vm.bundler.macro_context.?; - const main_ast = ((bundler.resolver.caches.js.parse(arena.allocator(), opts, bundler.options.define, bundler.log, &jsc_vm.entry_point.source) catch null) orelse { - return error.ParseError; - }).ast; - var parse_result = ParseResult{ .source = jsc_vm.entry_point.source, .ast = main_ast, .loader = .js, .input_fd = null }; - var file_path = Fs.Path.init(bundler.fs.top_level_dir); - file_path.name.dir = bundler.fs.top_level_dir; - file_path.name.base = "bun:main"; - try bundler.linker.link( - file_path, - &parse_result, - jsc_vm.origin, - .absolute_path, - false, - true, - ); - var printer = JSC.VirtualMachine.source_code_printer.?.*; - var written: usize = undefined; - printer.ctx.reset(); - { - defer JSC.VirtualMachine.source_code_printer.?.* = printer; - written = try jsc_vm.bundler.printWithSourceMap( - parse_result, - @TypeOf(&printer), - &printer, - .esm_ascii, - SavedSourceMap.SourceMapHandler.init(&jsc_vm.source_mappings), - ); - } - - if (comptime Environment.dump_source) - try dumpSource(JSC.VirtualMachine.main_file_name, &printer); - - if (written == 0) { - return error.PrintingErrorWriteFailed; - } - return ResolvedSource{ .allocator = null, - .source_code = bun.String.createLatin1(printer.ctx.written), + .source_code = bun.String.create(jsc_vm.entry_point.source.contents), .specifier = specifier, .source_url = ZigString.init(bun.asByteSlice(JSC.VirtualMachine.main_file_name)), .hash = 0, + .tag = .esm, }; }, + + // Native modules + .bun => return jsSyntheticModule(.bun, specifier), .@"node:buffer" => return jsSyntheticModule(.@"node:buffer", specifier), .@"node:string_decoder" => return jsSyntheticModule(.@"node:string_decoder", specifier), .@"node:module" => return jsSyntheticModule(.@"node:module", specifier), .@"node:process" => return jsSyntheticModule(.@"node:process", specifier), .@"node:tty" => return jsSyntheticModule(.@"node:tty", specifier), .@"node:util/types" => return jsSyntheticModule(.@"node:util/types", specifier), - .@"bun:events_native" => return jsSyntheticModule(.@"bun:events_native", specifier), .@"node:constants" => return jsSyntheticModule(.@"node:constants", specifier), - .@"node:fs/promises" => { - return ResolvedSource{ - .allocator = null, - .source_code = bun.String.static(comptime JSC.Node.fs.constants_string ++ @embedFile("../js/out/modules/node/fs.promises.js")), - .specifier = specifier, - .source_url = ZigString.init("node:fs/promises"), - .hash = 0, - }; - }, - .@"bun:ffi" => { - const shared_library_suffix = if (Environment.isMac) "dylib" else if (Environment.isLinux) "so" else if (Environment.isWindows) "dll" else ""; - return ResolvedSource{ - .allocator = null, - .source_code = bun.String.static( - comptime "export const FFIType=" ++ - JSC.FFI.ABIType.map_to_js_object ++ - ";export const suffix='" ++ shared_library_suffix ++ "';" ++ - @embedFile("../js/out/modules/bun/ffi.js"), - ), - .specifier = specifier, - .source_url = ZigString.init("bun:ffi"), - .hash = 0, - }; - }, - - .@"bun:jsc" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"bun:jsc", "bun/jsc.js", specifier), - .@"bun:sqlite" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"bun:sqlite", "bun/sqlite.js", specifier), - - .@"node:assert" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:assert", "node/assert.js", specifier), - .@"node:assert/strict" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:assert/strict", "node/assert.strict.js", specifier), - .@"node:async_hooks" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:async_hooks", "node/async_hooks.js", specifier), - .@"node:child_process" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:child_process", "node/child_process.js", specifier), - .@"node:crypto" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:crypto", "node/crypto.js", specifier), - .@"node:dns" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:dns", "node/dns.js", specifier), - .@"node:dns/promises" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:dns/promises", "node/dns.promises.js", specifier), - .@"node:events" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:child_process", "node/events.js", specifier), - .@"node:fs" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:fs", "node/fs.js", specifier), - .@"node:http" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:http", "node/http.js", specifier), - .@"node:https" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:https", "node/https.js", specifier), - .@"node:net" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:net", "node/net.js", specifier), - .@"node:os" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:os", "node/os.js", specifier), - .@"node:path" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:path", "node/path.js", specifier), - .@"node:path/posix" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:path/posix", "node/path.posix.js", specifier), - .@"node:path/win32" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:path/win32", "node/path.win32.js", specifier), - .@"node:perf_hooks" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:perf_hooks", "node/perf_hooks.js", specifier), - .@"node:readline" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:readline", "node/readline.js", specifier), - .@"node:readline/promises" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:readline/promises", "node/readline.promises.js", specifier), - .@"node:stream" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:stream", "node/stream.js", specifier), - .@"node:stream/consumers" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:stream/consumers", "node/stream.consumers.js", specifier), - .@"node:stream/promises" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:stream/promises", "node/stream.promises.js", specifier), - .@"node:stream/web" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:stream/web", "node/stream.web.js", specifier), - .@"node:timers" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:timers", "node/timers.js", specifier), - .@"node:timers/promises" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:timers/promises", "node/timers.promises.js", specifier), - .@"node:tls" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:tls", "node/tls.js", specifier), - .@"node:url" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:url", "node/url.js", specifier), - .@"node:util" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:util", "node/util.js", specifier), - .@"node:vm" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:vm", "node/vm.js", specifier), - .@"node:wasi" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:wasi", "node/wasi.js", specifier), - .@"node:zlib" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:zlib", "node/zlib.js", specifier), - - .@"detect-libc" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"detect-libc", if (Environment.isLinux) "thirdparty/detect-libc.linux.js" else "thirdparty/detect-libc.js", specifier), - .undici => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .undici, "thirdparty/undici.js", specifier), - .ws => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .ws, "thirdparty/ws.js", specifier), - - .@"node:cluster" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:cluster", "node/cluster.js", specifier), - .@"node:dgram" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:dgram", "node/dgram.js", specifier), - .@"node:diagnostics_channel" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:diagnostics_channel", "node/diagnostics_channel.js", specifier), - .@"node:http2" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:http2", "node/http2.js", specifier), - .@"node:inspector" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:inspector", "node/inspector.js", specifier), - .@"node:repl" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:repl", "node/repl.js", specifier), - .@"node:trace_events" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:trace_events", "node/trace_events.js", specifier), - .@"node:v8" => return jsResolvedSource(jsc_vm, jsc_vm.load_builtins_from_path, .@"node:v8", "node/v8.js", specifier), + .@"bun:jsc" => return jsSyntheticModule(.@"bun:jsc", specifier), + + // These are defined in src/js/* + .@"bun:ffi" => return jsSyntheticModule(.@"bun:ffi", specifier), + .@"bun:sqlite" => return jsSyntheticModule(.@"bun:sqlite", specifier), + .@"detect-libc" => return jsSyntheticModule(if (Environment.isLinux) .@"detect-libc/linux" else .@"detect-libc", specifier), + .@"node:assert" => return jsSyntheticModule(.@"node:assert", specifier), + .@"node:assert/strict" => return jsSyntheticModule(.@"node:assert/strict", specifier), + .@"node:async_hooks" => return jsSyntheticModule(.@"node:async_hooks", specifier), + .@"node:child_process" => return jsSyntheticModule(.@"node:child_process", specifier), + .@"node:cluster" => return jsSyntheticModule(.@"node:cluster", specifier), + .@"node:console" => return jsSyntheticModule(.@"node:console", specifier), + .@"node:crypto" => return jsSyntheticModule(.@"node:crypto", specifier), + .@"node:dgram" => return jsSyntheticModule(.@"node:dgram", specifier), + .@"node:diagnostics_channel" => return jsSyntheticModule(.@"node:diagnostics_channel", specifier), + .@"node:dns" => return jsSyntheticModule(.@"node:dns", specifier), + .@"node:dns/promises" => return jsSyntheticModule(.@"node:dns/promises", specifier), + .@"node:domain" => return jsSyntheticModule(.@"node:domain", specifier), + .@"node:events" => return jsSyntheticModule(.@"node:events", specifier), + .@"node:fs" => return jsSyntheticModule(.@"node:fs", specifier), + .@"node:fs/promises" => return jsSyntheticModule(.@"node:fs/promises", specifier), + .@"node:http" => return jsSyntheticModule(.@"node:http", specifier), + .@"node:http2" => return jsSyntheticModule(.@"node:http2", specifier), + .@"node:https" => return jsSyntheticModule(.@"node:https", specifier), + .@"node:inspector" => return jsSyntheticModule(.@"node:inspector", specifier), + .@"node:net" => return jsSyntheticModule(.@"node:net", specifier), + .@"node:os" => return jsSyntheticModule(.@"node:os", specifier), + .@"node:path" => return jsSyntheticModule(.@"node:path", specifier), + .@"node:path/posix" => return jsSyntheticModule(.@"node:path/posix", specifier), + .@"node:path/win32" => return jsSyntheticModule(.@"node:path/win32", specifier), + .@"node:punycode" => return jsSyntheticModule(.@"node:punycode", specifier), + .@"node:perf_hooks" => return jsSyntheticModule(.@"node:perf_hooks", specifier), + .@"node:querystring" => return jsSyntheticModule(.@"node:querystring", specifier), + .@"node:readline" => return jsSyntheticModule(.@"node:readline", specifier), + .@"node:readline/promises" => return jsSyntheticModule(.@"node:readline/promises", specifier), + .@"node:repl" => return jsSyntheticModule(.@"node:repl", specifier), + .@"node:stream" => return jsSyntheticModule(.@"node:stream", specifier), + .@"node:stream/consumers" => return jsSyntheticModule(.@"node:stream/consumers", specifier), + .@"node:stream/promises" => return jsSyntheticModule(.@"node:stream/promises", specifier), + .@"node:stream/web" => return jsSyntheticModule(.@"node:stream/web", specifier), + .@"node:timers" => return jsSyntheticModule(.@"node:timers", specifier), + .@"node:timers/promises" => return jsSyntheticModule(.@"node:timers/promises", specifier), + .@"node:tls" => return jsSyntheticModule(.@"node:tls", specifier), + .@"node:trace_events" => return jsSyntheticModule(.@"node:trace_events", specifier), + .@"node:url" => return jsSyntheticModule(.@"node:url", specifier), + .@"node:util" => return jsSyntheticModule(.@"node:util", specifier), + .@"node:v8" => return jsSyntheticModule(.@"node:v8", specifier), + .@"node:vm" => return jsSyntheticModule(.@"node:vm", specifier), + .@"node:wasi" => return jsSyntheticModule(.@"node:wasi", specifier), + .@"node:worker_threads" => return jsSyntheticModule(.@"node:worker_threads", specifier), + .@"node:zlib" => return jsSyntheticModule(.@"node:zlib", specifier), + .@"isomorphic-fetch" => return jsSyntheticModule(.@"isomorphic-fetch", specifier), + .@"node-fetch" => return jsSyntheticModule(.@"node-fetch", specifier), + .@"@vercel/fetch" => return jsSyntheticModule(.vercel_fetch, specifier), + .@"utf-8-validate" => return jsSyntheticModule(.@"utf-8-validate", specifier), + .undici => return jsSyntheticModule(.undici, specifier), + .ws => return jsSyntheticModule(.ws, specifier), } } else if (specifier.hasPrefixComptime(js_ast.Macro.namespaceWithColon)) { const spec = specifier.toUTF8(bun.default_allocator); @@ -1901,20 +2116,6 @@ pub const ModuleLoader = struct { .hash = 0, }; } - } else if (DisabledModule.getWithEql(specifier, bun.String.eqlComptime) != null) { - return ResolvedSource{ - .allocator = null, - .source_code = bun.String.static( - \\var masqueradesAsUndefined=globalThis[Symbol.for("Bun.lazy")]("masqueradesAsUndefined"); - \\masqueradesAsUndefined[Symbol.for("CommonJS")]=0; - \\masqueradesAsUndefined.default=masqueradesAsUndefined; - \\export default masqueradesAsUndefined; - \\ - ), - .specifier = specifier, - .source_url = specifier.toZigString(), - .hash = 0, - }; } else if (jsc_vm.standalone_module_graph) |graph| { const specifier_utf8 = specifier.toUTF8(bun.default_allocator); defer specifier_utf8.deinit(); @@ -2017,21 +2218,23 @@ pub const FetchFlags = enum { const SavedSourceMap = JSC.SavedSourceMap; pub const HardcodedModule = enum { + bun, @"bun:ffi", @"bun:jsc", @"bun:main", @"bun:sqlite", - @"bun:events_native", @"detect-libc", @"node:assert", @"node:assert/strict", @"node:async_hooks", @"node:buffer", @"node:child_process", - @"node:crypto", + @"node:console", @"node:constants", + @"node:crypto", @"node:dns", @"node:dns/promises", + @"node:domain", @"node:events", @"node:fs", @"node:fs/promises", @@ -2045,6 +2248,7 @@ pub const HardcodedModule = enum { @"node:path/win32", @"node:perf_hooks", @"node:process", + @"node:querystring", @"node:readline", @"node:readline/promises", @"node:stream", @@ -2062,8 +2266,14 @@ pub const HardcodedModule = enum { @"node:vm", @"node:wasi", @"node:zlib", + @"node:worker_threads", + @"node:punycode", undici, ws, + @"isomorphic-fetch", + @"node-fetch", + @"@vercel/fetch", + @"utf-8-validate", // These are all not implemented yet, but are stubbed @"node:v8", @"node:trace_events", @@ -2082,11 +2292,11 @@ pub const HardcodedModule = enum { HardcodedModule, .{ .{ "buffer", HardcodedModule.@"node:buffer" }, + .{ "bun", HardcodedModule.bun }, .{ "bun:ffi", HardcodedModule.@"bun:ffi" }, .{ "bun:jsc", HardcodedModule.@"bun:jsc" }, .{ "bun:main", HardcodedModule.@"bun:main" }, .{ "bun:sqlite", HardcodedModule.@"bun:sqlite" }, - .{ "bun:events_native", HardcodedModule.@"bun:events_native" }, .{ "detect-libc", HardcodedModule.@"detect-libc" }, .{ "node:assert", HardcodedModule.@"node:assert" }, .{ "node:assert/strict", HardcodedModule.@"node:assert/strict" }, @@ -2094,12 +2304,14 @@ pub const HardcodedModule = enum { .{ "node:buffer", HardcodedModule.@"node:buffer" }, .{ "node:child_process", HardcodedModule.@"node:child_process" }, .{ "node:cluster", HardcodedModule.@"node:cluster" }, - .{ "node:crypto", HardcodedModule.@"node:crypto" }, + .{ "node:console", HardcodedModule.@"node:console" }, .{ "node:constants", HardcodedModule.@"node:constants" }, + .{ "node:crypto", HardcodedModule.@"node:crypto" }, .{ "node:dgram", HardcodedModule.@"node:dgram" }, .{ "node:diagnostics_channel", HardcodedModule.@"node:diagnostics_channel" }, .{ "node:dns", HardcodedModule.@"node:dns" }, .{ "node:dns/promises", HardcodedModule.@"node:dns/promises" }, + .{ "node:domain", HardcodedModule.@"node:domain" }, .{ "node:events", HardcodedModule.@"node:events" }, .{ "node:fs", HardcodedModule.@"node:fs" }, .{ "node:fs/promises", HardcodedModule.@"node:fs/promises" }, @@ -2113,8 +2325,12 @@ pub const HardcodedModule = enum { .{ "node:path", HardcodedModule.@"node:path" }, .{ "node:path/posix", HardcodedModule.@"node:path/posix" }, .{ "node:path/win32", HardcodedModule.@"node:path/win32" }, + .{ "node:punycode", HardcodedModule.@"node:punycode" }, .{ "node:perf_hooks", HardcodedModule.@"node:perf_hooks" }, .{ "node:process", HardcodedModule.@"node:process" }, + .{ "node:querystring", HardcodedModule.@"node:querystring" }, + .{ "node-fetch", HardcodedModule.@"node-fetch" }, + .{ "isomorphic-fetch", HardcodedModule.@"isomorphic-fetch" }, .{ "node:readline", HardcodedModule.@"node:readline" }, .{ "node:readline/promises", HardcodedModule.@"node:readline/promises" }, .{ "node:repl", HardcodedModule.@"node:repl" }, @@ -2134,9 +2350,12 @@ pub const HardcodedModule = enum { .{ "node:v8", HardcodedModule.@"node:v8" }, .{ "node:vm", HardcodedModule.@"node:vm" }, .{ "node:wasi", HardcodedModule.@"node:wasi" }, + .{ "node:worker_threads", HardcodedModule.@"node:worker_threads" }, .{ "node:zlib", HardcodedModule.@"node:zlib" }, .{ "undici", HardcodedModule.undici }, .{ "ws", HardcodedModule.ws }, + .{ "@vercel/fetch", HardcodedModule.@"@vercel/fetch" }, + .{ "utf-8-validate", HardcodedModule.@"utf-8-validate" }, }, ); pub const Alias = struct { @@ -2155,10 +2374,9 @@ pub const HardcodedModule = enum { .{ "bun:jsc", .{ .path = "bun:jsc" } }, .{ "bun:sqlite", .{ .path = "bun:sqlite" } }, .{ "bun:wrap", .{ .path = "bun:wrap" } }, - .{ "bun:events_native", .{ .path = "bun:events_native" } }, .{ "child_process", .{ .path = "node:child_process" } }, - .{ "crypto", .{ .path = "node:crypto" } }, .{ "constants", .{ .path = "node:constants" } }, + .{ "crypto", .{ .path = "node:crypto" } }, .{ "detect-libc", .{ .path = "detect-libc" } }, .{ "detect-libc/lib/detect-libc.js", .{ .path = "detect-libc" } }, .{ "dns", .{ .path = "node:dns" } }, @@ -2176,8 +2394,17 @@ pub const HardcodedModule = enum { .{ "node:async_hooks", .{ .path = "node:async_hooks" } }, .{ "node:buffer", .{ .path = "node:buffer" } }, .{ "node:child_process", .{ .path = "node:child_process" } }, - .{ "node:crypto", .{ .path = "node:crypto" } }, .{ "node:constants", .{ .path = "node:constants" } }, + .{ "node:console", .{ .path = "node:console" } }, + .{ "console", .{ .path = "node:console" } }, + .{ "node:querystring", .{ .path = "node:querystring" } }, + .{ "querystring", .{ .path = "node:querystring" } }, + .{ "node:domain", .{ .path = "node:domain" } }, + .{ "domain", .{ .path = "node:domain" } }, + .{ "@vercel/fetch", .{ .path = "@vercel/fetch" } }, + .{ "node:punycode", .{ .path = "node:punycode" } }, + .{ "punycode", .{ .path = "node:punycode" } }, + .{ "node:crypto", .{ .path = "node:crypto" } }, .{ "node:dns", .{ .path = "node:dns" } }, .{ "node:dns/promises", .{ .path = "node:dns/promises" } }, .{ "node:events", .{ .path = "node:events" } }, @@ -2216,11 +2443,6 @@ pub const HardcodedModule = enum { .{ "path/win32", .{ .path = "node:path/win32" } }, .{ "perf_hooks", .{ .path = "node:perf_hooks" } }, .{ "process", .{ .path = "node:process" } }, - // Older versions of `readable-stream` is incompatible with latest - // version of Node.js Stream API, which `bun` implements - // .{ "readable-stream", .{ .path = "node:stream" } }, - // .{ "readable-stream/consumer", .{ .path = "node:stream/consumers" } }, - // .{ "readable-stream/web", .{ .path = "node:stream/web" } }, .{ "readline", .{ .path = "node:readline" } }, .{ "readline/promises", .{ .path = "node:readline/promises" } }, .{ "stream", .{ .path = "node:stream" } }, @@ -2240,7 +2462,13 @@ pub const HardcodedModule = enum { .{ "worker_threads", .{ .path = "node:worker_threads" } }, .{ "ws", .{ .path = "ws" } }, .{ "ws/lib/websocket", .{ .path = "ws" } }, + .{ "utf-8-validate", .{ .path = "utf-8-validate" } }, .{ "zlib", .{ .path = "node:zlib" } }, + // .{ "readable-stream", .{ .path = "node:stream" } }, + // .{ "readable-stream/consumer", .{ .path = "node:stream/consumers" } }, + // .{ "readable-stream/web", .{ .path = "node:stream/web" } }, + // Older versions of `readable-stream` is incompatible with latest + // version of Node.js Stream API, which `bun` implements // These are returned in builtinModules, but probably not many packages use them // so we will just alias them. @@ -2283,29 +2511,13 @@ pub const HardcodedModule = enum { .{ "node:trace_events", .{ .path = "node:trace_events" } }, .{ "node:v8", .{ .path = "node:v8" } }, .{ "node:vm", .{ .path = "node:vm" } }, + + .{ "node:sys", .{ .path = "node:util" } }, + .{ "sys", .{ .path = "node:util" } }, + + .{ "node-fetch", .{ .path = "node-fetch" } }, + .{ "isomorphic-fetch", .{ .path = "isomorphic-fetch" } }, + .{ "@vercel/fetch", .{ .path = "@vercel/fetch" } }, }, ); }; - -pub const DisabledModule = bun.ComptimeStringMap( - void, - .{ - // Stubbing out worker_threads will break esbuild. - .{"worker_threads"}, - .{"node:worker_threads"}, - }, -); - -fn jsResolvedSource(vm: *JSC.VirtualMachine, builtins: []const u8, comptime module: HardcodedModule, comptime input: []const u8, specifier: bun.String) ResolvedSource { - // We use RefCountedResolvedSource because we want a stable StringImpl* - // pointer so that the SourceProviderCache has the maximum hit rate - return vm.refCountedResolvedSource( - jsModuleFromFile(builtins, input), - specifier, - @tagName(module), - null, - - // we never want to free these - true, - ); -} diff --git a/src/bun.js/modules/BunJSCModule.h b/src/bun.js/modules/BunJSCModule.h new file mode 100644 index 00000000000000..73823e16e02102 --- /dev/null +++ b/src/bun.js/modules/BunJSCModule.h @@ -0,0 +1,791 @@ +#include "_NativeModule.h" + +#include "ExceptionOr.h" +#include "JavaScriptCore/APICast.h" +#include "JavaScriptCore/AggregateError.h" +#include "JavaScriptCore/BytecodeIndex.h" +#include "JavaScriptCore/CallFrameInlines.h" +#include "JavaScriptCore/ClassInfo.h" +#include "JavaScriptCore/CodeBlock.h" +#include "JavaScriptCore/Completion.h" +#include "JavaScriptCore/DeferTermination.h" +#include "JavaScriptCore/Error.h" +#include "JavaScriptCore/ErrorInstance.h" +#include "JavaScriptCore/HeapSnapshotBuilder.h" +#include "JavaScriptCore/JIT.h" +#include "JavaScriptCore/JSBasePrivate.h" +#include "JavaScriptCore/JSCInlines.h" +#include "JavaScriptCore/JSONObject.h" +#include "JavaScriptCore/JavaScript.h" +#include "JavaScriptCore/ObjectConstructor.h" +#include "JavaScriptCore/SamplingProfiler.h" +#include "JavaScriptCore/TestRunnerUtils.h" +#include "JavaScriptCore/VMTrapsInlines.h" +#include "MessagePort.h" +#include "SerializedScriptValue.h" +#include "wtf/FileSystem.h" +#include "wtf/MemoryFootprint.h" +#include "wtf/text/WTFString.h" + +#include "Process.h" +#include +#if ENABLE(REMOTE_INSPECTOR) +#include "JavaScriptCore/RemoteInspectorServer.h" +#endif + +#include "JSDOMConvertBase.h" +#include "ZigSourceProvider.h" +#include "mimalloc.h" + +#include "JavaScriptCore/ControlFlowProfiler.h" + +using namespace JSC; +using namespace WTF; +using namespace WebCore; + +JSC_DECLARE_HOST_FUNCTION(functionStartRemoteDebugger); +JSC_DEFINE_HOST_FUNCTION(functionStartRemoteDebugger, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { +#if ENABLE(REMOTE_INSPECTOR) + static const char *defaultHost = "127.0.0.1\0"; + static uint16_t defaultPort = 9230; // node + 1 + + auto &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSC::JSValue hostValue = callFrame->argument(0); + JSC::JSValue portValue = callFrame->argument(1); + const char *host = defaultHost; + if (hostValue.isString()) { + + auto str = hostValue.toWTFString(globalObject); + if (!str.isEmpty()) + host = toCString(str).data(); + } else if (!hostValue.isUndefined()) { + throwVMError(globalObject, scope, + createTypeError(globalObject, "host must be a string"_s)); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + uint16_t port = defaultPort; + if (portValue.isNumber()) { + auto port_int = portValue.toUInt32(globalObject); + if (!(port_int > 0 && port_int < 65536)) { + throwVMError( + globalObject, scope, + createRangeError(globalObject, "port must be between 0 and 65535"_s)); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + port = port_int; + } else if (!portValue.isUndefined()) { + throwVMError( + globalObject, scope, + createTypeError(globalObject, + "port must be a number between 0 and 65535"_s)); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + globalObject->setInspectable(true); + auto &server = Inspector::RemoteInspectorServer::singleton(); + if (!server.start(reinterpret_cast(host), port)) { + throwVMError( + globalObject, scope, + createError(globalObject, "Failed to start server \""_s + host + ":"_s + + port + "\". Is port already in use?"_s)); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + RELEASE_AND_RETURN(scope, JSC::JSValue::encode(JSC::jsUndefined())); +#else + auto &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + throwVMError(globalObject, scope, + createTypeError( + globalObject, + "Remote inspector is not enabled in this build of Bun"_s)); + return JSC::JSValue::encode(JSC::jsUndefined()); +#endif +} + +JSC_DECLARE_HOST_FUNCTION(functionDescribe); +JSC_DEFINE_HOST_FUNCTION(functionDescribe, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + VM &vm = globalObject->vm(); + if (callFrame->argumentCount() < 1) + return JSValue::encode(jsUndefined()); + return JSValue::encode(jsString(vm, toString(callFrame->argument(0)))); +} + +JSC_DECLARE_HOST_FUNCTION(functionDescribeArray); +JSC_DEFINE_HOST_FUNCTION(functionDescribeArray, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + if (callFrame->argumentCount() < 1) + return JSValue::encode(jsUndefined()); + VM &vm = globalObject->vm(); + JSObject *object = jsDynamicCast(callFrame->argument(0)); + if (!object) + return JSValue::encode(jsNontrivialString(vm, ""_s)); + return JSValue::encode(jsNontrivialString( + vm, toString("butterfly()), + "; public length: ", object->getArrayLength(), + "; vector length: ", object->getVectorLength(), ">"))); +} + +JSC_DECLARE_HOST_FUNCTION(functionGCAndSweep); +JSC_DEFINE_HOST_FUNCTION(functionGCAndSweep, + (JSGlobalObject * globalObject, CallFrame *)) { + VM &vm = globalObject->vm(); + JSLockHolder lock(vm); + vm.heap.collectNow(Sync, CollectionScope::Full); + return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection())); +} + +JSC_DECLARE_HOST_FUNCTION(functionFullGC); +JSC_DEFINE_HOST_FUNCTION(functionFullGC, + (JSGlobalObject * globalObject, CallFrame *)) { + VM &vm = globalObject->vm(); + JSLockHolder lock(vm); + vm.heap.collectSync(CollectionScope::Full); + return JSValue::encode(jsNumber(vm.heap.sizeAfterLastFullCollection())); +} + +JSC_DECLARE_HOST_FUNCTION(functionEdenGC); +JSC_DEFINE_HOST_FUNCTION(functionEdenGC, + (JSGlobalObject * globalObject, CallFrame *)) { + VM &vm = globalObject->vm(); + JSLockHolder lock(vm); + vm.heap.collectSync(CollectionScope::Eden); + return JSValue::encode(jsNumber(vm.heap.sizeAfterLastEdenCollection())); +} + +JSC_DECLARE_HOST_FUNCTION(functionHeapSize); +JSC_DEFINE_HOST_FUNCTION(functionHeapSize, + (JSGlobalObject * globalObject, CallFrame *)) { + VM &vm = globalObject->vm(); + JSLockHolder lock(vm); + return JSValue::encode(jsNumber(vm.heap.size())); +} + +JSC::Structure * +createMemoryFootprintStructure(JSC::VM &vm, JSC::JSGlobalObject *globalObject) { + + JSC::Structure *structure = + globalObject->structureCache().emptyObjectStructureForPrototype( + globalObject, globalObject->objectPrototype(), 5); + JSC::PropertyOffset offset; + + structure = structure->addPropertyTransition( + vm, structure, Identifier::fromString(vm, "current"_s), 0, offset); + structure = structure->addPropertyTransition( + vm, structure, Identifier::fromString(vm, "peak"_s), 0, offset); + structure = structure->addPropertyTransition( + vm, structure, Identifier::fromString(vm, "currentCommit"_s), 0, offset); + structure = structure->addPropertyTransition( + vm, structure, Identifier::fromString(vm, "peakCommit"_s), 0, offset); + structure = structure->addPropertyTransition( + vm, structure, Identifier::fromString(vm, "pageFaults"_s), 0, offset); + + return structure; +} + +JSC_DECLARE_HOST_FUNCTION(functionMemoryUsageStatistics); +JSC_DEFINE_HOST_FUNCTION(functionMemoryUsageStatistics, + (JSGlobalObject * globalObject, CallFrame *)) { + + auto &vm = globalObject->vm(); + JSC::DisallowGC disallowGC; + + // this is a C API function + auto *stats = toJS(JSGetMemoryUsageStatistics(toRef(globalObject))); + + if (JSValue heapSizeValue = + stats->getDirect(vm, Identifier::fromString(vm, "heapSize"_s))) { + ASSERT(heapSizeValue.isNumber()); + if (heapSizeValue.toInt32(globalObject) == 0) { + vm.heap.collectNow(Sync, CollectionScope::Full); + stats = toJS(JSGetMemoryUsageStatistics(toRef(globalObject))); + } + } + + // This is missing from the C API + JSC::JSObject *protectedCounts = constructEmptyObject(globalObject); + auto typeCounts = *vm.heap.protectedObjectTypeCounts(); + for (auto &it : typeCounts) + protectedCounts->putDirect(vm, Identifier::fromLatin1(vm, it.key), + jsNumber(it.value)); + + stats->putDirect(vm, + Identifier::fromLatin1(vm, "protectedObjectTypeCounts"_s), + protectedCounts); + return JSValue::encode(stats); +} + +JSC_DECLARE_HOST_FUNCTION(functionCreateMemoryFootprint); +JSC_DEFINE_HOST_FUNCTION(functionCreateMemoryFootprint, + (JSGlobalObject * globalObject, CallFrame *)) { + + size_t elapsed_msecs = 0; + size_t user_msecs = 0; + size_t system_msecs = 0; + size_t current_rss = 0; + size_t peak_rss = 0; + size_t current_commit = 0; + size_t peak_commit = 0; + size_t page_faults = 0; + + mi_process_info(&elapsed_msecs, &user_msecs, &system_msecs, ¤t_rss, + &peak_rss, ¤t_commit, &peak_commit, &page_faults); + + // mi_process_info produces incorrect rss size on linux. + Zig::getRSS(¤t_rss); + + VM &vm = globalObject->vm(); + JSC::JSObject *object = JSC::constructEmptyObject( + vm, JSC::jsCast(globalObject) + ->memoryFootprintStructure()); + + object->putDirectOffset(vm, 0, jsNumber(current_rss)); + object->putDirectOffset(vm, 1, jsNumber(peak_rss)); + object->putDirectOffset(vm, 2, jsNumber(current_commit)); + object->putDirectOffset(vm, 3, jsNumber(peak_commit)); + object->putDirectOffset(vm, 4, jsNumber(page_faults)); + + return JSValue::encode(object); +} + +JSC_DECLARE_HOST_FUNCTION(functionNeverInlineFunction); +JSC_DEFINE_HOST_FUNCTION(functionNeverInlineFunction, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + return JSValue::encode(setNeverInline(globalObject, callFrame)); +} + +extern "C" bool Bun__mkdirp(JSC::JSGlobalObject *, const char *); + +JSC_DECLARE_HOST_FUNCTION(functionStartSamplingProfiler); +JSC_DEFINE_HOST_FUNCTION(functionStartSamplingProfiler, + (JSC::JSGlobalObject * globalObject, + JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + JSC::SamplingProfiler &samplingProfiler = + vm.ensureSamplingProfiler(WTF::Stopwatch::create()); + + JSC::JSValue directoryValue = callFrame->argument(0); + JSC::JSValue sampleValue = callFrame->argument(1); + + auto scope = DECLARE_THROW_SCOPE(vm); + if (directoryValue.isString()) { + auto path = directoryValue.toWTFString(globalObject); + if (!path.isEmpty()) { + StringPrintStream pathOut; + auto pathCString = toCString(String(path)); + if (!Bun__mkdirp(globalObject, pathCString.data())) { + throwVMError( + globalObject, scope, + createTypeError(globalObject, "directory couldn't be created"_s)); + return JSC::JSValue::encode(jsUndefined()); + } + + Options::samplingProfilerPath() = pathCString.data(); + samplingProfiler.registerForReportAtExit(); + } + } + if (sampleValue.isNumber()) { + unsigned sampleInterval = sampleValue.toUInt32(globalObject); + samplingProfiler.setTimingInterval( + Seconds::fromMicroseconds(sampleInterval)); + } + + samplingProfiler.noticeCurrentThreadAsJSCExecutionThread(); + samplingProfiler.start(); + return JSC::JSValue::encode(jsUndefined()); +} + +JSC_DECLARE_HOST_FUNCTION(functionSamplingProfilerStackTraces); +JSC_DEFINE_HOST_FUNCTION(functionSamplingProfilerStackTraces, + (JSC::JSGlobalObject * globalObject, + JSC::CallFrame *)) { + JSC::VM &vm = globalObject->vm(); + JSC::DeferTermination deferScope(vm); + auto scope = DECLARE_THROW_SCOPE(vm); + + if (!vm.samplingProfiler()) + return JSC::JSValue::encode(throwException( + globalObject, scope, + createError(globalObject, "Sampling profiler was never started"_s))); + + WTF::String jsonString = + vm.samplingProfiler()->stackTracesAsJSON()->toJSONString(); + JSC::EncodedJSValue result = + JSC::JSValue::encode(JSONParse(globalObject, jsonString)); + scope.releaseAssertNoException(); + return result; +} + +JSC_DECLARE_HOST_FUNCTION(functionGetRandomSeed); +JSC_DEFINE_HOST_FUNCTION(functionGetRandomSeed, + (JSGlobalObject * globalObject, CallFrame *)) { + return JSValue::encode(jsNumber(globalObject->weakRandom().seed())); +} + +JSC_DECLARE_HOST_FUNCTION(functionSetRandomSeed); +JSC_DEFINE_HOST_FUNCTION(functionSetRandomSeed, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + unsigned seed = callFrame->argument(0).toUInt32(globalObject); + RETURN_IF_EXCEPTION(scope, encodedJSValue()); + globalObject->weakRandom().setSeed(seed); + return JSValue::encode(jsUndefined()); +} + +JSC_DECLARE_HOST_FUNCTION(functionIsRope); +JSC_DEFINE_HOST_FUNCTION(functionIsRope, + (JSGlobalObject *, CallFrame *callFrame)) { + JSValue argument = callFrame->argument(0); + if (!argument.isString()) + return JSValue::encode(jsBoolean(false)); + const StringImpl *impl = asString(argument)->tryGetValueImpl(); + return JSValue::encode(jsBoolean(!impl)); +} + +JSC_DECLARE_HOST_FUNCTION(functionCallerSourceOrigin); +JSC_DEFINE_HOST_FUNCTION(functionCallerSourceOrigin, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + VM &vm = globalObject->vm(); + SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm); + if (sourceOrigin.url().isNull()) + return JSValue::encode(jsNull()); + return JSValue::encode(jsString(vm, sourceOrigin.string())); +} + +JSC_DECLARE_HOST_FUNCTION(functionNoFTL); +JSC_DEFINE_HOST_FUNCTION(functionNoFTL, + (JSGlobalObject *, CallFrame *callFrame)) { + if (callFrame->argumentCount()) { + FunctionExecutable *executable = + getExecutableForFunction(callFrame->argument(0)); + if (executable) + executable->setNeverFTLOptimize(true); + } + return JSValue::encode(jsUndefined()); +} + +JSC_DECLARE_HOST_FUNCTION(functionNoOSRExitFuzzing); +JSC_DEFINE_HOST_FUNCTION(functionNoOSRExitFuzzing, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + return JSValue::encode(setCannotUseOSRExitFuzzing(globalObject, callFrame)); +} + +JSC_DECLARE_HOST_FUNCTION(functionOptimizeNextInvocation); +JSC_DEFINE_HOST_FUNCTION(functionOptimizeNextInvocation, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + return JSValue::encode(optimizeNextInvocation(globalObject, callFrame)); +} + +JSC_DECLARE_HOST_FUNCTION(functionNumberOfDFGCompiles); +JSC_DEFINE_HOST_FUNCTION(functionNumberOfDFGCompiles, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + return JSValue::encode(numberOfDFGCompiles(globalObject, callFrame)); +} + +JSC_DECLARE_HOST_FUNCTION(functionReleaseWeakRefs); +JSC_DEFINE_HOST_FUNCTION(functionReleaseWeakRefs, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + globalObject->vm().finalizeSynchronousJSExecution(); + return JSValue::encode(jsUndefined()); +} + +JSC_DECLARE_HOST_FUNCTION(functionTotalCompileTime); +JSC_DEFINE_HOST_FUNCTION(functionTotalCompileTime, + (JSGlobalObject *, CallFrame *)) { + return JSValue::encode(jsNumber(JIT::totalCompileTime().milliseconds())); +} + +JSC_DECLARE_HOST_FUNCTION(functionGetProtectedObjects); +JSC_DEFINE_HOST_FUNCTION(functionGetProtectedObjects, + (JSGlobalObject * globalObject, CallFrame *)) { + MarkedArgumentBuffer list; + size_t result = 0; + globalObject->vm().heap.forEachProtectedCell( + [&](JSCell *cell) { list.append(cell); }); + RELEASE_ASSERT(!list.hasOverflowed()); + return JSC::JSValue::encode(constructArray( + globalObject, static_cast(nullptr), list)); +} + +JSC_DECLARE_HOST_FUNCTION(functionReoptimizationRetryCount); +JSC_DEFINE_HOST_FUNCTION(functionReoptimizationRetryCount, + (JSGlobalObject *, CallFrame *callFrame)) { + if (callFrame->argumentCount() < 1) + return JSValue::encode(jsUndefined()); + + CodeBlock *block = + getSomeBaselineCodeBlockForFunction(callFrame->argument(0)); + if (!block) + return JSValue::encode(jsNumber(0)); + + return JSValue::encode(jsNumber(block->reoptimizationRetryCounter())); +} + +extern "C" void Bun__drainMicrotasks(); + +JSC_DECLARE_HOST_FUNCTION(functionDrainMicrotasks); +JSC_DEFINE_HOST_FUNCTION(functionDrainMicrotasks, + (JSGlobalObject * globalObject, CallFrame *)) { + VM &vm = globalObject->vm(); + vm.drainMicrotasks(); + Bun__drainMicrotasks(); + return JSValue::encode(jsUndefined()); +} + +JSC_DEFINE_HOST_FUNCTION(functionSetTimeZone, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + if (callFrame->argumentCount() < 1) { + throwTypeError(globalObject, scope, + "setTimeZone requires a timezone string"_s); + return encodedJSValue(); + } + + if (!callFrame->argument(0).isString()) { + throwTypeError(globalObject, scope, + "setTimeZone requires a timezone string"_s); + return encodedJSValue(); + } + + String timeZoneName = callFrame->argument(0).toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, encodedJSValue()); + + double time = callFrame->argument(1).toNumber(globalObject); + RETURN_IF_EXCEPTION(scope, encodedJSValue()); + + if (!WTF::setTimeZoneOverride(timeZoneName)) { + throwTypeError(globalObject, scope, + makeString("Invalid timezone: \""_s, timeZoneName, "\""_s)); + return encodedJSValue(); + } + vm.dateCache.resetIfNecessarySlow(); + WTF::Vector buffer; + WTF::getTimeZoneOverride(buffer); + WTF::String timeZoneString(buffer.data(), buffer.size()); + return JSValue::encode(jsString(vm, timeZoneString)); +} + +JSC_DEFINE_HOST_FUNCTION(functionRunProfiler, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + JSC::SamplingProfiler &samplingProfiler = + vm.ensureSamplingProfiler(WTF::Stopwatch::create()); + + JSC::JSValue callbackValue = callFrame->argument(0); + auto throwScope = DECLARE_THROW_SCOPE(vm); + if (callbackValue.isUndefinedOrNull() || !callbackValue.isCallable()) { + throwException( + globalObject, throwScope, + createTypeError(globalObject, "First argument must be a function."_s)); + return JSValue::encode(JSValue{}); + } + + JSC::JSFunction *function = jsCast(callbackValue); + + JSC::JSValue sampleValue = callFrame->argument(1); + if (sampleValue.isNumber()) { + unsigned sampleInterval = sampleValue.toUInt32(globalObject); + samplingProfiler.setTimingInterval( + Seconds::fromMicroseconds(sampleInterval)); + } + + JSC::CallData callData = JSC::getCallData(function); + MarkedArgumentBuffer args; + + samplingProfiler.noticeCurrentThreadAsJSCExecutionThread(); + samplingProfiler.start(); + JSC::call(globalObject, function, callData, JSC::jsUndefined(), args); + samplingProfiler.pause(); + if (throwScope.exception()) { + samplingProfiler.shutdown(); + samplingProfiler.clearData(); + return JSValue::encode(JSValue{}); + } + + StringPrintStream topFunctions; + samplingProfiler.reportTopFunctions(topFunctions); + + StringPrintStream byteCodes; + samplingProfiler.reportTopBytecodes(byteCodes); + + JSValue stackTraces = JSONParse( + globalObject, samplingProfiler.stackTracesAsJSON()->toJSONString()); + + samplingProfiler.shutdown(); + samplingProfiler.clearData(); + + JSObject *result = + constructEmptyObject(globalObject, globalObject->objectPrototype(), 3); + result->putDirect(vm, Identifier::fromString(vm, "functions"_s), + jsString(vm, topFunctions.toString())); + result->putDirect(vm, Identifier::fromString(vm, "bytecodes"_s), + jsString(vm, byteCodes.toString())); + result->putDirect(vm, Identifier::fromString(vm, "stackTraces"_s), + stackTraces); + + return JSValue::encode(result); +} + +JSC_DECLARE_HOST_FUNCTION(functionGenerateHeapSnapshotForDebugging); +JSC_DEFINE_HOST_FUNCTION(functionGenerateHeapSnapshotForDebugging, + (JSGlobalObject * globalObject, CallFrame *)) { + VM &vm = globalObject->vm(); + JSLockHolder lock(vm); + DeferTermination deferScope(vm); + auto scope = DECLARE_THROW_SCOPE(vm); + String jsonString; + { + DeferGCForAWhile deferGC(vm); // Prevent concurrent GC from interfering with + // the full GC that the snapshot does. + + HeapSnapshotBuilder snapshotBuilder( + vm.ensureHeapProfiler(), + HeapSnapshotBuilder::SnapshotType::GCDebuggingSnapshot); + snapshotBuilder.buildSnapshot(); + + jsonString = snapshotBuilder.json(); + } + scope.releaseAssertNoException(); + + return JSValue::encode(JSONParse(globalObject, WTFMove(jsonString))); +} + +JSC_DEFINE_HOST_FUNCTION(functionSerialize, + (JSGlobalObject * lexicalGlobalObject, + CallFrame *callFrame)) { + auto *globalObject = jsCast(lexicalGlobalObject); + JSC::VM &vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + + JSValue value = callFrame->argument(0); + JSValue optionsObject = callFrame->argument(1); + bool asNodeBuffer = false; + if (optionsObject.isObject()) { + JSC::JSObject *options = optionsObject.getObject(); + if (JSC::JSValue binaryTypeValue = options->getIfPropertyExists( + globalObject, JSC::Identifier::fromString(vm, "binaryType"_s))) { + if (!binaryTypeValue.isString()) { + throwTypeError(globalObject, throwScope, + "binaryType must be a string"_s); + return JSValue::encode(jsUndefined()); + } + + asNodeBuffer = + binaryTypeValue.toWTFString(globalObject) == "nodebuffer"_s; + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + } + } + + Vector> transferList; + Vector> dummyPorts; + ExceptionOr> serialized = + SerializedScriptValue::create(*globalObject, value, WTFMove(transferList), + dummyPorts); + + if (serialized.hasException()) { + WebCore::propagateException(*globalObject, throwScope, + serialized.releaseException()); + return JSValue::encode(jsUndefined()); + } + + auto serializedValue = serialized.releaseReturnValue(); + auto arrayBuffer = serializedValue->toArrayBuffer(); + + if (asNodeBuffer) { + size_t byteLength = arrayBuffer->byteLength(); + JSC::JSUint8Array *uint8Array = JSC::JSUint8Array::create( + lexicalGlobalObject, globalObject->JSBufferSubclassStructure(), + WTFMove(arrayBuffer), 0, byteLength); + return JSValue::encode(uint8Array); + } + + if (arrayBuffer->isShared()) { + return JSValue::encode( + JSArrayBuffer::create(vm, + globalObject->arrayBufferStructureWithSharingMode< + ArrayBufferSharingMode::Shared>(), + WTFMove(arrayBuffer))); + } + + return JSValue::encode(JSArrayBuffer::create( + vm, globalObject->arrayBufferStructure(), WTFMove(arrayBuffer))); +} +JSC_DEFINE_HOST_FUNCTION(functionDeserialize, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + JSValue value = callFrame->argument(0); + + JSValue result; + + if (auto *jsArrayBuffer = jsDynamicCast(value)) { + result = SerializedScriptValue::fromArrayBuffer( + *globalObject, globalObject, jsArrayBuffer->impl(), 0, + jsArrayBuffer->impl()->byteLength()); + } else if (auto *view = jsDynamicCast(value)) { + auto arrayBuffer = view->possiblySharedImpl()->possiblySharedBuffer(); + result = SerializedScriptValue::fromArrayBuffer( + *globalObject, globalObject, arrayBuffer.get(), view->byteOffset(), + view->byteLength()); + } else { + throwTypeError(globalObject, throwScope, + "First argument must be an ArrayBuffer"_s); + return JSValue::encode(jsUndefined()); + } + + RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined())); + RELEASE_AND_RETURN(throwScope, JSValue::encode(result)); +} + +extern "C" EncodedJSValue ByteRangeMapping__findExecutedLines( + JSC::JSGlobalObject *, BunString sourceURL, BasicBlockRange *ranges, + size_t len, size_t functionOffset, bool ignoreSourceMap); + +JSC_DEFINE_HOST_FUNCTION(functionCodeCoverageForFile, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + VM &vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + + String fileName = callFrame->argument(0).toWTFString(globalObject); + RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); + bool ignoreSourceMap = callFrame->argument(1).toBoolean(globalObject); + + auto sourceID = Zig::sourceIDForSourceURL(fileName); + if (!sourceID) { + throwException(globalObject, throwScope, + createError(globalObject, "No source for file"_s)); + return JSValue::encode(jsUndefined()); + } + + auto basicBlocks = + vm.controlFlowProfiler()->getBasicBlocksForSourceIDWithoutFunctionRange( + sourceID, vm); + + if (basicBlocks.isEmpty()) { + return JSC::JSValue::encode( + JSC::constructEmptyArray(globalObject, nullptr, 0)); + } + + size_t functionStartOffset = basicBlocks.size(); + + const Vector> &functionRanges = + vm.functionHasExecutedCache()->getFunctionRanges(sourceID); + + basicBlocks.reserveCapacity(functionRanges.size() + basicBlocks.size()); + + for (const auto &functionRange : functionRanges) { + BasicBlockRange range; + range.m_hasExecuted = std::get<0>(functionRange); + range.m_startOffset = static_cast(std::get<1>(functionRange)); + range.m_endOffset = static_cast(std::get<2>(functionRange)); + range.m_executionCount = + range.m_hasExecuted + ? 1 + : 0; // This is a hack. We don't actually count this. + basicBlocks.append(range); + } + + return ByteRangeMapping__findExecutedLines( + globalObject, Bun::toString(fileName), basicBlocks.data(), + basicBlocks.size(), functionStartOffset, ignoreSourceMap); +} + +// clang-format off +/* Source for BunJSCModuleTable.lut.h +@begin BunJSCModuleTable + callerSourceOrigin functionCallerSourceOrigin Function 0 + jscDescribe functionDescribe Function 0 + jscDescribeArray functionDescribeArray Function 0 + drainMicrotasks functionDrainMicrotasks Function 0 + edenGC functionEdenGC Function 0 + fullGC functionFullGC Function 0 + gcAndSweep functionGCAndSweep Function 0 + getRandomSeed functionGetRandomSeed Function 0 + heapSize functionHeapSize Function 0 + heapStats functionMemoryUsageStatistics Function 0 + startSamplingProfiler functionStartSamplingProfiler Function 0 + samplingProfilerStackTraces functionSamplingProfilerStackTraces Function 0 + noInline functionNeverInlineFunction Function 0 + isRope functionIsRope Function 0 + memoryUsage functionCreateMemoryFootprint Function 0 + noFTL functionNoFTL Function 0 + noOSRExitFuzzing functionNoOSRExitFuzzing Function 0 + numberOfDFGCompiles functionNumberOfDFGCompiles Function 0 + optimizeNextInvocation functionOptimizeNextInvocation Function 0 + releaseWeakRefs functionReleaseWeakRefs Function 0 + reoptimizationRetryCount functionReoptimizationRetryCount Function 0 + setRandomSeed functionSetRandomSeed Function 0 + startRemoteDebugger functionStartRemoteDebugger Function 0 + totalCompileTime functionTotalCompileTime Function 0 + getProtectedObjects functionGetProtectedObjects Function 0 + generateHeapSnapshotForDebugging functionGenerateHeapSnapshotForDebugging Function 0 + profile functionRunProfiler Function 0 + setTimeZone functionSetTimeZone Function 0 + serialize functionSerialize Function 0 + deserialize functionDeserialize Function 0 +@end +*/ + +namespace Zig { +DEFINE_NATIVE_MODULE(BunJSC) +{ + INIT_NATIVE_MODULE(33); + + putNativeFn(Identifier::fromString(vm, "callerSourceOrigin"_s), functionCallerSourceOrigin); + putNativeFn(Identifier::fromString(vm, "jscDescribe"_s), functionDescribe); + putNativeFn(Identifier::fromString(vm, "jscDescribeArray"_s), functionDescribeArray); + putNativeFn(Identifier::fromString(vm, "drainMicrotasks"_s), functionDrainMicrotasks); + putNativeFn(Identifier::fromString(vm, "edenGC"_s), functionEdenGC); + putNativeFn(Identifier::fromString(vm, "fullGC"_s), functionFullGC); + putNativeFn(Identifier::fromString(vm, "gcAndSweep"_s), functionGCAndSweep); + putNativeFn(Identifier::fromString(vm, "getRandomSeed"_s), functionGetRandomSeed); + putNativeFn(Identifier::fromString(vm, "heapSize"_s), functionHeapSize); + putNativeFn(Identifier::fromString(vm, "heapStats"_s), functionMemoryUsageStatistics); + putNativeFn(Identifier::fromString(vm, "startSamplingProfiler"_s), functionStartSamplingProfiler); + putNativeFn(Identifier::fromString(vm, "samplingProfilerStackTraces"_s), functionSamplingProfilerStackTraces); + putNativeFn(Identifier::fromString(vm, "noInline"_s), functionNeverInlineFunction); + putNativeFn(Identifier::fromString(vm, "isRope"_s), functionIsRope); + putNativeFn(Identifier::fromString(vm, "memoryUsage"_s), functionCreateMemoryFootprint); + putNativeFn(Identifier::fromString(vm, "noFTL"_s), functionNoFTL); + putNativeFn(Identifier::fromString(vm, "noOSRExitFuzzing"_s), functionNoOSRExitFuzzing); + putNativeFn(Identifier::fromString(vm, "numberOfDFGCompiles"_s), functionNumberOfDFGCompiles); + putNativeFn(Identifier::fromString(vm, "optimizeNextInvocation"_s), functionOptimizeNextInvocation); + putNativeFn(Identifier::fromString(vm, "releaseWeakRefs"_s), functionReleaseWeakRefs); + putNativeFn(Identifier::fromString(vm, "reoptimizationRetryCount"_s), functionReoptimizationRetryCount); + putNativeFn(Identifier::fromString(vm, "setRandomSeed"_s), functionSetRandomSeed); + putNativeFn(Identifier::fromString(vm, "startRemoteDebugger"_s), functionStartRemoteDebugger); + putNativeFn(Identifier::fromString(vm, "totalCompileTime"_s), functionTotalCompileTime); + putNativeFn(Identifier::fromString(vm, "getProtectedObjects"_s), functionGetProtectedObjects); + putNativeFn(Identifier::fromString(vm, "generateHeapSnapshotForDebugging"_s), functionGenerateHeapSnapshotForDebugging); + putNativeFn(Identifier::fromString(vm, "profile"_s), functionRunProfiler); + putNativeFn(Identifier::fromString(vm, "codeCoverageForFile"_s), functionCodeCoverageForFile); + putNativeFn(Identifier::fromString(vm, "setTimeZone"_s), functionSetTimeZone); + putNativeFn(Identifier::fromString(vm, "serialize"_s), functionSerialize); + putNativeFn(Identifier::fromString(vm, "deserialize"_s), functionDeserialize); + + // Deprecated + putNativeFn(Identifier::fromString(vm, "describe"_s), functionDescribe); + putNativeFn(Identifier::fromString(vm, "describeArray"_s), functionDescribeArray); + putNativeFn(Identifier::fromString(vm, "setTimezone"_s), functionSetTimeZone); + + RETURN_NATIVE_MODULE(); +} + +} // namespace Zig diff --git a/src/bun.js/modules/BunObjectModule.cpp b/src/bun.js/modules/BunObjectModule.cpp new file mode 100644 index 00000000000000..55f694fa1696d6 --- /dev/null +++ b/src/bun.js/modules/BunObjectModule.cpp @@ -0,0 +1,24 @@ +#include "root.h" + +#include "ZigGlobalObject.h" + +#include "ObjectModule.h" + +namespace Zig { +void generateNativeModule_BunObject(JSC::JSGlobalObject *lexicalGlobalObject, + JSC::Identifier moduleKey, + Vector &exportNames, + JSC::MarkedArgumentBuffer &exportValues) { + JSC::VM &vm = lexicalGlobalObject->vm(); + Zig::GlobalObject *globalObject = + reinterpret_cast(lexicalGlobalObject); + + JSObject *object = + globalObject->get(globalObject, Identifier::fromString(vm, "Bun"_s)) + .getObject(); + + exportNames.append(vm.propertyNames->defaultKeyword); + exportValues.append(object); +} + +} // namespace Zig \ No newline at end of file diff --git a/src/bun.js/modules/BunObjectModule.h b/src/bun.js/modules/BunObjectModule.h new file mode 100644 index 00000000000000..3d7ba1534f0825 --- /dev/null +++ b/src/bun.js/modules/BunObjectModule.h @@ -0,0 +1,8 @@ + +namespace Zig { +void generateNativeModule_BunObject(JSC::JSGlobalObject *lexicalGlobalObject, + JSC::Identifier moduleKey, + Vector &exportNames, + JSC::MarkedArgumentBuffer &exportValues); + +} // namespace Zig \ No newline at end of file diff --git a/src/bun.js/modules/ConstantsModule.h b/src/bun.js/modules/ConstantsModule.h deleted file mode 100644 index 8d7c1602b6382d..00000000000000 --- a/src/bun.js/modules/ConstantsModule.h +++ /dev/null @@ -1,262 +0,0 @@ -#include "JavaScriptCore/JSGlobalObject.h" -#include "ZigGlobalObject.h" - -namespace Zig { -using namespace WebCore; - -inline void generateConstantsSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues) { - JSC::VM &vm = lexicalGlobalObject->vm(); - GlobalObject *globalObject = reinterpret_cast(lexicalGlobalObject); - - auto* defaultObject = JSC::constructEmptyObject(globalObject); - - - auto exportProperty = [&](JSC::Identifier name, JSC::JSValue value) { - exportNames.append(name); - exportValues.append(value); - defaultObject->putDirect(vm, name, value, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | 0); - }; - - exportProperty(JSC::Identifier::fromString(vm, "RTLD_LAZY"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "RTLD_NOW"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "RTLD_GLOBAL"_s), JSC::jsNumber(256)); - exportProperty(JSC::Identifier::fromString(vm, "RTLD_LOCAL"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "RTLD_DEEPBIND"_s), JSC::jsNumber(8)); - exportProperty(JSC::Identifier::fromString(vm, "E2BIG"_s), JSC::jsNumber(7)); - exportProperty(JSC::Identifier::fromString(vm, "EACCES"_s), JSC::jsNumber(13)); - exportProperty(JSC::Identifier::fromString(vm, "EADDRINUSE"_s), JSC::jsNumber(98)); - exportProperty(JSC::Identifier::fromString(vm, "EADDRNOTAVAIL"_s), JSC::jsNumber(99)); - exportProperty(JSC::Identifier::fromString(vm, "EAFNOSUPPORT"_s), JSC::jsNumber(97)); - exportProperty(JSC::Identifier::fromString(vm, "EAGAIN"_s), JSC::jsNumber(11)); - exportProperty(JSC::Identifier::fromString(vm, "EALREADY"_s), JSC::jsNumber(114)); - exportProperty(JSC::Identifier::fromString(vm, "EBADF"_s), JSC::jsNumber(9)); - exportProperty(JSC::Identifier::fromString(vm, "EBADMSG"_s), JSC::jsNumber(74)); - exportProperty(JSC::Identifier::fromString(vm, "EBUSY"_s), JSC::jsNumber(16)); - exportProperty(JSC::Identifier::fromString(vm, "ECANCELED"_s), JSC::jsNumber(125)); - exportProperty(JSC::Identifier::fromString(vm, "ECHILD"_s), JSC::jsNumber(10)); - exportProperty(JSC::Identifier::fromString(vm, "ECONNABORTED"_s), JSC::jsNumber(103)); - exportProperty(JSC::Identifier::fromString(vm, "ECONNREFUSED"_s), JSC::jsNumber(111)); - exportProperty(JSC::Identifier::fromString(vm, "ECONNRESET"_s), JSC::jsNumber(104)); - exportProperty(JSC::Identifier::fromString(vm, "EDEADLK"_s), JSC::jsNumber(35)); - exportProperty(JSC::Identifier::fromString(vm, "EDESTADDRREQ"_s), JSC::jsNumber(89)); - exportProperty(JSC::Identifier::fromString(vm, "EDOM"_s), JSC::jsNumber(33)); - exportProperty(JSC::Identifier::fromString(vm, "EDQUOT"_s), JSC::jsNumber(122)); - exportProperty(JSC::Identifier::fromString(vm, "EEXIST"_s), JSC::jsNumber(17)); - exportProperty(JSC::Identifier::fromString(vm, "EFAULT"_s), JSC::jsNumber(14)); - exportProperty(JSC::Identifier::fromString(vm, "EFBIG"_s), JSC::jsNumber(27)); - exportProperty(JSC::Identifier::fromString(vm, "EHOSTUNREACH"_s), JSC::jsNumber(113)); - exportProperty(JSC::Identifier::fromString(vm, "EIDRM"_s), JSC::jsNumber(43)); - exportProperty(JSC::Identifier::fromString(vm, "EILSEQ"_s), JSC::jsNumber(84)); - exportProperty(JSC::Identifier::fromString(vm, "EINPROGRESS"_s), JSC::jsNumber(115)); - exportProperty(JSC::Identifier::fromString(vm, "EINTR"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "EINVAL"_s), JSC::jsNumber(22)); - exportProperty(JSC::Identifier::fromString(vm, "EIO"_s), JSC::jsNumber(5)); - exportProperty(JSC::Identifier::fromString(vm, "EISCONN"_s), JSC::jsNumber(106)); - exportProperty(JSC::Identifier::fromString(vm, "EISDIR"_s), JSC::jsNumber(21)); - exportProperty(JSC::Identifier::fromString(vm, "ELOOP"_s), JSC::jsNumber(40)); - exportProperty(JSC::Identifier::fromString(vm, "EMFILE"_s), JSC::jsNumber(24)); - exportProperty(JSC::Identifier::fromString(vm, "EMLINK"_s), JSC::jsNumber(31)); - exportProperty(JSC::Identifier::fromString(vm, "EMSGSIZE"_s), JSC::jsNumber(90)); - exportProperty(JSC::Identifier::fromString(vm, "EMULTIHOP"_s), JSC::jsNumber(72)); - exportProperty(JSC::Identifier::fromString(vm, "ENAMETOOLONG"_s), JSC::jsNumber(36)); - exportProperty(JSC::Identifier::fromString(vm, "ENETDOWN"_s), JSC::jsNumber(100)); - exportProperty(JSC::Identifier::fromString(vm, "ENETRESET"_s), JSC::jsNumber(102)); - exportProperty(JSC::Identifier::fromString(vm, "ENETUNREACH"_s), JSC::jsNumber(101)); - exportProperty(JSC::Identifier::fromString(vm, "ENFILE"_s), JSC::jsNumber(23)); - exportProperty(JSC::Identifier::fromString(vm, "ENOBUFS"_s), JSC::jsNumber(105)); - exportProperty(JSC::Identifier::fromString(vm, "ENODATA"_s), JSC::jsNumber(61)); - exportProperty(JSC::Identifier::fromString(vm, "ENODEV"_s), JSC::jsNumber(19)); - exportProperty(JSC::Identifier::fromString(vm, "ENOENT"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "ENOEXEC"_s), JSC::jsNumber(8)); - exportProperty(JSC::Identifier::fromString(vm, "ENOLCK"_s), JSC::jsNumber(37)); - exportProperty(JSC::Identifier::fromString(vm, "ENOLINK"_s), JSC::jsNumber(67)); - exportProperty(JSC::Identifier::fromString(vm, "ENOMEM"_s), JSC::jsNumber(12)); - exportProperty(JSC::Identifier::fromString(vm, "ENOMSG"_s), JSC::jsNumber(42)); - exportProperty(JSC::Identifier::fromString(vm, "ENOPROTOOPT"_s), JSC::jsNumber(92)); - exportProperty(JSC::Identifier::fromString(vm, "ENOSPC"_s), JSC::jsNumber(28)); - exportProperty(JSC::Identifier::fromString(vm, "ENOSR"_s), JSC::jsNumber(63)); - exportProperty(JSC::Identifier::fromString(vm, "ENOSTR"_s), JSC::jsNumber(60)); - exportProperty(JSC::Identifier::fromString(vm, "ENOSYS"_s), JSC::jsNumber(38)); - exportProperty(JSC::Identifier::fromString(vm, "ENOTCONN"_s), JSC::jsNumber(107)); - exportProperty(JSC::Identifier::fromString(vm, "ENOTDIR"_s), JSC::jsNumber(20)); - exportProperty(JSC::Identifier::fromString(vm, "ENOTEMPTY"_s), JSC::jsNumber(39)); - exportProperty(JSC::Identifier::fromString(vm, "ENOTSOCK"_s), JSC::jsNumber(88)); - exportProperty(JSC::Identifier::fromString(vm, "ENOTSUP"_s), JSC::jsNumber(95)); - exportProperty(JSC::Identifier::fromString(vm, "ENOTTY"_s), JSC::jsNumber(25)); - exportProperty(JSC::Identifier::fromString(vm, "ENXIO"_s), JSC::jsNumber(6)); - exportProperty(JSC::Identifier::fromString(vm, "EOPNOTSUPP"_s), JSC::jsNumber(95)); - exportProperty(JSC::Identifier::fromString(vm, "EOVERFLOW"_s), JSC::jsNumber(75)); - exportProperty(JSC::Identifier::fromString(vm, "EPERM"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "EPIPE"_s), JSC::jsNumber(32)); - exportProperty(JSC::Identifier::fromString(vm, "EPROTO"_s), JSC::jsNumber(71)); - exportProperty(JSC::Identifier::fromString(vm, "EPROTONOSUPPORT"_s), JSC::jsNumber(93)); - exportProperty(JSC::Identifier::fromString(vm, "EPROTOTYPE"_s), JSC::jsNumber(91)); - exportProperty(JSC::Identifier::fromString(vm, "ERANGE"_s), JSC::jsNumber(34)); - exportProperty(JSC::Identifier::fromString(vm, "EROFS"_s), JSC::jsNumber(30)); - exportProperty(JSC::Identifier::fromString(vm, "ESPIPE"_s), JSC::jsNumber(29)); - exportProperty(JSC::Identifier::fromString(vm, "ESRCH"_s), JSC::jsNumber(3)); - exportProperty(JSC::Identifier::fromString(vm, "ESTALE"_s), JSC::jsNumber(116)); - exportProperty(JSC::Identifier::fromString(vm, "ETIME"_s), JSC::jsNumber(62)); - exportProperty(JSC::Identifier::fromString(vm, "ETIMEDOUT"_s), JSC::jsNumber(110)); - exportProperty(JSC::Identifier::fromString(vm, "ETXTBSY"_s), JSC::jsNumber(26)); - exportProperty(JSC::Identifier::fromString(vm, "EWOULDBLOCK"_s), JSC::jsNumber(11)); - exportProperty(JSC::Identifier::fromString(vm, "EXDEV"_s), JSC::jsNumber(18)); - exportProperty(JSC::Identifier::fromString(vm, "PRIORITY_LOW"_s), JSC::jsNumber(19)); - exportProperty(JSC::Identifier::fromString(vm, "PRIORITY_BELOW_NORMAL"_s), JSC::jsNumber(10)); - exportProperty(JSC::Identifier::fromString(vm, "PRIORITY_NORMAL"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "PRIORITY_ABOVE_NORMAL"_s), JSC::jsNumber(-7)); - exportProperty(JSC::Identifier::fromString(vm, "PRIORITY_HIGH"_s), JSC::jsNumber(-14)); - exportProperty(JSC::Identifier::fromString(vm, "PRIORITY_HIGHEST"_s), JSC::jsNumber(-20)); - exportProperty(JSC::Identifier::fromString(vm, "SIGHUP"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "SIGINT"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "SIGQUIT"_s), JSC::jsNumber(3)); - exportProperty(JSC::Identifier::fromString(vm, "SIGILL"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "SIGTRAP"_s), JSC::jsNumber(5)); - exportProperty(JSC::Identifier::fromString(vm, "SIGABRT"_s), JSC::jsNumber(6)); - exportProperty(JSC::Identifier::fromString(vm, "SIGIOT"_s), JSC::jsNumber(6)); - exportProperty(JSC::Identifier::fromString(vm, "SIGBUS"_s), JSC::jsNumber(7)); - exportProperty(JSC::Identifier::fromString(vm, "SIGFPE"_s), JSC::jsNumber(8)); - exportProperty(JSC::Identifier::fromString(vm, "SIGKILL"_s), JSC::jsNumber(9)); - exportProperty(JSC::Identifier::fromString(vm, "SIGUSR1"_s), JSC::jsNumber(10)); - exportProperty(JSC::Identifier::fromString(vm, "SIGSEGV"_s), JSC::jsNumber(11)); - exportProperty(JSC::Identifier::fromString(vm, "SIGUSR2"_s), JSC::jsNumber(12)); - exportProperty(JSC::Identifier::fromString(vm, "SIGPIPE"_s), JSC::jsNumber(13)); - exportProperty(JSC::Identifier::fromString(vm, "SIGALRM"_s), JSC::jsNumber(14)); - exportProperty(JSC::Identifier::fromString(vm, "SIGTERM"_s), JSC::jsNumber(15)); - exportProperty(JSC::Identifier::fromString(vm, "SIGCHLD"_s), JSC::jsNumber(17)); - exportProperty(JSC::Identifier::fromString(vm, "SIGSTKFLT"_s), JSC::jsNumber(16)); - exportProperty(JSC::Identifier::fromString(vm, "SIGCONT"_s), JSC::jsNumber(18)); - exportProperty(JSC::Identifier::fromString(vm, "SIGSTOP"_s), JSC::jsNumber(19)); - exportProperty(JSC::Identifier::fromString(vm, "SIGTSTP"_s), JSC::jsNumber(20)); - exportProperty(JSC::Identifier::fromString(vm, "SIGTTIN"_s), JSC::jsNumber(21)); - exportProperty(JSC::Identifier::fromString(vm, "SIGTTOU"_s), JSC::jsNumber(22)); - exportProperty(JSC::Identifier::fromString(vm, "SIGURG"_s), JSC::jsNumber(23)); - exportProperty(JSC::Identifier::fromString(vm, "SIGXCPU"_s), JSC::jsNumber(24)); - exportProperty(JSC::Identifier::fromString(vm, "SIGXFSZ"_s), JSC::jsNumber(25)); - exportProperty(JSC::Identifier::fromString(vm, "SIGVTALRM"_s), JSC::jsNumber(26)); - exportProperty(JSC::Identifier::fromString(vm, "SIGPROF"_s), JSC::jsNumber(27)); - exportProperty(JSC::Identifier::fromString(vm, "SIGWINCH"_s), JSC::jsNumber(28)); - exportProperty(JSC::Identifier::fromString(vm, "SIGIO"_s), JSC::jsNumber(29)); - exportProperty(JSC::Identifier::fromString(vm, "SIGPOLL"_s), JSC::jsNumber(29)); - exportProperty(JSC::Identifier::fromString(vm, "SIGPWR"_s), JSC::jsNumber(30)); - exportProperty(JSC::Identifier::fromString(vm, "SIGSYS"_s), JSC::jsNumber(31)); - exportProperty(JSC::Identifier::fromString(vm, "UV_FS_SYMLINK_DIR"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "UV_FS_SYMLINK_JUNCTION"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "O_RDONLY"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "O_WRONLY"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "O_RDWR"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_UNKNOWN"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_FILE"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_DIR"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_LINK"_s), JSC::jsNumber(3)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_FIFO"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_SOCKET"_s), JSC::jsNumber(5)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_CHAR"_s), JSC::jsNumber(6)); - exportProperty(JSC::Identifier::fromString(vm, "UV_DIRENT_BLOCK"_s), JSC::jsNumber(7)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFMT"_s), JSC::jsNumber(61440)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFREG"_s), JSC::jsNumber(32768)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFDIR"_s), JSC::jsNumber(16384)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFCHR"_s), JSC::jsNumber(8192)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFBLK"_s), JSC::jsNumber(24576)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFIFO"_s), JSC::jsNumber(4096)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFLNK"_s), JSC::jsNumber(40960)); - exportProperty(JSC::Identifier::fromString(vm, "S_IFSOCK"_s), JSC::jsNumber(49152)); - exportProperty(JSC::Identifier::fromString(vm, "O_CREAT"_s), JSC::jsNumber(64)); - exportProperty(JSC::Identifier::fromString(vm, "O_EXCL"_s), JSC::jsNumber(128)); - exportProperty(JSC::Identifier::fromString(vm, "UV_FS_O_FILEMAP"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "O_NOCTTY"_s), JSC::jsNumber(256)); - exportProperty(JSC::Identifier::fromString(vm, "O_TRUNC"_s), JSC::jsNumber(512)); - exportProperty(JSC::Identifier::fromString(vm, "O_APPEND"_s), JSC::jsNumber(1024)); - exportProperty(JSC::Identifier::fromString(vm, "O_DIRECTORY"_s), JSC::jsNumber(65536)); - exportProperty(JSC::Identifier::fromString(vm, "O_NOATIME"_s), JSC::jsNumber(262144)); - exportProperty(JSC::Identifier::fromString(vm, "O_NOFOLLOW"_s), JSC::jsNumber(131072)); - exportProperty(JSC::Identifier::fromString(vm, "O_SYNC"_s), JSC::jsNumber(1052672)); - exportProperty(JSC::Identifier::fromString(vm, "O_DSYNC"_s), JSC::jsNumber(4096)); - exportProperty(JSC::Identifier::fromString(vm, "O_DIRECT"_s), JSC::jsNumber(16384)); - exportProperty(JSC::Identifier::fromString(vm, "O_NONBLOCK"_s), JSC::jsNumber(2048)); - exportProperty(JSC::Identifier::fromString(vm, "S_IRWXU"_s), JSC::jsNumber(448)); - exportProperty(JSC::Identifier::fromString(vm, "S_IRUSR"_s), JSC::jsNumber(256)); - exportProperty(JSC::Identifier::fromString(vm, "S_IWUSR"_s), JSC::jsNumber(128)); - exportProperty(JSC::Identifier::fromString(vm, "S_IXUSR"_s), JSC::jsNumber(64)); - exportProperty(JSC::Identifier::fromString(vm, "S_IRWXG"_s), JSC::jsNumber(56)); - exportProperty(JSC::Identifier::fromString(vm, "S_IRGRP"_s), JSC::jsNumber(32)); - exportProperty(JSC::Identifier::fromString(vm, "S_IWGRP"_s), JSC::jsNumber(16)); - exportProperty(JSC::Identifier::fromString(vm, "S_IXGRP"_s), JSC::jsNumber(8)); - exportProperty(JSC::Identifier::fromString(vm, "S_IRWXO"_s), JSC::jsNumber(7)); - exportProperty(JSC::Identifier::fromString(vm, "S_IROTH"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "S_IWOTH"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "S_IXOTH"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "F_OK"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "R_OK"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "W_OK"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "X_OK"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "UV_FS_COPYFILE_EXCL"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "COPYFILE_EXCL"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "UV_FS_COPYFILE_FICLONE"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "COPYFILE_FICLONE"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "UV_FS_COPYFILE_FICLONE_FORCE"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "COPYFILE_FICLONE_FORCE"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "OPENSSL_VERSION_NUMBER"_s), JSC::jsNumber(805306496)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_ALL"_s), JSC::jsNumber(2147485776)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_ALLOW_NO_DHE_KEX"_s), JSC::jsNumber(1024)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION"_s), JSC::jsNumber(262144)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_CIPHER_SERVER_PREFERENCE"_s), JSC::jsNumber(4194304)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_CISCO_ANYCONNECT"_s), JSC::jsNumber(32768)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_COOKIE_EXCHANGE"_s), JSC::jsNumber(8192)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_CRYPTOPRO_TLSEXT_BUG"_s), JSC::jsNumber(2147483648)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS"_s), JSC::jsNumber(2048)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_LEGACY_SERVER_CONNECT"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_COMPRESSION"_s), JSC::jsNumber(131072)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_ENCRYPT_THEN_MAC"_s), JSC::jsNumber(524288)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_QUERY_MTU"_s), JSC::jsNumber(4096)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_RENEGOTIATION"_s), JSC::jsNumber(1073741824)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION"_s), JSC::jsNumber(65536)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_SSLv2"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_SSLv3"_s), JSC::jsNumber(33554432)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_TICKET"_s), JSC::jsNumber(16384)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_TLSv1"_s), JSC::jsNumber(67108864)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_TLSv1_1"_s), JSC::jsNumber(268435456)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_TLSv1_2"_s), JSC::jsNumber(134217728)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_NO_TLSv1_3"_s), JSC::jsNumber(536870912)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_PRIORITIZE_CHACHA"_s), JSC::jsNumber(2097152)); - exportProperty(JSC::Identifier::fromString(vm, "SSL_OP_TLS_ROLLBACK_BUG"_s), JSC::jsNumber(8388608)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_RSA"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_DSA"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_DH"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_RAND"_s), JSC::jsNumber(8)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_EC"_s), JSC::jsNumber(2048)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_CIPHERS"_s), JSC::jsNumber(64)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_DIGESTS"_s), JSC::jsNumber(128)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_PKEY_METHS"_s), JSC::jsNumber(512)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_PKEY_ASN1_METHS"_s), JSC::jsNumber(1024)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_ALL"_s), JSC::jsNumber(65535)); - exportProperty(JSC::Identifier::fromString(vm, "ENGINE_METHOD_NONE"_s), JSC::jsNumber(0)); - exportProperty(JSC::Identifier::fromString(vm, "DH_CHECK_P_NOT_SAFE_PRIME"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "DH_CHECK_P_NOT_PRIME"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "DH_UNABLE_TO_CHECK_GENERATOR"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "DH_NOT_SUITABLE_GENERATOR"_s), JSC::jsNumber(8)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_PKCS1_PADDING"_s), JSC::jsNumber(1)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_NO_PADDING"_s), JSC::jsNumber(3)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_PKCS1_OAEP_PADDING"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_X931_PADDING"_s), JSC::jsNumber(5)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_PKCS1_PSS_PADDING"_s), JSC::jsNumber(6)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_PSS_SALTLEN_DIGEST"_s), JSC::jsNumber(-1)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_PSS_SALTLEN_MAX_SIGN"_s), JSC::jsNumber(-2)); - exportProperty(JSC::Identifier::fromString(vm, "RSA_PSS_SALTLEN_AUTO"_s), JSC::jsNumber(-2)); - exportProperty(JSC::Identifier::fromString(vm, "defaultCoreCipherList"_s), JSC::jsString(vm, WTF::String::fromUTF8("DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256"))); - exportProperty(JSC::Identifier::fromString(vm, "TLS1_VERSION"_s), JSC::jsNumber(769)); - exportProperty(JSC::Identifier::fromString(vm, "TLS1_1_VERSION"_s), JSC::jsNumber(770)); - exportProperty(JSC::Identifier::fromString(vm, "TLS1_2_VERSION"_s), JSC::jsNumber(771)); - exportProperty(JSC::Identifier::fromString(vm, "TLS1_3_VERSION"_s), JSC::jsNumber(772)); - exportProperty(JSC::Identifier::fromString(vm, "POINT_CONVERSION_COMPRESSED"_s), JSC::jsNumber(2)); - exportProperty(JSC::Identifier::fromString(vm, "POINT_CONVERSION_UNCOMPRESSED"_s), JSC::jsNumber(4)); - exportProperty(JSC::Identifier::fromString(vm, "POINT_CONVERSION_HYBRID"_s), JSC::jsNumber(6)); - - exportNames.append(vm.propertyNames->defaultKeyword); - exportValues.append(defaultObject); -} - -} // namespace Zig diff --git a/src/bun.js/modules/EventsModule.h b/src/bun.js/modules/EventsModule.h deleted file mode 100644 index 7d53ff838fe926..00000000000000 --- a/src/bun.js/modules/EventsModule.h +++ /dev/null @@ -1,58 +0,0 @@ -#include "JavaScriptCore/JSGlobalObject.h" -#include "ZigGlobalObject.h" - -namespace Zig { -using namespace WebCore; - -inline void generateEventsSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues) { - JSC::VM &vm = lexicalGlobalObject->vm(); - GlobalObject *globalObject = - reinterpret_cast(lexicalGlobalObject); - - exportNames.append(JSC::Identifier::fromString(vm, "EventEmitter"_s)); - exportValues.append( - WebCore::JSEventEmitter::getConstructor(vm, globalObject)); - - exportNames.append(JSC::Identifier::fromString(vm, "getEventListeners"_s)); - exportValues.append(JSC::JSFunction::create( - vm, lexicalGlobalObject, 0, MAKE_STATIC_STRING_IMPL("getEventListeners"), - Events_functionGetEventListeners, ImplementationVisibility::Public)); - exportNames.append(JSC::Identifier::fromString(vm, "listenerCount"_s)); - exportValues.append(JSC::JSFunction::create( - vm, lexicalGlobalObject, 0, MAKE_STATIC_STRING_IMPL("listenerCount"), - Events_functionListenerCount, ImplementationVisibility::Public)); - exportNames.append(JSC::Identifier::fromString(vm, "once"_s)); - exportValues.append(JSC::JSFunction::create( - vm, lexicalGlobalObject, 0, MAKE_STATIC_STRING_IMPL("once"), - Events_functionOnce, ImplementationVisibility::Public)); - exportNames.append(JSC::Identifier::fromString(vm, "on"_s)); - exportValues.append(JSC::JSFunction::create( - vm, lexicalGlobalObject, 0, MAKE_STATIC_STRING_IMPL("on"), - Events_functionOn, ImplementationVisibility::Public)); - exportNames.append( - JSC::Identifier::fromString(vm, "captureRejectionSymbol"_s)); - exportValues.append(Symbol::create( - vm, vm.symbolRegistry().symbolForKey("nodejs.rejection"_s))); - - JSFunction *eventEmitterModuleCJS = - jsCast(WebCore::JSEventEmitter::getConstructor( - vm, reinterpret_cast(globalObject))); - - eventEmitterModuleCJS->putDirect( - vm, - PropertyName( - Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s))), - jsNumber(0), 0); - - for (size_t i = 0; i < exportNames.size(); i++) { - eventEmitterModuleCJS->putDirect(vm, exportNames[i], exportValues.at(i), 0); - } - - exportNames.append(JSC::Identifier::fromString(vm, "default"_s)); - exportValues.append(eventEmitterModuleCJS); -} - -} // namespace Zig diff --git a/src/bun.js/modules/BufferModule.h b/src/bun.js/modules/NodeBufferModule.h similarity index 65% rename from src/bun.js/modules/BufferModule.h rename to src/bun.js/modules/NodeBufferModule.h index 6e6e39e9cf1b36..5c6acd48e8886a 100644 --- a/src/bun.js/modules/BufferModule.h +++ b/src/bun.js/modules/NodeBufferModule.h @@ -1,7 +1,5 @@ #include "../bindings/JSBuffer.h" -#include "../bindings/ZigGlobalObject.h" -#include "JavaScriptCore/JSGlobalObject.h" -#include "JavaScriptCore/ObjectConstructor.h" +#include "_NativeModule.h" #include "simdutf.h" namespace Zig { @@ -134,33 +132,11 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionNotImplemented, return JSValue::encode(jsUndefined()); } -inline void generateBufferSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues) { - JSC::VM &vm = lexicalGlobalObject->vm(); - GlobalObject *globalObject = - reinterpret_cast(lexicalGlobalObject); +DEFINE_NATIVE_MODULE(NodeBuffer) { + INIT_NATIVE_MODULE(12); - JSC::JSObject *defaultObject = JSC::constructEmptyObject( - globalObject, globalObject->objectPrototype(), 12); - - auto CommonJS = - Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s)); - - defaultObject->putDirect(vm, PropertyName(CommonJS), jsNumber(0), 0); - - exportNames.append(CommonJS); - exportValues.append(jsNumber(0)); - - auto exportProperty = [&](JSC::Identifier name, JSC::JSValue value) { - exportNames.append(name); - exportValues.append(value); - defaultObject->putDirect(vm, name, value, 0); - }; - - exportProperty(JSC::Identifier::fromString(vm, "Buffer"_s), - globalObject->JSBufferConstructor()); + put(JSC::Identifier::fromString(vm, "Buffer"_s), + globalObject->JSBufferConstructor()); auto *slowBuffer = JSC::JSFunction::create( vm, globalObject, 0, "SlowBuffer"_s, WebCore::constructSlowBuffer, @@ -170,24 +146,24 @@ inline void generateBufferSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, vm, vm.propertyNames->prototype, globalObject->JSBufferPrototype(), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::DontDelete); - exportProperty(JSC::Identifier::fromString(vm, "SlowBuffer"_s), slowBuffer); + put(JSC::Identifier::fromString(vm, "SlowBuffer"_s), slowBuffer); auto blobIdent = JSC::Identifier::fromString(vm, "Blob"_s); JSValue blobValue = lexicalGlobalObject->get(globalObject, PropertyName(blobIdent)); - exportProperty(blobIdent, blobValue); + put(blobIdent, blobValue); // TODO: implement File - exportProperty(JSC::Identifier::fromString(vm, "File"_s), blobValue); + put(JSC::Identifier::fromString(vm, "File"_s), blobValue); - exportProperty(JSC::Identifier::fromString(vm, "INSPECT_MAX_BYTES"_s), - JSC::jsNumber(50)); + put(JSC::Identifier::fromString(vm, "INSPECT_MAX_BYTES"_s), + JSC::jsNumber(50)); - exportProperty(JSC::Identifier::fromString(vm, "kMaxLength"_s), - JSC::jsNumber(4294967296LL)); + put(JSC::Identifier::fromString(vm, "kMaxLength"_s), + JSC::jsNumber(4294967296LL)); - exportProperty(JSC::Identifier::fromString(vm, "kStringMaxLength"_s), - JSC::jsNumber(536870888)); + put(JSC::Identifier::fromString(vm, "kStringMaxLength"_s), + JSC::jsNumber(536870888)); JSC::JSObject *constants = JSC::constructEmptyObject( lexicalGlobalObject, globalObject->objectPrototype(), 2); @@ -197,7 +173,7 @@ inline void generateBufferSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, JSC::Identifier::fromString(vm, "MAX_STRING_LENGTH"_s), JSC::jsNumber(536870888)); - exportProperty(JSC::Identifier::fromString(vm, "constants"_s), constants); + put(JSC::Identifier::fromString(vm, "constants"_s), constants); JSC::Identifier atobI = JSC::Identifier::fromString(vm, "atob"_s); JSC::JSValue atobV = @@ -207,37 +183,31 @@ inline void generateBufferSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, JSC::JSValue btoaV = lexicalGlobalObject->get(globalObject, PropertyName(btoaI)); - exportProperty(atobI, atobV); - exportProperty(btoaI, btoaV); + put(atobI, atobV); + put(btoaI, btoaV); auto *transcode = InternalFunction::createFunctionThatMasqueradesAsUndefined( vm, globalObject, 1, "transcode"_s, jsFunctionNotImplemented); - exportProperty(JSC::Identifier::fromString(vm, "transcode"_s), transcode); + put(JSC::Identifier::fromString(vm, "transcode"_s), transcode); auto *resolveObjectURL = InternalFunction::createFunctionThatMasqueradesAsUndefined( vm, globalObject, 1, "resolveObjectURL"_s, jsFunctionNotImplemented); - exportProperty(JSC::Identifier::fromString(vm, "resolveObjectURL"_s), - resolveObjectURL); - - exportProperty(JSC::Identifier::fromString(vm, "isAscii"_s), - JSC::JSFunction::create(vm, globalObject, 1, "isAscii"_s, - jsBufferConstructorFunction_isAscii, - ImplementationVisibility::Public, - NoIntrinsic, - jsBufferConstructorFunction_isUtf8)); - - exportProperty(JSC::Identifier::fromString(vm, "isUtf8"_s), - JSC::JSFunction::create(vm, globalObject, 1, "isUtf8"_s, - jsBufferConstructorFunction_isUtf8, - ImplementationVisibility::Public, - NoIntrinsic, - jsBufferConstructorFunction_isUtf8)); - - exportNames.append(vm.propertyNames->defaultKeyword); - exportValues.append(defaultObject); + put(JSC::Identifier::fromString(vm, "resolveObjectURL"_s), resolveObjectURL); + + put(JSC::Identifier::fromString(vm, "isAscii"_s), + JSC::JSFunction::create(vm, globalObject, 1, "isAscii"_s, + jsBufferConstructorFunction_isAscii, + ImplementationVisibility::Public, NoIntrinsic, + jsBufferConstructorFunction_isUtf8)); + + put(JSC::Identifier::fromString(vm, "isUtf8"_s), + JSC::JSFunction::create(vm, globalObject, 1, "isUtf8"_s, + jsBufferConstructorFunction_isUtf8, + ImplementationVisibility::Public, NoIntrinsic, + jsBufferConstructorFunction_isUtf8)); } } // namespace Zig diff --git a/src/bun.js/modules/NodeConstantsModule.h b/src/bun.js/modules/NodeConstantsModule.h new file mode 100644 index 00000000000000..c1e324b0a3d16f --- /dev/null +++ b/src/bun.js/modules/NodeConstantsModule.h @@ -0,0 +1,916 @@ +#include "_NativeModule.h" +// Modelled off of https://github.com/nodejs/node/blob/main/src/node_constants.cc +// Note that if you change any of this code, you probably also have to change ProcessBindingConstants.cpp + +// require('constants') is implemented in node as a spread of: +// - constants.os.dlopen +// - constants.os.errno +// - constants.os.priority +// - constants.os.signals +// - constants.fs +// - constants.crypto +// Instead of loading $processBindingConstants, we just inline it + +// These headers may not all be needed, but they are the ones node references. +// Most of the constants are defined with #if checks on existing #defines, instead of platform-checks +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef OPENSSL_NO_ENGINE +#include +#endif + +#if !defined(_MSC_VER) +#include +#endif + +#if defined(_WIN32) +#include // _S_IREAD _S_IWRITE +#ifndef S_IRUSR +#define S_IRUSR _S_IREAD +#endif // S_IRUSR +#ifndef S_IWUSR +#define S_IWUSR _S_IWRITE +#endif // S_IWUSR +#else +#include +#endif + +namespace Zig { +using namespace WebCore; + +DEFINE_NATIVE_MODULE(NodeConstants) { + INIT_NATIVE_MODULE(63); + +#ifdef RTLD_LAZY + put(Identifier::fromString(vm, "RTLD_LAZY"_s), jsNumber(RTLD_LAZY)); +#endif +#ifdef RTLD_NOW + put(Identifier::fromString(vm, "RTLD_NOW"_s), jsNumber(RTLD_NOW)); +#endif +#ifdef RTLD_GLOBAL + put(Identifier::fromString(vm, "RTLD_GLOBAL"_s), jsNumber(RTLD_GLOBAL)); +#endif +#ifdef RTLD_LOCAL + put(Identifier::fromString(vm, "RTLD_LOCAL"_s), jsNumber(RTLD_LOCAL)); +#endif +#ifdef RTLD_DEEPBIND + put(Identifier::fromString(vm, "RTLD_DEEPBIND"_s), jsNumber(RTLD_DEEPBIND)); +#endif +#ifdef E2BIG + put(Identifier::fromString(vm, "E2BIG"_s), jsNumber(E2BIG)); +#endif +#ifdef EACCES + put(Identifier::fromString(vm, "EACCES"_s), jsNumber(EACCES)); +#endif +#ifdef EADDRINUSE + put(Identifier::fromString(vm, "EADDRINUSE"_s), jsNumber(EADDRINUSE)); +#endif +#ifdef EADDRNOTAVAIL + put(Identifier::fromString(vm, "EADDRNOTAVAIL"_s), jsNumber(EADDRNOTAVAIL)); +#endif +#ifdef EAFNOSUPPORT + put(Identifier::fromString(vm, "EAFNOSUPPORT"_s), jsNumber(EAFNOSUPPORT)); +#endif +#ifdef EAGAIN + put(Identifier::fromString(vm, "EAGAIN"_s), jsNumber(EAGAIN)); +#endif +#ifdef EALREADY + put(Identifier::fromString(vm, "EALREADY"_s), jsNumber(EALREADY)); +#endif +#ifdef EBADF + put(Identifier::fromString(vm, "EBADF"_s), jsNumber(EBADF)); +#endif +#ifdef EBADMSG + put(Identifier::fromString(vm, "EBADMSG"_s), jsNumber(EBADMSG)); +#endif +#ifdef EBUSY + put(Identifier::fromString(vm, "EBUSY"_s), jsNumber(EBUSY)); +#endif +#ifdef ECANCELED + put(Identifier::fromString(vm, "ECANCELED"_s), jsNumber(ECANCELED)); +#endif +#ifdef ECHILD + put(Identifier::fromString(vm, "ECHILD"_s), jsNumber(ECHILD)); +#endif +#ifdef ECONNABORTED + put(Identifier::fromString(vm, "ECONNABORTED"_s), jsNumber(ECONNABORTED)); +#endif +#ifdef ECONNREFUSED + put(Identifier::fromString(vm, "ECONNREFUSED"_s), jsNumber(ECONNREFUSED)); +#endif +#ifdef ECONNRESET + put(Identifier::fromString(vm, "ECONNRESET"_s), jsNumber(ECONNRESET)); +#endif +#ifdef EDEADLK + put(Identifier::fromString(vm, "EDEADLK"_s), jsNumber(EDEADLK)); +#endif +#ifdef EDESTADDRREQ + put(Identifier::fromString(vm, "EDESTADDRREQ"_s), jsNumber(EDESTADDRREQ)); +#endif +#ifdef EDOM + put(Identifier::fromString(vm, "EDOM"_s), jsNumber(EDOM)); +#endif +#ifdef EDQUOT + put(Identifier::fromString(vm, "EDQUOT"_s), jsNumber(EDQUOT)); +#endif +#ifdef EEXIST + put(Identifier::fromString(vm, "EEXIST"_s), jsNumber(EEXIST)); +#endif +#ifdef EFAULT + put(Identifier::fromString(vm, "EFAULT"_s), jsNumber(EFAULT)); +#endif +#ifdef EFBIG + put(Identifier::fromString(vm, "EFBIG"_s), jsNumber(EFBIG)); +#endif +#ifdef EHOSTUNREACH + put(Identifier::fromString(vm, "EHOSTUNREACH"_s), jsNumber(EHOSTUNREACH)); +#endif +#ifdef EIDRM + put(Identifier::fromString(vm, "EIDRM"_s), jsNumber(EIDRM)); +#endif +#ifdef EILSEQ + put(Identifier::fromString(vm, "EILSEQ"_s), jsNumber(EILSEQ)); +#endif +#ifdef EINPROGRESS + put(Identifier::fromString(vm, "EINPROGRESS"_s), jsNumber(EINPROGRESS)); +#endif +#ifdef EINTR + put(Identifier::fromString(vm, "EINTR"_s), jsNumber(EINTR)); +#endif +#ifdef EINVAL + put(Identifier::fromString(vm, "EINVAL"_s), jsNumber(EINVAL)); +#endif +#ifdef EIO + put(Identifier::fromString(vm, "EIO"_s), jsNumber(EIO)); +#endif +#ifdef EISCONN + put(Identifier::fromString(vm, "EISCONN"_s), jsNumber(EISCONN)); +#endif +#ifdef EISDIR + put(Identifier::fromString(vm, "EISDIR"_s), jsNumber(EISDIR)); +#endif +#ifdef ELOOP + put(Identifier::fromString(vm, "ELOOP"_s), jsNumber(ELOOP)); +#endif +#ifdef EMFILE + put(Identifier::fromString(vm, "EMFILE"_s), jsNumber(EMFILE)); +#endif +#ifdef EMLINK + put(Identifier::fromString(vm, "EMLINK"_s), jsNumber(EMLINK)); +#endif +#ifdef EMSGSIZE + put(Identifier::fromString(vm, "EMSGSIZE"_s), jsNumber(EMSGSIZE)); +#endif +#ifdef EMULTIHOP + put(Identifier::fromString(vm, "EMULTIHOP"_s), jsNumber(EMULTIHOP)); +#endif +#ifdef ENAMETOOLONG + put(Identifier::fromString(vm, "ENAMETOOLONG"_s), jsNumber(ENAMETOOLONG)); +#endif +#ifdef ENETDOWN + put(Identifier::fromString(vm, "ENETDOWN"_s), jsNumber(ENETDOWN)); +#endif +#ifdef ENETRESET + put(Identifier::fromString(vm, "ENETRESET"_s), jsNumber(ENETRESET)); +#endif +#ifdef ENETUNREACH + put(Identifier::fromString(vm, "ENETUNREACH"_s), jsNumber(ENETUNREACH)); +#endif +#ifdef ENFILE + put(Identifier::fromString(vm, "ENFILE"_s), jsNumber(ENFILE)); +#endif +#ifdef ENOBUFS + put(Identifier::fromString(vm, "ENOBUFS"_s), jsNumber(ENOBUFS)); +#endif +#ifdef ENODATA + put(Identifier::fromString(vm, "ENODATA"_s), jsNumber(ENODATA)); +#endif +#ifdef ENODEV + put(Identifier::fromString(vm, "ENODEV"_s), jsNumber(ENODEV)); +#endif +#ifdef ENOENT + put(Identifier::fromString(vm, "ENOENT"_s), jsNumber(ENOENT)); +#endif +#ifdef ENOEXEC + put(Identifier::fromString(vm, "ENOEXEC"_s), jsNumber(ENOEXEC)); +#endif +#ifdef ENOLCK + put(Identifier::fromString(vm, "ENOLCK"_s), jsNumber(ENOLCK)); +#endif +#ifdef ENOLINK + put(Identifier::fromString(vm, "ENOLINK"_s), jsNumber(ENOLINK)); +#endif +#ifdef ENOMEM + put(Identifier::fromString(vm, "ENOMEM"_s), jsNumber(ENOMEM)); +#endif +#ifdef ENOMSG + put(Identifier::fromString(vm, "ENOMSG"_s), jsNumber(ENOMSG)); +#endif +#ifdef ENOPROTOOPT + put(Identifier::fromString(vm, "ENOPROTOOPT"_s), jsNumber(ENOPROTOOPT)); +#endif +#ifdef ENOSPC + put(Identifier::fromString(vm, "ENOSPC"_s), jsNumber(ENOSPC)); +#endif +#ifdef ENOSR + put(Identifier::fromString(vm, "ENOSR"_s), jsNumber(ENOSR)); +#endif +#ifdef ENOSTR + put(Identifier::fromString(vm, "ENOSTR"_s), jsNumber(ENOSTR)); +#endif +#ifdef ENOSYS + put(Identifier::fromString(vm, "ENOSYS"_s), jsNumber(ENOSYS)); +#endif +#ifdef ENOTCONN + put(Identifier::fromString(vm, "ENOTCONN"_s), jsNumber(ENOTCONN)); +#endif +#ifdef ENOTDIR + put(Identifier::fromString(vm, "ENOTDIR"_s), jsNumber(ENOTDIR)); +#endif +#ifdef ENOTEMPTY + put(Identifier::fromString(vm, "ENOTEMPTY"_s), jsNumber(ENOTEMPTY)); +#endif +#ifdef ENOTSOCK + put(Identifier::fromString(vm, "ENOTSOCK"_s), jsNumber(ENOTSOCK)); +#endif +#ifdef ENOTSUP + put(Identifier::fromString(vm, "ENOTSUP"_s), jsNumber(ENOTSUP)); +#endif +#ifdef ENOTTY + put(Identifier::fromString(vm, "ENOTTY"_s), jsNumber(ENOTTY)); +#endif +#ifdef ENXIO + put(Identifier::fromString(vm, "ENXIO"_s), jsNumber(ENXIO)); +#endif +#ifdef EOPNOTSUPP + put(Identifier::fromString(vm, "EOPNOTSUPP"_s), jsNumber(EOPNOTSUPP)); +#endif +#ifdef EOVERFLOW + put(Identifier::fromString(vm, "EOVERFLOW"_s), jsNumber(EOVERFLOW)); +#endif +#ifdef EPERM + put(Identifier::fromString(vm, "EPERM"_s), jsNumber(EPERM)); +#endif +#ifdef EPIPE + put(Identifier::fromString(vm, "EPIPE"_s), jsNumber(EPIPE)); +#endif +#ifdef EPROTO + put(Identifier::fromString(vm, "EPROTO"_s), jsNumber(EPROTO)); +#endif +#ifdef EPROTONOSUPPORT + put(Identifier::fromString(vm, "EPROTONOSUPPORT"_s), jsNumber(EPROTONOSUPPORT)); +#endif +#ifdef EPROTOTYPE + put(Identifier::fromString(vm, "EPROTOTYPE"_s), jsNumber(EPROTOTYPE)); +#endif +#ifdef ERANGE + put(Identifier::fromString(vm, "ERANGE"_s), jsNumber(ERANGE)); +#endif +#ifdef EROFS + put(Identifier::fromString(vm, "EROFS"_s), jsNumber(EROFS)); +#endif +#ifdef ESPIPE + put(Identifier::fromString(vm, "ESPIPE"_s), jsNumber(ESPIPE)); +#endif +#ifdef ESRCH + put(Identifier::fromString(vm, "ESRCH"_s), jsNumber(ESRCH)); +#endif +#ifdef ESTALE + put(Identifier::fromString(vm, "ESTALE"_s), jsNumber(ESTALE)); +#endif +#ifdef ETIME + put(Identifier::fromString(vm, "ETIME"_s), jsNumber(ETIME)); +#endif +#ifdef ETIMEDOUT + put(Identifier::fromString(vm, "ETIMEDOUT"_s), jsNumber(ETIMEDOUT)); +#endif +#ifdef ETXTBSY + put(Identifier::fromString(vm, "ETXTBSY"_s), jsNumber(ETXTBSY)); +#endif +#ifdef EWOULDBLOCK + put(Identifier::fromString(vm, "EWOULDBLOCK"_s), jsNumber(EWOULDBLOCK)); +#endif +#ifdef EXDEV + put(Identifier::fromString(vm, "EXDEV"_s), jsNumber(EXDEV)); +#endif +#ifdef WSAEINTR + put(Identifier::fromString(vm, "WSAEINTR"_s), jsNumber(WSAEINTR)); +#endif +#ifdef WSAEBADF + put(Identifier::fromString(vm, "WSAEBADF"_s), jsNumber(WSAEBADF)); +#endif +#ifdef WSAEACCES + put(Identifier::fromString(vm, "WSAEACCES"_s), jsNumber(WSAEACCES)); +#endif +#ifdef WSAEFAULT + put(Identifier::fromString(vm, "WSAEFAULT"_s), jsNumber(WSAEFAULT)); +#endif +#ifdef WSAEINVAL + put(Identifier::fromString(vm, "WSAEINVAL"_s), jsNumber(WSAEINVAL)); +#endif +#ifdef WSAEMFILE + put(Identifier::fromString(vm, "WSAEMFILE"_s), jsNumber(WSAEMFILE)); +#endif +#ifdef WSAEWOULDBLOCK + put(Identifier::fromString(vm, "WSAEWOULDBLOCK"_s), jsNumber(WSAEWOULDBLOCK)); +#endif +#ifdef WSAEINPROGRESS + put(Identifier::fromString(vm, "WSAEINPROGRESS"_s), jsNumber(WSAEINPROGRESS)); +#endif +#ifdef WSAEALREADY + put(Identifier::fromString(vm, "WSAEALREADY"_s), jsNumber(WSAEALREADY)); +#endif +#ifdef WSAENOTSOCK + put(Identifier::fromString(vm, "WSAENOTSOCK"_s), jsNumber(WSAENOTSOCK)); +#endif +#ifdef WSAEDESTADDRREQ + put(Identifier::fromString(vm, "WSAEDESTADDRREQ"_s), jsNumber(WSAEDESTADDRREQ)); +#endif +#ifdef WSAEMSGSIZE + put(Identifier::fromString(vm, "WSAEMSGSIZE"_s), jsNumber(WSAEMSGSIZE)); +#endif +#ifdef WSAEPROTOTYPE + put(Identifier::fromString(vm, "WSAEPROTOTYPE"_s), jsNumber(WSAEPROTOTYPE)); +#endif +#ifdef WSAENOPROTOOPT + put(Identifier::fromString(vm, "WSAENOPROTOOPT"_s), jsNumber(WSAENOPROTOOPT)); +#endif +#ifdef WSAEPROTONOSUPPORT + put(Identifier::fromString(vm, "WSAEPROTONOSUPPORT"_s), jsNumber(WSAEPROTONOSUPPORT)); +#endif +#ifdef WSAESOCKTNOSUPPORT + put(Identifier::fromString(vm, "WSAESOCKTNOSUPPORT"_s), jsNumber(WSAESOCKTNOSUPPORT)); +#endif +#ifdef WSAEOPNOTSUPP + put(Identifier::fromString(vm, "WSAEOPNOTSUPP"_s), jsNumber(WSAEOPNOTSUPP)); +#endif +#ifdef WSAEPFNOSUPPORT + put(Identifier::fromString(vm, "WSAEPFNOSUPPORT"_s), jsNumber(WSAEPFNOSUPPORT)); +#endif +#ifdef WSAEAFNOSUPPORT + put(Identifier::fromString(vm, "WSAEAFNOSUPPORT"_s), jsNumber(WSAEAFNOSUPPORT)); +#endif +#ifdef WSAEADDRINUSE + put(Identifier::fromString(vm, "WSAEADDRINUSE"_s), jsNumber(WSAEADDRINUSE)); +#endif +#ifdef WSAEADDRNOTAVAIL + put(Identifier::fromString(vm, "WSAEADDRNOTAVAIL"_s), jsNumber(WSAEADDRNOTAVAIL)); +#endif +#ifdef WSAENETDOWN + put(Identifier::fromString(vm, "WSAENETDOWN"_s), jsNumber(WSAENETDOWN)); +#endif +#ifdef WSAENETUNREACH + put(Identifier::fromString(vm, "WSAENETUNREACH"_s), jsNumber(WSAENETUNREACH)); +#endif +#ifdef WSAENETRESET + put(Identifier::fromString(vm, "WSAENETRESET"_s), jsNumber(WSAENETRESET)); +#endif +#ifdef WSAECONNABORTED + put(Identifier::fromString(vm, "WSAECONNABORTED"_s), jsNumber(WSAECONNABORTED)); +#endif +#ifdef WSAECONNRESET + put(Identifier::fromString(vm, "WSAECONNRESET"_s), jsNumber(WSAECONNRESET)); +#endif +#ifdef WSAENOBUFS + put(Identifier::fromString(vm, "WSAENOBUFS"_s), jsNumber(WSAENOBUFS)); +#endif +#ifdef WSAEISCONN + put(Identifier::fromString(vm, "WSAEISCONN"_s), jsNumber(WSAEISCONN)); +#endif +#ifdef WSAENOTCONN + put(Identifier::fromString(vm, "WSAENOTCONN"_s), jsNumber(WSAENOTCONN)); +#endif +#ifdef WSAESHUTDOWN + put(Identifier::fromString(vm, "WSAESHUTDOWN"_s), jsNumber(WSAESHUTDOWN)); +#endif +#ifdef WSAETOOMANYREFS + put(Identifier::fromString(vm, "WSAETOOMANYREFS"_s), jsNumber(WSAETOOMANYREFS)); +#endif +#ifdef WSAETIMEDOUT + put(Identifier::fromString(vm, "WSAETIMEDOUT"_s), jsNumber(WSAETIMEDOUT)); +#endif +#ifdef WSAECONNREFUSED + put(Identifier::fromString(vm, "WSAECONNREFUSED"_s), jsNumber(WSAECONNREFUSED)); +#endif +#ifdef WSAELOOP + put(Identifier::fromString(vm, "WSAELOOP"_s), jsNumber(WSAELOOP)); +#endif +#ifdef WSAENAMETOOLONG + put(Identifier::fromString(vm, "WSAENAMETOOLONG"_s), jsNumber(WSAENAMETOOLONG)); +#endif +#ifdef WSAEHOSTDOWN + put(Identifier::fromString(vm, "WSAEHOSTDOWN"_s), jsNumber(WSAEHOSTDOWN)); +#endif +#ifdef WSAEHOSTUNREACH + put(Identifier::fromString(vm, "WSAEHOSTUNREACH"_s), jsNumber(WSAEHOSTUNREACH)); +#endif +#ifdef WSAENOTEMPTY + put(Identifier::fromString(vm, "WSAENOTEMPTY"_s), jsNumber(WSAENOTEMPTY)); +#endif +#ifdef WSAEPROCLIM + put(Identifier::fromString(vm, "WSAEPROCLIM"_s), jsNumber(WSAEPROCLIM)); +#endif +#ifdef WSAEUSERS + put(Identifier::fromString(vm, "WSAEUSERS"_s), jsNumber(WSAEUSERS)); +#endif +#ifdef WSAEDQUOT + put(Identifier::fromString(vm, "WSAEDQUOT"_s), jsNumber(WSAEDQUOT)); +#endif +#ifdef WSAESTALE + put(Identifier::fromString(vm, "WSAESTALE"_s), jsNumber(WSAESTALE)); +#endif +#ifdef WSAEREMOTE + put(Identifier::fromString(vm, "WSAEREMOTE"_s), jsNumber(WSAEREMOTE)); +#endif +#ifdef WSASYSNOTREADY + put(Identifier::fromString(vm, "WSASYSNOTREADY"_s), jsNumber(WSASYSNOTREADY)); +#endif +#ifdef WSAVERNOTSUPPORTED + put(Identifier::fromString(vm, "WSAVERNOTSUPPORTED"_s), jsNumber(WSAVERNOTSUPPORTED)); +#endif +#ifdef WSANOTINITIALISED + put(Identifier::fromString(vm, "WSANOTINITIALISED"_s), jsNumber(WSANOTINITIALISED)); +#endif +#ifdef WSAEDISCON + put(Identifier::fromString(vm, "WSAEDISCON"_s), jsNumber(WSAEDISCON)); +#endif +#ifdef WSAENOMORE + put(Identifier::fromString(vm, "WSAENOMORE"_s), jsNumber(WSAENOMORE)); +#endif +#ifdef WSAECANCELLED + put(Identifier::fromString(vm, "WSAECANCELLED"_s), jsNumber(WSAECANCELLED)); +#endif +#ifdef WSAEINVALIDPROCTABLE + put(Identifier::fromString(vm, "WSAEINVALIDPROCTABLE"_s), jsNumber(WSAEINVALIDPROCTABLE)); +#endif +#ifdef WSAEINVALIDPROVIDER + put(Identifier::fromString(vm, "WSAEINVALIDPROVIDER"_s), jsNumber(WSAEINVALIDPROVIDER)); +#endif +#ifdef WSAEPROVIDERFAILEDINIT + put(Identifier::fromString(vm, "WSAEPROVIDERFAILEDINIT"_s), jsNumber(WSAEPROVIDERFAILEDINIT)); +#endif +#ifdef WSASYSCALLFAILURE + put(Identifier::fromString(vm, "WSASYSCALLFAILURE"_s), jsNumber(WSASYSCALLFAILURE)); +#endif +#ifdef WSASERVICE_NOT_FOUND + put(Identifier::fromString(vm, "WSASERVICE_NOT_FOUND"_s), jsNumber(WSASERVICE_NOT_FOUND)); +#endif +#ifdef WSATYPE_NOT_FOUND + put(Identifier::fromString(vm, "WSATYPE_NOT_FOUND"_s), jsNumber(WSATYPE_NOT_FOUND)); +#endif +#ifdef WSA_E_NO_MORE + put(Identifier::fromString(vm, "WSA_E_NO_MORE"_s), jsNumber(WSA_E_NO_MORE)); +#endif +#ifdef WSA_E_CANCELLED + put(Identifier::fromString(vm, "WSA_E_CANCELLED"_s), jsNumber(WSA_E_CANCELLED)); +#endif +#ifdef WSAEREFUSED + put(Identifier::fromString(vm, "WSAEREFUSED"_s), jsNumber(WSAEREFUSED)); +#endif + put(Identifier::fromString(vm, "PRIORITY_LOW"_s), jsNumber(19)); + put(Identifier::fromString(vm, "PRIORITY_BELOW_NORMAL"_s), jsNumber(10)); + put(Identifier::fromString(vm, "PRIORITY_NORMAL"_s), jsNumber(0)); + put(Identifier::fromString(vm, "PRIORITY_ABOVE_NORMAL"_s), jsNumber(-7)); + put(Identifier::fromString(vm, "PRIORITY_HIGH"_s), jsNumber(-14)); + put(Identifier::fromString(vm, "PRIORITY_HIGHEST"_s), jsNumber(-20)); +#ifdef SIGHUP + put(Identifier::fromString(vm, "SIGHUP"_s), jsNumber(SIGHUP)); +#endif +#ifdef SIGINT + put(Identifier::fromString(vm, "SIGINT"_s), jsNumber(SIGINT)); +#endif +#ifdef SIGQUIT + put(Identifier::fromString(vm, "SIGQUIT"_s), jsNumber(SIGQUIT)); +#endif +#ifdef SIGILL + put(Identifier::fromString(vm, "SIGILL"_s), jsNumber(SIGILL)); +#endif +#ifdef SIGTRAP + put(Identifier::fromString(vm, "SIGTRAP"_s), jsNumber(SIGTRAP)); +#endif +#ifdef SIGABRT + put(Identifier::fromString(vm, "SIGABRT"_s), jsNumber(SIGABRT)); +#endif +#ifdef SIGIOT + put(Identifier::fromString(vm, "SIGIOT"_s), jsNumber(SIGIOT)); +#endif +#ifdef SIGBUS + put(Identifier::fromString(vm, "SIGBUS"_s), jsNumber(SIGBUS)); +#endif +#ifdef SIGFPE + put(Identifier::fromString(vm, "SIGFPE"_s), jsNumber(SIGFPE)); +#endif +#ifdef SIGKILL + put(Identifier::fromString(vm, "SIGKILL"_s), jsNumber(SIGKILL)); +#endif +#ifdef SIGUSR1 + put(Identifier::fromString(vm, "SIGUSR1"_s), jsNumber(SIGUSR1)); +#endif +#ifdef SIGSEGV + put(Identifier::fromString(vm, "SIGSEGV"_s), jsNumber(SIGSEGV)); +#endif +#ifdef SIGUSR2 + put(Identifier::fromString(vm, "SIGUSR2"_s), jsNumber(SIGUSR2)); +#endif +#ifdef SIGPIPE + put(Identifier::fromString(vm, "SIGPIPE"_s), jsNumber(SIGPIPE)); +#endif +#ifdef SIGALRM + put(Identifier::fromString(vm, "SIGALRM"_s), jsNumber(SIGALRM)); +#endif +#ifdef SIGTERM + put(Identifier::fromString(vm, "SIGTERM"_s), jsNumber(SIGTERM)); +#endif +#ifdef SIGCHLD + put(Identifier::fromString(vm, "SIGCHLD"_s), jsNumber(SIGCHLD)); +#endif +#ifdef SIGSTKFLT + put(Identifier::fromString(vm, "SIGSTKFLT"_s), jsNumber(SIGSTKFLT)); +#endif +#ifdef SIGCONT + put(Identifier::fromString(vm, "SIGCONT"_s), jsNumber(SIGCONT)); +#endif +#ifdef SIGSTOP + put(Identifier::fromString(vm, "SIGSTOP"_s), jsNumber(SIGSTOP)); +#endif +#ifdef SIGTSTP + put(Identifier::fromString(vm, "SIGTSTP"_s), jsNumber(SIGTSTP)); +#endif +#ifdef SIGBREAK + put(Identifier::fromString(vm, "SIGBREAK"_s), jsNumber(SIGBREAK)); +#endif +#ifdef SIGTTIN + put(Identifier::fromString(vm, "SIGTTIN"_s), jsNumber(SIGTTIN)); +#endif +#ifdef SIGTTOU + put(Identifier::fromString(vm, "SIGTTOU"_s), jsNumber(SIGTTOU)); +#endif +#ifdef SIGURG + put(Identifier::fromString(vm, "SIGURG"_s), jsNumber(SIGURG)); +#endif +#ifdef SIGXCPU + put(Identifier::fromString(vm, "SIGXCPU"_s), jsNumber(SIGXCPU)); +#endif +#ifdef SIGXFSZ + put(Identifier::fromString(vm, "SIGXFSZ"_s), jsNumber(SIGXFSZ)); +#endif +#ifdef SIGVTALRM + put(Identifier::fromString(vm, "SIGVTALRM"_s), jsNumber(SIGVTALRM)); +#endif +#ifdef SIGPROF + put(Identifier::fromString(vm, "SIGPROF"_s), jsNumber(SIGPROF)); +#endif +#ifdef SIGWINCH + put(Identifier::fromString(vm, "SIGWINCH"_s), jsNumber(SIGWINCH)); +#endif +#ifdef SIGIO + put(Identifier::fromString(vm, "SIGIO"_s), jsNumber(SIGIO)); +#endif +#ifdef SIGPOLL + put(Identifier::fromString(vm, "SIGPOLL"_s), jsNumber(SIGPOLL)); +#endif +#ifdef SIGLOST + put(Identifier::fromString(vm, "SIGLOST"_s), jsNumber(SIGLOST)); +#endif +#ifdef SIGPWR + put(Identifier::fromString(vm, "SIGPWR"_s), jsNumber(SIGPWR)); +#endif +#ifdef SIGINFO + put(Identifier::fromString(vm, "SIGINFO"_s), jsNumber(SIGINFO)); +#endif +#ifdef SIGSYS + put(Identifier::fromString(vm, "SIGSYS"_s), jsNumber(SIGSYS)); +#endif +#ifdef SIGUNUSED + put(Identifier::fromString(vm, "SIGUNUSED"_s), jsNumber(SIGUNUSED)); +#endif + put(Identifier::fromString(vm, "UV_FS_SYMLINK_DIR"_s), jsNumber(1)); + put(Identifier::fromString(vm, "UV_FS_SYMLINK_JUNCTION"_s), jsNumber(2)); + put(Identifier::fromString(vm, "O_RDONLY"_s), jsNumber(O_RDONLY)); + put(Identifier::fromString(vm, "O_WRONLY"_s), jsNumber(O_WRONLY)); + put(Identifier::fromString(vm, "O_RDWR"_s), jsNumber(O_RDWR)); + + put(Identifier::fromString(vm, "UV_DIRENT_UNKNOWN"_s), jsNumber(0)); + put(Identifier::fromString(vm, "UV_DIRENT_FILE"_s), jsNumber(1)); + put(Identifier::fromString(vm, "UV_DIRENT_DIR"_s), jsNumber(2)); + put(Identifier::fromString(vm, "UV_DIRENT_LINK"_s), jsNumber(3)); + put(Identifier::fromString(vm, "UV_DIRENT_FIFO"_s), jsNumber(4)); + put(Identifier::fromString(vm, "UV_DIRENT_SOCKET"_s), jsNumber(5)); + put(Identifier::fromString(vm, "UV_DIRENT_CHAR"_s), jsNumber(6)); + put(Identifier::fromString(vm, "UV_DIRENT_BLOCK"_s), jsNumber(7)); + + put(Identifier::fromString(vm, "S_IFMT"_s), jsNumber(S_IFMT)); + put(Identifier::fromString(vm, "S_IFREG"_s), jsNumber(S_IFREG)); + put(Identifier::fromString(vm, "S_IFDIR"_s), jsNumber(S_IFDIR)); + put(Identifier::fromString(vm, "S_IFCHR"_s), jsNumber(S_IFCHR)); +#ifdef S_IFBLK + put(Identifier::fromString(vm, "S_IFBLK"_s), jsNumber(S_IFBLK)); +#endif +#ifdef S_IFIFO + put(Identifier::fromString(vm, "S_IFIFO"_s), jsNumber(S_IFIFO)); +#endif +#ifdef S_IFLNK + put(Identifier::fromString(vm, "S_IFLNK"_s), jsNumber(S_IFLNK)); +#endif +#ifdef S_IFSOCK + put(Identifier::fromString(vm, "S_IFSOCK"_s), jsNumber(S_IFSOCK)); +#endif +#ifdef O_CREAT + put(Identifier::fromString(vm, "O_CREAT"_s), jsNumber(O_CREAT)); +#endif +#ifdef O_EXCL + put(Identifier::fromString(vm, "O_EXCL"_s), jsNumber(O_EXCL)); +#endif + put(Identifier::fromString(vm, "UV_FS_O_FILEMAP"_s), jsNumber(0)); + +#ifdef O_NOCTTY + put(Identifier::fromString(vm, "O_NOCTTY"_s), jsNumber(O_NOCTTY)); +#endif +#ifdef O_TRUNC + put(Identifier::fromString(vm, "O_TRUNC"_s), jsNumber(O_TRUNC)); +#endif +#ifdef O_APPEND + put(Identifier::fromString(vm, "O_APPEND"_s), jsNumber(O_APPEND)); +#endif +#ifdef O_DIRECTORY + put(Identifier::fromString(vm, "O_DIRECTORY"_s), jsNumber(O_DIRECTORY)); +#endif +#ifdef O_EXCL + put(Identifier::fromString(vm, "O_EXCL"_s), jsNumber(O_EXCL)); +#endif +#ifdef O_NOATIME + put(Identifier::fromString(vm, "O_NOATIME"_s), jsNumber(O_NOATIME)); +#endif +#ifdef O_NOFOLLOW + put(Identifier::fromString(vm, "O_NOFOLLOW"_s), jsNumber(O_NOFOLLOW)); +#endif +#ifdef O_SYNC + put(Identifier::fromString(vm, "O_SYNC"_s), jsNumber(O_SYNC)); +#endif +#ifdef O_DSYNC + put(Identifier::fromString(vm, "O_DSYNC"_s), jsNumber(O_DSYNC)); +#endif +#ifdef O_SYMLINK + put(Identifier::fromString(vm, "O_SYMLINK"_s), jsNumber(O_SYMLINK)); +#endif +#ifdef O_DIRECT + put(Identifier::fromString(vm, "O_DIRECT"_s), jsNumber(O_DIRECT)); +#endif +#ifdef O_NONBLOCK + put(Identifier::fromString(vm, "O_NONBLOCK"_s), jsNumber(O_NONBLOCK)); +#endif +#ifdef S_IRWXU + put(Identifier::fromString(vm, "S_IRWXU"_s), jsNumber(S_IRWXU)); +#endif +#ifdef S_IRUSR + put(Identifier::fromString(vm, "S_IRUSR"_s), jsNumber(S_IRUSR)); +#endif +#ifdef S_IWUSR + put(Identifier::fromString(vm, "S_IWUSR"_s), jsNumber(S_IWUSR)); +#endif +#ifdef S_IXUSR + put(Identifier::fromString(vm, "S_IXUSR"_s), jsNumber(S_IXUSR)); +#endif +#ifdef S_IRWXG + put(Identifier::fromString(vm, "S_IRWXG"_s), jsNumber(S_IRWXG)); +#endif +#ifdef S_IRGRP + put(Identifier::fromString(vm, "S_IRGRP"_s), jsNumber(S_IRGRP)); +#endif +#ifdef S_IWGRP + put(Identifier::fromString(vm, "S_IWGRP"_s), jsNumber(S_IWGRP)); +#endif +#ifdef S_IXGRP + put(Identifier::fromString(vm, "S_IXGRP"_s), jsNumber(S_IXGRP)); +#endif +#ifdef S_IRWXO + put(Identifier::fromString(vm, "S_IRWXO"_s), jsNumber(S_IRWXO)); +#endif +#ifdef S_IROTH + put(Identifier::fromString(vm, "S_IROTH"_s), jsNumber(S_IROTH)); +#endif +#ifdef S_IWOTH + put(Identifier::fromString(vm, "S_IWOTH"_s), jsNumber(S_IWOTH)); +#endif +#ifdef S_IXOTH + put(Identifier::fromString(vm, "S_IXOTH"_s), jsNumber(S_IXOTH)); +#endif +#ifdef F_OK + put(Identifier::fromString(vm, "F_OK"_s), jsNumber(F_OK)); +#endif +#ifdef R_OK + put(Identifier::fromString(vm, "R_OK"_s), jsNumber(R_OK)); +#endif +#ifdef W_OK + put(Identifier::fromString(vm, "W_OK"_s), jsNumber(W_OK)); +#endif +#ifdef X_OK + put(Identifier::fromString(vm, "X_OK"_s), jsNumber(X_OK)); +#endif + put(Identifier::fromString(vm, "UV_FS_COPYFILE_EXCL"_s), jsNumber(1)); + put(Identifier::fromString(vm, "COPYFILE_EXCL"_s), jsNumber(1)); + put(Identifier::fromString(vm, "UV_FS_COPYFILE_FICLONE"_s), jsNumber(2)); + put(Identifier::fromString(vm, "COPYFILE_FICLONE"_s), jsNumber(2)); + put(Identifier::fromString(vm, "UV_FS_COPYFILE_FICLONE_FORCE"_s), jsNumber(4)); + put(Identifier::fromString(vm, "COPYFILE_FICLONE_FORCE"_s), jsNumber(4)); +#ifdef OPENSSL_VERSION_NUMBER + put(Identifier::fromString(vm, "OPENSSL_VERSION_NUMBER"_s), jsNumber(OPENSSL_VERSION_NUMBER)); +#endif +#ifdef SSL_OP_ALL + put(Identifier::fromString(vm, "SSL_OP_ALL"_s), jsNumber(SSL_OP_ALL)); +#endif +#ifdef SSL_OP_ALLOW_NO_DHE_KEX + put(Identifier::fromString(vm, "SSL_OP_ALLOW_NO_DHE_KEX"_s), jsNumber(SSL_OP_ALLOW_NO_DHE_KEX)); +#endif +#ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION + put(Identifier::fromString(vm, "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION"_s), jsNumber(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)); +#endif +#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE + put(Identifier::fromString(vm, "SSL_OP_CIPHER_SERVER_PREFERENCE"_s), jsNumber(SSL_OP_CIPHER_SERVER_PREFERENCE)); +#endif +#ifdef SSL_OP_CISCO_ANYCONNECT + put(Identifier::fromString(vm, "SSL_OP_CISCO_ANYCONNECT"_s), jsNumber(SSL_OP_CISCO_ANYCONNECT)); +#endif +#ifdef SSL_OP_COOKIE_EXCHANGE + put(Identifier::fromString(vm, "SSL_OP_COOKIE_EXCHANGE"_s), jsNumber(SSL_OP_COOKIE_EXCHANGE)); +#endif +#ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG + put(Identifier::fromString(vm, "SSL_OP_CRYPTOPRO_TLSEXT_BUG"_s), jsNumber(SSL_OP_CRYPTOPRO_TLSEXT_BUG)); +#endif +#ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS + put(Identifier::fromString(vm, "SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS"_s), jsNumber(SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)); +#endif +#ifdef SSL_OP_LEGACY_SERVER_CONNECT + put(Identifier::fromString(vm, "SSL_OP_LEGACY_SERVER_CONNECT"_s), jsNumber(SSL_OP_LEGACY_SERVER_CONNECT)); +#endif +#ifdef SSL_OP_NO_COMPRESSION + put(Identifier::fromString(vm, "SSL_OP_NO_COMPRESSION"_s), jsNumber(SSL_OP_NO_COMPRESSION)); +#endif +#ifdef SSL_OP_NO_ENCRYPT_THEN_MAC + put(Identifier::fromString(vm, "SSL_OP_NO_ENCRYPT_THEN_MAC"_s), jsNumber(SSL_OP_NO_ENCRYPT_THEN_MAC)); +#endif +#ifdef SSL_OP_NO_QUERY_MTU + put(Identifier::fromString(vm, "SSL_OP_NO_QUERY_MTU"_s), jsNumber(SSL_OP_NO_QUERY_MTU)); +#endif +#ifdef SSL_OP_NO_RENEGOTIATION + put(Identifier::fromString(vm, "SSL_OP_NO_RENEGOTIATION"_s), jsNumber(SSL_OP_NO_RENEGOTIATION)); +#endif +#ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION + put(Identifier::fromString(vm, "SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION"_s), jsNumber(SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)); +#endif +#ifdef SSL_OP_NO_SSLv2 + put(Identifier::fromString(vm, "SSL_OP_NO_SSLv2"_s), jsNumber(SSL_OP_NO_SSLv2)); +#endif +#ifdef SSL_OP_NO_SSLv3 + put(Identifier::fromString(vm, "SSL_OP_NO_SSLv3"_s), jsNumber(SSL_OP_NO_SSLv3)); +#endif +#ifdef SSL_OP_NO_TICKET + put(Identifier::fromString(vm, "SSL_OP_NO_TICKET"_s), jsNumber(SSL_OP_NO_TICKET)); +#endif +#ifdef SSL_OP_NO_TLSv1 + put(Identifier::fromString(vm, "SSL_OP_NO_TLSv1"_s), jsNumber(SSL_OP_NO_TLSv1)); +#endif +#ifdef SSL_OP_NO_TLSv1_1 + put(Identifier::fromString(vm, "SSL_OP_NO_TLSv1_1"_s), jsNumber(SSL_OP_NO_TLSv1_1)); +#endif +#ifdef SSL_OP_NO_TLSv1_2 + put(Identifier::fromString(vm, "SSL_OP_NO_TLSv1_2"_s), jsNumber(SSL_OP_NO_TLSv1_2)); +#endif +#ifdef SSL_OP_NO_TLSv1_3 + put(Identifier::fromString(vm, "SSL_OP_NO_TLSv1_3"_s), jsNumber(SSL_OP_NO_TLSv1_3)); +#endif +#ifdef SSL_OP_PRIORITIZE_CHACHA + put(Identifier::fromString(vm, "SSL_OP_PRIORITIZE_CHACHA"_s), jsNumber(SSL_OP_PRIORITIZE_CHACHA)); +#endif +#ifdef SSL_OP_TLS_ROLLBACK_BUG + put(Identifier::fromString(vm, "SSL_OP_TLS_ROLLBACK_BUG"_s), jsNumber(SSL_OP_TLS_ROLLBACK_BUG)); +#endif +#ifndef OPENSSL_NO_ENGINE +#ifdef ENGINE_METHOD_RSA + put(Identifier::fromString(vm, "ENGINE_METHOD_RSA"_s), jsNumber(ENGINE_METHOD_RSA)); +#endif +#ifdef ENGINE_METHOD_DSA + put(Identifier::fromString(vm, "ENGINE_METHOD_DSA"_s), jsNumber(ENGINE_METHOD_DSA)); +#endif +#ifdef ENGINE_METHOD_DH + put(Identifier::fromString(vm, "ENGINE_METHOD_DH"_s), jsNumber(ENGINE_METHOD_DH)); +#endif +#ifdef ENGINE_METHOD_RAND + put(Identifier::fromString(vm, "ENGINE_METHOD_RAND"_s), jsNumber(ENGINE_METHOD_RAND)); +#endif +#ifdef ENGINE_METHOD_EC + put(Identifier::fromString(vm, "ENGINE_METHOD_EC"_s), jsNumber(ENGINE_METHOD_EC)); +#endif +#ifdef ENGINE_METHOD_CIPHERS + put(Identifier::fromString(vm, "ENGINE_METHOD_CIPHERS"_s), jsNumber(ENGINE_METHOD_CIPHERS)); +#endif +#ifdef ENGINE_METHOD_DIGESTS + put(Identifier::fromString(vm, "ENGINE_METHOD_DIGESTS"_s), jsNumber(ENGINE_METHOD_DIGESTS)); +#endif +#ifdef ENGINE_METHOD_PKEY_METHS + put(Identifier::fromString(vm, "ENGINE_METHOD_PKEY_METHS"_s), jsNumber(ENGINE_METHOD_PKEY_METHS)); +#endif +#ifdef ENGINE_METHOD_PKEY_ASN1_METHS + put(Identifier::fromString(vm, "ENGINE_METHOD_PKEY_ASN1_METHS"_s), jsNumber(ENGINE_METHOD_PKEY_ASN1_METHS)); +#endif +#ifdef ENGINE_METHOD_ALL + put(Identifier::fromString(vm, "ENGINE_METHOD_ALL"_s), jsNumber(ENGINE_METHOD_ALL)); +#endif +#ifdef ENGINE_METHOD_NONE + put(Identifier::fromString(vm, "ENGINE_METHOD_NONE"_s), jsNumber(ENGINE_METHOD_NONE)); +#endif +#endif // !OPENSSL_NO_ENGINE +#ifdef DH_CHECK_P_NOT_SAFE_PRIME + put(Identifier::fromString(vm, "DH_CHECK_P_NOT_SAFE_PRIME"_s), jsNumber(DH_CHECK_P_NOT_SAFE_PRIME)); +#endif +#ifdef DH_CHECK_P_NOT_PRIME + put(Identifier::fromString(vm, "DH_CHECK_P_NOT_PRIME"_s), jsNumber(DH_CHECK_P_NOT_PRIME)); +#endif +#ifdef DH_UNABLE_TO_CHECK_GENERATOR + put(Identifier::fromString(vm, "DH_UNABLE_TO_CHECK_GENERATOR"_s), jsNumber(DH_UNABLE_TO_CHECK_GENERATOR)); +#endif +#ifdef DH_NOT_SUITABLE_GENERATOR + put(Identifier::fromString(vm, "DH_NOT_SUITABLE_GENERATOR"_s), jsNumber(DH_NOT_SUITABLE_GENERATOR)); +#endif +#ifdef RSA_PKCS1_PADDING + put(Identifier::fromString(vm, "RSA_PKCS1_PADDING"_s), jsNumber(RSA_PKCS1_PADDING)); +#endif +#ifdef RSA_SSLV23_PADDING + put(Identifier::fromString(vm, "RSA_SSLV23_PADDING"_s), jsNumber(RSA_SSLV23_PADDING)); +#endif +#ifdef RSA_NO_PADDING + put(Identifier::fromString(vm, "RSA_NO_PADDING"_s), jsNumber(RSA_NO_PADDING)); +#endif +#ifdef RSA_PKCS1_OAEP_PADDING + put(Identifier::fromString(vm, "RSA_PKCS1_OAEP_PADDING"_s), jsNumber(RSA_PKCS1_OAEP_PADDING)); +#endif +#ifdef RSA_X931_PADDING + put(Identifier::fromString(vm, "RSA_X931_PADDING"_s), jsNumber(RSA_X931_PADDING)); +#endif +#ifdef RSA_PKCS1_PSS_PADDING + put(Identifier::fromString(vm, "RSA_PKCS1_PSS_PADDING"_s), jsNumber(RSA_PKCS1_PSS_PADDING)); +#endif +#ifdef RSA_PSS_SALTLEN_DIGEST + put(Identifier::fromString(vm, "RSA_PSS_SALTLEN_DIGEST"_s), jsNumber(RSA_PSS_SALTLEN_DIGEST)); +#endif +#ifdef RSA_PSS_SALTLEN_MAX_SIGN + put(Identifier::fromString(vm, "RSA_PSS_SALTLEN_MAX_SIGN"_s), jsNumber(RSA_PSS_SALTLEN_MAX_SIGN)); +#endif +#ifdef RSA_PSS_SALTLEN_AUTO + put(Identifier::fromString(vm, "RSA_PSS_SALTLEN_AUTO"_s), jsNumber(RSA_PSS_SALTLEN_AUTO)); +#endif + auto cipherList = String("TLS_AES_256_GCM_SHA384:" + "TLS_CHACHA20_POLY1305_SHA256:" + "TLS_AES_128_GCM_SHA256:" + "ECDHE-RSA-AES128-GCM-SHA256:" + "ECDHE-ECDSA-AES128-GCM-SHA256:" + "ECDHE-RSA-AES256-GCM-SHA384:" + "ECDHE-ECDSA-AES256-GCM-SHA384:" + "DHE-RSA-AES128-GCM-SHA256:" + "ECDHE-RSA-AES128-SHA256:" + "DHE-RSA-AES128-SHA256:" + "ECDHE-RSA-AES256-SHA384:" + "DHE-RSA-AES256-SHA384:" + "ECDHE-RSA-AES256-SHA256:" + "DHE-RSA-AES256-SHA256:" + "HIGH:" + "!aNULL:" + "!eNULL:" + "!EXPORT:" + "!DES:" + "!RC4:" + "!MD5:" + "!PSK:" + "!SRP:" + "!CAMELLIA"_s); + put(Identifier::fromString(vm, "defaultCoreCipherList"_s), + jsString(vm, cipherList)); + put(Identifier::fromString(vm, "defaultCipherList"_s), + jsString(vm, cipherList)); +#ifdef TLS1_VERSION + put(Identifier::fromString(vm, "TLS1_VERSION"_s), jsNumber(TLS1_VERSION)); +#endif +#ifdef TLS1_1_VERSION + put(Identifier::fromString(vm, "TLS1_1_VERSION"_s), jsNumber(TLS1_1_VERSION)); +#endif +#ifdef TLS1_2_VERSION + put(Identifier::fromString(vm, "TLS1_2_VERSION"_s), jsNumber(TLS1_2_VERSION)); +#endif +#ifdef TLS1_3_VERSION + put(Identifier::fromString(vm, "TLS1_3_VERSION"_s), jsNumber(TLS1_3_VERSION)); +#endif + put(Identifier::fromString(vm, "POINT_CONVERSION_COMPRESSED"_s), jsNumber(POINT_CONVERSION_COMPRESSED)); + put(Identifier::fromString(vm, "POINT_CONVERSION_UNCOMPRESSED"_s), jsNumber(POINT_CONVERSION_UNCOMPRESSED)); + put(Identifier::fromString(vm, "POINT_CONVERSION_HYBRID"_s), jsNumber(POINT_CONVERSION_HYBRID)); + RETURN_NATIVE_MODULE(); +} + +} // namespace Zig diff --git a/src/bun.js/modules/NodeModuleModule.cpp b/src/bun.js/modules/NodeModuleModule.cpp deleted file mode 100644 index 476ee95dce2798..00000000000000 --- a/src/bun.js/modules/NodeModuleModule.cpp +++ /dev/null @@ -1,297 +0,0 @@ -#include "root.h" - -#include "./NodeModuleModule.h" - -#include "CommonJSModuleRecord.h" -#include "ImportMetaObject.h" -#include "JavaScriptCore/JSBoundFunction.h" -#include "JavaScriptCore/ObjectConstructor.h" -using namespace Zig; -using namespace JSC; - -// This is a mix of bun's builtin module names and also the ones reported by -// node v20.4.0 -static constexpr ASCIILiteral builtinModuleNames[] = { - "_http_agent"_s, - "_http_client"_s, - "_http_common"_s, - "_http_incoming"_s, - "_http_outgoing"_s, - "_http_server"_s, - "_stream_duplex"_s, - "_stream_passthrough"_s, - "_stream_readable"_s, - "_stream_transform"_s, - "_stream_wrap"_s, - "_stream_writable"_s, - "_tls_common"_s, - "_tls_wrap"_s, - "assert"_s, - "assert/strict"_s, - "async_hooks"_s, - "buffer"_s, - "bun"_s, - "bun:events_native"_s, - "bun:ffi"_s, - "bun:jsc"_s, - "bun:sqlite"_s, - "bun:wrap"_s, - "child_process"_s, - "cluster"_s, - "console"_s, - "constants"_s, - "crypto"_s, - "detect-libc"_s, - "dgram"_s, - "diagnostics_channel"_s, - "dns"_s, - "dns/promises"_s, - "domain"_s, - "events"_s, - "fs"_s, - "fs/promises"_s, - "http"_s, - "http2"_s, - "https"_s, - "inspector"_s, - "inspector/promises"_s, - "module"_s, - "net"_s, - "os"_s, - "path"_s, - "path/posix"_s, - "path/win32"_s, - "perf_hooks"_s, - "process"_s, - "punycode"_s, - "querystring"_s, - "readline"_s, - "readline/promises"_s, - "repl"_s, - "stream"_s, - "stream/consumers"_s, - "stream/promises"_s, - "stream/web"_s, - "string_decoder"_s, - "sys"_s, - "timers"_s, - "timers/promises"_s, - "tls"_s, - "trace_events"_s, - "tty"_s, - "undici"_s, - "url"_s, - "util"_s, - "util/types"_s, - "v8"_s, - "vm"_s, - "wasi"_s, - "worker_threads"_s, - "ws"_s, - "zlib"_s, -}; - -static bool isBuiltinModule(const String &namePossiblyWithNodePrefix) { - String name = namePossiblyWithNodePrefix; - if (name.startsWith("node:"_s)) - name = name.substringSharingImpl(5); - - for (auto &builtinModule : builtinModuleNames) { - if (name == builtinModule) - return true; - } - return false; -} - -JSC_DEFINE_HOST_FUNCTION(jsFunctionIsBuiltinModule, - (JSC::JSGlobalObject * globalObject, - JSC::CallFrame *callFrame)) { - JSC::VM &vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - JSValue moduleName = callFrame->argument(0); - if (!moduleName.isString()) { - return JSValue::encode(jsBoolean(false)); - } - - auto moduleStr = moduleName.toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, JSValue::encode(jsBoolean(false))); - - return JSValue::encode(jsBoolean(isBuiltinModule(moduleStr))); -} - -JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleCreateRequire, - (JSC::JSGlobalObject * globalObject, - JSC::CallFrame *callFrame)) { - JSC::VM &vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - if (callFrame->argumentCount() < 1) { - throwTypeError(globalObject, scope, - "createRequire() requires at least one argument"_s); - RELEASE_AND_RETURN(scope, JSC::JSValue::encode(JSC::jsUndefined())); - } - - auto val = callFrame->uncheckedArgument(0).toWTFString(globalObject); - RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::jsUndefined())); - RELEASE_AND_RETURN( - scope, JSValue::encode(Bun::JSCommonJSModule::createBoundRequireFunction( - vm, globalObject, val))); -} -extern "C" EncodedJSValue Resolver__nodeModulePathsForJS(JSGlobalObject *, - CallFrame *); - -JSC_DEFINE_HOST_FUNCTION(jsFunctionFindSourceMap, - (JSGlobalObject * globalObject, - CallFrame *callFrame)) { - auto &vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - throwException(globalObject, scope, - createError(globalObject, "Not implemented"_s)); - return JSValue::encode(jsUndefined()); -} - -JSC_DEFINE_HOST_FUNCTION(jsFunctionSyncBuiltinExports, - (JSGlobalObject * globalObject, - CallFrame *callFrame)) { - return JSValue::encode(jsUndefined()); -} - -JSC_DEFINE_HOST_FUNCTION(jsFunctionSourceMap, (JSGlobalObject * globalObject, - CallFrame *callFrame)) { - auto &vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - throwException(globalObject, scope, - createError(globalObject, "Not implemented"_s)); - return JSValue::encode(jsUndefined()); -} - -JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, - (JSC::JSGlobalObject * globalObject, - JSC::CallFrame *callFrame)) { - JSC::VM &vm = globalObject->vm(); - - switch (callFrame->argumentCount()) { - case 0: { - auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); - // not "requires" because "require" could be confusing - JSC::throwTypeError( - globalObject, scope, - "Module._resolveFileName needs 2+ arguments (a string)"_s); - scope.release(); - return JSC::JSValue::encode(JSC::JSValue{}); - } - default: { - JSC::JSValue moduleName = callFrame->argument(0); - - if (moduleName.isUndefinedOrNull()) { - auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); - JSC::throwTypeError(globalObject, scope, - "Module._resolveFileName expects a string"_s); - scope.release(); - return JSC::JSValue::encode(JSC::JSValue{}); - } - - auto result = - Bun__resolveSync(globalObject, JSC::JSValue::encode(moduleName), - JSValue::encode(callFrame->argument(1)), false); - auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); - - if (!JSC::JSValue::decode(result).isString()) { - JSC::throwException(globalObject, scope, JSC::JSValue::decode(result)); - return JSC::JSValue::encode(JSC::JSValue{}); - } - - scope.release(); - return result; - } - } -} -template consteval std::size_t countof(T (&)[N]) { - return N; -} - -namespace Zig { -void generateNodeModuleModule(JSC::JSGlobalObject *globalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues) { - JSC::VM &vm = globalObject->vm(); - - JSObject *defaultObject = JSC::constructEmptyObject( - vm, globalObject->nullPrototypeObjectStructure()); - auto append = [&](Identifier name, JSValue value) { - defaultObject->putDirect(vm, name, value); - exportNames.append(name); - exportValues.append(value); - }; - - append(Identifier::fromString(vm, "createRequire"_s), - JSFunction::create(vm, globalObject, 1, String("createRequire"_s), - jsFunctionNodeModuleCreateRequire, - ImplementationVisibility::Public)); - - append(Identifier::fromString(vm, "paths"_s), - JSFunction::create(vm, globalObject, 1, String("paths"_s), - Resolver__nodeModulePathsForJS, - ImplementationVisibility::Public)); - - append(Identifier::fromString(vm, "findSourceMap"_s), - JSFunction::create(vm, globalObject, 1, String("findSourceMap"_s), - jsFunctionFindSourceMap, - ImplementationVisibility::Public)); - append(Identifier::fromString(vm, "syncBuiltinExports"_s), - JSFunction::create(vm, globalObject, 0, String("syncBuiltinExports"_s), - jsFunctionSyncBuiltinExports, - ImplementationVisibility::Public)); - append(Identifier::fromString(vm, "SourceMap"_s), - JSFunction::create(vm, globalObject, 1, String("SourceMap"_s), - jsFunctionSourceMap, - ImplementationVisibility::Public, NoIntrinsic, - jsFunctionSourceMap, nullptr)); - - append(Identifier::fromString(vm, "isBuiltin"_s), - JSFunction::create(vm, globalObject, 1, String("isBuiltin"_s), - jsFunctionIsBuiltinModule, - ImplementationVisibility::Public, NoIntrinsic, - jsFunctionIsBuiltinModule, nullptr)); - - append(JSC::Identifier::fromString(vm, "_resolveFilename"_s), - JSFunction::create(vm, globalObject, 3, String("_resolveFilename"_s), - jsFunctionResolveFileName, - ImplementationVisibility::Public)); - - append(JSC::Identifier::fromString(vm, "_nodeModulePaths"_s), - JSFunction::create(vm, globalObject, 0, String("_nodeModulePaths"_s), - Resolver__nodeModulePathsForJS, - ImplementationVisibility::Public)); - - append(JSC::Identifier::fromString(vm, "_cache"_s), - jsCast(globalObject)->lazyRequireCacheObject()); - - append(JSC::Identifier::fromString(vm, "globalPaths"_s), - JSC::constructEmptyArray(globalObject, nullptr, 0)); - - append(JSC::Identifier::fromString(vm, "prototype"_s), - JSC::constructEmptyObject(globalObject)); - - JSC::JSArray *builtinModules = JSC::JSArray::create( - vm, - globalObject->arrayStructureForIndexingTypeDuringAllocation( - ArrayWithContiguous), - countof(builtinModuleNames)); - - for (unsigned i = 0; i < countof(builtinModuleNames); ++i) { - builtinModules->putDirectIndex( - globalObject, i, JSC::jsString(vm, String(builtinModuleNames[i]))); - } - - append(JSC::Identifier::fromString(vm, "builtinModules"_s), builtinModules); - - defaultObject->putDirect(vm, - JSC::PropertyName(Identifier::fromUid( - vm.symbolRegistry().symbolForKey("CommonJS"_s))), - jsNumber(0), 0); - - exportNames.append(vm.propertyNames->defaultKeyword); - exportValues.append(defaultObject); -} -} // namespace Zig diff --git a/src/bun.js/modules/NodeModuleModule.h b/src/bun.js/modules/NodeModuleModule.h index 0aefdef1222e3e..7c8f6ee143d84e 100644 --- a/src/bun.js/modules/NodeModuleModule.h +++ b/src/bun.js/modules/NodeModuleModule.h @@ -1,12 +1,348 @@ -#include "../bindings/ZigGlobalObject.h" -#include "JavaScriptCore/JSGlobalObject.h" +#include "CommonJSModuleRecord.h" +#include "ImportMetaObject.h" +#include "JavaScriptCore/JSBoundFunction.h" +#include "JavaScriptCore/ObjectConstructor.h" +#include "_NativeModule.h" + +using namespace Zig; +using namespace JSC; + +// This is a mix of bun's builtin module names and also the ones reported by +// node v20.4.0 +static constexpr ASCIILiteral builtinModuleNames[] = { + "_http_agent"_s, + "_http_client"_s, + "_http_common"_s, + "_http_incoming"_s, + "_http_outgoing"_s, + "_http_server"_s, + "_stream_duplex"_s, + "_stream_passthrough"_s, + "_stream_readable"_s, + "_stream_transform"_s, + "_stream_wrap"_s, + "_stream_writable"_s, + "_tls_common"_s, + "_tls_wrap"_s, + "assert"_s, + "assert/strict"_s, + "async_hooks"_s, + "buffer"_s, + "bun"_s, + "bun:ffi"_s, + "bun:jsc"_s, + "bun:sqlite"_s, + "bun:wrap"_s, + "child_process"_s, + "cluster"_s, + "console"_s, + "constants"_s, + "crypto"_s, + "detect-libc"_s, + "dgram"_s, + "diagnostics_channel"_s, + "dns"_s, + "dns/promises"_s, + "domain"_s, + "events"_s, + "fs"_s, + "fs/promises"_s, + "http"_s, + "http2"_s, + "https"_s, + "inspector"_s, + "inspector/promises"_s, + "module"_s, + "net"_s, + "os"_s, + "path"_s, + "path/posix"_s, + "path/win32"_s, + "perf_hooks"_s, + "process"_s, + "punycode"_s, + "querystring"_s, + "readline"_s, + "readline/promises"_s, + "repl"_s, + "stream"_s, + "stream/consumers"_s, + "stream/promises"_s, + "stream/web"_s, + "string_decoder"_s, + "sys"_s, + "timers"_s, + "timers/promises"_s, + "tls"_s, + "trace_events"_s, + "tty"_s, + "undici"_s, + "url"_s, + "util"_s, + "util/types"_s, + "v8"_s, + "vm"_s, + "wasi"_s, + "worker_threads"_s, + "ws"_s, + "zlib"_s, +}; + +static bool isBuiltinModule(const String &namePossiblyWithNodePrefix) { + String name = namePossiblyWithNodePrefix; + if (name.startsWith("node:"_s)) + name = name.substringSharingImpl(5); + + for (auto &builtinModule : builtinModuleNames) { + if (name == builtinModule) + return true; + } + return false; +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleModuleConstructor, + (JSC::JSGlobalObject * globalObject, + JSC::CallFrame *callFrame)) { + // In node, this is supposed to be the actual CommonJSModule constructor. + // We are cutting a huge corner by not doing all that work. + // This code is only to support babel. + JSC::VM &vm = globalObject->vm(); + JSString *idString = JSC::jsString(vm, WTF::String("."_s)); + + JSString *dirname = jsEmptyString(vm); + + // TODO: handle when JSGlobalObject !== Zig::GlobalObject, such as in node:vm + Structure *structure = static_cast(globalObject) + ->CommonJSModuleObjectStructure(); + + // TODO: handle ShadowRealm, node:vm, new.target, subclasses + JSValue idValue = callFrame->argument(0); + JSValue parentValue = callFrame->argument(1); + + auto scope = DECLARE_THROW_SCOPE(vm); + if (idValue.isString()) { + idString = idValue.toString(globalObject); + RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::jsUndefined())); + + auto index = idString->tryGetValue().reverseFind('/', idString->length()); + + if (index != WTF::notFound) { + dirname = JSC::jsSubstring(globalObject, idString, 0, index); + } + } + + auto *out = Bun::JSCommonJSModule::create(vm, structure, idString, jsNull(), + dirname, nullptr); + + if (!parentValue.isUndefined()) + out->putDirect(vm, JSC::Identifier::fromString(vm, "parent"_s), parentValue, + 0); + + out->putDirect(vm, JSC::Identifier::fromString(vm, "exports"_s), + JSC::constructEmptyObject(globalObject, + globalObject->objectPrototype(), 0), + 0); + return JSValue::encode(out); +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionIsBuiltinModule, + (JSC::JSGlobalObject * globalObject, + JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSValue moduleName = callFrame->argument(0); + if (!moduleName.isString()) { + return JSValue::encode(jsBoolean(false)); + } + + auto moduleStr = moduleName.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, JSValue::encode(jsBoolean(false))); + + return JSValue::encode(jsBoolean(isBuiltinModule(moduleStr))); +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionWrap, (JSC::JSGlobalObject * globalObject, + JSC::CallFrame *callFrame)) { + auto &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + JSString *code = callFrame->argument(0).toStringOrNull(globalObject); + RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::jsUndefined())); + if (!code) { + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + JSString *prefix = jsString( + vm, + String( + "(function (exports, require, module, __filename, __dirname) { "_s)); + JSString *suffix = jsString(vm, String("\n});"_s)); + + return JSValue::encode(jsString(globalObject, prefix, code, suffix)); +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionNodeModuleCreateRequire, + (JSC::JSGlobalObject * globalObject, + JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + if (callFrame->argumentCount() < 1) { + throwTypeError(globalObject, scope, + "createRequire() requires at least one argument"_s); + RELEASE_AND_RETURN(scope, JSC::JSValue::encode(JSC::jsUndefined())); + } + + auto val = callFrame->uncheckedArgument(0).toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::jsUndefined())); + RELEASE_AND_RETURN( + scope, JSValue::encode(Bun::JSCommonJSModule::createBoundRequireFunction( + vm, globalObject, val))); +} +extern "C" EncodedJSValue Resolver__nodeModulePathsForJS(JSGlobalObject *, + CallFrame *); + +JSC_DEFINE_HOST_FUNCTION(jsFunctionFindSourceMap, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + auto &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + throwException(globalObject, scope, + createError(globalObject, "Not implemented"_s)); + return JSValue::encode(jsUndefined()); +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionSyncBuiltinExports, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + return JSValue::encode(jsUndefined()); +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionSourceMap, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + auto &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + throwException(globalObject, scope, + createError(globalObject, "Not implemented"_s)); + return JSValue::encode(jsUndefined()); +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionResolveFileName, + (JSC::JSGlobalObject * globalObject, + JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + + switch (callFrame->argumentCount()) { + case 0: { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + // not "requires" because "require" could be confusing + JSC::throwTypeError( + globalObject, scope, + "Module._resolveFileName needs 2+ arguments (a string)"_s); + scope.release(); + return JSC::JSValue::encode(JSC::JSValue{}); + } + default: { + JSC::JSValue moduleName = callFrame->argument(0); + + if (moduleName.isUndefinedOrNull()) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, + "Module._resolveFileName expects a string"_s); + scope.release(); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + auto result = + Bun__resolveSync(globalObject, JSC::JSValue::encode(moduleName), + JSValue::encode(callFrame->argument(1)), false); + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + + if (!JSC::JSValue::decode(result).isString()) { + JSC::throwException(globalObject, scope, JSC::JSValue::decode(result)); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + scope.release(); + return result; + } + } +} +template consteval std::size_t countof(T (&)[N]) { + return N; +} namespace Zig { -// node:module -void generateNodeModuleModule(JSC::JSGlobalObject *globalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues); +DEFINE_NATIVE_MODULE(NodeModule) { + // the default object here is a function, so we cant use the + // INIT_NATIVE_MODULE helper + + Zig::GlobalObject *globalObject = + reinterpret_cast(lexicalGlobalObject); + JSC::VM &vm = globalObject->vm(); + JSC::JSObject *defaultObject = JSC::JSFunction::create( + vm, globalObject, 0, "Module"_s, jsFunctionNodeModuleModuleConstructor, + JSC::ImplementationVisibility::Public, JSC::NoIntrinsic, + jsFunctionNodeModuleModuleConstructor); + auto put = [&](JSC::Identifier name, JSC::JSValue value) { + defaultObject->putDirect(vm, name, value); + exportNames.append(name); + exportValues.append(value); + }; + auto putNativeFn = [&](JSC::Identifier name, JSC::NativeFunction ptr) { + JSC::JSFunction *value = JSC::JSFunction::create( + vm, globalObject, 1, name.string(), ptr, + JSC::ImplementationVisibility::Public, JSC::NoIntrinsic, ptr); + defaultObject->putDirect(vm, name, value); + exportNames.append(name); + exportValues.append(value); + }; + exportNames.reserveCapacity(15); + exportValues.ensureCapacity(15); + exportNames.append(vm.propertyNames->defaultKeyword); + exportValues.append(defaultObject); + + put(Identifier::fromString(vm, "Module"_s), defaultObject); + + putNativeFn(Identifier::fromString(vm, "createRequire"_s), + jsFunctionNodeModuleCreateRequire); + putNativeFn(Identifier::fromString(vm, "paths"_s), + Resolver__nodeModulePathsForJS); + putNativeFn(Identifier::fromString(vm, "findSourceMap"_s), + jsFunctionFindSourceMap); + putNativeFn(Identifier::fromString(vm, "syncBuiltinExports"_s), + jsFunctionSyncBuiltinExports); + putNativeFn(Identifier::fromString(vm, "SourceMap"_s), jsFunctionSourceMap); + putNativeFn(Identifier::fromString(vm, "isBuiltin"_s), + jsFunctionIsBuiltinModule); + putNativeFn(Identifier::fromString(vm, "_resolveFilename"_s), + jsFunctionResolveFileName); + putNativeFn(Identifier::fromString(vm, "_nodeModulePaths"_s), + Resolver__nodeModulePathsForJS); + putNativeFn(Identifier::fromString(vm, "wrap"_s), jsFunctionWrap); + + put(Identifier::fromString(vm, "_cache"_s), + jsCast(globalObject)->lazyRequireCacheObject()); + + put(Identifier::fromString(vm, "globalPaths"_s), + constructEmptyArray(globalObject, nullptr, 0)); + + put(Identifier::fromString(vm, "prototype"_s), + constructEmptyObject(globalObject)); + + JSC::JSArray *builtinModules = JSC::JSArray::create( + vm, + globalObject->arrayStructureForIndexingTypeDuringAllocation( + ArrayWithContiguous), + countof(builtinModuleNames)); + + for (unsigned i = 0; i < countof(builtinModuleNames); ++i) { + builtinModules->putDirectIndex( + globalObject, i, JSC::jsString(vm, String(builtinModuleNames[i]))); + } + + put(JSC::Identifier::fromString(vm, "builtinModules"_s), builtinModules); + + RETURN_NATIVE_MODULE(); +} -} // namespace Zig \ No newline at end of file +} // namespace Zig diff --git a/src/bun.js/modules/ProcessModule.h b/src/bun.js/modules/NodeProcessModule.h similarity index 84% rename from src/bun.js/modules/ProcessModule.h rename to src/bun.js/modules/NodeProcessModule.h index fab0298aec5ce9..6c3db073112ccd 100644 --- a/src/bun.js/modules/ProcessModule.h +++ b/src/bun.js/modules/NodeProcessModule.h @@ -1,6 +1,7 @@ #include "../bindings/ZigGlobalObject.h" #include "JavaScriptCore/CustomGetterSetter.h" #include "JavaScriptCore/JSGlobalObject.h" +#include "_NativeModule.h" namespace Zig { @@ -35,10 +36,7 @@ JSC_DEFINE_CUSTOM_SETTER(jsFunctionProcessModuleCommonJSSetter, ->putDirect(vm, propertyName, JSValue::decode(encodedValue), 0); } -inline void generateProcessSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues) { +DEFINE_NATIVE_MODULE(NodeProcess) { JSC::VM &vm = lexicalGlobalObject->vm(); GlobalObject *globalObject = reinterpret_cast(lexicalGlobalObject); @@ -61,10 +59,6 @@ inline void generateProcessSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, exportNames.append(vm.propertyNames->defaultKeyword); exportValues.append(process); - exportNames.append( - Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s))); - exportValues.append(jsNumber(0)); - for (auto &entry : properties) { exportNames.append(entry); auto catchScope = DECLARE_CATCH_SCOPE(vm); diff --git a/src/bun.js/modules/NodeStringDecoderModule.h b/src/bun.js/modules/NodeStringDecoderModule.h new file mode 100644 index 00000000000000..3f5258cc1d8513 --- /dev/null +++ b/src/bun.js/modules/NodeStringDecoderModule.h @@ -0,0 +1,16 @@ +#include "../bindings/JSStringDecoder.h" +#include "../bindings/ZigGlobalObject.h" +#include "JavaScriptCore/JSGlobalObject.h" + +namespace Zig { + +DEFINE_NATIVE_MODULE(NodeStringDecoder) { + INIT_NATIVE_MODULE(1); + + put(JSC::Identifier::fromString(vm, "StringDecoder"_s), + globalObject->JSStringDecoder()); + + RETURN_NATIVE_MODULE(); +} + +} // namespace Zig diff --git a/src/bun.js/modules/NodeTTYModule.h b/src/bun.js/modules/NodeTTYModule.h new file mode 100644 index 00000000000000..18a8f59a9a32d2 --- /dev/null +++ b/src/bun.js/modules/NodeTTYModule.h @@ -0,0 +1,50 @@ +#include "JSBuffer.h" +#include "_NativeModule.h" + +namespace Zig { +using namespace WebCore; + +JSC_DEFINE_HOST_FUNCTION(jsFunctionTty_isatty, (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + VM &vm = globalObject->vm(); + if (callFrame->argumentCount() < 1) { + return JSValue::encode(jsBoolean(false)); + } + + auto scope = DECLARE_CATCH_SCOPE(vm); + int fd = callFrame->argument(0).toInt32(globalObject); + RETURN_IF_EXCEPTION(scope, encodedJSValue()); + + return JSValue::encode(jsBoolean(isatty(fd))); +} + +JSC_DEFINE_HOST_FUNCTION(jsFunctionNotImplementedYet, + (JSGlobalObject * globalObject, + CallFrame *callFrame)) { + VM &vm = globalObject->vm(); + auto throwScope = DECLARE_THROW_SCOPE(vm); + throwException(globalObject, throwScope, + createError(globalObject, "Not implemented yet"_s)); + return JSValue::encode(jsUndefined()); +} + +DEFINE_NATIVE_MODULE(NodeTTY) { + INIT_NATIVE_MODULE(3); + + auto *isattyFunction = + JSFunction::create(vm, globalObject, 1, "isatty"_s, jsFunctionTty_isatty, + ImplementationVisibility::Public); + + auto *notimpl = JSFunction::create(vm, globalObject, 0, "notimpl"_s, + jsFunctionNotImplementedYet, + ImplementationVisibility::Public, + NoIntrinsic, jsFunctionNotImplementedYet); + + putNativeFn(Identifier::fromString(vm, "isatty"_s), jsFunctionTty_isatty); + put(Identifier::fromString(vm, "ReadStream"_s), notimpl); + put(Identifier::fromString(vm, "WriteStream"_s), notimpl); + + RETURN_NATIVE_MODULE(); +} + +} // namespace Zig diff --git a/src/bun.js/bindings/node_util_types.cpp b/src/bun.js/modules/NodeUtilTypesModule.h similarity index 73% rename from src/bun.js/bindings/node_util_types.cpp rename to src/bun.js/modules/NodeUtilTypesModule.h index f7ae3949e2e619..586743feaca2ab 100644 --- a/src/bun.js/bindings/node_util_types.cpp +++ b/src/bun.js/modules/NodeUtilTypesModule.h @@ -1,5 +1,4 @@ -#include "root.h" -#include "node_util_types.h" +#include "_NativeModule.h" #include "webcrypto/JSCryptoKey.h" #include "napi_external.h" @@ -312,72 +311,54 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionIsCryptoKey, (JSC::JSGlobalObject * globalObj return JSValue::encode(jsBoolean(cell->inherits())); } -namespace Bun { -void generateNodeUtilTypesSourceCode(JSC::JSGlobalObject* lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector& exportNames, - JSC::MarkedArgumentBuffer& exportValues) +namespace Zig { +DEFINE_NATIVE_MODULE(NodeUtilTypes) { - Zig::GlobalObject* globalObject = reinterpret_cast(lexicalGlobalObject); + INIT_NATIVE_MODULE(42); - JSC::VM& vm = globalObject->vm(); + putNativeFn(Identifier::fromString(vm, "isExternal"_s), jsFunctionIsExternal); + putNativeFn(Identifier::fromString(vm, "isDate"_s), jsFunctionIsDate); + putNativeFn(Identifier::fromString(vm, "isArgumentsObject"_s), jsFunctionIsArgumentsObject); + putNativeFn(Identifier::fromString(vm, "isBigIntObject"_s), jsFunctionIsBigIntObject); + putNativeFn(Identifier::fromString(vm, "isBooleanObject"_s), jsFunctionIsBooleanObject); + putNativeFn(Identifier::fromString(vm, "isNumberObject"_s), jsFunctionIsNumberObject); + putNativeFn(Identifier::fromString(vm, "isStringObject"_s), jsFunctionIsStringObject); + putNativeFn(Identifier::fromString(vm, "isSymbolObject"_s), jsFunctionIsSymbolObject); + putNativeFn(Identifier::fromString(vm, "isNativeError"_s), jsFunctionIsNativeError); + putNativeFn(Identifier::fromString(vm, "isRegExp"_s), jsFunctionIsRegExp); + putNativeFn(Identifier::fromString(vm, "isAsyncFunction"_s), jsFunctionIsAsyncFunction); + putNativeFn(Identifier::fromString(vm, "isGeneratorFunction"_s), jsFunctionIsGeneratorFunction); + putNativeFn(Identifier::fromString(vm, "isGeneratorObject"_s), jsFunctionIsGeneratorObject); + putNativeFn(Identifier::fromString(vm, "isPromise"_s), jsFunctionIsPromise); + putNativeFn(Identifier::fromString(vm, "isMap"_s), jsFunctionIsMap); + putNativeFn(Identifier::fromString(vm, "isSet"_s), jsFunctionIsSet); + putNativeFn(Identifier::fromString(vm, "isMapIterator"_s), jsFunctionIsMapIterator); + putNativeFn(Identifier::fromString(vm, "isSetIterator"_s), jsFunctionIsSetIterator); + putNativeFn(Identifier::fromString(vm, "isWeakMap"_s), jsFunctionIsWeakMap); + putNativeFn(Identifier::fromString(vm, "isWeakSet"_s), jsFunctionIsWeakSet); + putNativeFn(Identifier::fromString(vm, "isArrayBuffer"_s), jsFunctionIsArrayBuffer); + putNativeFn(Identifier::fromString(vm, "isDataView"_s), jsFunctionIsDataView); + putNativeFn(Identifier::fromString(vm, "isSharedArrayBuffer"_s), jsFunctionIsSharedArrayBuffer); + putNativeFn(Identifier::fromString(vm, "isProxy"_s), jsFunctionIsProxy); + putNativeFn(Identifier::fromString(vm, "isModuleNamespaceObject"_s), jsFunctionIsModuleNamespaceObject); + putNativeFn(Identifier::fromString(vm, "isAnyArrayBuffer"_s), jsFunctionIsAnyArrayBuffer); + putNativeFn(Identifier::fromString(vm, "isBoxedPrimitive"_s), jsFunctionIsBoxedPrimitive); + putNativeFn(Identifier::fromString(vm, "isArrayBufferView"_s), jsFunctionIsArrayBufferView); + putNativeFn(Identifier::fromString(vm, "isTypedArray"_s), jsFunctionIsTypedArray); + putNativeFn(Identifier::fromString(vm, "isUint8Array"_s), jsFunctionIsUint8Array); + putNativeFn(Identifier::fromString(vm, "isUint8ClampedArray"_s), jsFunctionIsUint8ClampedArray); + putNativeFn(Identifier::fromString(vm, "isUint16Array"_s), jsFunctionIsUint16Array); + putNativeFn(Identifier::fromString(vm, "isUint32Array"_s), jsFunctionIsUint32Array); + putNativeFn(Identifier::fromString(vm, "isInt8Array"_s), jsFunctionIsInt8Array); + putNativeFn(Identifier::fromString(vm, "isInt16Array"_s), jsFunctionIsInt16Array); + putNativeFn(Identifier::fromString(vm, "isInt32Array"_s), jsFunctionIsInt32Array); + putNativeFn(Identifier::fromString(vm, "isFloat32Array"_s), jsFunctionIsFloat32Array); + putNativeFn(Identifier::fromString(vm, "isFloat64Array"_s), jsFunctionIsFloat64Array); + putNativeFn(Identifier::fromString(vm, "isBigInt64Array"_s), jsFunctionIsBigInt64Array); + putNativeFn(Identifier::fromString(vm, "isBigUint64Array"_s), jsFunctionIsBigUint64Array); + putNativeFn(Identifier::fromString(vm, "isKeyObject"_s), jsFunctionIsKeyObject); + putNativeFn(Identifier::fromString(vm, "isCryptoKey"_s), jsFunctionIsCryptoKey); - JSC::JSObject* defaultObject = constructEmptyObject(globalObject, globalObject->objectPrototype(), 42); - exportNames.reserveCapacity(43); - exportValues.ensureCapacity(43); - - auto putBoth = [&](JSC::Identifier identifier, NativeFunction functionPtr) { - JSC::JSFunction* function = JSC::JSFunction::create(vm, globalObject, 1, identifier.string(), functionPtr, ImplementationVisibility::Public, NoIntrinsic, functionPtr); - defaultObject->putDirect(vm, identifier, function, 0); - exportNames.append(identifier); - exportValues.append(function); - }; - - putBoth(Identifier::fromString(vm, "isExternal"_s), jsFunctionIsExternal); - putBoth(Identifier::fromString(vm, "isDate"_s), jsFunctionIsDate); - putBoth(Identifier::fromString(vm, "isArgumentsObject"_s), jsFunctionIsArgumentsObject); - putBoth(Identifier::fromString(vm, "isBigIntObject"_s), jsFunctionIsBigIntObject); - putBoth(Identifier::fromString(vm, "isBooleanObject"_s), jsFunctionIsBooleanObject); - putBoth(Identifier::fromString(vm, "isNumberObject"_s), jsFunctionIsNumberObject); - putBoth(Identifier::fromString(vm, "isStringObject"_s), jsFunctionIsStringObject); - putBoth(Identifier::fromString(vm, "isSymbolObject"_s), jsFunctionIsSymbolObject); - putBoth(Identifier::fromString(vm, "isNativeError"_s), jsFunctionIsNativeError); - putBoth(Identifier::fromString(vm, "isRegExp"_s), jsFunctionIsRegExp); - putBoth(Identifier::fromString(vm, "isAsyncFunction"_s), jsFunctionIsAsyncFunction); - putBoth(Identifier::fromString(vm, "isGeneratorFunction"_s), jsFunctionIsGeneratorFunction); - putBoth(Identifier::fromString(vm, "isGeneratorObject"_s), jsFunctionIsGeneratorObject); - putBoth(Identifier::fromString(vm, "isPromise"_s), jsFunctionIsPromise); - putBoth(Identifier::fromString(vm, "isMap"_s), jsFunctionIsMap); - putBoth(Identifier::fromString(vm, "isSet"_s), jsFunctionIsSet); - putBoth(Identifier::fromString(vm, "isMapIterator"_s), jsFunctionIsMapIterator); - putBoth(Identifier::fromString(vm, "isSetIterator"_s), jsFunctionIsSetIterator); - putBoth(Identifier::fromString(vm, "isWeakMap"_s), jsFunctionIsWeakMap); - putBoth(Identifier::fromString(vm, "isWeakSet"_s), jsFunctionIsWeakSet); - putBoth(Identifier::fromString(vm, "isArrayBuffer"_s), jsFunctionIsArrayBuffer); - putBoth(Identifier::fromString(vm, "isDataView"_s), jsFunctionIsDataView); - putBoth(Identifier::fromString(vm, "isSharedArrayBuffer"_s), jsFunctionIsSharedArrayBuffer); - putBoth(Identifier::fromString(vm, "isProxy"_s), jsFunctionIsProxy); - putBoth(Identifier::fromString(vm, "isModuleNamespaceObject"_s), jsFunctionIsModuleNamespaceObject); - putBoth(Identifier::fromString(vm, "isAnyArrayBuffer"_s), jsFunctionIsAnyArrayBuffer); - putBoth(Identifier::fromString(vm, "isBoxedPrimitive"_s), jsFunctionIsBoxedPrimitive); - putBoth(Identifier::fromString(vm, "isArrayBufferView"_s), jsFunctionIsArrayBufferView); - putBoth(Identifier::fromString(vm, "isTypedArray"_s), jsFunctionIsTypedArray); - putBoth(Identifier::fromString(vm, "isUint8Array"_s), jsFunctionIsUint8Array); - putBoth(Identifier::fromString(vm, "isUint8ClampedArray"_s), jsFunctionIsUint8ClampedArray); - putBoth(Identifier::fromString(vm, "isUint16Array"_s), jsFunctionIsUint16Array); - putBoth(Identifier::fromString(vm, "isUint32Array"_s), jsFunctionIsUint32Array); - putBoth(Identifier::fromString(vm, "isInt8Array"_s), jsFunctionIsInt8Array); - putBoth(Identifier::fromString(vm, "isInt16Array"_s), jsFunctionIsInt16Array); - putBoth(Identifier::fromString(vm, "isInt32Array"_s), jsFunctionIsInt32Array); - putBoth(Identifier::fromString(vm, "isFloat32Array"_s), jsFunctionIsFloat32Array); - putBoth(Identifier::fromString(vm, "isFloat64Array"_s), jsFunctionIsFloat64Array); - putBoth(Identifier::fromString(vm, "isBigInt64Array"_s), jsFunctionIsBigInt64Array); - putBoth(Identifier::fromString(vm, "isBigUint64Array"_s), jsFunctionIsBigUint64Array); - putBoth(Identifier::fromString(vm, "isKeyObject"_s), jsFunctionIsKeyObject); - putBoth(Identifier::fromString(vm, "isCryptoKey"_s), jsFunctionIsCryptoKey); - defaultObject->putDirect(vm, JSC::PropertyName(Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s))), jsNumber(0), 0); - - exportNames.append(JSC::Identifier::fromString(vm, "default"_s)); - exportValues.append(defaultObject); -} + RETURN_NATIVE_MODULE(); } +} // namespace Zig diff --git a/src/bun.js/modules/StringDecoderModule.h b/src/bun.js/modules/StringDecoderModule.h deleted file mode 100644 index 1dbf5ef8e24c12..00000000000000 --- a/src/bun.js/modules/StringDecoderModule.h +++ /dev/null @@ -1,36 +0,0 @@ -#include "../bindings/JSStringDecoder.h" -#include "../bindings/ZigGlobalObject.h" -#include "JavaScriptCore/JSGlobalObject.h" - -namespace Zig { - -inline void -generateStringDecoderSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues) { - JSC::VM &vm = lexicalGlobalObject->vm(); - GlobalObject *globalObject = - reinterpret_cast(lexicalGlobalObject); - - exportNames.append(JSC::Identifier::fromString(vm, "StringDecoder"_s)); - exportValues.append(globalObject->JSStringDecoder()); - - auto CommonJS = - Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s)); - - JSC::JSObject *defaultObject = constructEmptyObject(globalObject); - defaultObject->putDirect(vm, PropertyName(CommonJS), jsNumber(0), 0); - - for (size_t i = 0; i < exportNames.size(); i++) { - defaultObject->putDirect(vm, exportNames[i], exportValues.at(i), 0); - } - - exportNames.append(vm.propertyNames->defaultKeyword); - exportValues.append(defaultObject); - - exportNames.append(CommonJS); - exportValues.append(jsNumber(0)); -} - -} // namespace Zig diff --git a/src/bun.js/modules/TTYModule.h b/src/bun.js/modules/TTYModule.h deleted file mode 100644 index 79bc8c8711d833..00000000000000 --- a/src/bun.js/modules/TTYModule.h +++ /dev/null @@ -1,81 +0,0 @@ -#include "../bindings/JSBuffer.h" -#include "../bindings/ZigGlobalObject.h" -#include "JavaScriptCore/JSGlobalObject.h" - -#include "JavaScriptCore/ObjectConstructor.h" - -namespace Zig { -using namespace WebCore; - -JSC_DEFINE_HOST_FUNCTION(jsFunctionTty_isatty, (JSGlobalObject * globalObject, - CallFrame *callFrame)) { - VM &vm = globalObject->vm(); - if (callFrame->argumentCount() < 1) { - return JSValue::encode(jsBoolean(false)); - } - - auto scope = DECLARE_CATCH_SCOPE(vm); - int fd = callFrame->argument(0).toInt32(globalObject); - RETURN_IF_EXCEPTION(scope, encodedJSValue()); - - return JSValue::encode(jsBoolean(isatty(fd))); -} - -JSC_DEFINE_HOST_FUNCTION(jsFunctionNotImplementedYet, - (JSGlobalObject * globalObject, - CallFrame *callFrame)) { - VM &vm = globalObject->vm(); - auto throwScope = DECLARE_THROW_SCOPE(vm); - throwException(globalObject, throwScope, - createError(globalObject, "Not implemented yet"_s)); - return JSValue::encode(jsUndefined()); -} - -inline void generateTTYSourceCode(JSC::JSGlobalObject *lexicalGlobalObject, - JSC::Identifier moduleKey, - Vector &exportNames, - JSC::MarkedArgumentBuffer &exportValues) { - JSC::VM &vm = lexicalGlobalObject->vm(); - GlobalObject *globalObject = - reinterpret_cast(lexicalGlobalObject); - - auto *tty = JSC::constructEmptyObject(globalObject, - globalObject->objectPrototype(), 3); - - auto *isattyFunction = - JSFunction::create(vm, globalObject, 1, "isatty"_s, jsFunctionTty_isatty, - ImplementationVisibility::Public); - - auto *notimpl = JSFunction::create(vm, globalObject, 0, "notimpl"_s, - jsFunctionNotImplementedYet, - ImplementationVisibility::Public, - NoIntrinsic, jsFunctionNotImplementedYet); - - exportNames.append(JSC::Identifier::fromString(vm, "isatty"_s)); - exportValues.append(isattyFunction); - - exportNames.append(JSC::Identifier::fromString(vm, "ReadStream"_s)); - tty->putDirect(vm, JSC::Identifier::fromString(vm, "ReadStream"_s), notimpl); - exportValues.append(notimpl); - - exportNames.append(JSC::Identifier::fromString(vm, "WriteStream"_s)); - tty->putDirect(vm, JSC::Identifier::fromString(vm, "WriteStream"_s), notimpl); - exportValues.append(notimpl); - - for (size_t i = 0; i < exportNames.size(); i++) { - tty->putDirect(vm, exportNames[i], exportValues.at(i), 0); - } - - exportNames.append(vm.propertyNames->defaultKeyword); - exportValues.append(tty); - - auto CommonJS = - Identifier::fromUid(vm.symbolRegistry().symbolForKey("CommonJS"_s)); - - exportNames.append(CommonJS); - exportValues.append(jsNumber(0)); - - tty->putDirect(vm, PropertyName(CommonJS), jsNumber(0), 0); -} - -} // namespace Zig diff --git a/src/bun.js/modules/UTF8ValidateModule.h b/src/bun.js/modules/UTF8ValidateModule.h new file mode 100644 index 00000000000000..18f309e6308d6e --- /dev/null +++ b/src/bun.js/modules/UTF8ValidateModule.h @@ -0,0 +1,20 @@ + +using namespace JSC; +using namespace WebCore; + +namespace Zig { +inline void +generateNativeModule_UTF8Validate(JSC::JSGlobalObject *globalObject, + JSC::Identifier moduleKey, + Vector &exportNames, + JSC::MarkedArgumentBuffer &exportValues) { + auto &vm = globalObject->vm(); + + exportNames.append(vm.propertyNames->defaultKeyword); + exportValues.append(JSC::JSFunction::create( + vm, globalObject, 1, "utf8Validate"_s, jsBufferConstructorFunction_isUtf8, + ImplementationVisibility::Public, NoIntrinsic, + jsBufferConstructorFunction_isUtf8)); +} + +} // namespace Zig diff --git a/src/bun.js/modules/_NativeModule.h b/src/bun.js/modules/_NativeModule.h new file mode 100644 index 00000000000000..485987e1cd4e8a --- /dev/null +++ b/src/bun.js/modules/_NativeModule.h @@ -0,0 +1,92 @@ +// clang-format off +#pragma once +#include "JSBuffer.h" +#include "JavaScriptCore/JSGlobalObject.h" +#include "JavaScriptCore/ObjectConstructor.h" +#include "ZigGlobalObject.h" + +// These modules are implemented in native code as a function which writes ESM +// export key+value pairs. The following macros help simplify the implementation +// of these functions. + +// To add a new native module +// 1. Add a new line to `BUN_FOREACH_NATIVE_MODULE` +// 2. Add a case to `module_loader.zig` that resolves the import. +// 3. Add a new file in this folder named after the module, camelcase and suffixed with Module, +// like "NodeBufferModule.h" or "BunJSCModule.h". It should call DEFINE_NATIVE_MODULE(name). +// +// The native module function is called to create the module object: +// - INIT_NATIVE_MODULE(n) is called with the number of exports +// - put(id, jsvalue) adds an export +// - putNativeFn(id, nativefn) lets you quickly add from `JSC_DEFINE_HOST_FUNCTION` +// - NATIVE_MODULE_FINISH() do asserts and finalize everything. +// If you decide to not use INIT_NATIVE_MODULE. make sure the first property +// given is the default export + +#define BUN_FOREACH_NATIVE_MODULE(macro) \ + macro("bun"_s, BunObject) \ + macro("bun:jsc"_s, BunJSC) \ + macro("node:buffer"_s, NodeBuffer) \ + macro("node:constants"_s, NodeConstants) \ + macro("node:module"_s, NodeModule) \ + macro("node:process"_s, NodeProcess) \ + macro("node:string_decoder"_s, NodeStringDecoder) \ + macro("node:tty"_s, NodeTTY) \ + macro("node:util/types"_s, NodeUtilTypes) \ + macro("utf-8-validate"_s, UTF8Validate) \ + +#if ASSERT_ENABLED + +// This function is a lie. It doesnt return, but rather it performs an assertion +// that what you passed to INIT_NATIVE_MODULE is indeed correct. +#define RETURN_NATIVE_MODULE() \ + ASSERT_WITH_MESSAGE(numberOfActualExportNames == passedNumberOfExportNames, \ + "NATIVE_MODULE_START() was given the incorrect value."); + +#define __NATIVE_MODULE_ASSERT_DECL \ + int numberOfActualExportNames = 0; \ + int passedNumberOfExportNames = numberOfExportNames; \ +#define __NATIVE_MODULE_ASSERT_INCR numberOfActualExportNames++; + +#else + +#define RETURN_NATIVE_MODULE() ; +#define __NATIVE_MODULE_ASSERT_INCR ; +#define __NATIVE_MODULE_ASSERT_DECL ; + +#endif + +#define DEFINE_NATIVE_MODULE(name) \ + inline void generateNativeModule_##name( \ + JSC::JSGlobalObject *lexicalGlobalObject, JSC::Identifier moduleKey, \ + Vector &exportNames, \ + JSC::MarkedArgumentBuffer &exportValues) + +#define INIT_NATIVE_MODULE(numberOfExportNames) \ + Zig::GlobalObject *globalObject = \ + reinterpret_cast(lexicalGlobalObject); \ + JSC::VM &vm = globalObject->vm(); \ + JSC::JSObject *defaultObject = JSC::constructEmptyObject( \ + globalObject, globalObject->objectPrototype(), numberOfExportNames); \ + __NATIVE_MODULE_ASSERT_DECL \ + auto put = [&](JSC::Identifier name, JSC::JSValue value) { \ + defaultObject->putDirect(vm, name, value); \ + exportNames.append(name); \ + exportValues.append(value); \ + __NATIVE_MODULE_ASSERT_INCR \ + }; \ + auto putNativeFn = [&](JSC::Identifier name, JSC::NativeFunction ptr) { \ + JSC::JSFunction *value = JSC::JSFunction::create( \ + vm, globalObject, 1, name.string(), ptr, \ + JSC::ImplementationVisibility::Public, JSC::NoIntrinsic, ptr); \ + defaultObject->putDirect(vm, name, value); \ + exportNames.append(name); \ + exportValues.append(value); \ + __NATIVE_MODULE_ASSERT_INCR \ + }; \ + exportNames.reserveCapacity(numberOfExportNames + 1); \ + exportValues.ensureCapacity(numberOfExportNames + 1); \ + exportNames.append(vm.propertyNames->defaultKeyword); \ + exportValues.append(defaultObject); \ + while (0) { \ + } diff --git a/src/bun.js/node/fs_events.zig b/src/bun.js/node/fs_events.zig index 54c969d0f2d336..70b41fc335529d 100644 --- a/src/bun.js/node/fs_events.zig +++ b/src/bun.js/node/fs_events.zig @@ -267,10 +267,11 @@ pub const FSEventsLoop = struct { pub const Queue = UnboundedQueue(ConcurrentTask, .next); - pub fn from(this: *ConcurrentTask, task: Task) *ConcurrentTask { + pub fn from(this: *ConcurrentTask, task: Task, auto_delete: bool) *ConcurrentTask { this.* = .{ .task = task, .next = null, + .auto_delete = auto_delete, }; return this; } @@ -339,8 +340,7 @@ pub const FSEventsLoop = struct { fn enqueueTaskConcurrent(this: *FSEventsLoop, task: Task) void { const CF = CoreFoundation.get(); var concurrent = bun.default_allocator.create(ConcurrentTask) catch unreachable; - concurrent.auto_delete = true; - this.tasks.push(concurrent.from(task)); + this.tasks.push(concurrent.from(task, true)); CF.RunLoopSourceSignal(this.signal_source); CF.RunLoopWakeUp(this.loop); } @@ -354,25 +354,27 @@ pub const FSEventsLoop = struct { for (loop.watchers.slice()) |watcher| { if (watcher) |handle| { + const handle_path = handle.path; + for (paths, 0..) |path_ptr, i| { var flags = event_flags[i]; var path = path_ptr[0..bun.len(path_ptr)]; // Filter out paths that are outside handle's request - if (path.len < handle.path.len or !bun.strings.startsWith(path, handle.path)) { + if (path.len < handle_path.len or !bun.strings.startsWith(path, handle_path)) { continue; } const is_file = (flags & kFSEventStreamEventFlagItemIsDir) == 0; // Remove common prefix, unless the watched folder is "/" - if (!(handle.path.len == 1 and handle.path[0] == '/')) { - path = path[handle.path.len..]; + if (!(handle_path.len == 1 and handle_path[0] == '/')) { + path = path[handle_path.len..]; // Ignore events with path equal to directory itself if (path.len <= 1 and is_file) { continue; } if (path.len == 0) { - // Since we're using fsevents to watch the file itself, path == handle.path, and we now need to get the basename of the file back + // Since we're using fsevents to watch the file itself, path == handle_path, and we now need to get the basename of the file back while (path.len > 0) { if (bun.strings.startsWithChar(path, '/')) { path = path[1..]; @@ -403,8 +405,9 @@ pub const FSEventsLoop = struct { } } - handle.callback(handle.ctx, path, is_file, is_rename); + handle.emit(path, is_file, if (is_rename) .rename else .change); } + handle.flush(); } } } @@ -414,6 +417,7 @@ pub const FSEventsLoop = struct { this.mutex.lock(); defer this.mutex.unlock(); this.has_scheduled_watchers = false; + const watcher_count = this.watcher_count; var watchers = this.watchers.slice(); @@ -432,14 +436,18 @@ pub const FSEventsLoop = struct { // clean old paths if (this.paths) |p| { this.paths = null; - bun.default_allocator.destroy(p); + bun.default_allocator.free(p); } if (this.cf_paths) |cf| { this.cf_paths = null; CF.Release(cf); } - const paths = bun.default_allocator.alloc(?*anyopaque, this.watcher_count) catch unreachable; + if (watcher_count == 0) { + return; + } + + const paths = bun.default_allocator.alloc(?*anyopaque, watcher_count) catch unreachable; var count: u32 = 0; for (watchers) |w| { if (w) |watcher| { @@ -548,7 +556,7 @@ pub const FSEventsLoop = struct { this.signal_source = null; this.sem.deinit(); - this.mutex.deinit(); + if (this.watcher_count > 0) { while (this.watchers.popOrNull()) |watcher| { if (watcher) |w| { @@ -567,17 +575,27 @@ pub const FSEventsLoop = struct { pub const FSEventsWatcher = struct { path: string, callback: Callback, + flushCallback: UpdateEndCallback, loop: ?*FSEventsLoop, recursive: bool, ctx: ?*anyopaque, - const Callback = *const fn (ctx: ?*anyopaque, path: string, is_file: bool, is_rename: bool) void; + pub const EventType = enum { + rename, + change, + @"error", + }; + + pub const Callback = *const fn (ctx: ?*anyopaque, path: string, is_file: bool, event_type: EventType) void; + pub const UpdateEndCallback = *const fn (ctx: ?*anyopaque) void; - pub fn init(loop: *FSEventsLoop, path: string, recursive: bool, callback: Callback, ctx: ?*anyopaque) *FSEventsWatcher { + pub fn init(loop: *FSEventsLoop, path: string, recursive: bool, callback: Callback, updateEnd: UpdateEndCallback, ctx: ?*anyopaque) *FSEventsWatcher { var this = bun.default_allocator.create(FSEventsWatcher) catch unreachable; + this.* = FSEventsWatcher{ .path = path, .callback = callback, + .flushCallback = updateEnd, .loop = loop, .recursive = recursive, .ctx = ctx, @@ -587,6 +605,14 @@ pub const FSEventsWatcher = struct { return this; } + pub fn emit(this: *FSEventsWatcher, path: string, is_file: bool, event_type: EventType) void { + this.callback(this.ctx, path, is_file, event_type); + } + + pub fn flush(this: *FSEventsWatcher) void { + this.flushCallback(this.ctx); + } + pub fn deinit(this: *FSEventsWatcher) void { if (this.loop) |loop| { loop.unregisterWatcher(this); @@ -595,15 +621,15 @@ pub const FSEventsWatcher = struct { } }; -pub fn watch(path: string, recursive: bool, callback: FSEventsWatcher.Callback, ctx: ?*anyopaque) !*FSEventsWatcher { +pub fn watch(path: string, recursive: bool, callback: FSEventsWatcher.Callback, updateEnd: FSEventsWatcher.UpdateEndCallback, ctx: ?*anyopaque) !*FSEventsWatcher { if (fsevents_default_loop) |loop| { - return FSEventsWatcher.init(loop, path, recursive, callback, ctx); + return FSEventsWatcher.init(loop, path, recursive, callback, updateEnd, ctx); } else { fsevents_default_loop_mutex.lock(); defer fsevents_default_loop_mutex.unlock(); if (fsevents_default_loop == null) { fsevents_default_loop = try FSEventsLoop.init(); } - return FSEventsWatcher.init(fsevents_default_loop.?, path, recursive, callback, ctx); + return FSEventsWatcher.init(fsevents_default_loop.?, path, recursive, callback, updateEnd, ctx); } } diff --git a/src/bun.js/node/node_fs.zig b/src/bun.js/node/node_fs.zig index 8fb769facace4f..826fde635a39d8 100644 --- a/src/bun.js/node/node_fs.zig +++ b/src/bun.js/node/node_fs.zig @@ -55,6 +55,250 @@ const ArrayBuffer = JSC.MarkedArrayBuffer; const Buffer = JSC.Buffer; const FileSystemFlags = JSC.Node.FileSystemFlags; +pub const AsyncReaddirTask = struct { + promise: JSC.JSPromise.Strong, + args: Arguments.Readdir, + globalObject: *JSC.JSGlobalObject, + task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, + result: JSC.Maybe(Return.Readdir), + ref: JSC.PollRef = .{}, + arena: bun.ArenaAllocator, + + pub fn create(globalObject: *JSC.JSGlobalObject, readdir_args: Arguments.Readdir, vm: *JSC.VirtualMachine, arena: bun.ArenaAllocator) JSC.JSValue { + var task = bun.default_allocator.create(AsyncReaddirTask) catch @panic("out of memory"); + task.* = AsyncReaddirTask{ + .promise = JSC.JSPromise.Strong.init(globalObject), + .args = readdir_args, + .result = undefined, + .globalObject = globalObject, + .arena = arena, + }; + task.ref.ref(vm); + task.args.path.toThreadSafe(); + + JSC.WorkPool.schedule(&task.task); + + return task.promise.value(); + } + + fn workPoolCallback(task: *JSC.WorkPoolTask) void { + var this: *AsyncReaddirTask = @fieldParentPtr(AsyncReaddirTask, "task", task); + + var node_fs = NodeFS{}; + this.result = node_fs.readdir(this.args, .promise); + + this.globalObject.bunVMConcurrently().eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, runFromJSThread)); + } + + fn runFromJSThread(this: *AsyncReaddirTask) void { + var globalObject = this.globalObject; + var success = @as(JSC.Maybe(Return.Readdir).Tag, this.result) == .result; + const result = switch (this.result) { + .err => |err| err.toJSC(globalObject), + .result => |res| brk: { + var exceptionref: JSC.C.JSValueRef = null; + const out = JSC.JSValue.c(JSC.To.JS.withType(Return.Readdir, res, globalObject, &exceptionref)); + const exception = JSC.JSValue.c(exceptionref); + if (exception != .zero) { + success = false; + break :brk exception; + } + + break :brk out; + }, + }; + var promise_value = this.promise.value(); + var promise = this.promise.get(); + promise_value.ensureStillAlive(); + + this.deinit(); + switch (success) { + false => { + promise.reject(globalObject, result); + }, + true => { + promise.resolve(globalObject, result); + }, + } + } + + pub fn deinit(this: *AsyncReaddirTask) void { + this.arena.deinit(); + this.ref.unref(this.globalObject.bunVM()); + this.args.deinitAndUnprotect(); + this.promise.strong.deinit(); + bun.default_allocator.destroy(this); + } +}; + +pub const AsyncStatTask = struct { + promise: JSC.JSPromise.Strong, + args: Arguments.Stat, + globalObject: *JSC.JSGlobalObject, + task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, + result: JSC.Maybe(Return.Stat), + ref: JSC.PollRef = .{}, + is_lstat: bool = false, + arena: bun.ArenaAllocator, + + pub fn create( + globalObject: *JSC.JSGlobalObject, + readdir_args: Arguments.Stat, + vm: *JSC.VirtualMachine, + is_lstat: bool, + arena: bun.ArenaAllocator, + ) JSC.JSValue { + var task = bun.default_allocator.create(AsyncStatTask) catch @panic("out of memory"); + task.* = AsyncStatTask{ + .promise = JSC.JSPromise.Strong.init(globalObject), + .args = readdir_args, + .result = undefined, + .globalObject = globalObject, + .is_lstat = is_lstat, + .arena = arena, + }; + task.ref.ref(vm); + task.args.path.toThreadSafe(); + + JSC.WorkPool.schedule(&task.task); + + return task.promise.value(); + } + + fn workPoolCallback(task: *JSC.WorkPoolTask) void { + var this: *AsyncStatTask = @fieldParentPtr(AsyncStatTask, "task", task); + + var node_fs = NodeFS{}; + this.result = if (this.is_lstat) + node_fs.lstat(this.args, .promise) + else + node_fs.stat(this.args, .promise); + + this.globalObject.bunVMConcurrently().eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, runFromJSThread)); + } + + fn runFromJSThread(this: *AsyncStatTask) void { + var globalObject = this.globalObject; + var success = @as(JSC.Maybe(Return.Lstat).Tag, this.result) == .result; + const result = switch (this.result) { + .err => |err| err.toJSC(globalObject), + .result => |res| brk: { + var exceptionref: JSC.C.JSValueRef = null; + const out = JSC.JSValue.c(JSC.To.JS.withType(Return.Lstat, res, globalObject, &exceptionref)); + const exception = JSC.JSValue.c(exceptionref); + if (exception != .zero) { + success = false; + break :brk exception; + } + + break :brk out; + }, + }; + var promise_value = this.promise.value(); + var promise = this.promise.get(); + promise_value.ensureStillAlive(); + + this.deinit(); + switch (success) { + false => { + promise.reject(globalObject, result); + }, + true => { + promise.resolve(globalObject, result); + }, + } + } + + pub fn deinit(this: *AsyncStatTask) void { + this.arena.deinit(); + this.ref.unref(this.globalObject.bunVM()); + this.args.deinitAndUnprotect(); + this.promise.strong.deinit(); + bun.default_allocator.destroy(this); + } +}; + +pub const AsyncReadFileTask = struct { + promise: JSC.JSPromise.Strong, + args: Arguments.ReadFile, + globalObject: *JSC.JSGlobalObject, + task: JSC.WorkPoolTask = .{ .callback = &workPoolCallback }, + result: JSC.Maybe(Return.ReadFile), + ref: JSC.PollRef = .{}, + arena: bun.ArenaAllocator, + + pub fn create( + globalObject: *JSC.JSGlobalObject, + args: Arguments.ReadFile, + vm: *JSC.VirtualMachine, + arena: bun.ArenaAllocator, + ) JSC.JSValue { + var task = bun.default_allocator.create(AsyncReadFileTask) catch @panic("out of memory"); + task.* = AsyncReadFileTask{ + .promise = JSC.JSPromise.Strong.init(globalObject), + .args = args, + .result = undefined, + .globalObject = globalObject, + .arena = arena, + }; + task.ref.ref(vm); + task.args.path.toThreadSafe(); + + JSC.WorkPool.schedule(&task.task); + + return task.promise.value(); + } + + fn workPoolCallback(task: *JSC.WorkPoolTask) void { + var this: *AsyncReadFileTask = @fieldParentPtr(AsyncReadFileTask, "task", task); + + var node_fs = NodeFS{}; + this.result = node_fs.readFile(this.args, .promise); + + this.globalObject.bunVMConcurrently().eventLoop().enqueueTaskConcurrent(JSC.ConcurrentTask.fromCallback(this, runFromJSThread)); + } + + fn runFromJSThread(this: *AsyncReadFileTask) void { + var globalObject = this.globalObject; + var success = @as(JSC.Maybe(Return.ReadFile).Tag, this.result) == .result; + const result = switch (this.result) { + .err => |err| err.toJSC(globalObject), + .result => |res| brk: { + var exceptionref: JSC.C.JSValueRef = null; + const out = JSC.JSValue.c(JSC.To.JS.withType(Return.ReadFile, res, globalObject, &exceptionref)); + const exception = JSC.JSValue.c(exceptionref); + if (exception != .zero) { + success = false; + break :brk exception; + } + + break :brk out; + }, + }; + var promise_value = this.promise.value(); + var promise = this.promise.get(); + promise_value.ensureStillAlive(); + + this.deinit(); + switch (success) { + false => { + promise.reject(globalObject, result); + }, + true => { + promise.resolve(globalObject, result); + }, + } + } + + pub fn deinit(this: *AsyncReadFileTask) void { + this.ref.unref(this.globalObject.bunVM()); + this.args.deinitAndUnprotect(); + this.promise.strong.deinit(); + this.arena.deinit(); + bun.default_allocator.destroy(this); + } +}; + // TODO: to improve performance for all of these // The tagged unions for each type should become regular unions // and the tags should be passed in as comptime arguments to the functions performing the syscalls @@ -658,8 +902,12 @@ pub const Arguments = struct { this.path.deinit(); } + pub fn deinitAndUnprotect(this: Stat) void { + this.path.deinitAndUnprotect(); + } + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Stat { - const path = PathLike.fromJS(ctx, arguments, exception) orelse { + const path = PathLike.fromJSWithAllocator(ctx, arguments, bun.default_allocator, exception) orelse { if (exception.* == null) { JSC.throwInvalidArguments( "path must be a string or TypedArray", @@ -1155,8 +1403,12 @@ pub const Arguments = struct { this.path.deinit(); } + pub fn deinitAndUnprotect(this: Readdir) void { + this.path.deinitAndUnprotect(); + } + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Readdir { - const path = PathLike.fromJS(ctx, arguments, exception) orelse { + const path = PathLike.fromJSWithAllocator(ctx, arguments, bun.default_allocator, exception) orelse { if (exception.* == null) { JSC.throwInvalidArguments( "path must be a string or TypedArray", @@ -1718,8 +1970,12 @@ pub const Arguments = struct { self.path.deinit(); } + pub fn deinitAndUnprotect(self: ReadFile) void { + self.path.deinitAndUnprotect(); + } + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?ReadFile { - const path = PathOrFileDescriptor.fromJS(ctx, arguments, arguments.arena.allocator(), exception) orelse { + const path = PathOrFileDescriptor.fromJS(ctx, arguments, bun.default_allocator, exception) orelse { if (exception.* == null) { JSC.throwInvalidArguments( "path must be a string or a file descriptor", @@ -2624,11 +2880,20 @@ const Return = struct { }; pub fn toJS(this: Readdir, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { - return switch (this) { - .with_file_types => JSC.To.JS.withType([]const Dirent, this.with_file_types, ctx, exception), - .buffers => JSC.To.JS.withType([]const Buffer, this.buffers, ctx, exception), - .files => JSC.To.JS.withType([]const bun.String, this.files, ctx, exception), - }; + switch (this) { + .with_file_types => { + defer bun.default_allocator.free(this.with_file_types); + return JSC.To.JS.withType([]const Dirent, this.with_file_types, ctx, exception); + }, + .buffers => { + defer bun.default_allocator.free(this.buffers); + return JSC.To.JS.withType([]const Buffer, this.buffers, ctx, exception); + }, + .files => { + // automatically freed + return JSC.To.JS.withType([]const bun.String, this.files, ctx, exception); + }, + } } }; pub const ReadFile = JSC.Node.StringOrNodeBuffer; @@ -3145,28 +3410,22 @@ pub const NodeFS = struct { return Maybe(Return.Link).todo; } pub fn lstat(this: *NodeFS, args: Arguments.Lstat, comptime flavor: Flavor) Maybe(Return.Lstat) { + _ = flavor; if (args.big_int) return Maybe(Return.Lstat).todo; - switch (comptime flavor) { - .sync => { - return switch (Syscall.lstat( - args.path.sliceZ( - &this.sync_error_buf, - ), - )) { - .result => |result| Maybe(Return.Lstat){ .result = .{ .stats = Stats.init(result, args.big_int) } }, - .err => |err| brk: { - if (!args.throw_if_no_entry and err.getErrno() == .NOENT) { - return Maybe(Return.Lstat){ .result = .{ .not_found = {} } }; - } - break :brk Maybe(Return.Lstat){ .err = err }; - }, - }; + return switch (Syscall.lstat( + args.path.sliceZ( + &this.sync_error_buf, + ), + )) { + .result => |result| Maybe(Return.Lstat){ .result = .{ .stats = Stats.init(result, args.big_int) } }, + .err => |err| brk: { + if (!args.throw_if_no_entry and err.getErrno() == .NOENT) { + return Maybe(Return.Lstat){ .result = .{ .not_found = {} } }; + } + break :brk Maybe(Return.Lstat){ .err = err }; }, - else => {}, - } - - return Maybe(Return.Lstat).todo; + }; } pub fn mkdir(this: *NodeFS, args: Arguments.Mkdir, comptime flavor: Flavor) Maybe(Return.Mkdir) { @@ -3575,7 +3834,7 @@ pub const NodeFS = struct { pub fn readdir(this: *NodeFS, args: Arguments.Readdir, comptime flavor: Flavor) Maybe(Return.Readdir) { return switch (args.encoding) { .buffer => _readdir( - this, + &this.sync_error_buf, args, Buffer, flavor, @@ -3583,7 +3842,7 @@ pub const NodeFS = struct { else => { if (!args.with_file_types) { return _readdir( - this, + &this.sync_error_buf, args, bun.String, flavor, @@ -3591,7 +3850,7 @@ pub const NodeFS = struct { } return _readdir( - this, + &this.sync_error_buf, args, Dirent, flavor, @@ -3601,10 +3860,10 @@ pub const NodeFS = struct { } pub fn _readdir( - this: *NodeFS, + buf: *[bun.MAX_PATH_BYTES]u8, args: Arguments.Readdir, comptime ExpectedType: type, - comptime flavor: Flavor, + comptime _: Flavor, ) Maybe(Return.Readdir) { const file_type = comptime switch (ExpectedType) { Dirent => "with_file_types", @@ -3613,73 +3872,66 @@ pub const NodeFS = struct { else => unreachable, }; - switch (comptime flavor) { - .sync => { - var path = args.path.sliceZ(&this.sync_error_buf); - const flags = os.O.DIRECTORY | os.O.RDONLY; - const fd = switch (Syscall.open(path, flags, 0)) { - .err => |err| return .{ - .err = err.withPath(args.path.slice()), - }, - .result => |fd_| fd_, - }; - defer { - _ = Syscall.close(fd); - } - - var entries = std.ArrayList(ExpectedType).init(bun.default_allocator); - var dir = std.fs.Dir{ .fd = fd }; - var iterator = DirIterator.iterate(dir); - var entry = iterator.next(); - while (switch (entry) { - .err => |err| { - for (entries.items) |*item| { - switch (comptime ExpectedType) { - Dirent => { - item.name.deref(); - }, - Buffer => { - item.destroy(); - }, - bun.String => { - item.deref(); - }, - else => unreachable, - } - } - - entries.deinit(); + var path = args.path.sliceZ(buf); + const flags = os.O.DIRECTORY | os.O.RDONLY; + const fd = switch (Syscall.open(path, flags, 0)) { + .err => |err| return .{ + .err = err.withPath(args.path.slice()), + }, + .result => |fd_| fd_, + }; + defer { + _ = Syscall.close(fd); + } - return .{ - .err = err.withPath(args.path.slice()), - }; - }, - .result => |ent| ent, - }) |current| : (entry = iterator.next()) { - const utf8_name = current.name.slice(); + var entries = std.ArrayList(ExpectedType).init(bun.default_allocator); + var dir = std.fs.Dir{ .fd = fd }; + var iterator = DirIterator.iterate(dir); + var entry = iterator.next(); + while (switch (entry) { + .err => |err| { + for (entries.items) |*item| { switch (comptime ExpectedType) { Dirent => { - entries.append(.{ - .name = bun.String.create(utf8_name), - .kind = current.kind, - }) catch unreachable; + item.name.deref(); }, Buffer => { - entries.append(Buffer.fromString(utf8_name, bun.default_allocator) catch unreachable) catch unreachable; + item.destroy(); }, bun.String => { - entries.append(bun.String.create(utf8_name)) catch unreachable; + item.deref(); }, else => unreachable, } } - return .{ .result = @unionInit(Return.Readdir, file_type, entries.items) }; + entries.deinit(); + + return .{ + .err = err.withPath(args.path.slice()), + }; }, - else => {}, + .result => |ent| ent, + }) |current| : (entry = iterator.next()) { + const utf8_name = current.name.slice(); + switch (comptime ExpectedType) { + Dirent => { + entries.append(.{ + .name = bun.String.create(utf8_name), + .kind = current.kind, + }) catch unreachable; + }, + Buffer => { + entries.append(Buffer.fromString(utf8_name, bun.default_allocator) catch unreachable) catch unreachable; + }, + bun.String => { + entries.append(bun.String.create(utf8_name)) catch unreachable; + }, + else => unreachable, + } } - return Maybe(Return.Readdir).todo; + return .{ .result = @unionInit(Return.Readdir, file_type, entries.items) }; } pub const StringType = enum { @@ -3707,193 +3959,186 @@ pub const NodeFS = struct { }; } - pub fn readFileWithOptions(this: *NodeFS, args: Arguments.ReadFile, comptime flavor: Flavor, comptime string_type: StringType) Maybe(Return.ReadFileWithOptions) { + pub fn readFileWithOptions(this: *NodeFS, args: Arguments.ReadFile, comptime _: Flavor, comptime string_type: StringType) Maybe(Return.ReadFileWithOptions) { var path: [:0]const u8 = undefined; - switch (comptime flavor) { - .sync => { - const fd = switch (args.path) { - .path => brk: { - path = args.path.path.sliceZ(&this.sync_error_buf); - if (this.vm) |vm| { - if (vm.standalone_module_graph) |graph| { - if (graph.find(path)) |file| { - if (args.encoding == .buffer) { - return .{ - .result = .{ - .buffer = Buffer.fromBytes( - bun.default_allocator.dupe(u8, file.contents) catch @panic("out of memory"), - bun.default_allocator, - .Uint8Array, - ), - }, - }; - } else if (comptime string_type == .default) - return .{ - .result = .{ - .string = bun.default_allocator.dupe(u8, file.contents) catch @panic("out of memory"), - }, - } - else - return .{ - .result = .{ - .null_terminated = bun.default_allocator.dupeZ(u8, file.contents) catch @panic("out of memory"), - }, - }; + const fd = switch (args.path) { + .path => brk: { + path = args.path.path.sliceZ(&this.sync_error_buf); + if (this.vm) |vm| { + if (vm.standalone_module_graph) |graph| { + if (graph.find(path)) |file| { + if (args.encoding == .buffer) { + return .{ + .result = .{ + .buffer = Buffer.fromBytes( + bun.default_allocator.dupe(u8, file.contents) catch @panic("out of memory"), + bun.default_allocator, + .Uint8Array, + ), + }, + }; + } else if (comptime string_type == .default) + return .{ + .result = .{ + .string = bun.default_allocator.dupe(u8, file.contents) catch @panic("out of memory"), + }, } - } + else + return .{ + .result = .{ + .null_terminated = bun.default_allocator.dupeZ(u8, file.contents) catch @panic("out of memory"), + }, + }; } - - break :brk switch (Syscall.open( - path, - os.O.RDONLY | os.O.NOCTTY, - 0, - )) { - .err => |err| return .{ - .err = err.withPath(if (args.path == .path) args.path.path.slice() else ""), - }, - .result => |fd_| fd_, - }; - }, - .fd => |_fd| _fd, - }; - - defer { - if (args.path == .path) - _ = Syscall.close(fd); + } } - const stat_ = switch (Syscall.fstat(fd)) { + break :brk switch (Syscall.open( + path, + os.O.RDONLY | os.O.NOCTTY, + 0, + )) { .err => |err| return .{ - .err = err, + .err = err.withPath(if (args.path == .path) args.path.path.slice() else ""), }, - .result => |stat_| stat_, + .result => |fd_| fd_, }; + }, + .fd => |_fd| _fd, + }; - // Only used in DOMFormData - if (args.offset > 0) { - std.os.lseek_SET(fd, args.offset) catch {}; - } + defer { + if (args.path == .path) + _ = Syscall.close(fd); + } - // For certain files, the size might be 0 but the file might still have contents. - const size = @as( - u64, - @intCast(@max( - @min( - stat_.size, - @as( - @TypeOf(stat_.size), - // Only used in DOMFormData - @intCast(args.max_size orelse std.math.maxInt( - JSC.WebCore.Blob.SizeType, - )), - ), - ), - 0, - )), - ) + if (comptime string_type == .null_terminated) 1 else 0; - - var buf = std.ArrayList(u8).init(bun.default_allocator); - buf.ensureTotalCapacityPrecise(size + 16) catch unreachable; - buf.expandToCapacity(); - var total: usize = 0; - - while (total < size) { - switch (Syscall.read(fd, buf.items.ptr[total..buf.capacity])) { - .err => |err| return .{ - .err = err, - }, - .result => |amt| { - total += amt; - // There are cases where stat()'s size is wrong or out of date - if (total > size and amt != 0) { - buf.ensureUnusedCapacity(8096) catch unreachable; - buf.expandToCapacity(); - continue; - } + const stat_ = switch (Syscall.fstat(fd)) { + .err => |err| return .{ + .err = err, + }, + .result => |stat_| stat_, + }; - if (amt == 0) { - break; - } - }, + // Only used in DOMFormData + if (args.offset > 0) { + std.os.lseek_SET(fd, args.offset) catch {}; + } + + // For certain files, the size might be 0 but the file might still have contents. + const size = @as( + u64, + @intCast(@max( + @min( + stat_.size, + @as( + @TypeOf(stat_.size), + // Only used in DOMFormData + @intCast(args.max_size orelse std.math.maxInt( + JSC.WebCore.Blob.SizeType, + )), + ), + ), + 0, + )), + ) + if (comptime string_type == .null_terminated) 1 else 0; + + var buf = std.ArrayList(u8).init(bun.default_allocator); + buf.ensureTotalCapacityPrecise(size + 16) catch unreachable; + buf.expandToCapacity(); + var total: usize = 0; + + while (total < size) { + switch (Syscall.read(fd, buf.items.ptr[total..buf.capacity])) { + .err => |err| return .{ + .err = err, + }, + .result => |amt| { + total += amt; + // There are cases where stat()'s size is wrong or out of date + if (total > size and amt != 0) { + buf.ensureUnusedCapacity(8096) catch unreachable; + buf.expandToCapacity(); + continue; } - } else { - // https://github.com/oven-sh/bun/issues/1220 - while (true) { - switch (Syscall.read(fd, buf.items.ptr[total..buf.capacity])) { - .err => |err| return .{ - .err = err, - }, - .result => |amt| { - total += amt; - // There are cases where stat()'s size is wrong or out of date - if (total > size and amt != 0) { - buf.ensureUnusedCapacity(8096) catch unreachable; - buf.expandToCapacity(); - continue; - } - if (amt == 0) { - break; - } - }, - } + if (amt == 0) { + break; } + }, + } + } else { + // https://github.com/oven-sh/bun/issues/1220 + while (true) { + switch (Syscall.read(fd, buf.items.ptr[total..buf.capacity])) { + .err => |err| return .{ + .err = err, + }, + .result => |amt| { + total += amt; + // There are cases where stat()'s size is wrong or out of date + if (total > size and amt != 0) { + buf.ensureUnusedCapacity(8096) catch unreachable; + buf.expandToCapacity(); + continue; + } + + if (amt == 0) { + break; + } + }, } + } + } - buf.items.len = if (comptime string_type == .null_terminated) total + 1 else total; - if (total == 0) { - buf.deinit(); - return switch (args.encoding) { - .buffer => .{ + buf.items.len = if (comptime string_type == .null_terminated) total + 1 else total; + if (total == 0) { + buf.deinit(); + return switch (args.encoding) { + .buffer => .{ + .result = .{ + .buffer = Buffer.empty, + }, + }, + else => brk: { + if (comptime string_type == .default) { + break :brk .{ .result = .{ - .buffer = Buffer.empty, + .string = "", }, - }, - else => brk: { - if (comptime string_type == .default) { - break :brk .{ - .result = .{ - .string = "", - }, - }; - } else { - break :brk .{ - .result = .{ - .null_terminated = "", - }, - }; - } + }; + } else { + break :brk .{ + .result = .{ + .null_terminated = "", + }, + }; + } + }, + }; + } + + return switch (args.encoding) { + .buffer => .{ + .result = .{ + .buffer = Buffer.fromBytes(buf.items, bun.default_allocator, .Uint8Array), + }, + }, + else => brk: { + if (comptime string_type == .default) { + break :brk .{ + .result = .{ + .string = buf.items, }, }; - } - - return switch (args.encoding) { - .buffer => .{ + } else { + break :brk .{ .result = .{ - .buffer = Buffer.fromBytes(buf.items, bun.default_allocator, .Uint8Array), + .null_terminated = buf.toOwnedSliceSentinel(0) catch unreachable, }, - }, - else => brk: { - if (comptime string_type == .default) { - break :brk .{ - .result = .{ - .string = buf.items, - }, - }; - } else { - break :brk .{ - .result = .{ - .null_terminated = buf.toOwnedSliceSentinel(0) catch unreachable, - }, - }; - } - }, - }; + }; + } }, - else => {}, - } - - return Maybe(Return.ReadFile).todo; + }; } pub fn writeFileWithPathBuffer(pathbuf: *[bun.MAX_PATH_BYTES]u8, args: Arguments.WriteFile) Maybe(Return.WriteFile) { @@ -4354,28 +4599,22 @@ pub const NodeFS = struct { return Maybe(Return.Rm).todo; } pub fn stat(this: *NodeFS, args: Arguments.Stat, comptime flavor: Flavor) Maybe(Return.Stat) { + _ = flavor; if (args.big_int) return Maybe(Return.Stat).todo; - switch (comptime flavor) { - .sync => { - return @as(Maybe(Return.Stat), switch (Syscall.stat( - args.path.sliceZ( - &this.sync_error_buf, - ), - )) { - .result => |result| Maybe(Return.Stat){ .result = .{ .stats = Stats.init(result, args.big_int) } }, - .err => |err| brk: { - if (!args.throw_if_no_entry and err.getErrno() == .NOENT) { - return Maybe(Return.Stat){ .result = .{ .not_found = {} } }; - } - break :brk Maybe(Return.Stat){ .err = err }; - }, - }); + return @as(Maybe(Return.Stat), switch (Syscall.stat( + args.path.sliceZ( + &this.sync_error_buf, + ), + )) { + .result => |result| Maybe(Return.Stat){ .result = .{ .stats = Stats.init(result, args.big_int) } }, + .err => |err| brk: { + if (!args.throw_if_no_entry and err.getErrno() == .NOENT) { + return Maybe(Return.Stat){ .result = .{ .not_found = {} } }; + } + break :brk Maybe(Return.Stat){ .err = err }; }, - else => {}, - } - - return Maybe(Return.Stat).todo; + }); } pub fn symlink(this: *NodeFS, args: Arguments.Symlink, comptime flavor: Flavor) Maybe(Return.Symlink) { @@ -4488,8 +4727,13 @@ pub const NodeFS = struct { } pub fn watch(_: *NodeFS, args: Arguments.Watch, comptime _: Flavor) Maybe(Return.Watch) { const watcher = args.createFSWatcher() catch |err| { - args.global_this.throwError(err, "Failed to watch filename"); - return Maybe(Return.Watch){ .result = JSC.JSValue.jsUndefined() }; + var buf = std.fmt.allocPrint(bun.default_allocator, "{s} watching {}", .{ @errorName(err), strings.QuotedFormatter{ .text = args.path.slice() } }) catch unreachable; + defer bun.default_allocator.free(buf); + args.global_this.throwValue((JSC.SystemError{ + .message = bun.String.init(buf), + .path = bun.String.init(args.path.slice()), + }).toErrorInstance(args.global_this)); + return Maybe(Return.Watch){ .result = JSC.JSValue.undefined }; }; return Maybe(Return.Watch){ .result = watcher }; } diff --git a/src/bun.js/node/node_fs_binding.zig b/src/bun.js/node/node_fs_binding.zig index a4cc62cd34e4e2..b7ce9996ca74c7 100644 --- a/src/bun.js/node/node_fs_binding.zig +++ b/src/bun.js/node/node_fs_binding.zig @@ -95,25 +95,61 @@ fn callSync(comptime FunctionEnum: NodeFSFunctionEnum) NodeFSFunction { return NodeBindingClosure.bind; } -fn call(comptime Function: NodeFSFunctionEnum) NodeFSFunction { - // const FunctionType = @TypeOf(Function); - _ = Function; - - // const function: std.builtin.Type.Fn = comptime @typeInfo(FunctionType).Fn; - // comptime if (function.args.len != 3) @compileError("Expected 3 arguments"); - // const Arguments = comptime function.args[2].type orelse @compileError(std.fmt.comptimePrint("Function {s} expected to have an arg type at [2]", .{@typeName(FunctionType)})); - // const Result = comptime function.return_type.?; - // comptime if (Arguments != void and !fromJSTrait(Arguments)) @compileError(std.fmt.comptimePrint("{s} is missing fromJS()", .{@typeName(Arguments)})); - // comptime if (Result != void and !toJSTrait(Result)) @compileError(std.fmt.comptimePrint("{s} is missing toJS()", .{@typeName(Result)})); +fn call(comptime FunctionEnum: NodeFSFunctionEnum) NodeFSFunction { + const Function = @field(JSC.Node.NodeFS, @tagName(FunctionEnum)); + const FunctionType = @TypeOf(Function); + + const function: std.builtin.Type.Fn = comptime @typeInfo(FunctionType).Fn; + comptime if (function.params.len != 3) @compileError("Expected 3 arguments"); + const Arguments = comptime function.params[1].type.?; const NodeBindingClosure = struct { pub fn bind( _: *JSC.Node.NodeJSFS, globalObject: *JSC.JSGlobalObject, - _: *JSC.CallFrame, + callframe: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { - globalObject.throw("Not implemented yet", .{}); - return .zero; - // var slice = ArgumentsSlice.init(arguments); + if (comptime FunctionEnum != .readdir and FunctionEnum != .lstat and FunctionEnum != .stat and FunctionEnum != .readFile) { + globalObject.throw("Not implemented yet", .{}); + return .zero; + } + + var arguments = callframe.arguments(8); + + var slice = ArgumentsSlice.init(globalObject.bunVM(), arguments.ptr[0..arguments.len]); + var exceptionref: JSC.C.JSValueRef = null; + const args = if (comptime Arguments != void) + (Arguments.fromJS(globalObject, &slice, &exceptionref) orelse { + // we might've already thrown + if (exceptionref != null) + globalObject.throwValue(JSC.JSValue.c(exceptionref)); + slice.deinit(); + return .zero; + }) + else + Arguments{}; + + const exception1 = JSC.JSValue.c(exceptionref); + + if (exception1 != .zero) { + globalObject.throwValue(exception1); + + slice.deinit(); + return .zero; + } + + // TODO: handle globalObject.throwValue + + if (comptime FunctionEnum == .readdir) { + return JSC.Node.AsyncReaddirTask.create(globalObject, args, slice.vm, slice.arena); + } + + if (comptime FunctionEnum == .readFile) { + return JSC.Node.AsyncReadFileTask.create(globalObject, args, slice.vm, slice.arena); + } + + if (comptime FunctionEnum == .stat or FunctionEnum == .lstat) { + return JSC.Node.AsyncStatTask.create(globalObject, args, slice.vm, FunctionEnum == .lstat, slice.arena); + } // defer { // for (arguments.len) |arg| { diff --git a/src/bun.js/node/node_fs_constant.zig b/src/bun.js/node/node_fs_constant.zig index 8e642ebad167c4..0d8ec66c5d7f5d 100644 --- a/src/bun.js/node/node_fs_constant.zig +++ b/src/bun.js/node/node_fs_constant.zig @@ -146,8 +146,7 @@ pub const Constants = struct { // Due to zig's format support max 32 arguments, we need to split // here. const constants_string_format1 = - \\ - \\export var constants = {{ + \\var constants = {{ \\ F_OK: {d}, \\ R_OK: {d}, \\ W_OK: {d}, diff --git a/src/bun.js/node/node_fs_watcher.zig b/src/bun.js/node/node_fs_watcher.zig index d0af350c0d70f2..d6d2f8a2fb27ab 100644 --- a/src/bun.js/node/node_fs_watcher.zig +++ b/src/bun.js/node/node_fs_watcher.zig @@ -6,7 +6,7 @@ const Path = @import("../../resolver/resolve_path.zig"); const Encoder = JSC.WebCore.Encoder; const Mutex = @import("../../lock.zig").Lock; -const FSEvents = @import("./fs_events.zig"); +const PathWatcher = @import("./path_watcher.zig"); const VirtualMachine = JSC.VirtualMachine; const EventLoop = JSC.EventLoop; @@ -18,31 +18,14 @@ const StoredFileDescriptorType = bun.StoredFileDescriptorType; const Environment = bun.Environment; pub const FSWatcher = struct { - const watcher = @import("../../watcher.zig"); - const options = @import("../../options.zig"); - pub const Watcher = watcher.NewWatcher(*FSWatcher); - const log = Output.scoped(.FSWatcher, false); - - pub const ChangeEvent = struct { - hash: Watcher.HashType = 0, - event_type: FSWatchTask.EventType = .change, - time_stamp: i64 = 0, - }; - - onAccept: std.ArrayHashMapUnmanaged(FSWatcher.Watcher.HashType, bun.BabyList(OnAcceptCallback), bun.ArrayIdentityContext, false) = .{}, ctx: *VirtualMachine, verbose: bool = false, - file_paths: bun.BabyList(string) = .{}, - entry_path: ?string = null, - entry_dir: string = "", - last_change_event: ChangeEvent = .{}, // JSObject mutex: Mutex, signal: ?*JSC.AbortSignal, persistent: bool, - default_watcher: ?*FSWatcher.Watcher, - fsevents_watcher: ?*FSEvents.FSEventsWatcher, + path_watcher: ?*PathWatcher.PathWatcher, poll_ref: JSC.PollRef = .{}, globalThis: *JSC.JSGlobalObject, js_this: JSC.JSValue, @@ -52,6 +35,7 @@ pub const FSWatcher = struct { // counts pending tasks so we only deinit after all tasks are done task_count: u32, has_pending_activity: std.atomic.Atomic(bool), + current_task: FSWatchTask = undefined, pub usingnamespace JSC.Codegen.JSFSWatcher; pub fn eventLoop(this: FSWatcher) *EventLoop { @@ -65,15 +49,6 @@ pub const FSWatcher = struct { pub fn deinit(this: *FSWatcher) void { // stop all managers and signals this.detach(); - - while (this.file_paths.popOrNull()) |file_path| { - bun.default_allocator.destroy(file_path); - } - this.file_paths.deinitWithAllocator(bun.default_allocator); - if (this.entry_path) |path| { - this.entry_path = null; - bun.default_allocator.destroy(path); - } bun.default_allocator.destroy(this); } @@ -91,19 +66,13 @@ pub const FSWatcher = struct { abort, }; - pub const EventFreeType = enum { - destroy, - free, - none, - }; - pub const Entry = struct { file_path: string, event_type: EventType, - free_type: EventFreeType, + needs_free: bool, }; - pub fn append(this: *FSWatchTask, file_path: string, event_type: EventType, free_type: EventFreeType) void { + pub fn append(this: *FSWatchTask, file_path: string, event_type: EventType, needs_free: bool) void { if (this.count == 8) { this.enqueue(); var ctx = this.ctx; @@ -116,7 +85,7 @@ pub const FSWatcher = struct { this.entries[this.count] = .{ .file_path = file_path, .event_type = event_type, - .free_type = free_type, + .needs_free = needs_free, }; this.count += 1; } @@ -163,14 +132,12 @@ pub const FSWatcher = struct { this.cleanEntries(); } pub fn cleanEntries(this: *FSWatchTask) void { - while (this.count > 0) { - this.count -= 1; - switch (this.entries[this.count].free_type) { - .destroy => bun.default_allocator.destroy(this.entries[this.count].file_path), - .free => bun.default_allocator.free(this.entries[this.count].file_path), - else => {}, + for (this.entries[0..this.count]) |entry| { + if (entry.needs_free) { + bun.default_allocator.free(entry.file_path); } } + this.count = 0; } pub fn deinit(this: *FSWatchTask) void { @@ -179,241 +146,39 @@ pub const FSWatcher = struct { } }; - fn NewCallback(comptime FunctionSignature: type) type { - return union(enum) { - javascript_callback: JSC.Strong, - zig_callback: struct { - ptr: *anyopaque, - function: *const FunctionSignature, - }, - }; - } - - pub const OnAcceptCallback = NewCallback(fn ( - vm: *JSC.VirtualMachine, - specifier: []const u8, - ) void); - - fn addDirectory(ctx: *FSWatcher, fs_watcher: *FSWatcher.Watcher, fd: StoredFileDescriptorType, file_path: string, recursive: bool, buf: *[bun.MAX_PATH_BYTES + 1]u8, is_entry_path: bool) !void { - var dir_path_clone = bun.default_allocator.dupeZ(u8, file_path) catch unreachable; - - if (is_entry_path) { - ctx.entry_path = dir_path_clone; - ctx.entry_dir = dir_path_clone; - } else { - ctx.file_paths.push(bun.default_allocator, dir_path_clone) catch unreachable; - } - fs_watcher.addDirectory(fd, dir_path_clone, FSWatcher.Watcher.getHash(file_path), false) catch |err| { - ctx.deinit(); - fs_watcher.deinit(true); - return err; - }; - - var iter = (std.fs.IterableDir{ .dir = std.fs.Dir{ - .fd = fd, - } }).iterate(); - - while (iter.next() catch |err| { - ctx.deinit(); - fs_watcher.deinit(true); - return err; - }) |entry| { - var parts = [2]string{ dir_path_clone, entry.name }; - var entry_path = Path.joinAbsStringBuf( - Fs.FileSystem.instance.topLevelDirWithoutTrailingSlash(), - buf, - &parts, - .auto, - ); - - buf[entry_path.len] = 0; - var entry_path_z = buf[0..entry_path.len :0]; - - var fs_info = fdFromAbsolutePathZ(entry_path_z) catch |err| { - ctx.deinit(); - fs_watcher.deinit(true); - return err; - }; - - if (fs_info.is_file) { - const file_path_clone = bun.default_allocator.dupeZ(u8, entry_path) catch unreachable; + pub fn onPathUpdate(ctx: ?*anyopaque, path: string, is_file: bool, event_type: PathWatcher.PathWatcher.EventType) void { + const this = bun.cast(*FSWatcher, ctx.?); - ctx.file_paths.push(bun.default_allocator, file_path_clone) catch unreachable; + const relative_path = bun.default_allocator.dupe(u8, path) catch unreachable; - fs_watcher.addFile(fs_info.fd, file_path_clone, FSWatcher.Watcher.getHash(entry_path), options.Loader.file, 0, null, false) catch |err| { - ctx.deinit(); - fs_watcher.deinit(true); - return err; - }; + if (this.verbose and event_type != .@"error") { + if (is_file) { + Output.prettyErrorln(" File changed: {s}", .{relative_path}); } else { - if (recursive) { - addDirectory(ctx, fs_watcher, fs_info.fd, entry_path, recursive, buf, false) catch |err| { - ctx.deinit(); - fs_watcher.deinit(true); - return err; - }; - } + Output.prettyErrorln(" Dir changed: {s}", .{relative_path}); } } - } - pub fn onError( - this: *FSWatcher, - err: anyerror, - ) void { - var current_task: FSWatchTask = .{ - .ctx = this, - }; - current_task.append(@errorName(err), .@"error", .none); - current_task.enqueue(); + switch (event_type) { + .rename => { + this.current_task.append(relative_path, .rename, true); + }, + .change => { + this.current_task.append(relative_path, .change, true); + }, + else => { + this.current_task.append(relative_path, .@"error", true); + }, + } } - pub fn onFSEventUpdate( - ctx: ?*anyopaque, - path: string, - _: bool, - is_rename: bool, - ) void { + pub fn onUpdateEnd(ctx: ?*anyopaque) void { const this = bun.cast(*FSWatcher, ctx.?); - - var current_task: FSWatchTask = .{ - .ctx = this, - }; - defer current_task.enqueue(); - - const relative_path = bun.default_allocator.dupe(u8, path) catch unreachable; - const event_type: FSWatchTask.EventType = if (is_rename) .rename else .change; - - current_task.append(relative_path, event_type, .destroy); - } - - pub fn onFileUpdate( - this: *FSWatcher, - events: []watcher.WatchEvent, - changed_files: []?[:0]u8, - watchlist: watcher.Watchlist, - ) void { - var slice = watchlist.slice(); - const file_paths = slice.items(.file_path); - - var counts = slice.items(.count); - const kinds = slice.items(.kind); - var _on_file_update_path_buf: [bun.MAX_PATH_BYTES]u8 = undefined; - - var ctx = this.default_watcher.?; - defer ctx.flushEvictions(); - defer Output.flush(); - - var bundler = if (@TypeOf(this.ctx.bundler) == *bun.Bundler) - this.ctx.bundler - else - &this.ctx.bundler; - - var fs: *Fs.FileSystem = bundler.fs; - - var current_task: FSWatchTask = .{ - .ctx = this, - }; - defer current_task.enqueue(); - - const time_stamp = std.time.milliTimestamp(); - const time_diff = time_stamp - this.last_change_event.time_stamp; - - for (events) |event| { - const file_path = file_paths[event.index]; - const update_count = counts[event.index] + 1; - counts[event.index] = update_count; - const kind = kinds[event.index]; - - if (comptime Environment.isDebug) { - if (this.verbose) { - Output.prettyErrorln("[watch] {s} ({s}, {})", .{ file_path, @tagName(kind), event.op }); - } - } - - switch (kind) { - .file => { - if (event.op.delete) { - ctx.removeAtIndex( - event.index, - 0, - &.{}, - .file, - ); - } - - var file_hash: FSWatcher.Watcher.HashType = FSWatcher.Watcher.getHash(file_path); - - if (event.op.write or event.op.delete or event.op.rename) { - const event_type: FSWatchTask.EventType = if (event.op.delete or event.op.rename or event.op.move_to) .rename else .change; - // skip consecutive duplicates - if ((this.last_change_event.time_stamp == 0 or time_diff > 1) or this.last_change_event.event_type != event_type and this.last_change_event.hash != file_hash) { - this.last_change_event.time_stamp = time_stamp; - this.last_change_event.event_type = event_type; - this.last_change_event.hash = file_hash; - - const relative_slice = fs.relative(this.entry_dir, file_path); - - if (this.verbose) - Output.prettyErrorln("File changed: {s}", .{relative_slice}); - - const relative_path = bun.default_allocator.dupe(u8, relative_slice) catch unreachable; - - current_task.append(relative_path, event_type, .destroy); - } - } - }, - .directory => { - // macOS should use FSEvents for directories - if (comptime Environment.isMac) { - @panic("Unexpected directory watch"); - } - - const affected = event.names(changed_files); - - for (affected) |changed_name_| { - const changed_name: []const u8 = bun.asByteSlice(changed_name_.?); - if (changed_name.len == 0 or changed_name[0] == '~' or changed_name[0] == '.') continue; - - var file_hash: FSWatcher.Watcher.HashType = 0; - const relative_slice: string = brk: { - var file_path_without_trailing_slash = std.mem.trimRight(u8, file_path, std.fs.path.sep_str); - - @memcpy(_on_file_update_path_buf[0..file_path_without_trailing_slash.len], file_path_without_trailing_slash); - - _on_file_update_path_buf[file_path_without_trailing_slash.len] = std.fs.path.sep; - - @memcpy(_on_file_update_path_buf[file_path_without_trailing_slash.len + 1 ..][0..changed_name.len], changed_name); - const path_slice = _on_file_update_path_buf[0 .. file_path_without_trailing_slash.len + changed_name.len + 1]; - file_hash = FSWatcher.Watcher.getHash(path_slice); - - const relative = fs.relative(this.entry_dir, path_slice); - - break :brk relative; - }; - - // skip consecutive duplicates - const event_type: FSWatchTask.EventType = .rename; // renaming folders, creating folder or files will be always be rename - if ((this.last_change_event.time_stamp == 0 or time_diff > 1) or this.last_change_event.event_type != event_type and this.last_change_event.hash != file_hash) { - const relative_path = bun.default_allocator.dupe(u8, relative_slice) catch unreachable; - - this.last_change_event.time_stamp = time_stamp; - this.last_change_event.event_type = event_type; - this.last_change_event.hash = file_hash; - - current_task.append(relative_path, event_type, .destroy); - - if (this.verbose) - Output.prettyErrorln(" Dir change: {s}", .{relative_path}); - } - } - - if (this.verbose and affected.len == 0) { - Output.prettyErrorln(" Dir change: {s}", .{fs.relative(this.entry_dir, file_path)}); - } - }, - } + if (this.verbose) { + Output.flush(); } + // we only enqueue after all events are processed + this.current_task.enqueue(); } pub const Arguments = struct { @@ -589,7 +354,7 @@ pub const FSWatcher = struct { var current_task: FSWatchTask = .{ .ctx = this, }; - current_task.append("", .abort, .none); + current_task.append("", .abort, false); current_task.enqueue(); } else { // watch for abortion @@ -753,26 +518,20 @@ pub const FSWatcher = struct { // this can be called multiple times pub fn detach(this: *FSWatcher) void { - if (this.persistent) { - this.persistent = false; - this.poll_ref.unref(this.ctx); - } - if (this.signal) |signal| { this.signal = null; signal.detach(this); } - if (this.default_watcher) |default_watcher| { - this.default_watcher = null; - default_watcher.deinit(true); + if (this.path_watcher) |path_watcher| { + this.path_watcher = null; + path_watcher.deinit(); } - if (this.fsevents_watcher) |fsevents_watcher| { - this.fsevents_watcher = null; - fsevents_watcher.deinit(); + if (this.persistent) { + this.persistent = false; + this.poll_ref.unref(this.ctx); } - this.js_this = .zero; } @@ -785,41 +544,6 @@ pub const FSWatcher = struct { this.deinit(); } - const PathResult = struct { - fd: StoredFileDescriptorType = 0, - is_file: bool = true, - }; - - fn fdFromAbsolutePathZ( - absolute_path_z: [:0]const u8, - ) !PathResult { - var stat = try bun.C.lstat_absolute(absolute_path_z); - var result = PathResult{}; - - switch (stat.kind) { - .sym_link => { - var file = try std.fs.openFileAbsoluteZ(absolute_path_z, .{ .mode = .read_only }); - result.fd = file.handle; - const _stat = try file.stat(); - - result.is_file = _stat.kind != .directory; - }, - .directory => { - const dir = (try std.fs.openIterableDirAbsoluteZ(absolute_path_z, .{ - .access_sub_paths = true, - })).dir; - result.fd = dir.fd; - result.is_file = false; - }, - else => { - const file = try std.fs.openFileAbsoluteZ(absolute_path_z, .{ .mode = .read_only }); - result.fd = file.handle; - result.is_file = true; - }, - } - return result; - } - pub fn init(args: Arguments) !*FSWatcher { var buf: [bun.MAX_PATH_BYTES + 1]u8 = undefined; var slice = args.path.slice(); @@ -840,17 +564,18 @@ pub const FSWatcher = struct { buf[file_path.len] = 0; var file_path_z = buf[0..file_path.len :0]; - var fs_type = try fdFromAbsolutePathZ(file_path_z); - var ctx = try bun.default_allocator.create(FSWatcher); const vm = args.global_this.bunVM(); ctx.* = .{ .ctx = vm, + .current_task = .{ + .ctx = ctx, + .count = 0, + }, .mutex = Mutex.init(), .signal = if (args.signal) |s| s.ref() else null, .persistent = args.persistent, - .default_watcher = null, - .fsevents_watcher = null, + .path_watcher = null, .globalThis = args.global_this, .js_this = .zero, .encoding = args.encoding, @@ -858,61 +583,11 @@ pub const FSWatcher = struct { .task_count = 0, .has_pending_activity = std.atomic.Atomic(bool).init(true), .verbose = args.verbose, - .file_paths = bun.BabyList(string).initCapacity(bun.default_allocator, 1) catch |err| { - ctx.deinit(); - return err; - }, - }; - - if (comptime Environment.isMac) { - if (!fs_type.is_file) { - var dir_path_clone = bun.default_allocator.dupeZ(u8, file_path) catch unreachable; - ctx.entry_path = dir_path_clone; - ctx.entry_dir = dir_path_clone; - - ctx.fsevents_watcher = FSEvents.watch(dir_path_clone, args.recursive, onFSEventUpdate, bun.cast(*anyopaque, ctx)) catch |err| { - ctx.deinit(); - return err; - }; - - ctx.initJS(args.listener); - return ctx; - } - } - - var default_watcher = FSWatcher.Watcher.init( - ctx, - vm.bundler.fs, - bun.default_allocator, - ) catch |err| { - ctx.deinit(); - return err; }; - ctx.default_watcher = default_watcher; - - if (fs_type.is_file) { - var file_path_clone = bun.default_allocator.dupeZ(u8, file_path) catch unreachable; - - ctx.entry_path = file_path_clone; - ctx.entry_dir = std.fs.path.dirname(file_path_clone) orelse file_path_clone; - - default_watcher.addFile(fs_type.fd, file_path_clone, FSWatcher.Watcher.getHash(file_path), options.Loader.file, 0, null, false) catch |err| { - ctx.deinit(); - return err; - }; - } else { - addDirectory(ctx, default_watcher, fs_type.fd, file_path, args.recursive, &buf, true) catch |err| { - ctx.deinit(); - return err; - }; - } - - default_watcher.start() catch |err| { - ctx.deinit(); - return err; - }; + errdefer ctx.deinit(); + ctx.path_watcher = try PathWatcher.watch(vm, file_path_z, args.recursive, onPathUpdate, onUpdateEnd, bun.cast(*anyopaque, ctx)); ctx.initJS(args.listener); return ctx; } diff --git a/src/bun.js/node/node_os.zig b/src/bun.js/node/node_os.zig index 5710b5c212cd2a..a4efe4454a6b40 100644 --- a/src/bun.js/node/node_os.zig +++ b/src/bun.js/node/node_os.zig @@ -9,7 +9,6 @@ const Environment = bun.Environment; const Global = bun.Global; const is_bindgen: bool = std.meta.globalOption("bindgen", bool) orelse false; const heap_allocator = bun.default_allocator; -const constants = @import("./os/constants.zig"); pub const Os = struct { pub const name = "Bun__Os"; @@ -41,7 +40,7 @@ pub const Os = struct { module.put(globalObject, JSC.ZigString.static("devNull"), JSC.ZigString.init(devNull).withEncoding().toValue(globalObject)); module.put(globalObject, JSC.ZigString.static("EOL"), JSC.ZigString.init(EOL).withEncoding().toValue(globalObject)); - module.put(globalObject, JSC.ZigString.static("constants"), constants.create(globalObject)); + // module.put(globalObject, JSC.ZigString.static("constants"), constants.create(globalObject)); return module; } @@ -110,9 +109,14 @@ pub const Os = struct { // Read /proc/stat to get number of CPUs and times if (std.fs.openFileAbsolute("/proc/stat", .{})) |file| { defer file.close(); - var reader = file.reader(); + // TODO: remove all usages of file.reader(). zig's std.io.Reader() + // is extremely slow and should rarely ever be used in Bun until + // that is fixed. + var buffered_reader = std.io.BufferedReader(8096, @TypeOf(file.reader())){ .unbuffered_reader = file.reader() }; + var reader = buffered_reader.reader(); // Skip the first line (aggregate of all CPUs) + // TODO: use indexOfNewline try reader.skipUntilDelimiterOrEof('\n'); // Read each CPU line @@ -148,18 +152,23 @@ pub const Os = struct { // Read /proc/cpuinfo to get model information (optional) if (std.fs.openFileAbsolute("/proc/cpuinfo", .{})) |file| { defer file.close(); - var reader = file.reader(); + // TODO: remove all usages of file.reader(). zig's std.io.Reader() + // is extremely slow and should rarely ever be used in Bun until + // that is fixed. + var buffered_reader = std.io.BufferedReader(8096, @TypeOf(file.reader())){ .unbuffered_reader = file.reader() }; + var reader = buffered_reader.reader(); + const key_processor = "processor\t: "; const key_model_name = "model name\t: "; var cpu_index: u32 = 0; while (try reader.readUntilDelimiterOrEof(&line_buffer, '\n')) |line| { - if (std.mem.startsWith(u8, line, key_processor)) { + if (strings.hasPrefixComptime(line, key_processor)) { // If this line starts a new processor, parse the index from the line const digits = std.mem.trim(u8, line[key_processor.len..], " \t\n"); cpu_index = try std.fmt.parseInt(u32, digits, 10); if (cpu_index >= num_cpus) return error.too_may_cpus; - } else if (std.mem.startsWith(u8, line, key_model_name)) { + } else if (strings.hasPrefixComptime(line, key_model_name)) { // If this is the model name, extract it and store on the current cpu const model_name = line[key_model_name.len..]; const cpu = JSC.JSObject.getIndex(values, globalThis, cpu_index); @@ -176,9 +185,8 @@ pub const Os = struct { } // Read /sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq to get current frequency (optional) - var cpu_index: u32 = 0; - while (cpu_index < num_cpus) : (cpu_index += 1) { - const cpu = JSC.JSObject.getIndex(values, globalThis, cpu_index); + for (0..num_cpus) |cpu_index| { + const cpu = JSC.JSObject.getIndex(values, globalThis, @truncate(cpu_index)); var path_buf: [128]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq", .{cpu_index}); @@ -199,6 +207,7 @@ pub const Os = struct { return values; } + extern fn bun_sysconf__SC_CLK_TCK() isize; fn cpusImplDarwin(globalThis: *JSC.JSGlobalObject) !JSC.JSValue { const local_bindings = @import("../../darwin_c.zig"); const c = std.c; @@ -243,10 +252,7 @@ pub const Os = struct { } // Get the multiplier; this is the number of ms/tick - const unistd = @cImport({ - @cInclude("unistd.h"); - }); - const ticks: i64 = unistd.sysconf(unistd._SC_CLK_TCK); + const ticks: i64 = bun_sysconf__SC_CLK_TCK(); const multiplier = 1000 / @as(u64, @intCast(ticks)); // Set up each CPU value in the return diff --git a/src/bun.js/node/path_watcher.zig b/src/bun.js/node/path_watcher.zig new file mode 100644 index 00000000000000..1d81661e9bd87f --- /dev/null +++ b/src/bun.js/node/path_watcher.zig @@ -0,0 +1,885 @@ +const std = @import("std"); + +const UnboundedQueue = @import("../unbounded_queue.zig").UnboundedQueue; +const Path = @import("../../resolver/resolve_path.zig"); +const Fs = @import("../../fs.zig"); +const Mutex = @import("../../lock.zig").Lock; +const FSEvents = @import("./fs_events.zig"); + +const bun = @import("root").bun; +const Output = bun.Output; +const Environment = bun.Environment; +const StoredFileDescriptorType = bun.StoredFileDescriptorType; +const string = bun.string; +const JSC = bun.JSC; +const VirtualMachine = JSC.VirtualMachine; + +const sync = @import("../../sync.zig"); +const Semaphore = sync.Semaphore; + +var default_manager_mutex: Mutex = Mutex.init(); +var default_manager: ?*PathWatcherManager = null; + +pub const PathWatcherManager = struct { + const GenericWatcher = @import("../../watcher.zig"); + const options = @import("../../options.zig"); + pub const Watcher = GenericWatcher.NewWatcher(*PathWatcherManager); + const log = Output.scoped(.PathWatcherManager, false); + main_watcher: *Watcher, + + watchers: bun.BabyList(?*PathWatcher) = .{}, + watcher_count: u32 = 0, + vm: *JSC.VirtualMachine, + file_paths: bun.StringHashMap(PathInfo), + current_fd_task: bun.FDHashMap(*DirectoryRegisterTask), + deinit_on_last_watcher: bool = false, + pending_tasks: u32 = 0, + deinit_on_last_task: bool = false, + has_pending_tasks: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + mutex: Mutex, + const PathInfo = struct { + fd: StoredFileDescriptorType = 0, + is_file: bool = true, + path: [:0]const u8, + dirname: string, + refs: u32 = 0, + hash: Watcher.HashType, + }; + + fn refPendingTask(this: *PathWatcherManager) bool { + @fence(.Release); + this.mutex.lock(); + defer this.mutex.unlock(); + if (this.deinit_on_last_task) return false; + this.pending_tasks += 1; + this.has_pending_tasks.store(true, .Release); + return true; + } + + fn hasPendingTasks(this: *PathWatcherManager) callconv(.C) bool { + @fence(.Acquire); + return this.has_pending_tasks.load(.Acquire); + } + + fn unrefPendingTask(this: *PathWatcherManager) void { + @fence(.Release); + this.mutex.lock(); + defer this.mutex.unlock(); + this.pending_tasks -= 1; + if (this.deinit_on_last_task and this.pending_tasks == 0) { + this.has_pending_tasks.store(false, .Release); + this.deinit(); + } + } + // TODO: switch to using JSC.Maybe to avoid using "unreachable" and improve error messages + fn _fdFromAbsolutePathZ( + this: *PathWatcherManager, + path: [:0]const u8, + ) !PathInfo { + this.mutex.lock(); + defer this.mutex.unlock(); + + if (this.file_paths.getEntry(path)) |entry| { + var info = entry.value_ptr; + info.refs += 1; + return info.*; + } + const cloned_path = try bun.default_allocator.dupeZ(u8, path); + errdefer bun.default_allocator.destroy(cloned_path); + + if (std.fs.openIterableDirAbsoluteZ(cloned_path, .{ + .access_sub_paths = true, + })) |iterable_dir| { + const result = PathInfo{ + .fd = iterable_dir.dir.fd, + .is_file = false, + .path = cloned_path, + .dirname = cloned_path, + .hash = Watcher.getHash(cloned_path), + .refs = 1, + }; + _ = try this.file_paths.put(cloned_path, result); + return result; + } else |err| { + if (err == error.NotDir) { + var file = try std.fs.openFileAbsoluteZ(cloned_path, .{ .mode = .read_only }); + const result = PathInfo{ + .fd = file.handle, + .is_file = true, + .path = cloned_path, + // if is really a file we need to get the dirname + .dirname = std.fs.path.dirname(cloned_path) orelse cloned_path, + .hash = Watcher.getHash(cloned_path), + .refs = 1, + }; + _ = try this.file_paths.put(cloned_path, result); + return result; + } else { + return err; + } + } + + unreachable; + } + + pub fn init(vm: *JSC.VirtualMachine) !*PathWatcherManager { + const this = try bun.default_allocator.create(PathWatcherManager); + errdefer bun.default_allocator.destroy(this); + var watchers = bun.BabyList(?*PathWatcher).initCapacity(bun.default_allocator, 1) catch |err| { + bun.default_allocator.destroy(this); + return err; + }; + errdefer watchers.deinitWithAllocator(bun.default_allocator); + var manager = PathWatcherManager{ + .file_paths = bun.StringHashMap(PathInfo).init(bun.default_allocator), + .current_fd_task = bun.FDHashMap(*DirectoryRegisterTask).init(bun.default_allocator), + .watchers = watchers, + .main_watcher = try Watcher.init( + this, + vm.bundler.fs, + bun.default_allocator, + ), + .vm = vm, + .watcher_count = 0, + .mutex = Mutex.init(), + }; + + this.* = manager; + try this.main_watcher.start(); + return this; + } + + pub fn onFileUpdate( + this: *PathWatcherManager, + events: []GenericWatcher.WatchEvent, + changed_files: []?[:0]u8, + watchlist: GenericWatcher.Watchlist, + ) void { + var slice = watchlist.slice(); + const file_paths = slice.items(.file_path); + + var counts = slice.items(.count); + const kinds = slice.items(.kind); + var _on_file_update_path_buf: [bun.MAX_PATH_BYTES]u8 = undefined; + + var ctx = this.main_watcher; + defer ctx.flushEvictions(); + + const timestamp = std.time.milliTimestamp(); + + this.mutex.lock(); + defer this.mutex.unlock(); + + const watchers = this.watchers.slice(); + + for (events) |event| { + if (event.index >= file_paths.len) continue; + const file_path = file_paths[event.index]; + const update_count = counts[event.index] + 1; + counts[event.index] = update_count; + const kind = kinds[event.index]; + + if (comptime Environment.isDebug) { + log("[watch] {s} ({s}, {})", .{ file_path, @tagName(kind), event.op }); + } + + switch (kind) { + .file => { + if (event.op.delete) { + ctx.removeAtIndex( + event.index, + 0, + &.{}, + .file, + ); + } + + if (event.op.write or event.op.delete or event.op.rename) { + const event_type: PathWatcher.EventType = if (event.op.delete or event.op.rename or event.op.move_to) .rename else .change; + const hash = Watcher.getHash(file_path); + + for (watchers) |w| { + if (w) |watcher| { + if (comptime Environment.isMac) { + if (watcher.fsevents_watcher != null) continue; + } + const entry_point = watcher.path.dirname; + var path = file_path; + + if (path.len < entry_point.len) { + continue; + } + if (watcher.path.is_file) { + if (watcher.path.hash != hash) { + continue; + } + } else { + if (!bun.strings.startsWith(path, entry_point)) { + continue; + } + } + // Remove common prefix, unless the watched folder is "/" + if (!(path.len == 1 and entry_point[0] == '/')) { + path = path[entry_point.len..]; + + // Ignore events with path equal to directory itself + if (path.len <= 1) { + continue; + } + if (path.len == 0) { + while (path.len > 0) { + if (bun.strings.startsWithChar(path, '/')) { + path = path[1..]; + break; + } else { + path = path[1..]; + } + } + } else { + // Skip forward slash + path = path[1..]; + } + } + + // Do not emit events from subdirectories (without option set) + if (path.len == 0 or (bun.strings.containsChar(path, '/') and !watcher.recursive)) { + continue; + } + watcher.emit(path, hash, timestamp, true, event_type); + } + } + } + }, + .directory => { + const affected = event.names(changed_files); + + for (affected) |changed_name_| { + const changed_name: []const u8 = bun.asByteSlice(changed_name_.?); + if (changed_name.len == 0 or changed_name[0] == '~' or changed_name[0] == '.') continue; + + var file_path_without_trailing_slash = std.mem.trimRight(u8, file_path, std.fs.path.sep_str); + + @memcpy(_on_file_update_path_buf[0..file_path_without_trailing_slash.len], file_path_without_trailing_slash); + + _on_file_update_path_buf[file_path_without_trailing_slash.len] = std.fs.path.sep; + + @memcpy(_on_file_update_path_buf[file_path_without_trailing_slash.len + 1 ..][0..changed_name.len], changed_name); + const len = file_path_without_trailing_slash.len + changed_name.len; + const path_slice = _on_file_update_path_buf[0 .. len + 1]; + + const hash = Watcher.getHash(path_slice); + + // skip consecutive duplicates + const event_type: PathWatcher.EventType = .rename; // renaming folders, creating folder or files will be always be rename + for (watchers) |w| { + if (w) |watcher| { + if (comptime Environment.isMac) { + if (watcher.fsevents_watcher != null) continue; + } + const entry_point = watcher.path.dirname; + var path = path_slice; + + if (watcher.path.is_file or path.len < entry_point.len or !bun.strings.startsWith(path, entry_point)) { + continue; + } + // Remove common prefix, unless the watched folder is "/" + if (!(path.len == 1 and entry_point[0] == '/')) { + path = path[entry_point.len..]; + + if (path.len == 0) { + while (path.len > 0) { + if (bun.strings.startsWithChar(path, '/')) { + path = path[1..]; + break; + } else { + path = path[1..]; + } + } + } else { + // Skip forward slash + path = path[1..]; + } + } + + // Do not emit events from subdirectories (without option set) + if (path.len == 0 or (bun.strings.containsChar(path, '/') and !watcher.recursive)) { + continue; + } + + watcher.emit(path, hash, timestamp, false, event_type); + } + } + } + }, + } + } + + if (comptime Environment.isDebug) { + Output.flush(); + } + for (watchers) |w| { + if (w) |watcher| { + if (watcher.needs_flush) watcher.flush(); + } + } + } + + pub fn onError( + this: *PathWatcherManager, + err: anyerror, + ) void { + { + this.mutex.lock(); + defer this.mutex.unlock(); + const watchers = this.watchers.slice(); + const timestamp = std.time.milliTimestamp(); + + // stop all watchers + for (watchers) |w| { + if (w) |watcher| { + log("[watch] error: {s}", .{@errorName(err)}); + watcher.emit(@errorName(err), 0, timestamp, false, .@"error"); + watcher.flush(); + } + } + + // we need a new manager at this point + default_manager_mutex.lock(); + defer default_manager_mutex.unlock(); + default_manager = null; + } + // deinit manager when all watchers are closed + this.deinit(); + } + + pub const DirectoryRegisterTask = struct { + manager: *PathWatcherManager, + path: PathInfo, + task: JSC.WorkPoolTask = .{ .callback = callback }, + watcher_list: bun.BabyList(*PathWatcher) = .{}, + + pub fn callback(task: *JSC.WorkPoolTask) void { + var routine = @fieldParentPtr(@This(), "task", task); + defer routine.deinit(); + routine.run(); + } + + fn schedule(manager: *PathWatcherManager, watcher: *PathWatcher, path: PathInfo) !void { + // keep the path alive + manager._incrementPathRef(path.path); + errdefer manager._decrementPathRef(path.path); + var routine: *DirectoryRegisterTask = undefined; + { + manager.mutex.lock(); + defer manager.mutex.unlock(); + + // use the same thread for the same fd to avoid race conditions + if (manager.current_fd_task.getEntry(path.fd)) |entry| { + routine = entry.value_ptr.*; + + if (watcher.refPendingDirectory()) { + routine.watcher_list.push(bun.default_allocator, watcher) catch |err| { + watcher.unrefPendingDirectory(); + return err; + }; + } else { + return error.UnexpectedFailure; + } + return; + } + + routine = try bun.default_allocator.create(DirectoryRegisterTask); + routine.* = DirectoryRegisterTask{ + .manager = manager, + .path = path, + .watcher_list = bun.BabyList(*PathWatcher).initCapacity(bun.default_allocator, 1) catch |err| { + bun.default_allocator.destroy(routine); + return err; + }, + }; + errdefer routine.deinit(); + if (watcher.refPendingDirectory()) { + routine.watcher_list.push(bun.default_allocator, watcher) catch |err| { + watcher.unrefPendingDirectory(); + return err; + }; + } else { + return error.UnexpectedFailure; + } + manager.current_fd_task.put(path.fd, routine) catch |err| { + watcher.unrefPendingDirectory(); + return err; + }; + } + if (manager.refPendingTask()) { + JSC.WorkPool.schedule(&routine.task); + return; + } + return error.UnexpectedFailure; + } + + fn getNext(this: *DirectoryRegisterTask) ?*PathWatcher { + this.manager.mutex.lock(); + defer this.manager.mutex.unlock(); + + const watcher = this.watcher_list.popOrNull(); + if (watcher == null) { + // no more work todo, release the fd and path + _ = this.manager.current_fd_task.remove(this.path.fd); + this.manager._decrementPathRefNoLock(this.path.path); + return null; + } + return watcher; + } + + fn processWatcher( + this: *DirectoryRegisterTask, + watcher: *PathWatcher, + buf: *[bun.MAX_PATH_BYTES + 1]u8, + ) !void { + const manager = this.manager; + const path = this.path; + const fd = path.fd; + var iter = (std.fs.IterableDir{ .dir = std.fs.Dir{ + .fd = fd, + } }).iterate(); + + // now we iterate over all files and directories + while (try iter.next()) |entry| { + var parts = [2]string{ path.path, entry.name }; + var entry_path = Path.joinAbsStringBuf( + Fs.FileSystem.instance.topLevelDirWithoutTrailingSlash(), + buf, + &parts, + .auto, + ); + + buf[entry_path.len] = 0; + var entry_path_z = buf[0..entry_path.len :0]; + + var child_path = try manager._fdFromAbsolutePathZ(entry_path_z); + { + watcher.mutex.lock(); + defer watcher.mutex.unlock(); + watcher.file_paths.push(bun.default_allocator, child_path.path) catch |err| { + manager._decrementPathRef(entry_path_z); + return err; + }; + } + + // we need to call this unlocked + if (child_path.is_file) { + try manager.main_watcher.addFile(child_path.fd, child_path.path, child_path.hash, options.Loader.file, 0, null, false); + } else { + if (watcher.recursive and !watcher.isClosed()) { + // this may trigger another thread with is desired when available to watch long trees + try manager._addDirectory(watcher, child_path); + } + } + } + } + + fn run(this: *DirectoryRegisterTask) void { + var buf: [bun.MAX_PATH_BYTES + 1]u8 = undefined; + + while (this.getNext()) |watcher| { + defer watcher.unrefPendingDirectory(); + this.processWatcher(watcher, &buf) catch |err| { + log("[watch] error registering directory: {s}", .{@errorName(err)}); + watcher.emit(@errorName(err), 0, std.time.milliTimestamp(), false, .@"error"); + watcher.flush(); + }; + } + + this.manager.unrefPendingTask(); + } + + fn deinit(this: *DirectoryRegisterTask) void { + bun.default_allocator.destroy(this); + } + }; + + // this should only be called if thread pool is not null + fn _addDirectory(this: *PathWatcherManager, watcher: *PathWatcher, path: PathInfo) !void { + const fd = path.fd; + try this.main_watcher.addDirectory(fd, path.path, path.hash, false); + + return try DirectoryRegisterTask.schedule(this, watcher, path); + } + + // register is always called form main thread + fn registerWatcher(this: *PathWatcherManager, watcher: *PathWatcher) !void { + { + this.mutex.lock(); + defer this.mutex.unlock(); + + if (this.watcher_count == this.watchers.len) { + this.watcher_count += 1; + this.watchers.push(bun.default_allocator, watcher) catch |err| { + this.watcher_count -= 1; + return err; + }; + } else { + var watchers = this.watchers.slice(); + for (watchers, 0..) |w, i| { + if (w == null) { + watchers[i] = watcher; + this.watcher_count += 1; + break; + } + } + } + } + + const path = watcher.path; + if (path.is_file) { + try this.main_watcher.addFile(path.fd, path.path, path.hash, options.Loader.file, 0, null, false); + } else { + if (comptime Environment.isMac) { + if (watcher.fsevents_watcher != null) { + return; + } + } + try this._addDirectory(watcher, path); + } + } + + fn _incrementPathRef(this: *PathWatcherManager, file_path: [:0]const u8) void { + this.mutex.lock(); + defer this.mutex.unlock(); + if (this.file_paths.getEntry(file_path)) |entry| { + var path = entry.value_ptr; + if (path.refs > 0) { + path.refs += 1; + } + } + } + + fn _decrementPathRefNoLock(this: *PathWatcherManager, file_path: [:0]const u8) void { + if (this.file_paths.getEntry(file_path)) |entry| { + var path = entry.value_ptr; + if (path.refs > 0) { + path.refs -= 1; + if (path.refs == 0) { + const path_ = path.path; + this.main_watcher.remove(path.hash); + _ = this.file_paths.remove(path_); + bun.default_allocator.free(path_); + } + } + } + } + + fn _decrementPathRef(this: *PathWatcherManager, file_path: [:0]const u8) void { + this.mutex.lock(); + defer this.mutex.unlock(); + this._decrementPathRefNoLock(file_path); + } + + // unregister is always called form main thread + fn unregisterWatcher(this: *PathWatcherManager, watcher: *PathWatcher) void { + this.mutex.lock(); + defer this.mutex.unlock(); + + var watchers = this.watchers.slice(); + defer { + if (this.deinit_on_last_watcher and this.watcher_count == 0) { + this.deinit(); + } + } + + for (watchers, 0..) |w, i| { + if (w) |item| { + if (item == watcher) { + watchers[i] = null; + // if is the last one just pop + if (i == watchers.len - 1) { + this.watchers.len -= 1; + } + this.watcher_count -= 1; + + this._decrementPathRefNoLock(watcher.path.path); + if (comptime Environment.isMac) { + if (watcher.fsevents_watcher != null) { + break; + } + } + + { + watcher.mutex.lock(); + defer watcher.mutex.unlock(); + while (watcher.file_paths.popOrNull()) |file_path| { + this._decrementPathRefNoLock(file_path); + } + } + break; + } + } + } + } + + fn deinit(this: *PathWatcherManager) void { + // enable to create a new manager + default_manager_mutex.lock(); + defer default_manager_mutex.unlock(); + if (default_manager == this) { + default_manager = null; + } + + // only deinit if no watchers are registered + if (this.watcher_count > 0) { + // wait last watcher to close + this.deinit_on_last_watcher = true; + return; + } + + if (this.hasPendingTasks()) { + this.mutex.lock(); + defer this.mutex.unlock(); + // deinit when all tasks are done + this.deinit_on_last_task = true; + return; + } + + this.main_watcher.deinit(false); + + if (this.watcher_count > 0) { + while (this.watchers.popOrNull()) |watcher| { + if (watcher) |w| { + // unlink watcher + w.manager = null; + } + } + } + + // close all file descriptors and free paths + var it = this.file_paths.iterator(); + while (it.next()) |*entry| { + const path = entry.value_ptr.*; + std.os.close(path.fd); + bun.default_allocator.destroy(path.path); + } + + this.file_paths.deinit(); + + this.watchers.deinitWithAllocator(bun.default_allocator); + + this.current_fd_task.deinit(); + + bun.default_allocator.destroy(this); + } +}; + +pub const PathWatcher = struct { + path: PathWatcherManager.PathInfo, + callback: Callback, + flushCallback: UpdateEndCallback, + manager: ?*PathWatcherManager, + recursive: bool, + needs_flush: bool = false, + ctx: ?*anyopaque, + // all watched file paths (including subpaths) except by path it self + file_paths: bun.BabyList([:0]const u8) = .{}, + last_change_event: ChangeEvent = .{}, + // on MacOS we use this to watch for changes on directories and subdirectories + fsevents_watcher: ?*FSEvents.FSEventsWatcher, + mutex: Mutex, + pending_directories: u32 = 0, + // only used on macOS + resolved_path: ?string = null, + has_pending_directories: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + closed: std.atomic.Atomic(bool) = std.atomic.Atomic(bool).init(false), + pub const ChangeEvent = struct { + hash: PathWatcherManager.Watcher.HashType = 0, + event_type: EventType = .change, + time_stamp: i64 = 0, + }; + + pub const EventType = enum { + rename, + change, + @"error", + }; + const Callback = *const fn (ctx: ?*anyopaque, path: string, is_file: bool, event_type: EventType) void; + const UpdateEndCallback = *const fn (ctx: ?*anyopaque) void; + + pub fn init(manager: *PathWatcherManager, path: PathWatcherManager.PathInfo, recursive: bool, callback: Callback, updateEndCallback: UpdateEndCallback, ctx: ?*anyopaque) !*PathWatcher { + var this = try bun.default_allocator.create(PathWatcher); + + if (comptime Environment.isMac) { + if (!path.is_file) { + var buffer: [bun.MAX_PATH_BYTES]u8 = undefined; + const resolved_path_temp = std.os.getFdPath(path.fd, &buffer) catch |err| { + bun.default_allocator.destroy(this); + return err; + }; + const resolved_path = bun.default_allocator.dupeZ(u8, resolved_path_temp) catch |err| { + bun.default_allocator.destroy(this); + return err; + }; + this.resolved_path = resolved_path; + this.* = PathWatcher{ + .path = path, + .callback = callback, + .fsevents_watcher = FSEvents.watch( + resolved_path, + recursive, + bun.cast(FSEvents.FSEventsWatcher.Callback, callback), + bun.cast(FSEvents.FSEventsWatcher.UpdateEndCallback, updateEndCallback), + bun.cast(*anyopaque, ctx), + ) catch |err| { + bun.default_allocator.destroy(this); + return err; + }, + .manager = manager, + .recursive = recursive, + .flushCallback = updateEndCallback, + .file_paths = .{}, + .ctx = ctx, + .mutex = Mutex.init(), + }; + + errdefer this.deinit(); + + // TODO: unify better FSEvents with PathWatcherManager + try manager.registerWatcher(this); + + return this; + } + } + + this.* = PathWatcher{ + .fsevents_watcher = null, + .path = path, + .callback = callback, + .manager = manager, + .recursive = recursive, + .flushCallback = updateEndCallback, + .ctx = ctx, + .mutex = Mutex.init(), + .file_paths = bun.BabyList([:0]const u8).initCapacity(bun.default_allocator, 1) catch |err| { + bun.default_allocator.destroy(this); + return err; + }, + }; + + errdefer this.deinit(); + + try manager.registerWatcher(this); + return this; + } + + pub fn refPendingDirectory(this: *PathWatcher) bool { + @fence(.Release); + this.mutex.lock(); + defer this.mutex.unlock(); + if (this.isClosed()) return false; + this.pending_directories += 1; + this.has_pending_directories.store(true, .Release); + return true; + } + + pub fn hasPendingDirectories(this: *PathWatcher) callconv(.C) bool { + @fence(.Acquire); + return this.has_pending_directories.load(.Acquire); + } + + pub fn isClosed(this: *PathWatcher) bool { + @fence(.Acquire); + return this.closed.load(.Acquire); + } + + pub fn setClosed(this: *PathWatcher) void { + this.mutex.lock(); + defer this.mutex.unlock(); + @fence(.Release); + this.closed.store(true, .Release); + } + + pub fn unrefPendingDirectory(this: *PathWatcher) void { + @fence(.Release); + this.mutex.lock(); + defer this.mutex.unlock(); + this.pending_directories -= 1; + if (this.isClosed() and this.pending_directories == 0) { + this.has_pending_directories.store(false, .Release); + this.deinit(); + } + } + + pub fn emit(this: *PathWatcher, path: string, hash: PathWatcherManager.Watcher.HashType, time_stamp: i64, is_file: bool, event_type: EventType) void { + const time_diff = time_stamp - this.last_change_event.time_stamp; + // skip consecutive duplicates + if ((this.last_change_event.time_stamp == 0 or time_diff > 1) or this.last_change_event.event_type != event_type and this.last_change_event.hash != hash) { + this.last_change_event.time_stamp = time_stamp; + this.last_change_event.event_type = event_type; + this.last_change_event.hash = hash; + this.needs_flush = true; + if (this.isClosed()) return; + this.callback(this.ctx, path, is_file, event_type); + } + } + + pub fn flush(this: *PathWatcher) void { + this.needs_flush = false; + if (this.isClosed()) return; + this.flushCallback(this.ctx); + } + + pub fn deinit(this: *PathWatcher) void { + this.setClosed(); + if (this.hasPendingDirectories()) { + // will be freed on last directory + return; + } + + if (this.manager) |manager| { + if (comptime Environment.isMac) { + if (this.fsevents_watcher) |watcher| { + // first unregister on FSEvents + watcher.deinit(); + manager.unregisterWatcher(this); + } else { + manager.unregisterWatcher(this); + this.file_paths.deinitWithAllocator(bun.default_allocator); + } + } else { + manager.unregisterWatcher(this); + this.file_paths.deinitWithAllocator(bun.default_allocator); + } + } + + if (comptime Environment.isMac) { + if (this.resolved_path) |path| { + bun.default_allocator.free(path); + } + } + + bun.default_allocator.destroy(this); + } +}; + +pub fn watch( + vm: *VirtualMachine, + path: [:0]const u8, + recursive: bool, + callback: PathWatcher.Callback, + updateEnd: PathWatcher.UpdateEndCallback, + ctx: ?*anyopaque, +) !*PathWatcher { + if (default_manager) |manager| { + const path_info = try manager._fdFromAbsolutePathZ(path); + errdefer manager._decrementPathRef(path); + return try PathWatcher.init(manager, path_info, recursive, callback, updateEnd, ctx); + } else { + default_manager_mutex.lock(); + defer default_manager_mutex.unlock(); + if (default_manager == null) { + default_manager = try PathWatcherManager.init(vm); + } + const manager = default_manager.?; + const path_info = try manager._fdFromAbsolutePathZ(path); + errdefer manager._decrementPathRef(path); + return try PathWatcher.init(manager, path_info, recursive, callback, updateEnd, ctx); + } +} diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index 23d693d693531e..02bfe87573e098 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -629,6 +629,24 @@ pub const PathLike = union(Tag) { } } + pub fn toThreadSafe(this: *PathLike) void { + if (this.* == .slice_with_underlying_string) { + this.slice_with_underlying_string.toThreadSafe(); + } + } + + pub fn deinitAndUnprotect(this: *const PathLike) void { + switch (this.*) { + .slice_with_underlying_string => |val| { + val.deinit(); + }, + .buffer => |val| { + val.buffer.value.unprotect(); + }, + else => {}, + } + } + pub inline fn slice(this: PathLike) string { return switch (this) { .string => this.string.slice(), @@ -917,6 +935,15 @@ pub const ArgumentsSlice = struct { }; } + pub fn initAsync(vm: *JSC.VirtualMachine, arguments: []const JSC.JSValue) ArgumentsSlice { + return ArgumentsSlice{ + .remaining = bun.default_allocator.dupe(JSC.JSValue, arguments), + .vm = vm, + .all = arguments, + .arena = bun.ArenaAllocator.init(bun.default_allocator), + }; + } + pub inline fn len(this: *const ArgumentsSlice) u16 { return @as(u16, @truncate(this.remaining.len)); } @@ -1029,6 +1056,18 @@ pub const PathOrFileDescriptor = union(Tag) { } } + pub fn toThreadSafe(this: *PathOrFileDescriptor) void { + if (this.* == .path) { + this.path.toThreadSafe(); + } + } + + pub fn deinitAndUnprotect(this: PathOrFileDescriptor) void { + if (this == .path) { + this.path.deinitAndUnprotect(); + } + } + pub fn hash(this: JSC.Node.PathOrFileDescriptor) u64 { return switch (this) { .path => bun.hash(this.path.slice()), @@ -1252,7 +1291,8 @@ fn StatsDataType(comptime T: type) type { uid: T, gid: T, rdev: T, - size: T, + // Always store size as a 64-bit integer + size: i64, blksize: T, blocks: T, atime_ms: f64, @@ -1279,7 +1319,7 @@ fn StatsDataType(comptime T: type) type { .uid = @as(T, @truncate(@as(i64, @intCast(stat_.uid)))), .gid = @as(T, @truncate(@as(i64, @intCast(stat_.gid)))), .rdev = @as(T, @truncate(@as(i64, @intCast(stat_.rdev)))), - .size = @as(T, @truncate(@as(i64, @intCast(stat_.size)))), + .size = @truncate(@as(i64, @intCast(stat_.size))), .blksize = @as(T, @truncate(@as(i64, @intCast(stat_.blksize)))), .blocks = @as(T, @truncate(@as(i64, @intCast(stat_.blocks)))), .atime_ms = (@as(f64, @floatFromInt(@max(atime.tv_sec, 0))) * std.time.ms_per_s) + (@as(f64, @floatFromInt(@as(usize, @intCast(@max(atime.tv_nsec, 0))))) / std.time.ns_per_ms), @@ -1798,7 +1838,7 @@ pub const Path = struct { const base_slice = path.slice(); - return JSC.ZigString.init(std.fs.path.extension(base_slice)).toValueGC(globalThis); + return JSC.ZigString.init(std.fs.path.extension(base_slice)).withEncoding().toValueGC(globalThis); } pub fn format(globalThis: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) callconv(.C) JSC.JSValue { if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); @@ -1821,14 +1861,17 @@ pub const Path = struct { var insert_separator = true; if (path_object.getTruthy(globalThis, "dir")) |prop| { prop.toZigString(&dir, globalThis); - insert_separator = !dir.isEmpty(); - } else if (path_object.getTruthy(globalThis, "root")) |prop| { - prop.toZigString(&dir, globalThis); + } + if (dir.isEmpty()) { + if (path_object.getTruthy(globalThis, "root")) |prop| { + prop.toZigString(&dir, globalThis); + } } if (path_object.getTruthy(globalThis, "base")) |prop| { prop.toZigString(&name_with_ext, globalThis); - } else { + } + if (name_with_ext.isEmpty()) { var had_ext = false; if (path_object.getTruthy(globalThis, "ext")) |prop| { prop.toZigString(&ext, globalThis); @@ -1857,6 +1900,16 @@ pub const Path = struct { defer allocator.free(out); return JSC.ZigString.init(out).withEncoding().toValueGC(globalThis); + } else { + if (!isWindows) { + if (dir.eqlComptime("/")) { + insert_separator = false; + } + } else { + if (dir.eqlComptime("\\")) { + insert_separator = false; + } + } } if (insert_separator) { @@ -1937,27 +1990,20 @@ pub const Path = struct { ) callconv(.C) JSC.JSValue { if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); if (args_len == 0) return JSC.ZigString.init("").toValue(globalThis); - + var arena = @import("root").bun.ArenaAllocator.init(heap_allocator); + var arena_allocator = arena.allocator(); var stack_fallback_allocator = std.heap.stackFallback( - (32 * @sizeOf(string)), - heap_allocator, + ((32 * @sizeOf(string)) + 1024), + arena_allocator, ); var allocator = stack_fallback_allocator.get(); - var arena = @import("root").bun.ArenaAllocator.init(heap_allocator); - var arena_allocator = arena.allocator(); + defer arena.deinit(); var buf: [bun.MAX_PATH_BYTES]u8 = undefined; var to_join = allocator.alloc(string, args_len) catch unreachable; - var possibly_utf16 = false; for (args_ptr[0..args_len], 0..) |arg, i| { const zig_str: JSC.ZigString = arg.getZigString(globalThis); - if (zig_str.is16Bit()) { - // TODO: remove this string conversion - to_join[i] = zig_str.toSlice(arena_allocator).slice(); - possibly_utf16 = true; - } else { - to_join[i] = zig_str.slice(); - } + to_join[i] = zig_str.toSlice(allocator).slice(); } const out = if (!isWindows) @@ -1965,19 +2011,17 @@ pub const Path = struct { else PathHandler.joinStringBuf(&buf, to_join, .windows); - var out_str = JSC.ZigString.init(out); - if (possibly_utf16) { - out_str.setOutputEncoding(); - } - - return out_str.toValueGC(globalThis); + var str = bun.String.create(out); + defer str.deref(); + return str.toJS(globalThis); } + pub fn normalize(globalThis: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [*]JSC.JSValue, args_len: u16) callconv(.C) JSC.JSValue { if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); if (args_len == 0) return JSC.ZigString.init("").toValue(globalThis); var zig_str: JSC.ZigString = args_ptr[0].getZigString(globalThis); - if (zig_str.len == 0) return JSC.ZigString.init("").toValue(globalThis); + if (zig_str.len == 0) return JSC.ZigString.init(".").toValue(globalThis); var buf: [bun.MAX_PATH_BYTES]u8 = undefined; var str_slice = zig_str.toSlice(heap_allocator); diff --git a/src/bun.js/scripts/class-definitions.ts b/src/bun.js/scripts/class-definitions.ts index 281cd62c5dc964..d9c327f6b7b8a4 100644 --- a/src/bun.js/scripts/class-definitions.ts +++ b/src/bun.js/scripts/class-definitions.ts @@ -41,7 +41,7 @@ export interface ClassDefinition { configurable?: boolean; enumerable?: boolean; - structuredClone?: boolean | { transferrable: boolean; tag: number }; + structuredClone?: boolean | { transferable: boolean; tag: number }; } export interface CustomField { diff --git a/src/bun.js/scripts/generate-classes.ts b/src/bun.js/scripts/generate-classes.ts index fb44196428c6e0..ec0021637b7407 100644 --- a/src/bun.js/scripts/generate-classes.ts +++ b/src/bun.js/scripts/generate-classes.ts @@ -1249,7 +1249,7 @@ function generateZig( if (structuredClone) { exports.set("onStructuredCloneSerialize", symbolName(typeName, "onStructuredCloneSerialize")); - if (structuredClone === "transferrable") { + if (structuredClone === "transferable") { exports.set("onStructuredCloneTransfer", symbolName(typeName, "onStructuredCloneTransfer")); } @@ -1306,8 +1306,8 @@ function generateZig( } `; - if (structuredClone === "transferrable") { - exports.set("structuredClone", symbolName(typeName, "onTransferrableStructuredClone")); + if (structuredClone === "transferable") { + exports.set("structuredClone", symbolName(typeName, "onTransferableStructuredClone")); output += ` if (@TypeOf(${typeName}.onStructuredCloneTransfer) != (fn(*${typeName}, globalThis: *JSC.JSGlobalObject, ctx: *anyopaque, write: *const fn(*anyopaque, ptr: [*]const u8, len: usize) callconv(.C) void) callconv(.C) void)) { @compileLog("${typeName}.onStructuredCloneTransfer is not a structured clone transfer function"); diff --git a/src/bun.js/test/expect.zig b/src/bun.js/test/expect.zig index d6f8ebb127bab2..de3f185d5c500f 100644 --- a/src/bun.js/test/expect.zig +++ b/src/bun.js/test/expect.zig @@ -28,6 +28,17 @@ pub const Counter = struct { actual: u32 = 0, }; +const JSTypeOfMap = bun.ComptimeStringMap([]const u8, .{ + .{ "function", "function" }, + .{ "object", "object" }, + .{ "bigint", "bigint" }, + .{ "boolean", "boolean" }, + .{ "number", "number" }, + .{ "string", "string" }, + .{ "symbol", "symbol" }, + .{ "undefined", "undefined" }, +}); + pub var active_test_expectation_counter: Counter = .{}; /// https://jestjs.io/docs/expect @@ -289,6 +300,108 @@ pub const Expect = struct { return null; } + // pass here has a leading underscore to avoid name collision with the pass variable in other functions + pub fn _pass( + this: *Expect, + globalObject: *JSC.JSGlobalObject, + callFrame: *JSC.CallFrame, + ) callconv(.C) JSC.JSValue { + defer this.postMatch(globalObject); + + const thisValue = callFrame.this(); + const arguments_ = callFrame.arguments(1); + const arguments = arguments_.ptr[0..arguments_.len]; + + var _msg: ZigString = ZigString.Empty; + + if (arguments.len > 0) { + const value = arguments[0]; + value.ensureStillAlive(); + + if (!value.isString()) { + globalObject.throwInvalidArgumentType("pass", "message", "string"); + return .zero; + } + + value.toZigString(&_msg, globalObject); + } else { + _msg = ZigString.fromBytes("passes by .pass() assertion"); + } + + active_test_expectation_counter.actual += 1; + + const not = this.flags.not; + var pass = true; + + if (not) pass = !pass; + if (pass) return thisValue; + + var msg = _msg.toSlice(default_allocator); + defer msg.deinit(); + + if (not) { + const signature = comptime getSignature("pass", "", true); + const fmt = signature ++ "\n\n{s}\n"; + if (Output.enable_ansi_colors) { + globalObject.throw(Output.prettyFmt(fmt, true), .{msg.slice()}); + return .zero; + } + globalObject.throw(Output.prettyFmt(fmt, false), .{msg.slice()}); + return .zero; + } + + // should never reach here + return .zero; + } + + pub fn fail( + this: *Expect, + globalObject: *JSC.JSGlobalObject, + callFrame: *JSC.CallFrame, + ) callconv(.C) JSC.JSValue { + defer this.postMatch(globalObject); + + const thisValue = callFrame.this(); + const arguments_ = callFrame.arguments(1); + const arguments = arguments_.ptr[0..arguments_.len]; + + var _msg: ZigString = ZigString.Empty; + + if (arguments.len > 0) { + const value = arguments[0]; + value.ensureStillAlive(); + + if (!value.isString()) { + globalObject.throwInvalidArgumentType("fail", "message", "string"); + return .zero; + } + + value.toZigString(&_msg, globalObject); + } else { + _msg = ZigString.fromBytes("fails by .fail() assertion"); + } + + active_test_expectation_counter.actual += 1; + + const not = this.flags.not; + var pass = false; + + if (not) pass = !pass; + if (pass) return thisValue; + + var msg = _msg.toSlice(default_allocator); + defer msg.deinit(); + + const signature = comptime getSignature("fail", "", true); + const fmt = signature ++ "\n\n{s}\n"; + if (Output.enable_ansi_colors) { + globalObject.throw(Output.prettyFmt(fmt, true), .{msg.slice()}); + return .zero; + } + globalObject.throw(Output.prettyFmt(fmt, false), .{msg.slice()}); + return .zero; + } + /// Object.is() pub fn toBe( this: *Expect, @@ -2215,15 +2328,7 @@ pub const Expect = struct { return .zero; } - if (!std.mem.eql(u8, expectedAsStr, "function") and - !std.mem.eql(u8, expectedAsStr, "object") and - !std.mem.eql(u8, expectedAsStr, "bigint") and - !std.mem.eql(u8, expectedAsStr, "boolean") and - !std.mem.eql(u8, expectedAsStr, "number") and - !std.mem.eql(u8, expectedAsStr, "string") and - !std.mem.eql(u8, expectedAsStr, "symbol") and - !std.mem.eql(u8, expectedAsStr, "undefined")) - { + if (!JSTypeOfMap.has(expectedAsStr)) { globalThis.throwInvalidArguments("toBeTypeOf() requires a valid type string argument ('function', 'object', 'bigint', 'boolean', 'number', 'string', 'symbol', 'undefined')", .{}); return .zero; } @@ -2254,7 +2359,7 @@ pub const Expect = struct { return .zero; } - pass = std.mem.eql(u8, expectedAsStr, whatIsTheType); + pass = strings.eql(expectedAsStr, whatIsTheType); if (not) pass = !pass; if (pass) return thisValue; @@ -2707,6 +2812,206 @@ pub const Expect = struct { return .zero; } + pub fn toIncludeRepeated(this: *Expect, globalThis: *JSGlobalObject, callFrame: *CallFrame) callconv(.C) JSValue { + defer this.postMatch(globalThis); + + const thisValue = callFrame.this(); + const arguments_ = callFrame.arguments(2); + const arguments = arguments_.ptr[0..arguments_.len]; + + if (arguments.len < 2) { + globalThis.throwInvalidArguments("toIncludeRepeated() requires 2 arguments", .{}); + return .zero; + } + + if (this.scope.tests.items.len <= this.test_id) { + globalThis.throw("toIncludeRepeated() must be called in a test", .{}); + return .zero; + } + + active_test_expectation_counter.actual += 1; + + const substring = arguments[0]; + substring.ensureStillAlive(); + + if (!substring.isString()) { + globalThis.throw("toIncludeRepeated() requires the first argument to be a string", .{}); + return .zero; + } + + const count = arguments[1]; + count.ensureStillAlive(); + + if (!count.isAnyInt()) { + globalThis.throw("toIncludeRepeated() requires the second argument to be a number", .{}); + return .zero; + } + + const countAsNum = count.toU32(); + + const expect_string = Expect.capturedValueGetCached(thisValue) orelse { + globalThis.throw("Internal consistency error: the expect(value) was garbage collected but it should not have been!", .{}); + return .zero; + }; + + if (!expect_string.isString()) { + globalThis.throw("toIncludeRepeated() requires the expect(value) to be a string", .{}); + return .zero; + } + + const not = this.flags.not; + var pass = false; + + const _expectStringAsStr = expect_string.toSliceOrNull(globalThis) orelse return .zero; + const _subStringAsStr = substring.toSliceOrNull(globalThis) orelse return .zero; + + defer { + _expectStringAsStr.deinit(); + _subStringAsStr.deinit(); + } + + var expectStringAsStr = _expectStringAsStr.slice(); + var subStringAsStr = _subStringAsStr.slice(); + + if (subStringAsStr.len == 0) { + globalThis.throw("toIncludeRepeated() requires the first argument to be a non-empty string", .{}); + return .zero; + } + + if (countAsNum == 0) + pass = !strings.contains(expectStringAsStr, subStringAsStr) + else + pass = std.mem.containsAtLeast(u8, expectStringAsStr, countAsNum, subStringAsStr); + + if (not) pass = !pass; + if (pass) return thisValue; + + var formatter = JSC.ZigConsoleClient.Formatter{ .globalThis = globalThis, .quote_strings = true }; + const expect_string_fmt = expect_string.toFmt(globalThis, &formatter); + const substring_fmt = substring.toFmt(globalThis, &formatter); + const times_fmt = count.toFmt(globalThis, &formatter); + + const received_line = "Received: {any}\n"; + + if (not) { + if (countAsNum == 0) { + const expected_line = "Expected to include: {any} \n"; + const fmt = comptime getSignature("toIncludeRepeated", "expected", true) ++ "\n\n" ++ expected_line ++ received_line; + globalThis.throwPretty(fmt, .{ substring_fmt, expect_string_fmt }); + } else if (countAsNum == 1) { + const expected_line = "Expected not to include: {any} \n"; + const fmt = comptime getSignature("toIncludeRepeated", "expected", true) ++ "\n\n" ++ expected_line ++ received_line; + globalThis.throwPretty(fmt, .{ substring_fmt, expect_string_fmt }); + } else { + const expected_line = "Expected not to include: {any} {any} times \n"; + const fmt = comptime getSignature("toIncludeRepeated", "expected", true) ++ "\n\n" ++ expected_line ++ received_line; + globalThis.throwPretty(fmt, .{ substring_fmt, times_fmt, expect_string_fmt }); + } + + return .zero; + } + + if (countAsNum == 0) { + const expected_line = "Expected to not include: {any}\n"; + const fmt = comptime getSignature("toIncludeRepeated", "expected", false) ++ "\n\n" ++ expected_line ++ received_line; + globalThis.throwPretty(fmt, .{ substring_fmt, expect_string_fmt }); + } else if (countAsNum == 1) { + const expected_line = "Expected to include: {any}\n"; + const fmt = comptime getSignature("toIncludeRepeated", "expected", false) ++ "\n\n" ++ expected_line ++ received_line; + globalThis.throwPretty(fmt, .{ substring_fmt, expect_string_fmt }); + } else { + const expected_line = "Expected to include: {any} {any} times \n"; + const fmt = comptime getSignature("toIncludeRepeated", "expected", false) ++ "\n\n" ++ expected_line ++ received_line; + globalThis.throwPretty(fmt, .{ substring_fmt, times_fmt, expect_string_fmt }); + } + + return .zero; + } + + pub fn toSatisfy(this: *Expect, globalThis: *JSGlobalObject, callFrame: *CallFrame) callconv(.C) JSValue { + defer this.postMatch(globalThis); + + const thisValue = callFrame.this(); + const arguments_ = callFrame.arguments(1); + const arguments = arguments_.ptr[0..arguments_.len]; + + if (arguments.len < 1) { + globalThis.throwInvalidArguments("toSatisfy() requires 1 argument", .{}); + return .zero; + } + + if (this.scope.tests.items.len <= this.test_id) { + globalThis.throw("toSatisfy() must be called in a test", .{}); + return .zero; + } + + active_test_expectation_counter.actual += 1; + + const predicate = arguments[0]; + predicate.ensureStillAlive(); + + if (!predicate.isCallable(globalThis.vm())) { + globalThis.throw("toSatisfy() argument must be a function", .{}); + return .zero; + } + + const value = Expect.capturedValueGetCached(thisValue) orelse { + globalThis.throw("Internal consistency error: the expect(value) was garbage collected but it should not have been!", .{}); + return .zero; + }; + value.ensureStillAlive(); + + const result = predicate.call(globalThis, &.{value}); + + if (result.toError()) |err| { + var errors: [1]*anyopaque = undefined; + var _err = errors[0..errors.len]; + + _err[0] = err.asVoid(); + + const fmt = ZigString.init("toSatisfy() predicate threw an exception"); + globalThis.vm().throwError(globalThis, globalThis.createAggregateError(_err.ptr, _err.len, &fmt)); + return .zero; + } + + const not = this.flags.not; + const pass = (result.isBoolean() and result.toBoolean()) != not; + + if (pass) return thisValue; + + var formatter = JSC.ZigConsoleClient.Formatter{ .globalThis = globalThis, .quote_strings = true }; + + if (not) { + const signature = comptime getSignature("toSatisfy", "expected", true); + const fmt = signature ++ "\n\nExpected: not {any}\n"; + if (Output.enable_ansi_colors) { + globalThis.throw(Output.prettyFmt(fmt, true), .{predicate.toFmt(globalThis, &formatter)}); + return .zero; + } + globalThis.throw(Output.prettyFmt(fmt, false), .{predicate.toFmt(globalThis, &formatter)}); + return .zero; + } + + const signature = comptime getSignature("toSatisfy", "expected", false); + + const fmt = signature ++ "\n\nExpected: {any}\nReceived: {any}\n"; + + if (Output.enable_ansi_colors) { + globalThis.throw(Output.prettyFmt(fmt, true), .{ + predicate.toFmt(globalThis, &formatter), + value.toFmt(globalThis, &formatter), + }); + return .zero; + } + + globalThis.throw(Output.prettyFmt(fmt, false), .{ + predicate.toFmt(globalThis, &formatter), + value.toFmt(globalThis, &formatter), + }); + + return .zero; + } + pub fn toStartWith(this: *Expect, globalThis: *JSGlobalObject, callFrame: *CallFrame) callconv(.C) JSValue { defer this.postMatch(globalThis); diff --git a/src/bun.js/test/jest.classes.ts b/src/bun.js/test/jest.classes.ts index e5bf567a9ea19a..d40acbf077d491 100644 --- a/src/bun.js/test/jest.classes.ts +++ b/src/bun.js/test/jest.classes.ts @@ -108,6 +108,14 @@ export default [ }, }, proto: { + pass: { + fn: "_pass", + length: 1, + }, + fail: { + fn: "fail", + length: 1, + }, toBe: { fn: "toBe", length: 1, @@ -345,6 +353,14 @@ export default [ fn: "toInclude", length: 1, }, + toIncludeRepeated: { + fn: "toIncludeRepeated", + length: 2, + }, + toSatisfy: { + fn: "toSatisfy", + length: 1, + }, toStartWith: { fn: "toStartWith", length: 1, diff --git a/src/bun.js/test/jest.zig b/src/bun.js/test/jest.zig index 39116054e875a5..9169c994ba2cb0 100644 --- a/src/bun.js/test/jest.zig +++ b/src/bun.js/test/jest.zig @@ -34,6 +34,7 @@ const FeatureFlags = @import("root").bun.FeatureFlags; const ArrayBuffer = @import("../base.zig").ArrayBuffer; const Properties = @import("../base.zig").Properties; const getAllocator = @import("../base.zig").getAllocator; +const RegularExpression = bun.RegularExpression; const ZigString = JSC.ZigString; const JSInternalPromise = JSC.JSInternalPromise; @@ -88,6 +89,7 @@ pub const TestRunner = struct { test_timeout_timer: ?*bun.uws.Timer = null, last_test_timeout_timer_duration: u32 = 0, active_test_for_timeout: ?TestRunner.Test.ID = null, + test_options: *const bun.CLI.Command.TestOptions = undefined, global_callbacks: struct { beforeAll: std.ArrayListUnmanaged(JSC.JSValue) = .{}, @@ -96,6 +98,10 @@ pub const TestRunner = struct { afterAll: std.ArrayListUnmanaged(JSC.JSValue) = .{}, } = .{}, + // Used for --test-name-pattern to reduce allocations + filter_regex: ?*RegularExpression, + filter_buffer: MutableString, + pub const Drainer = JSC.AnyTask.New(TestRunner, drain); pub fn onTestTimeout(timer: *bun.uws.Timer) callconv(.C) void { @@ -367,6 +373,11 @@ pub const Jest = struct { ZigString.static("skipIf"), JSC.NewFunction(globalObject, ZigString.static("skipIf"), 2, TestScope.skipIf, false), ); + test_fn.put( + globalObject, + ZigString.static("each"), + JSC.NewFunction(globalObject, ZigString.static("each"), 2, TestScope.each, false), + ); module.put( globalObject, @@ -399,6 +410,11 @@ pub const Jest = struct { ZigString.static("skipIf"), JSC.NewFunction(globalObject, ZigString.static("skipIf"), 2, DescribeScope.skipIf, false), ); + describe.put( + globalObject, + ZigString.static("each"), + JSC.NewFunction(globalObject, ZigString.static("each"), 2, DescribeScope.each, false), + ); module.put( globalObject, @@ -540,7 +556,11 @@ pub const Jest = struct { pub const TestScope = struct { label: string = "", parent: *DescribeScope, - callback: JSC.JSValue, + + func: JSC.JSValue, + func_arg: []JSC.JSValue, + func_has_callback: bool = false, + id: TestRunner.Test.ID = 0, promise: ?*JSInternalPromise = null, ran: bool = false, @@ -572,6 +592,10 @@ pub const TestScope = struct { return createScope(globalThis, callframe, "test.todo()", true, .todo); } + pub fn each(globalThis: *JSGlobalObject, callframe: *CallFrame) callconv(.C) JSValue { + return createEach(globalThis, callframe, "test.each()", "each", true); + } + pub fn callIf(globalThis: *JSGlobalObject, callframe: *CallFrame) callconv(.C) JSValue { return createIfScope(globalThis, callframe, "test.if()", "if", TestScope, false); } @@ -631,17 +655,19 @@ pub const TestScope = struct { ) Result { if (comptime is_bindgen) return undefined; var vm = VirtualMachine.get(); - const callback = this.callback; + const func = this.func; Jest.runner.?.did_pending_test_fail = false; defer { - callback.unprotect(); - this.callback = .zero; + for (this.func_arg) |arg| { + arg.unprotect(); + } + func.unprotect(); + this.func = .zero; + this.func_has_callback = false; vm.autoGarbageCollect(); } JSC.markBinding(@src()); - const callback_length = callback.getLength(vm.global); - var initial_value = JSValue.zero; if (test_elapsed_timer) |timer| { timer.reset(); @@ -653,7 +679,7 @@ pub const TestScope = struct { task.test_id, ); - if (callback_length > 0) { + if (this.func_has_callback) { const callback_func = JSC.NewFunctionWithData( vm.global, ZigString.static("done"), @@ -663,11 +689,11 @@ pub const TestScope = struct { task, ); task.done_callback_state = .pending; - initial_value = callback.call(vm.global, &.{callback_func}); - } else { - initial_value = callback.call(vm.global, &.{}); + this.func_arg[this.func_arg.len - 1] = callback_func; } + initial_value = this.func.call(vm.global, @as([]const JSC.JSValue, this.func_arg)); + if (initial_value.isAnyError()) { if (!Jest.runner.?.did_pending_test_fail) { // test failed unless it's a todo @@ -724,7 +750,7 @@ pub const TestScope = struct { } } - if (callback_length > 0) { + if (this.func_has_callback) { return .{ .pending = {} }; } @@ -1028,6 +1054,10 @@ pub const DescribeScope = struct { return createScope(globalThis, callframe, "describe.todo()", false, .todo); } + pub fn each(globalThis: *JSGlobalObject, callframe: *CallFrame) callconv(.C) JSValue { + return createEach(globalThis, callframe, "describe.each()", "each", false); + } + pub fn callIf(globalThis: *JSGlobalObject, callframe: *CallFrame) callconv(.C) JSValue { return createIfScope(globalThis, callframe, "describe.if()", "if", DescribeScope, false); } @@ -1036,7 +1066,7 @@ pub const DescribeScope = struct { return createIfScope(globalThis, callframe, "describe.skipIf()", "skipIf", DescribeScope, true); } - pub fn run(this: *DescribeScope, globalObject: *JSC.JSGlobalObject, callback: JSC.JSValue) JSC.JSValue { + pub fn run(this: *DescribeScope, globalObject: *JSC.JSGlobalObject, callback: JSC.JSValue, args: []const JSC.JSValue) JSC.JSValue { if (comptime is_bindgen) return undefined; callback.protect(); defer callback.unprotect(); @@ -1051,7 +1081,7 @@ pub const DescribeScope = struct { { JSC.markBinding(@src()); globalObject.clearTerminationException(); - var result = callback.call(globalObject, &.{}); + var result = callback.call(globalObject, args); if (result.asAnyPromise()) |prom| { globalObject.bunVM().waitForPromise(prom); @@ -1242,7 +1272,7 @@ pub const TestRunnerTask = struct { var test_: TestScope = this.describe.tests.items[test_id]; describe.current_test_id = test_id; - if (test_.callback == .zero or (describe.is_skip and test_.tag != .only)) { + if (test_.func == .zero or (describe.is_skip and test_.tag != .only)) { var tag = if (describe.is_skip) describe.tag else test_.tag; switch (tag) { .todo => { @@ -1441,6 +1471,17 @@ pub const Result = union(TestRunner.Test.Status) { } }; +fn appendParentLabel( + buffer: *bun.MutableString, + parent: *DescribeScope, +) !void { + if (parent.parent) |par| { + try appendParentLabel(buffer, par); + } + try buffer.append(parent.label); + try buffer.append(" "); +} + inline fn createScope( globalThis: *JSGlobalObject, callframe: *CallFrame, @@ -1516,11 +1557,26 @@ inline fn createScope( return .zero; } - const is_skip = tag == .skip or + var is_skip = tag == .skip or (tag == .todo and (function == .zero or !Jest.runner.?.run_todo)) or (tag != .only and Jest.runner.?.only and parent.tag != .only); + var tag_to_use = tag; if (is_test) { + if (!is_skip) { + if (Jest.runner.?.filter_regex) |regex| { + var buffer: bun.MutableString = Jest.runner.?.filter_buffer; + buffer.reset(); + appendParentLabel(&buffer, parent) catch @panic("Bun ran out of memory while filtering tests"); + buffer.append(label) catch unreachable; + var str = bun.String.fromBytes(buffer.toOwnedSliceLeaky()); + is_skip = !regex.matches(str); + if (is_skip) { + tag_to_use = .skip; + } + } + } + if (is_skip) { parent.skip_count += 1; function.unprotect(); @@ -1528,11 +1584,22 @@ inline fn createScope( function.protect(); } + const func_params_length = function.getLength(globalThis); + var arg_size: usize = 0; + var has_callback = false; + if (func_params_length > 0) { + has_callback = true; + arg_size = 1; + } + var function_args = allocator.alloc(JSC.JSValue, arg_size) catch unreachable; + parent.tests.append(allocator, TestScope{ .label = label, .parent = parent, - .tag = tag, - .callback = if (is_skip) .zero else function, + .tag = tag_to_use, + .func = if (is_skip) .zero else function, + .func_arg = function_args, + .func_has_callback = has_callback, .timeout_millis = timeout_ms, }) catch unreachable; @@ -1551,7 +1618,7 @@ inline fn createScope( .is_skip = is_skip or parent.is_skip, }; - return scope.run(globalThis, function); + return scope.run(globalThis, function, &.{}); } return this; @@ -1705,3 +1772,187 @@ pub fn printGithubAnnotation(exception: *JSC.ZigException) void { Output.printError("\n", .{}); Output.flush(); } + +pub const EachData = struct { strong: JSC.Strong, is_test: bool }; + +fn eachBind( + globalThis: *JSGlobalObject, + callframe: *CallFrame, +) callconv(.C) JSValue { + comptime var signature = "eachBind"; + const callee = callframe.callee(); + const arguments = callframe.arguments(3); + const args = arguments.ptr[0..arguments.len]; + + if (args.len < 2) { + globalThis.throwPretty("{s} a description and callback function", .{signature}); + return .zero; + } + + var description = args[0]; + var function = args[1]; + var options = if (args.len > 2) args[2] else .zero; + + if (function.isEmptyOrUndefinedOrNull() or !function.isCell() or !function.isCallable(globalThis.vm())) { + globalThis.throwPretty("{s} expects a function", .{signature}); + return .zero; + } + + var timeout_ms: u32 = Jest.runner.?.default_timeout_ms; + if (options.isNumber()) { + timeout_ms = @as(u32, @intCast(@max(args[2].coerce(i32, globalThis), 0))); + } else if (options.isObject()) { + if (options.get(globalThis, "timeout")) |timeout| { + if (!timeout.isNumber()) { + globalThis.throwPretty("{s} expects timeout to be a number", .{signature}); + return .zero; + } + timeout_ms = @as(u32, @intCast(@max(timeout.coerce(i32, globalThis), 0))); + } + if (options.get(globalThis, "retry")) |retries| { + if (!retries.isNumber()) { + globalThis.throwPretty("{s} expects retry to be a number", .{signature}); + return .zero; + } + // TODO: retry_count = @intCast(u32, @max(retries.coerce(i32, globalThis), 0)); + } + if (options.get(globalThis, "repeats")) |repeats| { + if (!repeats.isNumber()) { + globalThis.throwPretty("{s} expects repeats to be a number", .{signature}); + return .zero; + } + // TODO: repeat_count = @intCast(u32, @max(repeats.coerce(i32, globalThis), 0)); + } + } else if (!options.isEmptyOrUndefinedOrNull()) { + globalThis.throwPretty("{s} expects options to be a number or object", .{signature}); + return .zero; + } + + const parent = DescribeScope.active.?; + + if (JSC.getFunctionData(callee)) |data| { + const allocator = getAllocator(globalThis); + const each_data = bun.cast(*EachData, data); + JSC.setFunctionData(callee, null); + const array = each_data.*.strong.get() orelse return .zero; + defer { + each_data.*.strong.deinit(); + allocator.destroy(each_data); + } + + if (array.isUndefinedOrNull() or !array.jsType().isArray()) { + return .zero; + } + + var iter = array.arrayIterator(globalThis); + + while (iter.next()) |item| { + // TODO: node:util.format() the label + const label = if (description.isEmptyOrUndefinedOrNull()) + "" + else + (description.toSlice(globalThis, allocator).cloneIfNeeded(allocator) catch unreachable).slice(); + + const func_params_length = function.getLength(globalThis); + const item_is_array = !item.isEmptyOrUndefinedOrNull() and item.jsType().isArray(); + var arg_size: usize = 1; + + if (item_is_array) { + arg_size = item.getLength(globalThis); + } + + // add room for callback function + const has_callback_function: bool = (func_params_length > arg_size) and each_data.is_test; + if (has_callback_function) { + arg_size += 1; + } + + var function_args = allocator.alloc(JSC.JSValue, arg_size) catch @panic("can't create function_args"); + var idx: u32 = 0; + + if (item_is_array) { + // Spread array as args + var item_iter = item.arrayIterator(globalThis); + while (item_iter.next()) |array_item| { + if (array_item == .zero) { + allocator.free(function_args); + break; + } + array_item.protect(); + function_args[idx] = array_item; + idx += 1; + } + } else { + item.protect(); + function_args[0] = item; + } + + if (each_data.is_test) { + function.protect(); + parent.tests.append(allocator, TestScope{ + .label = label, + .parent = parent, + .tag = parent.tag, + .func = function, + .func_arg = function_args, + .func_has_callback = has_callback_function, + .timeout_millis = timeout_ms, + }) catch unreachable; + + if (test_elapsed_timer == null) create_timer: { + var timer = allocator.create(std.time.Timer) catch unreachable; + timer.* = std.time.Timer.start() catch break :create_timer; + test_elapsed_timer = timer; + } + } else { + var scope = allocator.create(DescribeScope) catch unreachable; + scope.* = .{ + .label = label, + .parent = parent, + .file_id = parent.file_id, + .tag = if (parent.is_skip) parent.tag else .pass, + .is_skip = parent.is_skip, + }; + + const ret = scope.run(globalThis, function, function_args); + _ = ret; + allocator.free(function_args); + } + } + } + + return .zero; +} + +inline fn createEach( + globalThis: *JSGlobalObject, + callframe: *CallFrame, + comptime property: string, + comptime signature: string, + comptime is_test: bool, +) JSValue { + const arguments = callframe.arguments(1); + const args = arguments.ptr[0..arguments.len]; + + if (args.len == 0) { + globalThis.throwPretty("{s} expects an array", .{signature}); + return .zero; + } + + var array = args[0]; + if (!array.jsType().isArray()) { + globalThis.throwPretty("{s} expects an array", .{signature}); + return .zero; + } + + const allocator = getAllocator(globalThis); + const name = ZigString.static(property); + var strong = JSC.Strong.create(array, globalThis); + var each_data = allocator.create(EachData) catch unreachable; + each_data.* = EachData{ + .strong = strong, + .is_test = is_test, + }; + + return JSC.NewFunctionWithData(globalThis, name, 3, eachBind, true, each_data); +} diff --git a/src/bun.js/test/test.zig b/src/bun.js/test/test.zig new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index 130e99be1ee34e..bbe708d188e192 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -341,22 +341,20 @@ pub const WebWorker = struct { if (this.requested_terminate) { return; } - - this.allowed_to_exit = false; _ = this.requestTerminate(); } pub fn setRef(this: *WebWorker, value: bool) callconv(.C) void { - if (this.requested_terminate and value) { + if (this.requested_terminate and !value) { this.parent_poll_ref.unref(this.parent); return; } - this.allowed_to_exit = value; - if (value) { - this.parent_poll_ref.ref(this.parent); - } else { + this.allowed_to_exit = !value; + if (this.allowed_to_exit) { this.parent_poll_ref.unref(this.parent); + } else { + this.parent_poll_ref.ref(this.parent); } if (this.vm) |vm| { @@ -404,6 +402,7 @@ pub const WebWorker = struct { } fn requestTerminate(this: *WebWorker) bool { + this.setRef(false); var vm = this.vm orelse { this.requested_terminate = true; return false; diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index 7036babfb3b030..b384048ce74221 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -3943,7 +3943,8 @@ pub const AnyBlob = union(enum) { pub fn isDetached(this: *const AnyBlob) bool { return switch (this.*) { .Blob => |blob| blob.isDetached(), - else => this.slice().len == 0, + .InternalBlob => this.InternalBlob.bytes.items.len == 0, + .WTFStringImpl => this.WTFStringImpl.length() == 0, }; } diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index 2007063f36ca8e..0dea0579d7e693 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -1222,7 +1222,7 @@ pub fn BodyMixin(comptime Type: type) type { if (blob.content_type.len == 0 and blob.store != null) { if (this.getFetchHeaders()) |fetch_headers| { if (fetch_headers.fastGet(.ContentType)) |content_type| { - blob.store.?.mime_type = MimeType.init(content_type.slice()); + blob.store.?.mime_type = MimeType.init(content_type.slice(), null, null); } } else { blob.store.?.mime_type = MimeType.text; diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig index 7a0188aabf8352..4fa0f4ca2bea20 100644 --- a/src/bun.js/webcore/encoding.zig +++ b/src/bun.js/webcore/encoding.zig @@ -866,13 +866,11 @@ pub const Encoder = struct { } 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 str = bun.String.createUninitialized(.latin1, len) orelse return ZigString.init("Out of memory").toErrorInstance(global); - defer str.deref(); @memcpy(@constCast(str.latin1()), input_ptr[0..len]); @@ -903,7 +901,6 @@ pub const Encoder = struct { .hex => { 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); diff --git a/src/bun.js/webcore/request.zig b/src/bun.js/webcore/request.zig index 75d4e63cdf1c81..e2b10401646859 100644 --- a/src/bun.js/webcore/request.zig +++ b/src/bun.js/webcore/request.zig @@ -63,8 +63,7 @@ pub fn InitRequestBodyValue(value: Body.Value) !*BodyValueRef { } // https://developer.mozilla.org/en-US/docs/Web/API/Request pub const Request = struct { - url: []const u8 = "", - url_was_allocated: bool = false, + url: bun.String = bun.String.empty, headers: ?*FetchHeaders = null, signal: ?*AbortSignal = null, @@ -143,7 +142,7 @@ pub const Request = struct { try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("url: ", enable_ansi_colors)); try this.ensureURL(); - try writer.print(comptime Output.prettyFmt("\"{s}\"", enable_ansi_colors), .{this.url}); + try writer.print(comptime Output.prettyFmt("\"{}\"", enable_ansi_colors), .{this.url}); formatter.printComma(Writer, writer, enable_ansi_colors) catch unreachable; try writer.writeAll("\n"); @@ -179,11 +178,10 @@ pub const Request = struct { pub fn fromRequestContext(ctx: *RequestContext) !Request { var req = Request{ - .url = bun.asByteSlice(ctx.getFullURL()), + .url = bun.String.create(ctx.full_url), .body = try InitRequestBodyValue(.{ .Null = {} }), .method = ctx.method, .headers = FetchHeaders.createFromPicoHeaders(ctx.request.headers), - .url_was_allocated = true, }; return req; } @@ -271,9 +269,8 @@ pub const Request = struct { this.headers = null; } - if (this.url_was_allocated) { - bun.default_allocator.free(bun.constStrToU8(this.url)); - } + this.url.deref(); + this.url = bun.String.empty; if (this.signal) |signal| { _ = signal.unref(); @@ -320,12 +317,12 @@ pub const Request = struct { return .zero; }; - return ZigString.init(this.url).withEncoding().toValueGC(globalObject); + return this.url.toJS(globalObject); } pub fn sizeOfURL(this: *const Request) usize { - if (this.url.len > 0) - return this.url.len; + if (this.url.length() > 0) + return this.url.byteSlice().len; if (this.uws_request) |req| { const req_url = req.url(); @@ -352,7 +349,7 @@ pub const Request = struct { } pub fn ensureURL(this: *Request) !void { - if (this.url.len > 0) return; + if (!this.url.isEmpty()) return; if (this.uws_request) |req| { const req_url = req.url(); @@ -362,16 +359,69 @@ pub const Request = struct { .is_https = this.https, .host = host, }; - const url = try std.fmt.allocPrint(bun.default_allocator, "{s}{any}{s}", .{ + const url_bytelength = std.fmt.count("{s}{any}{s}", .{ this.getProtocol(), fmt, req_url, }); + if (comptime Environment.allow_assert) { - std.debug.assert(this.sizeOfURL() == url.len); + std.debug.assert(this.sizeOfURL() == url_bytelength); + } + + if (url_bytelength < 128) { + var buffer: [128]u8 = undefined; + const url = std.fmt.bufPrint(&buffer, "{s}{any}{s}", .{ + this.getProtocol(), + fmt, + req_url, + }) catch @panic("Unexpected error while printing URL"); + + if (comptime Environment.allow_assert) { + std.debug.assert(this.sizeOfURL() == url.len); + } + + var href = bun.JSC.URL.hrefFromString(bun.String.fromBytes(url)); + if (!href.isEmpty()) { + if (href.byteSlice().ptr == url.ptr) { + this.url = bun.String.createLatin1(url[0..href.length()]); + href.deref(); + } else { + this.url = href; + } + } else { + // TODO: what is the right thing to do for invalid URLS? + this.url = bun.String.create(url); + } + + return; + } + + if (strings.isAllASCII(host) and strings.isAllASCII(req_url)) { + this.url = bun.String.createUninitializedLatin1(url_bytelength); + var bytes = @constCast(this.url.byteSlice()); + _ = std.fmt.bufPrint(bytes, "{s}{any}{s}", .{ + this.getProtocol(), + fmt, + req_url, + }) catch @panic("Unexpected error while printing URL"); + } else { + // slow path + var temp_url = std.fmt.allocPrint(bun.default_allocator, "{s}{any}{s}", .{ + this.getProtocol(), + fmt, + req_url, + }) catch unreachable; + defer bun.default_allocator.free(temp_url); + this.url = bun.String.create(temp_url); } - this.url = url; - this.url_was_allocated = true; + + const href = bun.JSC.URL.hrefFromString(this.url); + // TODO: what is the right thing to do for invalid URLS? + if (!href.isEmpty()) { + this.url = href; + } + return; } } @@ -379,8 +429,7 @@ pub const Request = struct { if (comptime Environment.allow_assert) { std.debug.assert(this.sizeOfURL() == req_url.len); } - this.url = try bun.default_allocator.dupe(u8, req_url); - this.url_was_allocated = true; + this.url = bun.String.create(req_url); } } @@ -432,18 +481,13 @@ pub const Request = struct { url_or_object.as(JSC.DOMURL) != null; if (is_first_argument_a_url) { - const slice = arguments[0].toSliceOrNull(globalThis) orelse { + const str = bun.String.tryFromJS(arguments[0], globalThis) orelse { req.finalizeWithoutDeinit(); _ = req.body.unref(); return null; }; - req.url = (slice.cloneIfNeeded(globalThis.allocator()) catch { - req.finalizeWithoutDeinit(); - _ = req.body.unref(); - return null; - }).slice(); - req.url_was_allocated = req.url.len > 0; - if (req.url.len > 0) + req.url = str; + if (!req.url.isEmpty()) fields.insert(.url); } else if (!url_or_object_type.isObject()) { globalThis.throw("Failed to construct 'Request': expected non-empty string or object", .{}); @@ -510,9 +554,8 @@ pub const Request = struct { } if (!fields.contains(.url)) { - if (response.url.len > 0) { - req.url = globalThis.allocator().dupe(u8, response.url) catch unreachable; - req.url_was_allocated = true; + if (!response.url.isEmpty()) { + req.url = response.url; fields.insert(.url); } } @@ -544,29 +587,21 @@ pub const Request = struct { if (!fields.contains(.url)) { if (value.fastGet(globalThis, .url)) |url| { - req.url = (url.toSlice(globalThis, bun.default_allocator).cloneIfNeeded(bun.default_allocator) catch { - return null; - }).slice(); - req.url_was_allocated = req.url.len > 0; - if (req.url.len > 0) + req.url = bun.String.fromJS(url, globalThis); + if (!req.url.isEmpty()) fields.insert(.url); // first value } else if (@intFromEnum(value) == @intFromEnum(values_to_try[values_to_try.len - 1]) and !is_first_argument_a_url and value.implementsToString(globalThis)) { - const slice = value.toSliceOrNull(globalThis) orelse { + const str = bun.String.tryFromJS(value, globalThis) orelse { req.finalizeWithoutDeinit(); _ = req.body.unref(); return null; }; - req.url = (slice.cloneIfNeeded(globalThis.allocator()) catch { - req.finalizeWithoutDeinit(); - _ = req.body.unref(); - return null; - }).slice(); - req.url_was_allocated = req.url.len > 0; - if (req.url.len > 0) + req.url = str; + if (!req.url.isEmpty()) fields.insert(.url); } } @@ -607,20 +642,24 @@ pub const Request = struct { } } - if (req.url.len == 0) { + if (req.url.isEmpty()) { globalThis.throw("Failed to construct 'Request': url is required.", .{}); req.finalizeWithoutDeinit(); _ = req.body.unref(); return null; } - const parsed_url = ZigURL.parse(req.url); - if (parsed_url.hostname.len == 0) { - globalThis.throw("Failed to construct 'Request': Invalid URL (missing a hostname)", .{}); + // Note that the string is going to be ref'd here, so we don't need to ref it above. + const href = JSC.URL.hrefFromString(req.url); + if (href.isEmpty()) { + globalThis.throw("Failed to construct 'Request': Invalid URL \"{}\"", .{ + req.url, + }); req.finalizeWithoutDeinit(); _ = req.body.unref(); return null; } + req.url = href; if (req.body.value == .Blob and req.headers != null and @@ -717,23 +756,18 @@ pub const Request = struct { globalThis: *JSGlobalObject, preserve_url: bool, ) void { + _ = allocator; this.ensureURL() catch {}; var body = InitRequestBodyValue(this.body.value.clone(globalThis)) catch { globalThis.throw("Failed to clone request", .{}); return; }; - - const original_url = req.url; + var original_url = req.url; req.* = Request{ .body = body, - .url = if (preserve_url) original_url else allocator.dupe(u8, this.url) catch { - _ = body.unref(); - globalThis.throw("Failed to clone request", .{}); - return; - }, - .url_was_allocated = if (preserve_url) req.url_was_allocated else true, + .url = if (preserve_url) original_url else this.url.dupeRef(), .method = this.method, .headers = this.cloneHeaders(globalThis), }; diff --git a/src/bun.js/webcore/response.classes.ts b/src/bun.js/webcore/response.classes.ts index f0d6e14515a39b..abd29c6545b9b9 100644 --- a/src/bun.js/webcore/response.classes.ts +++ b/src/bun.js/webcore/response.classes.ts @@ -125,7 +125,7 @@ export default [ JSType: "0b11101110", klass: {}, configurable: false, - structuredClone: { transferrable: false, tag: 254 }, + structuredClone: { transferable: false, tag: 254 }, proto: { text: { fn: "getText" }, json: { fn: "getJSON" }, diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index a70a4f0eeddd20..0d5691a3f0af6d 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -37,6 +37,7 @@ const JSValue = JSC.JSValue; const JSError = JSC.JSError; const JSGlobalObject = JSC.JSGlobalObject; const NullableAllocator = @import("../../nullable_allocator.zig").NullableAllocator; +const DataURL = @import("../../resolver/data_url.zig").DataURL; const VirtualMachine = JSC.VirtualMachine; const Task = JSC.Task; @@ -59,8 +60,8 @@ pub const Response = struct { allocator: std.mem.Allocator, body: Body, - url: string = "", - status_text: string = "", + url: bun.String = bun.String.empty, + status_text: bun.String = bun.String.empty, redirected: bool = false, // We must report a consistent value for this @@ -85,7 +86,7 @@ pub const Response = struct { return this.reported_estimated_size orelse brk: { this.reported_estimated_size = @as( u63, - @intCast(this.body.value.estimatedSize() + this.url.len + this.status_text.len + @sizeOf(Response)), + @intCast(this.body.value.estimatedSize() + this.url.byteSlice().len + this.status_text.byteSlice().len + @sizeOf(Response)), ); break :brk this.reported_estimated_size.?; }; @@ -135,7 +136,7 @@ pub const Response = struct { try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("url: \"", enable_ansi_colors)); - try writer.print(comptime Output.prettyFmt("{s}", enable_ansi_colors), .{this.url}); + try writer.print(comptime Output.prettyFmt("{}", enable_ansi_colors), .{this.url}); try writer.writeAll("\""); formatter.printComma(Writer, writer, enable_ansi_colors) catch unreachable; try writer.writeAll("\n"); @@ -148,7 +149,7 @@ pub const Response = struct { try formatter.writeIndent(Writer, writer); try writer.writeAll(comptime Output.prettyFmt("statusText: ", enable_ansi_colors)); - try JSPrinter.writeJSONString(this.status_text, Writer, writer, .ascii); + try writer.print(comptime Output.prettyFmt("\"{}\"", enable_ansi_colors), .{this.status_text}); formatter.printComma(Writer, writer, enable_ansi_colors) catch unreachable; try writer.writeAll("\n"); @@ -175,7 +176,7 @@ pub const Response = struct { globalThis: *JSC.JSGlobalObject, ) callconv(.C) JSC.JSValue { // https://developer.mozilla.org/en-US/docs/Web/API/Response/url - return ZigString.init(this.url).toValueGC(globalThis); + return this.url.toJS(globalThis); } pub fn getResponseType( @@ -194,7 +195,7 @@ pub const Response = struct { globalThis: *JSC.JSGlobalObject, ) callconv(.C) JSC.JSValue { // https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText - return ZigString.init(this.status_text).withEncoding().toValueGC(globalThis); + return this.status_text.toJS(globalThis); } pub fn getRedirected( @@ -241,12 +242,7 @@ pub const Response = struct { _: *JSC.CallFrame, ) callconv(.C) JSValue { var cloned = this.clone(getAllocator(globalThis), globalThis); - const val = Response.makeMaybePooled(globalThis, cloned); - if (this.body.init.headers) |headers| { - cloned.body.init.headers = headers.cloneThis(globalThis); - } - - return val; + return Response.makeMaybePooled(globalThis, cloned); } pub fn makeMaybePooled(globalObject: *JSC.JSGlobalObject, ptr: *Response) JSValue { @@ -262,8 +258,8 @@ pub const Response = struct { new_response.* = Response{ .allocator = allocator, .body = this.body.clone(globalThis), - .url = allocator.dupe(u8, this.url) catch unreachable, - .status_text = allocator.dupe(u8, this.status_text) catch unreachable, + .url = this.url.clone(), + .status_text = this.status_text.clone(), .redirected = this.redirected, }; } @@ -289,13 +285,8 @@ pub const Response = struct { var allocator = this.allocator; - if (this.status_text.len > 0) { - allocator.free(this.status_text); - } - - if (this.url.len > 0) { - allocator.free(this.url); - } + this.status_text.deref(); + this.url.deref(); allocator.destroy(this); } @@ -381,7 +372,7 @@ pub const Response = struct { .value = .{ .Empty = {} }, }, .allocator = getAllocator(globalThis), - .url = "", + .url = bun.String.empty, }; const json_value = args.nextEat() orelse JSC.JSValue.zero; @@ -443,7 +434,7 @@ pub const Response = struct { .value = .{ .Empty = {} }, }, .allocator = getAllocator(globalThis), - .url = "", + .url = bun.String.empty, }; const url_string_value = args.nextEat() orelse JSC.JSValue.zero; @@ -487,7 +478,6 @@ pub const Response = struct { .value = .{ .Empty = {} }, }, .allocator = getAllocator(globalThis), - .url = "", }; return response.toJS(globalThis); @@ -534,7 +524,6 @@ pub const Response = struct { response.* = Response{ .body = body, .allocator = getAllocator(globalThis), - .url = "", }; if (response.body.value == .Blob and @@ -821,8 +810,8 @@ pub const Fetch = struct { const http_response = this.result.response; return Response{ .allocator = allocator, - .url = allocator.dupe(u8, this.result.href) catch unreachable, - .status_text = allocator.dupe(u8, http_response.status) catch unreachable, + .url = bun.String.createAtomIfPossible(this.result.href), + .status_text = bun.String.createAtomIfPossible(http_response.status), .redirected = this.result.redirected, .body = .{ .init = .{ @@ -983,6 +972,45 @@ pub const Fetch = struct { } }; + fn dataURLResponse( + _data_url: DataURL, + globalThis: *JSGlobalObject, + allocator: std.mem.Allocator, + ) JSValue { + var data_url = _data_url; + + const data = data_url.decodeData(allocator) catch { + const err = JSC.createError(globalThis, "failed to fetch the data URL", .{}); + return JSPromise.rejectedPromiseValue(globalThis, err); + }; + var blob = Blob.init(data, allocator, globalThis); + + var allocated = false; + const mime_type = bun.HTTP.MimeType.init(data_url.mime_type, allocator, &allocated); + blob.content_type = mime_type.value; + if (allocated) { + blob.content_type_allocated = true; + } + + var response = allocator.create(Response) catch @panic("out of memory"); + + response.* = Response{ + .body = Body{ + .init = Body.Init{ + .status_code = 200, + }, + .value = .{ + .Blob = blob, + }, + }, + .allocator = allocator, + .status_text = bun.String.createAtom("OK"), + .url = data_url.url.dupeRef(), + }; + + return JSPromise.resolvedPromiseValue(globalThis, response.toJS(globalThis)); + } + pub export fn Bun__fetch( ctx: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, @@ -1034,13 +1062,14 @@ pub const Fetch = struct { var hostname: ?[]u8 = null; var url_proxy_buffer: []const u8 = undefined; + var is_file_url = false; // TODO: move this into a DRYer implementation // The status quo is very repetitive and very bug prone if (first_arg.as(Request)) |request| { request.ensureURL() catch unreachable; - if (request.url.len == 0) { + if (request.url.isEmpty()) { const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, fetch_error_blank_url, .{}, ctx); // clean hostname if any if (hostname) |host| { @@ -1049,7 +1078,20 @@ pub const Fetch = struct { return JSPromise.rejectedPromiseValue(globalThis, err); } - url = ZigURL.fromUTF8(bun.default_allocator, request.url) catch { + if (request.url.hasPrefixComptime("data:")) { + var url_slice = request.url.toUTF8WithoutRef(bun.default_allocator); + defer url_slice.deinit(); + + var data_url = DataURL.parseWithoutCheck(url_slice.slice()) catch { + const err = JSC.createError(globalThis, "failed to fetch the data URL", .{}); + return JSPromise.rejectedPromiseValue(globalThis, err); + }; + + data_url.url = request.url; + return dataURLResponse(data_url, globalThis, bun.default_allocator); + } + + url = ZigURL.fromString(bun.default_allocator, request.url) catch { const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, "fetch() URL is invalid", .{}, ctx); // clean hostname if any if (hostname) |host| { @@ -1061,127 +1103,131 @@ pub const Fetch = struct { err, ); }; + is_file_url = url.isFile(); url_proxy_buffer = url.href; - - if (args.nextEat()) |options| { - if (options.isObject() or options.jsType() == .DOMWrapper) { - if (options.fastGet(ctx.ptr(), .method)) |method_| { - var slice_ = method_.toSlice(ctx.ptr(), getAllocator(ctx)); - defer slice_.deinit(); - method = Method.which(slice_.slice()) orelse .GET; - } else { - method = request.method; - } - - if (options.fastGet(ctx.ptr(), .body)) |body__| { - if (Body.Value.fromJS(ctx.ptr(), body__)) |body_const| { - var body_value = body_const; - // TODO: buffer ReadableStream? - // we have to explicitly check for InternalBlob - body = body_value.useAsAnyBlob(); + if (!is_file_url) { + if (args.nextEat()) |options| { + if (options.isObject() or options.jsType() == .DOMWrapper) { + if (options.fastGet(ctx.ptr(), .method)) |method_| { + var slice_ = method_.toSlice(ctx.ptr(), getAllocator(ctx)); + defer slice_.deinit(); + method = Method.which(slice_.slice()) orelse .GET; } else { - // clean hostname if any - if (hostname) |host| { - bun.default_allocator.free(host); - } - // an error was thrown - return JSC.JSValue.jsUndefined(); + method = request.method; } - } else { - body = request.body.value.useAsAnyBlob(); - } - if (options.fastGet(ctx.ptr(), .headers)) |headers_| { - if (headers_.as(FetchHeaders)) |headers__| { - if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { - hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + if (options.fastGet(ctx.ptr(), .body)) |body__| { + if (Body.Value.fromJS(ctx.ptr(), body__)) |body_const| { + var body_value = body_const; + // TODO: buffer ReadableStream? + // we have to explicitly check for InternalBlob + body = body_value.useAsAnyBlob(); + } else { + // clean hostname if any + if (hostname) |host| { + bun.default_allocator.free(host); + } + // an error was thrown + return JSC.JSValue.jsUndefined(); } - headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; - // TODO: make this one pass - } else if (FetchHeaders.createFromJS(ctx.ptr(), headers_)) |headers__| { - if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { - hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } else { + body = request.body.value.useAsAnyBlob(); + } + + if (options.fastGet(ctx.ptr(), .headers)) |headers_| { + if (headers_.as(FetchHeaders)) |headers__| { + if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { + hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } + headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; + // TODO: make this one pass + } else if (FetchHeaders.createFromJS(ctx.ptr(), headers_)) |headers__| { + if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { + hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } + headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; + headers__.deref(); + } else if (request.headers) |head| { + if (head.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { + hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } + headers = Headers.from(head, bun.default_allocator, .{ .body = &body }) catch unreachable; } - headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; - headers__.deref(); } else if (request.headers) |head| { - if (head.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { - hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; - } headers = Headers.from(head, bun.default_allocator, .{ .body = &body }) catch unreachable; } - } else if (request.headers) |head| { - headers = Headers.from(head, bun.default_allocator, .{ .body = &body }) catch unreachable; - } - if (options.get(ctx, "timeout")) |timeout_value| { - if (timeout_value.isBoolean()) { - disable_timeout = !timeout_value.asBoolean(); - } else if (timeout_value.isNumber()) { - disable_timeout = timeout_value.to(i32) == 0; + if (options.get(ctx, "timeout")) |timeout_value| { + if (timeout_value.isBoolean()) { + disable_timeout = !timeout_value.asBoolean(); + } else if (timeout_value.isNumber()) { + disable_timeout = timeout_value.to(i32) == 0; + } } - } - if (options.getOptionalEnum(ctx, "redirect", FetchRedirect) catch { - return .zero; - }) |redirect_value| { - redirect_type = redirect_value; - } + if (options.getOptionalEnum(ctx, "redirect", FetchRedirect) catch { + return .zero; + }) |redirect_value| { + redirect_type = redirect_value; + } - if (options.get(ctx, "keepalive")) |keepalive_value| { - if (keepalive_value.isBoolean()) { - disable_keepalive = !keepalive_value.asBoolean(); - } else if (keepalive_value.isNumber()) { - disable_keepalive = keepalive_value.to(i32) == 0; + if (options.get(ctx, "keepalive")) |keepalive_value| { + if (keepalive_value.isBoolean()) { + disable_keepalive = !keepalive_value.asBoolean(); + } else if (keepalive_value.isNumber()) { + disable_keepalive = keepalive_value.to(i32) == 0; + } } - } - if (options.get(globalThis, "verbose")) |verb| { - verbose = verb.toBoolean(); - } - if (options.get(globalThis, "signal")) |signal_arg| { - if (signal_arg.as(JSC.WebCore.AbortSignal)) |signal_| { - _ = signal_.ref(); - signal = signal_; + if (options.get(globalThis, "verbose")) |verb| { + verbose = verb.toBoolean(); + } + if (options.get(globalThis, "signal")) |signal_arg| { + if (signal_arg.as(JSC.WebCore.AbortSignal)) |signal_| { + _ = signal_.ref(); + signal = signal_; + } } - } - if (options.get(globalThis, "proxy")) |proxy_arg| { - if (proxy_arg.isString() and proxy_arg.getLength(ctx) > 0) { - var href = JSC.URL.hrefFromJS(proxy_arg, globalThis); - if (href.tag == .Dead) { - const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, "fetch() proxy URL is invalid", .{}, ctx); - // clean hostname if any - if (hostname) |host| { - bun.default_allocator.free(host); + if (options.get(globalThis, "proxy")) |proxy_arg| { + if (proxy_arg.isString() and proxy_arg.getLength(ctx) > 0) { + var href = JSC.URL.hrefFromJS(proxy_arg, globalThis); + if (href.tag == .Dead) { + const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, "fetch() proxy URL is invalid", .{}, ctx); + // clean hostname if any + if (hostname) |host| { + bun.default_allocator.free(host); + } + bun.default_allocator.free(url_proxy_buffer); + + return JSPromise.rejectedPromiseValue(globalThis, err); } + defer href.deref(); + var buffer = std.fmt.allocPrint(bun.default_allocator, "{s}{}", .{ url_proxy_buffer, href }) catch { + globalThis.throwOutOfMemory(); + return .zero; + }; + url = ZigURL.parse(buffer[0..url.href.len]); + is_file_url = url.isFile(); + + proxy = ZigURL.parse(buffer[url.href.len..]); bun.default_allocator.free(url_proxy_buffer); - - return JSPromise.rejectedPromiseValue(globalThis, err); + url_proxy_buffer = buffer; } - defer href.deref(); - var buffer = std.fmt.allocPrint(bun.default_allocator, "{s}{}", .{ url_proxy_buffer, href }) catch { - globalThis.throwOutOfMemory(); - return .zero; - }; - url = ZigURL.parse(buffer[0..url.href.len]); - proxy = ZigURL.parse(buffer[url.href.len..]); - bun.default_allocator.free(url_proxy_buffer); - url_proxy_buffer = buffer; } } - } - } else { - method = request.method; - body = request.body.value.useAsAnyBlob(); - if (request.headers) |head| { - if (head.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { - hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } else { + method = request.method; + body = request.body.value.useAsAnyBlob(); + if (request.headers) |head| { + if (head.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { + hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } + headers = Headers.from(head, bun.default_allocator, .{ .body = &body }) catch unreachable; + } + if (request.signal) |signal_| { + _ = signal_.ref(); + signal = signal_; } - headers = Headers.from(head, bun.default_allocator, .{ .body = &body }) catch unreachable; - } - if (request.signal) |signal_| { - _ = signal_.ref(); - signal = signal_; } } } else if (bun.String.tryFromJS(first_arg, globalThis)) |str| { @@ -1194,6 +1240,19 @@ pub const Fetch = struct { return JSPromise.rejectedPromiseValue(globalThis, err); } + if (str.hasPrefixComptime("data:")) { + var url_slice = str.toUTF8WithoutRef(bun.default_allocator); + defer url_slice.deinit(); + + var data_url = DataURL.parseWithoutCheck(url_slice.slice()) catch { + const err = JSC.createError(globalThis, "failed to fetch the data URL", .{}); + return JSPromise.rejectedPromiseValue(globalThis, err); + }; + data_url.url = str; + + return dataURLResponse(data_url, globalThis, bun.default_allocator); + } + url = ZigURL.fromString(bun.default_allocator, str) catch { // clean hostname if any if (hostname) |host| { @@ -1203,105 +1262,108 @@ pub const Fetch = struct { return JSPromise.rejectedPromiseValue(globalThis, err); }; url_proxy_buffer = url.href; + is_file_url = url.isFile(); + + if (!is_file_url) { + if (args.nextEat()) |options| { + if (options.isObject() or options.jsType() == .DOMWrapper) { + if (options.fastGet(ctx.ptr(), .method)) |method_| { + var slice_ = method_.toSlice(ctx.ptr(), getAllocator(ctx)); + defer slice_.deinit(); + method = Method.which(slice_.slice()) orelse .GET; + } - if (args.nextEat()) |options| { - if (options.isObject() or options.jsType() == .DOMWrapper) { - if (options.fastGet(ctx.ptr(), .method)) |method_| { - var slice_ = method_.toSlice(ctx.ptr(), getAllocator(ctx)); - defer slice_.deinit(); - method = Method.which(slice_.slice()) orelse .GET; - } - - if (options.fastGet(ctx.ptr(), .body)) |body__| { - if (Body.Value.fromJS(ctx.ptr(), body__)) |body_const| { - var body_value = body_const; - // TODO: buffer ReadableStream? - // we have to explicitly check for InternalBlob - body = body_value.useAsAnyBlob(); - } else { - // clean hostname if any - if (hostname) |host| { - bun.default_allocator.free(host); + if (options.fastGet(ctx.ptr(), .body)) |body__| { + if (Body.Value.fromJS(ctx.ptr(), body__)) |body_const| { + var body_value = body_const; + // TODO: buffer ReadableStream? + // we have to explicitly check for InternalBlob + body = body_value.useAsAnyBlob(); + } else { + // clean hostname if any + if (hostname) |host| { + bun.default_allocator.free(host); + } + // an error was thrown + return JSC.JSValue.jsUndefined(); } - // an error was thrown - return JSC.JSValue.jsUndefined(); } - } - if (options.fastGet(ctx.ptr(), .headers)) |headers_| { - if (headers_.as(FetchHeaders)) |headers__| { - if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { - hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; - } - headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; - // TODO: make this one pass - } else if (FetchHeaders.createFromJS(ctx.ptr(), headers_)) |headers__| { - defer headers__.deref(); - if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { - hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + if (options.fastGet(ctx.ptr(), .headers)) |headers_| { + if (headers_.as(FetchHeaders)) |headers__| { + if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { + hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } + headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; + // TODO: make this one pass + } else if (FetchHeaders.createFromJS(ctx.ptr(), headers_)) |headers__| { + defer headers__.deref(); + if (headers__.fastGet(JSC.FetchHeaders.HTTPHeaderName.Host)) |_hostname| { + hostname = _hostname.toOwnedSliceZ(bun.default_allocator) catch unreachable; + } + headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; + } else { + // Converting the headers failed; return null and + // let the set exception get thrown + return .zero; } - headers = Headers.from(headers__, bun.default_allocator, .{ .body = &body }) catch unreachable; - } else { - // Converting the headers failed; return null and - // let the set exception get thrown - return .zero; } - } - if (options.get(ctx, "timeout")) |timeout_value| { - if (timeout_value.isBoolean()) { - disable_timeout = !timeout_value.asBoolean(); - } else if (timeout_value.isNumber()) { - disable_timeout = timeout_value.to(i32) == 0; + if (options.get(ctx, "timeout")) |timeout_value| { + if (timeout_value.isBoolean()) { + disable_timeout = !timeout_value.asBoolean(); + } else if (timeout_value.isNumber()) { + disable_timeout = timeout_value.to(i32) == 0; + } } - } - if (options.getOptionalEnum(ctx, "redirect", FetchRedirect) catch { - return .zero; - }) |redirect_value| { - redirect_type = redirect_value; - } + if (options.getOptionalEnum(ctx, "redirect", FetchRedirect) catch { + return .zero; + }) |redirect_value| { + redirect_type = redirect_value; + } - if (options.get(ctx, "keepalive")) |keepalive_value| { - if (keepalive_value.isBoolean()) { - disable_keepalive = !keepalive_value.asBoolean(); - } else if (keepalive_value.isNumber()) { - disable_keepalive = keepalive_value.to(i32) == 0; + if (options.get(ctx, "keepalive")) |keepalive_value| { + if (keepalive_value.isBoolean()) { + disable_keepalive = !keepalive_value.asBoolean(); + } else if (keepalive_value.isNumber()) { + disable_keepalive = keepalive_value.to(i32) == 0; + } } - } - if (options.get(globalThis, "verbose")) |verb| { - verbose = verb.toBoolean(); - } - if (options.get(globalThis, "signal")) |signal_arg| { - if (signal_arg.as(JSC.WebCore.AbortSignal)) |signal_| { - _ = signal_.ref(); - signal = signal_; + if (options.get(globalThis, "verbose")) |verb| { + verbose = verb.toBoolean(); + } + if (options.get(globalThis, "signal")) |signal_arg| { + if (signal_arg.as(JSC.WebCore.AbortSignal)) |signal_| { + _ = signal_.ref(); + signal = signal_; + } } - } - if (options.getTruthy(globalThis, "proxy")) |proxy_arg| { - if (proxy_arg.isString() and proxy_arg.getLength(globalThis) > 0) { - var href = JSC.URL.hrefFromJS(proxy_arg, globalThis); - if (href.tag == .Dead) { - const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, "fetch() proxy URL is invalid", .{}, ctx); - // clean hostname if any - if (hostname) |host| { - bun.default_allocator.free(host); + if (options.getTruthy(globalThis, "proxy")) |proxy_arg| { + if (proxy_arg.isString() and proxy_arg.getLength(globalThis) > 0) { + var href = JSC.URL.hrefFromJS(proxy_arg, globalThis); + if (href.tag == .Dead) { + const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, "fetch() proxy URL is invalid", .{}, ctx); + // clean hostname if any + if (hostname) |host| { + bun.default_allocator.free(host); + } + bun.default_allocator.free(url_proxy_buffer); + + return JSPromise.rejectedPromiseValue(globalThis, err); } + defer href.deref(); + var buffer = std.fmt.allocPrint(bun.default_allocator, "{s}{}", .{ url_proxy_buffer, href }) catch { + globalThis.throwOutOfMemory(); + return .zero; + }; + url = ZigURL.parse(buffer[0..url.href.len]); + proxy = ZigURL.parse(buffer[url.href.len..]); bun.default_allocator.free(url_proxy_buffer); - - return JSPromise.rejectedPromiseValue(globalThis, err); + url_proxy_buffer = buffer; } - defer href.deref(); - var buffer = std.fmt.allocPrint(bun.default_allocator, "{s}{}", .{ url_proxy_buffer, href }) catch { - globalThis.throwOutOfMemory(); - return .zero; - }; - url = ZigURL.parse(buffer[0..url.href.len]); - proxy = ZigURL.parse(buffer[url.href.len..]); - bun.default_allocator.free(url_proxy_buffer); - url_proxy_buffer = buffer; } } } @@ -1318,14 +1380,73 @@ pub const Fetch = struct { return JSPromise.rejectedPromiseValue(globalThis, err); } + // This is not 100% correct. + // We don't pass along headers, we ignore method, we ignore status code... + // But it's better than status quo. + if (is_file_url) { + defer bun.default_allocator.free(url_proxy_buffer); + var path_buf: [bun.MAX_PATH_BYTES]u8 = undefined; + const PercentEncoding = @import("../../url.zig").PercentEncoding; + var path_buf2: [bun.MAX_PATH_BYTES]u8 = undefined; + var stream = std.io.fixedBufferStream(&path_buf2); + const url_path_decoded = path_buf2[0 .. PercentEncoding.decode( + @TypeOf(&stream.writer()), + &stream.writer(), + url.path, + ) catch { + globalThis.throwOutOfMemory(); + return .zero; + }]; + const temp_file_path = bun.path.joinAbsStringBuf( + globalThis.bunVM().bundler.fs.top_level_dir, + &path_buf, + &[_]string{ + globalThis.bunVM().main, + "../", + url_path_decoded, + }, + .auto, + ); + var file_url_string = JSC.URL.fileURLFromString(bun.String.fromUTF8(temp_file_path)); + defer file_url_string.deref(); + + const bun_file = Blob.findOrCreateFileFromPath( + .{ + .path = .{ + .string = bun.PathString.init( + temp_file_path, + ), + }, + }, + globalThis, + ); + + var response = bun.default_allocator.create(Response) catch @panic("out of memory"); + + response.* = Response{ + .body = Body{ + .init = Body.Init{ + .status_code = 200, + }, + .value = .{ .Blob = bun_file }, + }, + .allocator = bun.default_allocator, + .url = file_url_string.clone(), + }; + + return JSPromise.resolvedPromiseValue(globalThis, response.toJS(globalThis)); + } + if (url.protocol.len > 0) { if (!(url.isHTTP() or url.isHTTPS())) { + defer bun.default_allocator.free(url_proxy_buffer); const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, "protocol must be http: or https:", .{}, ctx); return JSPromise.rejectedPromiseValue(globalThis, err); } } if (!method.hasRequestBody() and body.size() > 0) { + defer bun.default_allocator.free(url_proxy_buffer); const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, fetch_error_unexpected_body, .{}, ctx); return JSPromise.rejectedPromiseValue(globalThis, err); } diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index 5dc4ea830e25e9..f2c5914ef6e98d 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -4433,6 +4433,10 @@ pub const FileReader = struct { var readable_file = File{ .loop = this.globalThis().bunVM().eventLoop() }; const result = readable_file.start(&blob.data.file); + if (result == .empty) { + this.lazy_readable = .{ .empty = {} }; + return result; + } if (result != .ready) { return result; } diff --git a/src/bun.zig b/src/bun.zig index 494e49cb4fd7f9..b274efaaf385e9 100644 --- a/src/bun.zig +++ b/src/bun.zig @@ -24,7 +24,7 @@ pub const huge_allocator_threshold: comptime_int = @import("./memory_allocator.z /// FileSystem is a singleton. pub const fs_allocator = default_allocator; -pub const C = @import("c.zig"); +pub const C = @import("root").C; pub const sha = @import("./sha.zig"); pub const FeatureFlags = @import("feature_flags.zig"); pub const meta = @import("./meta.zig"); @@ -486,8 +486,12 @@ pub fn copy(comptime Type: type, dest: []Type, src: []const Type) void { if (!does_input_or_output_overlap) { @memcpy(output[0..input.len], input); - } else { + } else if (comptime Environment.isNative) { C.memmove(output.ptr, input.ptr, input.len); + } else { + for (input, output) |input_byte, *out| { + out.* = input_byte; + } } } @@ -700,7 +704,7 @@ pub const invalid_fd = std.math.maxInt(FileDescriptor); pub const simdutf = @import("./bun.js/bindings/bun-simdutf.zig"); -pub const JSC = @import("./jsc.zig"); +pub const JSC = @import("root").JavaScriptCore; pub const AsyncIO = @import("async_io"); pub const logger = @import("./logger.zig"); @@ -725,10 +729,42 @@ pub const MimallocArena = @import("./mimalloc_arena.zig").Arena; /// This wrapper exists to avoid the call to sliceTo(0) /// Zig's sliceTo(0) is scalar pub fn getenvZ(path_: [:0]const u8) ?[]const u8 { + if (comptime !Environment.isNative) { + return null; + } + const ptr = std.c.getenv(path_.ptr) orelse return null; return sliceTo(ptr, 0); } +//TODO: add windows support +pub const FDHashMapContext = struct { + pub fn hash(_: @This(), fd: FileDescriptor) u64 { + return @as(u64, @intCast(fd)); + } + pub fn eql(_: @This(), a: FileDescriptor, b: FileDescriptor) bool { + return a == b; + } + pub fn pre(input: FileDescriptor) Prehashed { + return Prehashed{ + .value = @This().hash(.{}, input), + .input = input, + }; + } + + pub const Prehashed = struct { + value: u64, + input: FileDescriptor, + pub fn hash(this: @This(), fd: FileDescriptor) u64 { + if (fd == this.input) return this.value; + return @as(u64, @intCast(fd)); + } + + pub fn eql(_: @This(), a: FileDescriptor, b: FileDescriptor) bool { + return a == b; + } + }; +}; // These wrappers exist to use our strings.eqlLong function pub const StringArrayHashMapContext = struct { pub fn hash(_: @This(), s: []const u8) u32 { @@ -831,11 +867,18 @@ pub fn StringHashMapUnmanaged(comptime Type: type) type { return std.HashMapUnmanaged([]const u8, Type, StringHashMapContext, std.hash_map.default_max_load_percentage); } +pub fn FDHashMap(comptime Type: type) type { + return std.HashMap(StoredFileDescriptorType, Type, FDHashMapContext, std.hash_map.default_max_load_percentage); +} + const CopyFile = @import("./copy_file.zig"); pub const copyFileRange = CopyFile.copyFileRange; pub const copyFile = CopyFile.copyFile; pub fn parseDouble(input: []const u8) !f64 { + if (comptime Environment.isWasm) { + return try std.fmt.parseFloat(f64, input); + } return JSC.WTF.parseDouble(input); } @@ -1155,7 +1198,10 @@ pub const MultiArrayList = @import("./multi_array_list.zig").MultiArrayList; pub const Joiner = @import("./string_joiner.zig"); pub const renamer = @import("./renamer.zig"); -pub const sourcemap = @import("./sourcemap/sourcemap.zig"); +pub const sourcemap = struct { + pub usingnamespace @import("./sourcemap/sourcemap.zig"); + pub usingnamespace @import("./sourcemap/CodeCoverage.zig"); +}; pub fn asByteSlice(buffer: anytype) []const u8 { return switch (@TypeOf(buffer)) { @@ -1539,3 +1585,5 @@ pub const WTF = struct { pub const ArenaAllocator = @import("./ArenaAllocator.zig").ArenaAllocator; pub const Wyhash = @import("./wyhash.zig").Wyhash; + +pub const RegularExpression = @import("./bun.js/bindings/RegularExpression.zig").RegularExpression; diff --git a/src/bun_js.zig b/src/bun_js.zig index 79f1c25960c493..6bbf093aeb3273 100644 --- a/src/bun_js.zig +++ b/src/bun_js.zig @@ -129,8 +129,7 @@ pub const Run = struct { vm.global.vm().holdAPILock(&run, callback); } - pub fn boot(ctx_: Command.Context, file: std.fs.File, entry_path: string) !void { - _ = file; + pub fn boot(ctx_: Command.Context, entry_path: string) !void { var ctx = ctx_; JSC.markBinding(@src()); bun.JSC.initialize(); @@ -241,6 +240,11 @@ pub const Run = struct { if (this.ctx.debug.hot_reload != .none) { JSC.HotReloader.enableHotModuleReloading(vm); } + + if (strings.eqlComptime(this.entry_path, ".") and vm.bundler.fs.top_level_dir.len > 0) { + this.entry_path = vm.bundler.fs.top_level_dir; + } + if (vm.loadEntryPoint(this.entry_path)) |promise| { if (promise.status(vm.global.vm()) == .Rejected) { vm.runErrorHandler(promise.result(vm.global.vm()), null); diff --git a/src/bundler.zig b/src/bundler.zig index c1209e7c6d762a..b3e62a43d83ffe 100644 --- a/src/bundler.zig +++ b/src/bundler.zig @@ -668,45 +668,7 @@ pub const Bundler = struct { } } - // if you pass just a directory, activate the router configured for the pages directory - // for now: - // - "." is not supported - // - multiple pages directories is not supported - if (!this.options.routes.routes_enabled and this.options.entry_points.len == 1 and !this.options.serve) { - - // When inferring: - // - pages directory with a file extension is not supported. e.g. "pages.app/" won't work. - // This is a premature optimization to avoid this magical auto-detection we do here from meaningfully increasing startup time if you're just passing a file - // readDirInfo is a recursive lookup, top-down instead of bottom-up. It opens each folder handle and potentially reads the package.jsons - // So it is not fast! Unless it's already cached. - var paths = [_]string{std.mem.trimLeft(u8, this.options.entry_points[0], "./")}; - if (std.mem.indexOfScalar(u8, paths[0], '.') == null) { - var pages_dir_buf: [bun.MAX_PATH_BYTES]u8 = undefined; - var entry = this.fs.absBuf(&paths, &pages_dir_buf); - - if (std.fs.path.extension(entry).len == 0) { - bun.constStrToU8(entry).ptr[entry.len] = '/'; - - // Only throw if they actually passed in a route config and the directory failed to load - var dir_info_ = this.resolver.readDirInfo(entry) catch return; - var dir_info = dir_info_ orelse return; - - this.options.routes.dir = dir_info.abs_path; - this.options.routes.extensions = options.RouteConfig.DefaultExtensions[0..]; - this.options.routes.routes_enabled = true; - this.router = try Router.init(this.fs, this.allocator, this.options.routes); - try this.router.?.loadRoutes( - this.log, - dir_info, - Resolver, - &this.resolver, - this.fs.top_level_dir, - ); - this.router.?.routes.client_framework_enabled = this.options.isFrontendFrameworkEnabled(); - return; - } - } - } else if (this.options.routes.routes_enabled) { + if (this.options.routes.routes_enabled) { var dir_info_ = try this.resolver.readDirInfo(this.options.routes.dir); var dir_info = dir_info_ orelse return error.MissingRoutesDir; @@ -1296,7 +1258,6 @@ pub const Bundler = struct { macro_js_ctx: MacroJSValueType = default_macro_js_value, virtual_source: ?*const logger.Source = null, replace_exports: runtime.Runtime.Features.ReplaceableExport.Map = .{}, - hoist_bun_plugin: bool = false, inject_jest_globals: bool = false, dont_bundle_twice: bool = false, @@ -1316,6 +1277,22 @@ pub const Bundler = struct { this_parse: ParseOptions, client_entry_point_: anytype, comptime return_file_only: bool, + ) ?ParseResult { + return parseMaybeReturnFileOnlyAllowSharedBuffer( + bundler, + this_parse, + client_entry_point_, + return_file_only, + false, + ); + } + + pub fn parseMaybeReturnFileOnlyAllowSharedBuffer( + bundler: *Bundler, + this_parse: ParseOptions, + client_entry_point_: anytype, + comptime return_file_only: bool, + comptime use_shared_buffer: bool, ) ?ParseResult { var allocator = this_parse.allocator; const dirname_fd = this_parse.dirname_fd; @@ -1345,11 +1322,12 @@ pub const Bundler = struct { break :brk logger.Source.initPathString(path.text, ""); } - const entry = bundler.resolver.caches.fs.readFile( + const entry = bundler.resolver.caches.fs.readFileWithAllocator( + if (use_shared_buffer) bun.fs_allocator else this_parse.allocator, bundler.fs, path.text, dirname_fd, - true, + use_shared_buffer, file_descriptor, ) catch |err| { bundler.log.addErrorFmt(null, logger.Loc.Empty, bundler.allocator, "{s} reading \"{s}\"", .{ @errorName(err), path.text }) catch {}; @@ -1433,7 +1411,6 @@ pub const Bundler = struct { strings.eqlComptime(jsx.import_source.production, "react/jsx-runtime"); opts.features.jsx_optimization_hoist = bundler.options.jsx_optimization_hoist orelse opts.features.jsx_optimization_inline; - opts.features.hoist_bun_plugin = this_parse.hoist_bun_plugin; opts.features.inject_jest_globals = this_parse.inject_jest_globals; opts.features.minify_syntax = bundler.options.minify_syntax; opts.features.minify_identifiers = bundler.options.minify_identifiers; diff --git a/src/bundler/bundle_v2.zig b/src/bundler/bundle_v2.zig index dae63a60fdd82e..db1f57c8a10369 100644 --- a/src/bundler/bundle_v2.zig +++ b/src/bundler/bundle_v2.zig @@ -1862,13 +1862,6 @@ pub const BundleV2 = struct { continue; } - if (JSC.DisabledModule.has(import_record.path.text)) { - import_record.path.is_disabled = true; - import_record.do_commonjs_transform_in_printer = true; - import_record.source_index = Index.invalid; - continue; - } - if (this.bundler.options.rewrite_jest_for_tests) { if (strings.eqlComptime( import_record.path.text, diff --git a/src/bundler/entry_points.zig b/src/bundler/entry_points.zig index cf961817aa8f4f..5e8310d92728c1 100644 --- a/src/bundler/entry_points.zig +++ b/src/bundler/entry_points.zig @@ -183,7 +183,7 @@ pub const ServerEntryPoint = struct { if (is_hot_reload_enabled) { break :brk try std.fmt.allocPrint( allocator, - \\//Auto-generated file + \\// @bun \\var hmrSymbol = Symbol.for("BunServerHMR"); \\import * as start from '{s}{s}'; \\var entryNamespace = start; @@ -195,7 +195,7 @@ pub const ServerEntryPoint = struct { \\ server.reload(entryNamespace.default); \\ }} else {{ \\ server = globalThis[hmrSymbol] = Bun.serve(entryNamespace.default); - \\ console.debug(`Started server ${{server.protocol}}//${{server.hostname}}:${{server.port}}`); + \\ console.debug(`Started server ${{server.protocol}}://${{server.hostname}}:${{server.port}}`); \\ }} \\ }} \\ }}, reportError); @@ -205,7 +205,7 @@ pub const ServerEntryPoint = struct { \\ server.reload(entryNamespace.default); \\ }} else {{ \\ server = globalThis[hmrSymbol] = Bun.serve(entryNamespace.default); - \\ console.debug(`Started server ${{server.protocol}}//${{server.hostname}}:${{server.port}}`); + \\ console.debug(`Started server ${{server.protocol}}://${{server.hostname}}:${{server.port}}`); \\ }} \\}} \\ @@ -218,7 +218,7 @@ pub const ServerEntryPoint = struct { } break :brk try std.fmt.allocPrint( allocator, - \\//Auto-generated file + \\// @bun \\import * as start from '{s}{s}'; \\var entryNamespace = start; \\if (typeof entryNamespace?.then === 'function') {{ diff --git a/src/bunfig.zig b/src/bunfig.zig index 7302907d929e16..050c603deff34e 100644 --- a/src/bunfig.zig +++ b/src/bunfig.zig @@ -242,6 +242,51 @@ pub const Bunfig = struct { try this.expect(expr, .e_boolean); this.ctx.runtime_options.smol = expr.data.e_boolean.value; } + + if (test_.get("coverage")) |expr| { + try this.expect(expr, .e_boolean); + this.ctx.test_options.coverage.enabled = expr.data.e_boolean.value; + } + + if (test_.get("coverageThreshold")) |expr| outer: { + if (expr.data == .e_number) { + this.ctx.test_options.coverage.fractions.functions = expr.data.e_number.value; + this.ctx.test_options.coverage.fractions.lines = expr.data.e_number.value; + this.ctx.test_options.coverage.fractions.stmts = expr.data.e_number.value; + this.ctx.test_options.coverage.fail_on_low_coverage = true; + break :outer; + } + + try this.expect(expr, .e_object); + if (expr.get("functions")) |functions| { + try this.expect(functions, .e_number); + this.ctx.test_options.coverage.fractions.functions = functions.data.e_number.value; + this.ctx.test_options.coverage.fail_on_low_coverage = true; + } + + if (expr.get("lines")) |lines| { + try this.expect(lines, .e_number); + this.ctx.test_options.coverage.fractions.lines = lines.data.e_number.value; + this.ctx.test_options.coverage.fail_on_low_coverage = true; + } + + if (expr.get("statements")) |stmts| { + try this.expect(stmts, .e_number); + this.ctx.test_options.coverage.fractions.stmts = stmts.data.e_number.value; + this.ctx.test_options.coverage.fail_on_low_coverage = true; + } + } + + // This mostly exists for debugging. + if (test_.get("coverageIgnoreSourcemaps")) |expr| { + try this.expect(expr, .e_boolean); + this.ctx.test_options.coverage.ignore_sourcemap = expr.data.e_boolean.value; + } + + if (test_.get("coverageSkipTestFiles")) |expr| { + try this.expect(expr, .e_boolean); + this.ctx.test_options.coverage.skip_test_files = expr.data.e_boolean.value; + } } } diff --git a/src/cli.zig b/src/cli.zig index 1debd9254feb0f..04f01053af63cb 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -20,6 +20,7 @@ const json_parser = bun.JSON; const js_printer = bun.js_printer; const js_ast = bun.JSAst; const linker = @import("linker.zig"); +const RegularExpression = bun.RegularExpression; const sync = @import("./sync.zig"); const Api = @import("api/schema.zig").Api; @@ -218,7 +219,9 @@ pub const Arguments = struct { clap.parseParam("--rerun-each Re-run each test file times, helps catch certain bugs") catch unreachable, clap.parseParam("--only Only run tests that are marked with \"test.only()\"") catch unreachable, clap.parseParam("--todo Include tests that are marked with \"test.todo()\"") catch unreachable, + clap.parseParam("--coverage Generate a coverage profile") catch unreachable, clap.parseParam("--bail ? Exit the test suite after failures. If you do not specify a number, it defaults to 1.") catch unreachable, + clap.parseParam("-t, --test-name-pattern Run only tests with a name that matches the given regex.") catch unreachable, }; const build_params_public = public_params ++ build_only_params; @@ -385,15 +388,20 @@ pub const Arguments = struct { }; } } + + if (!ctx.test_options.coverage.enabled) { + ctx.test_options.coverage.enabled = args.flag("--coverage"); + } + if (args.option("--bail")) |bail| { if (bail.len > 0) { ctx.test_options.bail = std.fmt.parseInt(u32, bail, 10) catch |e| { - Output.prettyErrorln("--bail expects a number: {s}", .{@errorName(e)}); + Output.prettyErrorln("error: --bail expects a number: {s}", .{@errorName(e)}); Global.exit(1); }; if (ctx.test_options.bail == 0) { - Output.prettyErrorln("--bail expects a number greater than 0", .{}); + Output.prettyErrorln("error: --bail expects a number greater than 0", .{}); Global.exit(1); } } else { @@ -403,11 +411,25 @@ pub const Arguments = struct { if (args.option("--rerun-each")) |repeat_count| { if (repeat_count.len > 0) { ctx.test_options.repeat_count = std.fmt.parseInt(u32, repeat_count, 10) catch |e| { - Output.prettyErrorln("--rerun-each expects a number: {s}", .{@errorName(e)}); + Output.prettyErrorln("error: --rerun-each expects a number: {s}", .{@errorName(e)}); Global.exit(1); }; } } + if (args.option("--test-name-pattern")) |namePattern| { + const regex = RegularExpression.init(bun.String.fromBytes(namePattern), RegularExpression.Flags.none) catch { + Output.prettyErrorln( + "error: --test-name-pattern expects a valid regular expression but received {}", + .{ + strings.QuotedFormatter{ + .text = namePattern, + }, + }, + ); + Global.exit(1); + }; + ctx.test_options.test_filter_regex = regex; + } ctx.test_options.update_snapshots = args.flag("--update-snapshots"); ctx.test_options.run_todo = args.flag("--todo"); ctx.test_options.only = args.flag("--only"); @@ -835,6 +857,7 @@ pub const HelpCommand = struct { \\> create next ./app Create a new project from a template (bun c) \\> install Install dependencies for a package.json (bun i) \\> add {s:<16} Add a dependency to package.json (bun a) + \\> update {s:<16} Update outdated dependencies & save to package.json \\> link Link an npm package globally \\> remove {s:<16} Remove a dependency from package.json (bun rm) \\> unlink Globally unlink an npm package @@ -856,6 +879,7 @@ pub const HelpCommand = struct { const args = .{ packages_to_add_filler[package_add_i], + packages_to_add_filler[(package_add_i + 1) % packages_to_add_filler.len], packages_to_remove_filler[package_remove_i], }; @@ -949,6 +973,8 @@ pub const Command = struct { run_todo: bool = false, only: bool = false, bail: u32 = 0, + coverage: TestCommand.CodeCoverageOptions = .{}, + test_filter_regex: ?*RegularExpression = null, }; pub const Context = struct { @@ -1068,11 +1094,11 @@ pub const Command = struct { for (args_iter.buf) |arg| { const span = std.mem.span(arg); if (span.len > 0 and (strings.eqlComptime(span, "-g") or strings.eqlComptime(span, "--global"))) { - break :brk Command.Tag.AddCommand; + break :brk .AddCommand; } } - break :brk Command.Tag.InstallCommand; + break :brk .InstallCommand; }, RootCommandMatcher.case("c"), RootCommandMatcher.case("create") => .CreateCommand, @@ -1080,7 +1106,8 @@ pub const Command = struct { RootCommandMatcher.case("pm") => .PackageManagerCommand, - RootCommandMatcher.case("add"), RootCommandMatcher.case("update"), RootCommandMatcher.case("a") => .AddCommand, + RootCommandMatcher.case("add"), RootCommandMatcher.case("a") => .AddCommand, + RootCommandMatcher.case("update") => .UpdateCommand, RootCommandMatcher.case("r"), RootCommandMatcher.case("remove"), RootCommandMatcher.case("rm"), RootCommandMatcher.case("uninstall") => .RemoveCommand, RootCommandMatcher.case("run") => .RunCommand, @@ -1130,6 +1157,7 @@ pub const Command = struct { const RemoveCommand = @import("./cli/remove_command.zig").RemoveCommand; const RunCommand = @import("./cli/run_command.zig").RunCommand; const ShellCompletions = @import("./cli/shell_completions.zig"); + const UpdateCommand = @import("./cli/update_command.zig").UpdateCommand; const UpgradeCommand = @import("./cli/upgrade_command.zig").UpgradeCommand; const BunxCommand = @import("./cli/bunx_command.zig").BunxCommand; @@ -1149,6 +1177,7 @@ pub const Command = struct { // _ = RunCommand; // _ = ShellCompletions; // _ = TestCommand; + // _ = UpdateCommand; // _ = UpgradeCommand; // _ = BunxCommand; } @@ -1219,6 +1248,13 @@ pub const Command = struct { try AddCommand.exec(ctx); return; }, + .UpdateCommand => { + if (comptime bun.fast_debug_build_mode and bun.fast_debug_build_cmd != .UpdateCommand) unreachable; + const ctx = try Command.Context.create(allocator, log, .UpdateCommand); + + try UpdateCommand.exec(ctx); + return; + }, .BunxCommand => { if (comptime bun.fast_debug_build_mode and bun.fast_debug_build_cmd != .BunxCommand) unreachable; const ctx = try Command.Context.create(allocator, log, .BunxCommand); @@ -1564,7 +1600,6 @@ pub const Command = struct { BunJS.Run.boot( ctx.*, - file, absolute_script_path, ) catch |err| { if (Output.enable_ansi_colors) { @@ -1601,6 +1636,7 @@ pub const Command = struct { RunCommand, TestCommand, UnlinkCommand, + UpdateCommand, UpgradeCommand, pub fn params(comptime cmd: Tag) []const Arguments.ParamType { @@ -1614,14 +1650,14 @@ pub const Command = struct { pub fn readGlobalConfig(this: Tag) bool { return switch (this) { - .BunxCommand, .PackageManagerCommand, .InstallCommand, .AddCommand, .RemoveCommand => true, + .BunxCommand, .PackageManagerCommand, .InstallCommand, .AddCommand, .RemoveCommand, .UpdateCommand => true, else => false, }; } pub fn isNPMRelated(this: Tag) bool { return switch (this) { - .BunxCommand, .LinkCommand, .UnlinkCommand, .PackageManagerCommand, .InstallCommand, .AddCommand, .RemoveCommand => true, + .BunxCommand, .LinkCommand, .UnlinkCommand, .PackageManagerCommand, .InstallCommand, .AddCommand, .RemoveCommand, .UpdateCommand => true, else => false, }; } @@ -1633,6 +1669,7 @@ pub const Command = struct { .InstallCommand = true, .AddCommand = true, .RemoveCommand = true, + .UpdateCommand = true, .PackageManagerCommand = true, .BunxCommand = true, .AutoCommand = true, @@ -1646,6 +1683,7 @@ pub const Command = struct { .InstallCommand = true, .AddCommand = true, .RemoveCommand = true, + .UpdateCommand = true, .PackageManagerCommand = true, .BunxCommand = true, }); @@ -1655,6 +1693,7 @@ pub const Command = struct { .InstallCommand = false, .AddCommand = false, .RemoveCommand = false, + .UpdateCommand = false, .PackageManagerCommand = false, .LinkCommand = false, .UnlinkCommand = false, diff --git a/src/cli/init_command.zig b/src/cli/init_command.zig index 9b5ad71444620d..6f1fced541d9ab 100644 --- a/src/cli/init_command.zig +++ b/src/cli/init_command.zig @@ -337,7 +337,14 @@ pub const InitCommand = struct { } if (fields.entry_point.len > 0 and !exists(fields.entry_point)) { - var entry = try std.fs.cwd().createFile(fields.entry_point, .{ .truncate = true }); + const cwd = std.fs.cwd(); + if (std.fs.path.dirname(fields.entry_point)) |dirname| { + if (!strings.eqlComptime(dirname, ".")) { + cwd.makePath(dirname) catch {}; + } + } + + var entry = try cwd.createFile(fields.entry_point, .{ .truncate = true }); entry.writeAll("console.log(\"Hello via Bun!\");") catch {}; entry.close(); Output.prettyln(" + {s}", .{fields.entry_point}); diff --git a/src/cli/package_manager_command.zig b/src/cli/package_manager_command.zig index 4408568e0aba63..cb03b9e3f2e6d9 100644 --- a/src/cli/package_manager_command.zig +++ b/src/cli/package_manager_command.zig @@ -51,7 +51,7 @@ pub const PackageManagerCommand = struct { @memcpy(lockfile_buffer[0..lockfile_.len], lockfile_); lockfile_buffer[lockfile_.len] = 0; var lockfile = lockfile_buffer[0..lockfile_.len :0]; - var pm = try PackageManager.init(ctx, null, PackageManager.Subcommand.pm); + var pm = try PackageManager.init(ctx, PackageManager.Subcommand.pm); const load_lockfile = pm.lockfile.loadFromDisk(ctx.allocator, ctx.log, lockfile); handleLoadLockfileErrors(load_lockfile, pm); @@ -87,7 +87,7 @@ pub const PackageManagerCommand = struct { var args = try std.process.argsAlloc(ctx.allocator); args = args[1..]; - var pm = PackageManager.init(ctx, null, PackageManager.Subcommand.pm) catch |err| { + var pm = PackageManager.init(ctx, PackageManager.Subcommand.pm) catch |err| { // TODO: error messages here // if (err == error.MissingPackageJSON) { // // TODO: error messages diff --git a/src/cli/run_command.zig b/src/cli/run_command.zig index 44b3935a3db7fe..4c6227eba03dc7 100644 --- a/src/cli/run_command.zig +++ b/src/cli/run_command.zig @@ -10,6 +10,7 @@ const default_allocator = bun.default_allocator; const C = bun.C; const std = @import("std"); +const PackageJSON = @import("../resolver/package_json.zig").PackageJSON; const lex = bun.js_lexer; const logger = @import("root").bun.logger; @@ -222,6 +223,31 @@ pub const RunCommand = struct { const log = Output.scoped(.RUN, false); + pub fn parseNpmPackageConfig( + allocator: std.mem.Allocator, + package_json: *PackageJSON, + env: *DotEnv.Loader, + ) !void { + const prefix = "npm_package_config_"; + + var buf = try std.ArrayList(u8).initCapacity(allocator, prefix.len); + defer buf.deinit(); + buf.appendSliceAssumeCapacity(prefix); + + for (package_json.npm_cfg_map.keys(), package_json.npm_cfg_map.values()) |key, value| { + buf.shrinkRetainingCapacity(prefix.len); + try buf.appendSlice(key); + + if (package_json.npm_cfg_map.map.getPtr(buf.items)) |ptr| { + ptr.* = value; + continue; + } + + const prefixed_key = try allocator.dupe(u8, buf.items); + errdefer allocator.free(prefixed_key); + try env.map.put(prefixed_key, value); + } + } pub fn runPackageScript( allocator: std.mem.Allocator, original_script: string, @@ -230,6 +256,7 @@ pub const RunCommand = struct { env: *DotEnv.Loader, passthrough: []const string, silent: bool, + package_json: ?*PackageJSON, ) !bool { const shell_bin = findShell(env.map.get("PATH") orelse "", cwd) orelse return error.MissingShell; @@ -241,6 +268,19 @@ pub const RunCommand = struct { try replacePackageManagerRun(©_script, script); + if (package_json) |pkg_json| { + var i: usize = 0; + const prefix = "$npm_package_config_"; + while (std.mem.indexOfPos(u8, copy_script.items, i, prefix)) |start| { + const end = std.mem.indexOfAnyPos(u8, copy_script.items, start + prefix.len, &std.ascii.whitespace) orelse copy_script.items.len; + const key = copy_script.items[start + prefix.len .. end]; + i = end; + const value = pkg_json.npm_cfg_map.get(key) orelse continue; + i = start + value.len; + try copy_script.replaceRange(start, prefix.len + key.len, value); + } + } + var combined_script: []u8 = copy_script.items; log("Script: \"{s}\"", .{combined_script}); @@ -872,6 +912,26 @@ pub const RunCommand = struct { const passthrough = ctx.passthrough; const force_using_bun = ctx.debug.run_in_bun; + // This doesn't cover every case + if ((script_name_to_search.len == 1 and script_name_to_search[0] == '.') or + (script_name_to_search.len == 2 and @as(u16, @bitCast(script_name_to_search[0..2].*)) == @as(u16, @bitCast([_]u8{ '.', '/' })))) + { + Run.boot(ctx, ".") catch |err| { + if (Output.enable_ansi_colors) { + ctx.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; + } else { + ctx.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; + } + + Output.prettyErrorln("error: Failed to run {s} due to error {s}", .{ + script_name_to_search, + @errorName(err), + }); + Global.exit(1); + }; + return true; + } + if (log_errors or force_using_bun) { if (script_name_to_search.len > 0) { possibly_open_with_bun_js: { @@ -952,8 +1012,7 @@ pub const RunCommand = struct { } Global.configureAllocator(.{ .long_running = true }); - - Run.boot(ctx, file, ctx.allocator.dupe(u8, file_path) catch unreachable) catch |err| { + Run.boot(ctx, ctx.allocator.dupe(u8, file_path) catch unreachable) catch |err| { if (Output.enable_ansi_colors) { ctx.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; } else { @@ -1013,6 +1072,8 @@ pub const RunCommand = struct { } }, else => { + try parseNpmPackageConfig(default_allocator, package_json, this_bundler.env); + if (scripts.get(script_name_to_search)) |script_content| { // allocate enough to hold "post${scriptname}" @@ -1027,6 +1088,7 @@ pub const RunCommand = struct { this_bundler.env, passthrough, ctx.debug.silent, + root_dir_info.enclosing_package_json, )) { return false; } @@ -1040,6 +1102,7 @@ pub const RunCommand = struct { this_bundler.env, passthrough, ctx.debug.silent, + root_dir_info.enclosing_package_json, )) return false; temp_script_buffer[0.."post".len].* = "post".*; @@ -1053,6 +1116,7 @@ pub const RunCommand = struct { this_bundler.env, passthrough, ctx.debug.silent, + root_dir_info.enclosing_package_json )) { return false; } @@ -1115,7 +1179,7 @@ pub const RunCommand = struct { if (comptime log_errors) { Output.prettyError("error: missing script \"{s}\"\n", .{script_name_to_search}); - Global.exit(0); + Global.exit(1); } return false; diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig index 14eca012e2b04b..3a9411e089bc80 100644 --- a/src/cli/test_command.zig +++ b/src/cli/test_command.zig @@ -261,6 +261,103 @@ pub const CommandLineReporter = struct { Output.prettyError("Ran {d} tests across {d} files. ", .{ tests, files }); Output.printStartEnd(bun.start_time, std.time.nanoTimestamp()); } + + pub fn printCodeCoverage(this: *CommandLineReporter, vm: *JSC.VirtualMachine, opts: *TestCommand.CodeCoverageOptions, comptime enable_ansi_colors: bool) !void { + const trace = bun.tracy.traceNamed(@src(), "TestCommand.printCodeCoverage"); + defer trace.end(); + + _ = this; + var map = bun.sourcemap.ByteRangeMapping.map orelse return; + var iter = map.valueIterator(); + var max_filepath_length: usize = "All files".len; + const relative_dir = vm.bundler.fs.top_level_dir; + + var byte_ranges = try std.ArrayList(bun.sourcemap.ByteRangeMapping).initCapacity(bun.default_allocator, map.count()); + + while (iter.next()) |entry| { + const value: bun.sourcemap.ByteRangeMapping = entry.*; + var utf8 = value.source_url.slice(); + byte_ranges.appendAssumeCapacity(value); + max_filepath_length = @max(bun.path.relative(relative_dir, utf8).len, max_filepath_length); + } + + if (byte_ranges.items.len == 0) { + return; + } + + std.sort.block(bun.sourcemap.ByteRangeMapping, byte_ranges.items, void{}, bun.sourcemap.ByteRangeMapping.isLessThan); + + iter = map.valueIterator(); + var writer = Output.errorWriter(); + var base_fraction = opts.fractions; + var failing = false; + + writer.writeAll(Output.prettyFmt("", enable_ansi_colors)) catch return; + writer.writeByteNTimes('-', max_filepath_length + 2) catch return; + writer.writeAll(Output.prettyFmt("|---------|---------|-------------------\n", enable_ansi_colors)) catch return; + writer.writeAll("File") catch return; + writer.writeByteNTimes(' ', max_filepath_length - "File".len + 1) catch return; + // writer.writeAll(Output.prettyFmt(" | % Funcs | % Blocks | % Lines | Uncovered Line #s\n", enable_ansi_colors)) catch return; + writer.writeAll(Output.prettyFmt(" | % Funcs | % Lines | Uncovered Line #s\n", enable_ansi_colors)) catch return; + writer.writeAll(Output.prettyFmt("", enable_ansi_colors)) catch return; + writer.writeByteNTimes('-', max_filepath_length + 2) catch return; + writer.writeAll(Output.prettyFmt("|---------|---------|-------------------\n", enable_ansi_colors)) catch return; + + var coverage_buffer = bun.MutableString.initEmpty(bun.default_allocator); + var coverage_buffer_buffer = coverage_buffer.bufferedWriter(); + var coverage_writer = coverage_buffer_buffer.writer(); + + var avg = bun.sourcemap.CoverageFraction{ + .functions = 0.0, + .lines = 0.0, + .stmts = 0.0, + }; + var avg_count: f64 = 0; + + for (byte_ranges.items) |*entry| { + var report = bun.sourcemap.CodeCoverageReport.generate(vm.global, bun.default_allocator, entry, opts.ignore_sourcemap) orelse continue; + defer report.deinit(bun.default_allocator); + var fraction = base_fraction; + report.writeFormat(max_filepath_length, &fraction, relative_dir, coverage_writer, enable_ansi_colors) catch continue; + avg.functions += fraction.functions; + avg.lines += fraction.lines; + avg.stmts += fraction.stmts; + avg_count += 1.0; + if (fraction.failing) { + failing = true; + } + + coverage_writer.writeAll("\n") catch continue; + } + + { + avg.functions /= avg_count; + avg.lines /= avg_count; + avg.stmts /= avg_count; + + try bun.sourcemap.CodeCoverageReport.writeFormatWithValues( + "All files", + max_filepath_length, + avg, + base_fraction, + failing, + writer, + false, + enable_ansi_colors, + ); + + try writer.writeAll(Output.prettyFmt(" |\n", enable_ansi_colors)); + } + + coverage_buffer_buffer.flush() catch return; + try writer.writeAll(coverage_buffer.list.items); + try writer.writeAll(Output.prettyFmt("", enable_ansi_colors)); + writer.writeByteNTimes('-', max_filepath_length + 2) catch return; + writer.writeAll(Output.prettyFmt("|---------|---------|-------------------\n", enable_ansi_colors)) catch return; + + opts.fractions.failing = failing; + Output.flush(); + } }; const Scanner = struct { @@ -334,6 +431,42 @@ const Scanner = struct { "_spec", }; + export fn BunTest__shouldGenerateCodeCoverage(test_name_str: bun.String) callconv(.C) bool { + var zig_slice: bun.JSC.ZigString.Slice = .{}; + defer zig_slice.deinit(); + + // In this particular case, we don't actually care about non-ascii latin1 characters. + // so we skip the ascii check + const slice = if (test_name_str.is8Bit()) test_name_str.latin1() else brk: { + zig_slice = test_name_str.toUTF8(bun.default_allocator); + break :brk zig_slice.slice(); + }; + + // always ignore node_modules. + if (strings.contains(slice, "/" ++ "node_modules" ++ "/")) { + return false; + } + + const ext = std.fs.path.extension(slice); + const loader_by_ext = JSC.VirtualMachine.get().bundler.options.loader(ext); + + // allow file loader just incase they use a custom loader with a non-standard extension + if (!(loader_by_ext.isJavaScriptLike() or loader_by_ext == .file)) { + return false; + } + + if (jest.Jest.runner.?.test_options.coverage.skip_test_files) { + const name_without_extension = slice[0 .. slice.len - ext.len]; + inline for (test_name_suffixes) |suffix| { + if (strings.endsWithComptime(name_without_extension, suffix)) { + return false; + } + } + } + + return true; + } + pub fn couldBeTestFile(this: *Scanner, name: string) bool { const extname = std.fs.path.extension(name); if (!this.options.loader(extname).isJavaScriptLike()) return false; @@ -419,6 +552,14 @@ pub const TestCommand = struct { pub const name = "test"; pub const old_name = "wiptest"; + pub const CodeCoverageOptions = struct { + skip_test_files: bool = !Environment.allow_assert, + fractions: bun.sourcemap.CoverageFraction = .{}, + ignore_sourcemap: bool = false, + enabled: bool = false, + fail_on_low_coverage: bool = false, + }; + pub fn exec(ctx: Command.Context) !void { if (comptime is_bindgen) unreachable; @@ -457,6 +598,8 @@ pub const TestCommand = struct { .run_todo = ctx.test_options.run_todo, .only = ctx.test_options.only, .bail = ctx.test_options.bail, + .filter_regex = ctx.test_options.test_filter_regex, + .filter_buffer = bun.MutableString.init(ctx.allocator, 0) catch unreachable, .snapshots = Snapshots{ .allocator = ctx.allocator, .update_snapshots = ctx.test_options.update_snapshots, @@ -478,7 +621,7 @@ pub const TestCommand = struct { reporter.repeat_count = @max(ctx.test_options.repeat_count, 1); reporter.jest.callback = &reporter.callback; jest.Jest.runner = &reporter.jest; - + reporter.jest.test_options = &ctx.test_options; js_ast.Expr.Data.Store.create(default_allocator); js_ast.Stmt.Data.Store.create(default_allocator); var vm = try JSC.VirtualMachine.init( @@ -505,6 +648,14 @@ pub const TestCommand = struct { vm.is_main_thread = true; JSC.VirtualMachine.is_main_thread_vm = true; + if (ctx.test_options.coverage.enabled) { + vm.bundler.options.code_coverage = true; + vm.bundler.options.minify_syntax = false; + vm.bundler.options.minify_identifiers = false; + vm.bundler.options.minify_whitespace = false; + vm.global.vm().setControlFlowProfiler(true); + } + // For tests, we default to UTC time zone // unless the user inputs TZ="", in which case we use local time zone var TZ_NAME: string = @@ -536,7 +687,6 @@ pub const TestCommand = struct { scanner.scan(dir_to_scan); scanner.dirs_to_scan.deinit(); - const test_files = try scanner.results.toOwnedSlice(); if (test_files.len > 0) { vm.hot_reload = ctx.debug.hot_reload; @@ -547,6 +697,7 @@ pub const TestCommand = struct { } try jest.Jest.runner.?.snapshots.writeSnapshotFile(); + var coverage = ctx.test_options.coverage; if (reporter.summary.pass > 20) { if (reporter.summary.skip > 0) { @@ -602,6 +753,12 @@ pub const TestCommand = struct { } else { Output.prettyError("\n", .{}); + if (coverage.enabled) { + switch (Output.enable_ansi_colors_stderr) { + inline else => |colors| reporter.printCodeCoverage(vm, &coverage, colors) catch {}, + } + } + if (reporter.summary.pass > 0) { Output.prettyError("", .{}); } @@ -686,7 +843,7 @@ pub const TestCommand = struct { } } - if (reporter.summary.fail > 0) { + if (reporter.summary.fail > 0 or (coverage.enabled and coverage.fractions.failing and coverage.fail_on_low_coverage)) { Global.exit(1); } } diff --git a/src/cli/update_command.zig b/src/cli/update_command.zig new file mode 100644 index 00000000000000..bc2bfa76c83c0f --- /dev/null +++ b/src/cli/update_command.zig @@ -0,0 +1,8 @@ +const Command = @import("../cli.zig").Command; +const PackageManager = @import("../install/install.zig").PackageManager; + +pub const UpdateCommand = struct { + pub fn exec(ctx: Command.Context) !void { + try PackageManager.update(ctx); + } +}; diff --git a/src/deps/c_ares.zig b/src/deps/c_ares.zig index a8ad9f02bbd91a..777827662e1147 100644 --- a/src/deps/c_ares.zig +++ b/src/deps/c_ares.zig @@ -1,6 +1,7 @@ const c = @import("std").c; const std = @import("std"); const bun = @import("root").bun; +const JSC = bun.JSC; const strings = bun.strings; const iovec = @import("std").os.iovec; const struct_in_addr = std.os.sockaddr.in; @@ -180,8 +181,6 @@ pub const struct_hostent = extern struct { h_length: c_int, h_addr_list: [*c][*c]u8, - const JSC = bun.JSC; - pub fn toJSReponse(this: *struct_hostent, _: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime lookup_name: []const u8) JSC.JSValue { // A cname lookup always returns a single record but we follow the common API here. @@ -296,13 +295,12 @@ pub const AddrInfo_node = extern struct { return len; } }; + pub const AddrInfo = extern struct { cnames_: [*c]AddrInfo_cname = null, node: ?*AddrInfo_node = null, name_: ?[*:0]u8 = null, - const JSC = bun.JSC; - pub fn toJSArray( addr_info: *AddrInfo, parent_allocator: std.mem.Allocator, @@ -624,8 +622,6 @@ pub const struct_ares_caa_reply = extern struct { value: [*c]u8, length: usize, - const JSC = bun.JSC; - pub fn toJSReponse(this: *struct_ares_caa_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) JSC.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = @import("root").bun.ArenaAllocator.init(stack.get()); @@ -703,7 +699,6 @@ pub const struct_ares_srv_reply = extern struct { priority: c_ushort, weight: c_ushort, port: c_ushort, - const JSC = bun.JSC; pub fn toJSReponse(this: *struct_ares_srv_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) JSC.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); @@ -788,8 +783,6 @@ pub const struct_ares_mx_reply = extern struct { host: [*c]u8, priority: c_ushort, - const JSC = bun.JSC; - pub fn toJSReponse(this: *struct_ares_mx_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) JSC.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = @import("root").bun.ArenaAllocator.init(stack.get()); @@ -864,8 +857,6 @@ pub const struct_ares_txt_reply = extern struct { txt: [*c]u8, length: usize, - const JSC = bun.JSC; - pub fn toJSReponse(this: *struct_ares_txt_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) JSC.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = @import("root").bun.ArenaAllocator.init(stack.get()); @@ -946,8 +937,6 @@ pub const struct_ares_naptr_reply = extern struct { order: c_ushort, preference: c_ushort, - const JSC = bun.JSC; - pub fn toJSReponse(this: *struct_ares_naptr_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) JSC.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = @import("root").bun.ArenaAllocator.init(stack.get()); @@ -1040,8 +1029,6 @@ pub const struct_ares_soa_reply = extern struct { expire: c_uint, minttl: c_uint, - const JSC = bun.JSC; - pub fn toJSReponse(this: *struct_ares_soa_reply, parent_allocator: std.mem.Allocator, globalThis: *JSC.JSGlobalObject, comptime _: []const u8) JSC.JSValue { var stack = std.heap.stackFallback(2048, parent_allocator); var arena = @import("root").bun.ArenaAllocator.init(stack.get()); @@ -1377,3 +1364,63 @@ pub const ares_soa_reply = struct_ares_soa_reply; pub const ares_uri_reply = struct_ares_uri_reply; pub const ares_addr_node = struct_ares_addr_node; pub const ares_addr_port_node = struct_ares_addr_port_node; + +pub export fn Bun__canonicalizeIP( + ctx: *JSC.JSGlobalObject, + callframe: *JSC.CallFrame, +) callconv(.C) JSC.JSValue { + JSC.markBinding(@src()); + + const globalThis = ctx.ptr(); + const arguments = callframe.arguments(1); + + if (arguments.len == 0) { + globalThis.throwInvalidArguments("canonicalizeIP() expects a string but received no arguments.", .{}); + return .zero; + } + // windows uses 65 bytes for ipv6 addresses and linux/macos uses 46 + const INET6_ADDRSTRLEN = if (comptime bun.Environment.isWindows) 65 else 46; + + var script_ctx = globalThis.bunVM(); + var args = JSC.Node.ArgumentsSlice.init(script_ctx, arguments.ptr[0..arguments.len]); + var addr_arg = args.nextEat().?; + + if (bun.String.tryFromJS(addr_arg, globalThis)) |addr| { + const addr_slice = addr.toSlice(bun.default_allocator); + defer addr_slice.deinit(); + const addr_str = addr_slice.slice(); + if (addr_str.len >= INET6_ADDRSTRLEN) { + return JSC.JSValue.jsUndefined(); + } + + var ip_std_text: [INET6_ADDRSTRLEN + 1]u8 = undefined; + // we need a null terminated string as input + var ip_addr: [INET6_ADDRSTRLEN + 1]u8 = undefined; + bun.copy(u8, &ip_addr, addr_str); + ip_addr[addr_str.len] = 0; + + var af: c_int = std.os.AF.INET; + // get the standard text representation of the IP + if (ares_inet_pton(af, &ip_addr, &ip_std_text) != 1) { + af = std.os.AF.INET6; + if (ares_inet_pton(af, &ip_addr, &ip_std_text) != 1) { + return JSC.JSValue.jsUndefined(); + } + } + // ip_addr will contain the null-terminated string of the cannonicalized IP + if (ares_inet_ntop(af, &ip_std_text, &ip_addr, @sizeOf(@TypeOf(ip_addr))) == null) { + return JSC.JSValue.jsUndefined(); + } + // use the null-terminated size to return the string + const size = bun.len(bun.cast([*:0]u8, &ip_addr)); + return JSC.ZigString.init(ip_addr[0..size]).toValueGC(globalThis); + } else { + globalThis.throwInvalidArguments("address must be a string", .{}); + return .zero; + } +} +comptime { + if (!JSC.is_bindgen) { + _ = Bun__canonicalizeIP; + } +} diff --git a/src/deps/lol-html b/src/deps/lol-html index 2681dcf0b3e690..8d4c273ded3221 160000 --- a/src/deps/lol-html +++ b/src/deps/lol-html @@ -1 +1 @@ -Subproject commit 2681dcf0b3e6907111565199df8c43cc9aab7fe8 +Subproject commit 8d4c273ded322193d017042d1f48df2766b0f88b diff --git a/src/deps/mimalloc b/src/deps/mimalloc index abfd4236d4e001..7968d428504340 160000 --- a/src/deps/mimalloc +++ b/src/deps/mimalloc @@ -1 +1 @@ -Subproject commit abfd4236d4e00136cd23c862ab880ce894899b90 +Subproject commit 7968d4285043401bb36573374710d47a4081a063 diff --git a/src/deps/uws b/src/deps/uws index 0e9ddbe6944c3c..8b4206edb96799 160000 --- a/src/deps/uws +++ b/src/deps/uws @@ -1 +1 @@ -Subproject commit 0e9ddbe6944c3ca6b6957e5938d77d8ed9a8181b +Subproject commit 8b4206edb96799df8c5fc01d43a4e51373064162 diff --git a/src/deps/uws.zig b/src/deps/uws.zig index 43711e69653a24..10f836bbc2497b 100644 --- a/src/deps/uws.zig +++ b/src/deps/uws.zig @@ -207,7 +207,7 @@ pub fn NewSocketHandler(comptime is_ssl: bool) type { ); } pub fn write(this: ThisSocket, data: []const u8, msg_more: bool) i32 { - return us_socket_write( + const result = us_socket_write( comptime ssl_int, this.socket, data.ptr, @@ -215,6 +215,12 @@ pub fn NewSocketHandler(comptime is_ssl: bool) type { @as(i32, @intCast(@as(u31, @truncate(data.len)))), @as(i32, @intFromBool(msg_more)), ); + + if (comptime Environment.allow_assert) { + debug("us_socket_write({*}, {d}) = {d}", .{ this.getNativeHandle(), data.len, result }); + } + + return result; } pub fn rawWrite(this: ThisSocket, data: []const u8, msg_more: bool) i32 { diff --git a/src/env_loader.zig b/src/env_loader.zig index bf1bf450e1a72c..088ec2d0cb3c19 100644 --- a/src/env_loader.zig +++ b/src/env_loader.zig @@ -624,6 +624,7 @@ const Parser = struct { fn parseQuoted(this: *Parser, comptime quote: u8) ?string { if (comptime Environment.allow_assert) std.debug.assert(this.src[this.pos] == quote); const start = this.pos; + const max_len = value_buffer.len; var end = start + 1; while (end < this.src.len) : (end += 1) { switch (this.src[end]) { @@ -639,7 +640,7 @@ const Parser = struct { { var ptr: usize = 0; var i = start; - while (i < end) { + while (i < end and ptr < max_len) { switch (this.src[i]) { '\\' => if (comptime quote == '"') { if (comptime Environment.allow_assert) std.debug.assert(i + 1 < end); @@ -647,16 +648,18 @@ const Parser = struct { 'n' => { value_buffer[ptr] = '\n'; ptr += 1; - i += 1; + i += 2; }, 'r' => { value_buffer[ptr] = '\r'; ptr += 1; - i += 1; + i += 2; }, else => { - value_buffer[ptr] = this.src[i]; - value_buffer[ptr + 1] = this.src[i + 1]; + if (ptr + 1 < max_len) { + value_buffer[ptr] = this.src[i]; + value_buffer[ptr + 1] = this.src[i + 1]; + } ptr += 2; i += 2; }, diff --git a/src/feature_flags.zig b/src/feature_flags.zig index 6c19df844b6051..130e07d334282a 100644 --- a/src/feature_flags.zig +++ b/src/feature_flags.zig @@ -112,7 +112,7 @@ pub const hardcode_localhost_to_127_0_0_1 = false; /// so we just disable it pub const support_jsxs_in_jsx_transform = false; -pub const use_simdutf = !@import("root").bun.JSC.is_bindgen; +pub const use_simdutf = @import("root").bun.Environment.isNative and !@import("root").bun.JSC.is_bindgen; pub const inline_properties_in_transpiler = true; @@ -172,3 +172,5 @@ pub const alignment_tweak = false; pub const export_star_redirect = false; pub const streaming_file_uploads_for_http_client = true; + +pub const concurrent_transpiler = true; diff --git a/src/hive_array.zig b/src/hive_array.zig index fd683539666724..06ba63ae45c6dc 100644 --- a/src/hive_array.zig +++ b/src/hive_array.zig @@ -86,6 +86,15 @@ pub fn HiveArray(comptime T: type, comptime capacity: u16) type { return self.allocator.create(T) catch unreachable; } + pub fn getAndSeeIfNew(self: *This, new: *bool) *T { + if (self.hive.get()) |value| { + new.* = false; + return value; + } + + return self.allocator.create(T) catch unreachable; + } + pub fn tryGet(self: *This) !*T { if (self.hive.get()) |value| { return value; diff --git a/src/http.zig b/src/http.zig index c206fbf66b6fa2..61cf9909524a36 100644 --- a/src/http.zig +++ b/src/http.zig @@ -2223,7 +2223,7 @@ pub const RequestContext = struct { const accept: MimeType = brk: { if (ctx.header("Accept")) |accept| - break :brk MimeType.init(accept); + break :brk MimeType.init(accept, null, null); break :brk ctx.mime_type; }; diff --git a/src/http/mime_type.zig b/src/http/mime_type.zig index 17f6821b3de761..fb4043482d7db2 100644 --- a/src/http/mime_type.zig +++ b/src/http/mime_type.zig @@ -110,7 +110,7 @@ fn initComptime(comptime str: string, t: Category) MimeType { }; } -pub fn init(str_: string) MimeType { +pub fn init(str_: string, allocator: ?std.mem.Allocator, allocated: ?*bool) MimeType { var str = str_; if (std.mem.indexOfScalar(u8, str, '/')) |slash| { const category_ = str[0..slash]; @@ -141,12 +141,17 @@ pub fn init(str_: string) MimeType { return wasm; } - return MimeType{ .value = str_, .category = .application }; + if (allocated != null and allocator != null) allocated.?.* = true; + return MimeType{ + .value = if (allocator) |a| a.dupe(u8, str_) catch unreachable else str_, + .category = .application, + }; }, "font".len => { if (strings.eqlComptimeIgnoreLen(category_, "font")) { + if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = str_, + .value = if (allocator) |a| a.dupe(u8, str_) catch unreachable else str_, .category = .font, }; } @@ -168,27 +173,34 @@ pub fn init(str_: string) MimeType { return all.@"text/plain"; } - return MimeType{ .value = str_, .category = .text }; + if (allocated != null and allocator != null) allocated.?.* = true; + return MimeType{ + .value = if (allocator) |a| a.dupe(u8, str_) catch unreachable else str_, + .category = .text, + }; } }, "image".len => { if (strings.eqlComptimeIgnoreLen(category_, "image")) { + if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = str_, + .value = if (allocator) |a| a.dupe(u8, str_) catch unreachable else str_, .category = .image, }; } if (strings.eqlComptimeIgnoreLen(category_, "audio")) { + if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = str_, + .value = if (allocator) |a| a.dupe(u8, str_) catch unreachable else str_, .category = .audio, }; } if (strings.eqlComptimeIgnoreLen(category_, "video")) { + if (allocated != null and allocator != null) allocated.?.* = true; return MimeType{ - .value = str_, + .value = if (allocator) |a| a.dupe(u8, str_) catch unreachable else str_, .category = .video, }; } @@ -197,7 +209,11 @@ pub fn init(str_: string) MimeType { } } - return MimeType{ .value = str_, .category = .other }; + if (allocated != null and allocator != null) allocated.?.* = true; + return MimeType{ + .value = if (allocator) |a| a.dupe(u8, str_) catch unreachable else str_, + .category = .other, + }; } // TODO: improve this @@ -2516,7 +2532,7 @@ pub const all = struct { // TODO: do a comptime static hash map for this // its too many branches to use ComptimeStringMap pub fn byName(name: []const u8) MimeType { - return MimeType.init(name); + return MimeType.init(name, null, null); } pub const extensions = ComptimeStringMap(MimeType, .{ diff --git a/src/http/websocket_http_client.zig b/src/http/websocket_http_client.zig index ccdcda20d8db13..333d236865355c 100644 --- a/src/http/websocket_http_client.zig +++ b/src/http/websocket_http_client.zig @@ -360,7 +360,8 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { } } - const wrote = socket.write(this.input_body_buf, true); + // Do not set MSG_MORE, see https://github.com/oven-sh/bun/issues/4010 + const wrote = socket.write(this.input_body_buf, false); if (wrote < 0) { this.terminate(ErrorCode.failed_to_write); return; @@ -542,7 +543,8 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { if (this.to_send.len == 0) return; - const wrote = socket.write(this.to_send, true); + // Do not set MSG_MORE, see https://github.com/oven-sh/bun/issues/4010 + const wrote = socket.write(this.to_send, false); if (wrote < 0) { this.terminate(ErrorCode.failed_to_write); return; @@ -1304,15 +1306,15 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { this.sendCloseWithBody(this.tcp, 1001, null, 0); } - fn enqueueEncodedBytesMaybeFinal( + fn enqueueEncodedBytes( this: *WebSocket, socket: Socket, bytes: []const u8, - is_closing: bool, ) bool { // fast path: no backpressure, no queue, just send the bytes. if (!this.hasBackpressure()) { - const wrote = socket.write(bytes, !is_closing); + // Do not set MSG_MORE, see https://github.com/oven-sh/bun/issues/4010 + const wrote = socket.write(bytes, false); const expected = @as(c_int, @intCast(bytes.len)); if (wrote == expected) { return true; @@ -1323,18 +1325,18 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { return false; } - _ = this.copyToSendBuffer(bytes[@as(usize, @intCast(wrote))..], false, is_closing); + _ = this.copyToSendBuffer(bytes[@as(usize, @intCast(wrote))..], false); return true; } - return this.copyToSendBuffer(bytes, true, is_closing); + return this.copyToSendBuffer(bytes, true); } - fn copyToSendBuffer(this: *WebSocket, bytes: []const u8, do_write: bool, is_closing: bool) bool { - return this.sendData(.{ .raw = bytes }, do_write, is_closing, .Binary); + fn copyToSendBuffer(this: *WebSocket, bytes: []const u8, do_write: bool) bool { + return this.sendData(.{ .raw = bytes }, do_write, .Binary); } - fn sendData(this: *WebSocket, bytes: Copy, do_write: bool, is_closing: bool, opcode: Opcode) bool { + fn sendData(this: *WebSocket, bytes: Copy, do_write: bool, opcode: Opcode) bool { var content_byte_len: usize = 0; const write_len = bytes.len(&content_byte_len); std.debug.assert(write_len > 0); @@ -1349,7 +1351,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { std.debug.assert(!this.tcp.isClosed()); std.debug.assert(this.tcp.isEstablished()); } - return this.sendBuffer(this.send_buffer.readableSlice(0), is_closing, !is_closing); + return this.sendBuffer(this.send_buffer.readableSlice(0)); } return true; @@ -1358,13 +1360,9 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { fn sendBuffer( this: *WebSocket, out_buf: []const u8, - is_closing: bool, - _: bool, ) bool { std.debug.assert(out_buf.len > 0); - _ = is_closing; - // set msg_more to false - // it seems to improve perf by ~20% + // Do not set MSG_MORE, see https://github.com/oven-sh/bun/issues/4010 const wrote = this.tcp.write(out_buf, false); if (wrote < 0) { this.terminate(ErrorCode.failed_to_write); @@ -1379,10 +1377,6 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { return true; } - fn enqueueEncodedBytes(this: *WebSocket, socket: Socket, bytes: []const u8) bool { - return this.enqueueEncodedBytesMaybeFinal(socket, bytes, false); - } - fn sendPong(this: *WebSocket, socket: Socket) bool { if (socket.isClosed() or socket.isShutdown()) { this.dispatchAbruptClose(); @@ -1444,7 +1438,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { var slice = final_body_bytes[0..(8 + body_len)]; Mask.fill(this.globalThis, mask_buf, slice[6..], slice[6..]); - if (this.enqueueEncodedBytesMaybeFinal(socket, slice, true)) { + if (this.enqueueEncodedBytes(socket, slice)) { this.dispatchClose(code, &reason); this.clearData(); } @@ -1463,7 +1457,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { const send_buf = this.send_buffer.readableSlice(0); if (send_buf.len == 0) return; - _ = this.sendBuffer(send_buf, false, true); + _ = this.sendBuffer(send_buf); } pub fn handleTimeout( this: *WebSocket, @@ -1502,7 +1496,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { return; } - _ = this.sendData(bytes, !this.hasBackpressure(), false, opcode); + _ = this.sendData(bytes, !this.hasBackpressure(), opcode); } pub fn writeString( this: *WebSocket, @@ -1549,7 +1543,6 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { else Copy{ .latin1 = str.slice() }, !this.hasBackpressure(), - false, opcode, ); } diff --git a/src/http_client_async.zig b/src/http_client_async.zig index 441c8ae477d677..4998cec857fef8 100644 --- a/src/http_client_async.zig +++ b/src/http_client_async.zig @@ -319,9 +319,7 @@ fn NewHTTPContext(comptime ssl: bool) type { } pub fn init(this: *@This()) !void { - var opts: uws.us_socket_context_options_t = undefined; - const size = @sizeOf(uws.us_socket_context_options_t); - @memset(@as([*]u8, @ptrCast(&opts))[0..size], 0); + var opts: uws.us_socket_context_options_t = .{}; this.us_socket_context = uws.us_create_socket_context(ssl_int, http_thread.loop, @sizeOf(usize), opts).?; if (comptime ssl) { this.sslCtx().setup(); @@ -2802,8 +2800,6 @@ pub fn handleResponseMetadata( } else if (strings.eqlComptime(header.value, "deflate")) { this.state.encoding = Encoding.deflate; this.state.content_encoding_i = @as(u8, @truncate(header_i)); - } else if (!strings.eqlComptime(header.value, "identity")) { - return error.UnsupportedContentEncoding; } }, hashHeaderConst("Transfer-Encoding") => { diff --git a/src/install/dependency.zig b/src/install/dependency.zig index 8578e998a91d0c..3a9ee6b545eeff 100644 --- a/src/install/dependency.zig +++ b/src/install/dependency.zig @@ -257,6 +257,14 @@ pub const Version = struct { return strings.cmpStringsAsc({}, lhs.literal.slice(string_buf), rhs.literal.slice(string_buf)); } + pub fn isLessThanWithTag(string_buf: []const u8, lhs: Dependency.Version, rhs: Dependency.Version) bool { + const tag_order = lhs.tag.cmp(rhs.tag); + if (tag_order != .eq) + return tag_order == .lt; + + return strings.cmpStringsAsc({}, lhs.literal.slice(string_buf), rhs.literal.slice(string_buf)); + } + pub const External = [9]u8; pub fn toVersion( @@ -338,6 +346,11 @@ pub const Version = struct { /// GitHub Repository (via REST API) github = 8, + pub fn cmp(this: Tag, other: Tag) std.math.Order { + // TODO: align with yarn + return std.math.order(@intFromEnum(this), @intFromEnum(other)); + } + pub inline fn isNPM(this: Tag) bool { return @intFromEnum(this) < 3; } diff --git a/src/install/install.zig b/src/install/install.zig index 74904b276c2c2f..38f2ae11f5aeab 100644 --- a/src/install/install.zig +++ b/src/install/install.zig @@ -1641,6 +1641,7 @@ pub const PackageManager = struct { root_download_node: std.Progress.Node = undefined, to_remove: []const UpdateRequest = &[_]UpdateRequest{}, + to_update: bool = false, root_package_json_file: std.fs.File, root_dependency_list: Lockfile.DependencySlice = .{}, @@ -3821,9 +3822,9 @@ pub const PackageManager = struct { }, } } - for (manager.package_json_updates) |*update| { - if (strings.eql(update.name, name.slice())) { - update.failed = true; + for (manager.package_json_updates) |*request| { + if (strings.eql(request.name, name.slice())) { + request.failed = true; manager.options.do.save_lockfile = false; manager.options.do.save_yarn_lock = false; manager.options.do.install_packages = false; @@ -4320,6 +4321,7 @@ pub const PackageManager = struct { }, local_package_features: Features = .{ .dev_dependencies = true, + .workspaces = true, }, // The idea here is: // 1. package has a platform-specific binary to install @@ -4475,23 +4477,7 @@ pub const PackageManager = struct { for (scoped.scopes, 0..) |name, i| { var registry = scoped.registries[i]; if (registry.url.len == 0) registry.url = base.url; - try this.registries.put(allocator, Npm.Registry.Scope.hash(name), Npm.Registry.Scope.fromAPI(name, registry, allocator, env) catch |err| { - if (err == error.InvalidURL) { - log.addErrorFmt( - null, - logger.Loc.Empty, - allocator, - "{} is not a valid registry URL", - .{ - strings.QuotedFormatter{ - .text = registry.url, - }, - }, - ) catch unreachable; - } - - return err; - }); + try this.registries.put(allocator, Npm.Registry.Scope.hash(name), try Npm.Registry.Scope.fromAPI(name, registry, allocator, env)); } } @@ -4604,21 +4590,10 @@ pub const PackageManager = struct { { const prev_scope = this.scope; var api_registry = std.mem.zeroes(Api.NpmRegistry); - var href = bun.JSC.URL.hrefFromString(bun.String.fromUTF8(registry_)); - if (href.tag == .Dead) { - try log.addErrorFmt(null, logger.Loc.Empty, bun.default_allocator, "${s} has invalid URL {}", .{ - registry_key, strings.QuotedFormatter{ - .text = registry_, - }, - }); - } else { - defer href.deref(); - - api_registry.token = prev_scope.token; - this.scope = try Npm.Registry.Scope.fromAPI("", api_registry, allocator, env); - api_registry.url = try href.toOwnedSlice(bun.default_allocator); - did_set = true; - } + api_registry.url = registry_; + api_registry.token = prev_scope.token; + this.scope = try Npm.Registry.Scope.fromAPI("", api_registry, allocator, env); + did_set = true; } } } @@ -4651,15 +4626,7 @@ pub const PackageManager = struct { if (cli.registry.len > 0 and strings.startsWith(cli.registry, "https://") or strings.startsWith(cli.registry, "http://")) { - if (URL.fromUTF8(instance.allocator, cli.registry)) |url| { - this.scope.url = url; - } else |_| { - try log.addErrorFmt(null, logger.Loc.Empty, bun.default_allocator, "--registry has invalid URL {}", .{ - strings.QuotedFormatter{ - .text = cli.registry, - }, - }); - } + this.scope.url = URL.parse(cli.registry); } if (cli.exact) { @@ -4914,21 +4881,21 @@ pub const PackageManager = struct { // 3. There is a "dependencies" (or equivalent list), and the package name exists in multiple lists ast_modifier: { // Try to use the existing spot in the dependencies list if possible - for (updates) |*update| { - for (dependency_lists_to_check) |list| { + for (updates) |*request| { + inline for ([_]string{ "dependencies", "devDependencies", "optionalDependencies" }) |list| { if (current_package_json.asProperty(list)) |query| { if (query.expr.data == .e_object) { if (query.expr.asProperty( - if (update.is_aliased) - update.name + if (request.is_aliased) + request.name else - update.version.literal.slice(update.version_buf), + request.version.literal.slice(request.version_buf), )) |value| { if (value.expr.data == .e_string) { - if (!update.resolved_name.isEmpty() and strings.eql(list, dependency_list)) { + if (!request.resolved_name.isEmpty() and strings.eql(list, dependency_list)) { replacing += 1; } else { - update.e_string = value.expr.data.e_string; + request.e_string = value.expr.data.e_string; remaining -= 1; } } @@ -4953,16 +4920,16 @@ pub const PackageManager = struct { bun.copy(G.Property, new_dependencies, dependencies); @memset(new_dependencies[dependencies.len..], G.Property{}); - outer: for (updates) |*update| { - if (update.e_string != null) continue; - defer if (comptime Environment.allow_assert) std.debug.assert(update.e_string != null); + outer: for (updates) |*request| { + if (request.e_string != null) continue; + defer if (comptime Environment.allow_assert) std.debug.assert(request.e_string != null); var k: usize = 0; while (k < new_dependencies.len) : (k += 1) { if (new_dependencies[k].key) |key| { - if (!update.is_aliased and !update.resolved_name.isEmpty() and key.data.e_string.eql( + if (!request.is_aliased and !request.resolved_name.isEmpty() and key.data.e_string.eql( string, - update.resolved_name.slice(update.version_buf), + request.resolved_name.slice(request.version_buf), )) { // This actually is a duplicate which we did not // pick up before dependency resolution. @@ -4977,12 +4944,12 @@ pub const PackageManager = struct { } if (key.data.e_string.eql( string, - if (update.is_aliased) - update.name + if (request.is_aliased) + request.name else - update.version.literal.slice(update.version_buf), + request.version.literal.slice(request.version_buf), )) { - if (update.resolved_name.isEmpty()) { + if (request.resolved_name.isEmpty()) { // This actually is a duplicate like "react" // appearing in both "dependencies" and "optionalDependencies". // For this case, we'll just swap remove it @@ -5002,12 +4969,12 @@ pub const PackageManager = struct { new_dependencies[k].key = try JSAst.Expr.init( JSAst.E.String, JSAst.E.String{ - .data = try allocator.dupe(u8, if (update.is_aliased) - update.name - else if (update.resolved_name.isEmpty()) - update.version.literal.slice(update.version_buf) + .data = try allocator.dupe(u8, if (request.is_aliased) + request.name + else if (request.resolved_name.isEmpty()) + request.version.literal.slice(request.version_buf) else - update.resolved_name.slice(update.version_buf)), + request.resolved_name.slice(request.version_buf)), }, logger.Loc.Empty, ).clone(allocator); @@ -5020,8 +4987,8 @@ pub const PackageManager = struct { }, logger.Loc.Empty, ).clone(allocator); - update.e_string = new_dependencies[k].value.?.data.e_string; - if (update.is_aliased) continue :outer; + request.e_string = new_dependencies[k].value.?.data.e_string; + if (request.is_aliased) continue :outer; } } } @@ -5085,26 +5052,26 @@ pub const PackageManager = struct { } } - for (updates) |*update| { - if (update.e_string) |e_string| { - e_string.data = switch (update.resolution.tag) { - .npm => if (update.version.tag == .dist_tag and update.version.literal.isEmpty()) + for (updates) |*request| { + if (request.e_string) |e_string| { + e_string.data = switch (request.resolution.tag) { + .npm => if (request.version.tag == .dist_tag and request.version.literal.isEmpty()) switch (exact_versions) { false => std.fmt.allocPrint(allocator, "^{}", .{ - update.resolution.value.npm.version.fmt(update.version_buf), + request.resolution.value.npm.version.fmt(request.version_buf), }) catch unreachable, true => std.fmt.allocPrint(allocator, "{}", .{ - update.resolution.value.npm.version.fmt(update.version_buf), + request.resolution.value.npm.version.fmt(request.version_buf), }) catch unreachable, } else null, - .uninitialized => switch (update.version.tag) { + .uninitialized => switch (request.version.tag) { .uninitialized => try allocator.dupe(u8, latest), else => null, }, else => null, - } orelse try allocator.dupe(u8, update.version.literal.slice(update.version_buf)); + } orelse try allocator.dupe(u8, request.version.literal.slice(request.version_buf)); } } } @@ -5113,6 +5080,7 @@ pub const PackageManager = struct { // Corresponds to possible commands from the CLI. pub const Subcommand = enum { install, + update, pm, add, remove, @@ -5120,19 +5088,7 @@ pub const PackageManager = struct { unlink, }; - pub fn init( - ctx: Command.Context, - package_json_file_: ?std.fs.File, - comptime subcommand: Subcommand, - ) !*PackageManager { - return initMaybeInstall(ctx, package_json_file_, subcommand); - } - - fn initMaybeInstall( - ctx: Command.Context, - package_json_file_: ?std.fs.File, - comptime subcommand: Subcommand, - ) !*PackageManager { + pub fn init(ctx: Command.Context, comptime subcommand: Subcommand) !*PackageManager { const cli = try CommandLineArguments.parse(ctx.allocator, subcommand); if (comptime subcommand == .install) { @@ -5142,12 +5098,11 @@ pub const PackageManager = struct { } var _ctx = ctx; - return initWithCLI(&_ctx, package_json_file_, cli, subcommand); + return initWithCLI(&_ctx, cli, subcommand); } fn initWithCLI( ctx: *Command.Context, - package_json_file_: ?std.fs.File, cli: CommandLineArguments, comptime subcommand: Subcommand, ) !*PackageManager { @@ -5172,7 +5127,7 @@ pub const PackageManager = struct { // // We will walk up from the cwd, calling chdir on each directory until we find a package.json // If we fail to find one, we will report an error saying no packages to install - const package_json_file = package_json_file_ orelse brk: { + const package_json_file = brk: { var this_cwd = original_cwd; const child_json = child: { while (true) { @@ -5471,40 +5426,35 @@ pub const PackageManager = struct { return manager; } - fn attemptToCreatePackageJSON() !std.fs.File { - var package_json_file = std.fs.cwd().createFileZ("package.json", .{ .read = true }) catch |err| { + fn attemptToCreatePackageJSON() !void { + const package_json_file = std.fs.cwd().createFileZ("package.json", .{ .read = true }) catch |err| { Output.prettyErrorln("error: {s} create package.json", .{@errorName(err)}); Global.crash(); }; + defer package_json_file.close(); try package_json_file.pwriteAll("{\"dependencies\": {}}", 0); - return package_json_file; } - pub inline fn add( - ctx: Command.Context, - ) !void { + pub inline fn update(ctx: Command.Context) !void { + try updatePackageJSONAndInstall(ctx, .update, .update); + } + + pub inline fn add(ctx: Command.Context) !void { try updatePackageJSONAndInstall(ctx, .add, .add); } - pub inline fn remove( - ctx: Command.Context, - ) !void { + pub inline fn remove(ctx: Command.Context) !void { try updatePackageJSONAndInstall(ctx, .remove, .remove); } - pub inline fn link( - ctx: Command.Context, - ) !void { - var manager = PackageManager.init(ctx, null, .link) catch |err| brk: { - switch (err) { - error.MissingPackageJSON => { - var package_json_file = try attemptToCreatePackageJSON(); - break :brk try PackageManager.init(ctx, package_json_file, .link); - }, - else => return err, + pub inline fn link(ctx: Command.Context) !void { + var manager = PackageManager.init(ctx, .link) catch |err| brk: { + if (err == error.MissingPackageJSON) { + try attemptToCreatePackageJSON(); + break :brk try PackageManager.init(ctx, .link); } - unreachable; + return err; }; if (manager.options.shouldPrintCommandName()) { @@ -5642,24 +5592,19 @@ pub const PackageManager = struct { } else { // bun link lodash switch (manager.options.log_level) { - inline else => |log_level| try updatePackageJSONAndInstallWithManager(ctx, manager, .link, log_level), + inline else => |log_level| try manager.updatePackageJSONAndInstallWithManager(ctx, .link, log_level), } } } - pub inline fn unlink( - ctx: Command.Context, - ) !void { - var manager = PackageManager.init(ctx, null, .unlink) catch |err| brk: { - switch (err) { - error.MissingPackageJSON => { - var package_json_file = try attemptToCreatePackageJSON(); - break :brk try PackageManager.init(ctx, package_json_file, .unlink); - }, - else => return err, + pub inline fn unlink(ctx: Command.Context) !void { + var manager = PackageManager.init(ctx, .unlink) catch |err| brk: { + if (err == error.MissingPackageJSON) { + try attemptToCreatePackageJSON(); + break :brk try PackageManager.init(ctx, .unlink); } - unreachable; + return err; }; if (manager.options.shouldPrintCommandName()) { @@ -5806,15 +5751,24 @@ pub const PackageManager = struct { }; const install_params = install_params_ ++ [_]ParamType{ + clap.parseParam("-d, --dev Add dependency to \"devDependencies\"") catch unreachable, + clap.parseParam("-D, --development") catch unreachable, + clap.parseParam("--optional Add dependency to \"optionalDependencies\"") catch unreachable, + clap.parseParam("--exact Add the exact version instead of the ^range") catch unreachable, clap.parseParam(" ... ") catch unreachable, }; + const update_params = install_params_ ++ [_]ParamType{ + clap.parseParam(" ... \"name\" of packages to update") catch unreachable, + }; + const pm_params = install_params_ ++ [_]ParamType{ clap.parseParam(" ... ") catch unreachable, }; const add_params = install_params_ ++ [_]ParamType{ - clap.parseParam("-d, --development Add dependency to \"devDependencies\"") catch unreachable, + clap.parseParam("-d, --dev Add dependency to \"devDependencies\"") catch unreachable, + clap.parseParam("-D, --development") catch unreachable, clap.parseParam("--optional Add dependency to \"optionalDependencies\"") catch unreachable, clap.parseParam("--exact Add the exact version instead of the ^range") catch unreachable, clap.parseParam(" ... \"name\" or \"name@version\" of packages to install") catch unreachable, @@ -5886,6 +5840,7 @@ pub const PackageManager = struct { pub fn parse(allocator: std.mem.Allocator, comptime subcommand: Subcommand) !CommandLineArguments { comptime var params: []const ParamType = &switch (subcommand) { .install => install_params, + .update => update_params, .pm => pm_params, .add => add_params, .remove => remove_params, @@ -5944,8 +5899,8 @@ pub const PackageManager = struct { cli.link_native_bins = args.options("--link-native-bins"); - if (comptime subcommand == .add) { - cli.development = args.flag("--development"); + if (comptime subcommand == .add or subcommand == .install) { + cli.development = args.flag("--development") or args.flag("--dev"); cli.optional = args.flag("--optional"); cli.exact = args.flag("--exact"); } @@ -6125,21 +6080,25 @@ pub const PackageManager = struct { comptime op: Lockfile.Package.Diff.Op, comptime subcommand: Subcommand, ) !void { - var manager = PackageManager.init(ctx, null, subcommand) catch |err| brk: { - switch (err) { - error.MissingPackageJSON => { - if (op == .add or op == .update) { - var package_json_file = try attemptToCreatePackageJSON(); - break :brk try PackageManager.init(ctx, package_json_file, subcommand); - } - - Output.prettyErrorln("No package.json, so nothing to remove\n", .{}); - Global.crash(); - }, - else => return err, + var manager = init(ctx, subcommand) catch |err| brk: { + if (err == error.MissingPackageJSON) { + switch (op) { + .update => { + Output.prettyErrorln("No package.json, so nothing to update\n", .{}); + Global.crash(); + }, + .remove => { + Output.prettyErrorln("No package.json, so nothing to remove\n", .{}); + Global.crash(); + }, + else => { + try attemptToCreatePackageJSON(); + break :brk try PackageManager.init(ctx, subcommand); + }, + } } - unreachable; + return err; }; if (manager.options.shouldPrintCommandName()) { @@ -6148,20 +6107,13 @@ pub const PackageManager = struct { } switch (manager.options.log_level) { - inline else => |log_level| try updatePackageJSONAndInstallWithManager(ctx, manager, op, log_level), + inline else => |log_level| try manager.updatePackageJSONAndInstallWithManager(ctx, op, log_level), } } - const dependency_lists_to_check = [_]string{ - "dependencies", - "devDependencies", - "optionalDependencies", - "peerDependencies", - }; - fn updatePackageJSONAndInstallWithManager( - ctx: Command.Context, manager: *PackageManager, + ctx: Command.Context, comptime op: Lockfile.Package.Diff.Op, comptime log_level: Options.LogLevel, ) !void { @@ -6173,7 +6125,7 @@ pub const PackageManager = struct { const off = @as(u64, @intCast(std.time.milliTimestamp())); switch (op) { - .update, .add => { + .add => { const filler = @import("../cli.zig").HelpCommand.packages_to_add_filler; examples_to_print[0] = filler[@as(usize, @intCast((off) % filler.len))]; @@ -6258,9 +6210,8 @@ pub const PackageManager = struct { } var updates = UpdateRequest.parse(ctx.allocator, ctx.log, manager.options.positionals[1..], &update_requests, op); - try updatePackageJSONAndInstallWithManagerWithUpdates( + try manager.updatePackageJSONAndInstallWithManagerWithUpdates( ctx, - manager, updates, false, op, @@ -6269,8 +6220,8 @@ pub const PackageManager = struct { } fn updatePackageJSONAndInstallWithManagerWithUpdates( - ctx: Command.Context, manager: *PackageManager, + ctx: Command.Context, updates: []UpdateRequest, auto_free: bool, comptime op: Lockfile.Package.Diff.Op, @@ -6340,21 +6291,20 @@ pub const PackageManager = struct { } } + const dependency_list = if (manager.options.update.development) + "devDependencies" + else if (manager.options.update.optional) + "optionalDependencies" + else + "dependencies"; var any_changes = false; - var dependency_list: string = "dependencies"; - if (manager.options.update.development) { - dependency_list = "devDependencies"; - } else if (manager.options.update.optional) { - dependency_list = "optionalDependencies"; - } - switch (op) { .remove => { // if we're removing, they don't have to specify where it is installed in the dependencies list // they can even put it multiple times and we will just remove all of them - for (updates) |update| { - inline for (dependency_lists_to_check) |list| { + for (updates) |request| { + inline for ([_]string{ "dependencies", "devDependencies", "optionalDependencies", "peerDependencies" }) |list| { if (current_package_json.asProperty(list)) |query| { if (query.expr.data == .e_object) { var dependencies = query.expr.data.e_object.properties.slice(); @@ -6362,7 +6312,7 @@ pub const PackageManager = struct { var new_len = dependencies.len; while (i < dependencies.len) : (i += 1) { if (dependencies[i].key.?.data == .e_string) { - if (dependencies[i].key.?.data.e_string.eql(string, update.name)) { + if (dependencies[i].key.?.data.e_string.eql(string, request.name)) { if (new_len > 1) { dependencies[i] = dependencies[new_len - 1]; new_len -= 1; @@ -6403,7 +6353,7 @@ pub const PackageManager = struct { } manager.to_remove = updates; }, - .link, .add, .update => { + .link, .add => { try PackageJSONEditor.edit( ctx.allocator, updates, @@ -6413,6 +6363,10 @@ pub const PackageManager = struct { ); manager.package_json_updates = updates; }, + .update => { + manager.package_json_updates = updates; + manager.to_update = true; + }, else => {}, } @@ -6446,8 +6400,8 @@ pub const PackageManager = struct { try manager.installWithManager(ctx, new_package_json_source, log_level); if (op == .update or op == .add or op == .link) { - for (manager.package_json_updates) |update| { - if (update.failed) { + for (manager.package_json_updates) |request| { + if (request.failed) { Global.exit(1); return; } @@ -6503,14 +6457,14 @@ pub const PackageManager = struct { bun.copy(u8, &node_modules_buf, "node_modules" ++ std.fs.path.sep_str); var offset_buf = node_modules_buf["node_modules/".len..]; const name_hashes = manager.lockfile.packages.items(.name_hash); - for (updates) |update| { + for (updates) |request| { // If the package no longer exists in the updated lockfile, delete the directory // This is not thorough. // It does not handle nested dependencies // This is a quick & dirty cleanup intended for when deleting top-level dependencies - if (std.mem.indexOfScalar(PackageNameHash, name_hashes, String.Builder.stringHash(update.name)) == null) { - bun.copy(u8, offset_buf, update.name); - cwd.deleteTree(node_modules_buf[0 .. "node_modules/".len + update.name.len]) catch {}; + if (std.mem.indexOfScalar(PackageNameHash, name_hashes, String.Builder.stringHash(request.name)) == null) { + bun.copy(u8, offset_buf, request.name); + cwd.deleteTree(node_modules_buf[0 .. "node_modules/".len + request.name.len]) catch {}; } } @@ -6549,7 +6503,7 @@ pub const PackageManager = struct { var package_json_cwd: string = ""; pub inline fn install(ctx: Command.Context) !void { - var manager = initMaybeInstall(ctx, null, .install) catch |err| { + var manager = init(ctx, .install) catch |err| { if (err == error.SwitchToBunAdd) { return add(ctx); } @@ -7537,15 +7491,16 @@ pub const PackageManager = struct { manager.summary = try Package.Diff.generate( ctx.allocator, + ctx.log, manager.lockfile, &lockfile, &root, &maybe_root, + if (manager.to_update) manager.package_json_updates else null, mapping, ); - const sum = manager.summary.add + manager.summary.remove + manager.summary.update; - had_any_diffs = had_any_diffs or sum > 0; + had_any_diffs = had_any_diffs or manager.summary.hasDiffs(); if (manager.options.enable.frozen_lockfile and had_any_diffs) { if (comptime log_level != .silent) { @@ -7554,13 +7509,12 @@ pub const PackageManager = struct { Global.crash(); } - // If you changed packages, we will copy over the new package from the new lockfile - const new_dependencies = maybe_root.dependencies.get(lockfile.buffers.dependencies.items); - if (had_any_diffs) { var builder_ = manager.lockfile.stringBuilder(); // ensure we use one pointer to reference it instead of creating new ones and potentially aliasing var builder = &builder_; + // If you changed packages, we will copy over the new package from the new lockfile + const new_dependencies = maybe_root.dependencies.get(lockfile.buffers.dependencies.items); for (new_dependencies) |new_dep| { new_dep.count(lockfile.buffers.string_bytes.items, *Lockfile.StringBuilder, builder); @@ -7716,9 +7670,9 @@ pub const PackageManager = struct { } if (manager.lockfile.packages.len > 0) { - for (manager.package_json_updates) |update| { + for (manager.package_json_updates) |request| { // prevent redundant errors - if (update.failed) { + if (request.failed) { return error.InstallFailed; } } @@ -7895,8 +7849,8 @@ pub const PackageManager = struct { } } else if (manager.summary.remove > 0) { if (manager.to_remove.len > 0) { - for (manager.to_remove) |update| { - Output.prettyln(" - {s}", .{update.name}); + for (manager.to_remove) |request| { + Output.prettyln(" - {s}", .{request.name}); } } diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig index 73347871a3622e..52b340d7d988d0 100644 --- a/src/install/lockfile.zig +++ b/src/install/lockfile.zig @@ -137,7 +137,7 @@ pub const Scripts = struct { pub fn run(this: *Scripts, allocator: Allocator, env: *DotEnv.Loader, silent: bool, comptime hook: []const u8) !void { for (@field(this, hook).items) |entry| { if (comptime Environment.allow_assert) std.debug.assert(Fs.FileSystem.instance_loaded); - _ = try RunCommand.runPackageScript(allocator, entry.script, hook, entry.cwd, env, &.{}, silent); + _ = try RunCommand.runPackageScript(allocator, entry.script, hook, entry.cwd, env, &.{}, silent, null); } } @@ -886,29 +886,32 @@ pub const Printer = struct { pub const Format = enum { yarn }; - var lockfile_path_buf1: [bun.MAX_PATH_BYTES]u8 = undefined; - var lockfile_path_buf2: [bun.MAX_PATH_BYTES]u8 = undefined; - pub fn print( allocator: Allocator, log: *logger.Log, - lockfile_path_: string, + input_lockfile_path: string, format: Format, ) !void { @setCold(true); + // We truncate longer than allowed paths. We should probably throw an error instead. + var path = input_lockfile_path[0..@min(input_lockfile_path.len, bun.MAX_PATH_BYTES)]; + + var lockfile_path_buf1: [bun.MAX_PATH_BYTES]u8 = undefined; + var lockfile_path_buf2: [bun.MAX_PATH_BYTES]u8 = undefined; + var lockfile_path: stringZ = ""; - if (!std.fs.path.isAbsolute(lockfile_path_)) { + if (!std.fs.path.isAbsolute(path)) { var cwd = try std.os.getcwd(&lockfile_path_buf1); - var parts = [_]string{lockfile_path_}; + var parts = [_]string{path}; var lockfile_path__ = Path.joinAbsStringBuf(cwd, &lockfile_path_buf2, &parts, .auto); lockfile_path_buf2[lockfile_path__.len] = 0; lockfile_path = lockfile_path_buf2[0..lockfile_path__.len :0]; - } else { - bun.copy(u8, &lockfile_path_buf1, lockfile_path); - lockfile_path_buf1[lockfile_path_.len] = 0; - lockfile_path = lockfile_path_buf1[0..lockfile_path_.len :0]; + } else if (path.len > 0) { + @memcpy(lockfile_path_buf1[0..path.len], path); + lockfile_path_buf1[path.len] = 0; + lockfile_path = lockfile_path_buf1[0..path.len :0]; } if (lockfile_path.len > 0 and lockfile_path[0] == std.fs.path.sep) @@ -942,8 +945,8 @@ pub const Printer = struct { Global.crash(); }, .not_found => { - Output.prettyErrorln("lockfile not found: {s}", .{ - std.mem.sliceAsBytes(lockfile_path), + Output.prettyErrorln("lockfile not found: {}", .{ + strings.QuotedFormatter{ .text = std.mem.sliceAsBytes(lockfile_path) }, }); Global.crash(); }, @@ -1234,7 +1237,7 @@ pub const Printer = struct { } var dependency_versions = requested_version_start[0..j]; - if (dependency_versions.len > 1) std.sort.insertion(Dependency.Version, dependency_versions, string_buf, Dependency.Version.isLessThan); + if (dependency_versions.len > 1) std.sort.insertion(Dependency.Version, dependency_versions, string_buf, Dependency.Version.isLessThanWithTag); try requested_versions.put(i, dependency_versions); } } @@ -2371,36 +2374,49 @@ pub const Package = extern struct { add: u32 = 0, remove: u32 = 0, update: u32 = 0, - deduped: u32 = 0, pub inline fn sum(this: *Summary, that: Summary) void { this.add += that.add; this.remove += that.remove; this.update += that.update; - this.deduped += that.deduped; + } + + pub inline fn hasDiffs(this: Summary) bool { + return this.add > 0 or this.remove > 0 or this.update > 0; } }; pub fn generate( - _: Allocator, + allocator: Allocator, + log: *logger.Log, from_lockfile: *Lockfile, to_lockfile: *Lockfile, from: *Lockfile.Package, to: *Lockfile.Package, - mapping: []PackageID, + update_requests: ?[]PackageManager.UpdateRequest, + id_mapping: ?[]PackageID, ) !Summary { var summary = Summary{}; const to_deps = to.dependencies.get(to_lockfile.buffers.dependencies.items); const from_deps = from.dependencies.get(from_lockfile.buffers.dependencies.items); + const from_resolutions = from.resolutions.get(from_lockfile.buffers.resolutions.items); + var to_i: usize = 0; for (from_deps, 0..) |*from_dep, i| { - // common case: dependency is present in both versions and in the same position - const to_i = if (to_deps.len > i and to_deps[i].name_hash == from_dep.name_hash) - i - else brk: { + found: { + const prev_i = to_i; + + // common case, dependency is present in both versions: + // - in the same position + // - shifted by a constant offset + while (to_i < to_deps.len) : (to_i += 1) { + if (from_dep.name_hash == to_deps[to_i].name_hash) break :found; + } + // less common, o(n^2) case - for (to_deps, 0..) |to_dep, j| { - if (from_dep.name_hash == to_dep.name_hash) break :brk j; + to_i = 0; + while (to_i < prev_i) : (to_i += 1) { + if (from_dep.name_hash == to_deps[to_i].name_hash) break :found; } // We found a removed dependency! @@ -2408,26 +2424,69 @@ pub const Package = extern struct { // It will be cleaned up later summary.remove += 1; continue; - }; + } + defer to_i += 1; if (to_deps[to_i].eql(from_dep, to_lockfile.buffers.string_bytes.items, from_lockfile.buffers.string_bytes.items)) { - mapping[to_i] = @as(PackageID, @truncate(i)); - continue; + if (update_requests) |updates| { + if (updates.len == 0 or brk: { + for (updates) |request| { + if (from_dep.name_hash == request.name_hash) break :brk true; + } + break :brk false; + }) { + // Listed as to be updated + summary.update += 1; + continue; + } + } + + if (id_mapping) |mapping| { + const version = to_deps[to_i].version; + if (switch (version.tag) { + .workspace => if (to_lockfile.workspace_paths.getPtr(@truncate(from_dep.name_hash))) |path_ptr| brk: { + const path = to_lockfile.str(path_ptr); + var file = std.fs.cwd().openFile(Path.join( + &[_]string{ path, "package.json" }, + .auto, + ), .{ .mode = .read_only }) catch break :brk false; + defer file.close(); + const bytes = try file.readToEndAlloc(allocator, std.math.maxInt(usize)); + defer allocator.free(bytes); + const source = logger.Source.initPathString(path, bytes); + + var workspace = Package{}; + try workspace.parseMain(to_lockfile, allocator, log, source, Features.workspace); + + var from_pkg = from_lockfile.packages.get(from_resolutions[i]); + const diff = try generate( + allocator, + log, + from_lockfile, + to_lockfile, + &from_pkg, + &workspace, + update_requests, + null, + ); + + break :brk !diff.hasDiffs(); + } else false, + else => true, + }) { + mapping[to_i] = @truncate(i); + continue; + } + } else { + continue; + } } // We found a changed dependency! summary.update += 1; } - outer: for (to_deps, 0..) |to_dep, i| { - if (from_deps.len > i and from_deps[i].name_hash == to_dep.name_hash) continue; - - for (from_deps) |from_dep| { - if (from_dep.name_hash == to_dep.name_hash) continue :outer; - } - - summary.add += 1; - } + summary.add = @truncate(to_deps.len - (from_deps.len - summary.remove)); return summary; } @@ -2515,8 +2574,21 @@ pub const Package = extern struct { &sliced, log, ) orelse Dependency.Version{}; + var workspace_range: ?Semver.Query.Group = null; const name_hash = switch (dependency_version.tag) { .npm => String.Builder.stringHash(dependency_version.value.npm.name.slice(buf)), + .workspace => if (strings.hasPrefixComptime(sliced.slice, "workspace:")) brk: { + const input = sliced.slice["workspace:".len..]; + if (!strings.eqlComptime(input, "*")) { + const at = strings.lastIndexOfChar(input, '@') orelse 0; + if (at > 0) { + workspace_range = Semver.Query.parse(allocator, input[at + 1 ..], sliced) catch return error.InstallFailed; + break :brk String.Builder.stringHash(input[0..at]); + } + workspace_range = Semver.Query.parse(allocator, input, sliced) catch null; + } + break :brk external_alias.hash; + } else external_alias.hash, else => external_alias.hash, }; const workspace_path = if (comptime tag == null) lockfile.workspace_paths.get(@truncate(name_hash)) else null; @@ -2564,74 +2636,90 @@ pub const Package = extern struct { } }, .workspace => if (workspace_path) |path| { - dependency_version.value.workspace = path; + if (workspace_range) |range| { + if (workspace_version) |ver| { + if (range.satisfies(ver)) { + dependency_version.literal = path; + dependency_version.value.workspace = path; + } + } + } else { + dependency_version.literal = path; + dependency_version.value.workspace = path; + } } else { - { - const workspace = dependency_version.value.workspace.slice(buf); - var path = string_builder.append( - String, - if (strings.eqlComptime(workspace, "*")) "*" else Path.relative( + const workspace = dependency_version.value.workspace.slice(buf); + const path = string_builder.append( + String, + if (strings.eqlComptime(workspace, "*")) "*" else Path.relative( + FileSystem.instance.top_level_dir, + Path.joinAbsString( FileSystem.instance.top_level_dir, - Path.joinAbsString( - FileSystem.instance.top_level_dir, - &[_]string{ - source.path.name.dir, - workspace, - }, - .posix, - ), + &[_]string{ + source.path.name.dir, + workspace, + }, + .posix, ), - ); - defer dependency_version.value.workspace = path; - var workspace_entry = try lockfile.workspace_paths.getOrPut(allocator, @truncate(name_hash)); - if (workspace_entry.found_existing) { - const old_path = workspace_entry.value_ptr.*; + ), + ); + if (comptime Environment.allow_assert) { + std.debug.assert(path.len() > 0); + std.debug.assert(!std.fs.path.isAbsolute(path.slice(buf))); + } + dependency_version.literal = path; + dependency_version.value.workspace = path; - if (strings.eqlComptime(workspace, "*")) { - path = old_path; - return null; - } else if (strings.eqlComptime(old_path.slice(buf), "*")) brk: { - workspace_entry.value_ptr.* = path; - for (package_dependencies[0..dependencies_count]) |*package_dep| { - if (String.Builder.stringHash(package_dep.realname().slice(buf)) == name_hash) { - if (package_dep.version.tag != .workspace) break :brk; - package_dep.version.value.workspace = path; - return null; - } - } - return error.InstallFailed; - } else if (strings.eql(old_path.slice(buf), path.slice(buf))) { - return null; - } else { - log.addErrorFmt(&source, logger.Loc.Empty, allocator, "Workspace name \"{s}\" already exists", .{ - external_alias.slice(buf), - }) catch {}; - return error.InstallFailed; - } + var workspace_entry = try lockfile.workspace_paths.getOrPut(allocator, @truncate(name_hash)); + if (workspace_entry.found_existing) { + if (strings.eqlComptime(workspace, "*")) return null; + + const old_path = workspace_entry.value_ptr.*.slice(buf); + if (!strings.eqlComptime(old_path, "*")) { + if (strings.eql(old_path, path.slice(buf))) return null; + + log.addErrorFmt(&source, logger.Loc.Empty, allocator, "Workspace name \"{s}\" already exists", .{ + external_alias.slice(buf), + }) catch {}; + return error.InstallFailed; } - workspace_entry.value_ptr.* = path; } + workspace_entry.value_ptr.* = path; if (workspace_version) |ver| { try lockfile.workspace_versions.put(allocator, @truncate(name_hash), ver); for (package_dependencies[0..dependencies_count]) |*package_dep| { - // `dependencies` & `workspaces` defined within the same `package.json` - if (package_dep.version.tag == .npm and - String.Builder.stringHash(package_dep.version.value.npm.name.slice(buf)) == name_hash and - package_dep.version.value.npm.version.satisfies(ver)) + if (switch (package_dep.version.tag) { + // `dependencies` & `workspaces` defined within the same `package.json` + .npm => String.Builder.stringHash(package_dep.realname().slice(buf)) == name_hash and + package_dep.version.value.npm.version.satisfies(ver), + // `workspace:*` + .workspace => workspace_entry.found_existing and + String.Builder.stringHash(package_dep.realname().slice(buf)) == name_hash, + else => false, + }) { + package_dep.version = dependency_version; + return null; + } + } + } else if (workspace_entry.found_existing) { + for (package_dependencies[0..dependencies_count]) |*package_dep| { + if (package_dep.version.tag == .workspace and + String.Builder.stringHash(package_dep.realname().slice(buf)) == name_hash) { package_dep.version = dependency_version; return null; } } + return error.InstallFailed; } }, else => {}, } const this_dep = Dependency{ - .behavior = group.behavior.setWorkspace(in_workspace), + .behavior = if (in_workspace) group.behavior.setWorkspace(in_workspace) else group.behavior, .name = external_alias.value, .name_hash = external_alias.hash, .version = dependency_version, diff --git a/src/install/npm.zig b/src/install/npm.zig index b135a9548f2417..0a25fe6360759f 100644 --- a/src/install/npm.zig +++ b/src/install/npm.zig @@ -68,7 +68,7 @@ pub const Registry = struct { pub fn fromAPI(name: string, registry_: Api.NpmRegistry, allocator: std.mem.Allocator, env: *DotEnv.Loader) !Scope { var registry = registry_; - var url = try URL.fromUTF8(bun.default_allocator, registry.url); + var url = URL.parse(registry.url); var auth: string = ""; if (registry.token.len == 0) { diff --git a/src/js/README.md b/src/js/README.md index c5f75eeecd9d59..8f270ed2ae0f60 100644 --- a/src/js/README.md +++ b/src/js/README.md @@ -1,30 +1,119 @@ # JS Modules +**TLDR**: If anything here changes, re-run `make js`. If you add/remove files, `make regenerate-bindings`. + - `./node` contains all `node:*` modules - `./bun` contains all `bun:*` modules - `./thirdparty` contains npm modules we replace like `ws` +- `./internal` contains modules that aren't assigned to the module resolver + +Each `.ts`/`.js` file above is assigned a numeric id at compile time and inlined into an array of lazily initialized modules. Internal modules referencing each other is extremely optimized, skipping the module resolver entirely. + +## Builtins Syntax + +Within these files, the `$` prefix on variables can be used to access private property names as well as JSC intrinsics. -When you change any of those folders, run this to bundle and minify them: +```ts +// Many globals have private versions which are impossible for the user to +// tamper with. Though, these global variables are auto-prefixed by the bundler. +const hello = $Array.from(...); -```bash -$ make esm +// Similar situation with prototype values. These aren't autoprefixed since it depends on type. +something.$then(...); +map.$set(...); + +// Internal variables we define +$requireMap.$has("elysia"); + +// JSC engine intrinsics. These usually translate directly to bytecode instructions. +const arr = $newArrayWithSize(5); +// A side effect of this is that using an intrinsic incorrectly like +// this will fail to parse and cause a segfault. +console.log($getInternalField) ``` -These modules are bundled into the binary, but in debug mode they are loaded from the filesystem, so you do not need to rerun `make dev`. If you want to override the modules in a release build, you can set `BUN_OVERRIDE_MODULE_PATH` to the path to the repo: +V8 has a [similar feature](https://v8.dev/blog/embedded-builtins) to this syntax (they use `%` instead) + +On top of this, we have some special functions that are handled by the bundle preprocessor: + +- `require` works, but it must be a string literal that resolves to a module within src/js. This call gets replaced with `$requireId(id)`, which is a special function that skips the module resolver and directly loads the module by it's generated numerical ID. -```bash -$ BUN_OVERRIDE_MODULE_PATH=/path/to/bun-repo bun ... +- `$debug` is exactly like console.log, but is stripped in release builds. It is disabled by default, requiring you to pass one of: `BUN_DEBUG_MODULE_NAME=1`, `BUN_DEBUG_JS=1`, or `BUN_DEBUG_ALL=1`. You can also do `if($debug) {}` to check if debug env var is set. + +- `IS_BUN_DEVELOPMENT` is inlined to be `true` in all development builds. + +- `process.platform` is properly inlined and DCE'd. Do use this to run different code on different platforms. + +- `$bundleError()` is like Zig's `@compileError`. It will stop a compile from succeeding. + +## Builtin Modules + +In module files, instead of using `module.exports`, use the `export default` variable. Due to the internal implementation, these must be `JSCell` types (function / object). + +```ts +export default { + hello: 2, + world: 3, +}; ``` -For any private types like `Bun.fs()`, add them to `./private.d.ts` +Keep in mind that **these are not ES modules**. `export default` is only syntax sugar to assign to the variable `$exports`, which is actually how the module exports it's contents. `export var` and `export function` are banned syntax, and so is `import` (use `require` instead) -# Builtins +To actually wire up one of these modules to the resolver, that is done separately in `module_resolver.zig`. Maybe in the future we can do codegen for it. -- `./builtins` contains builtins that use intrinsics. They're inlined into generated C++ code. It's a separate system, see the readme in that folder. +## Builtin Functions -When anything in that is changed, run this to regenerate the code: +`./functions` contains isolated functions. Each function within is bundled separately, meaning you may not use global variables, non-type `import`s, and even directly referencing the other functions in these files. `require` is still resolved the same way it does in the modules. -```make -$ make regenerate-bindings -$ make bun-link-lld-debug +In function files, these are accessible in C++ by using `CodeGenerator(vm)`, for example: + +```cpp +object->putDirectBuiltinFunction( + vm, + globalObject, + identifier, + // ReadableStream.ts, `function readableStreamToJSON()` + // This returns a FunctionExecutable* (extends JSCell*, but not JSFunction*). + readableStreamReadableStreamToJSONCodeGenerator(vm), + JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DontDelete | 0 +); ``` + +## Extra Features + +`require` is replaced with `$requireId(id)` which allows these modules to import each other in a way that skips the module resolver. Being written in a syncronous format also makes this faster than ESM. All calls to `require` must be statically known or else this transformation is not possible. + +## Building + +Run `make js` to bundle all the builtins. The output is placed in `src/js/out/{modules,functions}/`, where these files are loaded dynamically by `bun-debug` (an exact filepath is inlined into the binary pointing at where you cloned bun, so moving the binary to another machine may not work). In a release build, these get minified and inlined into the binary (Please commit those generated headers). + +If you change the list of files or functions, you will have to run `make regenerate-bindings`, but otherwise any change can be done with just `make js`. + +## Notes on how the build process works + +_This isn't really required knowledge to use it, but a rough overview of how ./\_codegen/\* works_ + +The build process is built on top of Bun's bundler. The first step is scanning all modules and assigning each a numerical ID. The order is determined by an A-Z sort. + +The `$` for private names is actually a lie, and in JSC it actually uses `@`; though that is a syntax error in regular JS/TS, so we opted for better IDE support. So first we have to pre-process the files to spot all instances of `$` at the start of an identifier and we convert it to `__intrinsic__`. We also scan for `require(string)` and replace it with `$requireId(n)` after resolving it to the integer id, which is defined in `./functions/Module.ts`. `export default` is transformed into `return ...;`, however this transform is a little more complicated that a string replace because it supports that not being the final statement, and access to the underlying variable `$exports`, etc. + +The preprocessor is smart enough to not replace `$` in strings, comments, regex, etc. However, it is not a real JS parser and instead a recursive regex-based nightmare, so may hit some edge cases. Yell at Dave if it breaks. + +The module is then printed like: + +```ts +// @ts-nocheck +$$capture_start$$(function () { + const path = __intrinsic__requireId(23); + // user code is pasted here + return { + cool: path, + }; +}).$$capture_end$$; +``` + +This capture thing is used to extract the function declaration afterwards, this is more useful in the functions case where functions can have arguments, or be async functions. + +After bundling, the inner part is extracted, and then `__intrinsic__` is replaced to `@`. + +These can then be inlined into C++ headers and loaded with `createBuiltin`. This is done in `InternalModuleRegistry.cpp`. diff --git a/src/js/builtins/codegen/index.ts b/src/js/_codegen/build-functions.ts similarity index 97% rename from src/js/builtins/codegen/index.ts rename to src/js/_codegen/build-functions.ts index 564b6968958f92..b5c0eeee9e08b5 100644 --- a/src/js/builtins/codegen/index.ts +++ b/src/js/_codegen/build-functions.ts @@ -8,7 +8,7 @@ import { spawn } 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, "../../../../src/bun.js/scripts/create_hash_table"); + const create_hash_table = path.join(import.meta.dir, "../../../src/bun.js/scripts/create_hash_table"); if (!create_hash_table) { console.warn( "Could not find create_hash_table executable. Run `bun i` or clone webkit to build static hash tables", @@ -16,7 +16,7 @@ async function createStaticHashtables() { return; } for (let cpp of STATIC_HASH_TABLES) { - cpp = path.join(import.meta.dir, "../../../../", cpp); + cpp = path.join(import.meta.dir, "../../../", cpp); const { stdout, exited } = spawn({ cmd: [create_hash_table, cpp], stdout: "pipe", @@ -35,23 +35,22 @@ async function createStaticHashtables() { } const staticHashTablePromise = createStaticHashtables(); -console.log("Bundling Bun builtins..."); +console.log("Bundling Bun builtin functions..."); const MINIFY = process.argv.includes("--minify") || process.argv.includes("-m"); const PARALLEL = process.argv.includes("--parallel") || process.argv.includes("-p"); const KEEP_TMP = process.argv.includes("--keep-tmp") || process.argv.includes("-k") || true; -const SRC_DIR = path.join(import.meta.dir, "../"); +const SRC_DIR = path.join(import.meta.dir, "../builtins"); const OUT_DIR = path.join(SRC_DIR, "../out"); -const TMP_DIR = path.join(SRC_DIR, "../out/tmp"); +const TMP_DIR = path.join(SRC_DIR, "../out/tmp/builtins"); if (existsSync(TMP_DIR)) rmSync(TMP_DIR, { recursive: true }); -mkdirSync(TMP_DIR); +mkdirSync(TMP_DIR, { recursive: true }); const define = { - "process.env.NODE_ENV": "development", - "process.platform": process.platform, - "process.arch": process.arch, + "process.env.NODE_ENV": "production", + "IS_BUN_DEVELOPMENT": "false", }; for (const name in enums) { @@ -170,12 +169,15 @@ async function processFileSplit(filename: string): Promise<{ functions: BundledB params.shift(); } - const { result, rest } = sliceSourceCode(contents.slice(declaration[0].length - 1), true); + const { result, rest } = sliceSourceCode(contents.slice(declaration[0].length - 1), true, x => + globalThis.requireTransformer(x, SRC_DIR + "/" + basename), + ); + functions.push({ name, params, directives, - source: result.trim().slice(1, -1), + source: result.trim().slice(2, -1), async, }); contents = rest; @@ -216,7 +218,7 @@ $$capture_start$$(${fn.async ? "async " : ""}${ const build = await Bun.build({ entrypoints: [tmpFile], define, - minify: true, + minify: { syntax: true, whitespace: true }, }); if (!build.success) { throw new AggregateError(build.logs, "Failed bundling builtin function " + fn.name + " from " + basename + ".ts"); diff --git a/src/js/_codegen/build-modules.ts b/src/js/_codegen/build-modules.ts new file mode 100644 index 00000000000000..f18bee0333aedc --- /dev/null +++ b/src/js/_codegen/build-modules.ts @@ -0,0 +1,384 @@ +import fs from "fs"; +import path from "path"; +import { sliceSourceCode } from "./builtin-parser"; +import { cap, fmtCPPString, readdirRecursive, resolveSyncOrNull } from "./helpers"; +import { createAssertClientJS, createLogClientJS } from "./client-js"; + +let start = performance.now(); +function mark(log: string) { + const now = performance.now(); + console.log(`${log} (${(now - start).toFixed(0)}ms)`); + start = now; +} + +const BASE = path.join(import.meta.dir, "../"); +const TMP = path.join(BASE, "out/tmp"); + +const moduleList = ["bun", "node", "thirdparty", "internal"] + .flatMap(dir => readdirRecursive(path.join(BASE, dir))) + .filter(file => file.endsWith(".js") || (file.endsWith(".ts") && !file.endsWith(".d.ts"))) + .map(file => file.slice(BASE.length)) + .sort(); + +const internalRegistry = new Map(); + +// Build Registry +for (let i = 0; i < moduleList.length; i++) { + const prefix = moduleList[i].startsWith("node/") ? "node:" : moduleList[i].startsWith("bun:") ? "bun/" : undefined; + if (prefix) { + const id = prefix + moduleList[i].slice(prefix.length).replaceAll(".", "/").slice(0, -3); + internalRegistry.set(id, i); + } +} + +// Native Module registry +const nativeModuleH = fs.readFileSync(path.join(BASE, "../bun.js/modules/_NativeModule.h"), "utf8"); +const nativeModuleDefine = nativeModuleH.match(/BUN_FOREACH_NATIVE_MODULE\(macro\)\s*\\\n((.*\\\n)*\n)/); +if (!nativeModuleDefine) { + throw new Error( + "Could not find BUN_FOREACH_NATIVE_MODULE in _NativeModule.h. Knowing native module IDs is a part of the codegen process.", + ); +} +let nextNativeModuleId = 0; +const nativeModuleIds: Record = {}; +const nativeModuleEnums: Record = {}; +const nativeModuleEnumToId: Record = {}; +for (const [_, idString, enumValue] of nativeModuleDefine[0].matchAll(/macro\((.*?),(.*?)\)/g)) { + const processedIdString = JSON.parse(idString.trim().replace(/_s$/, "")); + const processedEnumValue = enumValue.trim(); + const processedNumericId = nextNativeModuleId++; + nativeModuleIds[processedIdString] = processedNumericId; + nativeModuleEnums[processedIdString] = processedEnumValue; + nativeModuleEnumToId[processedEnumValue] = processedNumericId; +} + +mark("Scan internal registry"); + +function codegenRequireId(id: string) { + return `(__intrinsic__getInternalField(__intrinsic__internalModuleRegistry, ${id}) || __intrinsic__createInternalModuleById(${id}))`; +} + +function codegenRequireNativeModule(id: string) { + return `(__intrinsic__requireNativeModule(${id}))`; +} + +globalThis.requireTransformer = (specifier: string, from: string) => { + // this one is deprecated + if (specifier === "$shared") specifier = "./internal/shared.ts"; + + const directMatch = internalRegistry.get(specifier); + if (directMatch) return codegenRequireId(`${directMatch}/*${specifier}*/`); + + if (specifier in nativeModuleIds) { + return `__intrinsic__requireNativeModule(${JSON.stringify(specifier)})`; + } + + const relativeMatch = + resolveSyncOrNull(specifier, path.join(BASE, path.dirname(from))) ?? resolveSyncOrNull(specifier, BASE); + + if (relativeMatch) { + const found = moduleList.indexOf(path.relative(BASE, relativeMatch)); + if (found === -1) { + throw new Error( + `Builtin Bundler: "${specifier}" cannot be imported here because it doesn't get a module ID. Only files in "src/js" besides "src/js/builtins" can be used here.`, + ); + } + return codegenRequireId(`${found}/*${path.relative(BASE, relativeMatch)}*/`); + } + + throw new Error(`Builtin Bundler: Could not resolve "${specifier}" in ${from}. These cannot be relative.`); +}; + +// Preprocess builtins +const bundledEntryPoints: string[] = []; +for (let i = 0; i < moduleList.length; i++) { + try { + const input = fs.readFileSync(path.join(BASE, moduleList[i]), "utf8"); + const processed = sliceSourceCode("{" + input.replace(/export\s*{\s*}\s*;/g, ""), true, x => + globalThis.requireTransformer(x, moduleList[i]), + ); + let fileToTranspile = `// @ts-nocheck +// GENERATED TEMP FILE - DO NOT EDIT +// Sourced from src/js/${moduleList[i]} + +$$capture_start$$(function() { +${processed.result.slice(1)} +return __intrinsic__exports; +}).$$capture_end$$;`; + + // Attempt to optimize "$exports = ..." to a variableless return + // otherwise, declare $exports so it works. + let exportOptimization = false; + fileToTranspile = fileToTranspile.replace( + /__intrinsic__exports\s*=\s*(.*|.*\{[^\}]*}|.*\([^\)]*\));?\n\s*return\s*__intrinsic__exports;/g, + (_, a) => { + exportOptimization = true; + return "return " + a + ";"; + }, + ); + if (!exportOptimization) { + fileToTranspile = fileToTranspile + .replaceAll("__intrinsic__exports", "$") + .replace("$$capture_start$$(function() {", "$$$$capture_start$$$$(function() {var $;"); + } + const outputPath = path.join(TMP, moduleList[i].slice(0, -3) + ".ts"); + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, fileToTranspile); + bundledEntryPoints.push(outputPath); + } catch (error) { + console.error(error); + console.error(`While processing: ${moduleList[i]}`); + process.exit(1); + } +} + +mark("Preprocess modules"); + +const config = ({ platform, debug }: { platform: string; debug?: boolean }) => ({ + entrypoints: bundledEntryPoints, + minify: { syntax: true, whitespace: !debug }, + root: TMP, + define: { + IS_BUN_DEVELOPMENT: String(!!debug), + __intrinsic__debug: debug ? "$debug_log_enabled" : "false", + "process.platform": JSON.stringify(platform), + }, +}); +const bundled_dev = await Bun.build(config({ platform: process.platform, debug: true })); +const bundled_linux = await Bun.build(config({ platform: "linux" })); +const bundled_darwin = await Bun.build(config({ platform: "darwin" })); +const bundled_win32 = await Bun.build(config({ platform: "win32" })); +for (const bundled of [bundled_dev, bundled_linux, bundled_darwin, bundled_win32]) { + if (!bundled.success) { + console.error(bundled.logs); + process.exit(1); + } +} + +mark("Bundle modules"); + +const bundledOutputs = { + host: new Map(), + linux: new Map(), + darwin: new Map(), + win32: new Map(), +}; + +for (const [name, bundle, outputs] of [ + ["modules_dev", bundled_dev, bundledOutputs.host], + ["modules_linux", bundled_linux, bundledOutputs.linux], + ["modules_darwin", bundled_darwin, bundledOutputs.darwin], + ["modules_win32", bundled_win32, bundledOutputs.win32], +] as const) { + for (const file of bundle.outputs) { + const output = await file.text(); + let captured = output.match(/\$\$capture_start\$\$([\s\S]+)\.\$\$capture_end\$\$/)![1]; + let usesDebug = output.includes("$debug_log"); + let usesAssert = output.includes("$assert"); + captured = + captured + .replace(/^\((async )?function\(/, "($1function (") + .replace(/]\s*,\s*__(debug|assert)_end__\)/g, ")") + .replace(/]\s*,\s*__debug_end__\)/g, ")") + .replace(/__intrinsic__lazy\(/g, "globalThis[globalThis.Symbol.for('Bun.lazy')](") + .replace(/__intrinsic__/g, "@") + "\n"; + captured = captured.replace( + /function\s*\(.*?\)\s*{/, + '$&"use strict";' + + (usesDebug + ? createLogClientJS( + file.path.replace(".js", ""), + idToPublicSpecifierOrEnumName(file.path).replace(/^node:|^bun:/, ""), + ) + : "") + + (usesAssert ? createAssertClientJS(idToPublicSpecifierOrEnumName(file.path).replace(/^node:|^bun:/, "")) : ""), + ); + const outputPath = path.join(BASE, "out", name, file.path); + if (name === "modules_dev") { + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, captured); + } + outputs.set(file.path.replace(".js", ""), captured); + } +} + +mark("Postprocesss modules"); + +function idToEnumName(id: string) { + return id + .replace(/\.[mc]?[tj]s$/, "") + .replace(/[^a-zA-Z0-9]+/g, " ") + .split(" ") + .map(x => (["jsc", "ffi", "vm", "tls", "os", "ws", "fs", "dns"].includes(x) ? x.toUpperCase() : cap(x))) + .join(""); +} + +function idToPublicSpecifierOrEnumName(id: string) { + id = id.replace(/\.[mc]?[tj]s$/, ""); + if (id.startsWith("node/")) { + return "node:" + id.slice(5).replaceAll(".", "/"); + } else if (id.startsWith("bun/")) { + return "bun:" + id.slice(4).replaceAll(".", "/"); + } else if (id.startsWith("internal/")) { + return "internal:" + id.slice(9).replaceAll(".", "/"); + } else if (id.startsWith("thirdparty/")) { + return id.slice(11).replaceAll(".", "/"); + } + return idToEnumName(id); +} + +// This is a file with a single macro that is used in defining InternalModuleRegistry.h +fs.writeFileSync( + path.join(BASE, "out/InternalModuleRegistry+numberOfModules.h"), + `#define BUN_INTERNAL_MODULE_COUNT ${moduleList.length}\n`, +); + +// This code slice is used in InternalModuleRegistry.h for inlining the enum. I dont think we +// actually use this enum but it's probably a good thing to include. +fs.writeFileSync( + path.join(BASE, "out/InternalModuleRegistry+enum.h"), + `${ + moduleList + .map((id, n) => { + return `${idToEnumName(id)} = ${n},`; + }) + .join("\n") + "\n" + } +`, +); + +// This code slice is used in InternalModuleRegistry.cpp. It defines the loading function for modules. +fs.writeFileSync( + path.join(BASE, "out/InternalModuleRegistry+createInternalModuleById.h"), + `JSValue InternalModuleRegistry::createInternalModuleById(JSGlobalObject* globalObject, VM& vm, Field id) +{ + switch (id) { + // JS internal modules + ${moduleList + .map((id, n) => { + return `case Field::${idToEnumName(id)}: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "${idToPublicSpecifierOrEnumName(id)}"_s, ${JSON.stringify( + id.replace(/\.[mc]?[tj]s$/, ".js"), + )}_s, InternalModuleRegistryConstants::${idToEnumName(id)}Code); + }`; + }) + .join("\n ")} + } +} +`, +); + +// This header is used by InternalModuleRegistry.cpp, and should only be included in that file. +// It inlines all the strings for the module IDs. +fs.writeFileSync( + path.join(BASE, "out/InternalModuleRegistryConstants.h"), + `#pragma once + + namespace Bun { + namespace InternalModuleRegistryConstants { + + #if __APPLE__ + ${moduleList + .map( + (id, n) => + `// +static constexpr ASCIILiteral ${idToEnumName(id)}Code = ${fmtCPPString(bundledOutputs.darwin.get(id.slice(0, -3)))}_s; +// +`, + ) + .join("\n")} + #elif _WIN32 + ${moduleList + .map( + (id, n) => + `// +static constexpr ASCIILiteral ${idToEnumName(id)}Code = ${fmtCPPString(bundledOutputs.win32.get(id.slice(0, -3)))}_s; +// +`, + ) + .join("\n")} + #else + // Not 100% accurate, but basically inlining linux on non-windows non-mac platforms. + ${moduleList + .map( + (id, n) => + `// +static constexpr ASCIILiteral ${idToEnumName(id)}Code = ${fmtCPPString(bundledOutputs.linux.get(id.slice(0, -3)))}_s; +// +`, + ) + .join("\n")} + #endif + + } + }`, +); + +// This is a generated enum for zig code (exports.zig) +fs.writeFileSync( + path.join(BASE, "out/ResolvedSourceTag.zig"), + `pub const ResolvedSourceTag = enum(u32) { + // Predefined + javascript = 0, + package_json_type_module = 1, + wasm = 2, + object = 3, + file = 4, + esm = 5, + + // Built in modules are loaded through InternalModuleRegistry by numerical ID. + // In this enum are represented as \`(1 << 9) & id\` +${moduleList.map((id, n) => ` @"${idToPublicSpecifierOrEnumName(id)}" = ${(1 << 9) | n},`).join("\n")} + // Native modules run through a different system using ESM registry. +${Object.entries(nativeModuleIds) + .map(([id, n]) => ` @"${id}" = ${(1 << 10) | n},`) + .join("\n")} +}; +`, +); + +// This is a generated enum for c++ code (headers-handwritten.h) +fs.writeFileSync( + path.join(BASE, "out/SyntheticModuleType.h"), + `enum SyntheticModuleType : uint32_t { + JavaScript = 0, + PackageJSONTypeModule = 1, + Wasm = 2, + ObjectModule = 3, + File = 4, + ESM = 5, + + // Built in modules are loaded through InternalModuleRegistry by numerical ID. + // In this enum are represented as \`(1 << 9) & id\` + InternalModuleRegistryFlag = 1 << 9, +${moduleList.map((id, n) => ` ${idToEnumName(id)} = ${(1 << 9) | n},`).join("\n")} + + // Native modules run through the same system, but with different underlying initializers. + // They also have bit 10 set to differentiate them from JS builtins. + NativeModuleFlag = (1 << 10) | (1 << 9), +${Object.entries(nativeModuleEnumToId) + .map(([id, n]) => ` ${id} = ${(1 << 10) | n},`) + .join("\n")} +}; + +`, +); + +// This is used in ModuleLoader.cpp to link to all the headers for native modules. +fs.writeFileSync( + path.join(BASE, "out/NativeModuleImpl.h"), + Object.values(nativeModuleEnums) + .map(value => `#include "../../bun.js/modules/${value}Module.h"`) + .join("\n") + "\n", +); + +// This is used for debug builds for the base path for dynamic loading +fs.writeFileSync( + path.join(BASE, "out/DebugPath.h"), + `// Using __FILE__ does not give an absolute file path +// This is a workaround for that. +#define BUN_DYNAMIC_JS_LOAD_PATH "${path.join(BASE, "out/")}" +`, +); + +mark("Generate Code"); diff --git a/src/js/_codegen/builtin-parser.ts b/src/js/_codegen/builtin-parser.ts new file mode 100644 index 00000000000000..ffd5671c104d70 --- /dev/null +++ b/src/js/_codegen/builtin-parser.ts @@ -0,0 +1,185 @@ +import { applyReplacements } from "./replacements"; + +/** + * Slices a string until it hits a }, but keeping in mind JS comments, + * regex, template literals, comments, and matching { + * + * Used to extract function bodies without parsing the code. + * + * If you pass replace=true, it will run replacements on the code + */ +export function sliceSourceCode( + contents: string, + replace: boolean, + replaceRequire?: (specifier: string) => string, + endOnComma = false, +): { result: string; rest: string } { + let bracketCount = 0; + let i = 0; + let result = ""; + while (contents.length) { + const match = contents.match( + endOnComma && bracketCount <= 1 + ? /((?:[(,=;:{]|return|\=\>)\s*)\/[^\/\*]|\/\*|\/\/|['"}`\),]|(?)\s*)\/[^\/\*]|\/\*|\/\/|['"}`\)]|(? ( + // The rationale for checking all these variables is just so you don't have to exactly remember which one you set. + (env.BUN_DEBUG_ALL && env.BUN_DEBUG_ALL !== '0') + || (env.BUN_DEBUG_JS && env.BUN_DEBUG_JS !== '0') + || (env.BUN_DEBUG_${filepath + .replace(/^.*?:/, "") + .split(/[-_./]/g) + .join("_") + .toUpperCase()}) + || (env.DEBUG_${filepath + .replace(/^.*?:/, "") + .split(/[-_./]/g) + .join("_") + .toUpperCase()}) +))(@Bun.env); +let $debug_log = $debug_log_enabled ? (...args) => { + // warn goes to stderr without colorizing + console.warn(Bun.enableANSIColors ? '\\x1b[90m[${publicName}]\\x1b[0m' : '[${publicName}]', ...args); +} : () => {}; +`; +} + +export function createAssertClientJS(publicName: string) { + return ` +let $assert = function(check, sourceString, ...message) { + if (!check) { + console.error('[${publicName}] ASSERTION FAILED: ' + sourceString); + if(message.length)console.warn (' ${" ".repeat(publicName.length)}', ...message); + const e = new Error(sourceString); + e.name = 'AssertionError'; + throw e; + } +} +`; +} diff --git a/src/js/builtins/codegen/helpers.ts b/src/js/_codegen/helpers.ts similarity index 52% rename from src/js/builtins/codegen/helpers.ts rename to src/js/_codegen/helpers.ts index 6345f8ffada10c..7f0c29ba0e248c 100644 --- a/src/js/builtins/codegen/helpers.ts +++ b/src/js/_codegen/helpers.ts @@ -1,3 +1,6 @@ +import fs from "fs"; +import path from "path"; + export function fmtCPPString(str: string) { return ( '"' + @@ -23,3 +26,19 @@ export function low(str: string) { return str[0].toLowerCase() + str.slice(1); } + +export function readdirRecursive(root: string): string[] { + const files = fs.readdirSync(root, { withFileTypes: true }); + return files.flatMap(file => { + const fullPath = path.join(root, file.name); + return file.isDirectory() ? readdirRecursive(fullPath) : fullPath; + }); +} + +export function resolveSyncOrNull(specifier: string, from: string) { + try { + return Bun.resolveSync(specifier, from); + } catch { + return null; + } +} diff --git a/src/js/_codegen/index.ts b/src/js/_codegen/index.ts new file mode 100644 index 00000000000000..4e048b144693e7 --- /dev/null +++ b/src/js/_codegen/index.ts @@ -0,0 +1,2 @@ +import "./build-modules"; +import "./build-functions"; diff --git a/src/js/builtins/codegen/replacements.ts b/src/js/_codegen/replacements.ts similarity index 67% rename from src/js/builtins/codegen/replacements.ts rename to src/js/_codegen/replacements.ts index 87157a587d3e1b..4621d6134fb67c 100644 --- a/src/js/builtins/codegen/replacements.ts +++ b/src/js/_codegen/replacements.ts @@ -1,4 +1,5 @@ -import { LoaderKeys } from "../../../api/schema"; +import { LoaderKeys } from "../../api/schema"; +import { sliceSourceCode } from "./builtin-parser"; // This is a list of extra syntax replacements to do. Kind of like macros // These are only run on code itself, not string contents or comments. @@ -7,6 +8,7 @@ export const replacements: ReplacementRule[] = [ { from: /\bthrow new RangeError\b/g, to: "$throwRangeError" }, { from: /\bthrow new OutOfMemoryError\b/g, to: "$throwOutOfMemoryError" }, { from: /\bnew TypeError\b/g, to: "$makeTypeError" }, + { from: /\bexport\s*default/g, to: "$exports =" }, ]; // These rules are run on the entire file, including within strings. @@ -41,6 +43,9 @@ export const globalsToPrefix = [ "TransformStream", "TransformStreamDefaultController", "Uint8Array", + "String", + "Buffer", + "RegExp", "WritableStream", "WritableStreamDefaultController", "WritableStreamDefaultWriter", @@ -81,12 +86,38 @@ export interface ReplacementRule { } /** Applies source code replacements as defined in `replacements` */ -export function applyReplacements(src: string) { - let result = src.replace(/\$([a-zA-Z0-9_]+)\b/gm, `__intrinsic__$1`); +export function applyReplacements(src: string, length: number) { + let slice = src.slice(0, length); + let rest = src.slice(length); + slice = slice.replace(/([^a-zA-Z0-9_\$])\$([a-zA-Z0-9_]+\b)/gm, `$1__intrinsic__$2`); for (const replacement of replacements) { - result = result.replace(replacement.from, replacement.to.replaceAll("$", "__intrinsic__")); + slice = slice.replace(replacement.from, replacement.to.replaceAll("$", "__intrinsic__")); } - return result; + let match; + if ((match = slice.match(/__intrinsic__(debug|assert)$/)) && rest.startsWith("(")) { + const name = match[1]; + if (name === "debug") { + const innerSlice = sliceSourceCode(rest, true); + return [ + slice.slice(0, match.index) + "(IS_BUN_DEVELOPMENT?$debug_log" + innerSlice.result + ":void 0)", + innerSlice.rest, + true, + ]; + } else if (name === "assert") { + const checkSlice = sliceSourceCode(rest, true, undefined, true); + return [ + slice.slice(0, match.index) + + "(IS_BUN_DEVELOPMENT?$assert(" + + checkSlice.result.slice(1, -1) + + "," + + JSON.stringify(checkSlice.result.slice(1, -1).replace(/__intrinsic__/g, "$")) + + "):void 0)", + checkSlice.rest, + true, + ]; + } + } + return [slice, rest, false]; } /** Applies source code replacements as defined in `globalReplacements` */ diff --git a/src/js/build-builtins.ts b/src/js/build-builtins.ts deleted file mode 100644 index 596b92270bee99..00000000000000 --- a/src/js/build-builtins.ts +++ /dev/null @@ -1 +0,0 @@ -import "./builtins/codegen"; diff --git a/src/js/build-esm.ts b/src/js/build-esm.ts deleted file mode 100644 index 762fc1e566aeb2..00000000000000 --- a/src/js/build-esm.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { BuildConfig } from "bun"; -import fs from "fs"; -import path from "path"; - -const OUT_DIR = path.join(import.meta.dir, "out/"); -const TMP_DIR = path.join(import.meta.dir, "out/tmp"); - -// Because we do not load sourcemaps, we are not enabling identifiers + whitespace -// minification on all files, just on the ones without logic or were already bundled -const minifyList = [ - "node/stream.js", - "node/crypto.js", - "node/assert.js", - "node/assert.strict.js", - "node/fs.promises.ts", - "node/path.js", - "node/path.posix.js", - "node/path.win32.js", - "node/stream.promises.js", - "node/stream.consumers.js", - "node/stream.web.js", - "node/url.js", - "node/zlib.js", -]; - -if (fs.existsSync(OUT_DIR + "/modules")) { - fs.rmSync(OUT_DIR + "/modules", { recursive: true }); -} -if (fs.existsSync(OUT_DIR + "/modules_dev")) { - fs.rmSync(OUT_DIR + "/modules_dev", { recursive: true }); -} - -function readdirRecursive(root: string): string[] { - const files = fs.readdirSync(root, { withFileTypes: true }); - return files.flatMap(file => { - const fullPath = path.join(root, file.name); - return file.isDirectory() ? readdirRecursive(fullPath) : fullPath; - }); -} - -const entrypoints = ["./bun", "./node", "./thirdparty"] - .flatMap(dir => readdirRecursive(path.join(import.meta.dir, dir))) - .filter(file => file.endsWith(".js") || (file.endsWith(".ts") && !file.endsWith(".d.ts"))); - -const opts = { - target: "bun", - naming: { - entry: "[dir]/[name].[ext]", - }, - root: import.meta.dir, - define: { - "process.platform": JSON.stringify(process.platform), - "process.arch": JSON.stringify(process.arch), - "$lazy": "$$BUN_LAZY$$", - }, -} 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, - ...productionOpts, -}); - -const build_prod_unminified = await Bun.build({ - entrypoints: entrypoints.filter(file => !minifyList.includes(file.slice(import.meta.dir.length + 1))), - minify: { syntax: true }, - ...productionOpts, -}); - -const build_dev = await Bun.build({ - entrypoints: entrypoints, - minify: { syntax: false }, - sourcemap: "external", - ...devOpts, -}); - -for (const [build, outdir] of [ - [build_dev, path.join(OUT_DIR, "modules_dev")], - [build_prod_minified, path.join(OUT_DIR, "modules")], - [build_prod_unminified, path.join(OUT_DIR, "modules")], -] as const) { - if (!build.success) { - console.error("Build failed"); - throw new AggregateError(build.logs); - } - - if (build.logs.length) { - console.log("Build has warnings:"); - for (const log of build.logs) { - console.log(log); - } - } - - for (const output of build.outputs) { - fs.mkdirSync(path.join(outdir, path.dirname(output.path)), { recursive: true }); - - if (output.kind === "entry-point" || output.kind === "chunk") { - const transformedOutput = (await output.text()) - .replace(/^(\/\/.*?\n)+/g, "") - .replace(/\$\$BUN_LAZY\$\$/g, 'globalThis[Symbol.for("Bun.lazy")]'); - - if (transformedOutput.includes("$bundleError")) { - // attempt to find the string that was passed to $bundleError - const match = transformedOutput.match(/(?<=\$bundleError\(")(?:[^"\\]|\\.)*?(?="\))/); - console.error(`Build ${output.path} $bundleError: ${match?.[0] ?? "unknown"}`); - console.error(`DCE should have removed this function call, but it was not.`); - process.exit(1); - } - - Bun.write(path.join(outdir, output.path), transformedOutput); - } else { - Bun.write(path.join(outdir, output.path), output); - } - } -} - -console.log(`Bundled esm modules in ${performance.now().toFixed(2)}ms`); diff --git a/src/js/builtins/builtins.d.ts b/src/js/builtins.d.ts similarity index 95% rename from src/js/builtins/builtins.d.ts rename to src/js/builtins.d.ts index 1b585ae7ab19ef..70d76e5a0219a0 100644 --- a/src/js/builtins/builtins.d.ts +++ b/src/js/builtins.d.ts @@ -1,6 +1,19 @@ // Typedefs for JSC intrinsics. Instead of @, we use $ type TODO = any; +/** $debug is a preprocessor macro that works like a templated console.log, and only runs in debug mode if you pass + * BUN_DEBUG_JS= + * + * So to get node stream to log, you pass BUN_DEBUG_JS=stream or BUN_DEBUG_JS=node:stream + * + * This only works in debug builds, the log fn is completely removed in release builds. + */ +declare function $debug(...args: any[]): void; +/** $assert is a preprocessor macro that only runs in debug mode. it throws an error if the first argument is falsy. + * The source code passed to `check` is inlined in the message, but in addition you can pass additional messages. + */ +declare function $assert(check: any, ...message: any[]): void; + /** Place this directly above a function declaration (like a decorator) to make it a getter. */ declare const $getter: never; /** Assign to this directly above a function declaration (like a decorator) to override the function's display name. */ @@ -25,8 +38,6 @@ declare function $extractHighWaterMarkFromQueuingStrategyInit(obj: any): any; // And implemented here: (search for "emit_intrinsic_", like "emit_intrinsic_arrayPush") // https://github.com/WebKit/WebKit/blob/main/Source/JavaScriptCore/bytecompiler/NodesCodegen.cpp -/** Assert a value is true */ -declare function $assert(index: any): void; /** returns `arguments[index]` */ declare function $argument(index: number): any; /** returns number of arguments */ @@ -199,6 +210,12 @@ declare const $AsyncGeneratorSuspendReasonYield: TODO; declare const $AsyncGeneratorSuspendReasonAwait: TODO; declare const $AsyncGeneratorSuspendReasonNone: TODO; declare const $abstractModuleRecordFieldState: TODO; +declare const $processBindingConstants: { + os: typeof import("os").constants; + fs: typeof import("fs").constants; + crypto: typeof import("crypto").constants; + zlib: typeof import("zlib").constants; +}; declare const $asyncContext: InternalFieldObject<[ReadonlyArray | undefined]>; // We define our intrinsics in ./BunBuiltinNames.h. Some of those are globals. @@ -231,7 +248,6 @@ declare function $closed(): TODO; declare function $closedPromise(): TODO; declare function $closedPromiseCapability(): TODO; declare function $code(): TODO; -declare const $commonJSSymbol: unique symbol; declare function $connect(): TODO; declare function $consumeReadableStream(): TODO; declare function $controlledReadableStream(): TODO; @@ -356,6 +372,7 @@ declare function $removeEventListener(): TODO; declare function $require(): TODO; declare function $requireESM(path: string): any; declare const $requireMap: Map; +declare const $internalModuleRegistry: InternalFieldObject; declare function $resolve(name: string, from: string): Promise; declare function $resolveSync(name: string, from: string, isESM?: boolean): string; declare function $resume(): TODO; diff --git a/src/js/builtins/AsyncContext.ts b/src/js/builtins/AsyncContext.ts deleted file mode 100644 index 1c55feeba8261c..00000000000000 --- a/src/js/builtins/AsyncContext.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Used by async_hooks to manipulate the async context - -export function getAsyncContext(): ReadonlyArray | undefined { - return $getInternalField($asyncContext, 0); -} - -export function setAsyncContext(contextValue: ReadonlyArray | undefined) { - return $putInternalField($asyncContext, 0, contextValue); -} diff --git a/src/js/builtins/BunBuiltinNames.h b/src/js/builtins/BunBuiltinNames.h index 1897f939e58817..1c34f272616173 100644 --- a/src/js/builtins/BunBuiltinNames.h +++ b/src/js/builtins/BunBuiltinNames.h @@ -1,6 +1,6 @@ +// clang-format off #pragma once - #ifdef ASSERT_ENABLED #if ASSERT_ENABLED #define ORIGINAL_ASSERT_ENABLED 1 @@ -9,7 +9,6 @@ #endif #endif - #include "JavaScriptCore/BuiltinUtils.h" #include "root.h" @@ -17,10 +16,6 @@ namespace WebCore { using namespace JSC; -#if !defined(BUN_ADDITIONAL_PRIVATE_IDENTIFIERS) -#define BUN_ADDITIONAL_PRIVATE_IDENTIFIERS(macro) -#endif - #define BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(macro) \ macro(AbortSignal) \ macro(Buffer) \ @@ -66,7 +61,6 @@ using namespace JSC; macro(closedPromise) \ macro(closedPromiseCapability) \ macro(code) \ - macro(commonJSSymbol) \ macro(connect) \ macro(consumeReadableStream) \ macro(controlledReadableStream) \ @@ -168,6 +162,7 @@ using namespace JSC; macro(ppid) \ macro(prependEventListener) \ macro(process) \ + macro(processBindingConstants) \ macro(protocol) \ macro(pull) \ macro(pullAgain) \ @@ -250,7 +245,9 @@ using namespace JSC; macro(writer) \ macro(writing) \ macro(written) \ - BUN_ADDITIONAL_PRIVATE_IDENTIFIERS(macro) \ + macro(createInternalModuleById) \ + macro(internalModuleRegistry) \ + macro(requireNativeModule) \ class BunBuiltinNames { public: diff --git a/src/js/builtins/BundlerPlugin.ts b/src/js/builtins/BundlerPlugin.ts index 831a6614e96b9d..7be030ee812ecf 100644 --- a/src/js/builtins/BundlerPlugin.ts +++ b/src/js/builtins/BundlerPlugin.ts @@ -3,7 +3,6 @@ import type { BuildConfig, BunPlugin, OnLoadCallback, - OnLoadResult, OnLoadResultObject, OnLoadResultSourceCode, OnResolveCallback, diff --git a/src/js/builtins/EventSource.ts b/src/js/builtins/EventSource.ts index a26c8d4ce275b3..5a65643237f4b7 100644 --- a/src/js/builtins/EventSource.ts +++ b/src/js/builtins/EventSource.ts @@ -494,7 +494,5 @@ export function getEventSource() { value: 2, }); - EventSource[Symbol.for("CommonJS")] = 0; - return EventSource; } diff --git a/src/js/builtins/ImportMetaObject.ts b/src/js/builtins/ImportMetaObject.ts index 46c00534a73e28..9409bb0f1c49a1 100644 --- a/src/js/builtins/ImportMetaObject.ts +++ b/src/js/builtins/ImportMetaObject.ts @@ -103,11 +103,6 @@ export function requireESM(this: ImportMetaObject, resolved) { throw new TypeError(`require() failed to evaluate module "${resolved}". This is an internal consistentency error.`); } var exports = Loader.getModuleNamespaceObject(entry.module); - if (exports[$commonJSSymbol] === 0) { - // CommonJS module created via `Bun::CommonJSModuleRecord` - // We will refer to the requireMap to get the exports - return; - } return exports; } @@ -141,10 +136,6 @@ export function internalRequire(this: ImportMetaObject, id) { if (cachedModule) { return cachedModule.exports; } - var defaultExport = exports?.default; - if (defaultExport?.[$commonJSSymbol] === 0) { - exports = defaultExport; - } $requireMap.$set(id, $createCommonJSModule(id, exports, true)); return exports; } @@ -161,9 +152,7 @@ export function createRequireCache() { const esm = Loader.registry.$get(key); if (esm?.evaluated) { const namespace = Loader.getModuleNamespaceObject(esm.module); - const exports = - namespace[$commonJSSymbol] === 0 || namespace.default?.[$commonJSSymbol] ? namespace.default : namespace; - const mod = $createCommonJSModule(key, exports, true); + const mod = $createCommonJSModule(key, namespace, true); $requireMap.$set(key, mod); return mod; } @@ -216,5 +205,5 @@ export function createRequireCache() { $getter; export function main(this: ImportMetaObject) { - return this.path === Bun.main; + return this.path === Bun.main && Bun.isMainThread; } diff --git a/src/js/builtins/Module.ts b/src/js/builtins/Module.ts index 0b5fcafe8d8066..d6ebc8578ad449 100644 --- a/src/js/builtins/Module.ts +++ b/src/js/builtins/Module.ts @@ -1,9 +1,13 @@ -interface Module { +interface CommonJSModuleRecord { + $require(id: string, mod: any): any; + children: CommonJSModuleRecord[]; + exports: any; id: string; + loaded: boolean; + parent: undefined; path: string; - - $require(id: string, mod: any): any; - children: Module[]; + paths: string[]; + require: typeof require; } $getter; @@ -11,7 +15,7 @@ export function main() { return $requireMap.$get(Bun.main); } -export function require(this: Module, id: string) { +export function require(this: CommonJSModuleRecord, id: string) { const existing = $requireMap.$get(id) || $requireMap.$get((id = $resolveSync(id, this.path, false))); if (existing) { // Scenario where this is necessary: @@ -39,20 +43,6 @@ export function require(this: Module, id: string) { return $internalRequire(id); } - let esm = Loader.registry.$get(id); - if (esm?.evaluated && (esm.state ?? 0) >= $ModuleReady) { - const mod = esm.module; - const namespace = Loader.getModuleNamespaceObject(mod); - const exports = - namespace?.[$commonJSSymbol] === 0 || namespace?.default?.[$commonJSSymbol] === 0 - ? namespace.default - : namespace.__esModule - ? namespace - : Object.create(namespace, { __esModule: { value: true } }); - $requireMap.$set(id, $createCommonJSModule(id, exports, true)); - return exports; - } - // To handle import/export cycles, we need to create a module object and put // it into the map before we import it. const mod = $createCommonJSModule(id, {}, false); @@ -76,18 +66,14 @@ export function require(this: Module, id: string) { throw exception; } - esm = Loader.registry.$get(id); + const esm = Loader.registry.$get(id); // If we can pull out a ModuleNamespaceObject, let's do it. if (esm?.evaluated && (esm.state ?? 0) >= $ModuleReady) { const namespace = Loader.getModuleNamespaceObject(esm!.module); return (mod.exports = // if they choose a module - namespace?.[$commonJSSymbol] === 0 || namespace?.default?.[$commonJSSymbol] === 0 - ? namespace.default - : namespace.__esModule - ? namespace - : Object.create(namespace, { __esModule: { value: true } })); + namespace.__esModule ? namespace : Object.create(namespace, { __esModule: { value: true } })); } } @@ -95,6 +81,16 @@ export function require(this: Module, id: string) { return mod.exports; } -export function requireResolve(this: Module, id: string) { - return $resolveSync(id, this.path, false); +export function requireResolve(this: string | { path: string }, id: string) { + return $resolveSync(id, typeof this === "string" ? this : this?.path, false); +} + +export function requireNativeModule(id: string) { + // There might be a race condition here? + let esm = Loader.registry.$get(id); + if (esm?.evaluated && (esm.state ?? 0) >= $ModuleReady) { + const exports = Loader.getModuleNamespaceObject(esm.module); + return exports.default; + } + return $requireESM(id).default; } diff --git a/src/js/builtins/ProcessObjectInternals.ts b/src/js/builtins/ProcessObjectInternals.ts index f6990dc5e51548..fc6b3800f77934 100644 --- a/src/js/builtins/ProcessObjectInternals.ts +++ b/src/js/builtins/ProcessObjectInternals.ts @@ -23,38 +23,29 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +// TODO: move this to native code? export function binding(bindingName) { - if (bindingName !== "constants") - throw new TypeError( - "process.binding() is not supported in Bun. If that breaks something, please file an issue and include a reproducible code sample.", + if (bindingName === "constants") { + return $processBindingConstants; + } + const issue = { + fs: 3546, + buffer: 2020, + natives: 2254, + uv: 2891, + }[bindingName]; + if (issue) { + throw new Error( + `process.binding("${bindingName}") is not implemented in Bun. Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/${issue}`, ); - - var cache = globalThis.Symbol.for("process.bindings.constants"); - var constants = globalThis[cache]; - if (!constants) { - // TODO: make this less hacky. - // This calls require("node:fs").constants - // except, outside an ESM module. - const { constants: fs } = $lazy("createImportMeta", "node:process").require("node:fs"); - constants = { - fs, - zlib: {}, - crypto: {}, - os: Bun._Os().constants, - }; - globalThis[cache] = constants; } - return constants; + throw new TypeError( + `process.binding("${bindingName}") is not implemented in Bun. If that breaks something, please file an issue and include a reproducible code sample.`, + ); } export function getStdioWriteStream(fd_, getWindowSize) { - var require = path => { - var existing = $requireMap.get(path); - if (existing) return existing.exports; - - return $internalRequire(path); - }; - var module = { path: "node:process", require }; + var EventEmitter = require("node:events"); function createStdioWriteStream(fd_) { var { Duplex, eos, destroy } = require("node:stream"); @@ -213,8 +204,6 @@ export function getStdioWriteStream(fd_, getWindowSize) { return new StdioWriteStream(fd_); } - var { EventEmitter } = require("node:events"); - function isFastEncoding(encoding) { if (!encoding) return true; @@ -499,14 +488,6 @@ export function getStdioWriteStream(fd_, getWindowSize) { } 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/README.md b/src/js/builtins/README.md deleted file mode 100644 index 67b8882ee21e2e..00000000000000 --- a/src/js/builtins/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# JavaScript Builtins - -**TLDR** — When files in this directory change, run: - -```bash -# Delete the built files -$ make regenerate-bindings -# Re-link the binary without compiling zig (so it's faster) -$ make bun-link-lld-debug -``` - -TypeScript files in [./ts](./ts) are bundled into C++ Headers that can access JavaScriptCore intrinsics. These files use special globals that are prefixed with `$`. - -```js -$getter -export function foo() { - return $getByIdDirectPrivate(this, "superSecret"); -} -``` - -It looks kind of like decorators but they're not. They let you directly call engine intrinsics and help with avoiding prototype pollution issues. - -V8 has a [similar feature](https://v8.dev/blog/embedded-builtins) (they use `%` instead of `@`) - -They usually are accompanied by a C++ file. - -We use a custom code generator located in `./codegen` which contains a regex-based parser that separates each function into it's own bundling context, so syntax like top level variables / functions will not work. - -You can also use `process.platform` and `process.arch` in these files. The values are inlined and DCE'd. - -## Generating builtins - -To regenerate the builtins, run this from Bun's project root (where the `Makefile` is) - -```bash -$ make builtins -``` - -You'll want to also rebuild all the C++ bindings or you will get strange crashes on start - -```bash -$ make clean-bindings -``` - -The `make regenerate-bindings` command will clean and rebuild the bindings. - -Also, you can run the code generator manually. - -```bash -$ bun ./codegen/index.ts -# pass --minify to minify (make passes this by default) -# pass --keep-tmp to keep the temporary ./tmp folder, which contains processed pre-bundled .ts files -``` diff --git a/src/js/builtins/ReadableStreamDefaultReader.ts b/src/js/builtins/ReadableStreamDefaultReader.ts index b4e0c2bd327a0f..ea1a64b687da20 100644 --- a/src/js/builtins/ReadableStreamDefaultReader.ts +++ b/src/js/builtins/ReadableStreamDefaultReader.ts @@ -59,7 +59,6 @@ export function readMany(this: ReadableStreamDefaultReader): ReadableStreamDefau var controller = $getByIdDirectPrivate(stream, "readableStreamController"); var queue = $getByIdDirectPrivate(controller, "queue"); - if (!queue) { // This is a ReadableStream direct controller implemented in JS // It hasn't been started yet. diff --git a/src/js/builtins/TransformStreamInternals.ts b/src/js/builtins/TransformStreamInternals.ts index 103b0651f404a2..833fafdc6b3eb1 100644 --- a/src/js/builtins/TransformStreamInternals.ts +++ b/src/js/builtins/TransformStreamInternals.ts @@ -241,7 +241,7 @@ export function transformStreamDefaultControllerPerformTransform(controller, chu const transformPromise = $getByIdDirectPrivate(controller, "transformAlgorithm").$call(undefined, chunk); transformPromise.$then( () => { - promiseCapability.$resolve(); + promiseCapability.resolve(); }, r => { $transformStreamError($getByIdDirectPrivate(controller, "stream"), r); @@ -286,7 +286,7 @@ export function transformStreamDefaultSinkWriteAlgorithm(stream, chunk) { $assert(state === "writable"); $transformStreamDefaultControllerPerformTransform(controller, chunk).$then( () => { - promiseCapability.$resolve(); + promiseCapability.resolve(); }, e => { promiseCapability.reject.$call(undefined, e); @@ -329,7 +329,7 @@ export function transformStreamDefaultSinkCloseAlgorithm(stream) { // FIXME: Update readableStreamDefaultControllerClose to make this check. if ($readableStreamDefaultControllerCanCloseOrEnqueue(readableController)) $readableStreamDefaultControllerClose(readableController); - promiseCapability.$resolve(); + promiseCapability.resolve(); }, r => { $transformStreamError($getByIdDirectPrivate(controller, "stream"), r); diff --git a/src/js/builtins/codegen/builtin-parser.ts b/src/js/builtins/codegen/builtin-parser.ts deleted file mode 100644 index e96d79c63e19e7..00000000000000 --- a/src/js/builtins/codegen/builtin-parser.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { applyReplacements } from "./replacements"; - -/** - * Slices a string until it hits a }, but keeping in mind JS comments, - * regex, template literals, comments, and matching { - * - * Used to extract function bodies without parsing the code. - * - * If you pass replace=true, it will run replacements on the code - */ -export function sliceSourceCode( - contents: string, - replace: boolean, -): { result: string; rest: string; usesThis: boolean } { - let bracketCount = 0; - let i = 0; - let result = ""; - let usesThis = false; - while (contents.length) { - // TODO: template literal, regexp - // these are important because our replacement logic would replace intrinsics - // within these, when it should remain as the literal dollar. - // but this isn't used in the codebase - i = contents.match(/\/\*|\/\/|'|"|{|}|`/)?.index ?? contents.length; - const chunk = replace ? applyReplacements(contents.slice(0, i)) : contents.slice(0, i); - if (chunk.includes("this")) usesThis = true; - result += chunk; - contents = contents.slice(i); - if (!contents.length) break; - if (contents.startsWith("/*")) { - i = contents.slice(2).indexOf("*/") + 2; - } else if (contents.startsWith("//")) { - i = contents.slice(2).indexOf("\n") + 2; - } else if (contents.startsWith("'")) { - i = contents.slice(1).match(/(? (typeof arg2 === "undefined" ? ffi.ptr(arg1) : ffi.ptr(arg1, arg2)); -export const toBuffer = ffi.toBuffer; -export const toArrayBuffer = ffi.toArrayBuffer; -export const viewSource = ffi.viewSource; +const ptr = (arg1, arg2) => (typeof arg2 === "undefined" ? ffi.ptr(arg1) : ffi.ptr(arg1, arg2)); +const toBuffer = ffi.toBuffer; +const toArrayBuffer = ffi.toArrayBuffer; +const viewSource = ffi.viewSource; const BunCString = ffi.CString; const nativeLinkSymbols = ffi.linkSymbols; @@ -16,7 +76,7 @@ const closeCallback = ffi.closeCallback; delete ffi.callback; delete ffi.closeCallback; -export class JSCallback { +class JSCallback { constructor(cb, options) { const { ctx, ptr } = nativeCallback(options, cb); this.#ctx = ctx; @@ -48,8 +108,8 @@ export class JSCallback { } } -export class CString extends String { - constructor(ptr, byteOffset, byteLength) { +class CString extends String { + constructor(ptr, byteOffset?, byteLength?) { super( ptr ? typeof byteLength === "number" && Number.isSafeInteger(byteLength) @@ -91,25 +151,15 @@ Object.defineProperty(globalThis, "__GlobalBunCString", { const ffiWrappers = new Array(18); -var char = val => val | 0; +var char = "val|0"; ffiWrappers.fill(char); -ffiWrappers[FFIType.uint8_t] = function uint8(val) { - return val < 0 ? 0 : val >= 255 ? 255 : val | 0; -}; -ffiWrappers[FFIType.int16_t] = function int16(val) { - return val <= -32768 ? -32768 : val >= 32768 ? 32768 : val | 0; -}; -ffiWrappers[FFIType.uint16_t] = function uint16(val) { - return val <= 0 ? 0 : val >= 65536 ? 65536 : val | 0; -}; -ffiWrappers[FFIType.int32_t] = function int32(val) { - return val | 0; -}; +ffiWrappers[FFIType.uint8_t] = "val<0?0:val>=255?255:val|0"; +ffiWrappers[FFIType.int16_t] = "val<=-32768?-32768:val>=32768?32768:val|0"; +ffiWrappers[FFIType.uint16_t] = "val<=0?0:val>=65536?65536:val|0"; +ffiWrappers[FFIType.int32_t] = "val|0"; // we never want to return NaN -ffiWrappers[FFIType.uint32_t] = function uint32(val) { - return val <= 0 ? 0 : val >= 0xffffffff ? 0xffffffff : +val || 0; -}; -ffiWrappers[FFIType.i64_fast] = function int64(val) { +ffiWrappers[FFIType.uint32_t] = "val<=0?0:val>=0xffffffff?0xffffffff:+val||0"; +ffiWrappers[FFIType.i64_fast] = `{ if (typeof val === "bigint") { if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) { return Number(val).valueOf() || 0; @@ -119,9 +169,20 @@ ffiWrappers[FFIType.i64_fast] = function int64(val) { } return !val ? 0 : +val || 0; -}; +}`; +ffiWrappers[FFIType.i64_fast] = `{ + if (typeof val === "bigint") { + if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) { + return Number(val).valueOf() || 0; + } + + return val; + } -ffiWrappers[FFIType.u64_fast] = function u64_fast(val) { + return !val ? 0 : +val || 0; +}`; + +ffiWrappers[FFIType.u64_fast] = `{ if (typeof val === "bigint") { if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= 0) { return Number(val).valueOf() || 0; @@ -131,9 +192,9 @@ ffiWrappers[FFIType.u64_fast] = function u64_fast(val) { } return !val ? 0 : +val || 0; -}; +}`; -ffiWrappers[FFIType.int64_t] = function int64(val) { +ffiWrappers[FFIType.int64_t] = `{ if (typeof val === "bigint") { return val; } @@ -143,9 +204,9 @@ ffiWrappers[FFIType.int64_t] = function int64(val) { } return BigInt(+val || 0); -}; +}`; -ffiWrappers[FFIType.uint64_t] = function uint64(val) { +ffiWrappers[FFIType.uint64_t] = `{ if (typeof val === "bigint") { return val; } @@ -155,23 +216,23 @@ ffiWrappers[FFIType.uint64_t] = function uint64(val) { } return BigInt(+val || 0); -}; +}`; -ffiWrappers[FFIType.u64_fast] = function u64_fast(val) { +ffiWrappers[FFIType.u64_fast] = `{ if (typeof val === "bigint") { if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(0)) return Number(val); return val; } return typeof val === "number" ? (val <= 0 ? 0 : +val || 0) : +val || 0; -}; +}`; -ffiWrappers[FFIType.uint16_t] = function uint16(val) { +ffiWrappers[FFIType.uint16_t] = `{ const ret = (typeof val === "bigint" ? Number(val) : val) | 0; return ret <= 0 ? 0 : ret > 0xffff ? 0xffff : ret; -}; +}`; -ffiWrappers[FFIType.double] = function double(val) { +ffiWrappers[FFIType.double] = `{ if (typeof val === "bigint") { if (val.valueOf() < BigInt(Number.MAX_VALUE)) { return Math.abs(Number(val).valueOf()) + 0.00000000000001 - 0.00000000000001; @@ -183,14 +244,14 @@ ffiWrappers[FFIType.double] = function double(val) { } return val + 0.00000000000001 - 0.00000000000001; -}; +}`; -ffiWrappers[FFIType.float] = ffiWrappers[10] = function float(val) { +ffiWrappers[FFIType.float] = ffiWrappers[10] = `{ return Math.fround(val); -}; -ffiWrappers[FFIType.bool] = function bool(val) { +}`; +ffiWrappers[FFIType.bool] = `{ return !!val; -}; +}`; // This prevents an extra property getter in potentially hot code Object.defineProperty(globalThis, "__GlobalBunFFIPtrFunctionForWrapper", { @@ -199,7 +260,7 @@ Object.defineProperty(globalThis, "__GlobalBunFFIPtrFunctionForWrapper", { configurable: true, }); -ffiWrappers[FFIType.cstring] = ffiWrappers[FFIType.pointer] = function pointer(val) { +ffiWrappers[FFIType.cstring] = ffiWrappers[FFIType.pointer] = `{ if (typeof val === "number") return val; if (!val) { return null; @@ -213,14 +274,10 @@ ffiWrappers[FFIType.cstring] = ffiWrappers[FFIType.pointer] = function pointer(v throw new TypeError("To convert a string to a pointer, encode it as a buffer"); } - throw new TypeError(`Unable to convert ${val} to a pointer`); -}; + throw new TypeError(\`Unable to convert \${ val } to a pointer\`); +}`; -function cstringReturnType(val) { - return new __GlobalBunCString(val); -} - -ffiWrappers[FFIType.function] = function functionType(val) { +ffiWrappers[FFIType.function] = `{ if (typeof val === "number") { return val; } @@ -236,7 +293,7 @@ ffiWrappers[FFIType.function] = function functionType(val) { } return ptr; -}; +}`; function FFIBuilder(params, returnType, functionToCall, name) { const hasReturnType = typeof FFIType[returnType] === "number" && FFIType[returnType as string] !== FFIType.void; @@ -247,7 +304,7 @@ function FFIBuilder(params, returnType, functionToCall, name) { const wrapper = ffiWrappers[FFIType[params[i]]]; if (wrapper) { // doing this inline benchmarked about 4x faster than referencing - args[i] = `(${wrapper.toString()})(p${i})`; + args[i] = `(val=>${wrapper})(p${i})`; } else { throw new TypeError(`Unsupported type ${params[i]}. Must be one of: ${Object.keys(FFIType).sort().join(", ")}`); } @@ -256,7 +313,7 @@ function FFIBuilder(params, returnType, functionToCall, name) { var code = `functionToCall(${args.join(", ")})`; if (hasReturnType) { if (FFIType[returnType as string] === FFIType.cstring) { - code = `return (${cstringReturnType.toString()})(${code})`; + code = `return new __GlobalBunCString(${code})`; } else { code = `return ${code}`; } @@ -316,14 +373,14 @@ function FFIBuilder(params, returnType, functionToCall, name) { return wrap; } -export const native = { +const native = { dlopen: nativeDLOpen, callback: () => { throw new Error("Deprecated. Use new JSCallback(options, fn) instead"); }, }; -export function dlopen(path, options) { +function dlopen(path, options) { const result = nativeDLOpen(path, options); for (let key in result.symbols) { @@ -349,7 +406,7 @@ export function dlopen(path, options) { return result; } -export function linkSymbols(options) { +function linkSymbols(options) { const result = nativeLinkSymbols(options); for (let key in result.symbols) { @@ -370,7 +427,7 @@ var cFunctionRegistry; function onCloseCFunction(close) { close(); } -export function CFunction(options) { +function CFunction(options) { const identifier = `CFunction${cFunctionI++}`; var result = linkSymbols({ [identifier]: options, @@ -390,4 +447,20 @@ export function CFunction(options) { return result.symbols[identifier]; } -export const read = ffi.read; +const read = ffi.read; + +export default { + CFunction, + CString, + FFIType, + JSCallback, + dlopen, + linkSymbols, + native, + ptr, + read, + suffix, + toArrayBuffer, + toBuffer, + viewSource, +}; diff --git a/src/js/bun/jsc.ts b/src/js/bun/jsc.ts deleted file mode 100644 index 8063da9484611f..00000000000000 --- a/src/js/bun/jsc.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Hardcoded module "bun:jsc" -const jsc = $lazy("bun:jsc"); - -export const callerSourceOrigin = jsc.callerSourceOrigin; -export const jscDescribe = jsc.describe; -export const jscDescribeArray = jsc.describeArray; -/** Too easy to confuse with test describe */ -export const describe = jscDescribe; -export const describeArray = jscDescribeArray; -export const drainMicrotasks = jsc.drainMicrotasks; -export const edenGC = jsc.edenGC; -export const fullGC = jsc.fullGC; -export const gcAndSweep = jsc.gcAndSweep; -export const getRandomSeed = jsc.getRandomSeed; -export const heapSize = jsc.heapSize; -export const heapStats = jsc.heapStats; -export const startSamplingProfiler = jsc.startSamplingProfiler; -export const samplingProfilerStackTraces = jsc.samplingProfilerStackTraces; -export const isRope = jsc.isRope; -export const memoryUsage = jsc.memoryUsage; -export const noInline = jsc.noInline; -export const noFTL = jsc.noFTL; -export const noOSRExitFuzzing = jsc.noOSRExitFuzzing; -export const numberOfDFGCompiles = jsc.numberOfDFGCompiles; -export const optimizeNextInvocation = jsc.optimizeNextInvocation; -export const releaseWeakRefs = jsc.releaseWeakRefs; -export const reoptimizationRetryCount = jsc.reoptimizationRetryCount; -export const setRandomSeed = jsc.setRandomSeed; -export const startRemoteDebugger = jsc.startRemoteDebugger; -export const totalCompileTime = jsc.totalCompileTime; -export const getProtectedObjects = jsc.getProtectedObjects; -export const generateHeapSnapshotForDebugging = jsc.generateHeapSnapshotForDebugging; -export const profile = jsc.profile; -export default jsc; -export const setTimeZone = jsc.setTimeZone; -export const setTimezone = setTimeZone; -export const serialize = jsc.serialize; -export const deserialize = jsc.deserialize; diff --git a/src/js/bun/sqlite.js b/src/js/bun/sqlite.ts similarity index 97% rename from src/js/bun/sqlite.js rename to src/js/bun/sqlite.ts index 7d1416a9082d99..a3d862fd0d04d7 100644 --- a/src/js/bun/sqlite.js +++ b/src/js/bun/sqlite.ts @@ -1,13 +1,11 @@ // Hardcoded module "sqlite" -const lazy = $lazy; - var defineProperties = Object.defineProperties; var toStringTag = Symbol.toStringTag; -var apply = Function.prototype.apply; var isArray = Array.isArray; var isTypedArray = ArrayBuffer.isView; -export const constants = { + +const constants = { SQLITE_OPEN_READONLY: 0x00000001 /* Ok for sqlite3_open_v2() */, SQLITE_OPEN_READWRITE: 0x00000002 /* Ok for sqlite3_open_v2() */, SQLITE_OPEN_CREATE: 0x00000004 /* Ok for sqlite3_open_v2() */, @@ -36,11 +34,10 @@ export const constants = { }; var SQL; -var _SQL; var controllers; -export class Statement { +class Statement { constructor(raw) { this.#raw = raw; @@ -167,7 +164,7 @@ export class Statement { } var cachedCount = Symbol.for("Bun.Database.cache.count"); -export class Database { +class Database { constructor(filenameGiven, options) { if (typeof filenameGiven === "undefined") { } else if (typeof filenameGiven !== "string") { @@ -213,7 +210,7 @@ export class Database { } if (!SQL) { - _SQL = SQL = lazy("sqlite"); + SQL = $lazy("sqlite"); } this.#handle = SQL.open(anonymous ? ":memory:" : filename, flags); @@ -248,7 +245,7 @@ export class Database { static deserialize(serialized, isReadOnly = false) { if (!SQL) { - _SQL = SQL = lazy("sqlite"); + SQL = $lazy("sqlite"); } return SQL.deserialize(serialized, isReadOnly); @@ -256,7 +253,7 @@ export class Database { static setCustomSQLite(path) { if (!SQL) { - _SQL = SQL = lazy("sqlite"); + SQL = $lazy("sqlite"); } return SQL.setCustomSQLite(path); @@ -370,6 +367,7 @@ export class Database { } } +// @ts-expect-error Database.prototype.exec = Database.prototype.run; // Return the database's cached transaction controller, or create a new one @@ -399,7 +397,7 @@ const getController = (db, self) => { // Return a new transaction function by wrapping the given function const wrapTransaction = (fn, db, { begin, commit, rollback, savepoint, release, rollbackTo }) => - function transaction(...args) { + function transaction(this, ...args) { let before, after, undo; if (db.inTransaction) { before = savepoint; @@ -424,5 +422,10 @@ const wrapTransaction = (fn, db, { begin, commit, rollback, savepoint, release, } }; -export { _SQL as native }; -export { Database as default }; +export default { + __esModule: true, + Database, + Statement, + constants, + default: Database, +}; diff --git a/src/js/shared.ts b/src/js/internal/shared.ts similarity index 75% rename from src/js/shared.ts rename to src/js/internal/shared.ts index 1e3da7d51d10c6..98a5b0a713b81a 100644 --- a/src/js/shared.ts +++ b/src/js/internal/shared.ts @@ -1,4 +1,4 @@ -export class NotImplementedError extends Error { +class NotImplementedError extends Error { code: string; constructor(feature: string, issue?: number) { super( @@ -14,17 +14,23 @@ export class NotImplementedError extends Error { } } -export function throwNotImplemented(feature: string, issue?: number): never { +function throwNotImplemented(feature: string, issue?: number): never { // in the definition so that it isn't bundled unless used hideFromStack(throwNotImplemented); throw new NotImplementedError(feature, issue); } -export function hideFromStack(...fns) { +function hideFromStack(...fns) { for (const fn of fns) { Object.defineProperty(fn, "name", { value: "::bunternal::", }); } } + +export default { + NotImplementedError, + throwNotImplemented, + hideFromStack, +}; diff --git a/src/js/node/assert.js b/src/js/node/assert.js index a00a845095f4bb..475f720060059e 100644 --- a/src/js/node/assert.js +++ b/src/js/node/assert.js @@ -1,6 +1,5 @@ // Hardcoded module "node:assert" -var { Bun } = $lazy("primordials"); -import util from "node:util"; +const util = require("node:util"); var isDeepEqual = Bun.deepEquals; var __commonJS = (cb, mod) => @@ -653,7 +652,6 @@ var require_assertion_error = __commonJS({ .concat(indicator); } var AssertionError = /* @__PURE__ */ (function (_Error) { - _inherits(AssertionError2, _Error); function AssertionError2(options) { var _this; if ((_classCallCheck(this, AssertionError2), _typeof(options) !== "object" || options === null)) @@ -781,6 +779,8 @@ should equal _possibleConstructorReturn(_this) ); } + AssertionError2.prototype = {}; + _inherits(AssertionError2, _Error); return ( _createClass(AssertionError2, [ { @@ -830,6 +830,7 @@ var require_assert = __commonJS({ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } + var _require = require_errors(), _require$codes = _require.codes, ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, @@ -1256,26 +1257,6 @@ function CallTracker() { throw new Error("CallTracker is not supported yet"); } -assert_module[Symbol.for("CommonJS")] = 0; assert_module["CallTracker"] = CallTracker; -export var { - AssertionError, - assert, - deepEqual, - deepStrictEqual, - doesNotReject, - doesNotThrow, - equal, - fail, - ifError, - notDeepEqual, - notDeepStrictEqual, - notEqual, - notStrictEqual, - ok, - rejects, - strict, - strictEqual, - throws, -} = assert_module; + export default assert_module; diff --git a/src/js/node/assert.strict.ts b/src/js/node/assert.strict.ts index f512c3c91bea99..f12edbff18644a 100644 --- a/src/js/node/assert.strict.ts +++ b/src/js/node/assert.strict.ts @@ -1,49 +1,2 @@ // Hardcoded module "node:assert/strict" -import { strict as strictBase } from "node:assert"; - -export var { - fail, - AssertionError, - ok, - equal, - notEqual, - deepEqual, - notDeepEqual, - deepStrictEqual, - notDeepStrictEqual, - strictEqual, - notStrictEqual, - throws, - rejects, - doesNotThrow, - doesNotReject, - ifError, - match, - doesNotMatch, - CallTracker, -} = strictBase; - -const defaultObject = { - fail, - AssertionError, - ok, - equal, - notEqual, - deepEqual, - notDeepEqual, - deepStrictEqual, - notDeepStrictEqual, - strictEqual, - notStrictEqual, - throws, - rejects, - doesNotThrow, - doesNotReject, - ifError, - match, - doesNotMatch, - CallTracker, - [Symbol.for("CommonJS")]: 0, -}; - -export { defaultObject as default, strictBase as strict }; +export default require("node:assert").strict; diff --git a/src/js/node/async_hooks.ts b/src/js/node/async_hooks.ts index da9f6c136e33ea..2a671b6a284337 100644 --- a/src/js/node/async_hooks.ts +++ b/src/js/node/async_hooks.ts @@ -21,7 +21,15 @@ // AsyncContextData is an immutable array managed in here, formatted [key, value, key, value] where // each key is an AsyncLocalStorage object and the value is the associated value. // -const { get, set, cleanupLater } = $lazy("async_hooks"); +const { cleanupLater } = $lazy("async_hooks"); + +function get(): ReadonlyArray | undefined { + return $getInternalField($asyncContext, 0); +} + +function set(contextValue: ReadonlyArray | undefined) { + return $putInternalField($asyncContext, 0, contextValue); +} class AsyncLocalStorage { #disableCalled = false; @@ -298,16 +306,6 @@ const asyncWrapProviders = { INSPECTORJSBINDING: 57, }; -export { - AsyncLocalStorage, - createHook, - executionAsyncId, - triggerAsyncId, - executionAsyncResource, - asyncWrapProviders, - AsyncResource, -}; - export default { AsyncLocalStorage, createHook, @@ -316,5 +314,4 @@ export default { executionAsyncResource, asyncWrapProviders, AsyncResource, - [Symbol.for("CommonJS")]: 0, }; diff --git a/src/js/node/child_process.js b/src/js/node/child_process.js index c6b10bbec21264..ef96dbce5c225b 100644 --- a/src/js/node/child_process.js +++ b/src/js/node/child_process.js @@ -1,13 +1,11 @@ // Hardcoded module "node:child_process" -import { EventEmitter } from "node:events"; -import * as StreamModule from "node:stream"; -import { constants } from "node:os"; -import { promisify } from "node:util"; -const signals = constants.signals; +const EventEmitter = require("node:events"); +const StreamModule = require("node:stream"); +const { + constants: { signals }, +} = require("node:os"); +const { promisify } = require("node:util"); -const { ArrayBuffer, Uint8Array, String, Object, Buffer, Promise } = $lazy("primordials"); - -var ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty; var ObjectCreate = Object.create; var ObjectAssign = Object.assign; var ObjectDefineProperty = Object.defineProperty; @@ -22,6 +20,8 @@ var ArrayPrototypeMap = Array.prototype.map; var ArrayPrototypeIncludes = Array.prototype.includes; var ArrayPrototypeSlice = Array.prototype.slice; var ArrayPrototypeUnshift = Array.prototype.unshift; +var ArrayPrototypeLastIndexOf = Array.prototype.lastIndexOf; +var ArrayPrototypeSplice = Array.prototype.splice; var ArrayIsArray = Array.isArray; // var ArrayBuffer = ArrayBuffer; @@ -37,17 +37,9 @@ var Uint8ArrayPrototypeIncludes = Uint8Array.prototype.includes; const MAX_BUFFER = 1024 * 1024; -// General debug vs tracking stdio streams. Useful for stream debugging in particular -const __DEBUG__ = process.env.DEBUG || false; - -// You can use this env var along with `process.env.DEBUG_TRACK_EE` to debug stdio streams -// Just set `DEBUG_TRACK_EE=PARENT_STDOUT-0, PARENT_STDOUT-1`, etc. and `DEBUG_STDIO=1` and you will be able to track particular stdio streams -// TODO: Add ability to track a range of IDs rather than just enumerated ones -const __TRACK_STDIO__ = process.env.DEBUG_STDIO; -const debug = __DEBUG__ ? console.log : () => {}; - -if (__TRACK_STDIO__) { - debug("child_process: debug mode on"); +// Pass DEBUG_CHILD_PROCESS=1 to enable debug output +if ($debug) { + $debug("child_process: debug mode on"); globalThis.__lastId = null; globalThis.__getId = () => { return globalThis.__lastId !== null ? globalThis.__lastId++ : 0; @@ -154,14 +146,14 @@ function spawnTimeoutFunction(child, timeoutHolder) { * }} [options] * @returns {ChildProcess} */ -export function spawn(file, args, options) { +function spawn(file, args, options) { options = normalizeSpawnArguments(file, args, options); validateTimeout(options.timeout); validateAbortSignal(options.signal, "options.signal"); const killSignal = sanitizeKillSignal(options.killSignal); const child = new ChildProcess(); - debug("spawn", options); + $debug("spawn", options); child.spawn(options); if (options.timeout > 0) { @@ -194,7 +186,7 @@ export function spawn(file, args, options) { } function onAbortListener() { - abortChildProcess(child, killSignal); + abortChildProcess(child, killSignal, options.signal.reason); } } return child; @@ -225,7 +217,7 @@ export function spawn(file, args, options) { * ) => any} [callback] * @returns {ChildProcess} */ -export function execFile(file, args, options, callback) { +function execFile(file, args, options, callback) { ({ file, args, options, callback } = normalizeExecFileArgs(file, args, options, callback)); options = { @@ -479,7 +471,7 @@ export function execFile(file, args, options, callback) { * ) => any} [callback] * @returns {ChildProcess} */ -export function exec(command, options, callback) { +function exec(command, options, callback) { const opts = normalizeExecArgs(command, options, callback); return execFile(opts.file, opts.options, opts.callback); } @@ -541,7 +533,7 @@ ObjectDefineProperty(exec, promisify.custom, { * error: Error; * }} */ -export function spawnSync(file, args, options) { +function spawnSync(file, args, options) { options = { maxBuffer: MAX_BUFFER, ...normalizeSpawnArguments(file, args, options), @@ -550,7 +542,7 @@ export function spawnSync(file, args, options) { const maxBuffer = options.maxBuffer; const encoding = options.encoding; - debug("spawnSync", options); + $debug("spawnSync", options); // Validate the timeout, if present. validateTimeout(options.timeout); @@ -629,7 +621,7 @@ export function spawnSync(file, args, options) { * }} [options] * @returns {Buffer | string} */ -export function execFileSync(file, args, options) { +function execFileSync(file, args, options) { ({ file, args, options } = normalizeExecFileArgs(file, args, options)); // const inheritStderr = !options.stdio; @@ -665,7 +657,7 @@ export function execFileSync(file, args, options) { * }} [options] * @returns {Buffer | string} */ -export function execSync(command, options) { +function execSync(command, options) { const opts = normalizeExecArgs(command, options, null); // const inheritStderr = !opts.options.stdio; @@ -680,8 +672,97 @@ export function execSync(command, options) { return ret.stdout; } -export function fork() { - throw new Error("Not implemented"); +function stdioStringToArray(stdio, channel) { + const options = []; + + switch (stdio) { + case "ignore": + case "overlapped": + case "pipe": + ArrayPrototypePush.call(options, stdio, stdio, stdio); + break; + case "inherit": + ArrayPrototypePush.call(options, 0, 1, 2); + break; + default: + throw new ERR_INVALID_ARG_VALUE("stdio", stdio); + } + + if (channel) ArrayPrototypePush.call(options, channel); + + return options; +} + +/** + * Spawns a new Node.js process + fork. + * @param {string|URL} modulePath + * @param {string[]} [args] + * @param {{ + * cwd?: string; + * detached?: boolean; + * env?: Record; + * execPath?: string; + * execArgv?: string[]; + * gid?: number; + * serialization?: string; + * signal?: AbortSignal; + * killSignal?: string | number; + * silent?: boolean; + * stdio?: Array | string; + * uid?: number; + * windowsVerbatimArguments?: boolean; + * timeout?: number; + * }} [options] + * @returns {ChildProcess} + */ +function fork(modulePath, args = [], options) { + modulePath = getValidatedPath(modulePath, "modulePath"); + + // Get options and args arguments. + let execArgv; + + if (args == null) { + args = []; + } else if (typeof args === "object" && !ArrayIsArray(args)) { + options = args; + args = []; + } else { + validateArray(args, "args"); + } + + if (options != null) { + validateObject(options, "options"); + } + options = { __proto__: null, ...options, shell: false }; + options.execPath = options.execPath || process.execPath; + validateArgumentNullCheck(options.execPath, "options.execPath"); + + // Prepare arguments for fork: + execArgv = options.execArgv || process.execArgv; + validateArgumentsNullCheck(execArgv, "options.execArgv"); + + if (execArgv === process.execArgv && process._eval != null) { + const index = ArrayPrototypeLastIndexOf.call(execArgv, process._eval); + if (index > 0) { + // Remove the -e switch to avoid fork bombing ourselves. + execArgv = ArrayPrototypeSlice.call(execArgv); + ArrayPrototypeSplice.call(execArgv, index - 1, 2); + } + } + + args = [...execArgv, modulePath, ...args]; + + if (typeof options.stdio === "string") { + options.stdio = stdioStringToArray(options.stdio, "ipc"); + } else if (!ArrayIsArray(options.stdio)) { + // Use a separate fd=3 for the IPC channel. Inherit stdin, stdout, + // and stderr from the parent if silent isn't set. + options.stdio = stdioStringToArray(options.silent ? "pipe" : "inherit", "ipc"); + } else if (!ArrayPrototypeIncludes.call(options.stdio, "ipc")) { + throw new ERR_CHILD_PROCESS_IPC_REQUIRED("options.stdio"); + } + + return spawn(options.execPath, args, options); } //------------------------------------------------------------------------------ @@ -884,7 +965,7 @@ function checkExecSyncError(ret, args, cmd) { //------------------------------------------------------------------------------ // Section 3. ChildProcess class //------------------------------------------------------------------------------ -export class ChildProcess extends EventEmitter { +class ChildProcess extends EventEmitter { #handle; #exited = false; #closesNeeded = 1; @@ -909,8 +990,11 @@ export class ChildProcess extends EventEmitter { #handleOnExit(exitCode, signalCode, err) { if (this.#exited) return; - this.exitCode = this.#handle.exitCode; - this.signalCode = exitCode > 0 ? signalCode : null; + if (signalCode) { + this.signalCode = signalCode; + } else { + this.exitCode = exitCode; + } if (this.#stdin) { this.#stdin.destroy(); @@ -951,11 +1035,11 @@ export class ChildProcess extends EventEmitter { } #getBunSpawnIo(i, encoding) { - if (__DEBUG__ && !this.#handle) { + if ($debug && !this.#handle) { if (this.#handle === null) { - debug("ChildProcess: getBunSpawnIo: this.#handle is null. This means the subprocess already exited"); + $debug("ChildProcess: getBunSpawnIo: this.#handle is null. This means the subprocess already exited"); } else { - debug("ChildProcess: getBunSpawnIo: this.#handle is undefined"); + $debug("ChildProcess: getBunSpawnIo: this.#handle is undefined"); } } @@ -1159,7 +1243,7 @@ export class ChildProcess extends EventEmitter { } #maybeClose() { - debug("Attempting to maybe close..."); + $debug("Attempting to maybe close..."); this.#closesGot++; if (this.#closesGot === this.#closesNeeded) { this.emit("close", this.exitCode, this.signalCode); @@ -1286,11 +1370,11 @@ function onSpawnNT(self) { self.emit("spawn"); } -function abortChildProcess(child, killSignal) { +function abortChildProcess(child, killSignal, reason) { if (!child) return; try { if (child.kill(killSignal)) { - child.emit("error", new AbortError()); + child.emit("error", new AbortError(undefined, { cause: reason })); } } catch (err) { child.emit("error", err); @@ -1696,7 +1780,7 @@ function ERR_UNKNOWN_SIGNAL(name) { } function ERR_INVALID_ARG_TYPE(name, type, value) { - const err = new TypeError(`The "${name}" argument must be of type ${type}. Received ${value}`); + const err = new TypeError(`The "${name}" argument must be of type ${type}. Received ${value?.toString()}`); err.code = "ERR_INVALID_ARG_TYPE"; return err; } @@ -1709,6 +1793,12 @@ function ERR_INVALID_ARG_VALUE(name, value, reason) { return new Error(`The value "${value}" is invalid for argument '${name}'. Reason: ${reason}`); } +function ERR_CHILD_PROCESS_IPC_REQUIRED(name) { + const err = new TypeError(`Forked processes must have an IPC channel, missing value 'ipc' in ${name}`); + err.code = "ERR_CHILD_PROCESS_IPC_REQUIRED"; + return err; +} + class SystemError extends Error { path; syscall; @@ -1736,6 +1826,4 @@ export default { spawnSync, execFileSync, execSync, - - [Symbol.for("CommonJS")]: 0, }; diff --git a/src/js/node/cluster.ts b/src/js/node/cluster.ts index 1be94eeb2172e7..8c1ebdd0976b4a 100644 --- a/src/js/node/cluster.ts +++ b/src/js/node/cluster.ts @@ -2,51 +2,39 @@ // This is a stub // We leave it in here to provide a better error message // TODO: implement node cluster -import EventEmitter from "node:events"; -import { throwNotImplemented } from "../shared"; - -export var SCHED_NONE = 0, - SCHED_RR = 1, - Worker, - schedulingPolicy = 2, - isWorker = false, - isPrimary = true, - isMaster = true, - cluster; - -Worker = function Worker() { - throwNotImplemented("node:cluster Worker", 2428); -}; +const EventEmitter = require("node:events"); +const { throwNotImplemented } = require("$shared"); // TODO: is it okay for this to be a class? class Cluster extends EventEmitter { - static isWorker = false; - static isPrimary = true; - static isMaster = true; + isWorker = false; + isPrimary = true; + isMaster = true; + workers = {}; + settings = {}; + SCHED_NONE = 1; + SCHED_RR = 2; + schedulingPolicy = 2; - static Worker = Worker; + Worker = function Worker() { + throwNotImplemented("node:cluster Worker", 2428); + }; - fork() { + setupPrimary() { throwNotImplemented("node:cluster", 2428); } - disconnect() { + setupMaster() { throwNotImplemented("node:cluster", 2428); } - setupMaster() { + fork() { throwNotImplemented("node:cluster", 2428); } - settings = {}; - workers = {}; - SCHED_NONE = 0; - SCHED_RR = 1; - schedulingPolicy = 2; - // @ts-expect-error - [Symbol.for("CommonJS")] = 0; + disconnect() { + throwNotImplemented("node:cluster", 2428); + } } -cluster = new Cluster(); - -export { cluster as default }; +export default new Cluster(); diff --git a/src/js/node/console.ts b/src/js/node/console.ts new file mode 100644 index 00000000000000..34cc54b56528c2 --- /dev/null +++ b/src/js/node/console.ts @@ -0,0 +1 @@ +export default console; diff --git a/src/js/node/crypto.js b/src/js/node/crypto.js index 0e4840d385383d..351f6adffb2b80 100644 --- a/src/js/node/crypto.js +++ b/src/js/node/crypto.js @@ -1,18 +1,14 @@ // Hardcoded module "node:crypto" -var __create = Object.create; var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf, - __hasOwnProp = Object.prototype.hasOwnProperty; -import { StringDecoder } from "node:string_decoder"; -import * as BufferModule from "node:buffer"; -import * as StreamModule from "node:stream"; +const StreamModule = require("node:stream"); +const BufferModule = require("node:buffer"); +const StringDecoder = require("node:string_decoder").StringDecoder; const MAX_STRING_LENGTH = 536870888; var Buffer = globalThis.Buffer; const EMPTY_BUFFER = Buffer.alloc(0); -const { isAnyArrayBuffer, isArrayBufferView } = require("util/types"); +const { isAnyArrayBuffer, isArrayBufferView } = require("node:util/types"); function getArrayBufferOrView(buffer, name, encoding) { if (isAnyArrayBuffer(buffer)) return buffer; @@ -34,38 +30,13 @@ function getArrayBufferOrView(buffer, name, encoding) { const crypto = globalThis.crypto; const globalCrypto = crypto; -var __esm = (fn, res) => - function () { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])((fn = 0))), res; - }; var __commonJS = (cb, mod) => function () { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { - for (var name in all) __defProp(target, name, { get: all[name], enumerable: !0 }); - }, - __copyProps = (to, from, except, desc) => { - if ((from && typeof from == "object") || typeof from == "function") - for (let key of __getOwnPropNames(from)) - !__hasOwnProp.call(to, key) && - key !== except && - __defProp(to, key, { - get: () => from[key], - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, - }); - return to; - }, - __reExport = (target, mod, secondTarget) => ( - __copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default") - ), - __toESM = (mod, isNodeMode, target) => ( - (target = mod != null ? __create(__getProtoOf(mod)) : {}), - __copyProps( - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target, - mod, - ) - ); + for (var name in all) __defProp(target, name, { get: all[name], enumerable: !0 }); +}; // node_modules/safe-buffer/index.js var require_safe_buffer = __commonJS({ @@ -138,28 +109,18 @@ Use Chrome, Firefox or Internet Explorer 11`); // node_modules/inherits/inherits_browser.js var require_inherits_browser = __commonJS({ "node_modules/inherits/inherits_browser.js"(exports, module) { - typeof Object.create == "function" - ? (module.exports = function (ctor, superCtor) { - superCtor && - ((ctor.super_ = superCtor), - (ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: !1, - writable: !0, - configurable: !0, - }, - }))); - }) - : (module.exports = function (ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - (TempCtor.prototype = superCtor.prototype), - (ctor.prototype = new TempCtor()), - (ctor.prototype.constructor = ctor); - } - }); + module.exports = function (ctor, superCtor) { + superCtor && + ((ctor.super_ = superCtor), + (ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: !1, + writable: !0, + configurable: !0, + }, + }))); + }; }, }); @@ -496,6 +457,7 @@ var require_hash = __commonJS({ (this._blockSize = blockSize), (this._len = 0); } + Hash.prototype = {}; Hash.prototype.update = function (data, enc) { typeof data == "string" && ((enc = enc || "utf8"), (data = Buffer2.from(data, enc))); for ( @@ -1149,7 +1111,7 @@ var require_cipher_base = __commonJS({ // node_modules/create-hash/browser.js var require_browser2 = __commonJS({ "node_modules/create-hash/browser.js"(exports, module) { - ("use strict"); + "use strict"; // does not become a node stream unless you create it into one const LazyHash = function Hash(algorithm, options) { this._options = options; @@ -1329,6 +1291,7 @@ var require_legacy = __commonJS({ (ipad[i] = key[i] ^ 54), (opad[i] = key[i] ^ 92); this._hash = [ipad]; } + Hmac.prototype = {}; inherits(Hmac, Base); Hmac.prototype._update = function (data) { this._hash.push(data); @@ -1355,14 +1318,14 @@ var require_md52 = __commonJS({ var require_browser3 = __commonJS({ "node_modules/create-hmac/browser.js"(exports, module) { "use strict"; - var inherits = require_inherits_browser(), - Legacy = require_legacy(), - Base = require_cipher_base(), - Buffer2 = require_safe_buffer().Buffer, - md5 = require_md52(), - RIPEMD160 = require_ripemd160(), - sha = require_sha2(), - ZEROS = Buffer2.alloc(128); + var inherits = require_inherits_browser(); + var Legacy = require_legacy(); + var Base = require_cipher_base(); + var Buffer2 = require_safe_buffer().Buffer; + var md5 = require_md52(); + var RIPEMD160 = require_ripemd160(); + var sha = require_sha2(); + var ZEROS = Buffer2.alloc(128); function Hmac(alg, key) { Base.call(this, "digest"), typeof key == "string" && (key = Buffer2.from(key)); var blocksize = alg === "sha512" || alg === "sha384" ? 128 : 64; @@ -1653,6 +1616,7 @@ var require_sync_browser = __commonJS({ (this.hash = hash), (this.size = sizes[alg]); } + Hmac.prototype = {}; Hmac.prototype.run = function (data, ipad) { data.copy(ipad, this.blocksize); var h = this.hash(ipad); @@ -1958,6 +1922,7 @@ var require_cipher = __commonJS({ (this.buffer = new Array(this.blockSize)), (this.bufferOff = 0); } + Cipher.prototype = {}; module.exports = Cipher; Cipher.prototype._init = function () {}; Cipher.prototype.update = function (data) { @@ -2778,6 +2743,7 @@ var require_aes = __commonJS({ function AES(key) { (this._key = asUInt32Array(key)), this._reset(); } + AES.prototype = {}; AES.blockSize = 4 * 4; AES.keySize = 256 / 8; AES.prototype.blockSize = AES.blockSize; @@ -2882,6 +2848,7 @@ var require_ghash = __commonJS({ function GHASH(key) { (this.h = key), (this.state = Buffer2.alloc(16, 0)), (this.cache = Buffer2.allocUnsafe(0)); } + GHASH.prototype = {}; GHASH.prototype.ghash = function (block) { for (var i = -1; ++i < block.length; ) this.state[i] ^= block[i]; this._multiply(); @@ -3102,6 +3069,7 @@ var require_encrypter = __commonJS({ function Splitter() { this.cache = Buffer2.allocUnsafe(0); } + Splitter.prototype = {}; Splitter.prototype.add = function (data) { this.cache = Buffer2.concat([this.cache, data]); }; @@ -3191,6 +3159,7 @@ var require_decrypter = __commonJS({ function Splitter() { this.cache = Buffer2.allocUnsafe(0); } + Splitter.prototype = {}; Splitter.prototype.add = function (data) { this.cache = Buffer2.concat([this.cache, data]); }; @@ -3367,6 +3336,7 @@ var require_bn = __commonJS({ ((base === "le" || base === "be") && ((endian = base), (base = 10)), this._init(number || 0, base || 10, endian || "be")); } + BN.prototype = {}; typeof module2 == "object" ? (module2.exports = BN) : (exports2.BN = BN), (BN.BN = BN), (BN.wordSize = 26); var Buffer2 = Buffer; (BN.isBN = function (num) { @@ -4432,6 +4402,7 @@ var require_bn = __commonJS({ function FFTM(x, y) { (this.x = x), (this.y = y); } + FFTM.prototype = {}; (FFTM.prototype.makeRBT = function (N) { for (var t = new Array(N), l = BN.prototype._countBits(N) - 1, i = 0; i < N; i++) t[i] = this.revBin(i, l, N); return t; @@ -5072,6 +5043,7 @@ var require_bn = __commonJS({ (this.k = new BN(1).iushln(this.n).isub(this.p)), (this.tmp = this._tmp()); } + MPrime.prototype = {}; (MPrime.prototype._tmp = function () { var tmp = new BN(null); return (tmp.words = new Array(Math.ceil(this.n / 13))), tmp; @@ -5165,6 +5137,7 @@ var require_bn = __commonJS({ (this.m = prime.p), (this.prime = prime); } else assert(m.gtn(1), "modulus must be greater than 1"), (this.m = m), (this.prime = null); } + Red.prototype = {}; (Red.prototype._verify1 = function (a) { assert(a.negative === 0, "red works only with positives"), assert(a.red, "red works only with red numbers"); }), @@ -5328,18181 +5301,6246 @@ var require_bn = __commonJS({ })(typeof module > "u" || module, exports); }, }); +var require_bn2 = require_bn; -// node_modules/miller-rabin/node_modules/bn.js/lib/bn.js -var require_bn2 = __commonJS({ - "node_modules/miller-rabin/node_modules/bn.js/lib/bn.js"(exports, module) { - (function (module2, exports2) { - "use strict"; - function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); +// node_modules/brorand/index.js +var require_brorand = __commonJS({ + "node_modules/brorand/index.js"(exports, module) { + var r; + module.exports = function (len) { + return r || (r = new Rand(null)), r.generate(len); + }; + function Rand(rand) { + this.rand = rand; + } + Rand.prototype = {}; + module.exports.Rand = Rand; + Rand.prototype.generate = function (len) { + return this._rand(len); + }; + Rand.prototype._rand = function (n) { + var out = new Buffer(n); + crypto.getRandomValues(out); + return out; + }; + }, +}); + +// node_modules/miller-rabin/lib/mr.js +var require_mr = __commonJS({ + "node_modules/miller-rabin/lib/mr.js"(exports, module) { + var bn = require_bn2(), + brorand = require_brorand(); + function MillerRabin(rand) { + this.rand = rand || new brorand.Rand(); + } + module.exports = MillerRabin; + MillerRabin.create = function (rand) { + return new MillerRabin(rand); + }; + MillerRabin.prototype = {}; + MillerRabin.prototype._randbelow = function (n) { + var len = n.bitLength(), + min_bytes = Math.ceil(len / 8); + do var a = new bn(this.rand.generate(min_bytes)); + while (a.cmp(n) >= 0); + return a; + }; + MillerRabin.prototype._randrange = function (start, stop) { + var size = stop.sub(start); + return start.add(this._randbelow(size)); + }; + MillerRabin.prototype.test = function (n, k, cb) { + var len = n.bitLength(), + red = bn.mont(n), + rone = new bn(1).toRed(red); + k || (k = Math.max(1, (len / 48) | 0)); + for (var n1 = n.subn(1), s = 0; !n1.testn(s); s++); + for (var d = n.shrn(s), rn1 = n1.toRed(red), prime = !0; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + cb && cb(a); + var x = a.toRed(red).redPow(d); + if (!(x.cmp(rone) === 0 || x.cmp(rn1) === 0)) { + for (var i = 1; i < s; i++) { + if (((x = x.redSqr()), x.cmp(rone) === 0)) return !1; + if (x.cmp(rn1) === 0) break; + } + if (i === s) return !1; + } } - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - (TempCtor.prototype = superCtor.prototype), - (ctor.prototype = new TempCtor()), - (ctor.prototype.constructor = ctor); + return prime; + }; + MillerRabin.prototype.getDivisor = function (n, k) { + var len = n.bitLength(), + red = bn.mont(n), + rone = new bn(1).toRed(red); + k || (k = Math.max(1, (len / 48) | 0)); + for (var n1 = n.subn(1), s = 0; !n1.testn(s); s++); + for (var d = n.shrn(s), rn1 = n1.toRed(red); k > 0; k--) { + var a = this._randrange(new bn(2), n1), + g = n.gcd(a); + if (g.cmpn(1) !== 0) return g; + var x = a.toRed(red).redPow(d); + if (!(x.cmp(rone) === 0 || x.cmp(rn1) === 0)) { + for (var i = 1; i < s; i++) { + if (((x = x.redSqr()), x.cmp(rone) === 0)) return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) break; + } + if (i === s) return (x = x.redSqr()), x.fromRed().subn(1).gcd(n); + } } - function BN(number, base, endian) { - if (BN.isBN(number)) return number; - (this.negative = 0), - (this.words = null), - (this.length = 0), - (this.red = null), - number !== null && - ((base === "le" || base === "be") && ((endian = base), (base = 10)), - this._init(number || 0, base || 10, endian || "be")); + return !1; + }; + }, +}); + +// node_modules/diffie-hellman/lib/generatePrime.js +var require_generatePrime = __commonJS({ + "node_modules/diffie-hellman/lib/generatePrime.js"(exports, module) { + var randomBytes = require_browser(); + module.exports = findPrime; + findPrime.simpleSieve = simpleSieve; + findPrime.fermatTest = fermatTest; + var BN = require_bn(), + TWENTYFOUR = new BN(24), + MillerRabin = require_mr(), + millerRabin = new MillerRabin(), + ONE = new BN(1), + TWO = new BN(2), + FIVE = new BN(5), + SIXTEEN = new BN(16), + EIGHT = new BN(8), + TEN = new BN(10), + THREE = new BN(3), + SEVEN = new BN(7), + ELEVEN = new BN(11), + FOUR = new BN(4), + TWELVE = new BN(12), + primes = null; + function _getPrimes() { + if (primes !== null) return primes; + var limit = 1048576, + res = []; + res[0] = 2; + for (var i = 1, k = 3; k < limit; k += 2) { + for (var sqrt = Math.ceil(Math.sqrt(k)), j = 0; j < i && res[j] <= sqrt && k % res[j] !== 0; j++); + (i !== j && res[j] <= sqrt) || (res[i++] = k); } - typeof module2 == "object" ? (module2.exports = BN) : (exports2.BN = BN), (BN.BN = BN), (BN.wordSize = 26); - var Buffer2 = Buffer; - (BN.isBN = function (num) { - return num instanceof BN - ? !0 - : num !== null && - typeof num == "object" && - num.constructor.wordSize === BN.wordSize && - Array.isArray(num.words); - }), - (BN.max = function (left, right) { - return left.cmp(right) > 0 ? left : right; - }), - (BN.min = function (left, right) { - return left.cmp(right) < 0 ? left : right; - }), - (BN.prototype._init = function (number, base, endian) { - if (typeof number == "number") return this._initNumber(number, base, endian); - if (typeof number == "object") return this._initArray(number, base, endian); - base === "hex" && (base = 16), - assert(base === (base | 0) && base >= 2 && base <= 36), - (number = number.toString().replace(/\s+/g, "")); - var start = 0; - number[0] === "-" && (start++, (this.negative = 1)), - start < number.length && - (base === 16 - ? this._parseHex(number, start, endian) - : (this._parseBase(number, base, start), - endian === "le" && this._initArray(this.toArray(), base, endian))); - }), - (BN.prototype._initNumber = function (number, base, endian) { - number < 0 && ((this.negative = 1), (number = -number)), - number < 67108864 - ? ((this.words = [number & 67108863]), (this.length = 1)) - : number < 4503599627370496 - ? ((this.words = [number & 67108863, (number / 67108864) & 67108863]), (this.length = 2)) - : (assert(number < 9007199254740992), - (this.words = [number & 67108863, (number / 67108864) & 67108863, 1]), - (this.length = 3)), - endian === "le" && this._initArray(this.toArray(), base, endian); - }), - (BN.prototype._initArray = function (number, base, endian) { - if ((assert(typeof number.length == "number"), number.length <= 0)) - return (this.words = [0]), (this.length = 1), this; - (this.length = Math.ceil(number.length / 3)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var j, - w, - off = 0; - if (endian === "be") - for (i = number.length - 1, j = 0; i >= 0; i -= 3) - (w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - else if (endian === "le") - for (i = 0, j = 0; i < number.length; i += 3) - (w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - return this.strip(); - }); - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - return c >= 65 && c <= 70 ? c - 55 : c >= 97 && c <= 102 ? c - 87 : (c - 48) & 15; + return (primes = res), res; + } + function simpleSieve(p) { + for (var primes2 = _getPrimes(), i = 0; i < primes2.length; i++) + if (p.modn(primes2[i]) === 0) return p.cmpn(primes2[i]) === 0; + return !0; + } + function fermatTest(p) { + var red = BN.mont(p); + return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; + } + function findPrime(bits, gen) { + if (bits < 16) return gen === 2 || gen === 5 ? new BN([140, 123]) : new BN([140, 39]); + gen = new BN(gen); + for (var num, n2; ; ) { + for (num = new BN(randomBytes(Math.ceil(bits / 8))); num.bitLength() > bits; ) num.ishrn(1); + if ((num.isEven() && num.iadd(ONE), num.testn(1) || num.iadd(TWO), gen.cmp(TWO))) { + if (!gen.cmp(FIVE)) for (; num.mod(TEN).cmp(THREE); ) num.iadd(FOUR); + } else for (; num.mod(TWENTYFOUR).cmp(ELEVEN); ) num.iadd(FOUR); + if ( + ((n2 = num.shrn(1)), + simpleSieve(n2) && + simpleSieve(num) && + fermatTest(n2) && + fermatTest(num) && + millerRabin.test(n2) && + millerRabin.test(num)) + ) + return num; } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - return index - 1 >= lowerBound && (r |= parseHex4Bits(string, index - 1) << 4), r; + } + }, +}); + +// node_modules/diffie-hellman/lib/primes.json +var require_primes = __commonJS({ + "node_modules/diffie-hellman/lib/primes.json"(exports, module) { + module.exports = { + modp1: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff", + }, + modp2: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff", + }, + modp5: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff", + }, + modp14: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff", + }, + modp15: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff", + }, + modp16: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff", + }, + modp17: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff", + }, + modp18: { + gen: "02", + prime: + "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff", + }, + }; + }, +}); + +// node_modules/diffie-hellman/lib/dh.js +var require_dh = __commonJS({ + "node_modules/diffie-hellman/lib/dh.js"(exports, module) { + var BN = require_bn(), + MillerRabin = require_mr(), + millerRabin = new MillerRabin(), + TWENTYFOUR = new BN(24), + ELEVEN = new BN(11), + TEN = new BN(10), + THREE = new BN(3), + SEVEN = new BN(7), + primes = require_generatePrime(), + randomBytes = require_browser(); + module.exports = DH; + function setPublicKey(pub, enc) { + return ( + (enc = enc || "utf8"), Buffer.isBuffer(pub) || (pub = new Buffer(pub, enc)), (this._pub = new BN(pub)), this + ); + } + function setPrivateKey(priv, enc) { + return ( + (enc = enc || "utf8"), + Buffer.isBuffer(priv) || (priv = new Buffer(priv, enc)), + (this._priv = new BN(priv)), + this + ); + } + var primeCache = {}; + function checkPrime(prime, generator) { + var gen = generator.toString("hex"), + hex = [gen, prime.toString(16)].join("_"); + if (hex in primeCache) return primeCache[hex]; + var error = 0; + if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) + return ( + (error += 1), gen === "02" || gen === "05" ? (error += 8) : (error += 4), (primeCache[hex] = error), error + ); + millerRabin.test(prime.shrn(1)) || (error += 2); + var rem; + switch (gen) { + case "02": + prime.mod(TWENTYFOUR).cmp(ELEVEN) && (error += 8); + break; + case "05": + (rem = prime.mod(TEN)), rem.cmp(THREE) && rem.cmp(SEVEN) && (error += 8); + break; + default: + error += 4; } - BN.prototype._parseHex = function (number, start, endian) { - (this.length = Math.ceil((number.length - start) / 6)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var off = 0, - j = 0, - w; - if (endian === "be") - for (i = number.length - 1; i >= start; i -= 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - } - this.strip(); - }; - function parseBase(str, start, end, mul) { - for (var r = 0, len = Math.min(str.length, end), i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - (r *= mul), c >= 49 ? (r += c - 49 + 10) : c >= 17 ? (r += c - 17 + 10) : (r += c); - } - return r; + return (primeCache[hex] = error), error; + } + function DH(prime, generator, malleable) { + this.setGenerator(generator), + (this.__prime = new BN(prime)), + (this._prime = BN.mont(this.__prime)), + (this._primeLen = prime.length), + (this._pub = void 0), + (this._priv = void 0), + (this._primeCode = void 0), + malleable ? ((this.setPublicKey = setPublicKey), (this.setPrivateKey = setPrivateKey)) : (this._primeCode = 8); + } + DH.prototype = {}; + Object.defineProperty(DH.prototype, "verifyError", { + enumerable: !0, + get: function () { + return ( + typeof this._primeCode != "number" && (this._primeCode = checkPrime(this.__prime, this.__gen)), + this._primeCode + ); + }, + }); + DH.prototype.generateKeys = function () { + return ( + this._priv || (this._priv = new BN(randomBytes(this._primeLen))), + (this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed()), + this.getPublicKey() + ); + }; + DH.prototype.computeSecret = function (other) { + (other = new BN(other)), (other = other.toRed(this._prime)); + var secret = other.redPow(this._priv).fromRed(), + out = new Buffer(secret.toArray()), + prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0), (out = Buffer.concat([front, out])); } - (BN.prototype._parseBase = function (number, base, start) { - (this.words = [0]), (this.length = 1); - for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base) limbLen++; - limbLen--, (limbPow = (limbPow / base) | 0); - for ( - var total = number.length - start, - mod = total % limbLen, - end = Math.min(total, total - mod) + start, - word = 0, - i = start; - i < end; - i += limbLen - ) - (word = parseBase(number, i, i + limbLen, base)), - this.imuln(limbPow), - this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - if (mod !== 0) { - var pow = 1; - for (word = parseBase(number, i, number.length, base), i = 0; i < mod; i++) pow *= base; - this.imuln(pow), this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - } - this.strip(); - }), - (BN.prototype.copy = function (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) dest.words[i] = this.words[i]; - (dest.length = this.length), (dest.negative = this.negative), (dest.red = this.red); - }), - (BN.prototype.clone = function () { - var r = new BN(null); - return this.copy(r), r; - }), - (BN.prototype._expand = function (size) { - for (; this.length < size; ) this.words[this.length++] = 0; - return this; - }), - (BN.prototype.strip = function () { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; - return this._normSign(); - }), - (BN.prototype._normSign = function () { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }), - (BN.prototype.inspect = function () { - return (this.red ? ""; - }); - var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000", - ], - groupSizes = [ - 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, - ], - groupBases = [ - 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, - 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, - 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, - 60466176, - ]; - (BN.prototype.toString = function (base, padding) { - (base = base || 10), (padding = padding | 0 || 1); - var out; - if (base === 16 || base === "hex") { - out = ""; - for (var off = 0, carry = 0, i = 0; i < this.length; i++) { - var w = this.words[i], - word = (((w << off) | carry) & 16777215).toString(16); - (carry = (w >>> (24 - off)) & 16777215), - carry !== 0 || i !== this.length - 1 ? (out = zeros[6 - word.length] + word + out) : (out = word + out), - (off += 2), - off >= 26 && ((off -= 26), i--); - } - for (carry !== 0 && (out = carry.toString(16) + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - if (base === (base | 0) && base >= 2 && base <= 36) { - var groupSize = groupSizes[base], - groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - for (c.negative = 0; !c.isZero(); ) { - var r = c.modn(groupBase).toString(base); - (c = c.idivn(groupBase)), c.isZero() ? (out = r + out) : (out = zeros[groupSize - r.length] + r + out); - } - for (this.isZero() && (out = "0" + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; + return out; + }; + DH.prototype.getPublicKey = function (enc) { + return formatReturnValue(this._pub, enc); + }; + DH.prototype.getPrivateKey = function (enc) { + return formatReturnValue(this._priv, enc); + }; + DH.prototype.getPrime = function (enc) { + return formatReturnValue(this.__prime, enc); + }; + DH.prototype.getGenerator = function (enc) { + return formatReturnValue(this._gen, enc); + }; + DH.prototype.setGenerator = function (gen, enc) { + return ( + (enc = enc || "utf8"), + Buffer.isBuffer(gen) || (gen = new Buffer(gen, enc)), + (this.__gen = gen), + (this._gen = new BN(gen)), + this + ); + }; + function formatReturnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + return enc ? buf.toString(enc) : buf; + } + }, +}); + +// node_modules/diffie-hellman/browser.js +var require_browser7 = __commonJS({ + "node_modules/diffie-hellman/browser.js"(exports) { + var generatePrime = require_generatePrime(), + primes = require_primes(), + DH = require_dh(); + function getDiffieHellman(mod) { + var prime = new Buffer(primes[mod].prime, "hex"), + gen = new Buffer(primes[mod].gen, "hex"); + return new DH(prime, gen); + } + var ENCODINGS = { + binary: !0, + hex: !0, + base64: !0, + }; + function createDiffieHellman(prime, enc, generator, genc) { + return Buffer.isBuffer(enc) || ENCODINGS[enc] === void 0 + ? createDiffieHellman(prime, "binary", enc, generator) + : ((enc = enc || "binary"), + (genc = genc || "binary"), + (generator = generator || new Buffer([2])), + Buffer.isBuffer(generator) || (generator = new Buffer(generator, genc)), + typeof prime == "number" + ? new DH(generatePrime(prime, generator), generator, !0) + : (Buffer.isBuffer(prime) || (prime = new Buffer(prime, enc)), new DH(prime, generator, !0))); + } + exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman; + exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman; + }, +}); + +// node_modules/bn.js/lib/bn.js +var require_bn3 = require_bn; + +// node_modules/browserify-rsa/index.js +var require_browserify_rsa = __commonJS({ + "node_modules/browserify-rsa/index.js"(exports, module) { + var BN = require_bn3(), + randomBytes = require_browser(); + function blind(priv) { + var r = getr(priv), + blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed(); + return { blinder, unblinder: r.invm(priv.modulus) }; + } + function getr(priv) { + var len = priv.modulus.byteLength(), + r; + do r = new BN(randomBytes(len)); + while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)); + return r; + } + function crt(msg, priv) { + var blinds = blind(priv), + len = priv.modulus.byteLength(), + blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus), + c1 = blinded.toRed(BN.mont(priv.prime1)), + c2 = blinded.toRed(BN.mont(priv.prime2)), + qinv = priv.coefficient, + p = priv.prime1, + q = priv.prime2, + m1 = c1.redPow(priv.exponent1).fromRed(), + m2 = c2.redPow(priv.exponent2).fromRed(), + h = m1.isub(m2).imul(qinv).umod(p).imul(q); + return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, "be", len); + } + crt.getr = getr; + module.exports = crt; + }, +}); + +// node_modules/elliptic/package.json +var require_package = __commonJS({ + "node_modules/elliptic/package.json"(exports, module) { + module.exports = { + name: "elliptic", + version: "6.5.4", + description: "EC cryptography", + main: "lib/elliptic.js", + files: ["lib"], + scripts: { + lint: "eslint lib test", + "lint:fix": "npm run lint -- --fix", + unit: "istanbul test _mocha --reporter=spec test/index.js", + test: "npm run lint && npm run unit", + version: "grunt dist && git add dist/", + }, + repository: { + type: "git", + url: "git@github.com:indutny/elliptic", + }, + keywords: ["EC", "Elliptic", "curve", "Cryptography"], + author: "Fedor Indutny ", + license: "MIT", + bugs: { + url: "https://github.com/indutny/elliptic/issues", + }, + homepage: "https://github.com/indutny/elliptic", + devDependencies: { + brfs: "^2.0.2", + coveralls: "^3.1.0", + eslint: "^7.6.0", + grunt: "^1.2.1", + "grunt-browserify": "^5.3.0", + "grunt-cli": "^1.3.2", + "grunt-contrib-connect": "^3.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^5.0.0", + "grunt-mocha-istanbul": "^5.0.2", + "grunt-saucelabs": "^9.0.1", + istanbul: "^0.4.5", + mocha: "^8.0.1", + }, + dependencies: { + "bn.js": "^4.11.9", + brorand: "^1.1.0", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.1", + inherits: "^2.0.4", + "minimalistic-assert": "^1.0.1", + "minimalistic-crypto-utils": "^1.0.1", + }, + }; + }, +}); + +// node_modules/elliptic/node_modules/bn.js/lib/bn.js +var require_bn4 = require_bn; + +// node_modules/minimalistic-crypto-utils/lib/utils.js +var require_utils2 = __commonJS({ + "node_modules/minimalistic-crypto-utils/lib/utils.js"(exports) { + "use strict"; + var utils = exports; + function toArray(msg, enc) { + if (Array.isArray(msg)) return msg.slice(); + if (!msg) return []; + var res = []; + if (typeof msg != "string") { + for (var i = 0; i < msg.length; i++) res[i] = msg[i] | 0; + return res; + } + if (enc === "hex") { + (msg = msg.replace(/[^a-z0-9]+/gi, "")), msg.length % 2 !== 0 && (msg = "0" + msg); + for (var i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i), + hi = c >> 8, + lo = c & 255; + hi ? res.push(hi, lo) : res.push(lo); } - assert(!1, "Base should be between 2 and 36"); - }), - (BN.prototype.toNumber = function () { - var ret = this.words[0]; - return ( - this.length === 2 - ? (ret += this.words[1] * 67108864) - : this.length === 3 && this.words[2] === 1 - ? (ret += 4503599627370496 + this.words[1] * 67108864) - : this.length > 2 && assert(!1, "Number can only safely store up to 53 bits"), - this.negative !== 0 ? -ret : ret - ); - }), - (BN.prototype.toJSON = function () { - return this.toString(16); - }), - (BN.prototype.toBuffer = function (endian, length) { - return assert(typeof Buffer2 < "u"), this.toArrayLike(Buffer2, endian, length); - }), - (BN.prototype.toArray = function (endian, length) { - return this.toArrayLike(Array, endian, length); - }), - (BN.prototype.toArrayLike = function (ArrayType, endian, length) { - var byteLength = this.byteLength(), - reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"), - assert(reqLength > 0, "Requested array length <= 0"), - this.strip(); - var littleEndian = endian === "le", - res = new ArrayType(reqLength), - b, - i, - q = this.clone(); - if (littleEndian) { - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[i] = b); - for (; i < reqLength; i++) res[i] = 0; - } else { - for (i = 0; i < reqLength - byteLength; i++) res[i] = 0; - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[reqLength - i - 1] = b); - } - return res; - }), - Math.clz32 - ? (BN.prototype._countBits = function (w) { - return 32 - Math.clz32(w); - }) - : (BN.prototype._countBits = function (w) { - var t = w, - r = 0; - return ( - t >= 4096 && ((r += 13), (t >>>= 13)), - t >= 64 && ((r += 7), (t >>>= 7)), - t >= 8 && ((r += 4), (t >>>= 4)), - t >= 2 && ((r += 2), (t >>>= 2)), - r + t - ); - }), - (BN.prototype._zeroBits = function (w) { - if (w === 0) return 26; - var t = w, - r = 0; - return ( - (t & 8191) === 0 && ((r += 13), (t >>>= 13)), - (t & 127) === 0 && ((r += 7), (t >>>= 7)), - (t & 15) === 0 && ((r += 4), (t >>>= 4)), - (t & 3) === 0 && ((r += 2), (t >>>= 2)), - (t & 1) === 0 && r++, - r - ); - }), - (BN.prototype.bitLength = function () { - var w = this.words[this.length - 1], - hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }); - function toBitArray(num) { - for (var w = new Array(num.bitLength()), bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0, - wbit = bit % 26; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; + return res; + } + utils.toArray = toArray; + function zero2(word) { + return word.length === 1 ? "0" + word : word; + } + utils.zero2 = zero2; + function toHex(msg) { + for (var res = "", i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); + return res; + } + utils.toHex = toHex; + utils.encode = function (arr, enc) { + return enc === "hex" ? toHex(arr) : arr; + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/utils.js +var require_utils3 = __commonJS({ + "node_modules/elliptic/lib/elliptic/utils.js"(exports) { + "use strict"; + var utils = exports, + BN = require_bn4(), + minAssert = require_minimalistic_assert(), + minUtils = require_utils2(); + utils.assert = minAssert; + utils.toArray = minUtils.toArray; + utils.zero2 = minUtils.zero2; + utils.toHex = minUtils.toHex; + utils.encode = minUtils.encode; + function getNAF(num, w, bits) { + var naf = new Array(Math.max(num.bitLength(), bits) + 1); + naf.fill(0); + for (var ws = 1 << (w + 1), k = num.clone(), i = 0; i < naf.length; i++) { + var z, + mod = k.andln(ws - 1); + k.isOdd() ? (mod > (ws >> 1) - 1 ? (z = (ws >> 1) - mod) : (z = mod), k.isubn(z)) : (z = 0), + (naf[i] = z), + k.iushrn(1); + } + return naf; + } + utils.getNAF = getNAF; + function getJSF(k1, k2) { + var jsf = [[], []]; + (k1 = k1.clone()), (k2 = k2.clone()); + for (var d1 = 0, d2 = 0, m8; k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0; ) { + var m14 = (k1.andln(3) + d1) & 3, + m24 = (k2.andln(3) + d2) & 3; + m14 === 3 && (m14 = -1), m24 === 3 && (m24 = -1); + var u1; + (m14 & 1) === 0 + ? (u1 = 0) + : ((m8 = (k1.andln(7) + d1) & 7), (m8 === 3 || m8 === 5) && m24 === 2 ? (u1 = -m14) : (u1 = m14)), + jsf[0].push(u1); + var u2; + (m24 & 1) === 0 + ? (u2 = 0) + : ((m8 = (k2.andln(7) + d2) & 7), (m8 === 3 || m8 === 5) && m14 === 2 ? (u2 = -m24) : (u2 = m24)), + jsf[1].push(u2), + 2 * d1 === u1 + 1 && (d1 = 1 - d1), + 2 * d2 === u2 + 1 && (d2 = 1 - d2), + k1.iushrn(1), + k2.iushrn(1); + } + return jsf; + } + utils.getJSF = getJSF; + function cachedProperty(obj, name, computer) { + var key = "_" + name; + obj.prototype[name] = function () { + return this[key] !== void 0 ? this[key] : (this[key] = computer.call(this)); + }; + } + utils.cachedProperty = cachedProperty; + function parseBytes(bytes) { + return typeof bytes == "string" ? utils.toArray(bytes, "hex") : bytes; + } + utils.parseBytes = parseBytes; + function intFromLE(bytes) { + return new BN(bytes, "hex", "le"); + } + utils.intFromLE = intFromLE; + }, +}); + +// node_modules/elliptic/lib/elliptic/curve/base.js +var require_base = __commonJS({ + "node_modules/elliptic/lib/elliptic/curve/base.js"(exports, module) { + "use strict"; + var BN = require_bn4(), + utils = require_utils3(), + getNAF = utils.getNAF, + getJSF = utils.getJSF, + assert = utils.assert; + function BaseCurve(type, conf) { + (this.type = type), + (this.p = new BN(conf.p, 16)), + (this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p)), + (this.zero = new BN(0).toRed(this.red)), + (this.one = new BN(1).toRed(this.red)), + (this.two = new BN(2).toRed(this.red)), + (this.n = conf.n && new BN(conf.n, 16)), + (this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed)), + (this._wnafT1 = new Array(4)), + (this._wnafT2 = new Array(4)), + (this._wnafT3 = new Array(4)), + (this._wnafT4 = new Array(4)), + (this._bitLength = this.n ? this.n.bitLength() : 0); + var adjustCount = this.n && this.p.div(this.n); + !adjustCount || adjustCount.cmpn(100) > 0 + ? (this.redN = null) + : ((this._maxwellTrick = !0), (this.redN = this.n.toRed(this.red))); + } + module.exports = BaseCurve; + BaseCurve.prototype = {}; + BaseCurve.prototype.point = function () { + throw new Error("Not implemented"); + }; + BaseCurve.prototype.validate = function () { + throw new Error("Not implemented"); + }; + BaseCurve.prototype._fixedNafMul = function (p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(), + naf = getNAF(k, 1, this._bitLength), + I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + var repr = [], + j, + nafW; + for (j = 0; j < naf.length; j += doubles.step) { + nafW = 0; + for (var l = j + doubles.step - 1; l >= j; l--) nafW = (nafW << 1) + naf[l]; + repr.push(nafW); + } + for (var a = this.jpoint(null, null, null), b = this.jpoint(null, null, null), i = I; i > 0; i--) { + for (j = 0; j < repr.length; j++) + (nafW = repr[j]), + nafW === i ? (b = b.mixedAdd(doubles.points[j])) : nafW === -i && (b = b.mixedAdd(doubles.points[j].neg())); + a = a.add(b); + } + return a.toP(); + }; + BaseCurve.prototype._wnafMul = function (p, k) { + var w = 4, + nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + for ( + var wnd = nafPoints.points, + naf = getNAF(k, w, this._bitLength), + acc = this.jpoint(null, null, null), + i = naf.length - 1; + i >= 0; + i-- + ) { + for (var l = 0; i >= 0 && naf[i] === 0; i--) l++; + if ((i >= 0 && l++, (acc = acc.dblp(l)), i < 0)) break; + var z = naf[i]; + assert(z !== 0), + p.type === "affine" + ? z > 0 + ? (acc = acc.mixedAdd(wnd[(z - 1) >> 1])) + : (acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg())) + : z > 0 + ? (acc = acc.add(wnd[(z - 1) >> 1])) + : (acc = acc.add(wnd[(-z - 1) >> 1].neg())); + } + return p.type === "affine" ? acc.toP() : acc; + }; + BaseCurve.prototype._wnafMulAdd = function (defW, points, coeffs, len, jacobianResult) { + var wndWidth = this._wnafT1, + wnd = this._wnafT2, + naf = this._wnafT3, + max = 0, + i, + j, + p; + for (i = 0; i < len; i++) { + p = points[i]; + var nafPoints = p._getNAFPoints(defW); + (wndWidth[i] = nafPoints.wnd), (wnd[i] = nafPoints.points); + } + for (i = len - 1; i >= 1; i -= 2) { + var a = i - 1, + b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + (naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength)), + (naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength)), + (max = Math.max(naf[a].length, max)), + (max = Math.max(naf[b].length, max)); + continue; + } + var comb = [points[a], null, null, points[b]]; + points[a].y.cmp(points[b].y) === 0 + ? ((comb[1] = points[a].add(points[b])), (comb[2] = points[a].toJ().mixedAdd(points[b].neg()))) + : points[a].y.cmp(points[b].y.redNeg()) === 0 + ? ((comb[1] = points[a].toJ().mixedAdd(points[b])), (comb[2] = points[a].add(points[b].neg()))) + : ((comb[1] = points[a].toJ().mixedAdd(points[b])), (comb[2] = points[a].toJ().mixedAdd(points[b].neg()))); + var index = [-3, -1, -5, -7, 0, 7, 5, 1, 3], + jsf = getJSF(coeffs[a], coeffs[b]); + for ( + max = Math.max(jsf[0].length, max), naf[a] = new Array(max), naf[b] = new Array(max), j = 0; + j < max; + j++ + ) { + var ja = jsf[0][j] | 0, + jb = jsf[1][j] | 0; + (naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]), (naf[b][j] = 0), (wnd[a] = comb); } - return w; } - (BN.prototype.zeroBits = function () { - if (this.isZero()) return 0; - for (var r = 0, i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - if (((r += b), b !== 26)) break; + var acc = this.jpoint(null, null, null), + tmp = this._wnafT4; + for (i = max; i >= 0; i--) { + for (var k = 0; i >= 0; ) { + var zero = !0; + for (j = 0; j < len; j++) (tmp[j] = naf[j][i] | 0), tmp[j] !== 0 && (zero = !1); + if (!zero) break; + k++, i--; } - return r; - }), - (BN.prototype.byteLength = function () { - return Math.ceil(this.bitLength() / 8); - }), - (BN.prototype.toTwos = function (width) { - return this.negative !== 0 ? this.abs().inotn(width).iaddn(1) : this.clone(); - }), - (BN.prototype.fromTwos = function (width) { - return this.testn(width - 1) ? this.notn(width).iaddn(1).ineg() : this.clone(); - }), - (BN.prototype.isNeg = function () { - return this.negative !== 0; - }), - (BN.prototype.neg = function () { - return this.clone().ineg(); - }), - (BN.prototype.ineg = function () { - return this.isZero() || (this.negative ^= 1), this; - }), - (BN.prototype.iuor = function (num) { - for (; this.length < num.length; ) this.words[this.length++] = 0; - for (var i = 0; i < num.length; i++) this.words[i] = this.words[i] | num.words[i]; - return this.strip(); - }), - (BN.prototype.ior = function (num) { - return assert((this.negative | num.negative) === 0), this.iuor(num); - }), - (BN.prototype.or = function (num) { - return this.length > num.length ? this.clone().ior(num) : num.clone().ior(this); - }), - (BN.prototype.uor = function (num) { - return this.length > num.length ? this.clone().iuor(num) : num.clone().iuor(this); - }), - (BN.prototype.iuand = function (num) { - var b; - this.length > num.length ? (b = num) : (b = this); - for (var i = 0; i < b.length; i++) this.words[i] = this.words[i] & num.words[i]; - return (this.length = b.length), this.strip(); - }), - (BN.prototype.iand = function (num) { - return assert((this.negative | num.negative) === 0), this.iuand(num); - }), - (BN.prototype.and = function (num) { - return this.length > num.length ? this.clone().iand(num) : num.clone().iand(this); - }), - (BN.prototype.uand = function (num) { - return this.length > num.length ? this.clone().iuand(num) : num.clone().iuand(this); - }), - (BN.prototype.iuxor = function (num) { - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var i = 0; i < b.length; i++) this.words[i] = a.words[i] ^ b.words[i]; - if (this !== a) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = a.length), this.strip(); - }), - (BN.prototype.ixor = function (num) { - return assert((this.negative | num.negative) === 0), this.iuxor(num); - }), - (BN.prototype.xor = function (num) { - return this.length > num.length ? this.clone().ixor(num) : num.clone().ixor(this); - }), - (BN.prototype.uxor = function (num) { - return this.length > num.length ? this.clone().iuxor(num) : num.clone().iuxor(this); - }), - (BN.prototype.inotn = function (width) { - assert(typeof width == "number" && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0, - bitsLeft = width % 26; - this._expand(bytesNeeded), bitsLeft > 0 && bytesNeeded--; - for (var i = 0; i < bytesNeeded; i++) this.words[i] = ~this.words[i] & 67108863; - return bitsLeft > 0 && (this.words[i] = ~this.words[i] & (67108863 >> (26 - bitsLeft))), this.strip(); - }), - (BN.prototype.notn = function (width) { - return this.clone().inotn(width); - }), - (BN.prototype.setn = function (bit, val) { - assert(typeof bit == "number" && bit >= 0); - var off = (bit / 26) | 0, - wbit = bit % 26; - return ( - this._expand(off + 1), - val - ? (this.words[off] = this.words[off] | (1 << wbit)) - : (this.words[off] = this.words[off] & ~(1 << wbit)), - this.strip() - ); - }), - (BN.prototype.iadd = function (num) { - var r; - if (this.negative !== 0 && num.negative === 0) - return (this.negative = 0), (r = this.isub(num)), (this.negative ^= 1), this._normSign(); - if (this.negative === 0 && num.negative !== 0) - return (num.negative = 0), (r = this.isub(num)), (num.negative = 1), r._normSign(); - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) + (b.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - if (((this.length = a.length), carry !== 0)) (this.words[this.length] = carry), this.length++; - else if (a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return this; - }), - (BN.prototype.add = function (num) { - var res; - return num.negative !== 0 && this.negative === 0 - ? ((num.negative = 0), (res = this.sub(num)), (num.negative ^= 1), res) - : num.negative === 0 && this.negative !== 0 - ? ((this.negative = 0), (res = num.sub(this)), (this.negative = 1), res) - : this.length > num.length - ? this.clone().iadd(num) - : num.clone().iadd(this); - }), - (BN.prototype.isub = function (num) { - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - return (num.negative = 1), r._normSign(); - } else if (this.negative !== 0) - return (this.negative = 0), this.iadd(num), (this.negative = 1), this._normSign(); - var cmp = this.cmp(num); - if (cmp === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; - var a, b; - cmp > 0 ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) - (b.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - if (carry === 0 && i < a.length && a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = Math.max(this.length, i)), a !== this && (this.negative = 1), this.strip(); - }), - (BN.prototype.sub = function (num) { - return this.clone().isub(num); - }); - function smallMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - var len = (self2.length + num.length) | 0; - (out.length = len), (len = (len - 1) | 0); - var a = self2.words[0] | 0, - b = num.words[0] | 0, - r = a * b, - lo = r & 67108863, - carry = (r / 67108864) | 0; - out.words[0] = lo; - for (var k = 1; k < len; k++) { - for ( - var ncarry = carry >>> 26, - rword = carry & 67108863, - maxJ = Math.min(k, num.length - 1), - j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = (k - j) | 0; - (a = self2.words[i] | 0), - (b = num.words[j] | 0), - (r = a * b + rword), - (ncarry += (r / 67108864) | 0), - (rword = r & 67108863); - } - (out.words[k] = rword | 0), (carry = ncarry | 0); + if ((i >= 0 && k++, (acc = acc.dblp(k)), i < 0)) break; + for (j = 0; j < len; j++) { + var z = tmp[j]; + z !== 0 && + (z > 0 ? (p = wnd[j][(z - 1) >> 1]) : z < 0 && (p = wnd[j][(-z - 1) >> 1].neg()), + p.type === "affine" ? (acc = acc.mixedAdd(p)) : (acc = acc.add(p))); } - return carry !== 0 ? (out.words[k] = carry | 0) : out.length--, out.strip(); } - var comb10MulTo = function (self2, num, out) { - var a = self2.words, - b = num.words, - o = out.words, - c = 0, - lo, - mid, - hi, - a0 = a[0] | 0, - al0 = a0 & 8191, - ah0 = a0 >>> 13, - a1 = a[1] | 0, - al1 = a1 & 8191, - ah1 = a1 >>> 13, - a2 = a[2] | 0, - al2 = a2 & 8191, - ah2 = a2 >>> 13, - a3 = a[3] | 0, - al3 = a3 & 8191, - ah3 = a3 >>> 13, - a4 = a[4] | 0, - al4 = a4 & 8191, - ah4 = a4 >>> 13, - a5 = a[5] | 0, - al5 = a5 & 8191, - ah5 = a5 >>> 13, - a6 = a[6] | 0, - al6 = a6 & 8191, - ah6 = a6 >>> 13, - a7 = a[7] | 0, - al7 = a7 & 8191, - ah7 = a7 >>> 13, - a8 = a[8] | 0, - al8 = a8 & 8191, - ah8 = a8 >>> 13, - a9 = a[9] | 0, - al9 = a9 & 8191, - ah9 = a9 >>> 13, - b0 = b[0] | 0, - bl0 = b0 & 8191, - bh0 = b0 >>> 13, - b1 = b[1] | 0, - bl1 = b1 & 8191, - bh1 = b1 >>> 13, - b2 = b[2] | 0, - bl2 = b2 & 8191, - bh2 = b2 >>> 13, - b3 = b[3] | 0, - bl3 = b3 & 8191, - bh3 = b3 >>> 13, - b4 = b[4] | 0, - bl4 = b4 & 8191, - bh4 = b4 >>> 13, - b5 = b[5] | 0, - bl5 = b5 & 8191, - bh5 = b5 >>> 13, - b6 = b[6] | 0, - bl6 = b6 & 8191, - bh6 = b6 >>> 13, - b7 = b[7] | 0, - bl7 = b7 & 8191, - bh7 = b7 >>> 13, - b8 = b[8] | 0, - bl8 = b8 & 8191, - bh8 = b8 >>> 13, - b9 = b[9] | 0, - bl9 = b9 & 8191, - bh9 = b9 >>> 13; - (out.negative = self2.negative ^ num.negative), - (out.length = 19), - (lo = Math.imul(al0, bl0)), - (mid = Math.imul(al0, bh0)), - (mid = (mid + Math.imul(ah0, bl0)) | 0), - (hi = Math.imul(ah0, bh0)); - var w0 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0), - (w0 &= 67108863), - (lo = Math.imul(al1, bl0)), - (mid = Math.imul(al1, bh0)), - (mid = (mid + Math.imul(ah1, bl0)) | 0), - (hi = Math.imul(ah1, bh0)), - (lo = (lo + Math.imul(al0, bl1)) | 0), - (mid = (mid + Math.imul(al0, bh1)) | 0), - (mid = (mid + Math.imul(ah0, bl1)) | 0), - (hi = (hi + Math.imul(ah0, bh1)) | 0); - var w1 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0), - (w1 &= 67108863), - (lo = Math.imul(al2, bl0)), - (mid = Math.imul(al2, bh0)), - (mid = (mid + Math.imul(ah2, bl0)) | 0), - (hi = Math.imul(ah2, bh0)), - (lo = (lo + Math.imul(al1, bl1)) | 0), - (mid = (mid + Math.imul(al1, bh1)) | 0), - (mid = (mid + Math.imul(ah1, bl1)) | 0), - (hi = (hi + Math.imul(ah1, bh1)) | 0), - (lo = (lo + Math.imul(al0, bl2)) | 0), - (mid = (mid + Math.imul(al0, bh2)) | 0), - (mid = (mid + Math.imul(ah0, bl2)) | 0), - (hi = (hi + Math.imul(ah0, bh2)) | 0); - var w2 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0), - (w2 &= 67108863), - (lo = Math.imul(al3, bl0)), - (mid = Math.imul(al3, bh0)), - (mid = (mid + Math.imul(ah3, bl0)) | 0), - (hi = Math.imul(ah3, bh0)), - (lo = (lo + Math.imul(al2, bl1)) | 0), - (mid = (mid + Math.imul(al2, bh1)) | 0), - (mid = (mid + Math.imul(ah2, bl1)) | 0), - (hi = (hi + Math.imul(ah2, bh1)) | 0), - (lo = (lo + Math.imul(al1, bl2)) | 0), - (mid = (mid + Math.imul(al1, bh2)) | 0), - (mid = (mid + Math.imul(ah1, bl2)) | 0), - (hi = (hi + Math.imul(ah1, bh2)) | 0), - (lo = (lo + Math.imul(al0, bl3)) | 0), - (mid = (mid + Math.imul(al0, bh3)) | 0), - (mid = (mid + Math.imul(ah0, bl3)) | 0), - (hi = (hi + Math.imul(ah0, bh3)) | 0); - var w3 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0), - (w3 &= 67108863), - (lo = Math.imul(al4, bl0)), - (mid = Math.imul(al4, bh0)), - (mid = (mid + Math.imul(ah4, bl0)) | 0), - (hi = Math.imul(ah4, bh0)), - (lo = (lo + Math.imul(al3, bl1)) | 0), - (mid = (mid + Math.imul(al3, bh1)) | 0), - (mid = (mid + Math.imul(ah3, bl1)) | 0), - (hi = (hi + Math.imul(ah3, bh1)) | 0), - (lo = (lo + Math.imul(al2, bl2)) | 0), - (mid = (mid + Math.imul(al2, bh2)) | 0), - (mid = (mid + Math.imul(ah2, bl2)) | 0), - (hi = (hi + Math.imul(ah2, bh2)) | 0), - (lo = (lo + Math.imul(al1, bl3)) | 0), - (mid = (mid + Math.imul(al1, bh3)) | 0), - (mid = (mid + Math.imul(ah1, bl3)) | 0), - (hi = (hi + Math.imul(ah1, bh3)) | 0), - (lo = (lo + Math.imul(al0, bl4)) | 0), - (mid = (mid + Math.imul(al0, bh4)) | 0), - (mid = (mid + Math.imul(ah0, bl4)) | 0), - (hi = (hi + Math.imul(ah0, bh4)) | 0); - var w4 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0), - (w4 &= 67108863), - (lo = Math.imul(al5, bl0)), - (mid = Math.imul(al5, bh0)), - (mid = (mid + Math.imul(ah5, bl0)) | 0), - (hi = Math.imul(ah5, bh0)), - (lo = (lo + Math.imul(al4, bl1)) | 0), - (mid = (mid + Math.imul(al4, bh1)) | 0), - (mid = (mid + Math.imul(ah4, bl1)) | 0), - (hi = (hi + Math.imul(ah4, bh1)) | 0), - (lo = (lo + Math.imul(al3, bl2)) | 0), - (mid = (mid + Math.imul(al3, bh2)) | 0), - (mid = (mid + Math.imul(ah3, bl2)) | 0), - (hi = (hi + Math.imul(ah3, bh2)) | 0), - (lo = (lo + Math.imul(al2, bl3)) | 0), - (mid = (mid + Math.imul(al2, bh3)) | 0), - (mid = (mid + Math.imul(ah2, bl3)) | 0), - (hi = (hi + Math.imul(ah2, bh3)) | 0), - (lo = (lo + Math.imul(al1, bl4)) | 0), - (mid = (mid + Math.imul(al1, bh4)) | 0), - (mid = (mid + Math.imul(ah1, bl4)) | 0), - (hi = (hi + Math.imul(ah1, bh4)) | 0), - (lo = (lo + Math.imul(al0, bl5)) | 0), - (mid = (mid + Math.imul(al0, bh5)) | 0), - (mid = (mid + Math.imul(ah0, bl5)) | 0), - (hi = (hi + Math.imul(ah0, bh5)) | 0); - var w5 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0), - (w5 &= 67108863), - (lo = Math.imul(al6, bl0)), - (mid = Math.imul(al6, bh0)), - (mid = (mid + Math.imul(ah6, bl0)) | 0), - (hi = Math.imul(ah6, bh0)), - (lo = (lo + Math.imul(al5, bl1)) | 0), - (mid = (mid + Math.imul(al5, bh1)) | 0), - (mid = (mid + Math.imul(ah5, bl1)) | 0), - (hi = (hi + Math.imul(ah5, bh1)) | 0), - (lo = (lo + Math.imul(al4, bl2)) | 0), - (mid = (mid + Math.imul(al4, bh2)) | 0), - (mid = (mid + Math.imul(ah4, bl2)) | 0), - (hi = (hi + Math.imul(ah4, bh2)) | 0), - (lo = (lo + Math.imul(al3, bl3)) | 0), - (mid = (mid + Math.imul(al3, bh3)) | 0), - (mid = (mid + Math.imul(ah3, bl3)) | 0), - (hi = (hi + Math.imul(ah3, bh3)) | 0), - (lo = (lo + Math.imul(al2, bl4)) | 0), - (mid = (mid + Math.imul(al2, bh4)) | 0), - (mid = (mid + Math.imul(ah2, bl4)) | 0), - (hi = (hi + Math.imul(ah2, bh4)) | 0), - (lo = (lo + Math.imul(al1, bl5)) | 0), - (mid = (mid + Math.imul(al1, bh5)) | 0), - (mid = (mid + Math.imul(ah1, bl5)) | 0), - (hi = (hi + Math.imul(ah1, bh5)) | 0), - (lo = (lo + Math.imul(al0, bl6)) | 0), - (mid = (mid + Math.imul(al0, bh6)) | 0), - (mid = (mid + Math.imul(ah0, bl6)) | 0), - (hi = (hi + Math.imul(ah0, bh6)) | 0); - var w6 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0), - (w6 &= 67108863), - (lo = Math.imul(al7, bl0)), - (mid = Math.imul(al7, bh0)), - (mid = (mid + Math.imul(ah7, bl0)) | 0), - (hi = Math.imul(ah7, bh0)), - (lo = (lo + Math.imul(al6, bl1)) | 0), - (mid = (mid + Math.imul(al6, bh1)) | 0), - (mid = (mid + Math.imul(ah6, bl1)) | 0), - (hi = (hi + Math.imul(ah6, bh1)) | 0), - (lo = (lo + Math.imul(al5, bl2)) | 0), - (mid = (mid + Math.imul(al5, bh2)) | 0), - (mid = (mid + Math.imul(ah5, bl2)) | 0), - (hi = (hi + Math.imul(ah5, bh2)) | 0), - (lo = (lo + Math.imul(al4, bl3)) | 0), - (mid = (mid + Math.imul(al4, bh3)) | 0), - (mid = (mid + Math.imul(ah4, bl3)) | 0), - (hi = (hi + Math.imul(ah4, bh3)) | 0), - (lo = (lo + Math.imul(al3, bl4)) | 0), - (mid = (mid + Math.imul(al3, bh4)) | 0), - (mid = (mid + Math.imul(ah3, bl4)) | 0), - (hi = (hi + Math.imul(ah3, bh4)) | 0), - (lo = (lo + Math.imul(al2, bl5)) | 0), - (mid = (mid + Math.imul(al2, bh5)) | 0), - (mid = (mid + Math.imul(ah2, bl5)) | 0), - (hi = (hi + Math.imul(ah2, bh5)) | 0), - (lo = (lo + Math.imul(al1, bl6)) | 0), - (mid = (mid + Math.imul(al1, bh6)) | 0), - (mid = (mid + Math.imul(ah1, bl6)) | 0), - (hi = (hi + Math.imul(ah1, bh6)) | 0), - (lo = (lo + Math.imul(al0, bl7)) | 0), - (mid = (mid + Math.imul(al0, bh7)) | 0), - (mid = (mid + Math.imul(ah0, bl7)) | 0), - (hi = (hi + Math.imul(ah0, bh7)) | 0); - var w7 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0), - (w7 &= 67108863), - (lo = Math.imul(al8, bl0)), - (mid = Math.imul(al8, bh0)), - (mid = (mid + Math.imul(ah8, bl0)) | 0), - (hi = Math.imul(ah8, bh0)), - (lo = (lo + Math.imul(al7, bl1)) | 0), - (mid = (mid + Math.imul(al7, bh1)) | 0), - (mid = (mid + Math.imul(ah7, bl1)) | 0), - (hi = (hi + Math.imul(ah7, bh1)) | 0), - (lo = (lo + Math.imul(al6, bl2)) | 0), - (mid = (mid + Math.imul(al6, bh2)) | 0), - (mid = (mid + Math.imul(ah6, bl2)) | 0), - (hi = (hi + Math.imul(ah6, bh2)) | 0), - (lo = (lo + Math.imul(al5, bl3)) | 0), - (mid = (mid + Math.imul(al5, bh3)) | 0), - (mid = (mid + Math.imul(ah5, bl3)) | 0), - (hi = (hi + Math.imul(ah5, bh3)) | 0), - (lo = (lo + Math.imul(al4, bl4)) | 0), - (mid = (mid + Math.imul(al4, bh4)) | 0), - (mid = (mid + Math.imul(ah4, bl4)) | 0), - (hi = (hi + Math.imul(ah4, bh4)) | 0), - (lo = (lo + Math.imul(al3, bl5)) | 0), - (mid = (mid + Math.imul(al3, bh5)) | 0), - (mid = (mid + Math.imul(ah3, bl5)) | 0), - (hi = (hi + Math.imul(ah3, bh5)) | 0), - (lo = (lo + Math.imul(al2, bl6)) | 0), - (mid = (mid + Math.imul(al2, bh6)) | 0), - (mid = (mid + Math.imul(ah2, bl6)) | 0), - (hi = (hi + Math.imul(ah2, bh6)) | 0), - (lo = (lo + Math.imul(al1, bl7)) | 0), - (mid = (mid + Math.imul(al1, bh7)) | 0), - (mid = (mid + Math.imul(ah1, bl7)) | 0), - (hi = (hi + Math.imul(ah1, bh7)) | 0), - (lo = (lo + Math.imul(al0, bl8)) | 0), - (mid = (mid + Math.imul(al0, bh8)) | 0), - (mid = (mid + Math.imul(ah0, bl8)) | 0), - (hi = (hi + Math.imul(ah0, bh8)) | 0); - var w8 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0), - (w8 &= 67108863), - (lo = Math.imul(al9, bl0)), - (mid = Math.imul(al9, bh0)), - (mid = (mid + Math.imul(ah9, bl0)) | 0), - (hi = Math.imul(ah9, bh0)), - (lo = (lo + Math.imul(al8, bl1)) | 0), - (mid = (mid + Math.imul(al8, bh1)) | 0), - (mid = (mid + Math.imul(ah8, bl1)) | 0), - (hi = (hi + Math.imul(ah8, bh1)) | 0), - (lo = (lo + Math.imul(al7, bl2)) | 0), - (mid = (mid + Math.imul(al7, bh2)) | 0), - (mid = (mid + Math.imul(ah7, bl2)) | 0), - (hi = (hi + Math.imul(ah7, bh2)) | 0), - (lo = (lo + Math.imul(al6, bl3)) | 0), - (mid = (mid + Math.imul(al6, bh3)) | 0), - (mid = (mid + Math.imul(ah6, bl3)) | 0), - (hi = (hi + Math.imul(ah6, bh3)) | 0), - (lo = (lo + Math.imul(al5, bl4)) | 0), - (mid = (mid + Math.imul(al5, bh4)) | 0), - (mid = (mid + Math.imul(ah5, bl4)) | 0), - (hi = (hi + Math.imul(ah5, bh4)) | 0), - (lo = (lo + Math.imul(al4, bl5)) | 0), - (mid = (mid + Math.imul(al4, bh5)) | 0), - (mid = (mid + Math.imul(ah4, bl5)) | 0), - (hi = (hi + Math.imul(ah4, bh5)) | 0), - (lo = (lo + Math.imul(al3, bl6)) | 0), - (mid = (mid + Math.imul(al3, bh6)) | 0), - (mid = (mid + Math.imul(ah3, bl6)) | 0), - (hi = (hi + Math.imul(ah3, bh6)) | 0), - (lo = (lo + Math.imul(al2, bl7)) | 0), - (mid = (mid + Math.imul(al2, bh7)) | 0), - (mid = (mid + Math.imul(ah2, bl7)) | 0), - (hi = (hi + Math.imul(ah2, bh7)) | 0), - (lo = (lo + Math.imul(al1, bl8)) | 0), - (mid = (mid + Math.imul(al1, bh8)) | 0), - (mid = (mid + Math.imul(ah1, bl8)) | 0), - (hi = (hi + Math.imul(ah1, bh8)) | 0), - (lo = (lo + Math.imul(al0, bl9)) | 0), - (mid = (mid + Math.imul(al0, bh9)) | 0), - (mid = (mid + Math.imul(ah0, bl9)) | 0), - (hi = (hi + Math.imul(ah0, bh9)) | 0); - var w9 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0), - (w9 &= 67108863), - (lo = Math.imul(al9, bl1)), - (mid = Math.imul(al9, bh1)), - (mid = (mid + Math.imul(ah9, bl1)) | 0), - (hi = Math.imul(ah9, bh1)), - (lo = (lo + Math.imul(al8, bl2)) | 0), - (mid = (mid + Math.imul(al8, bh2)) | 0), - (mid = (mid + Math.imul(ah8, bl2)) | 0), - (hi = (hi + Math.imul(ah8, bh2)) | 0), - (lo = (lo + Math.imul(al7, bl3)) | 0), - (mid = (mid + Math.imul(al7, bh3)) | 0), - (mid = (mid + Math.imul(ah7, bl3)) | 0), - (hi = (hi + Math.imul(ah7, bh3)) | 0), - (lo = (lo + Math.imul(al6, bl4)) | 0), - (mid = (mid + Math.imul(al6, bh4)) | 0), - (mid = (mid + Math.imul(ah6, bl4)) | 0), - (hi = (hi + Math.imul(ah6, bh4)) | 0), - (lo = (lo + Math.imul(al5, bl5)) | 0), - (mid = (mid + Math.imul(al5, bh5)) | 0), - (mid = (mid + Math.imul(ah5, bl5)) | 0), - (hi = (hi + Math.imul(ah5, bh5)) | 0), - (lo = (lo + Math.imul(al4, bl6)) | 0), - (mid = (mid + Math.imul(al4, bh6)) | 0), - (mid = (mid + Math.imul(ah4, bl6)) | 0), - (hi = (hi + Math.imul(ah4, bh6)) | 0), - (lo = (lo + Math.imul(al3, bl7)) | 0), - (mid = (mid + Math.imul(al3, bh7)) | 0), - (mid = (mid + Math.imul(ah3, bl7)) | 0), - (hi = (hi + Math.imul(ah3, bh7)) | 0), - (lo = (lo + Math.imul(al2, bl8)) | 0), - (mid = (mid + Math.imul(al2, bh8)) | 0), - (mid = (mid + Math.imul(ah2, bl8)) | 0), - (hi = (hi + Math.imul(ah2, bh8)) | 0), - (lo = (lo + Math.imul(al1, bl9)) | 0), - (mid = (mid + Math.imul(al1, bh9)) | 0), - (mid = (mid + Math.imul(ah1, bl9)) | 0), - (hi = (hi + Math.imul(ah1, bh9)) | 0); - var w10 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0), - (w10 &= 67108863), - (lo = Math.imul(al9, bl2)), - (mid = Math.imul(al9, bh2)), - (mid = (mid + Math.imul(ah9, bl2)) | 0), - (hi = Math.imul(ah9, bh2)), - (lo = (lo + Math.imul(al8, bl3)) | 0), - (mid = (mid + Math.imul(al8, bh3)) | 0), - (mid = (mid + Math.imul(ah8, bl3)) | 0), - (hi = (hi + Math.imul(ah8, bh3)) | 0), - (lo = (lo + Math.imul(al7, bl4)) | 0), - (mid = (mid + Math.imul(al7, bh4)) | 0), - (mid = (mid + Math.imul(ah7, bl4)) | 0), - (hi = (hi + Math.imul(ah7, bh4)) | 0), - (lo = (lo + Math.imul(al6, bl5)) | 0), - (mid = (mid + Math.imul(al6, bh5)) | 0), - (mid = (mid + Math.imul(ah6, bl5)) | 0), - (hi = (hi + Math.imul(ah6, bh5)) | 0), - (lo = (lo + Math.imul(al5, bl6)) | 0), - (mid = (mid + Math.imul(al5, bh6)) | 0), - (mid = (mid + Math.imul(ah5, bl6)) | 0), - (hi = (hi + Math.imul(ah5, bh6)) | 0), - (lo = (lo + Math.imul(al4, bl7)) | 0), - (mid = (mid + Math.imul(al4, bh7)) | 0), - (mid = (mid + Math.imul(ah4, bl7)) | 0), - (hi = (hi + Math.imul(ah4, bh7)) | 0), - (lo = (lo + Math.imul(al3, bl8)) | 0), - (mid = (mid + Math.imul(al3, bh8)) | 0), - (mid = (mid + Math.imul(ah3, bl8)) | 0), - (hi = (hi + Math.imul(ah3, bh8)) | 0), - (lo = (lo + Math.imul(al2, bl9)) | 0), - (mid = (mid + Math.imul(al2, bh9)) | 0), - (mid = (mid + Math.imul(ah2, bl9)) | 0), - (hi = (hi + Math.imul(ah2, bh9)) | 0); - var w11 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0), - (w11 &= 67108863), - (lo = Math.imul(al9, bl3)), - (mid = Math.imul(al9, bh3)), - (mid = (mid + Math.imul(ah9, bl3)) | 0), - (hi = Math.imul(ah9, bh3)), - (lo = (lo + Math.imul(al8, bl4)) | 0), - (mid = (mid + Math.imul(al8, bh4)) | 0), - (mid = (mid + Math.imul(ah8, bl4)) | 0), - (hi = (hi + Math.imul(ah8, bh4)) | 0), - (lo = (lo + Math.imul(al7, bl5)) | 0), - (mid = (mid + Math.imul(al7, bh5)) | 0), - (mid = (mid + Math.imul(ah7, bl5)) | 0), - (hi = (hi + Math.imul(ah7, bh5)) | 0), - (lo = (lo + Math.imul(al6, bl6)) | 0), - (mid = (mid + Math.imul(al6, bh6)) | 0), - (mid = (mid + Math.imul(ah6, bl6)) | 0), - (hi = (hi + Math.imul(ah6, bh6)) | 0), - (lo = (lo + Math.imul(al5, bl7)) | 0), - (mid = (mid + Math.imul(al5, bh7)) | 0), - (mid = (mid + Math.imul(ah5, bl7)) | 0), - (hi = (hi + Math.imul(ah5, bh7)) | 0), - (lo = (lo + Math.imul(al4, bl8)) | 0), - (mid = (mid + Math.imul(al4, bh8)) | 0), - (mid = (mid + Math.imul(ah4, bl8)) | 0), - (hi = (hi + Math.imul(ah4, bh8)) | 0), - (lo = (lo + Math.imul(al3, bl9)) | 0), - (mid = (mid + Math.imul(al3, bh9)) | 0), - (mid = (mid + Math.imul(ah3, bl9)) | 0), - (hi = (hi + Math.imul(ah3, bh9)) | 0); - var w12 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0), - (w12 &= 67108863), - (lo = Math.imul(al9, bl4)), - (mid = Math.imul(al9, bh4)), - (mid = (mid + Math.imul(ah9, bl4)) | 0), - (hi = Math.imul(ah9, bh4)), - (lo = (lo + Math.imul(al8, bl5)) | 0), - (mid = (mid + Math.imul(al8, bh5)) | 0), - (mid = (mid + Math.imul(ah8, bl5)) | 0), - (hi = (hi + Math.imul(ah8, bh5)) | 0), - (lo = (lo + Math.imul(al7, bl6)) | 0), - (mid = (mid + Math.imul(al7, bh6)) | 0), - (mid = (mid + Math.imul(ah7, bl6)) | 0), - (hi = (hi + Math.imul(ah7, bh6)) | 0), - (lo = (lo + Math.imul(al6, bl7)) | 0), - (mid = (mid + Math.imul(al6, bh7)) | 0), - (mid = (mid + Math.imul(ah6, bl7)) | 0), - (hi = (hi + Math.imul(ah6, bh7)) | 0), - (lo = (lo + Math.imul(al5, bl8)) | 0), - (mid = (mid + Math.imul(al5, bh8)) | 0), - (mid = (mid + Math.imul(ah5, bl8)) | 0), - (hi = (hi + Math.imul(ah5, bh8)) | 0), - (lo = (lo + Math.imul(al4, bl9)) | 0), - (mid = (mid + Math.imul(al4, bh9)) | 0), - (mid = (mid + Math.imul(ah4, bl9)) | 0), - (hi = (hi + Math.imul(ah4, bh9)) | 0); - var w13 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0), - (w13 &= 67108863), - (lo = Math.imul(al9, bl5)), - (mid = Math.imul(al9, bh5)), - (mid = (mid + Math.imul(ah9, bl5)) | 0), - (hi = Math.imul(ah9, bh5)), - (lo = (lo + Math.imul(al8, bl6)) | 0), - (mid = (mid + Math.imul(al8, bh6)) | 0), - (mid = (mid + Math.imul(ah8, bl6)) | 0), - (hi = (hi + Math.imul(ah8, bh6)) | 0), - (lo = (lo + Math.imul(al7, bl7)) | 0), - (mid = (mid + Math.imul(al7, bh7)) | 0), - (mid = (mid + Math.imul(ah7, bl7)) | 0), - (hi = (hi + Math.imul(ah7, bh7)) | 0), - (lo = (lo + Math.imul(al6, bl8)) | 0), - (mid = (mid + Math.imul(al6, bh8)) | 0), - (mid = (mid + Math.imul(ah6, bl8)) | 0), - (hi = (hi + Math.imul(ah6, bh8)) | 0), - (lo = (lo + Math.imul(al5, bl9)) | 0), - (mid = (mid + Math.imul(al5, bh9)) | 0), - (mid = (mid + Math.imul(ah5, bl9)) | 0), - (hi = (hi + Math.imul(ah5, bh9)) | 0); - var w14 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0), - (w14 &= 67108863), - (lo = Math.imul(al9, bl6)), - (mid = Math.imul(al9, bh6)), - (mid = (mid + Math.imul(ah9, bl6)) | 0), - (hi = Math.imul(ah9, bh6)), - (lo = (lo + Math.imul(al8, bl7)) | 0), - (mid = (mid + Math.imul(al8, bh7)) | 0), - (mid = (mid + Math.imul(ah8, bl7)) | 0), - (hi = (hi + Math.imul(ah8, bh7)) | 0), - (lo = (lo + Math.imul(al7, bl8)) | 0), - (mid = (mid + Math.imul(al7, bh8)) | 0), - (mid = (mid + Math.imul(ah7, bl8)) | 0), - (hi = (hi + Math.imul(ah7, bh8)) | 0), - (lo = (lo + Math.imul(al6, bl9)) | 0), - (mid = (mid + Math.imul(al6, bh9)) | 0), - (mid = (mid + Math.imul(ah6, bl9)) | 0), - (hi = (hi + Math.imul(ah6, bh9)) | 0); - var w15 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0), - (w15 &= 67108863), - (lo = Math.imul(al9, bl7)), - (mid = Math.imul(al9, bh7)), - (mid = (mid + Math.imul(ah9, bl7)) | 0), - (hi = Math.imul(ah9, bh7)), - (lo = (lo + Math.imul(al8, bl8)) | 0), - (mid = (mid + Math.imul(al8, bh8)) | 0), - (mid = (mid + Math.imul(ah8, bl8)) | 0), - (hi = (hi + Math.imul(ah8, bh8)) | 0), - (lo = (lo + Math.imul(al7, bl9)) | 0), - (mid = (mid + Math.imul(al7, bh9)) | 0), - (mid = (mid + Math.imul(ah7, bl9)) | 0), - (hi = (hi + Math.imul(ah7, bh9)) | 0); - var w16 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0), - (w16 &= 67108863), - (lo = Math.imul(al9, bl8)), - (mid = Math.imul(al9, bh8)), - (mid = (mid + Math.imul(ah9, bl8)) | 0), - (hi = Math.imul(ah9, bh8)), - (lo = (lo + Math.imul(al8, bl9)) | 0), - (mid = (mid + Math.imul(al8, bh9)) | 0), - (mid = (mid + Math.imul(ah8, bl9)) | 0), - (hi = (hi + Math.imul(ah8, bh9)) | 0); - var w17 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0), - (w17 &= 67108863), - (lo = Math.imul(al9, bl9)), - (mid = Math.imul(al9, bh9)), - (mid = (mid + Math.imul(ah9, bl9)) | 0), - (hi = Math.imul(ah9, bh9)); - var w18 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - return ( - (c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0), - (w18 &= 67108863), - (o[0] = w0), - (o[1] = w1), - (o[2] = w2), - (o[3] = w3), - (o[4] = w4), - (o[5] = w5), - (o[6] = w6), - (o[7] = w7), - (o[8] = w8), - (o[9] = w9), - (o[10] = w10), - (o[11] = w11), - (o[12] = w12), - (o[13] = w13), - (o[14] = w14), - (o[15] = w15), - (o[16] = w16), - (o[17] = w17), - (o[18] = w18), - c !== 0 && ((o[19] = c), out.length++), - out - ); - }; - Math.imul || (comb10MulTo = smallMulTo); - function bigMulTo(self2, num, out) { - (out.negative = num.negative ^ self2.negative), (out.length = self2.length + num.length); - for (var carry = 0, hncarry = 0, k = 0; k < out.length - 1; k++) { - var ncarry = hncarry; - hncarry = 0; - for ( - var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1), j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = k - j, - a = self2.words[i] | 0, - b = num.words[j] | 0, - r = a * b, - lo = r & 67108863; - (ncarry = (ncarry + ((r / 67108864) | 0)) | 0), - (lo = (lo + rword) | 0), - (rword = lo & 67108863), - (ncarry = (ncarry + (lo >>> 26)) | 0), - (hncarry += ncarry >>> 26), - (ncarry &= 67108863); - } - (out.words[k] = rword), (carry = ncarry), (ncarry = hncarry); - } - return carry !== 0 ? (out.words[k] = carry) : out.length--, out.strip(); - } - function jumboMulTo(self2, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self2, num, out); - } - BN.prototype.mulTo = function (num, out) { - var res, - len = this.length + num.length; - return ( - this.length === 10 && num.length === 10 - ? (res = comb10MulTo(this, num, out)) - : len < 63 - ? (res = smallMulTo(this, num, out)) - : len < 1024 - ? (res = bigMulTo(this, num, out)) - : (res = jumboMulTo(this, num, out)), - res - ); - }; - function FFTM(x, y) { - (this.x = x), (this.y = y); - } - (FFTM.prototype.makeRBT = function (N) { - for (var t = new Array(N), l = BN.prototype._countBits(N) - 1, i = 0; i < N; i++) t[i] = this.revBin(i, l, N); - return t; - }), - (FFTM.prototype.revBin = function (x, l, N) { - if (x === 0 || x === N - 1) return x; - for (var rb = 0, i = 0; i < l; i++) (rb |= (x & 1) << (l - i - 1)), (x >>= 1); - return rb; - }), - (FFTM.prototype.permute = function (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) (rtws[i] = rws[rbt[i]]), (itws[i] = iws[rbt[i]]); - }), - (FFTM.prototype.transform = function (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - for (var s = 1; s < N; s <<= 1) - for ( - var l = s << 1, rtwdf = Math.cos((2 * Math.PI) / l), itwdf = Math.sin((2 * Math.PI) / l), p = 0; - p < N; - p += l - ) - for (var rtwdf_ = rtwdf, itwdf_ = itwdf, j = 0; j < s; j++) { - var re = rtws[p + j], - ie = itws[p + j], - ro = rtws[p + j + s], - io = itws[p + j + s], - rx = rtwdf_ * ro - itwdf_ * io; - (io = rtwdf_ * io + itwdf_ * ro), - (ro = rx), - (rtws[p + j] = re + ro), - (itws[p + j] = ie + io), - (rtws[p + j + s] = re - ro), - (itws[p + j + s] = ie - io), - j !== l && - ((rx = rtwdf * rtwdf_ - itwdf * itwdf_), (itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_), (rtwdf_ = rx)); - } - }), - (FFTM.prototype.guessLen13b = function (n, m) { - var N = Math.max(m, n) | 1, - odd = N & 1, - i = 0; - for (N = (N / 2) | 0; N; N = N >>> 1) i++; - return 1 << (i + 1 + odd); - }), - (FFTM.prototype.conjugate = function (rws, iws, N) { - if (!(N <= 1)) - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - (rws[i] = rws[N - i - 1]), - (rws[N - i - 1] = t), - (t = iws[i]), - (iws[i] = -iws[N - i - 1]), - (iws[N - i - 1] = -t); - } - }), - (FFTM.prototype.normalize13b = function (ws, N) { - for (var carry = 0, i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 8192 + Math.round(ws[2 * i] / N) + carry; - (ws[i] = w & 67108863), w < 67108864 ? (carry = 0) : (carry = (w / 67108864) | 0); - } - return ws; - }), - (FFTM.prototype.convert13b = function (ws, len, rws, N) { - for (var carry = 0, i = 0; i < len; i++) - (carry = carry + (ws[i] | 0)), - (rws[2 * i] = carry & 8191), - (carry = carry >>> 13), - (rws[2 * i + 1] = carry & 8191), - (carry = carry >>> 13); - for (i = 2 * len; i < N; ++i) rws[i] = 0; - assert(carry === 0), assert((carry & -8192) === 0); - }), - (FFTM.prototype.stub = function (N) { - for (var ph = new Array(N), i = 0; i < N; i++) ph[i] = 0; - return ph; - }), - (FFTM.prototype.mulp = function (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length), - rbt = this.makeRBT(N), - _ = this.stub(N), - rws = new Array(N), - rwst = new Array(N), - iwst = new Array(N), - nrws = new Array(N), - nrwst = new Array(N), - niwst = new Array(N), - rmws = out.words; - (rmws.length = N), - this.convert13b(x.words, x.length, rws, N), - this.convert13b(y.words, y.length, nrws, N), - this.transform(rws, _, rwst, iwst, N, rbt), - this.transform(nrws, _, nrwst, niwst, N, rbt); - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - (iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]), (rwst[i] = rx); - } - return ( - this.conjugate(rwst, iwst, N), - this.transform(rwst, iwst, rmws, _, N, rbt), - this.conjugate(rmws, _, N), - this.normalize13b(rmws, N), - (out.negative = x.negative ^ y.negative), - (out.length = x.length + y.length), - out.strip() - ); - }), - (BN.prototype.mul = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), this.mulTo(num, out); - }), - (BN.prototype.mulf = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), jumboMulTo(this, num, out); - }), - (BN.prototype.imul = function (num) { - return this.clone().mulTo(num, this); - }), - (BN.prototype.imuln = function (num) { - assert(typeof num == "number"), assert(num < 67108864); - for (var carry = 0, i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num, - lo = (w & 67108863) + (carry & 67108863); - (carry >>= 26), (carry += (w / 67108864) | 0), (carry += lo >>> 26), (this.words[i] = lo & 67108863); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.muln = function (num) { - return this.clone().imuln(num); - }), - (BN.prototype.sqr = function () { - return this.mul(this); - }), - (BN.prototype.isqr = function () { - return this.imul(this.clone()); - }), - (BN.prototype.pow = function (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - for (var res = this, i = 0; i < w.length && w[i] === 0; i++, res = res.sqr()); - if (++i < w.length) for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) w[i] !== 0 && (res = res.mul(q)); - return res; - }), - (BN.prototype.iushln = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26, - carryMask = (67108863 >>> (26 - r)) << (26 - r), - i; - if (r !== 0) { - var carry = 0; - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask, - c = ((this.words[i] | 0) - newCarry) << r; - (this.words[i] = c | carry), (carry = newCarry >>> (26 - r)); - } - carry && ((this.words[i] = carry), this.length++); - } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) this.words[i + s] = this.words[i]; - for (i = 0; i < s; i++) this.words[i] = 0; - this.length += s; - } - return this.strip(); - }), - (BN.prototype.ishln = function (bits) { - return assert(this.negative === 0), this.iushln(bits); - }), - (BN.prototype.iushrn = function (bits, hint, extended) { - assert(typeof bits == "number" && bits >= 0); - var h; - hint ? (h = (hint - (hint % 26)) / 26) : (h = 0); - var r = bits % 26, - s = Math.min((bits - r) / 26, this.length), - mask = 67108863 ^ ((67108863 >>> r) << r), - maskedWords = extended; - if (((h -= s), (h = Math.max(0, h)), maskedWords)) { - for (var i = 0; i < s; i++) maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - if (s !== 0) - if (this.length > s) for (this.length -= s, i = 0; i < this.length; i++) this.words[i] = this.words[i + s]; - else (this.words[0] = 0), (this.length = 1); - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - (this.words[i] = (carry << (26 - r)) | (word >>> r)), (carry = word & mask); - } - return ( - maskedWords && carry !== 0 && (maskedWords.words[maskedWords.length++] = carry), - this.length === 0 && ((this.words[0] = 0), (this.length = 1)), - this.strip() - ); - }), - (BN.prototype.ishrn = function (bits, hint, extended) { - return assert(this.negative === 0), this.iushrn(bits, hint, extended); - }), - (BN.prototype.shln = function (bits) { - return this.clone().ishln(bits); - }), - (BN.prototype.ushln = function (bits) { - return this.clone().iushln(bits); - }), - (BN.prototype.shrn = function (bits) { - return this.clone().ishrn(bits); - }), - (BN.prototype.ushrn = function (bits) { - return this.clone().iushrn(bits); - }), - (BN.prototype.testn = function (bit) { - assert(typeof bit == "number" && bit >= 0); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return !1; - var w = this.words[s]; - return !!(w & q); - }), - (BN.prototype.imaskn = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26; - if ((assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)) return this; - if ((r !== 0 && s++, (this.length = Math.min(s, this.length)), r !== 0)) { - var mask = 67108863 ^ ((67108863 >>> r) << r); - this.words[this.length - 1] &= mask; - } - return this.strip(); - }), - (BN.prototype.maskn = function (bits) { - return this.clone().imaskn(bits); - }), - (BN.prototype.iaddn = function (num) { - return ( - assert(typeof num == "number"), - assert(num < 67108864), - num < 0 - ? this.isubn(-num) - : this.negative !== 0 - ? this.length === 1 && (this.words[0] | 0) < num - ? ((this.words[0] = num - (this.words[0] | 0)), (this.negative = 0), this) - : ((this.negative = 0), this.isubn(num), (this.negative = 1), this) - : this._iaddn(num) - ); - }), - (BN.prototype._iaddn = function (num) { - this.words[0] += num; - for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) - (this.words[i] -= 67108864), i === this.length - 1 ? (this.words[i + 1] = 1) : this.words[i + 1]++; - return (this.length = Math.max(this.length, i + 1)), this; - }), - (BN.prototype.isubn = function (num) { - if ((assert(typeof num == "number"), assert(num < 67108864), num < 0)) return this.iaddn(-num); - if (this.negative !== 0) return (this.negative = 0), this.iaddn(num), (this.negative = 1), this; - if (((this.words[0] -= num), this.length === 1 && this.words[0] < 0)) - (this.words[0] = -this.words[0]), (this.negative = 1); - else - for (var i = 0; i < this.length && this.words[i] < 0; i++) - (this.words[i] += 67108864), (this.words[i + 1] -= 1); - return this.strip(); - }), - (BN.prototype.addn = function (num) { - return this.clone().iaddn(num); - }), - (BN.prototype.subn = function (num) { - return this.clone().isubn(num); - }), - (BN.prototype.iabs = function () { - return (this.negative = 0), this; - }), - (BN.prototype.abs = function () { - return this.clone().iabs(); - }), - (BN.prototype._ishlnsubmul = function (num, mul, shift) { - var len = num.length + shift, - i; - this._expand(len); - var w, - carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - (w -= right & 67108863), - (carry = (w >> 26) - ((right / 67108864) | 0)), - (this.words[i + shift] = w & 67108863); - } - for (; i < this.length - shift; i++) - (w = (this.words[i + shift] | 0) + carry), (carry = w >> 26), (this.words[i + shift] = w & 67108863); - if (carry === 0) return this.strip(); - for (assert(carry === -1), carry = 0, i = 0; i < this.length; i++) - (w = -(this.words[i] | 0) + carry), (carry = w >> 26), (this.words[i] = w & 67108863); - return (this.negative = 1), this.strip(); - }), - (BN.prototype._wordDiv = function (num, mode) { - var shift = this.length - num.length, - a = this.clone(), - b = num, - bhi = b.words[b.length - 1] | 0, - bhiBits = this._countBits(bhi); - (shift = 26 - bhiBits), - shift !== 0 && ((b = b.ushln(shift)), a.iushln(shift), (bhi = b.words[b.length - 1] | 0)); - var m = a.length - b.length, - q; - if (mode !== "mod") { - (q = new BN(null)), (q.length = m + 1), (q.words = new Array(q.length)); - for (var i = 0; i < q.length; i++) q.words[i] = 0; - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - diff.negative === 0 && ((a = diff), q && (q.words[m] = 1)); - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); - for (qj = Math.min((qj / bhi) | 0, 67108863), a._ishlnsubmul(b, qj, j); a.negative !== 0; ) - qj--, (a.negative = 0), a._ishlnsubmul(b, 1, j), a.isZero() || (a.negative ^= 1); - q && (q.words[j] = qj); - } - return ( - q && q.strip(), - a.strip(), - mode !== "div" && shift !== 0 && a.iushrn(shift), - { - div: q || null, - mod: a, - } - ); - }), - (BN.prototype.divmod = function (num, mode, positive) { - if ((assert(!num.isZero()), this.isZero())) - return { - div: new BN(0), - mod: new BN(0), - }; - var div, mod, res; - return this.negative !== 0 && num.negative === 0 - ? ((res = this.neg().divmod(num, mode)), - mode !== "mod" && (div = res.div.neg()), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.iadd(num)), - { - div, - mod, - }) - : this.negative === 0 && num.negative !== 0 - ? ((res = this.divmod(num.neg(), mode)), - mode !== "mod" && (div = res.div.neg()), - { - div, - mod: res.mod, - }) - : (this.negative & num.negative) !== 0 - ? ((res = this.neg().divmod(num.neg(), mode)), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.isub(num)), - { - div: res.div, - mod, - }) - : num.length > this.length || this.cmp(num) < 0 - ? { - div: new BN(0), - mod: this, - } - : num.length === 1 - ? mode === "div" - ? { - div: this.divn(num.words[0]), - mod: null, - } - : mode === "mod" - ? { - div: null, - mod: new BN(this.modn(num.words[0])), - } - : { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])), - } - : this._wordDiv(num, mode); - }), - (BN.prototype.div = function (num) { - return this.divmod(num, "div", !1).div; - }), - (BN.prototype.mod = function (num) { - return this.divmod(num, "mod", !1).mod; - }), - (BN.prototype.umod = function (num) { - return this.divmod(num, "mod", !0).mod; - }), - (BN.prototype.divRound = function (num) { - var dm = this.divmod(num); - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, - half = num.ushrn(1), - r2 = num.andln(1), - cmp = mod.cmp(half); - return cmp < 0 || (r2 === 1 && cmp === 0) - ? dm.div - : dm.div.negative !== 0 - ? dm.div.isubn(1) - : dm.div.iaddn(1); - }), - (BN.prototype.modn = function (num) { - assert(num <= 67108863); - for (var p = (1 << 26) % num, acc = 0, i = this.length - 1; i >= 0; i--) - acc = (p * acc + (this.words[i] | 0)) % num; - return acc; - }), - (BN.prototype.idivn = function (num) { - assert(num <= 67108863); - for (var carry = 0, i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 67108864; - (this.words[i] = (w / num) | 0), (carry = w % num); - } - return this.strip(); - }), - (BN.prototype.divn = function (num) { - return this.clone().idivn(num); - }), - (BN.prototype.egcd = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var x = this, - y = p.clone(); - x.negative !== 0 ? (x = x.umod(p)) : (x = x.clone()); - for (var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0; x.isEven() && y.isEven(); ) - x.iushrn(1), y.iushrn(1), ++g; - for (var yp = y.clone(), xp = x.clone(); !x.isZero(); ) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) - for (x.iushrn(i); i-- > 0; ) - (A.isOdd() || B.isOdd()) && (A.iadd(yp), B.isub(xp)), A.iushrn(1), B.iushrn(1); - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) - for (y.iushrn(j); j-- > 0; ) - (C.isOdd() || D.isOdd()) && (C.iadd(yp), D.isub(xp)), C.iushrn(1), D.iushrn(1); - x.cmp(y) >= 0 ? (x.isub(y), A.isub(C), B.isub(D)) : (y.isub(x), C.isub(A), D.isub(B)); - } - return { - a: C, - b: D, - gcd: y.iushln(g), - }; - }), - (BN.prototype._invmp = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var a = this, - b = p.clone(); - a.negative !== 0 ? (a = a.umod(p)) : (a = a.clone()); - for (var x1 = new BN(1), x2 = new BN(0), delta = b.clone(); a.cmpn(1) > 0 && b.cmpn(1) > 0; ) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) for (a.iushrn(i); i-- > 0; ) x1.isOdd() && x1.iadd(delta), x1.iushrn(1); - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) for (b.iushrn(j); j-- > 0; ) x2.isOdd() && x2.iadd(delta), x2.iushrn(1); - a.cmp(b) >= 0 ? (a.isub(b), x1.isub(x2)) : (b.isub(a), x2.isub(x1)); - } - var res; - return a.cmpn(1) === 0 ? (res = x1) : (res = x2), res.cmpn(0) < 0 && res.iadd(p), res; - }), - (BN.prototype.gcd = function (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(), - b = num.clone(); - (a.negative = 0), (b.negative = 0); - for (var shift = 0; a.isEven() && b.isEven(); shift++) a.iushrn(1), b.iushrn(1); - do { - for (; a.isEven(); ) a.iushrn(1); - for (; b.isEven(); ) b.iushrn(1); - var r = a.cmp(b); - if (r < 0) { - var t = a; - (a = b), (b = t); - } else if (r === 0 || b.cmpn(1) === 0) break; - a.isub(b); - } while (!0); - return b.iushln(shift); - }), - (BN.prototype.invm = function (num) { - return this.egcd(num).a.umod(num); - }), - (BN.prototype.isEven = function () { - return (this.words[0] & 1) === 0; - }), - (BN.prototype.isOdd = function () { - return (this.words[0] & 1) === 1; - }), - (BN.prototype.andln = function (num) { - return this.words[0] & num; - }), - (BN.prototype.bincn = function (bit) { - assert(typeof bit == "number"); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return this._expand(s + 1), (this.words[s] |= q), this; - for (var carry = q, i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - (w += carry), (carry = w >>> 26), (w &= 67108863), (this.words[i] = w); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.isZero = function () { - return this.length === 1 && this.words[0] === 0; - }), - (BN.prototype.cmpn = function (num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - this.strip(); - var res; - if (this.length > 1) res = 1; - else { - negative && (num = -num), assert(num <= 67108863, "Number is too big"); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.cmp = function (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.ucmp = function (num) { - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - for (var res = 0, i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0, - b = num.words[i] | 0; - if (a !== b) { - a < b ? (res = -1) : a > b && (res = 1); - break; - } - } - return res; - }), - (BN.prototype.gtn = function (num) { - return this.cmpn(num) === 1; - }), - (BN.prototype.gt = function (num) { - return this.cmp(num) === 1; - }), - (BN.prototype.gten = function (num) { - return this.cmpn(num) >= 0; - }), - (BN.prototype.gte = function (num) { - return this.cmp(num) >= 0; - }), - (BN.prototype.ltn = function (num) { - return this.cmpn(num) === -1; - }), - (BN.prototype.lt = function (num) { - return this.cmp(num) === -1; - }), - (BN.prototype.lten = function (num) { - return this.cmpn(num) <= 0; - }), - (BN.prototype.lte = function (num) { - return this.cmp(num) <= 0; - }), - (BN.prototype.eqn = function (num) { - return this.cmpn(num) === 0; - }), - (BN.prototype.eq = function (num) { - return this.cmp(num) === 0; - }), - (BN.red = function (num) { - return new Red(num); - }), - (BN.prototype.toRed = function (ctx) { - return ( - assert(!this.red, "Already a number in reduction context"), - assert(this.negative === 0, "red works only with positives"), - ctx.convertTo(this)._forceRed(ctx) - ); - }), - (BN.prototype.fromRed = function () { - return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }), - (BN.prototype._forceRed = function (ctx) { - return (this.red = ctx), this; - }), - (BN.prototype.forceRed = function (ctx) { - return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx); - }), - (BN.prototype.redAdd = function (num) { - return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num); - }), - (BN.prototype.redIAdd = function (num) { - return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num); - }), - (BN.prototype.redSub = function (num) { - return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num); - }), - (BN.prototype.redISub = function (num) { - return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num); - }), - (BN.prototype.redShl = function (num) { - return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num); - }), - (BN.prototype.redMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.mul(this, num) - ); - }), - (BN.prototype.redIMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.imul(this, num) - ); - }), - (BN.prototype.redSqr = function () { - return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }), - (BN.prototype.redISqr = function () { - return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }), - (BN.prototype.redSqrt = function () { - return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }), - (BN.prototype.redInvm = function () { - return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); - }), - (BN.prototype.redNeg = function () { - return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); - }), - (BN.prototype.redPow = function (num) { - return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num); - }); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null, - }; - function MPrime(name, p) { - (this.name = name), - (this.p = new BN(p, 16)), - (this.n = this.p.bitLength()), - (this.k = new BN(1).iushln(this.n).isub(this.p)), - (this.tmp = this._tmp()); - } - (MPrime.prototype._tmp = function () { - var tmp = new BN(null); - return (tmp.words = new Array(Math.ceil(this.n / 13))), tmp; - }), - (MPrime.prototype.ireduce = function (num) { - var r = num, - rlen; - do this.split(r, this.tmp), (r = this.imulK(r)), (r = r.iadd(this.tmp)), (rlen = r.bitLength()); - while (rlen > this.n); - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - return ( - cmp === 0 - ? ((r.words[0] = 0), (r.length = 1)) - : cmp > 0 - ? r.isub(this.p) - : r.strip !== void 0 - ? r.strip() - : r._strip(), - r - ); - }), - (MPrime.prototype.split = function (input, out) { - input.iushrn(this.n, 0, out); - }), - (MPrime.prototype.imulK = function (num) { - return num.imul(this.k); - }); - function K256() { - MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - inherits(K256, MPrime), - (K256.prototype.split = function (input, output) { - for (var mask = 4194303, outLen = Math.min(input.length, 9), i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - if (((output.length = outLen), input.length <= 9)) { - (input.words[0] = 0), (input.length = 1); - return; - } - var prev = input.words[9]; - for (output.words[output.length++] = prev & mask, i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - (input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22)), (prev = next); - } - (prev >>>= 22), - (input.words[i - 10] = prev), - prev === 0 && input.length > 10 ? (input.length -= 10) : (input.length -= 9); - }), - (K256.prototype.imulK = function (num) { - (num.words[num.length] = 0), (num.words[num.length + 1] = 0), (num.length += 2); - for (var lo = 0, i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - (lo += w * 977), (num.words[i] = lo & 67108863), (lo = w * 64 + ((lo / 67108864) | 0)); - } - return ( - num.words[num.length - 1] === 0 && (num.length--, num.words[num.length - 1] === 0 && num.length--), num - ); - }); - function P224() { - MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - inherits(P224, MPrime); - function P192() { - MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - inherits(P192, MPrime); - function P25519() { - MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - inherits(P25519, MPrime), - (P25519.prototype.imulK = function (num) { - for (var carry = 0, i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 19 + carry, - lo = hi & 67108863; - (hi >>>= 26), (num.words[i] = lo), (carry = hi); - } - return carry !== 0 && (num.words[num.length++] = carry), num; - }), - (BN._prime = function (name) { - if (primes[name]) return primes[name]; - var prime2; - if (name === "k256") prime2 = new K256(); - else if (name === "p224") prime2 = new P224(); - else if (name === "p192") prime2 = new P192(); - else if (name === "p25519") prime2 = new P25519(); - else throw new Error("Unknown prime " + name); - return (primes[name] = prime2), prime2; - }); - function Red(m) { - if (typeof m == "string") { - var prime = BN._prime(m); - (this.m = prime.p), (this.prime = prime); - } else assert(m.gtn(1), "modulus must be greater than 1"), (this.m = m), (this.prime = null); - } - (Red.prototype._verify1 = function (a) { - assert(a.negative === 0, "red works only with positives"), assert(a.red, "red works only with red numbers"); - }), - (Red.prototype._verify2 = function (a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"), - assert(a.red && a.red === b.red, "red works only with red numbers"); - }), - (Red.prototype.imod = function (a) { - return this.prime ? this.prime.ireduce(a)._forceRed(this) : a.umod(this.m)._forceRed(this); - }), - (Red.prototype.neg = function (a) { - return a.isZero() ? a.clone() : this.m.sub(a)._forceRed(this); - }), - (Red.prototype.add = function (a, b) { - this._verify2(a, b); - var res = a.add(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res._forceRed(this); - }), - (Red.prototype.iadd = function (a, b) { - this._verify2(a, b); - var res = a.iadd(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res; - }), - (Red.prototype.sub = function (a, b) { - this._verify2(a, b); - var res = a.sub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res._forceRed(this); - }), - (Red.prototype.isub = function (a, b) { - this._verify2(a, b); - var res = a.isub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res; - }), - (Red.prototype.shl = function (a, num) { - return this._verify1(a), this.imod(a.ushln(num)); - }), - (Red.prototype.imul = function (a, b) { - return this._verify2(a, b), this.imod(a.imul(b)); - }), - (Red.prototype.mul = function (a, b) { - return this._verify2(a, b), this.imod(a.mul(b)); - }), - (Red.prototype.isqr = function (a) { - return this.imul(a, a.clone()); - }), - (Red.prototype.sqr = function (a) { - return this.mul(a, a); - }), - (Red.prototype.sqrt = function (a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - if ((assert(mod3 % 2 === 1), mod3 === 3)) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - for (var q = this.m.subn(1), s = 0; !q.isZero() && q.andln(1) === 0; ) s++, q.iushrn(1); - assert(!q.isZero()); - var one = new BN(1).toRed(this), - nOne = one.redNeg(), - lpow = this.m.subn(1).iushrn(1), - z = this.m.bitLength(); - for (z = new BN(2 * z * z).toRed(this); this.pow(z, lpow).cmp(nOne) !== 0; ) z.redIAdd(nOne); - for ( - var c = this.pow(z, q), r = this.pow(a, q.addn(1).iushrn(1)), t = this.pow(a, q), m = s; - t.cmp(one) !== 0; - - ) { - for (var tmp = t, i = 0; tmp.cmp(one) !== 0; i++) tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - (r = r.redMul(b)), (c = b.redSqr()), (t = t.redMul(c)), (m = i); - } - return r; - }), - (Red.prototype.invm = function (a) { - var inv = a._invmp(this.m); - return inv.negative !== 0 ? ((inv.negative = 0), this.imod(inv).redNeg()) : this.imod(inv); - }), - (Red.prototype.pow = function (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4, - wnd = new Array(1 << windowSize); - (wnd[0] = new BN(1).toRed(this)), (wnd[1] = a); - for (var i = 2; i < wnd.length; i++) wnd[i] = this.mul(wnd[i - 1], a); - var res = wnd[0], - current = 0, - currentLen = 0, - start = num.bitLength() % 26; - for (start === 0 && (start = 26), i = num.length - 1; i >= 0; i--) { - for (var word = num.words[i], j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if ((res !== wnd[0] && (res = this.sqr(res)), bit === 0 && current === 0)) { - currentLen = 0; - continue; - } - (current <<= 1), - (current |= bit), - currentLen++, - !(currentLen !== windowSize && (i !== 0 || j !== 0)) && - ((res = this.mul(res, wnd[current])), (currentLen = 0), (current = 0)); - } - start = 26; - } - return res; - }), - (Red.prototype.convertTo = function (num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }), - (Red.prototype.convertFrom = function (num) { - var res = num.clone(); - return (res.red = null), res; - }), - (BN.mont = function (num) { - return new Mont(num); - }); - function Mont(m) { - Red.call(this, m), - (this.shift = this.m.bitLength()), - this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), - (this.r = new BN(1).iushln(this.shift)), - (this.r2 = this.imod(this.r.sqr())), - (this.rinv = this.r._invmp(this.m)), - (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), - (this.minv = this.minv.umod(this.r)), - (this.minv = this.r.sub(this.minv)); - } - inherits(Mont, Red), - (Mont.prototype.convertTo = function (num) { - return this.imod(num.ushln(this.shift)); - }), - (Mont.prototype.convertFrom = function (num) { - var r = this.imod(num.mul(this.rinv)); - return (r.red = null), r; - }), - (Mont.prototype.imul = function (a, b) { - if (a.isZero() || b.isZero()) return (a.words[0] = 0), (a.length = 1), a; - var t = a.imul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.mul = function (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.invm = function (a) { - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }); - })(typeof module > "u" || module, exports); - }, -}); - -// (disabled):node_modules/crypto-browserify/index.js -var require_crypto_browserify = __commonJS({ - "(disabled):node_modules/crypto-browserify/index.js"() {}, -}); - -// node_modules/brorand/index.js -var require_brorand = __commonJS({ - "node_modules/brorand/index.js"(exports, module) { - var r; - module.exports = function (len) { - return r || (r = new Rand(null)), r.generate(len); - }; - function Rand(rand) { - this.rand = rand; - } - module.exports.Rand = Rand; - Rand.prototype.generate = function (len) { - return this._rand(len); - }; - Rand.prototype._rand = function (n) { - var out = new Buffer(n); - crypto.getRandomValues(out); - return out; - }; - }, -}); - -// node_modules/miller-rabin/lib/mr.js -var require_mr = __commonJS({ - "node_modules/miller-rabin/lib/mr.js"(exports, module) { - var bn = require_bn2(), - brorand = require_brorand(); - function MillerRabin(rand) { - this.rand = rand || new brorand.Rand(); - } - module.exports = MillerRabin; - MillerRabin.create = function (rand) { - return new MillerRabin(rand); - }; - MillerRabin.prototype._randbelow = function (n) { - var len = n.bitLength(), - min_bytes = Math.ceil(len / 8); - do var a = new bn(this.rand.generate(min_bytes)); - while (a.cmp(n) >= 0); - return a; - }; - MillerRabin.prototype._randrange = function (start, stop) { - var size = stop.sub(start); - return start.add(this._randbelow(size)); - }; - MillerRabin.prototype.test = function (n, k, cb) { - var len = n.bitLength(), - red = bn.mont(n), - rone = new bn(1).toRed(red); - k || (k = Math.max(1, (len / 48) | 0)); - for (var n1 = n.subn(1), s = 0; !n1.testn(s); s++); - for (var d = n.shrn(s), rn1 = n1.toRed(red), prime = !0; k > 0; k--) { - var a = this._randrange(new bn(2), n1); - cb && cb(a); - var x = a.toRed(red).redPow(d); - if (!(x.cmp(rone) === 0 || x.cmp(rn1) === 0)) { - for (var i = 1; i < s; i++) { - if (((x = x.redSqr()), x.cmp(rone) === 0)) return !1; - if (x.cmp(rn1) === 0) break; - } - if (i === s) return !1; - } - } - return prime; - }; - MillerRabin.prototype.getDivisor = function (n, k) { - var len = n.bitLength(), - red = bn.mont(n), - rone = new bn(1).toRed(red); - k || (k = Math.max(1, (len / 48) | 0)); - for (var n1 = n.subn(1), s = 0; !n1.testn(s); s++); - for (var d = n.shrn(s), rn1 = n1.toRed(red); k > 0; k--) { - var a = this._randrange(new bn(2), n1), - g = n.gcd(a); - if (g.cmpn(1) !== 0) return g; - var x = a.toRed(red).redPow(d); - if (!(x.cmp(rone) === 0 || x.cmp(rn1) === 0)) { - for (var i = 1; i < s; i++) { - if (((x = x.redSqr()), x.cmp(rone) === 0)) return x.fromRed().subn(1).gcd(n); - if (x.cmp(rn1) === 0) break; - } - if (i === s) return (x = x.redSqr()), x.fromRed().subn(1).gcd(n); - } - } - return !1; - }; - }, -}); - -// node_modules/diffie-hellman/lib/generatePrime.js -var require_generatePrime = __commonJS({ - "node_modules/diffie-hellman/lib/generatePrime.js"(exports, module) { - var randomBytes = require_browser(); - module.exports = findPrime; - findPrime.simpleSieve = simpleSieve; - findPrime.fermatTest = fermatTest; - var BN = require_bn(), - TWENTYFOUR = new BN(24), - MillerRabin = require_mr(), - millerRabin = new MillerRabin(), - ONE = new BN(1), - TWO = new BN(2), - FIVE = new BN(5), - SIXTEEN = new BN(16), - EIGHT = new BN(8), - TEN = new BN(10), - THREE = new BN(3), - SEVEN = new BN(7), - ELEVEN = new BN(11), - FOUR = new BN(4), - TWELVE = new BN(12), - primes = null; - function _getPrimes() { - if (primes !== null) return primes; - var limit = 1048576, - res = []; - res[0] = 2; - for (var i = 1, k = 3; k < limit; k += 2) { - for (var sqrt = Math.ceil(Math.sqrt(k)), j = 0; j < i && res[j] <= sqrt && k % res[j] !== 0; j++); - (i !== j && res[j] <= sqrt) || (res[i++] = k); - } - return (primes = res), res; - } - function simpleSieve(p) { - for (var primes2 = _getPrimes(), i = 0; i < primes2.length; i++) - if (p.modn(primes2[i]) === 0) return p.cmpn(primes2[i]) === 0; - return !0; - } - function fermatTest(p) { - var red = BN.mont(p); - return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; - } - function findPrime(bits, gen) { - if (bits < 16) return gen === 2 || gen === 5 ? new BN([140, 123]) : new BN([140, 39]); - gen = new BN(gen); - for (var num, n2; ; ) { - for (num = new BN(randomBytes(Math.ceil(bits / 8))); num.bitLength() > bits; ) num.ishrn(1); - if ((num.isEven() && num.iadd(ONE), num.testn(1) || num.iadd(TWO), gen.cmp(TWO))) { - if (!gen.cmp(FIVE)) for (; num.mod(TEN).cmp(THREE); ) num.iadd(FOUR); - } else for (; num.mod(TWENTYFOUR).cmp(ELEVEN); ) num.iadd(FOUR); - if ( - ((n2 = num.shrn(1)), - simpleSieve(n2) && - simpleSieve(num) && - fermatTest(n2) && - fermatTest(num) && - millerRabin.test(n2) && - millerRabin.test(num)) - ) - return num; - } - } - }, -}); - -// node_modules/diffie-hellman/lib/primes.json -var require_primes = __commonJS({ - "node_modules/diffie-hellman/lib/primes.json"(exports, module) { - module.exports = { - modp1: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff", - }, - modp2: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff", - }, - modp5: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff", - }, - modp14: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff", - }, - modp15: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff", - }, - modp16: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff", - }, - modp17: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff", - }, - modp18: { - gen: "02", - prime: - "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff", - }, - }; - }, -}); - -// node_modules/diffie-hellman/lib/dh.js -var require_dh = __commonJS({ - "node_modules/diffie-hellman/lib/dh.js"(exports, module) { - var BN = require_bn(), - MillerRabin = require_mr(), - millerRabin = new MillerRabin(), - TWENTYFOUR = new BN(24), - ELEVEN = new BN(11), - TEN = new BN(10), - THREE = new BN(3), - SEVEN = new BN(7), - primes = require_generatePrime(), - randomBytes = require_browser(); - module.exports = DH; - function setPublicKey(pub, enc) { - return ( - (enc = enc || "utf8"), Buffer.isBuffer(pub) || (pub = new Buffer(pub, enc)), (this._pub = new BN(pub)), this - ); - } - function setPrivateKey(priv, enc) { - return ( - (enc = enc || "utf8"), - Buffer.isBuffer(priv) || (priv = new Buffer(priv, enc)), - (this._priv = new BN(priv)), - this - ); - } - var primeCache = {}; - function checkPrime(prime, generator) { - var gen = generator.toString("hex"), - hex = [gen, prime.toString(16)].join("_"); - if (hex in primeCache) return primeCache[hex]; - var error = 0; - if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) - return ( - (error += 1), gen === "02" || gen === "05" ? (error += 8) : (error += 4), (primeCache[hex] = error), error - ); - millerRabin.test(prime.shrn(1)) || (error += 2); - var rem; - switch (gen) { - case "02": - prime.mod(TWENTYFOUR).cmp(ELEVEN) && (error += 8); - break; - case "05": - (rem = prime.mod(TEN)), rem.cmp(THREE) && rem.cmp(SEVEN) && (error += 8); - break; - default: - error += 4; - } - return (primeCache[hex] = error), error; - } - function DH(prime, generator, malleable) { - this.setGenerator(generator), - (this.__prime = new BN(prime)), - (this._prime = BN.mont(this.__prime)), - (this._primeLen = prime.length), - (this._pub = void 0), - (this._priv = void 0), - (this._primeCode = void 0), - malleable ? ((this.setPublicKey = setPublicKey), (this.setPrivateKey = setPrivateKey)) : (this._primeCode = 8); - } - Object.defineProperty(DH.prototype, "verifyError", { - enumerable: !0, - get: function () { - return ( - typeof this._primeCode != "number" && (this._primeCode = checkPrime(this.__prime, this.__gen)), - this._primeCode - ); - }, - }); - DH.prototype.generateKeys = function () { - return ( - this._priv || (this._priv = new BN(randomBytes(this._primeLen))), - (this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed()), - this.getPublicKey() - ); - }; - DH.prototype.computeSecret = function (other) { - (other = new BN(other)), (other = other.toRed(this._prime)); - var secret = other.redPow(this._priv).fromRed(), - out = new Buffer(secret.toArray()), - prime = this.getPrime(); - if (out.length < prime.length) { - var front = new Buffer(prime.length - out.length); - front.fill(0), (out = Buffer.concat([front, out])); - } - return out; - }; - DH.prototype.getPublicKey = function (enc) { - return formatReturnValue(this._pub, enc); - }; - DH.prototype.getPrivateKey = function (enc) { - return formatReturnValue(this._priv, enc); - }; - DH.prototype.getPrime = function (enc) { - return formatReturnValue(this.__prime, enc); - }; - DH.prototype.getGenerator = function (enc) { - return formatReturnValue(this._gen, enc); - }; - DH.prototype.setGenerator = function (gen, enc) { - return ( - (enc = enc || "utf8"), - Buffer.isBuffer(gen) || (gen = new Buffer(gen, enc)), - (this.__gen = gen), - (this._gen = new BN(gen)), - this - ); - }; - function formatReturnValue(bn, enc) { - var buf = new Buffer(bn.toArray()); - return enc ? buf.toString(enc) : buf; - } - }, -}); - -// node_modules/diffie-hellman/browser.js -var require_browser7 = __commonJS({ - "node_modules/diffie-hellman/browser.js"(exports) { - var generatePrime = require_generatePrime(), - primes = require_primes(), - DH = require_dh(); - function getDiffieHellman(mod) { - var prime = new Buffer(primes[mod].prime, "hex"), - gen = new Buffer(primes[mod].gen, "hex"); - return new DH(prime, gen); - } - var ENCODINGS = { - binary: !0, - hex: !0, - base64: !0, - }; - function createDiffieHellman(prime, enc, generator, genc) { - return Buffer.isBuffer(enc) || ENCODINGS[enc] === void 0 - ? createDiffieHellman(prime, "binary", enc, generator) - : ((enc = enc || "binary"), - (genc = genc || "binary"), - (generator = generator || new Buffer([2])), - Buffer.isBuffer(generator) || (generator = new Buffer(generator, genc)), - typeof prime == "number" - ? new DH(generatePrime(prime, generator), generator, !0) - : (Buffer.isBuffer(prime) || (prime = new Buffer(prime, enc)), new DH(prime, generator, !0))); - } - exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman; - exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman; - }, -}); - -// node_modules/bn.js/lib/bn.js -var require_bn3 = __commonJS({ - "node_modules/bn.js/lib/bn.js"(exports, module) { - (function (module2, exports2) { - "use strict"; - function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); - } - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - (TempCtor.prototype = superCtor.prototype), - (ctor.prototype = new TempCtor()), - (ctor.prototype.constructor = ctor); - } - function BN(number, base, endian) { - if (BN.isBN(number)) return number; - (this.negative = 0), - (this.words = null), - (this.length = 0), - (this.red = null), - number !== null && - ((base === "le" || base === "be") && ((endian = base), (base = 10)), - this._init(number || 0, base || 10, endian || "be")); - } - typeof module2 == "object" ? (module2.exports = BN) : (exports2.BN = BN), (BN.BN = BN), (BN.wordSize = 26); - var Buffer2 = Buffer; - (BN.isBN = function (num) { - return num instanceof BN - ? !0 - : num !== null && - typeof num == "object" && - num.constructor.wordSize === BN.wordSize && - Array.isArray(num.words); - }), - (BN.max = function (left, right) { - return left.cmp(right) > 0 ? left : right; - }), - (BN.min = function (left, right) { - return left.cmp(right) < 0 ? left : right; - }), - (BN.prototype._init = function (number, base, endian) { - if (typeof number == "number") return this._initNumber(number, base, endian); - if (typeof number == "object") return this._initArray(number, base, endian); - base === "hex" && (base = 16), - assert(base === (base | 0) && base >= 2 && base <= 36), - (number = number.toString().replace(/\s+/g, "")); - var start = 0; - number[0] === "-" && (start++, (this.negative = 1)), - start < number.length && - (base === 16 - ? this._parseHex(number, start, endian) - : (this._parseBase(number, base, start), - endian === "le" && this._initArray(this.toArray(), base, endian))); - }), - (BN.prototype._initNumber = function (number, base, endian) { - number < 0 && ((this.negative = 1), (number = -number)), - number < 67108864 - ? ((this.words = [number & 67108863]), (this.length = 1)) - : number < 4503599627370496 - ? ((this.words = [number & 67108863, (number / 67108864) & 67108863]), (this.length = 2)) - : (assert(number < 9007199254740992), - (this.words = [number & 67108863, (number / 67108864) & 67108863, 1]), - (this.length = 3)), - endian === "le" && this._initArray(this.toArray(), base, endian); - }), - (BN.prototype._initArray = function (number, base, endian) { - if ((assert(typeof number.length == "number"), number.length <= 0)) - return (this.words = [0]), (this.length = 1), this; - (this.length = Math.ceil(number.length / 3)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var j, - w, - off = 0; - if (endian === "be") - for (i = number.length - 1, j = 0; i >= 0; i -= 3) - (w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - else if (endian === "le") - for (i = 0, j = 0; i < number.length; i += 3) - (w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - return this._strip(); - }); - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - if (c >= 48 && c <= 57) return c - 48; - if (c >= 65 && c <= 70) return c - 55; - if (c >= 97 && c <= 102) return c - 87; - assert(!1, "Invalid character in " + string); - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - return index - 1 >= lowerBound && (r |= parseHex4Bits(string, index - 1) << 4), r; - } - BN.prototype._parseHex = function (number, start, endian) { - (this.length = Math.ceil((number.length - start) / 6)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var off = 0, - j = 0, - w; - if (endian === "be") - for (i = number.length - 1; i >= start; i -= 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - } - this._strip(); - }; - function parseBase(str, start, end, mul) { - for (var r = 0, b = 0, len = Math.min(str.length, end), i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - (r *= mul), - c >= 49 ? (b = c - 49 + 10) : c >= 17 ? (b = c - 17 + 10) : (b = c), - assert(c >= 0 && b < mul, "Invalid character"), - (r += b); - } - return r; - } - (BN.prototype._parseBase = function (number, base, start) { - (this.words = [0]), (this.length = 1); - for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base) limbLen++; - limbLen--, (limbPow = (limbPow / base) | 0); - for ( - var total = number.length - start, - mod = total % limbLen, - end = Math.min(total, total - mod) + start, - word = 0, - i = start; - i < end; - i += limbLen - ) - (word = parseBase(number, i, i + limbLen, base)), - this.imuln(limbPow), - this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - if (mod !== 0) { - var pow = 1; - for (word = parseBase(number, i, number.length, base), i = 0; i < mod; i++) pow *= base; - this.imuln(pow), this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - } - this._strip(); - }), - (BN.prototype.copy = function (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) dest.words[i] = this.words[i]; - (dest.length = this.length), (dest.negative = this.negative), (dest.red = this.red); - }); - function move(dest, src) { - (dest.words = src.words), (dest.length = src.length), (dest.negative = src.negative), (dest.red = src.red); - } - if ( - ((BN.prototype._move = function (dest) { - move(dest, this); - }), - (BN.prototype.clone = function () { - var r = new BN(null); - return this.copy(r), r; - }), - (BN.prototype._expand = function (size) { - for (; this.length < size; ) this.words[this.length++] = 0; - return this; - }), - (BN.prototype._strip = function () { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; - return this._normSign(); - }), - (BN.prototype._normSign = function () { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }), - typeof Symbol < "u" && typeof Symbol.for == "function") - ) - try { - BN.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect; - } catch { - BN.prototype.inspect = inspect; - } - else BN.prototype.inspect = inspect; - function inspect() { - return (this.red ? ""; - } - var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000", - ], - groupSizes = [ - 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, - ], - groupBases = [ - 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, - 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, - 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, - 60466176, - ]; - (BN.prototype.toString = function (base, padding) { - (base = base || 10), (padding = padding | 0 || 1); - var out; - if (base === 16 || base === "hex") { - out = ""; - for (var off = 0, carry = 0, i = 0; i < this.length; i++) { - var w = this.words[i], - word = (((w << off) | carry) & 16777215).toString(16); - (carry = (w >>> (24 - off)) & 16777215), - (off += 2), - off >= 26 && ((off -= 26), i--), - carry !== 0 || i !== this.length - 1 ? (out = zeros[6 - word.length] + word + out) : (out = word + out); - } - for (carry !== 0 && (out = carry.toString(16) + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - if (base === (base | 0) && base >= 2 && base <= 36) { - var groupSize = groupSizes[base], - groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - for (c.negative = 0; !c.isZero(); ) { - var r = c.modrn(groupBase).toString(base); - (c = c.idivn(groupBase)), c.isZero() ? (out = r + out) : (out = zeros[groupSize - r.length] + r + out); - } - for (this.isZero() && (out = "0" + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - assert(!1, "Base should be between 2 and 36"); - }), - (BN.prototype.toNumber = function () { - var ret = this.words[0]; - return ( - this.length === 2 - ? (ret += this.words[1] * 67108864) - : this.length === 3 && this.words[2] === 1 - ? (ret += 4503599627370496 + this.words[1] * 67108864) - : this.length > 2 && assert(!1, "Number can only safely store up to 53 bits"), - this.negative !== 0 ? -ret : ret - ); - }), - (BN.prototype.toJSON = function () { - return this.toString(16, 2); - }), - Buffer2 && - (BN.prototype.toBuffer = function (endian, length) { - return this.toArrayLike(Buffer2, endian, length); - }), - (BN.prototype.toArray = function (endian, length) { - return this.toArrayLike(Array, endian, length); - }); - var allocate = function (ArrayType, size) { - return ArrayType.allocUnsafe ? ArrayType.allocUnsafe(size) : new ArrayType(size); - }; - (BN.prototype.toArrayLike = function (ArrayType, endian, length) { - this._strip(); - var byteLength = this.byteLength(), - reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"), - assert(reqLength > 0, "Requested array length <= 0"); - var res = allocate(ArrayType, reqLength), - postfix = endian === "le" ? "LE" : "BE"; - return this["_toArrayLike" + postfix](res, byteLength), res; - }), - (BN.prototype._toArrayLikeLE = function (res, byteLength) { - for (var position = 0, carry = 0, i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; - (res[position++] = word & 255), - position < res.length && (res[position++] = (word >> 8) & 255), - position < res.length && (res[position++] = (word >> 16) & 255), - shift === 6 - ? (position < res.length && (res[position++] = (word >> 24) & 255), (carry = 0), (shift = 0)) - : ((carry = word >>> 24), (shift += 2)); - } - if (position < res.length) for (res[position++] = carry; position < res.length; ) res[position++] = 0; - }), - (BN.prototype._toArrayLikeBE = function (res, byteLength) { - for (var position = res.length - 1, carry = 0, i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; - (res[position--] = word & 255), - position >= 0 && (res[position--] = (word >> 8) & 255), - position >= 0 && (res[position--] = (word >> 16) & 255), - shift === 6 - ? (position >= 0 && (res[position--] = (word >> 24) & 255), (carry = 0), (shift = 0)) - : ((carry = word >>> 24), (shift += 2)); - } - if (position >= 0) for (res[position--] = carry; position >= 0; ) res[position--] = 0; - }), - Math.clz32 - ? (BN.prototype._countBits = function (w) { - return 32 - Math.clz32(w); - }) - : (BN.prototype._countBits = function (w) { - var t = w, - r = 0; - return ( - t >= 4096 && ((r += 13), (t >>>= 13)), - t >= 64 && ((r += 7), (t >>>= 7)), - t >= 8 && ((r += 4), (t >>>= 4)), - t >= 2 && ((r += 2), (t >>>= 2)), - r + t - ); - }), - (BN.prototype._zeroBits = function (w) { - if (w === 0) return 26; - var t = w, - r = 0; - return ( - (t & 8191) === 0 && ((r += 13), (t >>>= 13)), - (t & 127) === 0 && ((r += 7), (t >>>= 7)), - (t & 15) === 0 && ((r += 4), (t >>>= 4)), - (t & 3) === 0 && ((r += 2), (t >>>= 2)), - (t & 1) === 0 && r++, - r - ); - }), - (BN.prototype.bitLength = function () { - var w = this.words[this.length - 1], - hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }); - function toBitArray(num) { - for (var w = new Array(num.bitLength()), bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0, - wbit = bit % 26; - w[bit] = (num.words[off] >>> wbit) & 1; - } - return w; - } - (BN.prototype.zeroBits = function () { - if (this.isZero()) return 0; - for (var r = 0, i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - if (((r += b), b !== 26)) break; - } - return r; - }), - (BN.prototype.byteLength = function () { - return Math.ceil(this.bitLength() / 8); - }), - (BN.prototype.toTwos = function (width) { - return this.negative !== 0 ? this.abs().inotn(width).iaddn(1) : this.clone(); - }), - (BN.prototype.fromTwos = function (width) { - return this.testn(width - 1) ? this.notn(width).iaddn(1).ineg() : this.clone(); - }), - (BN.prototype.isNeg = function () { - return this.negative !== 0; - }), - (BN.prototype.neg = function () { - return this.clone().ineg(); - }), - (BN.prototype.ineg = function () { - return this.isZero() || (this.negative ^= 1), this; - }), - (BN.prototype.iuor = function (num) { - for (; this.length < num.length; ) this.words[this.length++] = 0; - for (var i = 0; i < num.length; i++) this.words[i] = this.words[i] | num.words[i]; - return this._strip(); - }), - (BN.prototype.ior = function (num) { - return assert((this.negative | num.negative) === 0), this.iuor(num); - }), - (BN.prototype.or = function (num) { - return this.length > num.length ? this.clone().ior(num) : num.clone().ior(this); - }), - (BN.prototype.uor = function (num) { - return this.length > num.length ? this.clone().iuor(num) : num.clone().iuor(this); - }), - (BN.prototype.iuand = function (num) { - var b; - this.length > num.length ? (b = num) : (b = this); - for (var i = 0; i < b.length; i++) this.words[i] = this.words[i] & num.words[i]; - return (this.length = b.length), this._strip(); - }), - (BN.prototype.iand = function (num) { - return assert((this.negative | num.negative) === 0), this.iuand(num); - }), - (BN.prototype.and = function (num) { - return this.length > num.length ? this.clone().iand(num) : num.clone().iand(this); - }), - (BN.prototype.uand = function (num) { - return this.length > num.length ? this.clone().iuand(num) : num.clone().iuand(this); - }), - (BN.prototype.iuxor = function (num) { - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var i = 0; i < b.length; i++) this.words[i] = a.words[i] ^ b.words[i]; - if (this !== a) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = a.length), this._strip(); - }), - (BN.prototype.ixor = function (num) { - return assert((this.negative | num.negative) === 0), this.iuxor(num); - }), - (BN.prototype.xor = function (num) { - return this.length > num.length ? this.clone().ixor(num) : num.clone().ixor(this); - }), - (BN.prototype.uxor = function (num) { - return this.length > num.length ? this.clone().iuxor(num) : num.clone().iuxor(this); - }), - (BN.prototype.inotn = function (width) { - assert(typeof width == "number" && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0, - bitsLeft = width % 26; - this._expand(bytesNeeded), bitsLeft > 0 && bytesNeeded--; - for (var i = 0; i < bytesNeeded; i++) this.words[i] = ~this.words[i] & 67108863; - return bitsLeft > 0 && (this.words[i] = ~this.words[i] & (67108863 >> (26 - bitsLeft))), this._strip(); - }), - (BN.prototype.notn = function (width) { - return this.clone().inotn(width); - }), - (BN.prototype.setn = function (bit, val) { - assert(typeof bit == "number" && bit >= 0); - var off = (bit / 26) | 0, - wbit = bit % 26; - return ( - this._expand(off + 1), - val - ? (this.words[off] = this.words[off] | (1 << wbit)) - : (this.words[off] = this.words[off] & ~(1 << wbit)), - this._strip() - ); - }), - (BN.prototype.iadd = function (num) { - var r; - if (this.negative !== 0 && num.negative === 0) - return (this.negative = 0), (r = this.isub(num)), (this.negative ^= 1), this._normSign(); - if (this.negative === 0 && num.negative !== 0) - return (num.negative = 0), (r = this.isub(num)), (num.negative = 1), r._normSign(); - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) + (b.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - if (((this.length = a.length), carry !== 0)) (this.words[this.length] = carry), this.length++; - else if (a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return this; - }), - (BN.prototype.add = function (num) { - var res; - return num.negative !== 0 && this.negative === 0 - ? ((num.negative = 0), (res = this.sub(num)), (num.negative ^= 1), res) - : num.negative === 0 && this.negative !== 0 - ? ((this.negative = 0), (res = num.sub(this)), (this.negative = 1), res) - : this.length > num.length - ? this.clone().iadd(num) - : num.clone().iadd(this); - }), - (BN.prototype.isub = function (num) { - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - return (num.negative = 1), r._normSign(); - } else if (this.negative !== 0) - return (this.negative = 0), this.iadd(num), (this.negative = 1), this._normSign(); - var cmp = this.cmp(num); - if (cmp === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; - var a, b; - cmp > 0 ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) - (b.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - if (carry === 0 && i < a.length && a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = Math.max(this.length, i)), a !== this && (this.negative = 1), this._strip(); - }), - (BN.prototype.sub = function (num) { - return this.clone().isub(num); - }); - function smallMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - var len = (self2.length + num.length) | 0; - (out.length = len), (len = (len - 1) | 0); - var a = self2.words[0] | 0, - b = num.words[0] | 0, - r = a * b, - lo = r & 67108863, - carry = (r / 67108864) | 0; - out.words[0] = lo; - for (var k = 1; k < len; k++) { - for ( - var ncarry = carry >>> 26, - rword = carry & 67108863, - maxJ = Math.min(k, num.length - 1), - j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = (k - j) | 0; - (a = self2.words[i] | 0), - (b = num.words[j] | 0), - (r = a * b + rword), - (ncarry += (r / 67108864) | 0), - (rword = r & 67108863); - } - (out.words[k] = rword | 0), (carry = ncarry | 0); - } - return carry !== 0 ? (out.words[k] = carry | 0) : out.length--, out._strip(); - } - var comb10MulTo = function (self2, num, out) { - var a = self2.words, - b = num.words, - o = out.words, - c = 0, - lo, - mid, - hi, - a0 = a[0] | 0, - al0 = a0 & 8191, - ah0 = a0 >>> 13, - a1 = a[1] | 0, - al1 = a1 & 8191, - ah1 = a1 >>> 13, - a2 = a[2] | 0, - al2 = a2 & 8191, - ah2 = a2 >>> 13, - a3 = a[3] | 0, - al3 = a3 & 8191, - ah3 = a3 >>> 13, - a4 = a[4] | 0, - al4 = a4 & 8191, - ah4 = a4 >>> 13, - a5 = a[5] | 0, - al5 = a5 & 8191, - ah5 = a5 >>> 13, - a6 = a[6] | 0, - al6 = a6 & 8191, - ah6 = a6 >>> 13, - a7 = a[7] | 0, - al7 = a7 & 8191, - ah7 = a7 >>> 13, - a8 = a[8] | 0, - al8 = a8 & 8191, - ah8 = a8 >>> 13, - a9 = a[9] | 0, - al9 = a9 & 8191, - ah9 = a9 >>> 13, - b0 = b[0] | 0, - bl0 = b0 & 8191, - bh0 = b0 >>> 13, - b1 = b[1] | 0, - bl1 = b1 & 8191, - bh1 = b1 >>> 13, - b2 = b[2] | 0, - bl2 = b2 & 8191, - bh2 = b2 >>> 13, - b3 = b[3] | 0, - bl3 = b3 & 8191, - bh3 = b3 >>> 13, - b4 = b[4] | 0, - bl4 = b4 & 8191, - bh4 = b4 >>> 13, - b5 = b[5] | 0, - bl5 = b5 & 8191, - bh5 = b5 >>> 13, - b6 = b[6] | 0, - bl6 = b6 & 8191, - bh6 = b6 >>> 13, - b7 = b[7] | 0, - bl7 = b7 & 8191, - bh7 = b7 >>> 13, - b8 = b[8] | 0, - bl8 = b8 & 8191, - bh8 = b8 >>> 13, - b9 = b[9] | 0, - bl9 = b9 & 8191, - bh9 = b9 >>> 13; - (out.negative = self2.negative ^ num.negative), - (out.length = 19), - (lo = Math.imul(al0, bl0)), - (mid = Math.imul(al0, bh0)), - (mid = (mid + Math.imul(ah0, bl0)) | 0), - (hi = Math.imul(ah0, bh0)); - var w0 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0), - (w0 &= 67108863), - (lo = Math.imul(al1, bl0)), - (mid = Math.imul(al1, bh0)), - (mid = (mid + Math.imul(ah1, bl0)) | 0), - (hi = Math.imul(ah1, bh0)), - (lo = (lo + Math.imul(al0, bl1)) | 0), - (mid = (mid + Math.imul(al0, bh1)) | 0), - (mid = (mid + Math.imul(ah0, bl1)) | 0), - (hi = (hi + Math.imul(ah0, bh1)) | 0); - var w1 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0), - (w1 &= 67108863), - (lo = Math.imul(al2, bl0)), - (mid = Math.imul(al2, bh0)), - (mid = (mid + Math.imul(ah2, bl0)) | 0), - (hi = Math.imul(ah2, bh0)), - (lo = (lo + Math.imul(al1, bl1)) | 0), - (mid = (mid + Math.imul(al1, bh1)) | 0), - (mid = (mid + Math.imul(ah1, bl1)) | 0), - (hi = (hi + Math.imul(ah1, bh1)) | 0), - (lo = (lo + Math.imul(al0, bl2)) | 0), - (mid = (mid + Math.imul(al0, bh2)) | 0), - (mid = (mid + Math.imul(ah0, bl2)) | 0), - (hi = (hi + Math.imul(ah0, bh2)) | 0); - var w2 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0), - (w2 &= 67108863), - (lo = Math.imul(al3, bl0)), - (mid = Math.imul(al3, bh0)), - (mid = (mid + Math.imul(ah3, bl0)) | 0), - (hi = Math.imul(ah3, bh0)), - (lo = (lo + Math.imul(al2, bl1)) | 0), - (mid = (mid + Math.imul(al2, bh1)) | 0), - (mid = (mid + Math.imul(ah2, bl1)) | 0), - (hi = (hi + Math.imul(ah2, bh1)) | 0), - (lo = (lo + Math.imul(al1, bl2)) | 0), - (mid = (mid + Math.imul(al1, bh2)) | 0), - (mid = (mid + Math.imul(ah1, bl2)) | 0), - (hi = (hi + Math.imul(ah1, bh2)) | 0), - (lo = (lo + Math.imul(al0, bl3)) | 0), - (mid = (mid + Math.imul(al0, bh3)) | 0), - (mid = (mid + Math.imul(ah0, bl3)) | 0), - (hi = (hi + Math.imul(ah0, bh3)) | 0); - var w3 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0), - (w3 &= 67108863), - (lo = Math.imul(al4, bl0)), - (mid = Math.imul(al4, bh0)), - (mid = (mid + Math.imul(ah4, bl0)) | 0), - (hi = Math.imul(ah4, bh0)), - (lo = (lo + Math.imul(al3, bl1)) | 0), - (mid = (mid + Math.imul(al3, bh1)) | 0), - (mid = (mid + Math.imul(ah3, bl1)) | 0), - (hi = (hi + Math.imul(ah3, bh1)) | 0), - (lo = (lo + Math.imul(al2, bl2)) | 0), - (mid = (mid + Math.imul(al2, bh2)) | 0), - (mid = (mid + Math.imul(ah2, bl2)) | 0), - (hi = (hi + Math.imul(ah2, bh2)) | 0), - (lo = (lo + Math.imul(al1, bl3)) | 0), - (mid = (mid + Math.imul(al1, bh3)) | 0), - (mid = (mid + Math.imul(ah1, bl3)) | 0), - (hi = (hi + Math.imul(ah1, bh3)) | 0), - (lo = (lo + Math.imul(al0, bl4)) | 0), - (mid = (mid + Math.imul(al0, bh4)) | 0), - (mid = (mid + Math.imul(ah0, bl4)) | 0), - (hi = (hi + Math.imul(ah0, bh4)) | 0); - var w4 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0), - (w4 &= 67108863), - (lo = Math.imul(al5, bl0)), - (mid = Math.imul(al5, bh0)), - (mid = (mid + Math.imul(ah5, bl0)) | 0), - (hi = Math.imul(ah5, bh0)), - (lo = (lo + Math.imul(al4, bl1)) | 0), - (mid = (mid + Math.imul(al4, bh1)) | 0), - (mid = (mid + Math.imul(ah4, bl1)) | 0), - (hi = (hi + Math.imul(ah4, bh1)) | 0), - (lo = (lo + Math.imul(al3, bl2)) | 0), - (mid = (mid + Math.imul(al3, bh2)) | 0), - (mid = (mid + Math.imul(ah3, bl2)) | 0), - (hi = (hi + Math.imul(ah3, bh2)) | 0), - (lo = (lo + Math.imul(al2, bl3)) | 0), - (mid = (mid + Math.imul(al2, bh3)) | 0), - (mid = (mid + Math.imul(ah2, bl3)) | 0), - (hi = (hi + Math.imul(ah2, bh3)) | 0), - (lo = (lo + Math.imul(al1, bl4)) | 0), - (mid = (mid + Math.imul(al1, bh4)) | 0), - (mid = (mid + Math.imul(ah1, bl4)) | 0), - (hi = (hi + Math.imul(ah1, bh4)) | 0), - (lo = (lo + Math.imul(al0, bl5)) | 0), - (mid = (mid + Math.imul(al0, bh5)) | 0), - (mid = (mid + Math.imul(ah0, bl5)) | 0), - (hi = (hi + Math.imul(ah0, bh5)) | 0); - var w5 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0), - (w5 &= 67108863), - (lo = Math.imul(al6, bl0)), - (mid = Math.imul(al6, bh0)), - (mid = (mid + Math.imul(ah6, bl0)) | 0), - (hi = Math.imul(ah6, bh0)), - (lo = (lo + Math.imul(al5, bl1)) | 0), - (mid = (mid + Math.imul(al5, bh1)) | 0), - (mid = (mid + Math.imul(ah5, bl1)) | 0), - (hi = (hi + Math.imul(ah5, bh1)) | 0), - (lo = (lo + Math.imul(al4, bl2)) | 0), - (mid = (mid + Math.imul(al4, bh2)) | 0), - (mid = (mid + Math.imul(ah4, bl2)) | 0), - (hi = (hi + Math.imul(ah4, bh2)) | 0), - (lo = (lo + Math.imul(al3, bl3)) | 0), - (mid = (mid + Math.imul(al3, bh3)) | 0), - (mid = (mid + Math.imul(ah3, bl3)) | 0), - (hi = (hi + Math.imul(ah3, bh3)) | 0), - (lo = (lo + Math.imul(al2, bl4)) | 0), - (mid = (mid + Math.imul(al2, bh4)) | 0), - (mid = (mid + Math.imul(ah2, bl4)) | 0), - (hi = (hi + Math.imul(ah2, bh4)) | 0), - (lo = (lo + Math.imul(al1, bl5)) | 0), - (mid = (mid + Math.imul(al1, bh5)) | 0), - (mid = (mid + Math.imul(ah1, bl5)) | 0), - (hi = (hi + Math.imul(ah1, bh5)) | 0), - (lo = (lo + Math.imul(al0, bl6)) | 0), - (mid = (mid + Math.imul(al0, bh6)) | 0), - (mid = (mid + Math.imul(ah0, bl6)) | 0), - (hi = (hi + Math.imul(ah0, bh6)) | 0); - var w6 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0), - (w6 &= 67108863), - (lo = Math.imul(al7, bl0)), - (mid = Math.imul(al7, bh0)), - (mid = (mid + Math.imul(ah7, bl0)) | 0), - (hi = Math.imul(ah7, bh0)), - (lo = (lo + Math.imul(al6, bl1)) | 0), - (mid = (mid + Math.imul(al6, bh1)) | 0), - (mid = (mid + Math.imul(ah6, bl1)) | 0), - (hi = (hi + Math.imul(ah6, bh1)) | 0), - (lo = (lo + Math.imul(al5, bl2)) | 0), - (mid = (mid + Math.imul(al5, bh2)) | 0), - (mid = (mid + Math.imul(ah5, bl2)) | 0), - (hi = (hi + Math.imul(ah5, bh2)) | 0), - (lo = (lo + Math.imul(al4, bl3)) | 0), - (mid = (mid + Math.imul(al4, bh3)) | 0), - (mid = (mid + Math.imul(ah4, bl3)) | 0), - (hi = (hi + Math.imul(ah4, bh3)) | 0), - (lo = (lo + Math.imul(al3, bl4)) | 0), - (mid = (mid + Math.imul(al3, bh4)) | 0), - (mid = (mid + Math.imul(ah3, bl4)) | 0), - (hi = (hi + Math.imul(ah3, bh4)) | 0), - (lo = (lo + Math.imul(al2, bl5)) | 0), - (mid = (mid + Math.imul(al2, bh5)) | 0), - (mid = (mid + Math.imul(ah2, bl5)) | 0), - (hi = (hi + Math.imul(ah2, bh5)) | 0), - (lo = (lo + Math.imul(al1, bl6)) | 0), - (mid = (mid + Math.imul(al1, bh6)) | 0), - (mid = (mid + Math.imul(ah1, bl6)) | 0), - (hi = (hi + Math.imul(ah1, bh6)) | 0), - (lo = (lo + Math.imul(al0, bl7)) | 0), - (mid = (mid + Math.imul(al0, bh7)) | 0), - (mid = (mid + Math.imul(ah0, bl7)) | 0), - (hi = (hi + Math.imul(ah0, bh7)) | 0); - var w7 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0), - (w7 &= 67108863), - (lo = Math.imul(al8, bl0)), - (mid = Math.imul(al8, bh0)), - (mid = (mid + Math.imul(ah8, bl0)) | 0), - (hi = Math.imul(ah8, bh0)), - (lo = (lo + Math.imul(al7, bl1)) | 0), - (mid = (mid + Math.imul(al7, bh1)) | 0), - (mid = (mid + Math.imul(ah7, bl1)) | 0), - (hi = (hi + Math.imul(ah7, bh1)) | 0), - (lo = (lo + Math.imul(al6, bl2)) | 0), - (mid = (mid + Math.imul(al6, bh2)) | 0), - (mid = (mid + Math.imul(ah6, bl2)) | 0), - (hi = (hi + Math.imul(ah6, bh2)) | 0), - (lo = (lo + Math.imul(al5, bl3)) | 0), - (mid = (mid + Math.imul(al5, bh3)) | 0), - (mid = (mid + Math.imul(ah5, bl3)) | 0), - (hi = (hi + Math.imul(ah5, bh3)) | 0), - (lo = (lo + Math.imul(al4, bl4)) | 0), - (mid = (mid + Math.imul(al4, bh4)) | 0), - (mid = (mid + Math.imul(ah4, bl4)) | 0), - (hi = (hi + Math.imul(ah4, bh4)) | 0), - (lo = (lo + Math.imul(al3, bl5)) | 0), - (mid = (mid + Math.imul(al3, bh5)) | 0), - (mid = (mid + Math.imul(ah3, bl5)) | 0), - (hi = (hi + Math.imul(ah3, bh5)) | 0), - (lo = (lo + Math.imul(al2, bl6)) | 0), - (mid = (mid + Math.imul(al2, bh6)) | 0), - (mid = (mid + Math.imul(ah2, bl6)) | 0), - (hi = (hi + Math.imul(ah2, bh6)) | 0), - (lo = (lo + Math.imul(al1, bl7)) | 0), - (mid = (mid + Math.imul(al1, bh7)) | 0), - (mid = (mid + Math.imul(ah1, bl7)) | 0), - (hi = (hi + Math.imul(ah1, bh7)) | 0), - (lo = (lo + Math.imul(al0, bl8)) | 0), - (mid = (mid + Math.imul(al0, bh8)) | 0), - (mid = (mid + Math.imul(ah0, bl8)) | 0), - (hi = (hi + Math.imul(ah0, bh8)) | 0); - var w8 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0), - (w8 &= 67108863), - (lo = Math.imul(al9, bl0)), - (mid = Math.imul(al9, bh0)), - (mid = (mid + Math.imul(ah9, bl0)) | 0), - (hi = Math.imul(ah9, bh0)), - (lo = (lo + Math.imul(al8, bl1)) | 0), - (mid = (mid + Math.imul(al8, bh1)) | 0), - (mid = (mid + Math.imul(ah8, bl1)) | 0), - (hi = (hi + Math.imul(ah8, bh1)) | 0), - (lo = (lo + Math.imul(al7, bl2)) | 0), - (mid = (mid + Math.imul(al7, bh2)) | 0), - (mid = (mid + Math.imul(ah7, bl2)) | 0), - (hi = (hi + Math.imul(ah7, bh2)) | 0), - (lo = (lo + Math.imul(al6, bl3)) | 0), - (mid = (mid + Math.imul(al6, bh3)) | 0), - (mid = (mid + Math.imul(ah6, bl3)) | 0), - (hi = (hi + Math.imul(ah6, bh3)) | 0), - (lo = (lo + Math.imul(al5, bl4)) | 0), - (mid = (mid + Math.imul(al5, bh4)) | 0), - (mid = (mid + Math.imul(ah5, bl4)) | 0), - (hi = (hi + Math.imul(ah5, bh4)) | 0), - (lo = (lo + Math.imul(al4, bl5)) | 0), - (mid = (mid + Math.imul(al4, bh5)) | 0), - (mid = (mid + Math.imul(ah4, bl5)) | 0), - (hi = (hi + Math.imul(ah4, bh5)) | 0), - (lo = (lo + Math.imul(al3, bl6)) | 0), - (mid = (mid + Math.imul(al3, bh6)) | 0), - (mid = (mid + Math.imul(ah3, bl6)) | 0), - (hi = (hi + Math.imul(ah3, bh6)) | 0), - (lo = (lo + Math.imul(al2, bl7)) | 0), - (mid = (mid + Math.imul(al2, bh7)) | 0), - (mid = (mid + Math.imul(ah2, bl7)) | 0), - (hi = (hi + Math.imul(ah2, bh7)) | 0), - (lo = (lo + Math.imul(al1, bl8)) | 0), - (mid = (mid + Math.imul(al1, bh8)) | 0), - (mid = (mid + Math.imul(ah1, bl8)) | 0), - (hi = (hi + Math.imul(ah1, bh8)) | 0), - (lo = (lo + Math.imul(al0, bl9)) | 0), - (mid = (mid + Math.imul(al0, bh9)) | 0), - (mid = (mid + Math.imul(ah0, bl9)) | 0), - (hi = (hi + Math.imul(ah0, bh9)) | 0); - var w9 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0), - (w9 &= 67108863), - (lo = Math.imul(al9, bl1)), - (mid = Math.imul(al9, bh1)), - (mid = (mid + Math.imul(ah9, bl1)) | 0), - (hi = Math.imul(ah9, bh1)), - (lo = (lo + Math.imul(al8, bl2)) | 0), - (mid = (mid + Math.imul(al8, bh2)) | 0), - (mid = (mid + Math.imul(ah8, bl2)) | 0), - (hi = (hi + Math.imul(ah8, bh2)) | 0), - (lo = (lo + Math.imul(al7, bl3)) | 0), - (mid = (mid + Math.imul(al7, bh3)) | 0), - (mid = (mid + Math.imul(ah7, bl3)) | 0), - (hi = (hi + Math.imul(ah7, bh3)) | 0), - (lo = (lo + Math.imul(al6, bl4)) | 0), - (mid = (mid + Math.imul(al6, bh4)) | 0), - (mid = (mid + Math.imul(ah6, bl4)) | 0), - (hi = (hi + Math.imul(ah6, bh4)) | 0), - (lo = (lo + Math.imul(al5, bl5)) | 0), - (mid = (mid + Math.imul(al5, bh5)) | 0), - (mid = (mid + Math.imul(ah5, bl5)) | 0), - (hi = (hi + Math.imul(ah5, bh5)) | 0), - (lo = (lo + Math.imul(al4, bl6)) | 0), - (mid = (mid + Math.imul(al4, bh6)) | 0), - (mid = (mid + Math.imul(ah4, bl6)) | 0), - (hi = (hi + Math.imul(ah4, bh6)) | 0), - (lo = (lo + Math.imul(al3, bl7)) | 0), - (mid = (mid + Math.imul(al3, bh7)) | 0), - (mid = (mid + Math.imul(ah3, bl7)) | 0), - (hi = (hi + Math.imul(ah3, bh7)) | 0), - (lo = (lo + Math.imul(al2, bl8)) | 0), - (mid = (mid + Math.imul(al2, bh8)) | 0), - (mid = (mid + Math.imul(ah2, bl8)) | 0), - (hi = (hi + Math.imul(ah2, bh8)) | 0), - (lo = (lo + Math.imul(al1, bl9)) | 0), - (mid = (mid + Math.imul(al1, bh9)) | 0), - (mid = (mid + Math.imul(ah1, bl9)) | 0), - (hi = (hi + Math.imul(ah1, bh9)) | 0); - var w10 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0), - (w10 &= 67108863), - (lo = Math.imul(al9, bl2)), - (mid = Math.imul(al9, bh2)), - (mid = (mid + Math.imul(ah9, bl2)) | 0), - (hi = Math.imul(ah9, bh2)), - (lo = (lo + Math.imul(al8, bl3)) | 0), - (mid = (mid + Math.imul(al8, bh3)) | 0), - (mid = (mid + Math.imul(ah8, bl3)) | 0), - (hi = (hi + Math.imul(ah8, bh3)) | 0), - (lo = (lo + Math.imul(al7, bl4)) | 0), - (mid = (mid + Math.imul(al7, bh4)) | 0), - (mid = (mid + Math.imul(ah7, bl4)) | 0), - (hi = (hi + Math.imul(ah7, bh4)) | 0), - (lo = (lo + Math.imul(al6, bl5)) | 0), - (mid = (mid + Math.imul(al6, bh5)) | 0), - (mid = (mid + Math.imul(ah6, bl5)) | 0), - (hi = (hi + Math.imul(ah6, bh5)) | 0), - (lo = (lo + Math.imul(al5, bl6)) | 0), - (mid = (mid + Math.imul(al5, bh6)) | 0), - (mid = (mid + Math.imul(ah5, bl6)) | 0), - (hi = (hi + Math.imul(ah5, bh6)) | 0), - (lo = (lo + Math.imul(al4, bl7)) | 0), - (mid = (mid + Math.imul(al4, bh7)) | 0), - (mid = (mid + Math.imul(ah4, bl7)) | 0), - (hi = (hi + Math.imul(ah4, bh7)) | 0), - (lo = (lo + Math.imul(al3, bl8)) | 0), - (mid = (mid + Math.imul(al3, bh8)) | 0), - (mid = (mid + Math.imul(ah3, bl8)) | 0), - (hi = (hi + Math.imul(ah3, bh8)) | 0), - (lo = (lo + Math.imul(al2, bl9)) | 0), - (mid = (mid + Math.imul(al2, bh9)) | 0), - (mid = (mid + Math.imul(ah2, bl9)) | 0), - (hi = (hi + Math.imul(ah2, bh9)) | 0); - var w11 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0), - (w11 &= 67108863), - (lo = Math.imul(al9, bl3)), - (mid = Math.imul(al9, bh3)), - (mid = (mid + Math.imul(ah9, bl3)) | 0), - (hi = Math.imul(ah9, bh3)), - (lo = (lo + Math.imul(al8, bl4)) | 0), - (mid = (mid + Math.imul(al8, bh4)) | 0), - (mid = (mid + Math.imul(ah8, bl4)) | 0), - (hi = (hi + Math.imul(ah8, bh4)) | 0), - (lo = (lo + Math.imul(al7, bl5)) | 0), - (mid = (mid + Math.imul(al7, bh5)) | 0), - (mid = (mid + Math.imul(ah7, bl5)) | 0), - (hi = (hi + Math.imul(ah7, bh5)) | 0), - (lo = (lo + Math.imul(al6, bl6)) | 0), - (mid = (mid + Math.imul(al6, bh6)) | 0), - (mid = (mid + Math.imul(ah6, bl6)) | 0), - (hi = (hi + Math.imul(ah6, bh6)) | 0), - (lo = (lo + Math.imul(al5, bl7)) | 0), - (mid = (mid + Math.imul(al5, bh7)) | 0), - (mid = (mid + Math.imul(ah5, bl7)) | 0), - (hi = (hi + Math.imul(ah5, bh7)) | 0), - (lo = (lo + Math.imul(al4, bl8)) | 0), - (mid = (mid + Math.imul(al4, bh8)) | 0), - (mid = (mid + Math.imul(ah4, bl8)) | 0), - (hi = (hi + Math.imul(ah4, bh8)) | 0), - (lo = (lo + Math.imul(al3, bl9)) | 0), - (mid = (mid + Math.imul(al3, bh9)) | 0), - (mid = (mid + Math.imul(ah3, bl9)) | 0), - (hi = (hi + Math.imul(ah3, bh9)) | 0); - var w12 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0), - (w12 &= 67108863), - (lo = Math.imul(al9, bl4)), - (mid = Math.imul(al9, bh4)), - (mid = (mid + Math.imul(ah9, bl4)) | 0), - (hi = Math.imul(ah9, bh4)), - (lo = (lo + Math.imul(al8, bl5)) | 0), - (mid = (mid + Math.imul(al8, bh5)) | 0), - (mid = (mid + Math.imul(ah8, bl5)) | 0), - (hi = (hi + Math.imul(ah8, bh5)) | 0), - (lo = (lo + Math.imul(al7, bl6)) | 0), - (mid = (mid + Math.imul(al7, bh6)) | 0), - (mid = (mid + Math.imul(ah7, bl6)) | 0), - (hi = (hi + Math.imul(ah7, bh6)) | 0), - (lo = (lo + Math.imul(al6, bl7)) | 0), - (mid = (mid + Math.imul(al6, bh7)) | 0), - (mid = (mid + Math.imul(ah6, bl7)) | 0), - (hi = (hi + Math.imul(ah6, bh7)) | 0), - (lo = (lo + Math.imul(al5, bl8)) | 0), - (mid = (mid + Math.imul(al5, bh8)) | 0), - (mid = (mid + Math.imul(ah5, bl8)) | 0), - (hi = (hi + Math.imul(ah5, bh8)) | 0), - (lo = (lo + Math.imul(al4, bl9)) | 0), - (mid = (mid + Math.imul(al4, bh9)) | 0), - (mid = (mid + Math.imul(ah4, bl9)) | 0), - (hi = (hi + Math.imul(ah4, bh9)) | 0); - var w13 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0), - (w13 &= 67108863), - (lo = Math.imul(al9, bl5)), - (mid = Math.imul(al9, bh5)), - (mid = (mid + Math.imul(ah9, bl5)) | 0), - (hi = Math.imul(ah9, bh5)), - (lo = (lo + Math.imul(al8, bl6)) | 0), - (mid = (mid + Math.imul(al8, bh6)) | 0), - (mid = (mid + Math.imul(ah8, bl6)) | 0), - (hi = (hi + Math.imul(ah8, bh6)) | 0), - (lo = (lo + Math.imul(al7, bl7)) | 0), - (mid = (mid + Math.imul(al7, bh7)) | 0), - (mid = (mid + Math.imul(ah7, bl7)) | 0), - (hi = (hi + Math.imul(ah7, bh7)) | 0), - (lo = (lo + Math.imul(al6, bl8)) | 0), - (mid = (mid + Math.imul(al6, bh8)) | 0), - (mid = (mid + Math.imul(ah6, bl8)) | 0), - (hi = (hi + Math.imul(ah6, bh8)) | 0), - (lo = (lo + Math.imul(al5, bl9)) | 0), - (mid = (mid + Math.imul(al5, bh9)) | 0), - (mid = (mid + Math.imul(ah5, bl9)) | 0), - (hi = (hi + Math.imul(ah5, bh9)) | 0); - var w14 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0), - (w14 &= 67108863), - (lo = Math.imul(al9, bl6)), - (mid = Math.imul(al9, bh6)), - (mid = (mid + Math.imul(ah9, bl6)) | 0), - (hi = Math.imul(ah9, bh6)), - (lo = (lo + Math.imul(al8, bl7)) | 0), - (mid = (mid + Math.imul(al8, bh7)) | 0), - (mid = (mid + Math.imul(ah8, bl7)) | 0), - (hi = (hi + Math.imul(ah8, bh7)) | 0), - (lo = (lo + Math.imul(al7, bl8)) | 0), - (mid = (mid + Math.imul(al7, bh8)) | 0), - (mid = (mid + Math.imul(ah7, bl8)) | 0), - (hi = (hi + Math.imul(ah7, bh8)) | 0), - (lo = (lo + Math.imul(al6, bl9)) | 0), - (mid = (mid + Math.imul(al6, bh9)) | 0), - (mid = (mid + Math.imul(ah6, bl9)) | 0), - (hi = (hi + Math.imul(ah6, bh9)) | 0); - var w15 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0), - (w15 &= 67108863), - (lo = Math.imul(al9, bl7)), - (mid = Math.imul(al9, bh7)), - (mid = (mid + Math.imul(ah9, bl7)) | 0), - (hi = Math.imul(ah9, bh7)), - (lo = (lo + Math.imul(al8, bl8)) | 0), - (mid = (mid + Math.imul(al8, bh8)) | 0), - (mid = (mid + Math.imul(ah8, bl8)) | 0), - (hi = (hi + Math.imul(ah8, bh8)) | 0), - (lo = (lo + Math.imul(al7, bl9)) | 0), - (mid = (mid + Math.imul(al7, bh9)) | 0), - (mid = (mid + Math.imul(ah7, bl9)) | 0), - (hi = (hi + Math.imul(ah7, bh9)) | 0); - var w16 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0), - (w16 &= 67108863), - (lo = Math.imul(al9, bl8)), - (mid = Math.imul(al9, bh8)), - (mid = (mid + Math.imul(ah9, bl8)) | 0), - (hi = Math.imul(ah9, bh8)), - (lo = (lo + Math.imul(al8, bl9)) | 0), - (mid = (mid + Math.imul(al8, bh9)) | 0), - (mid = (mid + Math.imul(ah8, bl9)) | 0), - (hi = (hi + Math.imul(ah8, bh9)) | 0); - var w17 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0), - (w17 &= 67108863), - (lo = Math.imul(al9, bl9)), - (mid = Math.imul(al9, bh9)), - (mid = (mid + Math.imul(ah9, bl9)) | 0), - (hi = Math.imul(ah9, bh9)); - var w18 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - return ( - (c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0), - (w18 &= 67108863), - (o[0] = w0), - (o[1] = w1), - (o[2] = w2), - (o[3] = w3), - (o[4] = w4), - (o[5] = w5), - (o[6] = w6), - (o[7] = w7), - (o[8] = w8), - (o[9] = w9), - (o[10] = w10), - (o[11] = w11), - (o[12] = w12), - (o[13] = w13), - (o[14] = w14), - (o[15] = w15), - (o[16] = w16), - (o[17] = w17), - (o[18] = w18), - c !== 0 && ((o[19] = c), out.length++), - out - ); - }; - Math.imul || (comb10MulTo = smallMulTo); - function bigMulTo(self2, num, out) { - (out.negative = num.negative ^ self2.negative), (out.length = self2.length + num.length); - for (var carry = 0, hncarry = 0, k = 0; k < out.length - 1; k++) { - var ncarry = hncarry; - hncarry = 0; - for ( - var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1), j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = k - j, - a = self2.words[i] | 0, - b = num.words[j] | 0, - r = a * b, - lo = r & 67108863; - (ncarry = (ncarry + ((r / 67108864) | 0)) | 0), - (lo = (lo + rword) | 0), - (rword = lo & 67108863), - (ncarry = (ncarry + (lo >>> 26)) | 0), - (hncarry += ncarry >>> 26), - (ncarry &= 67108863); - } - (out.words[k] = rword), (carry = ncarry), (ncarry = hncarry); - } - return carry !== 0 ? (out.words[k] = carry) : out.length--, out._strip(); - } - function jumboMulTo(self2, num, out) { - return bigMulTo(self2, num, out); - } - BN.prototype.mulTo = function (num, out) { - var res, - len = this.length + num.length; - return ( - this.length === 10 && num.length === 10 - ? (res = comb10MulTo(this, num, out)) - : len < 63 - ? (res = smallMulTo(this, num, out)) - : len < 1024 - ? (res = bigMulTo(this, num, out)) - : (res = jumboMulTo(this, num, out)), - res - ); - }; - function FFTM(x, y) { - (this.x = x), (this.y = y); - } - (FFTM.prototype.makeRBT = function (N) { - for (var t = new Array(N), l = BN.prototype._countBits(N) - 1, i = 0; i < N; i++) t[i] = this.revBin(i, l, N); - return t; - }), - (FFTM.prototype.revBin = function (x, l, N) { - if (x === 0 || x === N - 1) return x; - for (var rb = 0, i = 0; i < l; i++) (rb |= (x & 1) << (l - i - 1)), (x >>= 1); - return rb; - }), - (FFTM.prototype.permute = function (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) (rtws[i] = rws[rbt[i]]), (itws[i] = iws[rbt[i]]); - }), - (FFTM.prototype.transform = function (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - for (var s = 1; s < N; s <<= 1) - for ( - var l = s << 1, rtwdf = Math.cos((2 * Math.PI) / l), itwdf = Math.sin((2 * Math.PI) / l), p = 0; - p < N; - p += l - ) - for (var rtwdf_ = rtwdf, itwdf_ = itwdf, j = 0; j < s; j++) { - var re = rtws[p + j], - ie = itws[p + j], - ro = rtws[p + j + s], - io = itws[p + j + s], - rx = rtwdf_ * ro - itwdf_ * io; - (io = rtwdf_ * io + itwdf_ * ro), - (ro = rx), - (rtws[p + j] = re + ro), - (itws[p + j] = ie + io), - (rtws[p + j + s] = re - ro), - (itws[p + j + s] = ie - io), - j !== l && - ((rx = rtwdf * rtwdf_ - itwdf * itwdf_), (itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_), (rtwdf_ = rx)); - } - }), - (FFTM.prototype.guessLen13b = function (n, m) { - var N = Math.max(m, n) | 1, - odd = N & 1, - i = 0; - for (N = (N / 2) | 0; N; N = N >>> 1) i++; - return 1 << (i + 1 + odd); - }), - (FFTM.prototype.conjugate = function (rws, iws, N) { - if (!(N <= 1)) - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - (rws[i] = rws[N - i - 1]), - (rws[N - i - 1] = t), - (t = iws[i]), - (iws[i] = -iws[N - i - 1]), - (iws[N - i - 1] = -t); - } - }), - (FFTM.prototype.normalize13b = function (ws, N) { - for (var carry = 0, i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 8192 + Math.round(ws[2 * i] / N) + carry; - (ws[i] = w & 67108863), w < 67108864 ? (carry = 0) : (carry = (w / 67108864) | 0); - } - return ws; - }), - (FFTM.prototype.convert13b = function (ws, len, rws, N) { - for (var carry = 0, i = 0; i < len; i++) - (carry = carry + (ws[i] | 0)), - (rws[2 * i] = carry & 8191), - (carry = carry >>> 13), - (rws[2 * i + 1] = carry & 8191), - (carry = carry >>> 13); - for (i = 2 * len; i < N; ++i) rws[i] = 0; - assert(carry === 0), assert((carry & -8192) === 0); - }), - (FFTM.prototype.stub = function (N) { - for (var ph = new Array(N), i = 0; i < N; i++) ph[i] = 0; - return ph; - }), - (FFTM.prototype.mulp = function (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length), - rbt = this.makeRBT(N), - _ = this.stub(N), - rws = new Array(N), - rwst = new Array(N), - iwst = new Array(N), - nrws = new Array(N), - nrwst = new Array(N), - niwst = new Array(N), - rmws = out.words; - (rmws.length = N), - this.convert13b(x.words, x.length, rws, N), - this.convert13b(y.words, y.length, nrws, N), - this.transform(rws, _, rwst, iwst, N, rbt), - this.transform(nrws, _, nrwst, niwst, N, rbt); - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - (iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]), (rwst[i] = rx); - } - return ( - this.conjugate(rwst, iwst, N), - this.transform(rwst, iwst, rmws, _, N, rbt), - this.conjugate(rmws, _, N), - this.normalize13b(rmws, N), - (out.negative = x.negative ^ y.negative), - (out.length = x.length + y.length), - out._strip() - ); - }), - (BN.prototype.mul = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), this.mulTo(num, out); - }), - (BN.prototype.mulf = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), jumboMulTo(this, num, out); - }), - (BN.prototype.imul = function (num) { - return this.clone().mulTo(num, this); - }), - (BN.prototype.imuln = function (num) { - var isNegNum = num < 0; - isNegNum && (num = -num), assert(typeof num == "number"), assert(num < 67108864); - for (var carry = 0, i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num, - lo = (w & 67108863) + (carry & 67108863); - (carry >>= 26), (carry += (w / 67108864) | 0), (carry += lo >>> 26), (this.words[i] = lo & 67108863); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), isNegNum ? this.ineg() : this; - }), - (BN.prototype.muln = function (num) { - return this.clone().imuln(num); - }), - (BN.prototype.sqr = function () { - return this.mul(this); - }), - (BN.prototype.isqr = function () { - return this.imul(this.clone()); - }), - (BN.prototype.pow = function (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - for (var res = this, i = 0; i < w.length && w[i] === 0; i++, res = res.sqr()); - if (++i < w.length) for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) w[i] !== 0 && (res = res.mul(q)); - return res; - }), - (BN.prototype.iushln = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26, - carryMask = (67108863 >>> (26 - r)) << (26 - r), - i; - if (r !== 0) { - var carry = 0; - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask, - c = ((this.words[i] | 0) - newCarry) << r; - (this.words[i] = c | carry), (carry = newCarry >>> (26 - r)); - } - carry && ((this.words[i] = carry), this.length++); - } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) this.words[i + s] = this.words[i]; - for (i = 0; i < s; i++) this.words[i] = 0; - this.length += s; - } - return this._strip(); - }), - (BN.prototype.ishln = function (bits) { - return assert(this.negative === 0), this.iushln(bits); - }), - (BN.prototype.iushrn = function (bits, hint, extended) { - assert(typeof bits == "number" && bits >= 0); - var h; - hint ? (h = (hint - (hint % 26)) / 26) : (h = 0); - var r = bits % 26, - s = Math.min((bits - r) / 26, this.length), - mask = 67108863 ^ ((67108863 >>> r) << r), - maskedWords = extended; - if (((h -= s), (h = Math.max(0, h)), maskedWords)) { - for (var i = 0; i < s; i++) maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - if (s !== 0) - if (this.length > s) for (this.length -= s, i = 0; i < this.length; i++) this.words[i] = this.words[i + s]; - else (this.words[0] = 0), (this.length = 1); - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - (this.words[i] = (carry << (26 - r)) | (word >>> r)), (carry = word & mask); - } - return ( - maskedWords && carry !== 0 && (maskedWords.words[maskedWords.length++] = carry), - this.length === 0 && ((this.words[0] = 0), (this.length = 1)), - this._strip() - ); - }), - (BN.prototype.ishrn = function (bits, hint, extended) { - return assert(this.negative === 0), this.iushrn(bits, hint, extended); - }), - (BN.prototype.shln = function (bits) { - return this.clone().ishln(bits); - }), - (BN.prototype.ushln = function (bits) { - return this.clone().iushln(bits); - }), - (BN.prototype.shrn = function (bits) { - return this.clone().ishrn(bits); - }), - (BN.prototype.ushrn = function (bits) { - return this.clone().iushrn(bits); - }), - (BN.prototype.testn = function (bit) { - assert(typeof bit == "number" && bit >= 0); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return !1; - var w = this.words[s]; - return !!(w & q); - }), - (BN.prototype.imaskn = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26; - if ((assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)) return this; - if ((r !== 0 && s++, (this.length = Math.min(s, this.length)), r !== 0)) { - var mask = 67108863 ^ ((67108863 >>> r) << r); - this.words[this.length - 1] &= mask; - } - return this._strip(); - }), - (BN.prototype.maskn = function (bits) { - return this.clone().imaskn(bits); - }), - (BN.prototype.iaddn = function (num) { - return ( - assert(typeof num == "number"), - assert(num < 67108864), - num < 0 - ? this.isubn(-num) - : this.negative !== 0 - ? this.length === 1 && (this.words[0] | 0) <= num - ? ((this.words[0] = num - (this.words[0] | 0)), (this.negative = 0), this) - : ((this.negative = 0), this.isubn(num), (this.negative = 1), this) - : this._iaddn(num) - ); - }), - (BN.prototype._iaddn = function (num) { - this.words[0] += num; - for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) - (this.words[i] -= 67108864), i === this.length - 1 ? (this.words[i + 1] = 1) : this.words[i + 1]++; - return (this.length = Math.max(this.length, i + 1)), this; - }), - (BN.prototype.isubn = function (num) { - if ((assert(typeof num == "number"), assert(num < 67108864), num < 0)) return this.iaddn(-num); - if (this.negative !== 0) return (this.negative = 0), this.iaddn(num), (this.negative = 1), this; - if (((this.words[0] -= num), this.length === 1 && this.words[0] < 0)) - (this.words[0] = -this.words[0]), (this.negative = 1); - else - for (var i = 0; i < this.length && this.words[i] < 0; i++) - (this.words[i] += 67108864), (this.words[i + 1] -= 1); - return this._strip(); - }), - (BN.prototype.addn = function (num) { - return this.clone().iaddn(num); - }), - (BN.prototype.subn = function (num) { - return this.clone().isubn(num); - }), - (BN.prototype.iabs = function () { - return (this.negative = 0), this; - }), - (BN.prototype.abs = function () { - return this.clone().iabs(); - }), - (BN.prototype._ishlnsubmul = function (num, mul, shift) { - var len = num.length + shift, - i; - this._expand(len); - var w, - carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - (w -= right & 67108863), - (carry = (w >> 26) - ((right / 67108864) | 0)), - (this.words[i + shift] = w & 67108863); - } - for (; i < this.length - shift; i++) - (w = (this.words[i + shift] | 0) + carry), (carry = w >> 26), (this.words[i + shift] = w & 67108863); - if (carry === 0) return this._strip(); - for (assert(carry === -1), carry = 0, i = 0; i < this.length; i++) - (w = -(this.words[i] | 0) + carry), (carry = w >> 26), (this.words[i] = w & 67108863); - return (this.negative = 1), this._strip(); - }), - (BN.prototype._wordDiv = function (num, mode) { - var shift = this.length - num.length, - a = this.clone(), - b = num, - bhi = b.words[b.length - 1] | 0, - bhiBits = this._countBits(bhi); - (shift = 26 - bhiBits), - shift !== 0 && ((b = b.ushln(shift)), a.iushln(shift), (bhi = b.words[b.length - 1] | 0)); - var m = a.length - b.length, - q; - if (mode !== "mod") { - (q = new BN(null)), (q.length = m + 1), (q.words = new Array(q.length)); - for (var i = 0; i < q.length; i++) q.words[i] = 0; - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - diff.negative === 0 && ((a = diff), q && (q.words[m] = 1)); - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); - for (qj = Math.min((qj / bhi) | 0, 67108863), a._ishlnsubmul(b, qj, j); a.negative !== 0; ) - qj--, (a.negative = 0), a._ishlnsubmul(b, 1, j), a.isZero() || (a.negative ^= 1); - q && (q.words[j] = qj); - } - return ( - q && q._strip(), - a._strip(), - mode !== "div" && shift !== 0 && a.iushrn(shift), - { - div: q || null, - mod: a, - } - ); - }), - (BN.prototype.divmod = function (num, mode, positive) { - if ((assert(!num.isZero()), this.isZero())) - return { - div: new BN(0), - mod: new BN(0), - }; - var div, mod, res; - return this.negative !== 0 && num.negative === 0 - ? ((res = this.neg().divmod(num, mode)), - mode !== "mod" && (div = res.div.neg()), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.iadd(num)), - { - div, - mod, - }) - : this.negative === 0 && num.negative !== 0 - ? ((res = this.divmod(num.neg(), mode)), - mode !== "mod" && (div = res.div.neg()), - { - div, - mod: res.mod, - }) - : (this.negative & num.negative) !== 0 - ? ((res = this.neg().divmod(num.neg(), mode)), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.isub(num)), - { - div: res.div, - mod, - }) - : num.length > this.length || this.cmp(num) < 0 - ? { - div: new BN(0), - mod: this, - } - : num.length === 1 - ? mode === "div" - ? { - div: this.divn(num.words[0]), - mod: null, - } - : mode === "mod" - ? { - div: null, - mod: new BN(this.modrn(num.words[0])), - } - : { - div: this.divn(num.words[0]), - mod: new BN(this.modrn(num.words[0])), - } - : this._wordDiv(num, mode); - }), - (BN.prototype.div = function (num) { - return this.divmod(num, "div", !1).div; - }), - (BN.prototype.mod = function (num) { - return this.divmod(num, "mod", !1).mod; - }), - (BN.prototype.umod = function (num) { - return this.divmod(num, "mod", !0).mod; - }), - (BN.prototype.divRound = function (num) { - var dm = this.divmod(num); - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, - half = num.ushrn(1), - r2 = num.andln(1), - cmp = mod.cmp(half); - return cmp < 0 || (r2 === 1 && cmp === 0) - ? dm.div - : dm.div.negative !== 0 - ? dm.div.isubn(1) - : dm.div.iaddn(1); - }), - (BN.prototype.modrn = function (num) { - var isNegNum = num < 0; - isNegNum && (num = -num), assert(num <= 67108863); - for (var p = (1 << 26) % num, acc = 0, i = this.length - 1; i >= 0; i--) - acc = (p * acc + (this.words[i] | 0)) % num; - return isNegNum ? -acc : acc; - }), - (BN.prototype.modn = function (num) { - return this.modrn(num); - }), - (BN.prototype.idivn = function (num) { - var isNegNum = num < 0; - isNegNum && (num = -num), assert(num <= 67108863); - for (var carry = 0, i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 67108864; - (this.words[i] = (w / num) | 0), (carry = w % num); - } - return this._strip(), isNegNum ? this.ineg() : this; - }), - (BN.prototype.divn = function (num) { - return this.clone().idivn(num); - }), - (BN.prototype.egcd = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var x = this, - y = p.clone(); - x.negative !== 0 ? (x = x.umod(p)) : (x = x.clone()); - for (var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0; x.isEven() && y.isEven(); ) - x.iushrn(1), y.iushrn(1), ++g; - for (var yp = y.clone(), xp = x.clone(); !x.isZero(); ) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) - for (x.iushrn(i); i-- > 0; ) - (A.isOdd() || B.isOdd()) && (A.iadd(yp), B.isub(xp)), A.iushrn(1), B.iushrn(1); - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) - for (y.iushrn(j); j-- > 0; ) - (C.isOdd() || D.isOdd()) && (C.iadd(yp), D.isub(xp)), C.iushrn(1), D.iushrn(1); - x.cmp(y) >= 0 ? (x.isub(y), A.isub(C), B.isub(D)) : (y.isub(x), C.isub(A), D.isub(B)); - } - return { - a: C, - b: D, - gcd: y.iushln(g), - }; - }), - (BN.prototype._invmp = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var a = this, - b = p.clone(); - a.negative !== 0 ? (a = a.umod(p)) : (a = a.clone()); - for (var x1 = new BN(1), x2 = new BN(0), delta = b.clone(); a.cmpn(1) > 0 && b.cmpn(1) > 0; ) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) for (a.iushrn(i); i-- > 0; ) x1.isOdd() && x1.iadd(delta), x1.iushrn(1); - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) for (b.iushrn(j); j-- > 0; ) x2.isOdd() && x2.iadd(delta), x2.iushrn(1); - a.cmp(b) >= 0 ? (a.isub(b), x1.isub(x2)) : (b.isub(a), x2.isub(x1)); - } - var res; - return a.cmpn(1) === 0 ? (res = x1) : (res = x2), res.cmpn(0) < 0 && res.iadd(p), res; - }), - (BN.prototype.gcd = function (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(), - b = num.clone(); - (a.negative = 0), (b.negative = 0); - for (var shift = 0; a.isEven() && b.isEven(); shift++) a.iushrn(1), b.iushrn(1); - do { - for (; a.isEven(); ) a.iushrn(1); - for (; b.isEven(); ) b.iushrn(1); - var r = a.cmp(b); - if (r < 0) { - var t = a; - (a = b), (b = t); - } else if (r === 0 || b.cmpn(1) === 0) break; - a.isub(b); - } while (!0); - return b.iushln(shift); - }), - (BN.prototype.invm = function (num) { - return this.egcd(num).a.umod(num); - }), - (BN.prototype.isEven = function () { - return (this.words[0] & 1) === 0; - }), - (BN.prototype.isOdd = function () { - return (this.words[0] & 1) === 1; - }), - (BN.prototype.andln = function (num) { - return this.words[0] & num; - }), - (BN.prototype.bincn = function (bit) { - assert(typeof bit == "number"); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return this._expand(s + 1), (this.words[s] |= q), this; - for (var carry = q, i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - (w += carry), (carry = w >>> 26), (w &= 67108863), (this.words[i] = w); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.isZero = function () { - return this.length === 1 && this.words[0] === 0; - }), - (BN.prototype.cmpn = function (num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - this._strip(); - var res; - if (this.length > 1) res = 1; - else { - negative && (num = -num), assert(num <= 67108863, "Number is too big"); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.cmp = function (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.ucmp = function (num) { - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - for (var res = 0, i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0, - b = num.words[i] | 0; - if (a !== b) { - a < b ? (res = -1) : a > b && (res = 1); - break; - } - } - return res; - }), - (BN.prototype.gtn = function (num) { - return this.cmpn(num) === 1; - }), - (BN.prototype.gt = function (num) { - return this.cmp(num) === 1; - }), - (BN.prototype.gten = function (num) { - return this.cmpn(num) >= 0; - }), - (BN.prototype.gte = function (num) { - return this.cmp(num) >= 0; - }), - (BN.prototype.ltn = function (num) { - return this.cmpn(num) === -1; - }), - (BN.prototype.lt = function (num) { - return this.cmp(num) === -1; - }), - (BN.prototype.lten = function (num) { - return this.cmpn(num) <= 0; - }), - (BN.prototype.lte = function (num) { - return this.cmp(num) <= 0; - }), - (BN.prototype.eqn = function (num) { - return this.cmpn(num) === 0; - }), - (BN.prototype.eq = function (num) { - return this.cmp(num) === 0; - }), - (BN.red = function (num) { - return new Red(num); - }), - (BN.prototype.toRed = function (ctx) { - return ( - assert(!this.red, "Already a number in reduction context"), - assert(this.negative === 0, "red works only with positives"), - ctx.convertTo(this)._forceRed(ctx) - ); - }), - (BN.prototype.fromRed = function () { - return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }), - (BN.prototype._forceRed = function (ctx) { - return (this.red = ctx), this; - }), - (BN.prototype.forceRed = function (ctx) { - return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx); - }), - (BN.prototype.redAdd = function (num) { - return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num); - }), - (BN.prototype.redIAdd = function (num) { - return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num); - }), - (BN.prototype.redSub = function (num) { - return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num); - }), - (BN.prototype.redISub = function (num) { - return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num); - }), - (BN.prototype.redShl = function (num) { - return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num); - }), - (BN.prototype.redMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.mul(this, num) - ); - }), - (BN.prototype.redIMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.imul(this, num) - ); - }), - (BN.prototype.redSqr = function () { - return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }), - (BN.prototype.redISqr = function () { - return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }), - (BN.prototype.redSqrt = function () { - return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }), - (BN.prototype.redInvm = function () { - return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); - }), - (BN.prototype.redNeg = function () { - return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); - }), - (BN.prototype.redPow = function (num) { - return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num); - }); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null, - }; - function MPrime(name, p) { - (this.name = name), - (this.p = new BN(p, 16)), - (this.n = this.p.bitLength()), - (this.k = new BN(1).iushln(this.n).isub(this.p)), - (this.tmp = this._tmp()); - } - (MPrime.prototype._tmp = function () { - var tmp = new BN(null); - return (tmp.words = new Array(Math.ceil(this.n / 13))), tmp; - }), - (MPrime.prototype.ireduce = function (num) { - var r = num, - rlen; - do this.split(r, this.tmp), (r = this.imulK(r)), (r = r.iadd(this.tmp)), (rlen = r.bitLength()); - while (rlen > this.n); - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - return ( - cmp === 0 - ? ((r.words[0] = 0), (r.length = 1)) - : cmp > 0 - ? r.isub(this.p) - : r.strip !== void 0 - ? r.strip() - : r._strip(), - r - ); - }), - (MPrime.prototype.split = function (input, out) { - input.iushrn(this.n, 0, out); - }), - (MPrime.prototype.imulK = function (num) { - return num.imul(this.k); - }); - function K256() { - MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - inherits(K256, MPrime), - (K256.prototype.split = function (input, output) { - for (var mask = 4194303, outLen = Math.min(input.length, 9), i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - if (((output.length = outLen), input.length <= 9)) { - (input.words[0] = 0), (input.length = 1); - return; - } - var prev = input.words[9]; - for (output.words[output.length++] = prev & mask, i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - (input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22)), (prev = next); - } - (prev >>>= 22), - (input.words[i - 10] = prev), - prev === 0 && input.length > 10 ? (input.length -= 10) : (input.length -= 9); - }), - (K256.prototype.imulK = function (num) { - (num.words[num.length] = 0), (num.words[num.length + 1] = 0), (num.length += 2); - for (var lo = 0, i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - (lo += w * 977), (num.words[i] = lo & 67108863), (lo = w * 64 + ((lo / 67108864) | 0)); - } - return ( - num.words[num.length - 1] === 0 && (num.length--, num.words[num.length - 1] === 0 && num.length--), num - ); - }); - function P224() { - MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - inherits(P224, MPrime); - function P192() { - MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - inherits(P192, MPrime); - function P25519() { - MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - inherits(P25519, MPrime), - (P25519.prototype.imulK = function (num) { - for (var carry = 0, i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 19 + carry, - lo = hi & 67108863; - (hi >>>= 26), (num.words[i] = lo), (carry = hi); - } - return carry !== 0 && (num.words[num.length++] = carry), num; - }), - (BN._prime = function (name) { - if (primes[name]) return primes[name]; - var prime2; - if (name === "k256") prime2 = new K256(); - else if (name === "p224") prime2 = new P224(); - else if (name === "p192") prime2 = new P192(); - else if (name === "p25519") prime2 = new P25519(); - else throw new Error("Unknown prime " + name); - return (primes[name] = prime2), prime2; - }); - function Red(m) { - if (typeof m == "string") { - var prime = BN._prime(m); - (this.m = prime.p), (this.prime = prime); - } else assert(m.gtn(1), "modulus must be greater than 1"), (this.m = m), (this.prime = null); - } - (Red.prototype._verify1 = function (a) { - assert(a.negative === 0, "red works only with positives"), assert(a.red, "red works only with red numbers"); - }), - (Red.prototype._verify2 = function (a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"), - assert(a.red && a.red === b.red, "red works only with red numbers"); - }), - (Red.prototype.imod = function (a) { - return this.prime ? this.prime.ireduce(a)._forceRed(this) : (move(a, a.umod(this.m)._forceRed(this)), a); - }), - (Red.prototype.neg = function (a) { - return a.isZero() ? a.clone() : this.m.sub(a)._forceRed(this); - }), - (Red.prototype.add = function (a, b) { - this._verify2(a, b); - var res = a.add(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res._forceRed(this); - }), - (Red.prototype.iadd = function (a, b) { - this._verify2(a, b); - var res = a.iadd(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res; - }), - (Red.prototype.sub = function (a, b) { - this._verify2(a, b); - var res = a.sub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res._forceRed(this); - }), - (Red.prototype.isub = function (a, b) { - this._verify2(a, b); - var res = a.isub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res; - }), - (Red.prototype.shl = function (a, num) { - return this._verify1(a), this.imod(a.ushln(num)); - }), - (Red.prototype.imul = function (a, b) { - return this._verify2(a, b), this.imod(a.imul(b)); - }), - (Red.prototype.mul = function (a, b) { - return this._verify2(a, b), this.imod(a.mul(b)); - }), - (Red.prototype.isqr = function (a) { - return this.imul(a, a.clone()); - }), - (Red.prototype.sqr = function (a) { - return this.mul(a, a); - }), - (Red.prototype.sqrt = function (a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - if ((assert(mod3 % 2 === 1), mod3 === 3)) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - for (var q = this.m.subn(1), s = 0; !q.isZero() && q.andln(1) === 0; ) s++, q.iushrn(1); - assert(!q.isZero()); - var one = new BN(1).toRed(this), - nOne = one.redNeg(), - lpow = this.m.subn(1).iushrn(1), - z = this.m.bitLength(); - for (z = new BN(2 * z * z).toRed(this); this.pow(z, lpow).cmp(nOne) !== 0; ) z.redIAdd(nOne); - for ( - var c = this.pow(z, q), r = this.pow(a, q.addn(1).iushrn(1)), t = this.pow(a, q), m = s; - t.cmp(one) !== 0; - - ) { - for (var tmp = t, i = 0; tmp.cmp(one) !== 0; i++) tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - (r = r.redMul(b)), (c = b.redSqr()), (t = t.redMul(c)), (m = i); - } - return r; - }), - (Red.prototype.invm = function (a) { - var inv = a._invmp(this.m); - return inv.negative !== 0 ? ((inv.negative = 0), this.imod(inv).redNeg()) : this.imod(inv); - }), - (Red.prototype.pow = function (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4, - wnd = new Array(1 << windowSize); - (wnd[0] = new BN(1).toRed(this)), (wnd[1] = a); - for (var i = 2; i < wnd.length; i++) wnd[i] = this.mul(wnd[i - 1], a); - var res = wnd[0], - current = 0, - currentLen = 0, - start = num.bitLength() % 26; - for (start === 0 && (start = 26), i = num.length - 1; i >= 0; i--) { - for (var word = num.words[i], j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if ((res !== wnd[0] && (res = this.sqr(res)), bit === 0 && current === 0)) { - currentLen = 0; - continue; - } - (current <<= 1), - (current |= bit), - currentLen++, - !(currentLen !== windowSize && (i !== 0 || j !== 0)) && - ((res = this.mul(res, wnd[current])), (currentLen = 0), (current = 0)); - } - start = 26; - } - return res; - }), - (Red.prototype.convertTo = function (num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }), - (Red.prototype.convertFrom = function (num) { - var res = num.clone(); - return (res.red = null), res; - }), - (BN.mont = function (num) { - return new Mont(num); - }); - function Mont(m) { - Red.call(this, m), - (this.shift = this.m.bitLength()), - this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), - (this.r = new BN(1).iushln(this.shift)), - (this.r2 = this.imod(this.r.sqr())), - (this.rinv = this.r._invmp(this.m)), - (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), - (this.minv = this.minv.umod(this.r)), - (this.minv = this.r.sub(this.minv)); - } - inherits(Mont, Red), - (Mont.prototype.convertTo = function (num) { - return this.imod(num.ushln(this.shift)); - }), - (Mont.prototype.convertFrom = function (num) { - var r = this.imod(num.mul(this.rinv)); - return (r.red = null), r; - }), - (Mont.prototype.imul = function (a, b) { - if (a.isZero() || b.isZero()) return (a.words[0] = 0), (a.length = 1), a; - var t = a.imul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.mul = function (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.invm = function (a) { - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }); - })(typeof module > "u" || module, exports); - }, -}); - -// node_modules/browserify-rsa/index.js -var require_browserify_rsa = __commonJS({ - "node_modules/browserify-rsa/index.js"(exports, module) { - var BN = require_bn3(), - randomBytes = require_browser(); - function blind(priv) { - var r = getr(priv), - blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed(); - return { blinder, unblinder: r.invm(priv.modulus) }; - } - function getr(priv) { - var len = priv.modulus.byteLength(), - r; - do r = new BN(randomBytes(len)); - while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)); - return r; - } - function crt(msg, priv) { - var blinds = blind(priv), - len = priv.modulus.byteLength(), - blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus), - c1 = blinded.toRed(BN.mont(priv.prime1)), - c2 = blinded.toRed(BN.mont(priv.prime2)), - qinv = priv.coefficient, - p = priv.prime1, - q = priv.prime2, - m1 = c1.redPow(priv.exponent1).fromRed(), - m2 = c2.redPow(priv.exponent2).fromRed(), - h = m1.isub(m2).imul(qinv).umod(p).imul(q); - return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, "be", len); - } - crt.getr = getr; - module.exports = crt; - }, -}); - -// node_modules/elliptic/package.json -var require_package = __commonJS({ - "node_modules/elliptic/package.json"(exports, module) { - module.exports = { - name: "elliptic", - version: "6.5.4", - description: "EC cryptography", - main: "lib/elliptic.js", - files: ["lib"], - scripts: { - lint: "eslint lib test", - "lint:fix": "npm run lint -- --fix", - unit: "istanbul test _mocha --reporter=spec test/index.js", - test: "npm run lint && npm run unit", - version: "grunt dist && git add dist/", - }, - repository: { - type: "git", - url: "git@github.com:indutny/elliptic", - }, - keywords: ["EC", "Elliptic", "curve", "Cryptography"], - author: "Fedor Indutny ", - license: "MIT", - bugs: { - url: "https://github.com/indutny/elliptic/issues", - }, - homepage: "https://github.com/indutny/elliptic", - devDependencies: { - brfs: "^2.0.2", - coveralls: "^3.1.0", - eslint: "^7.6.0", - grunt: "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - istanbul: "^0.4.5", - mocha: "^8.0.1", - }, - dependencies: { - "bn.js": "^4.11.9", - brorand: "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - inherits: "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1", - }, - }; - }, -}); - -// node_modules/elliptic/node_modules/bn.js/lib/bn.js -var require_bn4 = __commonJS({ - "node_modules/elliptic/node_modules/bn.js/lib/bn.js"(exports, module) { - (function (module2, exports2) { - "use strict"; - function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); - } - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - (TempCtor.prototype = superCtor.prototype), - (ctor.prototype = new TempCtor()), - (ctor.prototype.constructor = ctor); - } - function BN(number, base, endian) { - if (BN.isBN(number)) return number; - (this.negative = 0), - (this.words = null), - (this.length = 0), - (this.red = null), - number !== null && - ((base === "le" || base === "be") && ((endian = base), (base = 10)), - this._init(number || 0, base || 10, endian || "be")); - } - typeof module2 == "object" ? (module2.exports = BN) : (exports2.BN = BN), (BN.BN = BN), (BN.wordSize = 26); - var Buffer2 = Buffer; - (BN.isBN = function (num) { - return num instanceof BN - ? !0 - : num !== null && - typeof num == "object" && - num.constructor.wordSize === BN.wordSize && - Array.isArray(num.words); - }), - (BN.max = function (left, right) { - return left.cmp(right) > 0 ? left : right; - }), - (BN.min = function (left, right) { - return left.cmp(right) < 0 ? left : right; - }), - (BN.prototype._init = function (number, base, endian) { - if (typeof number == "number") return this._initNumber(number, base, endian); - if (typeof number == "object") return this._initArray(number, base, endian); - base === "hex" && (base = 16), - assert(base === (base | 0) && base >= 2 && base <= 36), - (number = number.toString().replace(/\s+/g, "")); - var start = 0; - number[0] === "-" && (start++, (this.negative = 1)), - start < number.length && - (base === 16 - ? this._parseHex(number, start, endian) - : (this._parseBase(number, base, start), - endian === "le" && this._initArray(this.toArray(), base, endian))); - }), - (BN.prototype._initNumber = function (number, base, endian) { - number < 0 && ((this.negative = 1), (number = -number)), - number < 67108864 - ? ((this.words = [number & 67108863]), (this.length = 1)) - : number < 4503599627370496 - ? ((this.words = [number & 67108863, (number / 67108864) & 67108863]), (this.length = 2)) - : (assert(number < 9007199254740992), - (this.words = [number & 67108863, (number / 67108864) & 67108863, 1]), - (this.length = 3)), - endian === "le" && this._initArray(this.toArray(), base, endian); - }), - (BN.prototype._initArray = function (number, base, endian) { - if ((assert(typeof number.length == "number"), number.length <= 0)) - return (this.words = [0]), (this.length = 1), this; - (this.length = Math.ceil(number.length / 3)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var j, - w, - off = 0; - if (endian === "be") - for (i = number.length - 1, j = 0; i >= 0; i -= 3) - (w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - else if (endian === "le") - for (i = 0, j = 0; i < number.length; i += 3) - (w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - return this.strip(); - }); - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - return c >= 65 && c <= 70 ? c - 55 : c >= 97 && c <= 102 ? c - 87 : (c - 48) & 15; - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - return index - 1 >= lowerBound && (r |= parseHex4Bits(string, index - 1) << 4), r; - } - BN.prototype._parseHex = function (number, start, endian) { - (this.length = Math.ceil((number.length - start) / 6)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var off = 0, - j = 0, - w; - if (endian === "be") - for (i = number.length - 1; i >= start; i -= 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - } - this.strip(); - }; - function parseBase(str, start, end, mul) { - for (var r = 0, len = Math.min(str.length, end), i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - (r *= mul), c >= 49 ? (r += c - 49 + 10) : c >= 17 ? (r += c - 17 + 10) : (r += c); - } - return r; - } - (BN.prototype._parseBase = function (number, base, start) { - (this.words = [0]), (this.length = 1); - for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base) limbLen++; - limbLen--, (limbPow = (limbPow / base) | 0); - for ( - var total = number.length - start, - mod = total % limbLen, - end = Math.min(total, total - mod) + start, - word = 0, - i = start; - i < end; - i += limbLen - ) - (word = parseBase(number, i, i + limbLen, base)), - this.imuln(limbPow), - this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - if (mod !== 0) { - var pow = 1; - for (word = parseBase(number, i, number.length, base), i = 0; i < mod; i++) pow *= base; - this.imuln(pow), this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - } - this.strip(); - }), - (BN.prototype.copy = function (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) dest.words[i] = this.words[i]; - (dest.length = this.length), (dest.negative = this.negative), (dest.red = this.red); - }), - (BN.prototype.clone = function () { - var r = new BN(null); - return this.copy(r), r; - }), - (BN.prototype._expand = function (size) { - for (; this.length < size; ) this.words[this.length++] = 0; - return this; - }), - (BN.prototype.strip = function () { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; - return this._normSign(); - }), - (BN.prototype._normSign = function () { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }), - (BN.prototype.inspect = function () { - return (this.red ? ""; - }); - var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000", - ], - groupSizes = [ - 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, - ], - groupBases = [ - 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, - 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, - 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, - 60466176, - ]; - (BN.prototype.toString = function (base, padding) { - (base = base || 10), (padding = padding | 0 || 1); - var out; - if (base === 16 || base === "hex") { - out = ""; - for (var off = 0, carry = 0, i = 0; i < this.length; i++) { - var w = this.words[i], - word = (((w << off) | carry) & 16777215).toString(16); - (carry = (w >>> (24 - off)) & 16777215), - carry !== 0 || i !== this.length - 1 ? (out = zeros[6 - word.length] + word + out) : (out = word + out), - (off += 2), - off >= 26 && ((off -= 26), i--); - } - for (carry !== 0 && (out = carry.toString(16) + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - if (base === (base | 0) && base >= 2 && base <= 36) { - var groupSize = groupSizes[base], - groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - for (c.negative = 0; !c.isZero(); ) { - var r = c.modn(groupBase).toString(base); - (c = c.idivn(groupBase)), c.isZero() ? (out = r + out) : (out = zeros[groupSize - r.length] + r + out); - } - for (this.isZero() && (out = "0" + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - assert(!1, "Base should be between 2 and 36"); - }), - (BN.prototype.toNumber = function () { - var ret = this.words[0]; - return ( - this.length === 2 - ? (ret += this.words[1] * 67108864) - : this.length === 3 && this.words[2] === 1 - ? (ret += 4503599627370496 + this.words[1] * 67108864) - : this.length > 2 && assert(!1, "Number can only safely store up to 53 bits"), - this.negative !== 0 ? -ret : ret - ); - }), - (BN.prototype.toJSON = function () { - return this.toString(16); - }), - (BN.prototype.toBuffer = function (endian, length) { - return assert(typeof Buffer2 < "u"), this.toArrayLike(Buffer2, endian, length); - }), - (BN.prototype.toArray = function (endian, length) { - return this.toArrayLike(Array, endian, length); - }), - (BN.prototype.toArrayLike = function (ArrayType, endian, length) { - var byteLength = this.byteLength(), - reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"), - assert(reqLength > 0, "Requested array length <= 0"), - this.strip(); - var littleEndian = endian === "le", - res = new ArrayType(reqLength), - b, - i, - q = this.clone(); - if (littleEndian) { - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[i] = b); - for (; i < reqLength; i++) res[i] = 0; - } else { - for (i = 0; i < reqLength - byteLength; i++) res[i] = 0; - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[reqLength - i - 1] = b); - } - return res; - }), - Math.clz32 - ? (BN.prototype._countBits = function (w) { - return 32 - Math.clz32(w); - }) - : (BN.prototype._countBits = function (w) { - var t = w, - r = 0; - return ( - t >= 4096 && ((r += 13), (t >>>= 13)), - t >= 64 && ((r += 7), (t >>>= 7)), - t >= 8 && ((r += 4), (t >>>= 4)), - t >= 2 && ((r += 2), (t >>>= 2)), - r + t - ); - }), - (BN.prototype._zeroBits = function (w) { - if (w === 0) return 26; - var t = w, - r = 0; - return ( - (t & 8191) === 0 && ((r += 13), (t >>>= 13)), - (t & 127) === 0 && ((r += 7), (t >>>= 7)), - (t & 15) === 0 && ((r += 4), (t >>>= 4)), - (t & 3) === 0 && ((r += 2), (t >>>= 2)), - (t & 1) === 0 && r++, - r - ); - }), - (BN.prototype.bitLength = function () { - var w = this.words[this.length - 1], - hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }); - function toBitArray(num) { - for (var w = new Array(num.bitLength()), bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0, - wbit = bit % 26; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - return w; - } - (BN.prototype.zeroBits = function () { - if (this.isZero()) return 0; - for (var r = 0, i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - if (((r += b), b !== 26)) break; - } - return r; - }), - (BN.prototype.byteLength = function () { - return Math.ceil(this.bitLength() / 8); - }), - (BN.prototype.toTwos = function (width) { - return this.negative !== 0 ? this.abs().inotn(width).iaddn(1) : this.clone(); - }), - (BN.prototype.fromTwos = function (width) { - return this.testn(width - 1) ? this.notn(width).iaddn(1).ineg() : this.clone(); - }), - (BN.prototype.isNeg = function () { - return this.negative !== 0; - }), - (BN.prototype.neg = function () { - return this.clone().ineg(); - }), - (BN.prototype.ineg = function () { - return this.isZero() || (this.negative ^= 1), this; - }), - (BN.prototype.iuor = function (num) { - for (; this.length < num.length; ) this.words[this.length++] = 0; - for (var i = 0; i < num.length; i++) this.words[i] = this.words[i] | num.words[i]; - return this.strip(); - }), - (BN.prototype.ior = function (num) { - return assert((this.negative | num.negative) === 0), this.iuor(num); - }), - (BN.prototype.or = function (num) { - return this.length > num.length ? this.clone().ior(num) : num.clone().ior(this); - }), - (BN.prototype.uor = function (num) { - return this.length > num.length ? this.clone().iuor(num) : num.clone().iuor(this); - }), - (BN.prototype.iuand = function (num) { - var b; - this.length > num.length ? (b = num) : (b = this); - for (var i = 0; i < b.length; i++) this.words[i] = this.words[i] & num.words[i]; - return (this.length = b.length), this.strip(); - }), - (BN.prototype.iand = function (num) { - return assert((this.negative | num.negative) === 0), this.iuand(num); - }), - (BN.prototype.and = function (num) { - return this.length > num.length ? this.clone().iand(num) : num.clone().iand(this); - }), - (BN.prototype.uand = function (num) { - return this.length > num.length ? this.clone().iuand(num) : num.clone().iuand(this); - }), - (BN.prototype.iuxor = function (num) { - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var i = 0; i < b.length; i++) this.words[i] = a.words[i] ^ b.words[i]; - if (this !== a) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = a.length), this.strip(); - }), - (BN.prototype.ixor = function (num) { - return assert((this.negative | num.negative) === 0), this.iuxor(num); - }), - (BN.prototype.xor = function (num) { - return this.length > num.length ? this.clone().ixor(num) : num.clone().ixor(this); - }), - (BN.prototype.uxor = function (num) { - return this.length > num.length ? this.clone().iuxor(num) : num.clone().iuxor(this); - }), - (BN.prototype.inotn = function (width) { - assert(typeof width == "number" && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0, - bitsLeft = width % 26; - this._expand(bytesNeeded), bitsLeft > 0 && bytesNeeded--; - for (var i = 0; i < bytesNeeded; i++) this.words[i] = ~this.words[i] & 67108863; - return bitsLeft > 0 && (this.words[i] = ~this.words[i] & (67108863 >> (26 - bitsLeft))), this.strip(); - }), - (BN.prototype.notn = function (width) { - return this.clone().inotn(width); - }), - (BN.prototype.setn = function (bit, val) { - assert(typeof bit == "number" && bit >= 0); - var off = (bit / 26) | 0, - wbit = bit % 26; - return ( - this._expand(off + 1), - val - ? (this.words[off] = this.words[off] | (1 << wbit)) - : (this.words[off] = this.words[off] & ~(1 << wbit)), - this.strip() - ); - }), - (BN.prototype.iadd = function (num) { - var r; - if (this.negative !== 0 && num.negative === 0) - return (this.negative = 0), (r = this.isub(num)), (this.negative ^= 1), this._normSign(); - if (this.negative === 0 && num.negative !== 0) - return (num.negative = 0), (r = this.isub(num)), (num.negative = 1), r._normSign(); - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) + (b.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - if (((this.length = a.length), carry !== 0)) (this.words[this.length] = carry), this.length++; - else if (a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return this; - }), - (BN.prototype.add = function (num) { - var res; - return num.negative !== 0 && this.negative === 0 - ? ((num.negative = 0), (res = this.sub(num)), (num.negative ^= 1), res) - : num.negative === 0 && this.negative !== 0 - ? ((this.negative = 0), (res = num.sub(this)), (this.negative = 1), res) - : this.length > num.length - ? this.clone().iadd(num) - : num.clone().iadd(this); - }), - (BN.prototype.isub = function (num) { - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - return (num.negative = 1), r._normSign(); - } else if (this.negative !== 0) - return (this.negative = 0), this.iadd(num), (this.negative = 1), this._normSign(); - var cmp = this.cmp(num); - if (cmp === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; - var a, b; - cmp > 0 ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) - (b.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - if (carry === 0 && i < a.length && a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = Math.max(this.length, i)), a !== this && (this.negative = 1), this.strip(); - }), - (BN.prototype.sub = function (num) { - return this.clone().isub(num); - }); - function smallMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - var len = (self2.length + num.length) | 0; - (out.length = len), (len = (len - 1) | 0); - var a = self2.words[0] | 0, - b = num.words[0] | 0, - r = a * b, - lo = r & 67108863, - carry = (r / 67108864) | 0; - out.words[0] = lo; - for (var k = 1; k < len; k++) { - for ( - var ncarry = carry >>> 26, - rword = carry & 67108863, - maxJ = Math.min(k, num.length - 1), - j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = (k - j) | 0; - (a = self2.words[i] | 0), - (b = num.words[j] | 0), - (r = a * b + rword), - (ncarry += (r / 67108864) | 0), - (rword = r & 67108863); - } - (out.words[k] = rword | 0), (carry = ncarry | 0); - } - return carry !== 0 ? (out.words[k] = carry | 0) : out.length--, out.strip(); - } - var comb10MulTo = function (self2, num, out) { - var a = self2.words, - b = num.words, - o = out.words, - c = 0, - lo, - mid, - hi, - a0 = a[0] | 0, - al0 = a0 & 8191, - ah0 = a0 >>> 13, - a1 = a[1] | 0, - al1 = a1 & 8191, - ah1 = a1 >>> 13, - a2 = a[2] | 0, - al2 = a2 & 8191, - ah2 = a2 >>> 13, - a3 = a[3] | 0, - al3 = a3 & 8191, - ah3 = a3 >>> 13, - a4 = a[4] | 0, - al4 = a4 & 8191, - ah4 = a4 >>> 13, - a5 = a[5] | 0, - al5 = a5 & 8191, - ah5 = a5 >>> 13, - a6 = a[6] | 0, - al6 = a6 & 8191, - ah6 = a6 >>> 13, - a7 = a[7] | 0, - al7 = a7 & 8191, - ah7 = a7 >>> 13, - a8 = a[8] | 0, - al8 = a8 & 8191, - ah8 = a8 >>> 13, - a9 = a[9] | 0, - al9 = a9 & 8191, - ah9 = a9 >>> 13, - b0 = b[0] | 0, - bl0 = b0 & 8191, - bh0 = b0 >>> 13, - b1 = b[1] | 0, - bl1 = b1 & 8191, - bh1 = b1 >>> 13, - b2 = b[2] | 0, - bl2 = b2 & 8191, - bh2 = b2 >>> 13, - b3 = b[3] | 0, - bl3 = b3 & 8191, - bh3 = b3 >>> 13, - b4 = b[4] | 0, - bl4 = b4 & 8191, - bh4 = b4 >>> 13, - b5 = b[5] | 0, - bl5 = b5 & 8191, - bh5 = b5 >>> 13, - b6 = b[6] | 0, - bl6 = b6 & 8191, - bh6 = b6 >>> 13, - b7 = b[7] | 0, - bl7 = b7 & 8191, - bh7 = b7 >>> 13, - b8 = b[8] | 0, - bl8 = b8 & 8191, - bh8 = b8 >>> 13, - b9 = b[9] | 0, - bl9 = b9 & 8191, - bh9 = b9 >>> 13; - (out.negative = self2.negative ^ num.negative), - (out.length = 19), - (lo = Math.imul(al0, bl0)), - (mid = Math.imul(al0, bh0)), - (mid = (mid + Math.imul(ah0, bl0)) | 0), - (hi = Math.imul(ah0, bh0)); - var w0 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0), - (w0 &= 67108863), - (lo = Math.imul(al1, bl0)), - (mid = Math.imul(al1, bh0)), - (mid = (mid + Math.imul(ah1, bl0)) | 0), - (hi = Math.imul(ah1, bh0)), - (lo = (lo + Math.imul(al0, bl1)) | 0), - (mid = (mid + Math.imul(al0, bh1)) | 0), - (mid = (mid + Math.imul(ah0, bl1)) | 0), - (hi = (hi + Math.imul(ah0, bh1)) | 0); - var w1 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0), - (w1 &= 67108863), - (lo = Math.imul(al2, bl0)), - (mid = Math.imul(al2, bh0)), - (mid = (mid + Math.imul(ah2, bl0)) | 0), - (hi = Math.imul(ah2, bh0)), - (lo = (lo + Math.imul(al1, bl1)) | 0), - (mid = (mid + Math.imul(al1, bh1)) | 0), - (mid = (mid + Math.imul(ah1, bl1)) | 0), - (hi = (hi + Math.imul(ah1, bh1)) | 0), - (lo = (lo + Math.imul(al0, bl2)) | 0), - (mid = (mid + Math.imul(al0, bh2)) | 0), - (mid = (mid + Math.imul(ah0, bl2)) | 0), - (hi = (hi + Math.imul(ah0, bh2)) | 0); - var w2 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0), - (w2 &= 67108863), - (lo = Math.imul(al3, bl0)), - (mid = Math.imul(al3, bh0)), - (mid = (mid + Math.imul(ah3, bl0)) | 0), - (hi = Math.imul(ah3, bh0)), - (lo = (lo + Math.imul(al2, bl1)) | 0), - (mid = (mid + Math.imul(al2, bh1)) | 0), - (mid = (mid + Math.imul(ah2, bl1)) | 0), - (hi = (hi + Math.imul(ah2, bh1)) | 0), - (lo = (lo + Math.imul(al1, bl2)) | 0), - (mid = (mid + Math.imul(al1, bh2)) | 0), - (mid = (mid + Math.imul(ah1, bl2)) | 0), - (hi = (hi + Math.imul(ah1, bh2)) | 0), - (lo = (lo + Math.imul(al0, bl3)) | 0), - (mid = (mid + Math.imul(al0, bh3)) | 0), - (mid = (mid + Math.imul(ah0, bl3)) | 0), - (hi = (hi + Math.imul(ah0, bh3)) | 0); - var w3 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0), - (w3 &= 67108863), - (lo = Math.imul(al4, bl0)), - (mid = Math.imul(al4, bh0)), - (mid = (mid + Math.imul(ah4, bl0)) | 0), - (hi = Math.imul(ah4, bh0)), - (lo = (lo + Math.imul(al3, bl1)) | 0), - (mid = (mid + Math.imul(al3, bh1)) | 0), - (mid = (mid + Math.imul(ah3, bl1)) | 0), - (hi = (hi + Math.imul(ah3, bh1)) | 0), - (lo = (lo + Math.imul(al2, bl2)) | 0), - (mid = (mid + Math.imul(al2, bh2)) | 0), - (mid = (mid + Math.imul(ah2, bl2)) | 0), - (hi = (hi + Math.imul(ah2, bh2)) | 0), - (lo = (lo + Math.imul(al1, bl3)) | 0), - (mid = (mid + Math.imul(al1, bh3)) | 0), - (mid = (mid + Math.imul(ah1, bl3)) | 0), - (hi = (hi + Math.imul(ah1, bh3)) | 0), - (lo = (lo + Math.imul(al0, bl4)) | 0), - (mid = (mid + Math.imul(al0, bh4)) | 0), - (mid = (mid + Math.imul(ah0, bl4)) | 0), - (hi = (hi + Math.imul(ah0, bh4)) | 0); - var w4 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0), - (w4 &= 67108863), - (lo = Math.imul(al5, bl0)), - (mid = Math.imul(al5, bh0)), - (mid = (mid + Math.imul(ah5, bl0)) | 0), - (hi = Math.imul(ah5, bh0)), - (lo = (lo + Math.imul(al4, bl1)) | 0), - (mid = (mid + Math.imul(al4, bh1)) | 0), - (mid = (mid + Math.imul(ah4, bl1)) | 0), - (hi = (hi + Math.imul(ah4, bh1)) | 0), - (lo = (lo + Math.imul(al3, bl2)) | 0), - (mid = (mid + Math.imul(al3, bh2)) | 0), - (mid = (mid + Math.imul(ah3, bl2)) | 0), - (hi = (hi + Math.imul(ah3, bh2)) | 0), - (lo = (lo + Math.imul(al2, bl3)) | 0), - (mid = (mid + Math.imul(al2, bh3)) | 0), - (mid = (mid + Math.imul(ah2, bl3)) | 0), - (hi = (hi + Math.imul(ah2, bh3)) | 0), - (lo = (lo + Math.imul(al1, bl4)) | 0), - (mid = (mid + Math.imul(al1, bh4)) | 0), - (mid = (mid + Math.imul(ah1, bl4)) | 0), - (hi = (hi + Math.imul(ah1, bh4)) | 0), - (lo = (lo + Math.imul(al0, bl5)) | 0), - (mid = (mid + Math.imul(al0, bh5)) | 0), - (mid = (mid + Math.imul(ah0, bl5)) | 0), - (hi = (hi + Math.imul(ah0, bh5)) | 0); - var w5 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0), - (w5 &= 67108863), - (lo = Math.imul(al6, bl0)), - (mid = Math.imul(al6, bh0)), - (mid = (mid + Math.imul(ah6, bl0)) | 0), - (hi = Math.imul(ah6, bh0)), - (lo = (lo + Math.imul(al5, bl1)) | 0), - (mid = (mid + Math.imul(al5, bh1)) | 0), - (mid = (mid + Math.imul(ah5, bl1)) | 0), - (hi = (hi + Math.imul(ah5, bh1)) | 0), - (lo = (lo + Math.imul(al4, bl2)) | 0), - (mid = (mid + Math.imul(al4, bh2)) | 0), - (mid = (mid + Math.imul(ah4, bl2)) | 0), - (hi = (hi + Math.imul(ah4, bh2)) | 0), - (lo = (lo + Math.imul(al3, bl3)) | 0), - (mid = (mid + Math.imul(al3, bh3)) | 0), - (mid = (mid + Math.imul(ah3, bl3)) | 0), - (hi = (hi + Math.imul(ah3, bh3)) | 0), - (lo = (lo + Math.imul(al2, bl4)) | 0), - (mid = (mid + Math.imul(al2, bh4)) | 0), - (mid = (mid + Math.imul(ah2, bl4)) | 0), - (hi = (hi + Math.imul(ah2, bh4)) | 0), - (lo = (lo + Math.imul(al1, bl5)) | 0), - (mid = (mid + Math.imul(al1, bh5)) | 0), - (mid = (mid + Math.imul(ah1, bl5)) | 0), - (hi = (hi + Math.imul(ah1, bh5)) | 0), - (lo = (lo + Math.imul(al0, bl6)) | 0), - (mid = (mid + Math.imul(al0, bh6)) | 0), - (mid = (mid + Math.imul(ah0, bl6)) | 0), - (hi = (hi + Math.imul(ah0, bh6)) | 0); - var w6 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0), - (w6 &= 67108863), - (lo = Math.imul(al7, bl0)), - (mid = Math.imul(al7, bh0)), - (mid = (mid + Math.imul(ah7, bl0)) | 0), - (hi = Math.imul(ah7, bh0)), - (lo = (lo + Math.imul(al6, bl1)) | 0), - (mid = (mid + Math.imul(al6, bh1)) | 0), - (mid = (mid + Math.imul(ah6, bl1)) | 0), - (hi = (hi + Math.imul(ah6, bh1)) | 0), - (lo = (lo + Math.imul(al5, bl2)) | 0), - (mid = (mid + Math.imul(al5, bh2)) | 0), - (mid = (mid + Math.imul(ah5, bl2)) | 0), - (hi = (hi + Math.imul(ah5, bh2)) | 0), - (lo = (lo + Math.imul(al4, bl3)) | 0), - (mid = (mid + Math.imul(al4, bh3)) | 0), - (mid = (mid + Math.imul(ah4, bl3)) | 0), - (hi = (hi + Math.imul(ah4, bh3)) | 0), - (lo = (lo + Math.imul(al3, bl4)) | 0), - (mid = (mid + Math.imul(al3, bh4)) | 0), - (mid = (mid + Math.imul(ah3, bl4)) | 0), - (hi = (hi + Math.imul(ah3, bh4)) | 0), - (lo = (lo + Math.imul(al2, bl5)) | 0), - (mid = (mid + Math.imul(al2, bh5)) | 0), - (mid = (mid + Math.imul(ah2, bl5)) | 0), - (hi = (hi + Math.imul(ah2, bh5)) | 0), - (lo = (lo + Math.imul(al1, bl6)) | 0), - (mid = (mid + Math.imul(al1, bh6)) | 0), - (mid = (mid + Math.imul(ah1, bl6)) | 0), - (hi = (hi + Math.imul(ah1, bh6)) | 0), - (lo = (lo + Math.imul(al0, bl7)) | 0), - (mid = (mid + Math.imul(al0, bh7)) | 0), - (mid = (mid + Math.imul(ah0, bl7)) | 0), - (hi = (hi + Math.imul(ah0, bh7)) | 0); - var w7 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0), - (w7 &= 67108863), - (lo = Math.imul(al8, bl0)), - (mid = Math.imul(al8, bh0)), - (mid = (mid + Math.imul(ah8, bl0)) | 0), - (hi = Math.imul(ah8, bh0)), - (lo = (lo + Math.imul(al7, bl1)) | 0), - (mid = (mid + Math.imul(al7, bh1)) | 0), - (mid = (mid + Math.imul(ah7, bl1)) | 0), - (hi = (hi + Math.imul(ah7, bh1)) | 0), - (lo = (lo + Math.imul(al6, bl2)) | 0), - (mid = (mid + Math.imul(al6, bh2)) | 0), - (mid = (mid + Math.imul(ah6, bl2)) | 0), - (hi = (hi + Math.imul(ah6, bh2)) | 0), - (lo = (lo + Math.imul(al5, bl3)) | 0), - (mid = (mid + Math.imul(al5, bh3)) | 0), - (mid = (mid + Math.imul(ah5, bl3)) | 0), - (hi = (hi + Math.imul(ah5, bh3)) | 0), - (lo = (lo + Math.imul(al4, bl4)) | 0), - (mid = (mid + Math.imul(al4, bh4)) | 0), - (mid = (mid + Math.imul(ah4, bl4)) | 0), - (hi = (hi + Math.imul(ah4, bh4)) | 0), - (lo = (lo + Math.imul(al3, bl5)) | 0), - (mid = (mid + Math.imul(al3, bh5)) | 0), - (mid = (mid + Math.imul(ah3, bl5)) | 0), - (hi = (hi + Math.imul(ah3, bh5)) | 0), - (lo = (lo + Math.imul(al2, bl6)) | 0), - (mid = (mid + Math.imul(al2, bh6)) | 0), - (mid = (mid + Math.imul(ah2, bl6)) | 0), - (hi = (hi + Math.imul(ah2, bh6)) | 0), - (lo = (lo + Math.imul(al1, bl7)) | 0), - (mid = (mid + Math.imul(al1, bh7)) | 0), - (mid = (mid + Math.imul(ah1, bl7)) | 0), - (hi = (hi + Math.imul(ah1, bh7)) | 0), - (lo = (lo + Math.imul(al0, bl8)) | 0), - (mid = (mid + Math.imul(al0, bh8)) | 0), - (mid = (mid + Math.imul(ah0, bl8)) | 0), - (hi = (hi + Math.imul(ah0, bh8)) | 0); - var w8 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0), - (w8 &= 67108863), - (lo = Math.imul(al9, bl0)), - (mid = Math.imul(al9, bh0)), - (mid = (mid + Math.imul(ah9, bl0)) | 0), - (hi = Math.imul(ah9, bh0)), - (lo = (lo + Math.imul(al8, bl1)) | 0), - (mid = (mid + Math.imul(al8, bh1)) | 0), - (mid = (mid + Math.imul(ah8, bl1)) | 0), - (hi = (hi + Math.imul(ah8, bh1)) | 0), - (lo = (lo + Math.imul(al7, bl2)) | 0), - (mid = (mid + Math.imul(al7, bh2)) | 0), - (mid = (mid + Math.imul(ah7, bl2)) | 0), - (hi = (hi + Math.imul(ah7, bh2)) | 0), - (lo = (lo + Math.imul(al6, bl3)) | 0), - (mid = (mid + Math.imul(al6, bh3)) | 0), - (mid = (mid + Math.imul(ah6, bl3)) | 0), - (hi = (hi + Math.imul(ah6, bh3)) | 0), - (lo = (lo + Math.imul(al5, bl4)) | 0), - (mid = (mid + Math.imul(al5, bh4)) | 0), - (mid = (mid + Math.imul(ah5, bl4)) | 0), - (hi = (hi + Math.imul(ah5, bh4)) | 0), - (lo = (lo + Math.imul(al4, bl5)) | 0), - (mid = (mid + Math.imul(al4, bh5)) | 0), - (mid = (mid + Math.imul(ah4, bl5)) | 0), - (hi = (hi + Math.imul(ah4, bh5)) | 0), - (lo = (lo + Math.imul(al3, bl6)) | 0), - (mid = (mid + Math.imul(al3, bh6)) | 0), - (mid = (mid + Math.imul(ah3, bl6)) | 0), - (hi = (hi + Math.imul(ah3, bh6)) | 0), - (lo = (lo + Math.imul(al2, bl7)) | 0), - (mid = (mid + Math.imul(al2, bh7)) | 0), - (mid = (mid + Math.imul(ah2, bl7)) | 0), - (hi = (hi + Math.imul(ah2, bh7)) | 0), - (lo = (lo + Math.imul(al1, bl8)) | 0), - (mid = (mid + Math.imul(al1, bh8)) | 0), - (mid = (mid + Math.imul(ah1, bl8)) | 0), - (hi = (hi + Math.imul(ah1, bh8)) | 0), - (lo = (lo + Math.imul(al0, bl9)) | 0), - (mid = (mid + Math.imul(al0, bh9)) | 0), - (mid = (mid + Math.imul(ah0, bl9)) | 0), - (hi = (hi + Math.imul(ah0, bh9)) | 0); - var w9 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0), - (w9 &= 67108863), - (lo = Math.imul(al9, bl1)), - (mid = Math.imul(al9, bh1)), - (mid = (mid + Math.imul(ah9, bl1)) | 0), - (hi = Math.imul(ah9, bh1)), - (lo = (lo + Math.imul(al8, bl2)) | 0), - (mid = (mid + Math.imul(al8, bh2)) | 0), - (mid = (mid + Math.imul(ah8, bl2)) | 0), - (hi = (hi + Math.imul(ah8, bh2)) | 0), - (lo = (lo + Math.imul(al7, bl3)) | 0), - (mid = (mid + Math.imul(al7, bh3)) | 0), - (mid = (mid + Math.imul(ah7, bl3)) | 0), - (hi = (hi + Math.imul(ah7, bh3)) | 0), - (lo = (lo + Math.imul(al6, bl4)) | 0), - (mid = (mid + Math.imul(al6, bh4)) | 0), - (mid = (mid + Math.imul(ah6, bl4)) | 0), - (hi = (hi + Math.imul(ah6, bh4)) | 0), - (lo = (lo + Math.imul(al5, bl5)) | 0), - (mid = (mid + Math.imul(al5, bh5)) | 0), - (mid = (mid + Math.imul(ah5, bl5)) | 0), - (hi = (hi + Math.imul(ah5, bh5)) | 0), - (lo = (lo + Math.imul(al4, bl6)) | 0), - (mid = (mid + Math.imul(al4, bh6)) | 0), - (mid = (mid + Math.imul(ah4, bl6)) | 0), - (hi = (hi + Math.imul(ah4, bh6)) | 0), - (lo = (lo + Math.imul(al3, bl7)) | 0), - (mid = (mid + Math.imul(al3, bh7)) | 0), - (mid = (mid + Math.imul(ah3, bl7)) | 0), - (hi = (hi + Math.imul(ah3, bh7)) | 0), - (lo = (lo + Math.imul(al2, bl8)) | 0), - (mid = (mid + Math.imul(al2, bh8)) | 0), - (mid = (mid + Math.imul(ah2, bl8)) | 0), - (hi = (hi + Math.imul(ah2, bh8)) | 0), - (lo = (lo + Math.imul(al1, bl9)) | 0), - (mid = (mid + Math.imul(al1, bh9)) | 0), - (mid = (mid + Math.imul(ah1, bl9)) | 0), - (hi = (hi + Math.imul(ah1, bh9)) | 0); - var w10 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0), - (w10 &= 67108863), - (lo = Math.imul(al9, bl2)), - (mid = Math.imul(al9, bh2)), - (mid = (mid + Math.imul(ah9, bl2)) | 0), - (hi = Math.imul(ah9, bh2)), - (lo = (lo + Math.imul(al8, bl3)) | 0), - (mid = (mid + Math.imul(al8, bh3)) | 0), - (mid = (mid + Math.imul(ah8, bl3)) | 0), - (hi = (hi + Math.imul(ah8, bh3)) | 0), - (lo = (lo + Math.imul(al7, bl4)) | 0), - (mid = (mid + Math.imul(al7, bh4)) | 0), - (mid = (mid + Math.imul(ah7, bl4)) | 0), - (hi = (hi + Math.imul(ah7, bh4)) | 0), - (lo = (lo + Math.imul(al6, bl5)) | 0), - (mid = (mid + Math.imul(al6, bh5)) | 0), - (mid = (mid + Math.imul(ah6, bl5)) | 0), - (hi = (hi + Math.imul(ah6, bh5)) | 0), - (lo = (lo + Math.imul(al5, bl6)) | 0), - (mid = (mid + Math.imul(al5, bh6)) | 0), - (mid = (mid + Math.imul(ah5, bl6)) | 0), - (hi = (hi + Math.imul(ah5, bh6)) | 0), - (lo = (lo + Math.imul(al4, bl7)) | 0), - (mid = (mid + Math.imul(al4, bh7)) | 0), - (mid = (mid + Math.imul(ah4, bl7)) | 0), - (hi = (hi + Math.imul(ah4, bh7)) | 0), - (lo = (lo + Math.imul(al3, bl8)) | 0), - (mid = (mid + Math.imul(al3, bh8)) | 0), - (mid = (mid + Math.imul(ah3, bl8)) | 0), - (hi = (hi + Math.imul(ah3, bh8)) | 0), - (lo = (lo + Math.imul(al2, bl9)) | 0), - (mid = (mid + Math.imul(al2, bh9)) | 0), - (mid = (mid + Math.imul(ah2, bl9)) | 0), - (hi = (hi + Math.imul(ah2, bh9)) | 0); - var w11 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0), - (w11 &= 67108863), - (lo = Math.imul(al9, bl3)), - (mid = Math.imul(al9, bh3)), - (mid = (mid + Math.imul(ah9, bl3)) | 0), - (hi = Math.imul(ah9, bh3)), - (lo = (lo + Math.imul(al8, bl4)) | 0), - (mid = (mid + Math.imul(al8, bh4)) | 0), - (mid = (mid + Math.imul(ah8, bl4)) | 0), - (hi = (hi + Math.imul(ah8, bh4)) | 0), - (lo = (lo + Math.imul(al7, bl5)) | 0), - (mid = (mid + Math.imul(al7, bh5)) | 0), - (mid = (mid + Math.imul(ah7, bl5)) | 0), - (hi = (hi + Math.imul(ah7, bh5)) | 0), - (lo = (lo + Math.imul(al6, bl6)) | 0), - (mid = (mid + Math.imul(al6, bh6)) | 0), - (mid = (mid + Math.imul(ah6, bl6)) | 0), - (hi = (hi + Math.imul(ah6, bh6)) | 0), - (lo = (lo + Math.imul(al5, bl7)) | 0), - (mid = (mid + Math.imul(al5, bh7)) | 0), - (mid = (mid + Math.imul(ah5, bl7)) | 0), - (hi = (hi + Math.imul(ah5, bh7)) | 0), - (lo = (lo + Math.imul(al4, bl8)) | 0), - (mid = (mid + Math.imul(al4, bh8)) | 0), - (mid = (mid + Math.imul(ah4, bl8)) | 0), - (hi = (hi + Math.imul(ah4, bh8)) | 0), - (lo = (lo + Math.imul(al3, bl9)) | 0), - (mid = (mid + Math.imul(al3, bh9)) | 0), - (mid = (mid + Math.imul(ah3, bl9)) | 0), - (hi = (hi + Math.imul(ah3, bh9)) | 0); - var w12 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0), - (w12 &= 67108863), - (lo = Math.imul(al9, bl4)), - (mid = Math.imul(al9, bh4)), - (mid = (mid + Math.imul(ah9, bl4)) | 0), - (hi = Math.imul(ah9, bh4)), - (lo = (lo + Math.imul(al8, bl5)) | 0), - (mid = (mid + Math.imul(al8, bh5)) | 0), - (mid = (mid + Math.imul(ah8, bl5)) | 0), - (hi = (hi + Math.imul(ah8, bh5)) | 0), - (lo = (lo + Math.imul(al7, bl6)) | 0), - (mid = (mid + Math.imul(al7, bh6)) | 0), - (mid = (mid + Math.imul(ah7, bl6)) | 0), - (hi = (hi + Math.imul(ah7, bh6)) | 0), - (lo = (lo + Math.imul(al6, bl7)) | 0), - (mid = (mid + Math.imul(al6, bh7)) | 0), - (mid = (mid + Math.imul(ah6, bl7)) | 0), - (hi = (hi + Math.imul(ah6, bh7)) | 0), - (lo = (lo + Math.imul(al5, bl8)) | 0), - (mid = (mid + Math.imul(al5, bh8)) | 0), - (mid = (mid + Math.imul(ah5, bl8)) | 0), - (hi = (hi + Math.imul(ah5, bh8)) | 0), - (lo = (lo + Math.imul(al4, bl9)) | 0), - (mid = (mid + Math.imul(al4, bh9)) | 0), - (mid = (mid + Math.imul(ah4, bl9)) | 0), - (hi = (hi + Math.imul(ah4, bh9)) | 0); - var w13 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0), - (w13 &= 67108863), - (lo = Math.imul(al9, bl5)), - (mid = Math.imul(al9, bh5)), - (mid = (mid + Math.imul(ah9, bl5)) | 0), - (hi = Math.imul(ah9, bh5)), - (lo = (lo + Math.imul(al8, bl6)) | 0), - (mid = (mid + Math.imul(al8, bh6)) | 0), - (mid = (mid + Math.imul(ah8, bl6)) | 0), - (hi = (hi + Math.imul(ah8, bh6)) | 0), - (lo = (lo + Math.imul(al7, bl7)) | 0), - (mid = (mid + Math.imul(al7, bh7)) | 0), - (mid = (mid + Math.imul(ah7, bl7)) | 0), - (hi = (hi + Math.imul(ah7, bh7)) | 0), - (lo = (lo + Math.imul(al6, bl8)) | 0), - (mid = (mid + Math.imul(al6, bh8)) | 0), - (mid = (mid + Math.imul(ah6, bl8)) | 0), - (hi = (hi + Math.imul(ah6, bh8)) | 0), - (lo = (lo + Math.imul(al5, bl9)) | 0), - (mid = (mid + Math.imul(al5, bh9)) | 0), - (mid = (mid + Math.imul(ah5, bl9)) | 0), - (hi = (hi + Math.imul(ah5, bh9)) | 0); - var w14 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0), - (w14 &= 67108863), - (lo = Math.imul(al9, bl6)), - (mid = Math.imul(al9, bh6)), - (mid = (mid + Math.imul(ah9, bl6)) | 0), - (hi = Math.imul(ah9, bh6)), - (lo = (lo + Math.imul(al8, bl7)) | 0), - (mid = (mid + Math.imul(al8, bh7)) | 0), - (mid = (mid + Math.imul(ah8, bl7)) | 0), - (hi = (hi + Math.imul(ah8, bh7)) | 0), - (lo = (lo + Math.imul(al7, bl8)) | 0), - (mid = (mid + Math.imul(al7, bh8)) | 0), - (mid = (mid + Math.imul(ah7, bl8)) | 0), - (hi = (hi + Math.imul(ah7, bh8)) | 0), - (lo = (lo + Math.imul(al6, bl9)) | 0), - (mid = (mid + Math.imul(al6, bh9)) | 0), - (mid = (mid + Math.imul(ah6, bl9)) | 0), - (hi = (hi + Math.imul(ah6, bh9)) | 0); - var w15 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0), - (w15 &= 67108863), - (lo = Math.imul(al9, bl7)), - (mid = Math.imul(al9, bh7)), - (mid = (mid + Math.imul(ah9, bl7)) | 0), - (hi = Math.imul(ah9, bh7)), - (lo = (lo + Math.imul(al8, bl8)) | 0), - (mid = (mid + Math.imul(al8, bh8)) | 0), - (mid = (mid + Math.imul(ah8, bl8)) | 0), - (hi = (hi + Math.imul(ah8, bh8)) | 0), - (lo = (lo + Math.imul(al7, bl9)) | 0), - (mid = (mid + Math.imul(al7, bh9)) | 0), - (mid = (mid + Math.imul(ah7, bl9)) | 0), - (hi = (hi + Math.imul(ah7, bh9)) | 0); - var w16 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0), - (w16 &= 67108863), - (lo = Math.imul(al9, bl8)), - (mid = Math.imul(al9, bh8)), - (mid = (mid + Math.imul(ah9, bl8)) | 0), - (hi = Math.imul(ah9, bh8)), - (lo = (lo + Math.imul(al8, bl9)) | 0), - (mid = (mid + Math.imul(al8, bh9)) | 0), - (mid = (mid + Math.imul(ah8, bl9)) | 0), - (hi = (hi + Math.imul(ah8, bh9)) | 0); - var w17 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0), - (w17 &= 67108863), - (lo = Math.imul(al9, bl9)), - (mid = Math.imul(al9, bh9)), - (mid = (mid + Math.imul(ah9, bl9)) | 0), - (hi = Math.imul(ah9, bh9)); - var w18 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - return ( - (c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0), - (w18 &= 67108863), - (o[0] = w0), - (o[1] = w1), - (o[2] = w2), - (o[3] = w3), - (o[4] = w4), - (o[5] = w5), - (o[6] = w6), - (o[7] = w7), - (o[8] = w8), - (o[9] = w9), - (o[10] = w10), - (o[11] = w11), - (o[12] = w12), - (o[13] = w13), - (o[14] = w14), - (o[15] = w15), - (o[16] = w16), - (o[17] = w17), - (o[18] = w18), - c !== 0 && ((o[19] = c), out.length++), - out - ); - }; - Math.imul || (comb10MulTo = smallMulTo); - function bigMulTo(self2, num, out) { - (out.negative = num.negative ^ self2.negative), (out.length = self2.length + num.length); - for (var carry = 0, hncarry = 0, k = 0; k < out.length - 1; k++) { - var ncarry = hncarry; - hncarry = 0; - for ( - var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1), j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = k - j, - a = self2.words[i] | 0, - b = num.words[j] | 0, - r = a * b, - lo = r & 67108863; - (ncarry = (ncarry + ((r / 67108864) | 0)) | 0), - (lo = (lo + rword) | 0), - (rword = lo & 67108863), - (ncarry = (ncarry + (lo >>> 26)) | 0), - (hncarry += ncarry >>> 26), - (ncarry &= 67108863); - } - (out.words[k] = rword), (carry = ncarry), (ncarry = hncarry); - } - return carry !== 0 ? (out.words[k] = carry) : out.length--, out.strip(); - } - function jumboMulTo(self2, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self2, num, out); - } - BN.prototype.mulTo = function (num, out) { - var res, - len = this.length + num.length; - return ( - this.length === 10 && num.length === 10 - ? (res = comb10MulTo(this, num, out)) - : len < 63 - ? (res = smallMulTo(this, num, out)) - : len < 1024 - ? (res = bigMulTo(this, num, out)) - : (res = jumboMulTo(this, num, out)), - res - ); - }; - function FFTM(x, y) { - (this.x = x), (this.y = y); - } - (FFTM.prototype.makeRBT = function (N) { - for (var t = new Array(N), l = BN.prototype._countBits(N) - 1, i = 0; i < N; i++) t[i] = this.revBin(i, l, N); - return t; - }), - (FFTM.prototype.revBin = function (x, l, N) { - if (x === 0 || x === N - 1) return x; - for (var rb = 0, i = 0; i < l; i++) (rb |= (x & 1) << (l - i - 1)), (x >>= 1); - return rb; - }), - (FFTM.prototype.permute = function (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) (rtws[i] = rws[rbt[i]]), (itws[i] = iws[rbt[i]]); - }), - (FFTM.prototype.transform = function (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - for (var s = 1; s < N; s <<= 1) - for ( - var l = s << 1, rtwdf = Math.cos((2 * Math.PI) / l), itwdf = Math.sin((2 * Math.PI) / l), p = 0; - p < N; - p += l - ) - for (var rtwdf_ = rtwdf, itwdf_ = itwdf, j = 0; j < s; j++) { - var re = rtws[p + j], - ie = itws[p + j], - ro = rtws[p + j + s], - io = itws[p + j + s], - rx = rtwdf_ * ro - itwdf_ * io; - (io = rtwdf_ * io + itwdf_ * ro), - (ro = rx), - (rtws[p + j] = re + ro), - (itws[p + j] = ie + io), - (rtws[p + j + s] = re - ro), - (itws[p + j + s] = ie - io), - j !== l && - ((rx = rtwdf * rtwdf_ - itwdf * itwdf_), (itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_), (rtwdf_ = rx)); - } - }), - (FFTM.prototype.guessLen13b = function (n, m) { - var N = Math.max(m, n) | 1, - odd = N & 1, - i = 0; - for (N = (N / 2) | 0; N; N = N >>> 1) i++; - return 1 << (i + 1 + odd); - }), - (FFTM.prototype.conjugate = function (rws, iws, N) { - if (!(N <= 1)) - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - (rws[i] = rws[N - i - 1]), - (rws[N - i - 1] = t), - (t = iws[i]), - (iws[i] = -iws[N - i - 1]), - (iws[N - i - 1] = -t); - } - }), - (FFTM.prototype.normalize13b = function (ws, N) { - for (var carry = 0, i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 8192 + Math.round(ws[2 * i] / N) + carry; - (ws[i] = w & 67108863), w < 67108864 ? (carry = 0) : (carry = (w / 67108864) | 0); - } - return ws; - }), - (FFTM.prototype.convert13b = function (ws, len, rws, N) { - for (var carry = 0, i = 0; i < len; i++) - (carry = carry + (ws[i] | 0)), - (rws[2 * i] = carry & 8191), - (carry = carry >>> 13), - (rws[2 * i + 1] = carry & 8191), - (carry = carry >>> 13); - for (i = 2 * len; i < N; ++i) rws[i] = 0; - assert(carry === 0), assert((carry & -8192) === 0); - }), - (FFTM.prototype.stub = function (N) { - for (var ph = new Array(N), i = 0; i < N; i++) ph[i] = 0; - return ph; - }), - (FFTM.prototype.mulp = function (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length), - rbt = this.makeRBT(N), - _ = this.stub(N), - rws = new Array(N), - rwst = new Array(N), - iwst = new Array(N), - nrws = new Array(N), - nrwst = new Array(N), - niwst = new Array(N), - rmws = out.words; - (rmws.length = N), - this.convert13b(x.words, x.length, rws, N), - this.convert13b(y.words, y.length, nrws, N), - this.transform(rws, _, rwst, iwst, N, rbt), - this.transform(nrws, _, nrwst, niwst, N, rbt); - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - (iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]), (rwst[i] = rx); - } - return ( - this.conjugate(rwst, iwst, N), - this.transform(rwst, iwst, rmws, _, N, rbt), - this.conjugate(rmws, _, N), - this.normalize13b(rmws, N), - (out.negative = x.negative ^ y.negative), - (out.length = x.length + y.length), - out.strip() - ); - }), - (BN.prototype.mul = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), this.mulTo(num, out); - }), - (BN.prototype.mulf = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), jumboMulTo(this, num, out); - }), - (BN.prototype.imul = function (num) { - return this.clone().mulTo(num, this); - }), - (BN.prototype.imuln = function (num) { - assert(typeof num == "number"), assert(num < 67108864); - for (var carry = 0, i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num, - lo = (w & 67108863) + (carry & 67108863); - (carry >>= 26), (carry += (w / 67108864) | 0), (carry += lo >>> 26), (this.words[i] = lo & 67108863); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.muln = function (num) { - return this.clone().imuln(num); - }), - (BN.prototype.sqr = function () { - return this.mul(this); - }), - (BN.prototype.isqr = function () { - return this.imul(this.clone()); - }), - (BN.prototype.pow = function (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - for (var res = this, i = 0; i < w.length && w[i] === 0; i++, res = res.sqr()); - if (++i < w.length) for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) w[i] !== 0 && (res = res.mul(q)); - return res; - }), - (BN.prototype.iushln = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26, - carryMask = (67108863 >>> (26 - r)) << (26 - r), - i; - if (r !== 0) { - var carry = 0; - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask, - c = ((this.words[i] | 0) - newCarry) << r; - (this.words[i] = c | carry), (carry = newCarry >>> (26 - r)); - } - carry && ((this.words[i] = carry), this.length++); - } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) this.words[i + s] = this.words[i]; - for (i = 0; i < s; i++) this.words[i] = 0; - this.length += s; - } - return this.strip(); - }), - (BN.prototype.ishln = function (bits) { - return assert(this.negative === 0), this.iushln(bits); - }), - (BN.prototype.iushrn = function (bits, hint, extended) { - assert(typeof bits == "number" && bits >= 0); - var h; - hint ? (h = (hint - (hint % 26)) / 26) : (h = 0); - var r = bits % 26, - s = Math.min((bits - r) / 26, this.length), - mask = 67108863 ^ ((67108863 >>> r) << r), - maskedWords = extended; - if (((h -= s), (h = Math.max(0, h)), maskedWords)) { - for (var i = 0; i < s; i++) maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - if (s !== 0) - if (this.length > s) for (this.length -= s, i = 0; i < this.length; i++) this.words[i] = this.words[i + s]; - else (this.words[0] = 0), (this.length = 1); - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - (this.words[i] = (carry << (26 - r)) | (word >>> r)), (carry = word & mask); - } - return ( - maskedWords && carry !== 0 && (maskedWords.words[maskedWords.length++] = carry), - this.length === 0 && ((this.words[0] = 0), (this.length = 1)), - this.strip() - ); - }), - (BN.prototype.ishrn = function (bits, hint, extended) { - return assert(this.negative === 0), this.iushrn(bits, hint, extended); - }), - (BN.prototype.shln = function (bits) { - return this.clone().ishln(bits); - }), - (BN.prototype.ushln = function (bits) { - return this.clone().iushln(bits); - }), - (BN.prototype.shrn = function (bits) { - return this.clone().ishrn(bits); - }), - (BN.prototype.ushrn = function (bits) { - return this.clone().iushrn(bits); - }), - (BN.prototype.testn = function (bit) { - assert(typeof bit == "number" && bit >= 0); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return !1; - var w = this.words[s]; - return !!(w & q); - }), - (BN.prototype.imaskn = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26; - if ((assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)) return this; - if ((r !== 0 && s++, (this.length = Math.min(s, this.length)), r !== 0)) { - var mask = 67108863 ^ ((67108863 >>> r) << r); - this.words[this.length - 1] &= mask; - } - return this.strip(); - }), - (BN.prototype.maskn = function (bits) { - return this.clone().imaskn(bits); - }), - (BN.prototype.iaddn = function (num) { - return ( - assert(typeof num == "number"), - assert(num < 67108864), - num < 0 - ? this.isubn(-num) - : this.negative !== 0 - ? this.length === 1 && (this.words[0] | 0) < num - ? ((this.words[0] = num - (this.words[0] | 0)), (this.negative = 0), this) - : ((this.negative = 0), this.isubn(num), (this.negative = 1), this) - : this._iaddn(num) - ); - }), - (BN.prototype._iaddn = function (num) { - this.words[0] += num; - for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) - (this.words[i] -= 67108864), i === this.length - 1 ? (this.words[i + 1] = 1) : this.words[i + 1]++; - return (this.length = Math.max(this.length, i + 1)), this; - }), - (BN.prototype.isubn = function (num) { - if ((assert(typeof num == "number"), assert(num < 67108864), num < 0)) return this.iaddn(-num); - if (this.negative !== 0) return (this.negative = 0), this.iaddn(num), (this.negative = 1), this; - if (((this.words[0] -= num), this.length === 1 && this.words[0] < 0)) - (this.words[0] = -this.words[0]), (this.negative = 1); - else - for (var i = 0; i < this.length && this.words[i] < 0; i++) - (this.words[i] += 67108864), (this.words[i + 1] -= 1); - return this.strip(); - }), - (BN.prototype.addn = function (num) { - return this.clone().iaddn(num); - }), - (BN.prototype.subn = function (num) { - return this.clone().isubn(num); - }), - (BN.prototype.iabs = function () { - return (this.negative = 0), this; - }), - (BN.prototype.abs = function () { - return this.clone().iabs(); - }), - (BN.prototype._ishlnsubmul = function (num, mul, shift) { - var len = num.length + shift, - i; - this._expand(len); - var w, - carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - (w -= right & 67108863), - (carry = (w >> 26) - ((right / 67108864) | 0)), - (this.words[i + shift] = w & 67108863); - } - for (; i < this.length - shift; i++) - (w = (this.words[i + shift] | 0) + carry), (carry = w >> 26), (this.words[i + shift] = w & 67108863); - if (carry === 0) return this.strip(); - for (assert(carry === -1), carry = 0, i = 0; i < this.length; i++) - (w = -(this.words[i] | 0) + carry), (carry = w >> 26), (this.words[i] = w & 67108863); - return (this.negative = 1), this.strip(); - }), - (BN.prototype._wordDiv = function (num, mode) { - var shift = this.length - num.length, - a = this.clone(), - b = num, - bhi = b.words[b.length - 1] | 0, - bhiBits = this._countBits(bhi); - (shift = 26 - bhiBits), - shift !== 0 && ((b = b.ushln(shift)), a.iushln(shift), (bhi = b.words[b.length - 1] | 0)); - var m = a.length - b.length, - q; - if (mode !== "mod") { - (q = new BN(null)), (q.length = m + 1), (q.words = new Array(q.length)); - for (var i = 0; i < q.length; i++) q.words[i] = 0; - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - diff.negative === 0 && ((a = diff), q && (q.words[m] = 1)); - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); - for (qj = Math.min((qj / bhi) | 0, 67108863), a._ishlnsubmul(b, qj, j); a.negative !== 0; ) - qj--, (a.negative = 0), a._ishlnsubmul(b, 1, j), a.isZero() || (a.negative ^= 1); - q && (q.words[j] = qj); - } - return ( - q && q.strip(), - a.strip(), - mode !== "div" && shift !== 0 && a.iushrn(shift), - { - div: q || null, - mod: a, - } - ); - }), - (BN.prototype.divmod = function (num, mode, positive) { - if ((assert(!num.isZero()), this.isZero())) - return { - div: new BN(0), - mod: new BN(0), - }; - var div, mod, res; - return this.negative !== 0 && num.negative === 0 - ? ((res = this.neg().divmod(num, mode)), - mode !== "mod" && (div = res.div.neg()), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.iadd(num)), - { - div, - mod, - }) - : this.negative === 0 && num.negative !== 0 - ? ((res = this.divmod(num.neg(), mode)), - mode !== "mod" && (div = res.div.neg()), - { - div, - mod: res.mod, - }) - : (this.negative & num.negative) !== 0 - ? ((res = this.neg().divmod(num.neg(), mode)), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.isub(num)), - { - div: res.div, - mod, - }) - : num.length > this.length || this.cmp(num) < 0 - ? { - div: new BN(0), - mod: this, - } - : num.length === 1 - ? mode === "div" - ? { - div: this.divn(num.words[0]), - mod: null, - } - : mode === "mod" - ? { - div: null, - mod: new BN(this.modn(num.words[0])), - } - : { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])), - } - : this._wordDiv(num, mode); - }), - (BN.prototype.div = function (num) { - return this.divmod(num, "div", !1).div; - }), - (BN.prototype.mod = function (num) { - return this.divmod(num, "mod", !1).mod; - }), - (BN.prototype.umod = function (num) { - return this.divmod(num, "mod", !0).mod; - }), - (BN.prototype.divRound = function (num) { - var dm = this.divmod(num); - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, - half = num.ushrn(1), - r2 = num.andln(1), - cmp = mod.cmp(half); - return cmp < 0 || (r2 === 1 && cmp === 0) - ? dm.div - : dm.div.negative !== 0 - ? dm.div.isubn(1) - : dm.div.iaddn(1); - }), - (BN.prototype.modn = function (num) { - assert(num <= 67108863); - for (var p = (1 << 26) % num, acc = 0, i = this.length - 1; i >= 0; i--) - acc = (p * acc + (this.words[i] | 0)) % num; - return acc; - }), - (BN.prototype.idivn = function (num) { - assert(num <= 67108863); - for (var carry = 0, i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 67108864; - (this.words[i] = (w / num) | 0), (carry = w % num); - } - return this.strip(); - }), - (BN.prototype.divn = function (num) { - return this.clone().idivn(num); - }), - (BN.prototype.egcd = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var x = this, - y = p.clone(); - x.negative !== 0 ? (x = x.umod(p)) : (x = x.clone()); - for (var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0; x.isEven() && y.isEven(); ) - x.iushrn(1), y.iushrn(1), ++g; - for (var yp = y.clone(), xp = x.clone(); !x.isZero(); ) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) - for (x.iushrn(i); i-- > 0; ) - (A.isOdd() || B.isOdd()) && (A.iadd(yp), B.isub(xp)), A.iushrn(1), B.iushrn(1); - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) - for (y.iushrn(j); j-- > 0; ) - (C.isOdd() || D.isOdd()) && (C.iadd(yp), D.isub(xp)), C.iushrn(1), D.iushrn(1); - x.cmp(y) >= 0 ? (x.isub(y), A.isub(C), B.isub(D)) : (y.isub(x), C.isub(A), D.isub(B)); - } - return { - a: C, - b: D, - gcd: y.iushln(g), - }; - }), - (BN.prototype._invmp = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var a = this, - b = p.clone(); - a.negative !== 0 ? (a = a.umod(p)) : (a = a.clone()); - for (var x1 = new BN(1), x2 = new BN(0), delta = b.clone(); a.cmpn(1) > 0 && b.cmpn(1) > 0; ) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) for (a.iushrn(i); i-- > 0; ) x1.isOdd() && x1.iadd(delta), x1.iushrn(1); - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) for (b.iushrn(j); j-- > 0; ) x2.isOdd() && x2.iadd(delta), x2.iushrn(1); - a.cmp(b) >= 0 ? (a.isub(b), x1.isub(x2)) : (b.isub(a), x2.isub(x1)); - } - var res; - return a.cmpn(1) === 0 ? (res = x1) : (res = x2), res.cmpn(0) < 0 && res.iadd(p), res; - }), - (BN.prototype.gcd = function (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(), - b = num.clone(); - (a.negative = 0), (b.negative = 0); - for (var shift = 0; a.isEven() && b.isEven(); shift++) a.iushrn(1), b.iushrn(1); - do { - for (; a.isEven(); ) a.iushrn(1); - for (; b.isEven(); ) b.iushrn(1); - var r = a.cmp(b); - if (r < 0) { - var t = a; - (a = b), (b = t); - } else if (r === 0 || b.cmpn(1) === 0) break; - a.isub(b); - } while (!0); - return b.iushln(shift); - }), - (BN.prototype.invm = function (num) { - return this.egcd(num).a.umod(num); - }), - (BN.prototype.isEven = function () { - return (this.words[0] & 1) === 0; - }), - (BN.prototype.isOdd = function () { - return (this.words[0] & 1) === 1; - }), - (BN.prototype.andln = function (num) { - return this.words[0] & num; - }), - (BN.prototype.bincn = function (bit) { - assert(typeof bit == "number"); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return this._expand(s + 1), (this.words[s] |= q), this; - for (var carry = q, i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - (w += carry), (carry = w >>> 26), (w &= 67108863), (this.words[i] = w); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.isZero = function () { - return this.length === 1 && this.words[0] === 0; - }), - (BN.prototype.cmpn = function (num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - this.strip(); - var res; - if (this.length > 1) res = 1; - else { - negative && (num = -num), assert(num <= 67108863, "Number is too big"); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.cmp = function (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.ucmp = function (num) { - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - for (var res = 0, i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0, - b = num.words[i] | 0; - if (a !== b) { - a < b ? (res = -1) : a > b && (res = 1); - break; - } - } - return res; - }), - (BN.prototype.gtn = function (num) { - return this.cmpn(num) === 1; - }), - (BN.prototype.gt = function (num) { - return this.cmp(num) === 1; - }), - (BN.prototype.gten = function (num) { - return this.cmpn(num) >= 0; - }), - (BN.prototype.gte = function (num) { - return this.cmp(num) >= 0; - }), - (BN.prototype.ltn = function (num) { - return this.cmpn(num) === -1; - }), - (BN.prototype.lt = function (num) { - return this.cmp(num) === -1; - }), - (BN.prototype.lten = function (num) { - return this.cmpn(num) <= 0; - }), - (BN.prototype.lte = function (num) { - return this.cmp(num) <= 0; - }), - (BN.prototype.eqn = function (num) { - return this.cmpn(num) === 0; - }), - (BN.prototype.eq = function (num) { - return this.cmp(num) === 0; - }), - (BN.red = function (num) { - return new Red(num); - }), - (BN.prototype.toRed = function (ctx) { - return ( - assert(!this.red, "Already a number in reduction context"), - assert(this.negative === 0, "red works only with positives"), - ctx.convertTo(this)._forceRed(ctx) - ); - }), - (BN.prototype.fromRed = function () { - return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }), - (BN.prototype._forceRed = function (ctx) { - return (this.red = ctx), this; - }), - (BN.prototype.forceRed = function (ctx) { - return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx); - }), - (BN.prototype.redAdd = function (num) { - return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num); - }), - (BN.prototype.redIAdd = function (num) { - return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num); - }), - (BN.prototype.redSub = function (num) { - return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num); - }), - (BN.prototype.redISub = function (num) { - return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num); - }), - (BN.prototype.redShl = function (num) { - return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num); - }), - (BN.prototype.redMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.mul(this, num) - ); - }), - (BN.prototype.redIMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.imul(this, num) - ); - }), - (BN.prototype.redSqr = function () { - return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }), - (BN.prototype.redISqr = function () { - return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }), - (BN.prototype.redSqrt = function () { - return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }), - (BN.prototype.redInvm = function () { - return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); - }), - (BN.prototype.redNeg = function () { - return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); - }), - (BN.prototype.redPow = function (num) { - return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num); - }); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null, - }; - function MPrime(name, p) { - (this.name = name), - (this.p = new BN(p, 16)), - (this.n = this.p.bitLength()), - (this.k = new BN(1).iushln(this.n).isub(this.p)), - (this.tmp = this._tmp()); - } - (MPrime.prototype._tmp = function () { - var tmp = new BN(null); - return (tmp.words = new Array(Math.ceil(this.n / 13))), tmp; - }), - (MPrime.prototype.ireduce = function (num) { - var r = num, - rlen; - do this.split(r, this.tmp), (r = this.imulK(r)), (r = r.iadd(this.tmp)), (rlen = r.bitLength()); - while (rlen > this.n); - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - return ( - cmp === 0 - ? ((r.words[0] = 0), (r.length = 1)) - : cmp > 0 - ? r.isub(this.p) - : r.strip !== void 0 - ? r.strip() - : r._strip(), - r - ); - }), - (MPrime.prototype.split = function (input, out) { - input.iushrn(this.n, 0, out); - }), - (MPrime.prototype.imulK = function (num) { - return num.imul(this.k); - }); - function K256() { - MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - inherits(K256, MPrime), - (K256.prototype.split = function (input, output) { - for (var mask = 4194303, outLen = Math.min(input.length, 9), i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - if (((output.length = outLen), input.length <= 9)) { - (input.words[0] = 0), (input.length = 1); - return; - } - var prev = input.words[9]; - for (output.words[output.length++] = prev & mask, i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - (input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22)), (prev = next); - } - (prev >>>= 22), - (input.words[i - 10] = prev), - prev === 0 && input.length > 10 ? (input.length -= 10) : (input.length -= 9); - }), - (K256.prototype.imulK = function (num) { - (num.words[num.length] = 0), (num.words[num.length + 1] = 0), (num.length += 2); - for (var lo = 0, i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - (lo += w * 977), (num.words[i] = lo & 67108863), (lo = w * 64 + ((lo / 67108864) | 0)); - } - return ( - num.words[num.length - 1] === 0 && (num.length--, num.words[num.length - 1] === 0 && num.length--), num - ); - }); - function P224() { - MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - inherits(P224, MPrime); - function P192() { - MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - inherits(P192, MPrime); - function P25519() { - MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - inherits(P25519, MPrime), - (P25519.prototype.imulK = function (num) { - for (var carry = 0, i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 19 + carry, - lo = hi & 67108863; - (hi >>>= 26), (num.words[i] = lo), (carry = hi); - } - return carry !== 0 && (num.words[num.length++] = carry), num; - }), - (BN._prime = function (name) { - if (primes[name]) return primes[name]; - var prime2; - if (name === "k256") prime2 = new K256(); - else if (name === "p224") prime2 = new P224(); - else if (name === "p192") prime2 = new P192(); - else if (name === "p25519") prime2 = new P25519(); - else throw new Error("Unknown prime " + name); - return (primes[name] = prime2), prime2; - }); - function Red(m) { - if (typeof m == "string") { - var prime = BN._prime(m); - (this.m = prime.p), (this.prime = prime); - } else assert(m.gtn(1), "modulus must be greater than 1"), (this.m = m), (this.prime = null); - } - (Red.prototype._verify1 = function (a) { - assert(a.negative === 0, "red works only with positives"), assert(a.red, "red works only with red numbers"); - }), - (Red.prototype._verify2 = function (a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"), - assert(a.red && a.red === b.red, "red works only with red numbers"); - }), - (Red.prototype.imod = function (a) { - return this.prime ? this.prime.ireduce(a)._forceRed(this) : a.umod(this.m)._forceRed(this); - }), - (Red.prototype.neg = function (a) { - return a.isZero() ? a.clone() : this.m.sub(a)._forceRed(this); - }), - (Red.prototype.add = function (a, b) { - this._verify2(a, b); - var res = a.add(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res._forceRed(this); - }), - (Red.prototype.iadd = function (a, b) { - this._verify2(a, b); - var res = a.iadd(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res; - }), - (Red.prototype.sub = function (a, b) { - this._verify2(a, b); - var res = a.sub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res._forceRed(this); - }), - (Red.prototype.isub = function (a, b) { - this._verify2(a, b); - var res = a.isub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res; - }), - (Red.prototype.shl = function (a, num) { - return this._verify1(a), this.imod(a.ushln(num)); - }), - (Red.prototype.imul = function (a, b) { - return this._verify2(a, b), this.imod(a.imul(b)); - }), - (Red.prototype.mul = function (a, b) { - return this._verify2(a, b), this.imod(a.mul(b)); - }), - (Red.prototype.isqr = function (a) { - return this.imul(a, a.clone()); - }), - (Red.prototype.sqr = function (a) { - return this.mul(a, a); - }), - (Red.prototype.sqrt = function (a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - if ((assert(mod3 % 2 === 1), mod3 === 3)) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - for (var q = this.m.subn(1), s = 0; !q.isZero() && q.andln(1) === 0; ) s++, q.iushrn(1); - assert(!q.isZero()); - var one = new BN(1).toRed(this), - nOne = one.redNeg(), - lpow = this.m.subn(1).iushrn(1), - z = this.m.bitLength(); - for (z = new BN(2 * z * z).toRed(this); this.pow(z, lpow).cmp(nOne) !== 0; ) z.redIAdd(nOne); - for ( - var c = this.pow(z, q), r = this.pow(a, q.addn(1).iushrn(1)), t = this.pow(a, q), m = s; - t.cmp(one) !== 0; - - ) { - for (var tmp = t, i = 0; tmp.cmp(one) !== 0; i++) tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - (r = r.redMul(b)), (c = b.redSqr()), (t = t.redMul(c)), (m = i); - } - return r; - }), - (Red.prototype.invm = function (a) { - var inv = a._invmp(this.m); - return inv.negative !== 0 ? ((inv.negative = 0), this.imod(inv).redNeg()) : this.imod(inv); - }), - (Red.prototype.pow = function (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4, - wnd = new Array(1 << windowSize); - (wnd[0] = new BN(1).toRed(this)), (wnd[1] = a); - for (var i = 2; i < wnd.length; i++) wnd[i] = this.mul(wnd[i - 1], a); - var res = wnd[0], - current = 0, - currentLen = 0, - start = num.bitLength() % 26; - for (start === 0 && (start = 26), i = num.length - 1; i >= 0; i--) { - for (var word = num.words[i], j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if ((res !== wnd[0] && (res = this.sqr(res)), bit === 0 && current === 0)) { - currentLen = 0; - continue; - } - (current <<= 1), - (current |= bit), - currentLen++, - !(currentLen !== windowSize && (i !== 0 || j !== 0)) && - ((res = this.mul(res, wnd[current])), (currentLen = 0), (current = 0)); - } - start = 26; - } - return res; - }), - (Red.prototype.convertTo = function (num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }), - (Red.prototype.convertFrom = function (num) { - var res = num.clone(); - return (res.red = null), res; - }), - (BN.mont = function (num) { - return new Mont(num); - }); - function Mont(m) { - Red.call(this, m), - (this.shift = this.m.bitLength()), - this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), - (this.r = new BN(1).iushln(this.shift)), - (this.r2 = this.imod(this.r.sqr())), - (this.rinv = this.r._invmp(this.m)), - (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), - (this.minv = this.minv.umod(this.r)), - (this.minv = this.r.sub(this.minv)); - } - inherits(Mont, Red), - (Mont.prototype.convertTo = function (num) { - return this.imod(num.ushln(this.shift)); - }), - (Mont.prototype.convertFrom = function (num) { - var r = this.imod(num.mul(this.rinv)); - return (r.red = null), r; - }), - (Mont.prototype.imul = function (a, b) { - if (a.isZero() || b.isZero()) return (a.words[0] = 0), (a.length = 1), a; - var t = a.imul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.mul = function (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.invm = function (a) { - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }); - })(typeof module > "u" || module, exports); - }, -}); - -// node_modules/minimalistic-crypto-utils/lib/utils.js -var require_utils2 = __commonJS({ - "node_modules/minimalistic-crypto-utils/lib/utils.js"(exports) { - "use strict"; - var utils = exports; - function toArray(msg, enc) { - if (Array.isArray(msg)) return msg.slice(); - if (!msg) return []; - var res = []; - if (typeof msg != "string") { - for (var i = 0; i < msg.length; i++) res[i] = msg[i] | 0; - return res; - } - if (enc === "hex") { - (msg = msg.replace(/[^a-z0-9]+/gi, "")), msg.length % 2 !== 0 && (msg = "0" + msg); - for (var i = 0; i < msg.length; i += 2) res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i), - hi = c >> 8, - lo = c & 255; - hi ? res.push(hi, lo) : res.push(lo); - } - return res; - } - utils.toArray = toArray; - function zero2(word) { - return word.length === 1 ? "0" + word : word; - } - utils.zero2 = zero2; - function toHex(msg) { - for (var res = "", i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); - return res; - } - utils.toHex = toHex; - utils.encode = function (arr, enc) { - return enc === "hex" ? toHex(arr) : arr; - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/utils.js -var require_utils3 = __commonJS({ - "node_modules/elliptic/lib/elliptic/utils.js"(exports) { - "use strict"; - var utils = exports, - BN = require_bn4(), - minAssert = require_minimalistic_assert(), - minUtils = require_utils2(); - utils.assert = minAssert; - utils.toArray = minUtils.toArray; - utils.zero2 = minUtils.zero2; - utils.toHex = minUtils.toHex; - utils.encode = minUtils.encode; - function getNAF(num, w, bits) { - var naf = new Array(Math.max(num.bitLength(), bits) + 1); - naf.fill(0); - for (var ws = 1 << (w + 1), k = num.clone(), i = 0; i < naf.length; i++) { - var z, - mod = k.andln(ws - 1); - k.isOdd() ? (mod > (ws >> 1) - 1 ? (z = (ws >> 1) - mod) : (z = mod), k.isubn(z)) : (z = 0), - (naf[i] = z), - k.iushrn(1); - } - return naf; - } - utils.getNAF = getNAF; - function getJSF(k1, k2) { - var jsf = [[], []]; - (k1 = k1.clone()), (k2 = k2.clone()); - for (var d1 = 0, d2 = 0, m8; k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0; ) { - var m14 = (k1.andln(3) + d1) & 3, - m24 = (k2.andln(3) + d2) & 3; - m14 === 3 && (m14 = -1), m24 === 3 && (m24 = -1); - var u1; - (m14 & 1) === 0 - ? (u1 = 0) - : ((m8 = (k1.andln(7) + d1) & 7), (m8 === 3 || m8 === 5) && m24 === 2 ? (u1 = -m14) : (u1 = m14)), - jsf[0].push(u1); - var u2; - (m24 & 1) === 0 - ? (u2 = 0) - : ((m8 = (k2.andln(7) + d2) & 7), (m8 === 3 || m8 === 5) && m14 === 2 ? (u2 = -m24) : (u2 = m24)), - jsf[1].push(u2), - 2 * d1 === u1 + 1 && (d1 = 1 - d1), - 2 * d2 === u2 + 1 && (d2 = 1 - d2), - k1.iushrn(1), - k2.iushrn(1); - } - return jsf; - } - utils.getJSF = getJSF; - function cachedProperty(obj, name, computer) { - var key = "_" + name; - obj.prototype[name] = function () { - return this[key] !== void 0 ? this[key] : (this[key] = computer.call(this)); - }; - } - utils.cachedProperty = cachedProperty; - function parseBytes(bytes) { - return typeof bytes == "string" ? utils.toArray(bytes, "hex") : bytes; - } - utils.parseBytes = parseBytes; - function intFromLE(bytes) { - return new BN(bytes, "hex", "le"); - } - utils.intFromLE = intFromLE; - }, -}); - -// node_modules/elliptic/lib/elliptic/curve/base.js -var require_base = __commonJS({ - "node_modules/elliptic/lib/elliptic/curve/base.js"(exports, module) { - "use strict"; - var BN = require_bn4(), - utils = require_utils3(), - getNAF = utils.getNAF, - getJSF = utils.getJSF, - assert = utils.assert; - function BaseCurve(type, conf) { - (this.type = type), - (this.p = new BN(conf.p, 16)), - (this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p)), - (this.zero = new BN(0).toRed(this.red)), - (this.one = new BN(1).toRed(this.red)), - (this.two = new BN(2).toRed(this.red)), - (this.n = conf.n && new BN(conf.n, 16)), - (this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed)), - (this._wnafT1 = new Array(4)), - (this._wnafT2 = new Array(4)), - (this._wnafT3 = new Array(4)), - (this._wnafT4 = new Array(4)), - (this._bitLength = this.n ? this.n.bitLength() : 0); - var adjustCount = this.n && this.p.div(this.n); - !adjustCount || adjustCount.cmpn(100) > 0 - ? (this.redN = null) - : ((this._maxwellTrick = !0), (this.redN = this.n.toRed(this.red))); - } - module.exports = BaseCurve; - BaseCurve.prototype.point = function () { - throw new Error("Not implemented"); - }; - BaseCurve.prototype.validate = function () { - throw new Error("Not implemented"); - }; - BaseCurve.prototype._fixedNafMul = function (p, k) { - assert(p.precomputed); - var doubles = p._getDoubles(), - naf = getNAF(k, 1, this._bitLength), - I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - var repr = [], - j, - nafW; - for (j = 0; j < naf.length; j += doubles.step) { - nafW = 0; - for (var l = j + doubles.step - 1; l >= j; l--) nafW = (nafW << 1) + naf[l]; - repr.push(nafW); - } - for (var a = this.jpoint(null, null, null), b = this.jpoint(null, null, null), i = I; i > 0; i--) { - for (j = 0; j < repr.length; j++) - (nafW = repr[j]), - nafW === i ? (b = b.mixedAdd(doubles.points[j])) : nafW === -i && (b = b.mixedAdd(doubles.points[j].neg())); - a = a.add(b); - } - return a.toP(); - }; - BaseCurve.prototype._wnafMul = function (p, k) { - var w = 4, - nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - for ( - var wnd = nafPoints.points, - naf = getNAF(k, w, this._bitLength), - acc = this.jpoint(null, null, null), - i = naf.length - 1; - i >= 0; - i-- - ) { - for (var l = 0; i >= 0 && naf[i] === 0; i--) l++; - if ((i >= 0 && l++, (acc = acc.dblp(l)), i < 0)) break; - var z = naf[i]; - assert(z !== 0), - p.type === "affine" - ? z > 0 - ? (acc = acc.mixedAdd(wnd[(z - 1) >> 1])) - : (acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg())) - : z > 0 - ? (acc = acc.add(wnd[(z - 1) >> 1])) - : (acc = acc.add(wnd[(-z - 1) >> 1].neg())); - } - return p.type === "affine" ? acc.toP() : acc; - }; - BaseCurve.prototype._wnafMulAdd = function (defW, points, coeffs, len, jacobianResult) { - var wndWidth = this._wnafT1, - wnd = this._wnafT2, - naf = this._wnafT3, - max = 0, - i, - j, - p; - for (i = 0; i < len; i++) { - p = points[i]; - var nafPoints = p._getNAFPoints(defW); - (wndWidth[i] = nafPoints.wnd), (wnd[i] = nafPoints.points); - } - for (i = len - 1; i >= 1; i -= 2) { - var a = i - 1, - b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - (naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength)), - (naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength)), - (max = Math.max(naf[a].length, max)), - (max = Math.max(naf[b].length, max)); - continue; - } - var comb = [points[a], null, null, points[b]]; - points[a].y.cmp(points[b].y) === 0 - ? ((comb[1] = points[a].add(points[b])), (comb[2] = points[a].toJ().mixedAdd(points[b].neg()))) - : points[a].y.cmp(points[b].y.redNeg()) === 0 - ? ((comb[1] = points[a].toJ().mixedAdd(points[b])), (comb[2] = points[a].add(points[b].neg()))) - : ((comb[1] = points[a].toJ().mixedAdd(points[b])), (comb[2] = points[a].toJ().mixedAdd(points[b].neg()))); - var index = [-3, -1, -5, -7, 0, 7, 5, 1, 3], - jsf = getJSF(coeffs[a], coeffs[b]); - for ( - max = Math.max(jsf[0].length, max), naf[a] = new Array(max), naf[b] = new Array(max), j = 0; - j < max; - j++ - ) { - var ja = jsf[0][j] | 0, - jb = jsf[1][j] | 0; - (naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]), (naf[b][j] = 0), (wnd[a] = comb); - } - } - var acc = this.jpoint(null, null, null), - tmp = this._wnafT4; - for (i = max; i >= 0; i--) { - for (var k = 0; i >= 0; ) { - var zero = !0; - for (j = 0; j < len; j++) (tmp[j] = naf[j][i] | 0), tmp[j] !== 0 && (zero = !1); - if (!zero) break; - k++, i--; - } - if ((i >= 0 && k++, (acc = acc.dblp(k)), i < 0)) break; - for (j = 0; j < len; j++) { - var z = tmp[j]; - z !== 0 && - (z > 0 ? (p = wnd[j][(z - 1) >> 1]) : z < 0 && (p = wnd[j][(-z - 1) >> 1].neg()), - p.type === "affine" ? (acc = acc.mixedAdd(p)) : (acc = acc.add(p))); - } - } - for (i = 0; i < len; i++) wnd[i] = null; - return jacobianResult ? acc : acc.toP(); - }; - function BasePoint(curve, type) { - (this.curve = curve), (this.type = type), (this.precomputed = null); - } - BaseCurve.BasePoint = BasePoint; - BasePoint.prototype.eq = function () { - throw new Error("Not implemented"); - }; - BasePoint.prototype.validate = function () { - return this.curve.validate(this); - }; - BaseCurve.prototype.decodePoint = function (bytes, enc) { - bytes = utils.toArray(bytes, enc); - var len = this.p.byteLength(); - if ((bytes[0] === 4 || bytes[0] === 6 || bytes[0] === 7) && bytes.length - 1 === 2 * len) { - bytes[0] === 6 - ? assert(bytes[bytes.length - 1] % 2 === 0) - : bytes[0] === 7 && assert(bytes[bytes.length - 1] % 2 === 1); - var res = this.point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len)); - return res; - } else if ((bytes[0] === 2 || bytes[0] === 3) && bytes.length - 1 === len) - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 3); - throw new Error("Unknown point format"); - }; - BasePoint.prototype.encodeCompressed = function (enc) { - return this.encode(enc, !0); - }; - BasePoint.prototype._encode = function (compact) { - var len = this.curve.p.byteLength(), - x = this.getX().toArray("be", len); - return compact ? [this.getY().isEven() ? 2 : 3].concat(x) : [4].concat(x, this.getY().toArray("be", len)); - }; - BasePoint.prototype.encode = function (enc, compact) { - return utils.encode(this._encode(compact), enc); - }; - BasePoint.prototype.precompute = function (power) { - if (this.precomputed) return this; - var precomputed = { - doubles: null, - naf: null, - beta: null, - }; - return ( - (precomputed.naf = this._getNAFPoints(8)), - (precomputed.doubles = this._getDoubles(4, power)), - (precomputed.beta = this._getBeta()), - (this.precomputed = precomputed), - this - ); - }; - BasePoint.prototype._hasDoubles = function (k) { - if (!this.precomputed) return !1; - var doubles = this.precomputed.doubles; - return doubles ? doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step) : !1; - }; - BasePoint.prototype._getDoubles = function (step, power) { - if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; - for (var doubles = [this], acc = this, i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) acc = acc.dbl(); - doubles.push(acc); - } - return { - step, - points: doubles, - }; - }; - BasePoint.prototype._getNAFPoints = function (wnd) { - if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; - for (var res = [this], max = (1 << wnd) - 1, dbl = max === 1 ? null : this.dbl(), i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd, - points: res, - }; - }; - BasePoint.prototype._getBeta = function () { - return null; - }; - BasePoint.prototype.dblp = function (k) { - for (var r = this, i = 0; i < k; i++) r = r.dbl(); - return r; - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/curve/short.js -var require_short = __commonJS({ - "node_modules/elliptic/lib/elliptic/curve/short.js"(exports, module) { - "use strict"; - var utils = require_utils3(), - BN = require_bn4(), - inherits = require_inherits_browser(), - Base = require_base(), - assert = utils.assert; - function ShortCurve(conf) { - Base.call(this, "short", conf), - (this.a = new BN(conf.a, 16).toRed(this.red)), - (this.b = new BN(conf.b, 16).toRed(this.red)), - (this.tinv = this.two.redInvm()), - (this.zeroA = this.a.fromRed().cmpn(0) === 0), - (this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0), - (this.endo = this._getEndomorphism(conf)), - (this._endoWnafT1 = new Array(4)), - (this._endoWnafT2 = new Array(4)); - } - inherits(ShortCurve, Base); - module.exports = ShortCurve; - ShortCurve.prototype._getEndomorphism = function (conf) { - if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { - var beta, lambda; - if (conf.beta) beta = new BN(conf.beta, 16).toRed(this.red); - else { - var betas = this._getEndoRoots(this.p); - (beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]), (beta = beta.toRed(this.red)); - } - if (conf.lambda) lambda = new BN(conf.lambda, 16); - else { - var lambdas = this._getEndoRoots(this.n); - this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0 - ? (lambda = lambdas[0]) - : ((lambda = lambdas[1]), assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0)); - } - var basis; - return ( - conf.basis - ? (basis = conf.basis.map(function (vec) { - return { - a: new BN(vec.a, 16), - b: new BN(vec.b, 16), - }; - })) - : (basis = this._getEndoBasis(lambda)), - { - beta, - lambda, - basis, - } - ); - } - }; - ShortCurve.prototype._getEndoRoots = function (num) { - var red = num === this.p ? this.red : BN.mont(num), - tinv = new BN(2).toRed(red).redInvm(), - ntinv = tinv.redNeg(), - s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv), - l1 = ntinv.redAdd(s).fromRed(), - l2 = ntinv.redSub(s).fromRed(); - return [l1, l2]; - }; - ShortCurve.prototype._getEndoBasis = function (lambda) { - for ( - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), - u = lambda, - v = this.n.clone(), - x1 = new BN(1), - y1 = new BN(0), - x2 = new BN(0), - y2 = new BN(1), - a0, - b0, - a1, - b1, - a2, - b2, - prevR, - i = 0, - r, - x; - u.cmpn(0) !== 0; - - ) { - var q = v.div(u); - (r = v.sub(q.mul(u))), (x = x2.sub(q.mul(x1))); - var y = y2.sub(q.mul(y1)); - if (!a1 && r.cmp(aprxSqrt) < 0) (a0 = prevR.neg()), (b0 = x1), (a1 = r.neg()), (b1 = x); - else if (a1 && ++i === 2) break; - (prevR = r), (v = u), (u = r), (x2 = x1), (x1 = x), (y2 = y1), (y1 = y); - } - (a2 = r.neg()), (b2 = x); - var len1 = a1.sqr().add(b1.sqr()), - len2 = a2.sqr().add(b2.sqr()); - return ( - len2.cmp(len1) >= 0 && ((a2 = a0), (b2 = b0)), - a1.negative && ((a1 = a1.neg()), (b1 = b1.neg())), - a2.negative && ((a2 = a2.neg()), (b2 = b2.neg())), - [ - { a: a1, b: b1 }, - { a: a2, b: b2 }, - ] - ); - }; - ShortCurve.prototype._endoSplit = function (k) { - var basis = this.endo.basis, - v1 = basis[0], - v2 = basis[1], - c1 = v2.b.mul(k).divRound(this.n), - c2 = v1.b.neg().mul(k).divRound(this.n), - p1 = c1.mul(v1.a), - p2 = c2.mul(v2.a), - q1 = c1.mul(v1.b), - q2 = c2.mul(v2.b), - k1 = k.sub(p1).sub(p2), - k2 = q1.add(q2).neg(); - return { k1, k2 }; - }; - ShortCurve.prototype.pointFromX = function (x, odd) { - (x = new BN(x, 16)), x.red || (x = x.toRed(this.red)); - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b), - y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error("invalid point"); - var isOdd = y.fromRed().isOdd(); - return ((odd && !isOdd) || (!odd && isOdd)) && (y = y.redNeg()), this.point(x, y); - }; - ShortCurve.prototype.validate = function (point) { - if (point.inf) return !0; - var x = point.x, - y = point.y, - ax = this.a.redMul(x), - rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; - }; - ShortCurve.prototype._endoWnafMulAdd = function (points, coeffs, jacobianResult) { - for (var npoints = this._endoWnafT1, ncoeffs = this._endoWnafT2, i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]), - p = points[i], - beta = p._getBeta(); - split.k1.negative && (split.k1.ineg(), (p = p.neg(!0))), - split.k2.negative && (split.k2.ineg(), (beta = beta.neg(!0))), - (npoints[i * 2] = p), - (npoints[i * 2 + 1] = beta), - (ncoeffs[i * 2] = split.k1), - (ncoeffs[i * 2 + 1] = split.k2); - } - for (var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult), j = 0; j < i * 2; j++) - (npoints[j] = null), (ncoeffs[j] = null); - return res; - }; - function Point(curve, x, y, isRed) { - Base.BasePoint.call(this, curve, "affine"), - x === null && y === null - ? ((this.x = null), (this.y = null), (this.inf = !0)) - : ((this.x = new BN(x, 16)), - (this.y = new BN(y, 16)), - isRed && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), - this.x.red || (this.x = this.x.toRed(this.curve.red)), - this.y.red || (this.y = this.y.toRed(this.curve.red)), - (this.inf = !1)); - } - inherits(Point, Base.BasePoint); - ShortCurve.prototype.point = function (x, y, isRed) { - return new Point(this, x, y, isRed); - }; - ShortCurve.prototype.pointFromJSON = function (obj, red) { - return Point.fromJSON(this, obj, red); - }; - Point.prototype._getBeta = function () { - if (!!this.curve.endo) { - var pre = this.precomputed; - if (pre && pre.beta) return pre.beta; - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve, - endoMul = function (p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - (pre.beta = beta), - (beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul), - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul), - }, - }); - } - return beta; - } - }; - Point.prototype.toJSON = function () { - return this.precomputed - ? [ - this.x, - this.y, - this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1), - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1), - }, - }, - ] - : [this.x, this.y]; - }; - Point.fromJSON = function (curve, obj, red) { - typeof obj == "string" && (obj = JSON.parse(obj)); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) return res; - function obj2point(obj2) { - return curve.point(obj2[0], obj2[1], red); - } - var pre = obj[2]; - return ( - (res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [res].concat(pre.doubles.points.map(obj2point)), - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [res].concat(pre.naf.points.map(obj2point)), - }, - }), - res - ); - }; - Point.prototype.inspect = function () { - return this.isInfinity() - ? "" - : ""; - }; - Point.prototype.isInfinity = function () { - return this.inf; - }; - Point.prototype.add = function (p) { - if (this.inf) return p; - if (p.inf) return this; - if (this.eq(p)) return this.dbl(); - if (this.neg().eq(p)) return this.curve.point(null, null); - if (this.x.cmp(p.x) === 0) return this.curve.point(null, null); - var c = this.y.redSub(p.y); - c.cmpn(0) !== 0 && (c = c.redMul(this.x.redSub(p.x).redInvm())); - var nx = c.redSqr().redISub(this.x).redISub(p.x), - ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); - }; - Point.prototype.dbl = function () { - if (this.inf) return this; - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) return this.curve.point(null, null); - var a = this.curve.a, - x2 = this.x.redSqr(), - dyinv = ys1.redInvm(), - c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv), - nx = c.redSqr().redISub(this.x.redAdd(this.x)), - ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); - }; - Point.prototype.getX = function () { - return this.x.fromRed(); - }; - Point.prototype.getY = function () { - return this.y.fromRed(); - }; - Point.prototype.mul = function (k) { - return ( - (k = new BN(k, 16)), - this.isInfinity() - ? this - : this._hasDoubles(k) - ? this.curve._fixedNafMul(this, k) - : this.curve.endo - ? this.curve._endoWnafMulAdd([this], [k]) - : this.curve._wnafMul(this, k) - ); - }; - Point.prototype.mulAdd = function (k1, p2, k2) { - var points = [this, p2], - coeffs = [k1, k2]; - return this.curve.endo - ? this.curve._endoWnafMulAdd(points, coeffs) - : this.curve._wnafMulAdd(1, points, coeffs, 2); - }; - Point.prototype.jmulAdd = function (k1, p2, k2) { - var points = [this, p2], - coeffs = [k1, k2]; - return this.curve.endo - ? this.curve._endoWnafMulAdd(points, coeffs, !0) - : this.curve._wnafMulAdd(1, points, coeffs, 2, !0); - }; - Point.prototype.eq = function (p) { - return this === p || (this.inf === p.inf && (this.inf || (this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0))); - }; - Point.prototype.neg = function (_precompute) { - if (this.inf) return this; - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed, - negate = function (p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate), - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate), - }, - }; - } - return res; - }; - Point.prototype.toJ = function () { - if (this.inf) return this.curve.jpoint(null, null, null); - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; - }; - function JPoint(curve, x, y, z) { - Base.BasePoint.call(this, curve, "jacobian"), - x === null && y === null && z === null - ? ((this.x = this.curve.one), (this.y = this.curve.one), (this.z = new BN(0))) - : ((this.x = new BN(x, 16)), (this.y = new BN(y, 16)), (this.z = new BN(z, 16))), - this.x.red || (this.x = this.x.toRed(this.curve.red)), - this.y.red || (this.y = this.y.toRed(this.curve.red)), - this.z.red || (this.z = this.z.toRed(this.curve.red)), - (this.zOne = this.z === this.curve.one); - } - inherits(JPoint, Base.BasePoint); - ShortCurve.prototype.jpoint = function (x, y, z) { - return new JPoint(this, x, y, z); - }; - JPoint.prototype.toP = function () { - if (this.isInfinity()) return this.curve.point(null, null); - var zinv = this.z.redInvm(), - zinv2 = zinv.redSqr(), - ax = this.x.redMul(zinv2), - ay = this.y.redMul(zinv2).redMul(zinv); - return this.curve.point(ax, ay); - }; - JPoint.prototype.neg = function () { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); - }; - JPoint.prototype.add = function (p) { - if (this.isInfinity()) return p; - if (p.isInfinity()) return this; - var pz2 = p.z.redSqr(), - z2 = this.z.redSqr(), - u1 = this.x.redMul(pz2), - u2 = p.x.redMul(z2), - s1 = this.y.redMul(pz2.redMul(p.z)), - s2 = p.y.redMul(z2.redMul(this.z)), - h = u1.redSub(u2), - r = s1.redSub(s2); - if (h.cmpn(0) === 0) return r.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); - var h2 = h.redSqr(), - h3 = h2.redMul(h), - v = u1.redMul(h2), - nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v), - ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)), - nz = this.z.redMul(p.z).redMul(h); - return this.curve.jpoint(nx, ny, nz); - }; - JPoint.prototype.mixedAdd = function (p) { - if (this.isInfinity()) return p.toJ(); - if (p.isInfinity()) return this; - var z2 = this.z.redSqr(), - u1 = this.x, - u2 = p.x.redMul(z2), - s1 = this.y, - s2 = p.y.redMul(z2).redMul(this.z), - h = u1.redSub(u2), - r = s1.redSub(s2); - if (h.cmpn(0) === 0) return r.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); - var h2 = h.redSqr(), - h3 = h2.redMul(h), - v = u1.redMul(h2), - nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v), - ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)), - nz = this.z.redMul(h); - return this.curve.jpoint(nx, ny, nz); - }; - JPoint.prototype.dblp = function (pow) { - if (pow === 0) return this; - if (this.isInfinity()) return this; - if (!pow) return this.dbl(); - var i; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (i = 0; i < pow; i++) r = r.dbl(); - return r; - } - var a = this.curve.a, - tinv = this.curve.tinv, - jx = this.x, - jy = this.y, - jz = this.z, - jz4 = jz.redSqr().redSqr(), - jyd = jy.redAdd(jy); - for (i = 0; i < pow; i++) { - var jx2 = jx.redSqr(), - jyd2 = jyd.redSqr(), - jyd4 = jyd2.redSqr(), - c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)), - t1 = jx.redMul(jyd2), - nx = c.redSqr().redISub(t1.redAdd(t1)), - t2 = t1.redISub(nx), - dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - i + 1 < pow && (jz4 = jz4.redMul(jyd4)), (jx = nx), (jz = nz), (jyd = dny); - } - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); - }; - JPoint.prototype.dbl = function () { - return this.isInfinity() - ? this - : this.curve.zeroA - ? this._zeroDbl() - : this.curve.threeA - ? this._threeDbl() - : this._dbl(); - }; - JPoint.prototype._zeroDbl = function () { - var nx, ny, nz; - if (this.zOne) { - var xx = this.x.redSqr(), - yy = this.y.redSqr(), - yyyy = yy.redSqr(), - s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - var m = xx.redAdd(xx).redIAdd(xx), - t = m.redSqr().redISub(s).redISub(s), - yyyy8 = yyyy.redIAdd(yyyy); - (yyyy8 = yyyy8.redIAdd(yyyy8)), - (yyyy8 = yyyy8.redIAdd(yyyy8)), - (nx = t), - (ny = m.redMul(s.redISub(t)).redISub(yyyy8)), - (nz = this.y.redAdd(this.y)); - } else { - var a = this.x.redSqr(), - b = this.y.redSqr(), - c = b.redSqr(), - d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - var e = a.redAdd(a).redIAdd(a), - f = e.redSqr(), - c8 = c.redIAdd(c); - (c8 = c8.redIAdd(c8)), - (c8 = c8.redIAdd(c8)), - (nx = f.redISub(d).redISub(d)), - (ny = e.redMul(d.redISub(nx)).redISub(c8)), - (nz = this.y.redMul(this.z)), - (nz = nz.redIAdd(nz)); - } - return this.curve.jpoint(nx, ny, nz); - }; - JPoint.prototype._threeDbl = function () { - var nx, ny, nz; - if (this.zOne) { - var xx = this.x.redSqr(), - yy = this.y.redSqr(), - yyyy = yy.redSqr(), - s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a), - t = m.redSqr().redISub(s).redISub(s); - nx = t; - var yyyy8 = yyyy.redIAdd(yyyy); - (yyyy8 = yyyy8.redIAdd(yyyy8)), - (yyyy8 = yyyy8.redIAdd(yyyy8)), - (ny = m.redMul(s.redISub(t)).redISub(yyyy8)), - (nz = this.y.redAdd(this.y)); - } else { - var delta = this.z.redSqr(), - gamma = this.y.redSqr(), - beta = this.x.redMul(gamma), - alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - (nx = alpha.redSqr().redISub(beta8)), (nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta)); - var ggamma8 = gamma.redSqr(); - (ggamma8 = ggamma8.redIAdd(ggamma8)), - (ggamma8 = ggamma8.redIAdd(ggamma8)), - (ggamma8 = ggamma8.redIAdd(ggamma8)), - (ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8)); - } - return this.curve.jpoint(nx, ny, nz); - }; - JPoint.prototype._dbl = function () { - var a = this.curve.a, - jx = this.x, - jy = this.y, - jz = this.z, - jz4 = jz.redSqr().redSqr(), - jx2 = jx.redSqr(), - jy2 = jy.redSqr(), - c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)), - jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2), - nx = c.redSqr().redISub(t1.redAdd(t1)), - t2 = t1.redISub(nx), - jyd8 = jy2.redSqr(); - (jyd8 = jyd8.redIAdd(jyd8)), (jyd8 = jyd8.redIAdd(jyd8)), (jyd8 = jyd8.redIAdd(jyd8)); - var ny = c.redMul(t2).redISub(jyd8), - nz = jy.redAdd(jy).redMul(jz); - return this.curve.jpoint(nx, ny, nz); - }; - JPoint.prototype.trpl = function () { - if (!this.curve.zeroA) return this.dbl().add(this); - var xx = this.x.redSqr(), - yy = this.y.redSqr(), - zz = this.z.redSqr(), - yyyy = yy.redSqr(), - m = xx.redAdd(xx).redIAdd(xx), - mm = m.redSqr(), - e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - (e = e.redIAdd(e)), (e = e.redAdd(e).redIAdd(e)), (e = e.redISub(mm)); - var ee = e.redSqr(), - t = yyyy.redIAdd(yyyy); - (t = t.redIAdd(t)), (t = t.redIAdd(t)), (t = t.redIAdd(t)); - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t), - yyu4 = yy.redMul(u); - (yyu4 = yyu4.redIAdd(yyu4)), (yyu4 = yyu4.redIAdd(yyu4)); - var nx = this.x.redMul(ee).redISub(yyu4); - (nx = nx.redIAdd(nx)), (nx = nx.redIAdd(nx)); - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - (ny = ny.redIAdd(ny)), (ny = ny.redIAdd(ny)), (ny = ny.redIAdd(ny)); - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - return this.curve.jpoint(nx, ny, nz); - }; - JPoint.prototype.mul = function (k, kbase) { - return (k = new BN(k, kbase)), this.curve._wnafMul(this, k); - }; - JPoint.prototype.eq = function (p) { - if (p.type === "affine") return this.eq(p.toJ()); - if (this === p) return !0; - var z2 = this.z.redSqr(), - pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return !1; - var z3 = z2.redMul(this.z), - pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; - }; - JPoint.prototype.eqXToP = function (x) { - var zs = this.z.redSqr(), - rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) return !0; - for (var xc = x.clone(), t = this.curve.redN.redMul(zs); ; ) { - if ((xc.iadd(this.curve.n), xc.cmp(this.curve.p) >= 0)) return !1; - if ((rx.redIAdd(t), this.x.cmp(rx) === 0)) return !0; - } - }; - JPoint.prototype.inspect = function () { - return this.isInfinity() - ? "" - : ""; - }; - JPoint.prototype.isInfinity = function () { - return this.z.cmpn(0) === 0; - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/curve/mont.js -var require_mont = __commonJS({ - "node_modules/elliptic/lib/elliptic/curve/mont.js"(exports, module) { - "use strict"; - var BN = require_bn4(), - inherits = require_inherits_browser(), - Base = require_base(), - utils = require_utils3(); - function MontCurve(conf) { - Base.call(this, "mont", conf), - (this.a = new BN(conf.a, 16).toRed(this.red)), - (this.b = new BN(conf.b, 16).toRed(this.red)), - (this.i4 = new BN(4).toRed(this.red).redInvm()), - (this.two = new BN(2).toRed(this.red)), - (this.a24 = this.i4.redMul(this.a.redAdd(this.two))); - } - inherits(MontCurve, Base); - module.exports = MontCurve; - MontCurve.prototype.validate = function (point) { - var x = point.normalize().x, - x2 = x.redSqr(), - rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x), - y = rhs.redSqrt(); - return y.redSqr().cmp(rhs) === 0; - }; - function Point(curve, x, z) { - Base.BasePoint.call(this, curve, "projective"), - x === null && z === null - ? ((this.x = this.curve.one), (this.z = this.curve.zero)) - : ((this.x = new BN(x, 16)), - (this.z = new BN(z, 16)), - this.x.red || (this.x = this.x.toRed(this.curve.red)), - this.z.red || (this.z = this.z.toRed(this.curve.red))); - } - inherits(Point, Base.BasePoint); - MontCurve.prototype.decodePoint = function (bytes, enc) { - return this.point(utils.toArray(bytes, enc), 1); - }; - MontCurve.prototype.point = function (x, z) { - return new Point(this, x, z); - }; - MontCurve.prototype.pointFromJSON = function (obj) { - return Point.fromJSON(this, obj); - }; - Point.prototype.precompute = function () {}; - Point.prototype._encode = function () { - return this.getX().toArray("be", this.curve.p.byteLength()); - }; - Point.fromJSON = function (curve, obj) { - return new Point(curve, obj[0], obj[1] || curve.one); - }; - Point.prototype.inspect = function () { - return this.isInfinity() - ? "" - : ""; - }; - Point.prototype.isInfinity = function () { - return this.z.cmpn(0) === 0; - }; - Point.prototype.dbl = function () { - var a = this.x.redAdd(this.z), - aa = a.redSqr(), - b = this.x.redSub(this.z), - bb = b.redSqr(), - c = aa.redSub(bb), - nx = aa.redMul(bb), - nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); - }; - Point.prototype.add = function () { - throw new Error("Not supported on Montgomery curve"); - }; - Point.prototype.diffAdd = function (p, diff) { - var a = this.x.redAdd(this.z), - b = this.x.redSub(this.z), - c = p.x.redAdd(p.z), - d = p.x.redSub(p.z), - da = d.redMul(a), - cb = c.redMul(b), - nx = diff.z.redMul(da.redAdd(cb).redSqr()), - nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); - }; - Point.prototype.mul = function (k) { - for ( - var t = k.clone(), a = this, b = this.curve.point(null, null), c = this, bits = []; - t.cmpn(0) !== 0; - t.iushrn(1) - ) - bits.push(t.andln(1)); - for (var i = bits.length - 1; i >= 0; i--) - bits[i] === 0 ? ((a = a.diffAdd(b, c)), (b = b.dbl())) : ((b = a.diffAdd(b, c)), (a = a.dbl())); - return b; - }; - Point.prototype.mulAdd = function () { - throw new Error("Not supported on Montgomery curve"); - }; - Point.prototype.jumlAdd = function () { - throw new Error("Not supported on Montgomery curve"); - }; - Point.prototype.eq = function (other) { - return this.getX().cmp(other.getX()) === 0; - }; - Point.prototype.normalize = function () { - return (this.x = this.x.redMul(this.z.redInvm())), (this.z = this.curve.one), this; - }; - Point.prototype.getX = function () { - return this.normalize(), this.x.fromRed(); - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/curve/edwards.js -var require_edwards = __commonJS({ - "node_modules/elliptic/lib/elliptic/curve/edwards.js"(exports, module) { - "use strict"; - var utils = require_utils3(), - BN = require_bn4(), - inherits = require_inherits_browser(), - Base = require_base(), - assert = utils.assert; - function EdwardsCurve(conf) { - (this.twisted = (conf.a | 0) !== 1), - (this.mOneA = this.twisted && (conf.a | 0) === -1), - (this.extended = this.mOneA), - Base.call(this, "edwards", conf), - (this.a = new BN(conf.a, 16).umod(this.red.m)), - (this.a = this.a.toRed(this.red)), - (this.c = new BN(conf.c, 16).toRed(this.red)), - (this.c2 = this.c.redSqr()), - (this.d = new BN(conf.d, 16).toRed(this.red)), - (this.dd = this.d.redAdd(this.d)), - assert(!this.twisted || this.c.fromRed().cmpn(1) === 0), - (this.oneC = (conf.c | 0) === 1); - } - inherits(EdwardsCurve, Base); - module.exports = EdwardsCurve; - EdwardsCurve.prototype._mulA = function (num) { - return this.mOneA ? num.redNeg() : this.a.redMul(num); - }; - EdwardsCurve.prototype._mulC = function (num) { - return this.oneC ? num : this.c.redMul(num); - }; - EdwardsCurve.prototype.jpoint = function (x, y, z, t) { - return this.point(x, y, z, t); - }; - EdwardsCurve.prototype.pointFromX = function (x, odd) { - (x = new BN(x, 16)), x.red || (x = x.toRed(this.red)); - var x2 = x.redSqr(), - rhs = this.c2.redSub(this.a.redMul(x2)), - lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)), - y2 = rhs.redMul(lhs.redInvm()), - y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error("invalid point"); - var isOdd = y.fromRed().isOdd(); - return ((odd && !isOdd) || (!odd && isOdd)) && (y = y.redNeg()), this.point(x, y); - }; - EdwardsCurve.prototype.pointFromY = function (y, odd) { - (y = new BN(y, 16)), y.red || (y = y.toRed(this.red)); - var y2 = y.redSqr(), - lhs = y2.redSub(this.c2), - rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a), - x2 = lhs.redMul(rhs.redInvm()); - if (x2.cmp(this.zero) === 0) { - if (odd) throw new Error("invalid point"); - return this.point(this.zero, y); - } - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) throw new Error("invalid point"); - return x.fromRed().isOdd() !== odd && (x = x.redNeg()), this.point(x, y); - }; - EdwardsCurve.prototype.validate = function (point) { - if (point.isInfinity()) return !0; - point.normalize(); - var x2 = point.x.redSqr(), - y2 = point.y.redSqr(), - lhs = x2.redMul(this.a).redAdd(y2), - rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - return lhs.cmp(rhs) === 0; - }; - function Point(curve, x, y, z, t) { - Base.BasePoint.call(this, curve, "projective"), - x === null && y === null && z === null - ? ((this.x = this.curve.zero), - (this.y = this.curve.one), - (this.z = this.curve.one), - (this.t = this.curve.zero), - (this.zOne = !0)) - : ((this.x = new BN(x, 16)), - (this.y = new BN(y, 16)), - (this.z = z ? new BN(z, 16) : this.curve.one), - (this.t = t && new BN(t, 16)), - this.x.red || (this.x = this.x.toRed(this.curve.red)), - this.y.red || (this.y = this.y.toRed(this.curve.red)), - this.z.red || (this.z = this.z.toRed(this.curve.red)), - this.t && !this.t.red && (this.t = this.t.toRed(this.curve.red)), - (this.zOne = this.z === this.curve.one), - this.curve.extended && - !this.t && - ((this.t = this.x.redMul(this.y)), this.zOne || (this.t = this.t.redMul(this.z.redInvm())))); - } - inherits(Point, Base.BasePoint); - EdwardsCurve.prototype.pointFromJSON = function (obj) { - return Point.fromJSON(this, obj); - }; - EdwardsCurve.prototype.point = function (x, y, z, t) { - return new Point(this, x, y, z, t); - }; - Point.fromJSON = function (curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); - }; - Point.prototype.inspect = function () { - return this.isInfinity() - ? "" - : ""; - }; - Point.prototype.isInfinity = function () { - return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || (this.zOne && this.y.cmp(this.curve.c) === 0)); - }; - Point.prototype._extDbl = function () { - var a = this.x.redSqr(), - b = this.y.redSqr(), - c = this.z.redSqr(); - c = c.redIAdd(c); - var d = this.curve._mulA(a), - e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b), - g = d.redAdd(b), - f = g.redSub(c), - h = d.redSub(b), - nx = e.redMul(f), - ny = g.redMul(h), - nt = e.redMul(h), - nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); - }; - Point.prototype._projDbl = function () { - var b = this.x.redAdd(this.y).redSqr(), - c = this.x.redSqr(), - d = this.y.redSqr(), - nx, - ny, - nz, - e, - h, - j; - if (this.curve.twisted) { - e = this.curve._mulA(c); - var f = e.redAdd(d); - this.zOne - ? ((nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two))), - (ny = f.redMul(e.redSub(d))), - (nz = f.redSqr().redSub(f).redSub(f))) - : ((h = this.z.redSqr()), - (j = f.redSub(h).redISub(h)), - (nx = b.redSub(c).redISub(d).redMul(j)), - (ny = f.redMul(e.redSub(d))), - (nz = f.redMul(j))); - } else - (e = c.redAdd(d)), - (h = this.curve._mulC(this.z).redSqr()), - (j = e.redSub(h).redSub(h)), - (nx = this.curve._mulC(b.redISub(e)).redMul(j)), - (ny = this.curve._mulC(e).redMul(c.redISub(d))), - (nz = e.redMul(j)); - return this.curve.point(nx, ny, nz); - }; - Point.prototype.dbl = function () { - return this.isInfinity() ? this : this.curve.extended ? this._extDbl() : this._projDbl(); - }; - Point.prototype._extAdd = function (p) { - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)), - b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)), - c = this.t.redMul(this.curve.dd).redMul(p.t), - d = this.z.redMul(p.z.redAdd(p.z)), - e = b.redSub(a), - f = d.redSub(c), - g = d.redAdd(c), - h = b.redAdd(a), - nx = e.redMul(f), - ny = g.redMul(h), - nt = e.redMul(h), - nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); - }; - Point.prototype._projAdd = function (p) { - var a = this.z.redMul(p.z), - b = a.redSqr(), - c = this.x.redMul(p.x), - d = this.y.redMul(p.y), - e = this.curve.d.redMul(c).redMul(d), - f = b.redSub(e), - g = b.redAdd(e), - tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d), - nx = a.redMul(f).redMul(tmp), - ny, - nz; - return ( - this.curve.twisted - ? ((ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)))), (nz = f.redMul(g))) - : ((ny = a.redMul(g).redMul(d.redSub(c))), (nz = this.curve._mulC(f).redMul(g))), - this.curve.point(nx, ny, nz) - ); - }; - Point.prototype.add = function (p) { - return this.isInfinity() ? p : p.isInfinity() ? this : this.curve.extended ? this._extAdd(p) : this._projAdd(p); - }; - Point.prototype.mul = function (k) { - return this._hasDoubles(k) ? this.curve._fixedNafMul(this, k) : this.curve._wnafMul(this, k); - }; - Point.prototype.mulAdd = function (k1, p, k2) { - return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, !1); - }; - Point.prototype.jmulAdd = function (k1, p, k2) { - return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, !0); - }; - Point.prototype.normalize = function () { - if (this.zOne) return this; - var zi = this.z.redInvm(); - return ( - (this.x = this.x.redMul(zi)), - (this.y = this.y.redMul(zi)), - this.t && (this.t = this.t.redMul(zi)), - (this.z = this.curve.one), - (this.zOne = !0), - this - ); - }; - Point.prototype.neg = function () { - return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg()); - }; - Point.prototype.getX = function () { - return this.normalize(), this.x.fromRed(); - }; - Point.prototype.getY = function () { - return this.normalize(), this.y.fromRed(); - }; - Point.prototype.eq = function (other) { - return this === other || (this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0); - }; - Point.prototype.eqXToP = function (x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) return !0; - for (var xc = x.clone(), t = this.curve.redN.redMul(this.z); ; ) { - if ((xc.iadd(this.curve.n), xc.cmp(this.curve.p) >= 0)) return !1; - if ((rx.redIAdd(t), this.x.cmp(rx) === 0)) return !0; - } - }; - Point.prototype.toP = Point.prototype.normalize; - Point.prototype.mixedAdd = Point.prototype.add; - }, -}); - -// node_modules/elliptic/lib/elliptic/curve/index.js -var require_curve = __commonJS({ - "node_modules/elliptic/lib/elliptic/curve/index.js"(exports) { - "use strict"; - var curve = exports; - curve.base = require_base(); - curve.short = require_short(); - curve.mont = require_mont(); - curve.edwards = require_edwards(); - }, -}); - -// node_modules/hash.js/lib/hash/utils.js -var require_utils4 = __commonJS({ - "node_modules/hash.js/lib/hash/utils.js"(exports) { - "use strict"; - var assert = require_minimalistic_assert(), - inherits = require_inherits_browser(); - exports.inherits = inherits; - function isSurrogatePair(msg, i) { - return (msg.charCodeAt(i) & 64512) !== 55296 || i < 0 || i + 1 >= msg.length - ? !1 - : (msg.charCodeAt(i + 1) & 64512) === 56320; - } - function toArray(msg, enc) { - if (Array.isArray(msg)) return msg.slice(); - if (!msg) return []; - var res = []; - if (typeof msg == "string") - if (enc) { - if (enc === "hex") - for ( - msg = msg.replace(/[^a-z0-9]+/gi, ""), msg.length % 2 !== 0 && (msg = "0" + msg), i = 0; - i < msg.length; - i += 2 - ) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else - for (var p = 0, i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - c < 128 - ? (res[p++] = c) - : c < 2048 - ? ((res[p++] = (c >> 6) | 192), (res[p++] = (c & 63) | 128)) - : isSurrogatePair(msg, i) - ? ((c = 65536 + ((c & 1023) << 10) + (msg.charCodeAt(++i) & 1023)), - (res[p++] = (c >> 18) | 240), - (res[p++] = ((c >> 12) & 63) | 128), - (res[p++] = ((c >> 6) & 63) | 128), - (res[p++] = (c & 63) | 128)) - : ((res[p++] = (c >> 12) | 224), (res[p++] = ((c >> 6) & 63) | 128), (res[p++] = (c & 63) | 128)); - } - else for (i = 0; i < msg.length; i++) res[i] = msg[i] | 0; - return res; - } - exports.toArray = toArray; - function toHex(msg) { - for (var res = "", i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); - return res; - } - exports.toHex = toHex; - function htonl(w) { - var res = (w >>> 24) | ((w >>> 8) & 65280) | ((w << 8) & 16711680) | ((w & 255) << 24); - return res >>> 0; - } - exports.htonl = htonl; - function toHex32(msg, endian) { - for (var res = "", i = 0; i < msg.length; i++) { - var w = msg[i]; - endian === "little" && (w = htonl(w)), (res += zero8(w.toString(16))); - } - return res; - } - exports.toHex32 = toHex32; - function zero2(word) { - return word.length === 1 ? "0" + word : word; - } - exports.zero2 = zero2; - function zero8(word) { - return word.length === 7 - ? "0" + word - : word.length === 6 - ? "00" + word - : word.length === 5 - ? "000" + word - : word.length === 4 - ? "0000" + word - : word.length === 3 - ? "00000" + word - : word.length === 2 - ? "000000" + word - : word.length === 1 - ? "0000000" + word - : word; - } - exports.zero8 = zero8; - function join32(msg, start, end, endian) { - var len = end - start; - assert(len % 4 === 0); - for (var res = new Array(len / 4), i = 0, k = start; i < res.length; i++, k += 4) { - var w; - endian === "big" - ? (w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]) - : (w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]), - (res[i] = w >>> 0); - } - return res; - } - exports.join32 = join32; - function split32(msg, endian) { - for (var res = new Array(msg.length * 4), i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - endian === "big" - ? ((res[k] = m >>> 24), - (res[k + 1] = (m >>> 16) & 255), - (res[k + 2] = (m >>> 8) & 255), - (res[k + 3] = m & 255)) - : ((res[k + 3] = m >>> 24), - (res[k + 2] = (m >>> 16) & 255), - (res[k + 1] = (m >>> 8) & 255), - (res[k] = m & 255)); - } - return res; - } - exports.split32 = split32; - function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); - } - exports.rotr32 = rotr32; - function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); - } - exports.rotl32 = rotl32; - function sum32(a, b) { - return (a + b) >>> 0; - } - exports.sum32 = sum32; - function sum32_3(a, b, c) { - return (a + b + c) >>> 0; - } - exports.sum32_3 = sum32_3; - function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; - } - exports.sum32_4 = sum32_4; - function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; - } - exports.sum32_5 = sum32_5; - function sum64(buf, pos, ah, al) { - var bh = buf[pos], - bl = buf[pos + 1], - lo = (al + bl) >>> 0, - hi = (lo < al ? 1 : 0) + ah + bh; - (buf[pos] = hi >>> 0), (buf[pos + 1] = lo); - } - exports.sum64 = sum64; - function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0, - hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; - } - exports.sum64_hi = sum64_hi; - function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; - } - exports.sum64_lo = sum64_lo; - function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0, - lo = al; - (lo = (lo + bl) >>> 0), - (carry += lo < al ? 1 : 0), - (lo = (lo + cl) >>> 0), - (carry += lo < cl ? 1 : 0), - (lo = (lo + dl) >>> 0), - (carry += lo < dl ? 1 : 0); - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; - } - exports.sum64_4_hi = sum64_4_hi; - function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; - } - exports.sum64_4_lo = sum64_4_lo; - function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0, - lo = al; - (lo = (lo + bl) >>> 0), - (carry += lo < al ? 1 : 0), - (lo = (lo + cl) >>> 0), - (carry += lo < cl ? 1 : 0), - (lo = (lo + dl) >>> 0), - (carry += lo < dl ? 1 : 0), - (lo = (lo + el) >>> 0), - (carry += lo < el ? 1 : 0); - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; - } - exports.sum64_5_hi = sum64_5_hi; - function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - return lo >>> 0; - } - exports.sum64_5_lo = sum64_5_lo; - function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; - } - exports.rotr64_hi = rotr64_hi; - function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - exports.rotr64_lo = rotr64_lo; - function shr64_hi(ah, al, num) { - return ah >>> num; - } - exports.shr64_hi = shr64_hi; - function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; - } - exports.shr64_lo = shr64_lo; - }, -}); - -// node_modules/hash.js/lib/hash/common.js -var require_common = __commonJS({ - "node_modules/hash.js/lib/hash/common.js"(exports) { - "use strict"; - var utils = require_utils4(), - assert = require_minimalistic_assert(); - function BlockHash() { - (this.pending = null), - (this.pendingTotal = 0), - (this.blockSize = this.constructor.blockSize), - (this.outSize = this.constructor.outSize), - (this.hmacStrength = this.constructor.hmacStrength), - (this.padLength = this.constructor.padLength / 8), - (this.endian = "big"), - (this._delta8 = this.blockSize / 8), - (this._delta32 = this.blockSize / 32); - } - exports.BlockHash = BlockHash; - BlockHash.prototype.update = function (msg, enc) { - if ( - ((msg = utils.toArray(msg, enc)), - this.pending ? (this.pending = this.pending.concat(msg)) : (this.pending = msg), - (this.pendingTotal += msg.length), - this.pending.length >= this._delta8) - ) { - msg = this.pending; - var r = msg.length % this._delta8; - (this.pending = msg.slice(msg.length - r, msg.length)), - this.pending.length === 0 && (this.pending = null), - (msg = utils.join32(msg, 0, msg.length - r, this.endian)); - for (var i = 0; i < msg.length; i += this._delta32) this._update(msg, i, i + this._delta32); - } - return this; - }; - BlockHash.prototype.digest = function (enc) { - return this.update(this._pad()), assert(this.pending === null), this._digest(enc); - }; - BlockHash.prototype._pad = function () { - var len = this.pendingTotal, - bytes = this._delta8, - k = bytes - ((len + this.padLength) % bytes), - res = new Array(k + this.padLength); - res[0] = 128; - for (var i = 1; i < k; i++) res[i] = 0; - if (((len <<= 3), this.endian === "big")) { - for (var t = 8; t < this.padLength; t++) res[i++] = 0; - (res[i++] = 0), - (res[i++] = 0), - (res[i++] = 0), - (res[i++] = 0), - (res[i++] = (len >>> 24) & 255), - (res[i++] = (len >>> 16) & 255), - (res[i++] = (len >>> 8) & 255), - (res[i++] = len & 255); - } else - for ( - res[i++] = len & 255, - res[i++] = (len >>> 8) & 255, - res[i++] = (len >>> 16) & 255, - res[i++] = (len >>> 24) & 255, - res[i++] = 0, - res[i++] = 0, - res[i++] = 0, - res[i++] = 0, - t = 8; - t < this.padLength; - t++ - ) - res[i++] = 0; - return res; - }; - }, -}); - -// node_modules/hash.js/lib/hash/sha/common.js -var require_common2 = __commonJS({ - "node_modules/hash.js/lib/hash/sha/common.js"(exports) { - "use strict"; - var utils = require_utils4(), - rotr32 = utils.rotr32; - function ft_1(s, x, y, z) { - if (s === 0) return ch32(x, y, z); - if (s === 1 || s === 3) return p32(x, y, z); - if (s === 2) return maj32(x, y, z); - } - exports.ft_1 = ft_1; - function ch32(x, y, z) { - return (x & y) ^ (~x & z); - } - exports.ch32 = ch32; - function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); - } - exports.maj32 = maj32; - function p32(x, y, z) { - return x ^ y ^ z; - } - exports.p32 = p32; - function s0_256(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); - } - exports.s0_256 = s0_256; - function s1_256(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); - } - exports.s1_256 = s1_256; - function g0_256(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); - } - exports.g0_256 = g0_256; - function g1_256(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); - } - exports.g1_256 = g1_256; - }, -}); - -// node_modules/hash.js/lib/hash/sha/1.js -var require__ = __commonJS({ - "node_modules/hash.js/lib/hash/sha/1.js"(exports, module) { - "use strict"; - var utils = require_utils4(), - common = require_common(), - shaCommon = require_common2(), - rotl32 = utils.rotl32, - sum32 = utils.sum32, - sum32_5 = utils.sum32_5, - ft_1 = shaCommon.ft_1, - BlockHash = common.BlockHash, - sha1_K = [1518500249, 1859775393, 2400959708, 3395469782]; - function SHA1() { - if (!(this instanceof SHA1)) return new SHA1(); - BlockHash.call(this), - (this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]), - (this.W = new Array(80)); - } - utils.inherits(SHA1, BlockHash); - module.exports = SHA1; - SHA1.blockSize = 512; - SHA1.outSize = 160; - SHA1.hmacStrength = 80; - SHA1.padLength = 64; - SHA1.prototype._update = function (msg, start) { - for (var W = this.W, i = 0; i < 16; i++) W[i] = msg[start + i]; - for (; i < W.length; i++) W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - var a = this.h[0], - b = this.h[1], - c = this.h[2], - d = this.h[3], - e = this.h[4]; - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20), - t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - (e = d), (d = c), (c = rotl32(b, 30)), (b = a), (a = t); - } - (this.h[0] = sum32(this.h[0], a)), - (this.h[1] = sum32(this.h[1], b)), - (this.h[2] = sum32(this.h[2], c)), - (this.h[3] = sum32(this.h[3], d)), - (this.h[4] = sum32(this.h[4], e)); - }; - SHA1.prototype._digest = function (enc) { - return enc === "hex" ? utils.toHex32(this.h, "big") : utils.split32(this.h, "big"); - }; - }, -}); - -// node_modules/hash.js/lib/hash/sha/256.js -var require__2 = __commonJS({ - "node_modules/hash.js/lib/hash/sha/256.js"(exports, module) { - "use strict"; - var utils = require_utils4(), - common = require_common(), - shaCommon = require_common2(), - assert = require_minimalistic_assert(), - sum32 = utils.sum32, - sum32_4 = utils.sum32_4, - sum32_5 = utils.sum32_5, - ch32 = shaCommon.ch32, - maj32 = shaCommon.maj32, - s0_256 = shaCommon.s0_256, - s1_256 = shaCommon.s1_256, - g0_256 = shaCommon.g0_256, - g1_256 = shaCommon.g1_256, - BlockHash = common.BlockHash, - sha256_K = [ - 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, - 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, - 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, - 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, - 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, - 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, - 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, - 3329325298, - ]; - function SHA256() { - if (!(this instanceof SHA256)) return new SHA256(); - BlockHash.call(this), - (this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]), - (this.k = sha256_K), - (this.W = new Array(64)); - } - utils.inherits(SHA256, BlockHash); - module.exports = SHA256; - SHA256.blockSize = 512; - SHA256.outSize = 256; - SHA256.hmacStrength = 192; - SHA256.padLength = 64; - SHA256.prototype._update = function (msg, start) { - for (var W = this.W, i = 0; i < 16; i++) W[i] = msg[start + i]; - for (; i < W.length; i++) W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - var a = this.h[0], - b = this.h[1], - c = this.h[2], - d = this.h[3], - e = this.h[4], - f = this.h[5], - g = this.h[6], - h = this.h[7]; - for (assert(this.k.length === W.length), i = 0; i < W.length; i++) { - var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]), - T2 = sum32(s0_256(a), maj32(a, b, c)); - (h = g), (g = f), (f = e), (e = sum32(d, T1)), (d = c), (c = b), (b = a), (a = sum32(T1, T2)); - } - (this.h[0] = sum32(this.h[0], a)), - (this.h[1] = sum32(this.h[1], b)), - (this.h[2] = sum32(this.h[2], c)), - (this.h[3] = sum32(this.h[3], d)), - (this.h[4] = sum32(this.h[4], e)), - (this.h[5] = sum32(this.h[5], f)), - (this.h[6] = sum32(this.h[6], g)), - (this.h[7] = sum32(this.h[7], h)); - }; - SHA256.prototype._digest = function (enc) { - return enc === "hex" ? utils.toHex32(this.h, "big") : utils.split32(this.h, "big"); - }; - }, -}); - -// node_modules/hash.js/lib/hash/sha/224.js -var require__3 = __commonJS({ - "node_modules/hash.js/lib/hash/sha/224.js"(exports, module) { - "use strict"; - var utils = require_utils4(), - SHA256 = require__2(); - function SHA224() { - if (!(this instanceof SHA224)) return new SHA224(); - SHA256.call(this), - (this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]); - } - utils.inherits(SHA224, SHA256); - module.exports = SHA224; - SHA224.blockSize = 512; - SHA224.outSize = 224; - SHA224.hmacStrength = 192; - SHA224.padLength = 64; - SHA224.prototype._digest = function (enc) { - return enc === "hex" ? utils.toHex32(this.h.slice(0, 7), "big") : utils.split32(this.h.slice(0, 7), "big"); - }; - }, -}); - -// node_modules/hash.js/lib/hash/sha/512.js -var require__4 = __commonJS({ - "node_modules/hash.js/lib/hash/sha/512.js"(exports, module) { - "use strict"; - var utils = require_utils4(), - common = require_common(), - assert = require_minimalistic_assert(), - rotr64_hi = utils.rotr64_hi, - rotr64_lo = utils.rotr64_lo, - shr64_hi = utils.shr64_hi, - shr64_lo = utils.shr64_lo, - sum64 = utils.sum64, - sum64_hi = utils.sum64_hi, - sum64_lo = utils.sum64_lo, - sum64_4_hi = utils.sum64_4_hi, - sum64_4_lo = utils.sum64_4_lo, - sum64_5_hi = utils.sum64_5_hi, - sum64_5_lo = utils.sum64_5_lo, - BlockHash = common.BlockHash, - sha512_K = [ - 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, - 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, - 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, - 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, - 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, - 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, - 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, - 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, - 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, - 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, - 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, - 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, - 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, - 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, - 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, - 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, - 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, - 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591, - ]; - function SHA512() { - if (!(this instanceof SHA512)) return new SHA512(); - BlockHash.call(this), - (this.h = [ - 1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, - 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209, - ]), - (this.k = sha512_K), - (this.W = new Array(160)); - } - utils.inherits(SHA512, BlockHash); - module.exports = SHA512; - SHA512.blockSize = 1024; - SHA512.outSize = 512; - SHA512.hmacStrength = 192; - SHA512.padLength = 128; - SHA512.prototype._prepareBlock = function (msg, start) { - for (var W = this.W, i = 0; i < 32; i++) W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]), - c0_lo = g1_512_lo(W[i - 4], W[i - 3]), - c1_hi = W[i - 14], - c1_lo = W[i - 13], - c2_hi = g0_512_hi(W[i - 30], W[i - 29]), - c2_lo = g0_512_lo(W[i - 30], W[i - 29]), - c3_hi = W[i - 32], - c3_lo = W[i - 31]; - (W[i] = sum64_4_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo)), - (W[i + 1] = sum64_4_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo)); - } - }; - SHA512.prototype._update = function (msg, start) { - this._prepareBlock(msg, start); - var W = this.W, - ah = this.h[0], - al = this.h[1], - bh = this.h[2], - bl = this.h[3], - ch = this.h[4], - cl = this.h[5], - dh = this.h[6], - dl = this.h[7], - eh = this.h[8], - el = this.h[9], - fh = this.h[10], - fl = this.h[11], - gh = this.h[12], - gl = this.h[13], - hh = this.h[14], - hl = this.h[15]; - assert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh, - c0_lo = hl, - c1_hi = s1_512_hi(eh, el), - c1_lo = s1_512_lo(eh, el), - c2_hi = ch64_hi(eh, el, fh, fl, gh, gl), - c2_lo = ch64_lo(eh, el, fh, fl, gh, gl), - c3_hi = this.k[i], - c3_lo = this.k[i + 1], - c4_hi = W[i], - c4_lo = W[i + 1], - T1_hi = sum64_5_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo), - T1_lo = sum64_5_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); - (c0_hi = s0_512_hi(ah, al)), - (c0_lo = s0_512_lo(ah, al)), - (c1_hi = maj64_hi(ah, al, bh, bl, ch, cl)), - (c1_lo = maj64_lo(ah, al, bh, bl, ch, cl)); - var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo), - T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); - (hh = gh), - (hl = gl), - (gh = fh), - (gl = fl), - (fh = eh), - (fl = el), - (eh = sum64_hi(dh, dl, T1_hi, T1_lo)), - (el = sum64_lo(dl, dl, T1_hi, T1_lo)), - (dh = ch), - (dl = cl), - (ch = bh), - (cl = bl), - (bh = ah), - (bl = al), - (ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo)), - (al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo)); - } - sum64(this.h, 0, ah, al), - sum64(this.h, 2, bh, bl), - sum64(this.h, 4, ch, cl), - sum64(this.h, 6, dh, dl), - sum64(this.h, 8, eh, el), - sum64(this.h, 10, fh, fl), - sum64(this.h, 12, gh, gl), - sum64(this.h, 14, hh, hl); - }; - SHA512.prototype._digest = function (enc) { - return enc === "hex" ? utils.toHex32(this.h, "big") : utils.split32(this.h, "big"); - }; - function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (~xh & zh); - return r < 0 && (r += 4294967296), r; - } - function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (~xl & zl); - return r < 0 && (r += 4294967296), r; - } - function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - return r < 0 && (r += 4294967296), r; - } - function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - return r < 0 && (r += 4294967296), r; - } - function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 28), - c1_hi = rotr64_hi(xl, xh, 2), - c2_hi = rotr64_hi(xl, xh, 7), - r = c0_hi ^ c1_hi ^ c2_hi; - return r < 0 && (r += 4294967296), r; - } - function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 28), - c1_lo = rotr64_lo(xl, xh, 2), - c2_lo = rotr64_lo(xl, xh, 7), - r = c0_lo ^ c1_lo ^ c2_lo; - return r < 0 && (r += 4294967296), r; - } - function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 14), - c1_hi = rotr64_hi(xh, xl, 18), - c2_hi = rotr64_hi(xl, xh, 9), - r = c0_hi ^ c1_hi ^ c2_hi; - return r < 0 && (r += 4294967296), r; - } - function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 14), - c1_lo = rotr64_lo(xh, xl, 18), - c2_lo = rotr64_lo(xl, xh, 9), - r = c0_lo ^ c1_lo ^ c2_lo; - return r < 0 && (r += 4294967296), r; - } - function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 1), - c1_hi = rotr64_hi(xh, xl, 8), - c2_hi = shr64_hi(xh, xl, 7), - r = c0_hi ^ c1_hi ^ c2_hi; - return r < 0 && (r += 4294967296), r; - } - function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 1), - c1_lo = rotr64_lo(xh, xl, 8), - c2_lo = shr64_lo(xh, xl, 7), - r = c0_lo ^ c1_lo ^ c2_lo; - return r < 0 && (r += 4294967296), r; - } - function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 19), - c1_hi = rotr64_hi(xl, xh, 29), - c2_hi = shr64_hi(xh, xl, 6), - r = c0_hi ^ c1_hi ^ c2_hi; - return r < 0 && (r += 4294967296), r; - } - function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 19), - c1_lo = rotr64_lo(xl, xh, 29), - c2_lo = shr64_lo(xh, xl, 6), - r = c0_lo ^ c1_lo ^ c2_lo; - return r < 0 && (r += 4294967296), r; - } - }, -}); - -// node_modules/hash.js/lib/hash/sha/384.js -var require__5 = __commonJS({ - "node_modules/hash.js/lib/hash/sha/384.js"(exports, module) { - "use strict"; - var utils = require_utils4(), - SHA512 = require__4(); - function SHA384() { - if (!(this instanceof SHA384)) return new SHA384(); - SHA512.call(this), - (this.h = [ - 3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, - 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428, - ]); - } - utils.inherits(SHA384, SHA512); - module.exports = SHA384; - SHA384.blockSize = 1024; - SHA384.outSize = 384; - SHA384.hmacStrength = 192; - SHA384.padLength = 128; - SHA384.prototype._digest = function (enc) { - return enc === "hex" ? utils.toHex32(this.h.slice(0, 12), "big") : utils.split32(this.h.slice(0, 12), "big"); - }; - }, -}); - -// node_modules/hash.js/lib/hash/sha.js -var require_sha3 = __commonJS({ - "node_modules/hash.js/lib/hash/sha.js"(exports) { - "use strict"; - exports.sha1 = require__(); - exports.sha224 = require__3(); - exports.sha256 = require__2(); - exports.sha384 = require__5(); - exports.sha512 = require__4(); - }, -}); - -// node_modules/hash.js/lib/hash/ripemd.js -var require_ripemd = __commonJS({ - "node_modules/hash.js/lib/hash/ripemd.js"(exports) { - "use strict"; - var utils = require_utils4(), - common = require_common(), - rotl32 = utils.rotl32, - sum32 = utils.sum32, - sum32_3 = utils.sum32_3, - sum32_4 = utils.sum32_4, - BlockHash = common.BlockHash; - function RIPEMD160() { - if (!(this instanceof RIPEMD160)) return new RIPEMD160(); - BlockHash.call(this), - (this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]), - (this.endian = "little"); - } - utils.inherits(RIPEMD160, BlockHash); - exports.ripemd160 = RIPEMD160; - RIPEMD160.blockSize = 512; - RIPEMD160.outSize = 160; - RIPEMD160.hmacStrength = 192; - RIPEMD160.padLength = 64; - RIPEMD160.prototype._update = function (msg, start) { - for ( - var A = this.h[0], - B = this.h[1], - C = this.h[2], - D = this.h[3], - E = this.h[4], - Ah = A, - Bh = B, - Ch = C, - Dh = D, - Eh = E, - j = 0; - j < 80; - j++ - ) { - var T = sum32(rotl32(sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), s[j]), E); - (A = E), - (E = D), - (D = rotl32(C, 10)), - (C = B), - (B = T), - (T = sum32(rotl32(sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh)), - (Ah = Eh), - (Eh = Dh), - (Dh = rotl32(Ch, 10)), - (Ch = Bh), - (Bh = T); - } - (T = sum32_3(this.h[1], C, Dh)), - (this.h[1] = sum32_3(this.h[2], D, Eh)), - (this.h[2] = sum32_3(this.h[3], E, Ah)), - (this.h[3] = sum32_3(this.h[4], A, Bh)), - (this.h[4] = sum32_3(this.h[0], B, Ch)), - (this.h[0] = T); - }; - RIPEMD160.prototype._digest = function (enc) { - return enc === "hex" ? utils.toHex32(this.h, "little") : utils.split32(this.h, "little"); - }; - function f(j, x, y, z) { - return j <= 15 - ? x ^ y ^ z - : j <= 31 - ? (x & y) | (~x & z) - : j <= 47 - ? (x | ~y) ^ z - : j <= 63 - ? (x & z) | (y & ~z) - : x ^ (y | ~z); - } - function K(j) { - return j <= 15 ? 0 : j <= 31 ? 1518500249 : j <= 47 ? 1859775393 : j <= 63 ? 2400959708 : 2840853838; - } - function Kh(j) { - return j <= 15 ? 1352829926 : j <= 31 ? 1548603684 : j <= 47 ? 1836072691 : j <= 63 ? 2053994217 : 0; - } - var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, - 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, - 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, - ], - rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, - 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, - 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11, - ], - s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, - ], - sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11, - ]; - }, -}); - -// node_modules/hash.js/lib/hash/hmac.js -var require_hmac = __commonJS({ - "node_modules/hash.js/lib/hash/hmac.js"(exports, module) { - "use strict"; - var utils = require_utils4(), - assert = require_minimalistic_assert(); - function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) return new Hmac(hash, key, enc); - (this.Hash = hash), - (this.blockSize = hash.blockSize / 8), - (this.outSize = hash.outSize / 8), - (this.inner = null), - (this.outer = null), - this._init(utils.toArray(key, enc)); - } - module.exports = Hmac; - Hmac.prototype._init = function (key) { - key.length > this.blockSize && (key = new this.Hash().update(key).digest()), assert(key.length <= this.blockSize); - for (var i = key.length; i < this.blockSize; i++) key.push(0); - for (i = 0; i < key.length; i++) key[i] ^= 54; - for (this.inner = new this.Hash().update(key), i = 0; i < key.length; i++) key[i] ^= 106; - this.outer = new this.Hash().update(key); - }; - Hmac.prototype.update = function (msg, enc) { - return this.inner.update(msg, enc), this; - }; - Hmac.prototype.digest = function (enc) { - return this.outer.update(this.inner.digest()), this.outer.digest(enc); - }; - }, -}); - -// node_modules/hash.js/lib/hash.js -var require_hash2 = __commonJS({ - "node_modules/hash.js/lib/hash.js"(exports) { - var hash = exports; - hash.utils = require_utils4(); - hash.common = require_common(); - hash.sha = require_sha3(); - hash.ripemd = require_ripemd(); - hash.hmac = require_hmac(); - hash.sha1 = hash.sha.sha1; - hash.sha256 = hash.sha.sha256; - hash.sha224 = hash.sha.sha224; - hash.sha384 = hash.sha.sha384; - hash.sha512 = hash.sha.sha512; - hash.ripemd160 = hash.ripemd.ripemd160; - }, -}); - -// node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js -var require_secp256k1 = __commonJS({ - "node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js"(exports, module) { - module.exports = { - doubles: { - step: 4, - points: [ - [ - "e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a", - "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821", - ], - [ - "8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508", - "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf", - ], - [ - "175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739", - "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695", - ], - [ - "363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640", - "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9", - ], - [ - "8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c", - "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36", - ], - [ - "723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda", - "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f", - ], - [ - "eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa", - "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999", - ], - [ - "100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0", - "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09", - ], - [ - "e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d", - "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d", - ], - [ - "feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d", - "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088", - ], - [ - "da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1", - "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d", - ], - [ - "53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0", - "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8", - ], - [ - "8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047", - "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a", - ], - [ - "385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862", - "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453", - ], - [ - "6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7", - "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160", - ], - [ - "3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd", - "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0", - ], - [ - "85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83", - "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6", - ], - [ - "948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a", - "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589", - ], - [ - "6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8", - "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17", - ], - [ - "e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d", - "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda", - ], - [ - "e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725", - "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd", - ], - [ - "213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754", - "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2", - ], - [ - "4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c", - "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6", - ], - [ - "fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6", - "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f", - ], - [ - "76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39", - "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01", - ], - [ - "c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891", - "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3", - ], - [ - "d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b", - "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f", - ], - [ - "b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03", - "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7", - ], - [ - "e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d", - "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78", - ], - [ - "a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070", - "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1", - ], - [ - "90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4", - "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150", - ], - [ - "8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da", - "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82", - ], - [ - "e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11", - "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc", - ], - [ - "8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e", - "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b", - ], - [ - "e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41", - "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51", - ], - [ - "b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef", - "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45", - ], - [ - "d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8", - "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120", - ], - [ - "324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d", - "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84", - ], - [ - "4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96", - "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d", - ], - [ - "9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd", - "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d", - ], - [ - "6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5", - "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8", - ], - [ - "a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266", - "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8", - ], - [ - "7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71", - "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac", - ], - [ - "928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac", - "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f", - ], - [ - "85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751", - "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962", - ], - [ - "ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e", - "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907", - ], - [ - "827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241", - "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec", - ], - [ - "eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3", - "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d", - ], - [ - "e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f", - "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414", - ], - [ - "1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19", - "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd", - ], - [ - "146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be", - "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0", - ], - [ - "fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9", - "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811", - ], - [ - "da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2", - "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1", - ], - [ - "a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13", - "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c", - ], - [ - "174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c", - "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73", - ], - [ - "959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba", - "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd", - ], - [ - "d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151", - "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405", - ], - [ - "64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073", - "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589", - ], - [ - "8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458", - "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e", - ], - [ - "13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b", - "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27", - ], - [ - "bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366", - "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1", - ], - [ - "8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa", - "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482", - ], - [ - "8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0", - "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945", - ], - [ - "dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787", - "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573", - ], - [ - "f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e", - "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82", - ], - ], - }, - naf: { - wnd: 7, - points: [ - [ - "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", - "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672", - ], - [ - "2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4", - "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6", - ], - [ - "5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", - "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da", - ], - [ - "acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe", - "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37", - ], - [ - "774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb", - "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b", - ], - [ - "f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8", - "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81", - ], - [ - "d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e", - "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58", - ], - [ - "defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34", - "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77", - ], - [ - "2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c", - "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a", - ], - [ - "352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5", - "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c", - ], - [ - "2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f", - "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67", - ], - [ - "9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714", - "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402", - ], - [ - "daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729", - "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55", - ], - [ - "c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db", - "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482", - ], - [ - "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", - "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82", - ], - [ - "1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5", - "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396", - ], - [ - "605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479", - "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49", - ], - [ - "62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d", - "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf", - ], - [ - "80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f", - "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a", - ], - [ - "7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb", - "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7", - ], - [ - "d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9", - "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933", - ], - [ - "49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963", - "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a", - ], - [ - "77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74", - "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6", - ], - [ - "f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530", - "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37", - ], - [ - "463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b", - "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e", - ], - [ - "f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247", - "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6", - ], - [ - "caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1", - "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476", - ], - [ - "2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120", - "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40", - ], - [ - "7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435", - "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61", - ], - [ - "754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18", - "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683", - ], - [ - "e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8", - "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5", - ], - [ - "186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb", - "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b", - ], - [ - "df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f", - "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417", - ], - [ - "5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143", - "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868", - ], - [ - "290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba", - "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a", - ], - [ - "af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45", - "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6", - ], - [ - "766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a", - "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996", - ], - [ - "59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e", - "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e", - ], - [ - "f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8", - "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d", - ], - [ - "7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c", - "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2", - ], - [ - "948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519", - "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e", - ], - [ - "7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab", - "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437", - ], - [ - "3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca", - "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311", - ], - [ - "d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf", - "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4", - ], - [ - "1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610", - "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575", - ], - [ - "733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4", - "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d", - ], - [ - "15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c", - "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d", - ], - [ - "a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940", - "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629", - ], - [ - "e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980", - "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06", - ], - [ - "311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3", - "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374", - ], - [ - "34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf", - "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee", - ], - [ - "f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63", - "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1", - ], - [ - "d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448", - "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b", - ], - [ - "32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf", - "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661", - ], - [ - "7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5", - "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6", - ], - [ - "ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6", - "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e", - ], - [ - "16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5", - "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d", - ], - [ - "eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99", - "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc", - ], - [ - "78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51", - "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4", - ], - [ - "494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5", - "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c", - ], - [ - "a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5", - "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b", - ], - [ - "c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997", - "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913", - ], - [ - "841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881", - "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154", - ], - [ - "5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5", - "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865", - ], - [ - "36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66", - "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc", - ], - [ - "336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726", - "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224", - ], - [ - "8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede", - "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e", - ], - [ - "1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94", - "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6", - ], - [ - "85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31", - "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511", - ], - [ - "29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51", - "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b", - ], - [ - "a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252", - "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2", - ], - [ - "4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5", - "cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c", - ], - [ - "d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b", - "6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3", - ], - [ - "ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4", - "322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d", - ], - [ - "af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f", - "6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700", - ], - [ - "e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889", - "2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4", - ], - [ - "591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246", - "b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196", - ], - [ - "11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984", - "998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4", - ], - [ - "3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a", - "b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257", - ], - [ - "cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030", - "bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13", - ], - [ - "c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197", - "6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096", - ], - [ - "c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593", - "c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38", - ], - [ - "a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef", - "21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f", - ], - [ - "347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38", - "60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448", - ], - [ - "da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a", - "49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a", - ], - [ - "c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111", - "5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4", - ], - [ - "4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502", - "7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437", - ], - [ - "3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea", - "be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7", - ], - [ - "cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26", - "8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d", - ], - [ - "b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986", - "39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a", - ], - [ - "d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e", - "62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54", - ], - [ - "48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4", - "25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77", - ], - [ - "dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda", - "ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517", - ], - [ - "6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859", - "cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10", - ], - [ - "e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f", - "f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125", - ], - [ - "eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c", - "6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e", - ], - [ - "13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942", - "fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1", - ], - [ - "ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a", - "1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2", - ], - [ - "b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80", - "5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423", - ], - [ - "ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d", - "438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8", - ], - [ - "8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1", - "cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758", - ], - [ - "52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63", - "c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375", - ], - [ - "e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352", - "6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d", - ], - [ - "7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193", - "ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec", - ], - [ - "5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00", - "9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0", - ], - [ - "32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58", - "ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c", - ], - [ - "e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7", - "d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4", - ], - [ - "8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8", - "c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f", - ], - [ - "4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e", - "67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649", - ], - [ - "3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d", - "cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826", - ], - [ - "674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b", - "299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5", - ], - [ - "d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f", - "f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87", - ], - [ - "30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6", - "462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b", - ], - [ - "be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297", - "62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc", - ], - [ - "93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a", - "7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c", - ], - [ - "b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c", - "ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f", - ], - [ - "d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52", - "4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a", - ], - [ - "d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb", - "bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46", - ], - [ - "463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065", - "bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f", - ], - [ - "7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917", - "603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03", - ], - [ - "74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9", - "cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08", - ], - [ - "30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3", - "553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8", - ], - [ - "9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57", - "712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373", - ], - [ - "176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66", - "ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3", - ], - [ - "75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8", - "9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8", - ], - [ - "809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721", - "9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1", - ], - [ - "1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180", - "4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9", - ], - ], - }, - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/curves.js -var require_curves = __commonJS({ - "node_modules/elliptic/lib/elliptic/curves.js"(exports) { - "use strict"; - var curves = exports, - hash = require_hash2(), - curve = require_curve(), - utils = require_utils3(), - assert = utils.assert; - function PresetCurve(options) { - options.type === "short" - ? (this.curve = new curve.short(options)) - : options.type === "edwards" - ? (this.curve = new curve.edwards(options)) - : (this.curve = new curve.mont(options)), - (this.g = this.curve.g), - (this.n = this.curve.n), - (this.hash = options.hash), - assert(this.g.validate(), "Invalid curve"), - assert(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); - } - curves.PresetCurve = PresetCurve; - function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: !0, - enumerable: !0, - get: function () { - var curve2 = new PresetCurve(options); - return ( - Object.defineProperty(curves, name, { - configurable: !0, - enumerable: !0, - value: curve2, - }), - curve2 - ); - }, - }); - } - defineCurve("p192", { - type: "short", - prime: "p192", - p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", - a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", - b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", - n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", - hash: hash.sha256, - gRed: !1, - g: [ - "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", - "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811", - ], - }); - defineCurve("p224", { - type: "short", - prime: "p224", - p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", - a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", - b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", - n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", - hash: hash.sha256, - gRed: !1, - g: [ - "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", - "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34", - ], - }); - defineCurve("p256", { - type: "short", - prime: null, - p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", - a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", - b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", - n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", - hash: hash.sha256, - gRed: !1, - g: [ - "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", - "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5", - ], - }); - defineCurve("p384", { - type: "short", - prime: null, - p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", - a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", - b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", - n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", - hash: hash.sha384, - gRed: !1, - g: [ - "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", - "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f", - ], - }); - defineCurve("p521", { - type: "short", - prime: null, - p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", - a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", - b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", - n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", - hash: hash.sha512, - gRed: !1, - g: [ - "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", - "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650", - ], - }); - defineCurve("curve25519", { - type: "mont", - prime: "p25519", - p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", - a: "76d06", - b: "1", - n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", - hash: hash.sha256, - gRed: !1, - g: ["9"], - }); - defineCurve("ed25519", { - type: "edwards", - prime: "p25519", - p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", - a: "-1", - c: "1", - d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", - n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", - hash: hash.sha256, - gRed: !1, - g: [ - "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", - "6666666666666666666666666666666666666666666666666666666666666658", - ], - }); - var pre; - try { - pre = require_secp256k1(); - } catch { - pre = void 0; - } - defineCurve("secp256k1", { - type: "short", - prime: "k256", - p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", - a: "0", - b: "7", - n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", - h: "1", - hash: hash.sha256, - beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", - lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", - basis: [ - { - a: "3086d221a7d46bcde86c90e49284eb15", - b: "-e4437ed6010e88286f547fa90abfe4c3", - }, - { - a: "114ca50f7a8e2f3f657c1108d9d44cfd8", - b: "3086d221a7d46bcde86c90e49284eb15", - }, - ], - gRed: !1, - g: [ - "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", - "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", - pre, - ], - }); - }, -}); - -// node_modules/hmac-drbg/lib/hmac-drbg.js -var require_hmac_drbg = __commonJS({ - "node_modules/hmac-drbg/lib/hmac-drbg.js"(exports, module) { - "use strict"; - var hash = require_hash2(), - utils = require_utils2(), - assert = require_minimalistic_assert(); - function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); - (this.hash = options.hash), - (this.predResist = !!options.predResist), - (this.outLen = this.hash.outSize), - (this.minEntropy = options.minEntropy || this.hash.hmacStrength), - (this._reseed = null), - (this.reseedInterval = null), - (this.K = null), - (this.V = null); - var entropy = utils.toArray(options.entropy, options.entropyEnc || "hex"), - nonce = utils.toArray(options.nonce, options.nonceEnc || "hex"), - pers = utils.toArray(options.pers, options.persEnc || "hex"); - assert(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), - this._init(entropy, nonce, pers); - } - module.exports = HmacDRBG; - HmacDRBG.prototype._init = function (entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - (this.K = new Array(this.outLen / 8)), (this.V = new Array(this.outLen / 8)); - for (var i = 0; i < this.V.length; i++) (this.K[i] = 0), (this.V[i] = 1); - this._update(seed), (this._reseed = 1), (this.reseedInterval = 281474976710656); - }; - HmacDRBG.prototype._hmac = function () { - return new hash.hmac(this.hash, this.K); - }; - HmacDRBG.prototype._update = function (seed) { - var kmac = this._hmac().update(this.V).update([0]); - seed && (kmac = kmac.update(seed)), - (this.K = kmac.digest()), - (this.V = this._hmac().update(this.V).digest()), - seed && - ((this.K = this._hmac().update(this.V).update([1]).update(seed).digest()), - (this.V = this._hmac().update(this.V).digest())); - }; - HmacDRBG.prototype.reseed = function (entropy, entropyEnc, add, addEnc) { - typeof entropyEnc != "string" && ((addEnc = add), (add = entropyEnc), (entropyEnc = null)), - (entropy = utils.toArray(entropy, entropyEnc)), - (add = utils.toArray(add, addEnc)), - assert(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), - this._update(entropy.concat(add || [])), - (this._reseed = 1); - }; - HmacDRBG.prototype.generate = function (len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) throw new Error("Reseed is required"); - typeof enc != "string" && ((addEnc = add), (add = enc), (enc = null)), - add && ((add = utils.toArray(add, addEnc || "hex")), this._update(add)); - for (var temp = []; temp.length < len; ) - (this.V = this._hmac().update(this.V).digest()), (temp = temp.concat(this.V)); - var res = temp.slice(0, len); - return this._update(add), this._reseed++, utils.encode(res, enc); - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/ec/key.js -var require_key = __commonJS({ - "node_modules/elliptic/lib/elliptic/ec/key.js"(exports, module) { - "use strict"; - var BN = require_bn4(), - utils = require_utils3(), - assert = utils.assert; - function KeyPair(ec, options) { - (this.ec = ec), - (this.priv = null), - (this.pub = null), - options.priv && this._importPrivate(options.priv, options.privEnc), - options.pub && this._importPublic(options.pub, options.pubEnc); - } - module.exports = KeyPair; - KeyPair.fromPublic = function (ec, pub, enc) { - return pub instanceof KeyPair - ? pub - : new KeyPair(ec, { - pub, - pubEnc: enc, - }); - }; - KeyPair.fromPrivate = function (ec, priv, enc) { - return priv instanceof KeyPair - ? priv - : new KeyPair(ec, { - priv, - privEnc: enc, - }); - }; - KeyPair.prototype.validate = function () { - var pub = this.getPublic(); - return pub.isInfinity() - ? { result: !1, reason: "Invalid public key" } - : pub.validate() - ? pub.mul(this.ec.curve.n).isInfinity() - ? { result: !0, reason: null } - : { result: !1, reason: "Public key * N != O" } - : { result: !1, reason: "Public key is not a point" }; - }; - KeyPair.prototype.getPublic = function (compact, enc) { - return ( - typeof compact == "string" && ((enc = compact), (compact = null)), - this.pub || (this.pub = this.ec.g.mul(this.priv)), - enc ? this.pub.encode(enc, compact) : this.pub - ); - }; - KeyPair.prototype.getPrivate = function (enc) { - return enc === "hex" ? this.priv.toString(16, 2) : this.priv; - }; - KeyPair.prototype._importPrivate = function (key, enc) { - (this.priv = new BN(key, enc || 16)), (this.priv = this.priv.umod(this.ec.curve.n)); - }; - KeyPair.prototype._importPublic = function (key, enc) { - if (key.x || key.y) { - this.ec.curve.type === "mont" - ? assert(key.x, "Need x coordinate") - : (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") && - assert(key.x && key.y, "Need both x and y coordinate"), - (this.pub = this.ec.curve.point(key.x, key.y)); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); - }; - KeyPair.prototype.derive = function (pub) { - return pub.validate() || assert(pub.validate(), "public point not validated"), pub.mul(this.priv).getX(); - }; - KeyPair.prototype.sign = function (msg, enc, options) { - return this.ec.sign(msg, this, enc, options); - }; - KeyPair.prototype.verify = function (msg, signature) { - return this.ec.verify(msg, signature, this); - }; - KeyPair.prototype.inspect = function () { - return ( - "" - ); - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/ec/signature.js -var require_signature = __commonJS({ - "node_modules/elliptic/lib/elliptic/ec/signature.js"(exports, module) { - "use strict"; - var BN = require_bn4(), - utils = require_utils3(), - assert = utils.assert; - function Signature(options, enc) { - if (options instanceof Signature) return options; - this._importDER(options, enc) || - (assert(options.r && options.s, "Signature without r or s"), - (this.r = new BN(options.r, 16)), - (this.s = new BN(options.s, 16)), - options.recoveryParam === void 0 ? (this.recoveryParam = null) : (this.recoveryParam = options.recoveryParam)); - } - module.exports = Signature; - function Position() { - this.place = 0; - } - function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 128)) return initial; - var octetLen = initial & 15; - if (octetLen === 0 || octetLen > 4) return !1; - for (var val = 0, i = 0, off = p.place; i < octetLen; i++, off++) (val <<= 8), (val |= buf[off]), (val >>>= 0); - return val <= 127 ? !1 : ((p.place = off), val); - } - function rmPadding(buf) { - for (var i = 0, len = buf.length - 1; !buf[i] && !(buf[i + 1] & 128) && i < len; ) i++; - return i === 0 ? buf : buf.slice(i); - } - Signature.prototype._importDER = function (data, enc) { - data = utils.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 48) return !1; - var len = getLength(data, p); - if (len === !1 || len + p.place !== data.length || data[p.place++] !== 2) return !1; - var rlen = getLength(data, p); - if (rlen === !1) return !1; - var r = data.slice(p.place, rlen + p.place); - if (((p.place += rlen), data[p.place++] !== 2)) return !1; - var slen = getLength(data, p); - if (slen === !1 || data.length !== slen + p.place) return !1; - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0) - if (r[1] & 128) r = r.slice(1); - else return !1; - if (s[0] === 0) - if (s[1] & 128) s = s.slice(1); - else return !1; - return (this.r = new BN(r)), (this.s = new BN(s)), (this.recoveryParam = null), !0; - }; - function constructLength(arr, len) { - if (len < 128) { - arr.push(len); - return; - } - var octets = 1 + ((Math.log(len) / Math.LN2) >>> 3); - for (arr.push(octets | 128); --octets; ) arr.push((len >>> (octets << 3)) & 255); - arr.push(len); - } - Signature.prototype.toDER = function (enc) { - var r = this.r.toArray(), - s = this.s.toArray(); - for ( - r[0] & 128 && (r = [0].concat(r)), s[0] & 128 && (s = [0].concat(s)), r = rmPadding(r), s = rmPadding(s); - !s[0] && !(s[1] & 128); - - ) - s = s.slice(1); - var arr = [2]; - constructLength(arr, r.length), (arr = arr.concat(r)), arr.push(2), constructLength(arr, s.length); - var backHalf = arr.concat(s), - res = [48]; - return constructLength(res, backHalf.length), (res = res.concat(backHalf)), utils.encode(res, enc); - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/ec/index.js -var require_ec = __commonJS({ - "node_modules/elliptic/lib/elliptic/ec/index.js"(exports, module) { - "use strict"; - var BN = require_bn4(), - HmacDRBG = require_hmac_drbg(), - utils = require_utils3(), - curves = require_curves(), - rand = require_brorand(), - assert = utils.assert, - KeyPair = require_key(), - Signature = require_signature(); - function EC(options) { - if (!(this instanceof EC)) return new EC(options); - typeof options == "string" && - (assert(Object.prototype.hasOwnProperty.call(curves, options), "Unknown curve " + options), - (options = curves[options])), - options instanceof curves.PresetCurve && (options = { curve: options }), - (this.curve = options.curve.curve), - (this.n = this.curve.n), - (this.nh = this.n.ushrn(1)), - (this.g = this.curve.g), - (this.g = options.curve.g), - this.g.precompute(options.curve.n.bitLength() + 1), - (this.hash = options.hash || options.curve.hash); - } - module.exports = EC; - EC.prototype.keyPair = function (options) { - return new KeyPair(this, options); - }; - EC.prototype.keyFromPrivate = function (priv, enc) { - return KeyPair.fromPrivate(this, priv, enc); - }; - EC.prototype.keyFromPublic = function (pub, enc) { - return KeyPair.fromPublic(this, pub, enc); - }; - EC.prototype.genKeyPair = function (options) { - options || (options = {}); - for ( - var drbg = new HmacDRBG({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || "utf8", - entropy: options.entropy || rand(this.hash.hmacStrength), - entropyEnc: (options.entropy && options.entropyEnc) || "utf8", - nonce: this.n.toArray(), - }), - bytes = this.n.byteLength(), - ns2 = this.n.sub(new BN(2)); - ; - - ) { - var priv = new BN(drbg.generate(bytes)); - if (!(priv.cmp(ns2) > 0)) return priv.iaddn(1), this.keyFromPrivate(priv); - } - }; - EC.prototype._truncateToN = function (msg, truncOnly) { - var delta = msg.byteLength() * 8 - this.n.bitLength(); - return delta > 0 && (msg = msg.ushrn(delta)), !truncOnly && msg.cmp(this.n) >= 0 ? msg.sub(this.n) : msg; - }; - EC.prototype.sign = function (msg, key, enc, options) { - typeof enc == "object" && ((options = enc), (enc = null)), - options || (options = {}), - (key = this.keyFromPrivate(key, enc)), - (msg = this._truncateToN(new BN(msg, 16))); - for ( - var bytes = this.n.byteLength(), - bkey = key.getPrivate().toArray("be", bytes), - nonce = msg.toArray("be", bytes), - drbg = new HmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce, - pers: options.pers, - persEnc: options.persEnc || "utf8", - }), - ns1 = this.n.sub(new BN(1)), - iter = 0; - ; - iter++ - ) { - var k = options.k ? options.k(iter) : new BN(drbg.generate(this.n.byteLength())); - if (((k = this._truncateToN(k, !0)), !(k.cmpn(1) <= 0 || k.cmp(ns1) >= 0))) { - var kp = this.g.mul(k); - if (!kp.isInfinity()) { - var kpX = kp.getX(), - r = kpX.umod(this.n); - if (r.cmpn(0) !== 0) { - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - if (((s = s.umod(this.n)), s.cmpn(0) !== 0)) { - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); - return ( - options.canonical && s.cmp(this.nh) > 0 && ((s = this.n.sub(s)), (recoveryParam ^= 1)), - new Signature({ r, s, recoveryParam }) - ); - } - } - } - } - } - }; - EC.prototype.verify = function (msg, signature, key, enc) { - (msg = this._truncateToN(new BN(msg, 16))), - (key = this.keyFromPublic(key, enc)), - (signature = new Signature(signature, "hex")); - var r = signature.r, - s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0 || s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return !1; - var sinv = s.invm(this.n), - u1 = sinv.mul(msg).umod(this.n), - u2 = sinv.mul(r).umod(this.n), - p; - return this.curve._maxwellTrick - ? ((p = this.g.jmulAdd(u1, key.getPublic(), u2)), p.isInfinity() ? !1 : p.eqXToP(r)) - : ((p = this.g.mulAdd(u1, key.getPublic(), u2)), p.isInfinity() ? !1 : p.getX().umod(this.n).cmp(r) === 0); - }; - EC.prototype.recoverPubKey = function (msg, signature, j, enc) { - assert((3 & j) === j, "The recovery param is more than two bits"), (signature = new Signature(signature, enc)); - var n = this.n, - e = new BN(msg), - r = signature.r, - s = signature.s, - isYOdd = j & 1, - isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error("Unable to find sencond key candinate"); - isSecondKey ? (r = this.curve.pointFromX(r.add(this.curve.n), isYOdd)) : (r = this.curve.pointFromX(r, isYOdd)); - var rInv = signature.r.invm(n), - s1 = n.sub(e).mul(rInv).umod(n), - s2 = s.mul(rInv).umod(n); - return this.g.mulAdd(s1, r, s2); - }; - EC.prototype.getKeyRecoveryParam = function (e, signature, Q, enc) { - if (((signature = new Signature(signature, enc)), signature.recoveryParam !== null)) - return signature.recoveryParam; - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch { - continue; - } - if (Qprime.eq(Q)) return i; - } - throw new Error("Unable to find valid recovery factor"); - }; - }, -}); - -// node_modules/elliptic/lib/elliptic/eddsa/key.js -var require_key2 = __commonJS({ - "node_modules/elliptic/lib/elliptic/eddsa/key.js"(exports, module) { - "use strict"; - var utils = require_utils3(), - assert = utils.assert, - parseBytes = utils.parseBytes, - cachedProperty = utils.cachedProperty; - function KeyPair(eddsa, params) { - (this.eddsa = eddsa), - (this._secret = parseBytes(params.secret)), - eddsa.isPoint(params.pub) ? (this._pub = params.pub) : (this._pubBytes = parseBytes(params.pub)); - } - KeyPair.fromPublic = function (eddsa, pub) { - return pub instanceof KeyPair ? pub : new KeyPair(eddsa, { pub }); - }; - KeyPair.fromSecret = function (eddsa, secret) { - return secret instanceof KeyPair ? secret : new KeyPair(eddsa, { secret }); - }; - KeyPair.prototype.secret = function () { - return this._secret; - }; - cachedProperty(KeyPair, "pubBytes", function () { - return this.eddsa.encodePoint(this.pub()); - }); - cachedProperty(KeyPair, "pub", function () { - return this._pubBytes ? this.eddsa.decodePoint(this._pubBytes) : this.eddsa.g.mul(this.priv()); - }); - cachedProperty(KeyPair, "privBytes", function () { - var eddsa = this.eddsa, - hash = this.hash(), - lastIx = eddsa.encodingLength - 1, - a = hash.slice(0, eddsa.encodingLength); - return (a[0] &= 248), (a[lastIx] &= 127), (a[lastIx] |= 64), a; - }); - cachedProperty(KeyPair, "priv", function () { - return this.eddsa.decodeInt(this.privBytes()); - }); - cachedProperty(KeyPair, "hash", function () { - return this.eddsa.hash().update(this.secret()).digest(); - }); - cachedProperty(KeyPair, "messagePrefix", function () { - return this.hash().slice(this.eddsa.encodingLength); - }); - KeyPair.prototype.sign = function (message) { - return assert(this._secret, "KeyPair can only verify"), this.eddsa.sign(message, this); - }; - KeyPair.prototype.verify = function (message, sig) { - return this.eddsa.verify(message, sig, this); - }; - KeyPair.prototype.getSecret = function (enc) { - return assert(this._secret, "KeyPair is public only"), utils.encode(this.secret(), enc); - }; - KeyPair.prototype.getPublic = function (enc) { - return utils.encode(this.pubBytes(), enc); - }; - module.exports = KeyPair; - }, -}); - -// node_modules/elliptic/lib/elliptic/eddsa/signature.js -var require_signature2 = __commonJS({ - "node_modules/elliptic/lib/elliptic/eddsa/signature.js"(exports, module) { - "use strict"; - var BN = require_bn4(), - utils = require_utils3(), - assert = utils.assert, - cachedProperty = utils.cachedProperty, - parseBytes = utils.parseBytes; - function Signature(eddsa, sig) { - (this.eddsa = eddsa), - typeof sig != "object" && (sig = parseBytes(sig)), - Array.isArray(sig) && - (sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), - }), - assert(sig.R && sig.S, "Signature without R or S"), - eddsa.isPoint(sig.R) && (this._R = sig.R), - sig.S instanceof BN && (this._S = sig.S), - (this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded), - (this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded); - } - cachedProperty(Signature, "S", function () { - return this.eddsa.decodeInt(this.Sencoded()); - }); - cachedProperty(Signature, "R", function () { - return this.eddsa.decodePoint(this.Rencoded()); - }); - cachedProperty(Signature, "Rencoded", function () { - return this.eddsa.encodePoint(this.R()); - }); - cachedProperty(Signature, "Sencoded", function () { - return this.eddsa.encodeInt(this.S()); - }); - Signature.prototype.toBytes = function () { - return this.Rencoded().concat(this.Sencoded()); - }; - Signature.prototype.toHex = function () { - return utils.encode(this.toBytes(), "hex").toUpperCase(); - }; - module.exports = Signature; - }, -}); - -// node_modules/elliptic/lib/elliptic/eddsa/index.js -var require_eddsa = __commonJS({ - "node_modules/elliptic/lib/elliptic/eddsa/index.js"(exports, module) { - "use strict"; - var hash = require_hash2(), - curves = require_curves(), - utils = require_utils3(), - assert = utils.assert, - parseBytes = utils.parseBytes, - KeyPair = require_key2(), - Signature = require_signature2(); - function EDDSA(curve) { - if ((assert(curve === "ed25519", "only tested with ed25519 so far"), !(this instanceof EDDSA))) - return new EDDSA(curve); - (curve = curves[curve].curve), - (this.curve = curve), - (this.g = curve.g), - this.g.precompute(curve.n.bitLength() + 1), - (this.pointClass = curve.point().constructor), - (this.encodingLength = Math.ceil(curve.n.bitLength() / 8)), - (this.hash = hash.sha512); - } - module.exports = EDDSA; - EDDSA.prototype.sign = function (message, secret) { - message = parseBytes(message); - var key = this.keyFromSecret(secret), - r = this.hashInt(key.messagePrefix(), message), - R = this.g.mul(r), - Rencoded = this.encodePoint(R), - s_ = this.hashInt(Rencoded, key.pubBytes(), message).mul(key.priv()), - S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R, S, Rencoded }); - }; - EDDSA.prototype.verify = function (message, sig, pub) { - (message = parseBytes(message)), (sig = this.makeSignature(sig)); - var key = this.keyFromPublic(pub), - h = this.hashInt(sig.Rencoded(), key.pubBytes(), message), - SG = this.g.mul(sig.S()), - RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); - }; - EDDSA.prototype.hashInt = function () { - for (var hash2 = this.hash(), i = 0; i < arguments.length; i++) hash2.update(arguments[i]); - return utils.intFromLE(hash2.digest()).umod(this.curve.n); - }; - EDDSA.prototype.keyFromPublic = function (pub) { - return KeyPair.fromPublic(this, pub); - }; - EDDSA.prototype.keyFromSecret = function (secret) { - return KeyPair.fromSecret(this, secret); - }; - EDDSA.prototype.makeSignature = function (sig) { - return sig instanceof Signature ? sig : new Signature(this, sig); - }; - EDDSA.prototype.encodePoint = function (point) { - var enc = point.getY().toArray("le", this.encodingLength); - return (enc[this.encodingLength - 1] |= point.getX().isOdd() ? 128 : 0), enc; - }; - EDDSA.prototype.decodePoint = function (bytes) { - bytes = utils.parseBytes(bytes); - var lastIx = bytes.length - 1, - normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & -129), - xIsOdd = (bytes[lastIx] & 128) !== 0, - y = utils.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); - }; - EDDSA.prototype.encodeInt = function (num) { - return num.toArray("le", this.encodingLength); - }; - EDDSA.prototype.decodeInt = function (bytes) { - return utils.intFromLE(bytes); - }; - EDDSA.prototype.isPoint = function (val) { - return val instanceof this.pointClass; - }; - }, -}); - -// node_modules/elliptic/lib/elliptic.js -var require_elliptic = __commonJS({ - "node_modules/elliptic/lib/elliptic.js"(exports) { - "use strict"; - var elliptic = exports; - elliptic.version = require_package().version; - elliptic.utils = require_utils3(); - elliptic.rand = require_brorand(); - elliptic.curve = require_curve(); - elliptic.curves = require_curves(); - elliptic.ec = require_ec(); - elliptic.eddsa = require_eddsa(); - }, -}); - -// node_modules/asn1.js/node_modules/bn.js/lib/bn.js -var require_bn5 = __commonJS({ - "node_modules/asn1.js/node_modules/bn.js/lib/bn.js"(exports, module) { - (function (module2, exports2) { - "use strict"; - function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); - } - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - (TempCtor.prototype = superCtor.prototype), - (ctor.prototype = new TempCtor()), - (ctor.prototype.constructor = ctor); - } - function BN(number, base, endian) { - if (BN.isBN(number)) return number; - (this.negative = 0), - (this.words = null), - (this.length = 0), - (this.red = null), - number !== null && - ((base === "le" || base === "be") && ((endian = base), (base = 10)), - this._init(number || 0, base || 10, endian || "be")); - } - typeof module2 == "object" ? (module2.exports = BN) : (exports2.BN = BN), (BN.BN = BN), (BN.wordSize = 26); - var Buffer2 = Buffer; - - (BN.isBN = function (num) { - return num instanceof BN - ? !0 - : num !== null && - typeof num == "object" && - num.constructor.wordSize === BN.wordSize && - Array.isArray(num.words); - }), - (BN.max = function (left, right) { - return left.cmp(right) > 0 ? left : right; - }), - (BN.min = function (left, right) { - return left.cmp(right) < 0 ? left : right; - }), - (BN.prototype._init = function (number, base, endian) { - if (typeof number == "number") return this._initNumber(number, base, endian); - if (typeof number == "object") return this._initArray(number, base, endian); - base === "hex" && (base = 16), - assert(base === (base | 0) && base >= 2 && base <= 36), - (number = number.toString().replace(/\s+/g, "")); - var start = 0; - number[0] === "-" && (start++, (this.negative = 1)), - start < number.length && - (base === 16 - ? this._parseHex(number, start, endian) - : (this._parseBase(number, base, start), - endian === "le" && this._initArray(this.toArray(), base, endian))); - }), - (BN.prototype._initNumber = function (number, base, endian) { - number < 0 && ((this.negative = 1), (number = -number)), - number < 67108864 - ? ((this.words = [number & 67108863]), (this.length = 1)) - : number < 4503599627370496 - ? ((this.words = [number & 67108863, (number / 67108864) & 67108863]), (this.length = 2)) - : (assert(number < 9007199254740992), - (this.words = [number & 67108863, (number / 67108864) & 67108863, 1]), - (this.length = 3)), - endian === "le" && this._initArray(this.toArray(), base, endian); - }), - (BN.prototype._initArray = function (number, base, endian) { - if ((assert(typeof number.length == "number"), number.length <= 0)) - return (this.words = [0]), (this.length = 1), this; - (this.length = Math.ceil(number.length / 3)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var j, - w, - off = 0; - if (endian === "be") - for (i = number.length - 1, j = 0; i >= 0; i -= 3) - (w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - else if (endian === "le") - for (i = 0, j = 0; i < number.length; i += 3) - (w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - return this.strip(); - }); - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - return c >= 65 && c <= 70 ? c - 55 : c >= 97 && c <= 102 ? c - 87 : (c - 48) & 15; - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - return index - 1 >= lowerBound && (r |= parseHex4Bits(string, index - 1) << 4), r; - } - BN.prototype._parseHex = function (number, start, endian) { - (this.length = Math.ceil((number.length - start) / 6)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var off = 0, - j = 0, - w; - if (endian === "be") - for (i = number.length - 1; i >= start; i -= 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - } - this.strip(); - }; - function parseBase(str, start, end, mul) { - for (var r = 0, len = Math.min(str.length, end), i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - (r *= mul), c >= 49 ? (r += c - 49 + 10) : c >= 17 ? (r += c - 17 + 10) : (r += c); - } - return r; - } - (BN.prototype._parseBase = function (number, base, start) { - (this.words = [0]), (this.length = 1); - for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base) limbLen++; - limbLen--, (limbPow = (limbPow / base) | 0); - for ( - var total = number.length - start, - mod = total % limbLen, - end = Math.min(total, total - mod) + start, - word = 0, - i = start; - i < end; - i += limbLen - ) - (word = parseBase(number, i, i + limbLen, base)), - this.imuln(limbPow), - this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - if (mod !== 0) { - var pow = 1; - for (word = parseBase(number, i, number.length, base), i = 0; i < mod; i++) pow *= base; - this.imuln(pow), this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - } - this.strip(); - }), - (BN.prototype.copy = function (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) dest.words[i] = this.words[i]; - (dest.length = this.length), (dest.negative = this.negative), (dest.red = this.red); - }), - (BN.prototype.clone = function () { - var r = new BN(null); - return this.copy(r), r; - }), - (BN.prototype._expand = function (size) { - for (; this.length < size; ) this.words[this.length++] = 0; - return this; - }), - (BN.prototype.strip = function () { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; - return this._normSign(); - }), - (BN.prototype._normSign = function () { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }), - (BN.prototype.inspect = function () { - return (this.red ? ""; - }); - var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000", - ], - groupSizes = [ - 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, - ], - groupBases = [ - 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, - 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, - 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, - 60466176, - ]; - (BN.prototype.toString = function (base, padding) { - (base = base || 10), (padding = padding | 0 || 1); - var out; - if (base === 16 || base === "hex") { - out = ""; - for (var off = 0, carry = 0, i = 0; i < this.length; i++) { - var w = this.words[i], - word = (((w << off) | carry) & 16777215).toString(16); - (carry = (w >>> (24 - off)) & 16777215), - carry !== 0 || i !== this.length - 1 ? (out = zeros[6 - word.length] + word + out) : (out = word + out), - (off += 2), - off >= 26 && ((off -= 26), i--); - } - for (carry !== 0 && (out = carry.toString(16) + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - if (base === (base | 0) && base >= 2 && base <= 36) { - var groupSize = groupSizes[base], - groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - for (c.negative = 0; !c.isZero(); ) { - var r = c.modn(groupBase).toString(base); - (c = c.idivn(groupBase)), c.isZero() ? (out = r + out) : (out = zeros[groupSize - r.length] + r + out); - } - for (this.isZero() && (out = "0" + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - assert(!1, "Base should be between 2 and 36"); - }), - (BN.prototype.toNumber = function () { - var ret = this.words[0]; - return ( - this.length === 2 - ? (ret += this.words[1] * 67108864) - : this.length === 3 && this.words[2] === 1 - ? (ret += 4503599627370496 + this.words[1] * 67108864) - : this.length > 2 && assert(!1, "Number can only safely store up to 53 bits"), - this.negative !== 0 ? -ret : ret - ); - }), - (BN.prototype.toJSON = function () { - return this.toString(16); - }), - (BN.prototype.toBuffer = function (endian, length) { - return assert(typeof Buffer2 < "u"), this.toArrayLike(Buffer2, endian, length); - }), - (BN.prototype.toArray = function (endian, length) { - return this.toArrayLike(Array, endian, length); - }), - (BN.prototype.toArrayLike = function (ArrayType, endian, length) { - var byteLength = this.byteLength(), - reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"), - assert(reqLength > 0, "Requested array length <= 0"), - this.strip(); - var littleEndian = endian === "le", - res = new ArrayType(reqLength), - b, - i, - q = this.clone(); - if (littleEndian) { - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[i] = b); - for (; i < reqLength; i++) res[i] = 0; - } else { - for (i = 0; i < reqLength - byteLength; i++) res[i] = 0; - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[reqLength - i - 1] = b); - } - return res; - }), - Math.clz32 - ? (BN.prototype._countBits = function (w) { - return 32 - Math.clz32(w); - }) - : (BN.prototype._countBits = function (w) { - var t = w, - r = 0; - return ( - t >= 4096 && ((r += 13), (t >>>= 13)), - t >= 64 && ((r += 7), (t >>>= 7)), - t >= 8 && ((r += 4), (t >>>= 4)), - t >= 2 && ((r += 2), (t >>>= 2)), - r + t - ); - }), - (BN.prototype._zeroBits = function (w) { - if (w === 0) return 26; - var t = w, - r = 0; - return ( - (t & 8191) === 0 && ((r += 13), (t >>>= 13)), - (t & 127) === 0 && ((r += 7), (t >>>= 7)), - (t & 15) === 0 && ((r += 4), (t >>>= 4)), - (t & 3) === 0 && ((r += 2), (t >>>= 2)), - (t & 1) === 0 && r++, - r - ); - }), - (BN.prototype.bitLength = function () { - var w = this.words[this.length - 1], - hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }); - function toBitArray(num) { - for (var w = new Array(num.bitLength()), bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0, - wbit = bit % 26; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - return w; - } - (BN.prototype.zeroBits = function () { - if (this.isZero()) return 0; - for (var r = 0, i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - if (((r += b), b !== 26)) break; - } - return r; - }), - (BN.prototype.byteLength = function () { - return Math.ceil(this.bitLength() / 8); - }), - (BN.prototype.toTwos = function (width) { - return this.negative !== 0 ? this.abs().inotn(width).iaddn(1) : this.clone(); - }), - (BN.prototype.fromTwos = function (width) { - return this.testn(width - 1) ? this.notn(width).iaddn(1).ineg() : this.clone(); - }), - (BN.prototype.isNeg = function () { - return this.negative !== 0; - }), - (BN.prototype.neg = function () { - return this.clone().ineg(); - }), - (BN.prototype.ineg = function () { - return this.isZero() || (this.negative ^= 1), this; - }), - (BN.prototype.iuor = function (num) { - for (; this.length < num.length; ) this.words[this.length++] = 0; - for (var i = 0; i < num.length; i++) this.words[i] = this.words[i] | num.words[i]; - return this.strip(); - }), - (BN.prototype.ior = function (num) { - return assert((this.negative | num.negative) === 0), this.iuor(num); - }), - (BN.prototype.or = function (num) { - return this.length > num.length ? this.clone().ior(num) : num.clone().ior(this); - }), - (BN.prototype.uor = function (num) { - return this.length > num.length ? this.clone().iuor(num) : num.clone().iuor(this); - }), - (BN.prototype.iuand = function (num) { - var b; - this.length > num.length ? (b = num) : (b = this); - for (var i = 0; i < b.length; i++) this.words[i] = this.words[i] & num.words[i]; - return (this.length = b.length), this.strip(); - }), - (BN.prototype.iand = function (num) { - return assert((this.negative | num.negative) === 0), this.iuand(num); - }), - (BN.prototype.and = function (num) { - return this.length > num.length ? this.clone().iand(num) : num.clone().iand(this); - }), - (BN.prototype.uand = function (num) { - return this.length > num.length ? this.clone().iuand(num) : num.clone().iuand(this); - }), - (BN.prototype.iuxor = function (num) { - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var i = 0; i < b.length; i++) this.words[i] = a.words[i] ^ b.words[i]; - if (this !== a) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = a.length), this.strip(); - }), - (BN.prototype.ixor = function (num) { - return assert((this.negative | num.negative) === 0), this.iuxor(num); - }), - (BN.prototype.xor = function (num) { - return this.length > num.length ? this.clone().ixor(num) : num.clone().ixor(this); - }), - (BN.prototype.uxor = function (num) { - return this.length > num.length ? this.clone().iuxor(num) : num.clone().iuxor(this); - }), - (BN.prototype.inotn = function (width) { - assert(typeof width == "number" && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0, - bitsLeft = width % 26; - this._expand(bytesNeeded), bitsLeft > 0 && bytesNeeded--; - for (var i = 0; i < bytesNeeded; i++) this.words[i] = ~this.words[i] & 67108863; - return bitsLeft > 0 && (this.words[i] = ~this.words[i] & (67108863 >> (26 - bitsLeft))), this.strip(); - }), - (BN.prototype.notn = function (width) { - return this.clone().inotn(width); - }), - (BN.prototype.setn = function (bit, val) { - assert(typeof bit == "number" && bit >= 0); - var off = (bit / 26) | 0, - wbit = bit % 26; - return ( - this._expand(off + 1), - val - ? (this.words[off] = this.words[off] | (1 << wbit)) - : (this.words[off] = this.words[off] & ~(1 << wbit)), - this.strip() - ); - }), - (BN.prototype.iadd = function (num) { - var r; - if (this.negative !== 0 && num.negative === 0) - return (this.negative = 0), (r = this.isub(num)), (this.negative ^= 1), this._normSign(); - if (this.negative === 0 && num.negative !== 0) - return (num.negative = 0), (r = this.isub(num)), (num.negative = 1), r._normSign(); - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) + (b.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - if (((this.length = a.length), carry !== 0)) (this.words[this.length] = carry), this.length++; - else if (a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return this; - }), - (BN.prototype.add = function (num) { - var res; - return num.negative !== 0 && this.negative === 0 - ? ((num.negative = 0), (res = this.sub(num)), (num.negative ^= 1), res) - : num.negative === 0 && this.negative !== 0 - ? ((this.negative = 0), (res = num.sub(this)), (this.negative = 1), res) - : this.length > num.length - ? this.clone().iadd(num) - : num.clone().iadd(this); - }), - (BN.prototype.isub = function (num) { - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - return (num.negative = 1), r._normSign(); - } else if (this.negative !== 0) - return (this.negative = 0), this.iadd(num), (this.negative = 1), this._normSign(); - var cmp = this.cmp(num); - if (cmp === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; - var a, b; - cmp > 0 ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) - (b.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - if (carry === 0 && i < a.length && a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = Math.max(this.length, i)), a !== this && (this.negative = 1), this.strip(); - }), - (BN.prototype.sub = function (num) { - return this.clone().isub(num); - }); - function smallMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - var len = (self2.length + num.length) | 0; - (out.length = len), (len = (len - 1) | 0); - var a = self2.words[0] | 0, - b = num.words[0] | 0, - r = a * b, - lo = r & 67108863, - carry = (r / 67108864) | 0; - out.words[0] = lo; - for (var k = 1; k < len; k++) { - for ( - var ncarry = carry >>> 26, - rword = carry & 67108863, - maxJ = Math.min(k, num.length - 1), - j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = (k - j) | 0; - (a = self2.words[i] | 0), - (b = num.words[j] | 0), - (r = a * b + rword), - (ncarry += (r / 67108864) | 0), - (rword = r & 67108863); - } - (out.words[k] = rword | 0), (carry = ncarry | 0); - } - return carry !== 0 ? (out.words[k] = carry | 0) : out.length--, out.strip(); - } - var comb10MulTo = function (self2, num, out) { - var a = self2.words, - b = num.words, - o = out.words, - c = 0, - lo, - mid, - hi, - a0 = a[0] | 0, - al0 = a0 & 8191, - ah0 = a0 >>> 13, - a1 = a[1] | 0, - al1 = a1 & 8191, - ah1 = a1 >>> 13, - a2 = a[2] | 0, - al2 = a2 & 8191, - ah2 = a2 >>> 13, - a3 = a[3] | 0, - al3 = a3 & 8191, - ah3 = a3 >>> 13, - a4 = a[4] | 0, - al4 = a4 & 8191, - ah4 = a4 >>> 13, - a5 = a[5] | 0, - al5 = a5 & 8191, - ah5 = a5 >>> 13, - a6 = a[6] | 0, - al6 = a6 & 8191, - ah6 = a6 >>> 13, - a7 = a[7] | 0, - al7 = a7 & 8191, - ah7 = a7 >>> 13, - a8 = a[8] | 0, - al8 = a8 & 8191, - ah8 = a8 >>> 13, - a9 = a[9] | 0, - al9 = a9 & 8191, - ah9 = a9 >>> 13, - b0 = b[0] | 0, - bl0 = b0 & 8191, - bh0 = b0 >>> 13, - b1 = b[1] | 0, - bl1 = b1 & 8191, - bh1 = b1 >>> 13, - b2 = b[2] | 0, - bl2 = b2 & 8191, - bh2 = b2 >>> 13, - b3 = b[3] | 0, - bl3 = b3 & 8191, - bh3 = b3 >>> 13, - b4 = b[4] | 0, - bl4 = b4 & 8191, - bh4 = b4 >>> 13, - b5 = b[5] | 0, - bl5 = b5 & 8191, - bh5 = b5 >>> 13, - b6 = b[6] | 0, - bl6 = b6 & 8191, - bh6 = b6 >>> 13, - b7 = b[7] | 0, - bl7 = b7 & 8191, - bh7 = b7 >>> 13, - b8 = b[8] | 0, - bl8 = b8 & 8191, - bh8 = b8 >>> 13, - b9 = b[9] | 0, - bl9 = b9 & 8191, - bh9 = b9 >>> 13; - (out.negative = self2.negative ^ num.negative), - (out.length = 19), - (lo = Math.imul(al0, bl0)), - (mid = Math.imul(al0, bh0)), - (mid = (mid + Math.imul(ah0, bl0)) | 0), - (hi = Math.imul(ah0, bh0)); - var w0 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0), - (w0 &= 67108863), - (lo = Math.imul(al1, bl0)), - (mid = Math.imul(al1, bh0)), - (mid = (mid + Math.imul(ah1, bl0)) | 0), - (hi = Math.imul(ah1, bh0)), - (lo = (lo + Math.imul(al0, bl1)) | 0), - (mid = (mid + Math.imul(al0, bh1)) | 0), - (mid = (mid + Math.imul(ah0, bl1)) | 0), - (hi = (hi + Math.imul(ah0, bh1)) | 0); - var w1 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0), - (w1 &= 67108863), - (lo = Math.imul(al2, bl0)), - (mid = Math.imul(al2, bh0)), - (mid = (mid + Math.imul(ah2, bl0)) | 0), - (hi = Math.imul(ah2, bh0)), - (lo = (lo + Math.imul(al1, bl1)) | 0), - (mid = (mid + Math.imul(al1, bh1)) | 0), - (mid = (mid + Math.imul(ah1, bl1)) | 0), - (hi = (hi + Math.imul(ah1, bh1)) | 0), - (lo = (lo + Math.imul(al0, bl2)) | 0), - (mid = (mid + Math.imul(al0, bh2)) | 0), - (mid = (mid + Math.imul(ah0, bl2)) | 0), - (hi = (hi + Math.imul(ah0, bh2)) | 0); - var w2 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0), - (w2 &= 67108863), - (lo = Math.imul(al3, bl0)), - (mid = Math.imul(al3, bh0)), - (mid = (mid + Math.imul(ah3, bl0)) | 0), - (hi = Math.imul(ah3, bh0)), - (lo = (lo + Math.imul(al2, bl1)) | 0), - (mid = (mid + Math.imul(al2, bh1)) | 0), - (mid = (mid + Math.imul(ah2, bl1)) | 0), - (hi = (hi + Math.imul(ah2, bh1)) | 0), - (lo = (lo + Math.imul(al1, bl2)) | 0), - (mid = (mid + Math.imul(al1, bh2)) | 0), - (mid = (mid + Math.imul(ah1, bl2)) | 0), - (hi = (hi + Math.imul(ah1, bh2)) | 0), - (lo = (lo + Math.imul(al0, bl3)) | 0), - (mid = (mid + Math.imul(al0, bh3)) | 0), - (mid = (mid + Math.imul(ah0, bl3)) | 0), - (hi = (hi + Math.imul(ah0, bh3)) | 0); - var w3 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0), - (w3 &= 67108863), - (lo = Math.imul(al4, bl0)), - (mid = Math.imul(al4, bh0)), - (mid = (mid + Math.imul(ah4, bl0)) | 0), - (hi = Math.imul(ah4, bh0)), - (lo = (lo + Math.imul(al3, bl1)) | 0), - (mid = (mid + Math.imul(al3, bh1)) | 0), - (mid = (mid + Math.imul(ah3, bl1)) | 0), - (hi = (hi + Math.imul(ah3, bh1)) | 0), - (lo = (lo + Math.imul(al2, bl2)) | 0), - (mid = (mid + Math.imul(al2, bh2)) | 0), - (mid = (mid + Math.imul(ah2, bl2)) | 0), - (hi = (hi + Math.imul(ah2, bh2)) | 0), - (lo = (lo + Math.imul(al1, bl3)) | 0), - (mid = (mid + Math.imul(al1, bh3)) | 0), - (mid = (mid + Math.imul(ah1, bl3)) | 0), - (hi = (hi + Math.imul(ah1, bh3)) | 0), - (lo = (lo + Math.imul(al0, bl4)) | 0), - (mid = (mid + Math.imul(al0, bh4)) | 0), - (mid = (mid + Math.imul(ah0, bl4)) | 0), - (hi = (hi + Math.imul(ah0, bh4)) | 0); - var w4 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0), - (w4 &= 67108863), - (lo = Math.imul(al5, bl0)), - (mid = Math.imul(al5, bh0)), - (mid = (mid + Math.imul(ah5, bl0)) | 0), - (hi = Math.imul(ah5, bh0)), - (lo = (lo + Math.imul(al4, bl1)) | 0), - (mid = (mid + Math.imul(al4, bh1)) | 0), - (mid = (mid + Math.imul(ah4, bl1)) | 0), - (hi = (hi + Math.imul(ah4, bh1)) | 0), - (lo = (lo + Math.imul(al3, bl2)) | 0), - (mid = (mid + Math.imul(al3, bh2)) | 0), - (mid = (mid + Math.imul(ah3, bl2)) | 0), - (hi = (hi + Math.imul(ah3, bh2)) | 0), - (lo = (lo + Math.imul(al2, bl3)) | 0), - (mid = (mid + Math.imul(al2, bh3)) | 0), - (mid = (mid + Math.imul(ah2, bl3)) | 0), - (hi = (hi + Math.imul(ah2, bh3)) | 0), - (lo = (lo + Math.imul(al1, bl4)) | 0), - (mid = (mid + Math.imul(al1, bh4)) | 0), - (mid = (mid + Math.imul(ah1, bl4)) | 0), - (hi = (hi + Math.imul(ah1, bh4)) | 0), - (lo = (lo + Math.imul(al0, bl5)) | 0), - (mid = (mid + Math.imul(al0, bh5)) | 0), - (mid = (mid + Math.imul(ah0, bl5)) | 0), - (hi = (hi + Math.imul(ah0, bh5)) | 0); - var w5 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0), - (w5 &= 67108863), - (lo = Math.imul(al6, bl0)), - (mid = Math.imul(al6, bh0)), - (mid = (mid + Math.imul(ah6, bl0)) | 0), - (hi = Math.imul(ah6, bh0)), - (lo = (lo + Math.imul(al5, bl1)) | 0), - (mid = (mid + Math.imul(al5, bh1)) | 0), - (mid = (mid + Math.imul(ah5, bl1)) | 0), - (hi = (hi + Math.imul(ah5, bh1)) | 0), - (lo = (lo + Math.imul(al4, bl2)) | 0), - (mid = (mid + Math.imul(al4, bh2)) | 0), - (mid = (mid + Math.imul(ah4, bl2)) | 0), - (hi = (hi + Math.imul(ah4, bh2)) | 0), - (lo = (lo + Math.imul(al3, bl3)) | 0), - (mid = (mid + Math.imul(al3, bh3)) | 0), - (mid = (mid + Math.imul(ah3, bl3)) | 0), - (hi = (hi + Math.imul(ah3, bh3)) | 0), - (lo = (lo + Math.imul(al2, bl4)) | 0), - (mid = (mid + Math.imul(al2, bh4)) | 0), - (mid = (mid + Math.imul(ah2, bl4)) | 0), - (hi = (hi + Math.imul(ah2, bh4)) | 0), - (lo = (lo + Math.imul(al1, bl5)) | 0), - (mid = (mid + Math.imul(al1, bh5)) | 0), - (mid = (mid + Math.imul(ah1, bl5)) | 0), - (hi = (hi + Math.imul(ah1, bh5)) | 0), - (lo = (lo + Math.imul(al0, bl6)) | 0), - (mid = (mid + Math.imul(al0, bh6)) | 0), - (mid = (mid + Math.imul(ah0, bl6)) | 0), - (hi = (hi + Math.imul(ah0, bh6)) | 0); - var w6 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0), - (w6 &= 67108863), - (lo = Math.imul(al7, bl0)), - (mid = Math.imul(al7, bh0)), - (mid = (mid + Math.imul(ah7, bl0)) | 0), - (hi = Math.imul(ah7, bh0)), - (lo = (lo + Math.imul(al6, bl1)) | 0), - (mid = (mid + Math.imul(al6, bh1)) | 0), - (mid = (mid + Math.imul(ah6, bl1)) | 0), - (hi = (hi + Math.imul(ah6, bh1)) | 0), - (lo = (lo + Math.imul(al5, bl2)) | 0), - (mid = (mid + Math.imul(al5, bh2)) | 0), - (mid = (mid + Math.imul(ah5, bl2)) | 0), - (hi = (hi + Math.imul(ah5, bh2)) | 0), - (lo = (lo + Math.imul(al4, bl3)) | 0), - (mid = (mid + Math.imul(al4, bh3)) | 0), - (mid = (mid + Math.imul(ah4, bl3)) | 0), - (hi = (hi + Math.imul(ah4, bh3)) | 0), - (lo = (lo + Math.imul(al3, bl4)) | 0), - (mid = (mid + Math.imul(al3, bh4)) | 0), - (mid = (mid + Math.imul(ah3, bl4)) | 0), - (hi = (hi + Math.imul(ah3, bh4)) | 0), - (lo = (lo + Math.imul(al2, bl5)) | 0), - (mid = (mid + Math.imul(al2, bh5)) | 0), - (mid = (mid + Math.imul(ah2, bl5)) | 0), - (hi = (hi + Math.imul(ah2, bh5)) | 0), - (lo = (lo + Math.imul(al1, bl6)) | 0), - (mid = (mid + Math.imul(al1, bh6)) | 0), - (mid = (mid + Math.imul(ah1, bl6)) | 0), - (hi = (hi + Math.imul(ah1, bh6)) | 0), - (lo = (lo + Math.imul(al0, bl7)) | 0), - (mid = (mid + Math.imul(al0, bh7)) | 0), - (mid = (mid + Math.imul(ah0, bl7)) | 0), - (hi = (hi + Math.imul(ah0, bh7)) | 0); - var w7 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0), - (w7 &= 67108863), - (lo = Math.imul(al8, bl0)), - (mid = Math.imul(al8, bh0)), - (mid = (mid + Math.imul(ah8, bl0)) | 0), - (hi = Math.imul(ah8, bh0)), - (lo = (lo + Math.imul(al7, bl1)) | 0), - (mid = (mid + Math.imul(al7, bh1)) | 0), - (mid = (mid + Math.imul(ah7, bl1)) | 0), - (hi = (hi + Math.imul(ah7, bh1)) | 0), - (lo = (lo + Math.imul(al6, bl2)) | 0), - (mid = (mid + Math.imul(al6, bh2)) | 0), - (mid = (mid + Math.imul(ah6, bl2)) | 0), - (hi = (hi + Math.imul(ah6, bh2)) | 0), - (lo = (lo + Math.imul(al5, bl3)) | 0), - (mid = (mid + Math.imul(al5, bh3)) | 0), - (mid = (mid + Math.imul(ah5, bl3)) | 0), - (hi = (hi + Math.imul(ah5, bh3)) | 0), - (lo = (lo + Math.imul(al4, bl4)) | 0), - (mid = (mid + Math.imul(al4, bh4)) | 0), - (mid = (mid + Math.imul(ah4, bl4)) | 0), - (hi = (hi + Math.imul(ah4, bh4)) | 0), - (lo = (lo + Math.imul(al3, bl5)) | 0), - (mid = (mid + Math.imul(al3, bh5)) | 0), - (mid = (mid + Math.imul(ah3, bl5)) | 0), - (hi = (hi + Math.imul(ah3, bh5)) | 0), - (lo = (lo + Math.imul(al2, bl6)) | 0), - (mid = (mid + Math.imul(al2, bh6)) | 0), - (mid = (mid + Math.imul(ah2, bl6)) | 0), - (hi = (hi + Math.imul(ah2, bh6)) | 0), - (lo = (lo + Math.imul(al1, bl7)) | 0), - (mid = (mid + Math.imul(al1, bh7)) | 0), - (mid = (mid + Math.imul(ah1, bl7)) | 0), - (hi = (hi + Math.imul(ah1, bh7)) | 0), - (lo = (lo + Math.imul(al0, bl8)) | 0), - (mid = (mid + Math.imul(al0, bh8)) | 0), - (mid = (mid + Math.imul(ah0, bl8)) | 0), - (hi = (hi + Math.imul(ah0, bh8)) | 0); - var w8 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0), - (w8 &= 67108863), - (lo = Math.imul(al9, bl0)), - (mid = Math.imul(al9, bh0)), - (mid = (mid + Math.imul(ah9, bl0)) | 0), - (hi = Math.imul(ah9, bh0)), - (lo = (lo + Math.imul(al8, bl1)) | 0), - (mid = (mid + Math.imul(al8, bh1)) | 0), - (mid = (mid + Math.imul(ah8, bl1)) | 0), - (hi = (hi + Math.imul(ah8, bh1)) | 0), - (lo = (lo + Math.imul(al7, bl2)) | 0), - (mid = (mid + Math.imul(al7, bh2)) | 0), - (mid = (mid + Math.imul(ah7, bl2)) | 0), - (hi = (hi + Math.imul(ah7, bh2)) | 0), - (lo = (lo + Math.imul(al6, bl3)) | 0), - (mid = (mid + Math.imul(al6, bh3)) | 0), - (mid = (mid + Math.imul(ah6, bl3)) | 0), - (hi = (hi + Math.imul(ah6, bh3)) | 0), - (lo = (lo + Math.imul(al5, bl4)) | 0), - (mid = (mid + Math.imul(al5, bh4)) | 0), - (mid = (mid + Math.imul(ah5, bl4)) | 0), - (hi = (hi + Math.imul(ah5, bh4)) | 0), - (lo = (lo + Math.imul(al4, bl5)) | 0), - (mid = (mid + Math.imul(al4, bh5)) | 0), - (mid = (mid + Math.imul(ah4, bl5)) | 0), - (hi = (hi + Math.imul(ah4, bh5)) | 0), - (lo = (lo + Math.imul(al3, bl6)) | 0), - (mid = (mid + Math.imul(al3, bh6)) | 0), - (mid = (mid + Math.imul(ah3, bl6)) | 0), - (hi = (hi + Math.imul(ah3, bh6)) | 0), - (lo = (lo + Math.imul(al2, bl7)) | 0), - (mid = (mid + Math.imul(al2, bh7)) | 0), - (mid = (mid + Math.imul(ah2, bl7)) | 0), - (hi = (hi + Math.imul(ah2, bh7)) | 0), - (lo = (lo + Math.imul(al1, bl8)) | 0), - (mid = (mid + Math.imul(al1, bh8)) | 0), - (mid = (mid + Math.imul(ah1, bl8)) | 0), - (hi = (hi + Math.imul(ah1, bh8)) | 0), - (lo = (lo + Math.imul(al0, bl9)) | 0), - (mid = (mid + Math.imul(al0, bh9)) | 0), - (mid = (mid + Math.imul(ah0, bl9)) | 0), - (hi = (hi + Math.imul(ah0, bh9)) | 0); - var w9 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0), - (w9 &= 67108863), - (lo = Math.imul(al9, bl1)), - (mid = Math.imul(al9, bh1)), - (mid = (mid + Math.imul(ah9, bl1)) | 0), - (hi = Math.imul(ah9, bh1)), - (lo = (lo + Math.imul(al8, bl2)) | 0), - (mid = (mid + Math.imul(al8, bh2)) | 0), - (mid = (mid + Math.imul(ah8, bl2)) | 0), - (hi = (hi + Math.imul(ah8, bh2)) | 0), - (lo = (lo + Math.imul(al7, bl3)) | 0), - (mid = (mid + Math.imul(al7, bh3)) | 0), - (mid = (mid + Math.imul(ah7, bl3)) | 0), - (hi = (hi + Math.imul(ah7, bh3)) | 0), - (lo = (lo + Math.imul(al6, bl4)) | 0), - (mid = (mid + Math.imul(al6, bh4)) | 0), - (mid = (mid + Math.imul(ah6, bl4)) | 0), - (hi = (hi + Math.imul(ah6, bh4)) | 0), - (lo = (lo + Math.imul(al5, bl5)) | 0), - (mid = (mid + Math.imul(al5, bh5)) | 0), - (mid = (mid + Math.imul(ah5, bl5)) | 0), - (hi = (hi + Math.imul(ah5, bh5)) | 0), - (lo = (lo + Math.imul(al4, bl6)) | 0), - (mid = (mid + Math.imul(al4, bh6)) | 0), - (mid = (mid + Math.imul(ah4, bl6)) | 0), - (hi = (hi + Math.imul(ah4, bh6)) | 0), - (lo = (lo + Math.imul(al3, bl7)) | 0), - (mid = (mid + Math.imul(al3, bh7)) | 0), - (mid = (mid + Math.imul(ah3, bl7)) | 0), - (hi = (hi + Math.imul(ah3, bh7)) | 0), - (lo = (lo + Math.imul(al2, bl8)) | 0), - (mid = (mid + Math.imul(al2, bh8)) | 0), - (mid = (mid + Math.imul(ah2, bl8)) | 0), - (hi = (hi + Math.imul(ah2, bh8)) | 0), - (lo = (lo + Math.imul(al1, bl9)) | 0), - (mid = (mid + Math.imul(al1, bh9)) | 0), - (mid = (mid + Math.imul(ah1, bl9)) | 0), - (hi = (hi + Math.imul(ah1, bh9)) | 0); - var w10 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0), - (w10 &= 67108863), - (lo = Math.imul(al9, bl2)), - (mid = Math.imul(al9, bh2)), - (mid = (mid + Math.imul(ah9, bl2)) | 0), - (hi = Math.imul(ah9, bh2)), - (lo = (lo + Math.imul(al8, bl3)) | 0), - (mid = (mid + Math.imul(al8, bh3)) | 0), - (mid = (mid + Math.imul(ah8, bl3)) | 0), - (hi = (hi + Math.imul(ah8, bh3)) | 0), - (lo = (lo + Math.imul(al7, bl4)) | 0), - (mid = (mid + Math.imul(al7, bh4)) | 0), - (mid = (mid + Math.imul(ah7, bl4)) | 0), - (hi = (hi + Math.imul(ah7, bh4)) | 0), - (lo = (lo + Math.imul(al6, bl5)) | 0), - (mid = (mid + Math.imul(al6, bh5)) | 0), - (mid = (mid + Math.imul(ah6, bl5)) | 0), - (hi = (hi + Math.imul(ah6, bh5)) | 0), - (lo = (lo + Math.imul(al5, bl6)) | 0), - (mid = (mid + Math.imul(al5, bh6)) | 0), - (mid = (mid + Math.imul(ah5, bl6)) | 0), - (hi = (hi + Math.imul(ah5, bh6)) | 0), - (lo = (lo + Math.imul(al4, bl7)) | 0), - (mid = (mid + Math.imul(al4, bh7)) | 0), - (mid = (mid + Math.imul(ah4, bl7)) | 0), - (hi = (hi + Math.imul(ah4, bh7)) | 0), - (lo = (lo + Math.imul(al3, bl8)) | 0), - (mid = (mid + Math.imul(al3, bh8)) | 0), - (mid = (mid + Math.imul(ah3, bl8)) | 0), - (hi = (hi + Math.imul(ah3, bh8)) | 0), - (lo = (lo + Math.imul(al2, bl9)) | 0), - (mid = (mid + Math.imul(al2, bh9)) | 0), - (mid = (mid + Math.imul(ah2, bl9)) | 0), - (hi = (hi + Math.imul(ah2, bh9)) | 0); - var w11 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0), - (w11 &= 67108863), - (lo = Math.imul(al9, bl3)), - (mid = Math.imul(al9, bh3)), - (mid = (mid + Math.imul(ah9, bl3)) | 0), - (hi = Math.imul(ah9, bh3)), - (lo = (lo + Math.imul(al8, bl4)) | 0), - (mid = (mid + Math.imul(al8, bh4)) | 0), - (mid = (mid + Math.imul(ah8, bl4)) | 0), - (hi = (hi + Math.imul(ah8, bh4)) | 0), - (lo = (lo + Math.imul(al7, bl5)) | 0), - (mid = (mid + Math.imul(al7, bh5)) | 0), - (mid = (mid + Math.imul(ah7, bl5)) | 0), - (hi = (hi + Math.imul(ah7, bh5)) | 0), - (lo = (lo + Math.imul(al6, bl6)) | 0), - (mid = (mid + Math.imul(al6, bh6)) | 0), - (mid = (mid + Math.imul(ah6, bl6)) | 0), - (hi = (hi + Math.imul(ah6, bh6)) | 0), - (lo = (lo + Math.imul(al5, bl7)) | 0), - (mid = (mid + Math.imul(al5, bh7)) | 0), - (mid = (mid + Math.imul(ah5, bl7)) | 0), - (hi = (hi + Math.imul(ah5, bh7)) | 0), - (lo = (lo + Math.imul(al4, bl8)) | 0), - (mid = (mid + Math.imul(al4, bh8)) | 0), - (mid = (mid + Math.imul(ah4, bl8)) | 0), - (hi = (hi + Math.imul(ah4, bh8)) | 0), - (lo = (lo + Math.imul(al3, bl9)) | 0), - (mid = (mid + Math.imul(al3, bh9)) | 0), - (mid = (mid + Math.imul(ah3, bl9)) | 0), - (hi = (hi + Math.imul(ah3, bh9)) | 0); - var w12 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0), - (w12 &= 67108863), - (lo = Math.imul(al9, bl4)), - (mid = Math.imul(al9, bh4)), - (mid = (mid + Math.imul(ah9, bl4)) | 0), - (hi = Math.imul(ah9, bh4)), - (lo = (lo + Math.imul(al8, bl5)) | 0), - (mid = (mid + Math.imul(al8, bh5)) | 0), - (mid = (mid + Math.imul(ah8, bl5)) | 0), - (hi = (hi + Math.imul(ah8, bh5)) | 0), - (lo = (lo + Math.imul(al7, bl6)) | 0), - (mid = (mid + Math.imul(al7, bh6)) | 0), - (mid = (mid + Math.imul(ah7, bl6)) | 0), - (hi = (hi + Math.imul(ah7, bh6)) | 0), - (lo = (lo + Math.imul(al6, bl7)) | 0), - (mid = (mid + Math.imul(al6, bh7)) | 0), - (mid = (mid + Math.imul(ah6, bl7)) | 0), - (hi = (hi + Math.imul(ah6, bh7)) | 0), - (lo = (lo + Math.imul(al5, bl8)) | 0), - (mid = (mid + Math.imul(al5, bh8)) | 0), - (mid = (mid + Math.imul(ah5, bl8)) | 0), - (hi = (hi + Math.imul(ah5, bh8)) | 0), - (lo = (lo + Math.imul(al4, bl9)) | 0), - (mid = (mid + Math.imul(al4, bh9)) | 0), - (mid = (mid + Math.imul(ah4, bl9)) | 0), - (hi = (hi + Math.imul(ah4, bh9)) | 0); - var w13 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0), - (w13 &= 67108863), - (lo = Math.imul(al9, bl5)), - (mid = Math.imul(al9, bh5)), - (mid = (mid + Math.imul(ah9, bl5)) | 0), - (hi = Math.imul(ah9, bh5)), - (lo = (lo + Math.imul(al8, bl6)) | 0), - (mid = (mid + Math.imul(al8, bh6)) | 0), - (mid = (mid + Math.imul(ah8, bl6)) | 0), - (hi = (hi + Math.imul(ah8, bh6)) | 0), - (lo = (lo + Math.imul(al7, bl7)) | 0), - (mid = (mid + Math.imul(al7, bh7)) | 0), - (mid = (mid + Math.imul(ah7, bl7)) | 0), - (hi = (hi + Math.imul(ah7, bh7)) | 0), - (lo = (lo + Math.imul(al6, bl8)) | 0), - (mid = (mid + Math.imul(al6, bh8)) | 0), - (mid = (mid + Math.imul(ah6, bl8)) | 0), - (hi = (hi + Math.imul(ah6, bh8)) | 0), - (lo = (lo + Math.imul(al5, bl9)) | 0), - (mid = (mid + Math.imul(al5, bh9)) | 0), - (mid = (mid + Math.imul(ah5, bl9)) | 0), - (hi = (hi + Math.imul(ah5, bh9)) | 0); - var w14 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0), - (w14 &= 67108863), - (lo = Math.imul(al9, bl6)), - (mid = Math.imul(al9, bh6)), - (mid = (mid + Math.imul(ah9, bl6)) | 0), - (hi = Math.imul(ah9, bh6)), - (lo = (lo + Math.imul(al8, bl7)) | 0), - (mid = (mid + Math.imul(al8, bh7)) | 0), - (mid = (mid + Math.imul(ah8, bl7)) | 0), - (hi = (hi + Math.imul(ah8, bh7)) | 0), - (lo = (lo + Math.imul(al7, bl8)) | 0), - (mid = (mid + Math.imul(al7, bh8)) | 0), - (mid = (mid + Math.imul(ah7, bl8)) | 0), - (hi = (hi + Math.imul(ah7, bh8)) | 0), - (lo = (lo + Math.imul(al6, bl9)) | 0), - (mid = (mid + Math.imul(al6, bh9)) | 0), - (mid = (mid + Math.imul(ah6, bl9)) | 0), - (hi = (hi + Math.imul(ah6, bh9)) | 0); - var w15 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0), - (w15 &= 67108863), - (lo = Math.imul(al9, bl7)), - (mid = Math.imul(al9, bh7)), - (mid = (mid + Math.imul(ah9, bl7)) | 0), - (hi = Math.imul(ah9, bh7)), - (lo = (lo + Math.imul(al8, bl8)) | 0), - (mid = (mid + Math.imul(al8, bh8)) | 0), - (mid = (mid + Math.imul(ah8, bl8)) | 0), - (hi = (hi + Math.imul(ah8, bh8)) | 0), - (lo = (lo + Math.imul(al7, bl9)) | 0), - (mid = (mid + Math.imul(al7, bh9)) | 0), - (mid = (mid + Math.imul(ah7, bl9)) | 0), - (hi = (hi + Math.imul(ah7, bh9)) | 0); - var w16 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0), - (w16 &= 67108863), - (lo = Math.imul(al9, bl8)), - (mid = Math.imul(al9, bh8)), - (mid = (mid + Math.imul(ah9, bl8)) | 0), - (hi = Math.imul(ah9, bh8)), - (lo = (lo + Math.imul(al8, bl9)) | 0), - (mid = (mid + Math.imul(al8, bh9)) | 0), - (mid = (mid + Math.imul(ah8, bl9)) | 0), - (hi = (hi + Math.imul(ah8, bh9)) | 0); - var w17 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0), - (w17 &= 67108863), - (lo = Math.imul(al9, bl9)), - (mid = Math.imul(al9, bh9)), - (mid = (mid + Math.imul(ah9, bl9)) | 0), - (hi = Math.imul(ah9, bh9)); - var w18 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - return ( - (c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0), - (w18 &= 67108863), - (o[0] = w0), - (o[1] = w1), - (o[2] = w2), - (o[3] = w3), - (o[4] = w4), - (o[5] = w5), - (o[6] = w6), - (o[7] = w7), - (o[8] = w8), - (o[9] = w9), - (o[10] = w10), - (o[11] = w11), - (o[12] = w12), - (o[13] = w13), - (o[14] = w14), - (o[15] = w15), - (o[16] = w16), - (o[17] = w17), - (o[18] = w18), - c !== 0 && ((o[19] = c), out.length++), - out - ); - }; - Math.imul || (comb10MulTo = smallMulTo); - function bigMulTo(self2, num, out) { - (out.negative = num.negative ^ self2.negative), (out.length = self2.length + num.length); - for (var carry = 0, hncarry = 0, k = 0; k < out.length - 1; k++) { - var ncarry = hncarry; - hncarry = 0; - for ( - var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1), j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = k - j, - a = self2.words[i] | 0, - b = num.words[j] | 0, - r = a * b, - lo = r & 67108863; - (ncarry = (ncarry + ((r / 67108864) | 0)) | 0), - (lo = (lo + rword) | 0), - (rword = lo & 67108863), - (ncarry = (ncarry + (lo >>> 26)) | 0), - (hncarry += ncarry >>> 26), - (ncarry &= 67108863); - } - (out.words[k] = rword), (carry = ncarry), (ncarry = hncarry); - } - return carry !== 0 ? (out.words[k] = carry) : out.length--, out.strip(); - } - function jumboMulTo(self2, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self2, num, out); - } - BN.prototype.mulTo = function (num, out) { - var res, - len = this.length + num.length; - return ( - this.length === 10 && num.length === 10 - ? (res = comb10MulTo(this, num, out)) - : len < 63 - ? (res = smallMulTo(this, num, out)) - : len < 1024 - ? (res = bigMulTo(this, num, out)) - : (res = jumboMulTo(this, num, out)), - res - ); - }; - function FFTM(x, y) { - (this.x = x), (this.y = y); - } - (FFTM.prototype.makeRBT = function (N) { - for (var t = new Array(N), l = BN.prototype._countBits(N) - 1, i = 0; i < N; i++) t[i] = this.revBin(i, l, N); - return t; - }), - (FFTM.prototype.revBin = function (x, l, N) { - if (x === 0 || x === N - 1) return x; - for (var rb = 0, i = 0; i < l; i++) (rb |= (x & 1) << (l - i - 1)), (x >>= 1); - return rb; - }), - (FFTM.prototype.permute = function (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) (rtws[i] = rws[rbt[i]]), (itws[i] = iws[rbt[i]]); - }), - (FFTM.prototype.transform = function (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - for (var s = 1; s < N; s <<= 1) - for ( - var l = s << 1, rtwdf = Math.cos((2 * Math.PI) / l), itwdf = Math.sin((2 * Math.PI) / l), p = 0; - p < N; - p += l - ) - for (var rtwdf_ = rtwdf, itwdf_ = itwdf, j = 0; j < s; j++) { - var re = rtws[p + j], - ie = itws[p + j], - ro = rtws[p + j + s], - io = itws[p + j + s], - rx = rtwdf_ * ro - itwdf_ * io; - (io = rtwdf_ * io + itwdf_ * ro), - (ro = rx), - (rtws[p + j] = re + ro), - (itws[p + j] = ie + io), - (rtws[p + j + s] = re - ro), - (itws[p + j + s] = ie - io), - j !== l && - ((rx = rtwdf * rtwdf_ - itwdf * itwdf_), (itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_), (rtwdf_ = rx)); - } - }), - (FFTM.prototype.guessLen13b = function (n, m) { - var N = Math.max(m, n) | 1, - odd = N & 1, - i = 0; - for (N = (N / 2) | 0; N; N = N >>> 1) i++; - return 1 << (i + 1 + odd); - }), - (FFTM.prototype.conjugate = function (rws, iws, N) { - if (!(N <= 1)) - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - (rws[i] = rws[N - i - 1]), - (rws[N - i - 1] = t), - (t = iws[i]), - (iws[i] = -iws[N - i - 1]), - (iws[N - i - 1] = -t); - } - }), - (FFTM.prototype.normalize13b = function (ws, N) { - for (var carry = 0, i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 8192 + Math.round(ws[2 * i] / N) + carry; - (ws[i] = w & 67108863), w < 67108864 ? (carry = 0) : (carry = (w / 67108864) | 0); - } - return ws; - }), - (FFTM.prototype.convert13b = function (ws, len, rws, N) { - for (var carry = 0, i = 0; i < len; i++) - (carry = carry + (ws[i] | 0)), - (rws[2 * i] = carry & 8191), - (carry = carry >>> 13), - (rws[2 * i + 1] = carry & 8191), - (carry = carry >>> 13); - for (i = 2 * len; i < N; ++i) rws[i] = 0; - assert(carry === 0), assert((carry & -8192) === 0); - }), - (FFTM.prototype.stub = function (N) { - for (var ph = new Array(N), i = 0; i < N; i++) ph[i] = 0; - return ph; - }), - (FFTM.prototype.mulp = function (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length), - rbt = this.makeRBT(N), - _ = this.stub(N), - rws = new Array(N), - rwst = new Array(N), - iwst = new Array(N), - nrws = new Array(N), - nrwst = new Array(N), - niwst = new Array(N), - rmws = out.words; - (rmws.length = N), - this.convert13b(x.words, x.length, rws, N), - this.convert13b(y.words, y.length, nrws, N), - this.transform(rws, _, rwst, iwst, N, rbt), - this.transform(nrws, _, nrwst, niwst, N, rbt); - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - (iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]), (rwst[i] = rx); - } - return ( - this.conjugate(rwst, iwst, N), - this.transform(rwst, iwst, rmws, _, N, rbt), - this.conjugate(rmws, _, N), - this.normalize13b(rmws, N), - (out.negative = x.negative ^ y.negative), - (out.length = x.length + y.length), - out.strip() - ); - }), - (BN.prototype.mul = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), this.mulTo(num, out); - }), - (BN.prototype.mulf = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), jumboMulTo(this, num, out); - }), - (BN.prototype.imul = function (num) { - return this.clone().mulTo(num, this); - }), - (BN.prototype.imuln = function (num) { - assert(typeof num == "number"), assert(num < 67108864); - for (var carry = 0, i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num, - lo = (w & 67108863) + (carry & 67108863); - (carry >>= 26), (carry += (w / 67108864) | 0), (carry += lo >>> 26), (this.words[i] = lo & 67108863); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.muln = function (num) { - return this.clone().imuln(num); - }), - (BN.prototype.sqr = function () { - return this.mul(this); - }), - (BN.prototype.isqr = function () { - return this.imul(this.clone()); - }), - (BN.prototype.pow = function (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - for (var res = this, i = 0; i < w.length && w[i] === 0; i++, res = res.sqr()); - if (++i < w.length) for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) w[i] !== 0 && (res = res.mul(q)); - return res; - }), - (BN.prototype.iushln = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26, - carryMask = (67108863 >>> (26 - r)) << (26 - r), - i; - if (r !== 0) { - var carry = 0; - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask, - c = ((this.words[i] | 0) - newCarry) << r; - (this.words[i] = c | carry), (carry = newCarry >>> (26 - r)); - } - carry && ((this.words[i] = carry), this.length++); - } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) this.words[i + s] = this.words[i]; - for (i = 0; i < s; i++) this.words[i] = 0; - this.length += s; - } - return this.strip(); - }), - (BN.prototype.ishln = function (bits) { - return assert(this.negative === 0), this.iushln(bits); - }), - (BN.prototype.iushrn = function (bits, hint, extended) { - assert(typeof bits == "number" && bits >= 0); - var h; - hint ? (h = (hint - (hint % 26)) / 26) : (h = 0); - var r = bits % 26, - s = Math.min((bits - r) / 26, this.length), - mask = 67108863 ^ ((67108863 >>> r) << r), - maskedWords = extended; - if (((h -= s), (h = Math.max(0, h)), maskedWords)) { - for (var i = 0; i < s; i++) maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - if (s !== 0) - if (this.length > s) for (this.length -= s, i = 0; i < this.length; i++) this.words[i] = this.words[i + s]; - else (this.words[0] = 0), (this.length = 1); - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - (this.words[i] = (carry << (26 - r)) | (word >>> r)), (carry = word & mask); - } - return ( - maskedWords && carry !== 0 && (maskedWords.words[maskedWords.length++] = carry), - this.length === 0 && ((this.words[0] = 0), (this.length = 1)), - this.strip() - ); - }), - (BN.prototype.ishrn = function (bits, hint, extended) { - return assert(this.negative === 0), this.iushrn(bits, hint, extended); - }), - (BN.prototype.shln = function (bits) { - return this.clone().ishln(bits); - }), - (BN.prototype.ushln = function (bits) { - return this.clone().iushln(bits); - }), - (BN.prototype.shrn = function (bits) { - return this.clone().ishrn(bits); - }), - (BN.prototype.ushrn = function (bits) { - return this.clone().iushrn(bits); - }), - (BN.prototype.testn = function (bit) { - assert(typeof bit == "number" && bit >= 0); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return !1; - var w = this.words[s]; - return !!(w & q); - }), - (BN.prototype.imaskn = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26; - if ((assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)) return this; - if ((r !== 0 && s++, (this.length = Math.min(s, this.length)), r !== 0)) { - var mask = 67108863 ^ ((67108863 >>> r) << r); - this.words[this.length - 1] &= mask; - } - return this.strip(); - }), - (BN.prototype.maskn = function (bits) { - return this.clone().imaskn(bits); - }), - (BN.prototype.iaddn = function (num) { - return ( - assert(typeof num == "number"), - assert(num < 67108864), - num < 0 - ? this.isubn(-num) - : this.negative !== 0 - ? this.length === 1 && (this.words[0] | 0) < num - ? ((this.words[0] = num - (this.words[0] | 0)), (this.negative = 0), this) - : ((this.negative = 0), this.isubn(num), (this.negative = 1), this) - : this._iaddn(num) - ); - }), - (BN.prototype._iaddn = function (num) { - this.words[0] += num; - for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) - (this.words[i] -= 67108864), i === this.length - 1 ? (this.words[i + 1] = 1) : this.words[i + 1]++; - return (this.length = Math.max(this.length, i + 1)), this; - }), - (BN.prototype.isubn = function (num) { - if ((assert(typeof num == "number"), assert(num < 67108864), num < 0)) return this.iaddn(-num); - if (this.negative !== 0) return (this.negative = 0), this.iaddn(num), (this.negative = 1), this; - if (((this.words[0] -= num), this.length === 1 && this.words[0] < 0)) - (this.words[0] = -this.words[0]), (this.negative = 1); - else - for (var i = 0; i < this.length && this.words[i] < 0; i++) - (this.words[i] += 67108864), (this.words[i + 1] -= 1); - return this.strip(); - }), - (BN.prototype.addn = function (num) { - return this.clone().iaddn(num); - }), - (BN.prototype.subn = function (num) { - return this.clone().isubn(num); - }), - (BN.prototype.iabs = function () { - return (this.negative = 0), this; - }), - (BN.prototype.abs = function () { - return this.clone().iabs(); - }), - (BN.prototype._ishlnsubmul = function (num, mul, shift) { - var len = num.length + shift, - i; - this._expand(len); - var w, - carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - (w -= right & 67108863), - (carry = (w >> 26) - ((right / 67108864) | 0)), - (this.words[i + shift] = w & 67108863); - } - for (; i < this.length - shift; i++) - (w = (this.words[i + shift] | 0) + carry), (carry = w >> 26), (this.words[i + shift] = w & 67108863); - if (carry === 0) return this.strip(); - for (assert(carry === -1), carry = 0, i = 0; i < this.length; i++) - (w = -(this.words[i] | 0) + carry), (carry = w >> 26), (this.words[i] = w & 67108863); - return (this.negative = 1), this.strip(); - }), - (BN.prototype._wordDiv = function (num, mode) { - var shift = this.length - num.length, - a = this.clone(), - b = num, - bhi = b.words[b.length - 1] | 0, - bhiBits = this._countBits(bhi); - (shift = 26 - bhiBits), - shift !== 0 && ((b = b.ushln(shift)), a.iushln(shift), (bhi = b.words[b.length - 1] | 0)); - var m = a.length - b.length, - q; - if (mode !== "mod") { - (q = new BN(null)), (q.length = m + 1), (q.words = new Array(q.length)); - for (var i = 0; i < q.length; i++) q.words[i] = 0; - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - diff.negative === 0 && ((a = diff), q && (q.words[m] = 1)); - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); - for (qj = Math.min((qj / bhi) | 0, 67108863), a._ishlnsubmul(b, qj, j); a.negative !== 0; ) - qj--, (a.negative = 0), a._ishlnsubmul(b, 1, j), a.isZero() || (a.negative ^= 1); - q && (q.words[j] = qj); - } - return ( - q && q.strip(), - a.strip(), - mode !== "div" && shift !== 0 && a.iushrn(shift), - { - div: q || null, - mod: a, - } - ); - }), - (BN.prototype.divmod = function (num, mode, positive) { - if ((assert(!num.isZero()), this.isZero())) - return { - div: new BN(0), - mod: new BN(0), - }; - var div, mod, res; - return this.negative !== 0 && num.negative === 0 - ? ((res = this.neg().divmod(num, mode)), - mode !== "mod" && (div = res.div.neg()), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.iadd(num)), - { - div, - mod, - }) - : this.negative === 0 && num.negative !== 0 - ? ((res = this.divmod(num.neg(), mode)), - mode !== "mod" && (div = res.div.neg()), - { - div, - mod: res.mod, - }) - : (this.negative & num.negative) !== 0 - ? ((res = this.neg().divmod(num.neg(), mode)), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.isub(num)), - { - div: res.div, - mod, - }) - : num.length > this.length || this.cmp(num) < 0 - ? { - div: new BN(0), - mod: this, - } - : num.length === 1 - ? mode === "div" - ? { - div: this.divn(num.words[0]), - mod: null, - } - : mode === "mod" - ? { - div: null, - mod: new BN(this.modn(num.words[0])), - } - : { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])), - } - : this._wordDiv(num, mode); - }), - (BN.prototype.div = function (num) { - return this.divmod(num, "div", !1).div; - }), - (BN.prototype.mod = function (num) { - return this.divmod(num, "mod", !1).mod; - }), - (BN.prototype.umod = function (num) { - return this.divmod(num, "mod", !0).mod; - }), - (BN.prototype.divRound = function (num) { - var dm = this.divmod(num); - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, - half = num.ushrn(1), - r2 = num.andln(1), - cmp = mod.cmp(half); - return cmp < 0 || (r2 === 1 && cmp === 0) - ? dm.div - : dm.div.negative !== 0 - ? dm.div.isubn(1) - : dm.div.iaddn(1); - }), - (BN.prototype.modn = function (num) { - assert(num <= 67108863); - for (var p = (1 << 26) % num, acc = 0, i = this.length - 1; i >= 0; i--) - acc = (p * acc + (this.words[i] | 0)) % num; - return acc; - }), - (BN.prototype.idivn = function (num) { - assert(num <= 67108863); - for (var carry = 0, i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 67108864; - (this.words[i] = (w / num) | 0), (carry = w % num); - } - return this.strip(); - }), - (BN.prototype.divn = function (num) { - return this.clone().idivn(num); - }), - (BN.prototype.egcd = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var x = this, - y = p.clone(); - x.negative !== 0 ? (x = x.umod(p)) : (x = x.clone()); - for (var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0; x.isEven() && y.isEven(); ) - x.iushrn(1), y.iushrn(1), ++g; - for (var yp = y.clone(), xp = x.clone(); !x.isZero(); ) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) - for (x.iushrn(i); i-- > 0; ) - (A.isOdd() || B.isOdd()) && (A.iadd(yp), B.isub(xp)), A.iushrn(1), B.iushrn(1); - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) - for (y.iushrn(j); j-- > 0; ) - (C.isOdd() || D.isOdd()) && (C.iadd(yp), D.isub(xp)), C.iushrn(1), D.iushrn(1); - x.cmp(y) >= 0 ? (x.isub(y), A.isub(C), B.isub(D)) : (y.isub(x), C.isub(A), D.isub(B)); - } - return { - a: C, - b: D, - gcd: y.iushln(g), - }; - }), - (BN.prototype._invmp = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var a = this, - b = p.clone(); - a.negative !== 0 ? (a = a.umod(p)) : (a = a.clone()); - for (var x1 = new BN(1), x2 = new BN(0), delta = b.clone(); a.cmpn(1) > 0 && b.cmpn(1) > 0; ) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) for (a.iushrn(i); i-- > 0; ) x1.isOdd() && x1.iadd(delta), x1.iushrn(1); - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) for (b.iushrn(j); j-- > 0; ) x2.isOdd() && x2.iadd(delta), x2.iushrn(1); - a.cmp(b) >= 0 ? (a.isub(b), x1.isub(x2)) : (b.isub(a), x2.isub(x1)); - } - var res; - return a.cmpn(1) === 0 ? (res = x1) : (res = x2), res.cmpn(0) < 0 && res.iadd(p), res; - }), - (BN.prototype.gcd = function (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(), - b = num.clone(); - (a.negative = 0), (b.negative = 0); - for (var shift = 0; a.isEven() && b.isEven(); shift++) a.iushrn(1), b.iushrn(1); - do { - for (; a.isEven(); ) a.iushrn(1); - for (; b.isEven(); ) b.iushrn(1); - var r = a.cmp(b); - if (r < 0) { - var t = a; - (a = b), (b = t); - } else if (r === 0 || b.cmpn(1) === 0) break; - a.isub(b); - } while (!0); - return b.iushln(shift); - }), - (BN.prototype.invm = function (num) { - return this.egcd(num).a.umod(num); - }), - (BN.prototype.isEven = function () { - return (this.words[0] & 1) === 0; - }), - (BN.prototype.isOdd = function () { - return (this.words[0] & 1) === 1; - }), - (BN.prototype.andln = function (num) { - return this.words[0] & num; - }), - (BN.prototype.bincn = function (bit) { - assert(typeof bit == "number"); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return this._expand(s + 1), (this.words[s] |= q), this; - for (var carry = q, i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - (w += carry), (carry = w >>> 26), (w &= 67108863), (this.words[i] = w); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.isZero = function () { - return this.length === 1 && this.words[0] === 0; - }), - (BN.prototype.cmpn = function (num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - this.strip(); - var res; - if (this.length > 1) res = 1; - else { - negative && (num = -num), assert(num <= 67108863, "Number is too big"); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.cmp = function (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.ucmp = function (num) { - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - for (var res = 0, i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0, - b = num.words[i] | 0; - if (a !== b) { - a < b ? (res = -1) : a > b && (res = 1); - break; - } - } - return res; - }), - (BN.prototype.gtn = function (num) { - return this.cmpn(num) === 1; - }), - (BN.prototype.gt = function (num) { - return this.cmp(num) === 1; - }), - (BN.prototype.gten = function (num) { - return this.cmpn(num) >= 0; - }), - (BN.prototype.gte = function (num) { - return this.cmp(num) >= 0; - }), - (BN.prototype.ltn = function (num) { - return this.cmpn(num) === -1; - }), - (BN.prototype.lt = function (num) { - return this.cmp(num) === -1; - }), - (BN.prototype.lten = function (num) { - return this.cmpn(num) <= 0; - }), - (BN.prototype.lte = function (num) { - return this.cmp(num) <= 0; - }), - (BN.prototype.eqn = function (num) { - return this.cmpn(num) === 0; - }), - (BN.prototype.eq = function (num) { - return this.cmp(num) === 0; - }), - (BN.red = function (num) { - return new Red(num); - }), - (BN.prototype.toRed = function (ctx) { - return ( - assert(!this.red, "Already a number in reduction context"), - assert(this.negative === 0, "red works only with positives"), - ctx.convertTo(this)._forceRed(ctx) - ); - }), - (BN.prototype.fromRed = function () { - return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }), - (BN.prototype._forceRed = function (ctx) { - return (this.red = ctx), this; - }), - (BN.prototype.forceRed = function (ctx) { - return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx); - }), - (BN.prototype.redAdd = function (num) { - return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num); - }), - (BN.prototype.redIAdd = function (num) { - return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num); - }), - (BN.prototype.redSub = function (num) { - return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num); - }), - (BN.prototype.redISub = function (num) { - return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num); - }), - (BN.prototype.redShl = function (num) { - return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num); - }), - (BN.prototype.redMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.mul(this, num) - ); - }), - (BN.prototype.redIMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.imul(this, num) - ); - }), - (BN.prototype.redSqr = function () { - return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }), - (BN.prototype.redISqr = function () { - return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }), - (BN.prototype.redSqrt = function () { - return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }), - (BN.prototype.redInvm = function () { - return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); - }), - (BN.prototype.redNeg = function () { - return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); - }), - (BN.prototype.redPow = function (num) { - return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num); - }); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null, - }; - function MPrime(name, p) { - (this.name = name), - (this.p = new BN(p, 16)), - (this.n = this.p.bitLength()), - (this.k = new BN(1).iushln(this.n).isub(this.p)), - (this.tmp = this._tmp()); - } - (MPrime.prototype._tmp = function () { - var tmp = new BN(null); - return (tmp.words = new Array(Math.ceil(this.n / 13))), tmp; - }), - (MPrime.prototype.ireduce = function (num) { - var r = num, - rlen; - do this.split(r, this.tmp), (r = this.imulK(r)), (r = r.iadd(this.tmp)), (rlen = r.bitLength()); - while (rlen > this.n); - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - return ( - cmp === 0 - ? ((r.words[0] = 0), (r.length = 1)) - : cmp > 0 - ? r.isub(this.p) - : r.strip !== void 0 - ? r.strip() - : r._strip(), - r - ); - }), - (MPrime.prototype.split = function (input, out) { - input.iushrn(this.n, 0, out); - }), - (MPrime.prototype.imulK = function (num) { - return num.imul(this.k); - }); - function K256() { - MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - inherits(K256, MPrime), - (K256.prototype.split = function (input, output) { - for (var mask = 4194303, outLen = Math.min(input.length, 9), i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - if (((output.length = outLen), input.length <= 9)) { - (input.words[0] = 0), (input.length = 1); - return; - } - var prev = input.words[9]; - for (output.words[output.length++] = prev & mask, i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - (input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22)), (prev = next); - } - (prev >>>= 22), - (input.words[i - 10] = prev), - prev === 0 && input.length > 10 ? (input.length -= 10) : (input.length -= 9); - }), - (K256.prototype.imulK = function (num) { - (num.words[num.length] = 0), (num.words[num.length + 1] = 0), (num.length += 2); - for (var lo = 0, i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - (lo += w * 977), (num.words[i] = lo & 67108863), (lo = w * 64 + ((lo / 67108864) | 0)); - } - return ( - num.words[num.length - 1] === 0 && (num.length--, num.words[num.length - 1] === 0 && num.length--), num - ); - }); - function P224() { - MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - inherits(P224, MPrime); - function P192() { - MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - inherits(P192, MPrime); - function P25519() { - MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - inherits(P25519, MPrime), - (P25519.prototype.imulK = function (num) { - for (var carry = 0, i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 19 + carry, - lo = hi & 67108863; - (hi >>>= 26), (num.words[i] = lo), (carry = hi); - } - return carry !== 0 && (num.words[num.length++] = carry), num; - }), - (BN._prime = function (name) { - if (primes[name]) return primes[name]; - var prime2; - if (name === "k256") prime2 = new K256(); - else if (name === "p224") prime2 = new P224(); - else if (name === "p192") prime2 = new P192(); - else if (name === "p25519") prime2 = new P25519(); - else throw new Error("Unknown prime " + name); - return (primes[name] = prime2), prime2; - }); - function Red(m) { - if (typeof m == "string") { - var prime = BN._prime(m); - (this.m = prime.p), (this.prime = prime); - } else assert(m.gtn(1), "modulus must be greater than 1"), (this.m = m), (this.prime = null); - } - (Red.prototype._verify1 = function (a) { - assert(a.negative === 0, "red works only with positives"), assert(a.red, "red works only with red numbers"); - }), - (Red.prototype._verify2 = function (a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"), - assert(a.red && a.red === b.red, "red works only with red numbers"); - }), - (Red.prototype.imod = function (a) { - return this.prime ? this.prime.ireduce(a)._forceRed(this) : a.umod(this.m)._forceRed(this); - }), - (Red.prototype.neg = function (a) { - return a.isZero() ? a.clone() : this.m.sub(a)._forceRed(this); - }), - (Red.prototype.add = function (a, b) { - this._verify2(a, b); - var res = a.add(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res._forceRed(this); - }), - (Red.prototype.iadd = function (a, b) { - this._verify2(a, b); - var res = a.iadd(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res; - }), - (Red.prototype.sub = function (a, b) { - this._verify2(a, b); - var res = a.sub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res._forceRed(this); - }), - (Red.prototype.isub = function (a, b) { - this._verify2(a, b); - var res = a.isub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res; - }), - (Red.prototype.shl = function (a, num) { - return this._verify1(a), this.imod(a.ushln(num)); - }), - (Red.prototype.imul = function (a, b) { - return this._verify2(a, b), this.imod(a.imul(b)); - }), - (Red.prototype.mul = function (a, b) { - return this._verify2(a, b), this.imod(a.mul(b)); - }), - (Red.prototype.isqr = function (a) { - return this.imul(a, a.clone()); - }), - (Red.prototype.sqr = function (a) { - return this.mul(a, a); - }), - (Red.prototype.sqrt = function (a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - if ((assert(mod3 % 2 === 1), mod3 === 3)) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - for (var q = this.m.subn(1), s = 0; !q.isZero() && q.andln(1) === 0; ) s++, q.iushrn(1); - assert(!q.isZero()); - var one = new BN(1).toRed(this), - nOne = one.redNeg(), - lpow = this.m.subn(1).iushrn(1), - z = this.m.bitLength(); - for (z = new BN(2 * z * z).toRed(this); this.pow(z, lpow).cmp(nOne) !== 0; ) z.redIAdd(nOne); - for ( - var c = this.pow(z, q), r = this.pow(a, q.addn(1).iushrn(1)), t = this.pow(a, q), m = s; - t.cmp(one) !== 0; - - ) { - for (var tmp = t, i = 0; tmp.cmp(one) !== 0; i++) tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - (r = r.redMul(b)), (c = b.redSqr()), (t = t.redMul(c)), (m = i); - } - return r; - }), - (Red.prototype.invm = function (a) { - var inv = a._invmp(this.m); - return inv.negative !== 0 ? ((inv.negative = 0), this.imod(inv).redNeg()) : this.imod(inv); - }), - (Red.prototype.pow = function (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4, - wnd = new Array(1 << windowSize); - (wnd[0] = new BN(1).toRed(this)), (wnd[1] = a); - for (var i = 2; i < wnd.length; i++) wnd[i] = this.mul(wnd[i - 1], a); - var res = wnd[0], - current = 0, - currentLen = 0, - start = num.bitLength() % 26; - for (start === 0 && (start = 26), i = num.length - 1; i >= 0; i--) { - for (var word = num.words[i], j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if ((res !== wnd[0] && (res = this.sqr(res)), bit === 0 && current === 0)) { - currentLen = 0; - continue; - } - (current <<= 1), - (current |= bit), - currentLen++, - !(currentLen !== windowSize && (i !== 0 || j !== 0)) && - ((res = this.mul(res, wnd[current])), (currentLen = 0), (current = 0)); - } - start = 26; - } - return res; - }), - (Red.prototype.convertTo = function (num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }), - (Red.prototype.convertFrom = function (num) { - var res = num.clone(); - return (res.red = null), res; - }), - (BN.mont = function (num) { - return new Mont(num); - }); - function Mont(m) { - Red.call(this, m), - (this.shift = this.m.bitLength()), - this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), - (this.r = new BN(1).iushln(this.shift)), - (this.r2 = this.imod(this.r.sqr())), - (this.rinv = this.r._invmp(this.m)), - (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), - (this.minv = this.minv.umod(this.r)), - (this.minv = this.r.sub(this.minv)); - } - inherits(Mont, Red), - (Mont.prototype.convertTo = function (num) { - return this.imod(num.ushln(this.shift)); - }), - (Mont.prototype.convertFrom = function (num) { - var r = this.imod(num.mul(this.rinv)); - return (r.red = null), r; - }), - (Mont.prototype.imul = function (a, b) { - if (a.isZero() || b.isZero()) return (a.words[0] = 0), (a.length = 1), a; - var t = a.imul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.mul = function (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.invm = function (a) { - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }); - })(typeof module > "u" || module, exports); - }, -}); - -// node_modules/safer-buffer/safer.js -var require_safer = __commonJS({ - "node_modules/safer-buffer/safer.js"(exports, module) { - "use strict"; - var buffer = BufferModule, - Buffer2 = Buffer, - safer = {}, - key; - for (key in buffer) - !buffer.hasOwnProperty(key) || key === "SlowBuffer" || key === "Buffer" || (safer[key] = buffer[key]); - var Safer = (safer.Buffer = {}); - for (key in Buffer2) - !Buffer2.hasOwnProperty(key) || key === "allocUnsafe" || key === "allocUnsafeSlow" || (Safer[key] = Buffer2[key]); - safer.Buffer.prototype = Buffer2.prototype; - (!Safer.from || Safer.from === Uint8Array.from) && - (Safer.from = function (value, encodingOrOffset, length) { - if (typeof value == "number") - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value); - if (value && typeof value.length > "u") - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + - typeof value, - ); - return Buffer2(value, encodingOrOffset, length); - }); - Safer.alloc || - (Safer.alloc = function (size, fill, encoding) { - if (typeof size != "number") - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size); - if (size < 0 || size >= 2 * (1 << 30)) - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - var buf = Buffer2(size); - return ( - !fill || fill.length === 0 - ? buf.fill(0) - : typeof encoding == "string" - ? buf.fill(fill, encoding) - : buf.fill(fill), - buf - ); - }); - if (!safer.kStringMaxLength) - try { - safer.kStringMaxLength = MAX_STRING_LENGTH; - } catch {} - safer.constants || - ((safer.constants = { - MAX_LENGTH: safer.kMaxLength, - }), - safer.kStringMaxLength && (safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength)); - module.exports = safer; - }, -}); - -// node_modules/asn1.js/lib/asn1/base/reporter.js -var require_reporter = __commonJS({ - "node_modules/asn1.js/lib/asn1/base/reporter.js"(exports) { - "use strict"; - var inherits = require_inherits_browser(); - function Reporter(options) { - this._reporterState = { - obj: null, - path: [], - options: options || {}, - errors: [], - }; - } - exports.Reporter = Reporter; - Reporter.prototype.isError = function (obj) { - return obj instanceof ReporterError; - }; - Reporter.prototype.save = function () { - let state = this._reporterState; - return { obj: state.obj, pathLen: state.path.length }; - }; - Reporter.prototype.restore = function (data) { - let state = this._reporterState; - (state.obj = data.obj), (state.path = state.path.slice(0, data.pathLen)); - }; - Reporter.prototype.enterKey = function (key) { - return this._reporterState.path.push(key); - }; - Reporter.prototype.exitKey = function (index) { - let state = this._reporterState; - state.path = state.path.slice(0, index - 1); - }; - Reporter.prototype.leaveKey = function (index, key, value) { - let state = this._reporterState; - this.exitKey(index), state.obj !== null && (state.obj[key] = value); - }; - Reporter.prototype.path = function () { - return this._reporterState.path.join("/"); - }; - Reporter.prototype.enterObject = function () { - let state = this._reporterState, - prev = state.obj; - return (state.obj = {}), prev; - }; - Reporter.prototype.leaveObject = function (prev) { - let state = this._reporterState, - now = state.obj; - return (state.obj = prev), now; - }; - Reporter.prototype.error = function (msg) { - let err, - state = this._reporterState, - inherited = msg instanceof ReporterError; - if ( - (inherited - ? (err = msg) - : (err = new ReporterError( - state.path - .map(function (elem) { - return "[" + JSON.stringify(elem) + "]"; - }) - .join(""), - msg.message || msg, - msg.stack, - )), - !state.options.partial) - ) - throw err; - return inherited || state.errors.push(err), err; - }; - Reporter.prototype.wrapResult = function (result) { - let state = this._reporterState; - return state.options.partial - ? { - result: this.isError(result) ? null : result, - errors: state.errors, - } - : result; - }; - function ReporterError(path, msg) { - (this.path = path), this.rethrow(msg); - } - inherits(ReporterError, Error); - ReporterError.prototype.rethrow = function (msg) { - if ( - ((this.message = msg + " at: " + (this.path || "(shallow)")), - Error.captureStackTrace && Error.captureStackTrace(this, ReporterError), - !this.stack) - ) - try { - throw new Error(this.message); - } catch (e) { - this.stack = e.stack; - } - return this; - }; - }, -}); - -// node_modules/asn1.js/lib/asn1/base/buffer.js -var require_buffer = __commonJS({ - "node_modules/asn1.js/lib/asn1/base/buffer.js"(exports) { - "use strict"; - var inherits = require_inherits_browser(), - Reporter = require_reporter().Reporter, - Buffer2 = require_safer().Buffer; - function DecoderBuffer(base, options) { - if ((Reporter.call(this, options), !Buffer2.isBuffer(base))) { - this.error("Input not Buffer"); - return; - } - (this.base = base), (this.offset = 0), (this.length = base.length); - } - inherits(DecoderBuffer, Reporter); - exports.DecoderBuffer = DecoderBuffer; - DecoderBuffer.isDecoderBuffer = function (data) { - return data instanceof DecoderBuffer - ? !0 - : typeof data == "object" && - Buffer2.isBuffer(data.base) && - data.constructor.name === "DecoderBuffer" && - typeof data.offset == "number" && - typeof data.length == "number" && - typeof data.save == "function" && - typeof data.restore == "function" && - typeof data.isEmpty == "function" && - typeof data.readUInt8 == "function" && - typeof data.skip == "function" && - typeof data.raw == "function"; - }; - DecoderBuffer.prototype.save = function () { - return { - offset: this.offset, - reporter: Reporter.prototype.save.call(this), - }; - }; - DecoderBuffer.prototype.restore = function (save) { - let res = new DecoderBuffer(this.base); - return ( - (res.offset = save.offset), - (res.length = this.offset), - (this.offset = save.offset), - Reporter.prototype.restore.call(this, save.reporter), - res - ); - }; - DecoderBuffer.prototype.isEmpty = function () { - return this.offset === this.length; - }; - DecoderBuffer.prototype.readUInt8 = function (fail) { - return this.offset + 1 <= this.length - ? this.base.readUInt8(this.offset++, !0) - : this.error(fail || "DecoderBuffer overrun"); - }; - DecoderBuffer.prototype.skip = function (bytes, fail) { - if (!(this.offset + bytes <= this.length)) return this.error(fail || "DecoderBuffer overrun"); - let res = new DecoderBuffer(this.base); - return ( - (res._reporterState = this._reporterState), - (res.offset = this.offset), - (res.length = this.offset + bytes), - (this.offset += bytes), - res - ); - }; - DecoderBuffer.prototype.raw = function (save) { - return this.base.slice(save ? save.offset : this.offset, this.length); - }; - function EncoderBuffer(value, reporter) { - if (Array.isArray(value)) - (this.length = 0), - (this.value = value.map(function (item) { - return ( - EncoderBuffer.isEncoderBuffer(item) || (item = new EncoderBuffer(item, reporter)), - (this.length += item.length), - item - ); - }, this)); - else if (typeof value == "number") { - if (!(0 <= value && value <= 255)) return reporter.error("non-byte EncoderBuffer value"); - (this.value = value), (this.length = 1); - } else if (typeof value == "string") (this.value = value), (this.length = Buffer2.byteLength(value)); - else if (Buffer2.isBuffer(value)) (this.value = value), (this.length = value.length); - else return reporter.error("Unsupported type: " + typeof value); - } - exports.EncoderBuffer = EncoderBuffer; - EncoderBuffer.isEncoderBuffer = function (data) { - return data instanceof EncoderBuffer - ? !0 - : typeof data == "object" && - data.constructor.name === "EncoderBuffer" && - typeof data.length == "number" && - typeof data.join == "function"; - }; - EncoderBuffer.prototype.join = function (out, offset) { - return ( - out || (out = Buffer2.alloc(this.length)), - offset || (offset = 0), - this.length === 0 || - (Array.isArray(this.value) - ? this.value.forEach(function (item) { - item.join(out, offset), (offset += item.length); - }) - : (typeof this.value == "number" - ? (out[offset] = this.value) - : typeof this.value == "string" - ? out.write(this.value, offset) - : Buffer2.isBuffer(this.value) && this.value.copy(out, offset), - (offset += this.length))), - out - ); - }; - }, -}); - -// node_modules/asn1.js/lib/asn1/base/node.js -var require_node = __commonJS({ - "node_modules/asn1.js/lib/asn1/base/node.js"(exports, module) { - "use strict"; - var Reporter = require_reporter().Reporter, - EncoderBuffer = require_buffer().EncoderBuffer, - DecoderBuffer = require_buffer().DecoderBuffer, - assert = require_minimalistic_assert(), - tags = [ - "seq", - "seqof", - "set", - "setof", - "objid", - "bool", - "gentime", - "utctime", - "null_", - "enum", - "int", - "objDesc", - "bitstr", - "bmpstr", - "charstr", - "genstr", - "graphstr", - "ia5str", - "iso646str", - "numstr", - "octstr", - "printstr", - "t61str", - "unistr", - "utf8str", - "videostr", - ], - methods = ["key", "obj", "use", "optional", "explicit", "implicit", "def", "choice", "any", "contains"].concat( - tags, - ), - overrided = [ - "_peekTag", - "_decodeTag", - "_use", - "_decodeStr", - "_decodeObjid", - "_decodeTime", - "_decodeNull", - "_decodeInt", - "_decodeBool", - "_decodeList", - "_encodeComposite", - "_encodeStr", - "_encodeObjid", - "_encodeTime", - "_encodeNull", - "_encodeInt", - "_encodeBool", - ]; - function Node(enc, parent, name) { - let state = {}; - (this._baseState = state), - (state.name = name), - (state.enc = enc), - (state.parent = parent || null), - (state.children = null), - (state.tag = null), - (state.args = null), - (state.reverseArgs = null), - (state.choice = null), - (state.optional = !1), - (state.any = !1), - (state.obj = !1), - (state.use = null), - (state.useDecoder = null), - (state.key = null), - (state.default = null), - (state.explicit = null), - (state.implicit = null), - (state.contains = null), - state.parent || ((state.children = []), this._wrap()); - } - module.exports = Node; - var stateProps = [ - "enc", - "parent", - "children", - "tag", - "args", - "reverseArgs", - "choice", - "optional", - "any", - "obj", - "use", - "alteredUse", - "key", - "default", - "explicit", - "implicit", - "contains", - ]; - Node.prototype.clone = function () { - let state = this._baseState, - cstate = {}; - stateProps.forEach(function (prop) { - cstate[prop] = state[prop]; - }); - let res = new this.constructor(cstate.parent); - return (res._baseState = cstate), res; - }; - Node.prototype._wrap = function () { - let state = this._baseState; - methods.forEach(function (method) { - this[method] = function () { - let clone = new this.constructor(this); - return state.children.push(clone), clone[method].apply(clone, arguments); - }; - }, this); - }; - Node.prototype._init = function (body) { - let state = this._baseState; - assert(state.parent === null), - body.call(this), - (state.children = state.children.filter(function (child) { - return child._baseState.parent === this; - }, this)), - assert.equal(state.children.length, 1, "Root node can have only one child"); - }; - Node.prototype._useArgs = function (args) { - let state = this._baseState, - children = args.filter(function (arg) { - return arg instanceof this.constructor; - }, this); - (args = args.filter(function (arg) { - return !(arg instanceof this.constructor); - }, this)), - children.length !== 0 && - (assert(state.children === null), - (state.children = children), - children.forEach(function (child) { - child._baseState.parent = this; - }, this)), - args.length !== 0 && - (assert(state.args === null), - (state.args = args), - (state.reverseArgs = args.map(function (arg) { - if (typeof arg != "object" || arg.constructor !== Object) return arg; - let res = {}; - return ( - Object.keys(arg).forEach(function (key) { - key == (key | 0) && (key |= 0); - let value = arg[key]; - res[value] = key; - }), - res - ); - }))); - }; - overrided.forEach(function (method) { - Node.prototype[method] = function () { - let state = this._baseState; - throw new Error(method + " not implemented for encoding: " + state.enc); - }; - }); - tags.forEach(function (tag) { - Node.prototype[tag] = function () { - let state = this._baseState, - args = Array.prototype.slice.call(arguments); - return assert(state.tag === null), (state.tag = tag), this._useArgs(args), this; - }; - }); - Node.prototype.use = function (item) { - assert(item); - let state = this._baseState; - return assert(state.use === null), (state.use = item), this; - }; - Node.prototype.optional = function () { - let state = this._baseState; - return (state.optional = !0), this; - }; - Node.prototype.def = function (val) { - let state = this._baseState; - return assert(state.default === null), (state.default = val), (state.optional = !0), this; - }; - Node.prototype.explicit = function (num) { - let state = this._baseState; - return assert(state.explicit === null && state.implicit === null), (state.explicit = num), this; - }; - Node.prototype.implicit = function (num) { - let state = this._baseState; - return assert(state.explicit === null && state.implicit === null), (state.implicit = num), this; - }; - Node.prototype.obj = function () { - let state = this._baseState, - args = Array.prototype.slice.call(arguments); - return (state.obj = !0), args.length !== 0 && this._useArgs(args), this; - }; - Node.prototype.key = function (newKey) { - let state = this._baseState; - return assert(state.key === null), (state.key = newKey), this; - }; - Node.prototype.any = function () { - let state = this._baseState; - return (state.any = !0), this; - }; - Node.prototype.choice = function (obj) { - let state = this._baseState; - return ( - assert(state.choice === null), - (state.choice = obj), - this._useArgs( - Object.keys(obj).map(function (key) { - return obj[key]; - }), - ), - this - ); - }; - Node.prototype.contains = function (item) { - let state = this._baseState; - return assert(state.use === null), (state.contains = item), this; - }; - Node.prototype._decode = function (input, options) { - let state = this._baseState; - if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); - let result = state.default, - present = !0, - prevKey = null; - if ((state.key !== null && (prevKey = input.enterKey(state.key)), state.optional)) { - let tag = null; - if ( - (state.explicit !== null - ? (tag = state.explicit) - : state.implicit !== null - ? (tag = state.implicit) - : state.tag !== null && (tag = state.tag), - tag === null && !state.any) - ) { - let save = input.save(); - try { - state.choice === null ? this._decodeGeneric(state.tag, input, options) : this._decodeChoice(input, options), - (present = !0); - } catch { - present = !1; - } - input.restore(save); - } else if (((present = this._peekTag(input, tag, state.any)), input.isError(present))) return present; - } - let prevObj; - if ((state.obj && present && (prevObj = input.enterObject()), present)) { - if (state.explicit !== null) { - let explicit = this._decodeTag(input, state.explicit); - if (input.isError(explicit)) return explicit; - input = explicit; - } - let start = input.offset; - if (state.use === null && state.choice === null) { - let save; - state.any && (save = input.save()); - let body = this._decodeTag(input, state.implicit !== null ? state.implicit : state.tag, state.any); - if (input.isError(body)) return body; - state.any ? (result = input.raw(save)) : (input = body); - } - if ( - (options && options.track && state.tag !== null && options.track(input.path(), start, input.length, "tagged"), - options && - options.track && - state.tag !== null && - options.track(input.path(), input.offset, input.length, "content"), - state.any || - (state.choice === null - ? (result = this._decodeGeneric(state.tag, input, options)) - : (result = this._decodeChoice(input, options))), - input.isError(result)) - ) - return result; - if ( - (!state.any && - state.choice === null && - state.children !== null && - state.children.forEach(function (child) { - child._decode(input, options); - }), - state.contains && (state.tag === "octstr" || state.tag === "bitstr")) - ) { - let data = new DecoderBuffer(result); - result = this._getUse(state.contains, input._reporterState.obj)._decode(data, options); - } - } - return ( - state.obj && present && (result = input.leaveObject(prevObj)), - state.key !== null && (result !== null || present === !0) - ? input.leaveKey(prevKey, state.key, result) - : prevKey !== null && input.exitKey(prevKey), - result - ); - }; - Node.prototype._decodeGeneric = function (tag, input, options) { - let state = this._baseState; - return tag === "seq" || tag === "set" - ? null - : tag === "seqof" || tag === "setof" - ? this._decodeList(input, tag, state.args[0], options) - : /str$/.test(tag) - ? this._decodeStr(input, tag, options) - : tag === "objid" && state.args - ? this._decodeObjid(input, state.args[0], state.args[1], options) - : tag === "objid" - ? this._decodeObjid(input, null, null, options) - : tag === "gentime" || tag === "utctime" - ? this._decodeTime(input, tag, options) - : tag === "null_" - ? this._decodeNull(input, options) - : tag === "bool" - ? this._decodeBool(input, options) - : tag === "objDesc" - ? this._decodeStr(input, tag, options) - : tag === "int" || tag === "enum" - ? this._decodeInt(input, state.args && state.args[0], options) - : state.use !== null - ? this._getUse(state.use, input._reporterState.obj)._decode(input, options) - : input.error("unknown tag: " + tag); - }; - Node.prototype._getUse = function (entity, obj) { - let state = this._baseState; - return ( - (state.useDecoder = this._use(entity, obj)), - assert(state.useDecoder._baseState.parent === null), - (state.useDecoder = state.useDecoder._baseState.children[0]), - state.implicit !== state.useDecoder._baseState.implicit && - ((state.useDecoder = state.useDecoder.clone()), (state.useDecoder._baseState.implicit = state.implicit)), - state.useDecoder - ); - }; - Node.prototype._decodeChoice = function (input, options) { - let state = this._baseState, - result = null, - match = !1; - return ( - Object.keys(state.choice).some(function (key) { - let save = input.save(), - node = state.choice[key]; - try { - let value = node._decode(input, options); - if (input.isError(value)) return !1; - (result = { type: key, value }), (match = !0); - } catch { - return input.restore(save), !1; - } - return !0; - }, this), - match ? result : input.error("Choice not matched") - ); - }; - Node.prototype._createEncoderBuffer = function (data) { - return new EncoderBuffer(data, this.reporter); - }; - Node.prototype._encode = function (data, reporter, parent) { - let state = this._baseState; - if (state.default !== null && state.default === data) return; - let result = this._encodeValue(data, reporter, parent); - if (result !== void 0 && !this._skipDefault(result, reporter, parent)) return result; - }; - Node.prototype._encodeValue = function (data, reporter, parent) { - let state = this._baseState; - if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); - let result = null; - if (((this.reporter = reporter), state.optional && data === void 0)) - if (state.default !== null) data = state.default; - else return; - let content = null, - primitive = !1; - if (state.any) result = this._createEncoderBuffer(data); - else if (state.choice) result = this._encodeChoice(data, reporter); - else if (state.contains) - (content = this._getUse(state.contains, parent)._encode(data, reporter)), (primitive = !0); - else if (state.children) - (content = state.children - .map(function (child) { - if (child._baseState.tag === "null_") return child._encode(null, reporter, data); - if (child._baseState.key === null) return reporter.error("Child should have a key"); - let prevKey = reporter.enterKey(child._baseState.key); - if (typeof data != "object") return reporter.error("Child expected, but input is not object"); - let res = child._encode(data[child._baseState.key], reporter, data); - return reporter.leaveKey(prevKey), res; - }, this) - .filter(function (child) { - return child; - })), - (content = this._createEncoderBuffer(content)); - else if (state.tag === "seqof" || state.tag === "setof") { - if (!(state.args && state.args.length === 1)) return reporter.error("Too many args for : " + state.tag); - if (!Array.isArray(data)) return reporter.error("seqof/setof, but data is not Array"); - let child = this.clone(); - (child._baseState.implicit = null), - (content = this._createEncoderBuffer( - data.map(function (item) { - let state2 = this._baseState; - return this._getUse(state2.args[0], data)._encode(item, reporter); - }, child), - )); - } else - state.use !== null - ? (result = this._getUse(state.use, parent)._encode(data, reporter)) - : ((content = this._encodePrimitive(state.tag, data)), (primitive = !0)); - if (!state.any && state.choice === null) { - let tag = state.implicit !== null ? state.implicit : state.tag, - cls = state.implicit === null ? "universal" : "context"; - tag === null - ? state.use === null && reporter.error("Tag could be omitted only for .use()") - : state.use === null && (result = this._encodeComposite(tag, primitive, cls, content)); - } - return state.explicit !== null && (result = this._encodeComposite(state.explicit, !1, "context", result)), result; - }; - Node.prototype._encodeChoice = function (data, reporter) { - let state = this._baseState, - node = state.choice[data.type]; - return ( - node || assert(!1, data.type + " not found in " + JSON.stringify(Object.keys(state.choice))), - node._encode(data.value, reporter) - ); - }; - Node.prototype._encodePrimitive = function (tag, data) { - let state = this._baseState; - if (/str$/.test(tag)) return this._encodeStr(data, tag); - if (tag === "objid" && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); - if (tag === "objid") return this._encodeObjid(data, null, null); - if (tag === "gentime" || tag === "utctime") return this._encodeTime(data, tag); - if (tag === "null_") return this._encodeNull(); - if (tag === "int" || tag === "enum") return this._encodeInt(data, state.args && state.reverseArgs[0]); - if (tag === "bool") return this._encodeBool(data); - if (tag === "objDesc") return this._encodeStr(data, tag); - throw new Error("Unsupported tag: " + tag); - }; - Node.prototype._isNumstr = function (str) { - return /^[0-9 ]*$/.test(str); - }; - Node.prototype._isPrintstr = function (str) { - return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); - }; - }, -}); - -// node_modules/asn1.js/lib/asn1/constants/der.js -var require_der = __commonJS({ - "node_modules/asn1.js/lib/asn1/constants/der.js"(exports) { - "use strict"; - function reverse(map) { - let res = {}; - return ( - Object.keys(map).forEach(function (key) { - (key | 0) == key && (key = key | 0); - let value = map[key]; - res[value] = key; - }), - res - ); - } - exports.tagClass = { - 0: "universal", - 1: "application", - 2: "context", - 3: "private", - }; - exports.tagClassByName = reverse(exports.tagClass); - exports.tag = { - 0: "end", - 1: "bool", - 2: "int", - 3: "bitstr", - 4: "octstr", - 5: "null_", - 6: "objid", - 7: "objDesc", - 8: "external", - 9: "real", - 10: "enum", - 11: "embed", - 12: "utf8str", - 13: "relativeOid", - 16: "seq", - 17: "set", - 18: "numstr", - 19: "printstr", - 20: "t61str", - 21: "videostr", - 22: "ia5str", - 23: "utctime", - 24: "gentime", - 25: "graphstr", - 26: "iso646str", - 27: "genstr", - 28: "unistr", - 29: "charstr", - 30: "bmpstr", - }; - exports.tagByName = reverse(exports.tag); - }, -}); - -// node_modules/asn1.js/lib/asn1/encoders/der.js -var require_der2 = __commonJS({ - "node_modules/asn1.js/lib/asn1/encoders/der.js"(exports, module) { - "use strict"; - var inherits = require_inherits_browser(), - Buffer2 = require_safer().Buffer, - Node = require_node(), - der = require_der(); - function DEREncoder(entity) { - (this.enc = "der"), - (this.name = entity.name), - (this.entity = entity), - (this.tree = new DERNode()), - this.tree._init(entity.body); - } - module.exports = DEREncoder; - DEREncoder.prototype.encode = function (data, reporter) { - return this.tree._encode(data, reporter).join(); - }; - function DERNode(parent) { - Node.call(this, "der", parent); - } - inherits(DERNode, Node); - DERNode.prototype._encodeComposite = function (tag, primitive, cls, content) { - let encodedTag = encodeTag(tag, primitive, cls, this.reporter); - if (content.length < 128) { - let header2 = Buffer2.alloc(2); - return (header2[0] = encodedTag), (header2[1] = content.length), this._createEncoderBuffer([header2, content]); - } - let lenOctets = 1; - for (let i = content.length; i >= 256; i >>= 8) lenOctets++; - let header = Buffer2.alloc(1 + 1 + lenOctets); - (header[0] = encodedTag), (header[1] = 128 | lenOctets); - for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 255; - return this._createEncoderBuffer([header, content]); - }; - DERNode.prototype._encodeStr = function (str, tag) { - if (tag === "bitstr") return this._createEncoderBuffer([str.unused | 0, str.data]); - if (tag === "bmpstr") { - let buf = Buffer2.alloc(str.length * 2); - for (let i = 0; i < str.length; i++) buf.writeUInt16BE(str.charCodeAt(i), i * 2); - return this._createEncoderBuffer(buf); - } else - return tag === "numstr" - ? this._isNumstr(str) - ? this._createEncoderBuffer(str) - : this.reporter.error("Encoding of string type: numstr supports only digits and space") - : tag === "printstr" - ? this._isPrintstr(str) - ? this._createEncoderBuffer(str) - : this.reporter.error( - "Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark", - ) - : /str$/.test(tag) - ? this._createEncoderBuffer(str) - : tag === "objDesc" - ? this._createEncoderBuffer(str) - : this.reporter.error("Encoding of string type: " + tag + " unsupported"); - }; - DERNode.prototype._encodeObjid = function (id, values, relative) { - if (typeof id == "string") { - if (!values) return this.reporter.error("string objid given, but no values map found"); - if (!values.hasOwnProperty(id)) return this.reporter.error("objid not found in values map"); - id = values[id].split(/[\s.]+/g); - for (let i = 0; i < id.length; i++) id[i] |= 0; - } else if (Array.isArray(id)) { - id = id.slice(); - for (let i = 0; i < id.length; i++) id[i] |= 0; - } - if (!Array.isArray(id)) - return this.reporter.error("objid() should be either array or string, got: " + JSON.stringify(id)); - if (!relative) { - if (id[1] >= 40) return this.reporter.error("Second objid identifier OOB"); - id.splice(0, 2, id[0] * 40 + id[1]); - } - let size = 0; - for (let i = 0; i < id.length; i++) { - let ident = id[i]; - for (size++; ident >= 128; ident >>= 7) size++; - } - let objid = Buffer2.alloc(size), - offset = objid.length - 1; - for (let i = id.length - 1; i >= 0; i--) { - let ident = id[i]; - for (objid[offset--] = ident & 127; (ident >>= 7) > 0; ) objid[offset--] = 128 | (ident & 127); - } - return this._createEncoderBuffer(objid); - }; - function two(num) { - return num < 10 ? "0" + num : num; - } - DERNode.prototype._encodeTime = function (time, tag) { - let str, - date = new Date(time); - return ( - tag === "gentime" - ? (str = [ - two(date.getUTCFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - "Z", - ].join("")) - : tag === "utctime" - ? (str = [ - two(date.getUTCFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - "Z", - ].join("")) - : this.reporter.error("Encoding " + tag + " time is not supported yet"), - this._encodeStr(str, "octstr") - ); - }; - DERNode.prototype._encodeNull = function () { - return this._createEncoderBuffer(""); - }; - DERNode.prototype._encodeInt = function (num, values) { - if (typeof num == "string") { - if (!values) return this.reporter.error("String int or enum given, but no values map"); - if (!values.hasOwnProperty(num)) - return this.reporter.error("Values map doesn't contain: " + JSON.stringify(num)); - num = values[num]; - } - if (typeof num != "number" && !Buffer2.isBuffer(num)) { - let numArray = num.toArray(); - !num.sign && numArray[0] & 128 && numArray.unshift(0), (num = Buffer2.from(numArray)); - } - if (Buffer2.isBuffer(num)) { - let size2 = num.length; - num.length === 0 && size2++; - let out2 = Buffer2.alloc(size2); - return num.copy(out2), num.length === 0 && (out2[0] = 0), this._createEncoderBuffer(out2); - } - if (num < 128) return this._createEncoderBuffer(num); - if (num < 256) return this._createEncoderBuffer([0, num]); - let size = 1; - for (let i = num; i >= 256; i >>= 8) size++; - let out = new Array(size); - for (let i = out.length - 1; i >= 0; i--) (out[i] = num & 255), (num >>= 8); - return out[0] & 128 && out.unshift(0), this._createEncoderBuffer(Buffer2.from(out)); - }; - DERNode.prototype._encodeBool = function (value) { - return this._createEncoderBuffer(value ? 255 : 0); - }; - DERNode.prototype._use = function (entity, obj) { - return typeof entity == "function" && (entity = entity(obj)), entity._getEncoder("der").tree; - }; - DERNode.prototype._skipDefault = function (dataBuffer, reporter, parent) { - let state = this._baseState, - i; - if (state.default === null) return !1; - let data = dataBuffer.join(); - if ( - (state.defaultBuffer === void 0 && - (state.defaultBuffer = this._encodeValue(state.default, reporter, parent).join()), - data.length !== state.defaultBuffer.length) - ) - return !1; - for (i = 0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return !1; - return !0; - }; - function encodeTag(tag, primitive, cls, reporter) { - let res; - if ((tag === "seqof" ? (tag = "seq") : tag === "setof" && (tag = "set"), der.tagByName.hasOwnProperty(tag))) - res = der.tagByName[tag]; - else if (typeof tag == "number" && (tag | 0) === tag) res = tag; - else return reporter.error("Unknown tag: " + tag); - return res >= 31 - ? reporter.error("Multi-octet tag encoding unsupported") - : (primitive || (res |= 32), (res |= der.tagClassByName[cls || "universal"] << 6), res); - } - }, -}); - -// node_modules/asn1.js/lib/asn1/encoders/pem.js -var require_pem = __commonJS({ - "node_modules/asn1.js/lib/asn1/encoders/pem.js"(exports, module) { - "use strict"; - var inherits = require_inherits_browser(), - DEREncoder = require_der2(); - function PEMEncoder(entity) { - DEREncoder.call(this, entity), (this.enc = "pem"); - } - inherits(PEMEncoder, DEREncoder); - module.exports = PEMEncoder; - PEMEncoder.prototype.encode = function (data, options) { - let p = DEREncoder.prototype.encode.call(this, data).toString("base64"), - out = ["-----BEGIN " + options.label + "-----"]; - for (let i = 0; i < p.length; i += 64) out.push(p.slice(i, i + 64)); - return ( - out.push("-----END " + options.label + "-----"), - out.join(` -`) - ); - }; - }, -}); - -// node_modules/asn1.js/lib/asn1/encoders/index.js -var require_encoders = __commonJS({ - "node_modules/asn1.js/lib/asn1/encoders/index.js"(exports) { - "use strict"; - var encoders = exports; - encoders.der = require_der2(); - encoders.pem = require_pem(); - }, -}); - -// node_modules/asn1.js/lib/asn1/decoders/der.js -var require_der3 = __commonJS({ - "node_modules/asn1.js/lib/asn1/decoders/der.js"(exports, module) { - "use strict"; - var inherits = require_inherits_browser(), - bignum = require_bn5(), - DecoderBuffer = require_buffer().DecoderBuffer, - Node = require_node(), - der = require_der(); - function DERDecoder(entity) { - (this.enc = "der"), - (this.name = entity.name), - (this.entity = entity), - (this.tree = new DERNode()), - this.tree._init(entity.body); - } - module.exports = DERDecoder; - DERDecoder.prototype.decode = function (data, options) { - return ( - DecoderBuffer.isDecoderBuffer(data) || (data = new DecoderBuffer(data, options)), - this.tree._decode(data, options) - ); - }; - function DERNode(parent) { - Node.call(this, "der", parent); - } - inherits(DERNode, Node); - DERNode.prototype._peekTag = function (buffer, tag, any) { - if (buffer.isEmpty()) return !1; - let state = buffer.save(), - decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); - return buffer.isError(decodedTag) - ? decodedTag - : (buffer.restore(state), - decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + "of" === tag || any); - }; - DERNode.prototype._decodeTag = function (buffer, tag, any) { - let decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); - if (buffer.isError(decodedTag)) return decodedTag; - let len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); - if (buffer.isError(len)) return len; - if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + "of" !== tag) - return buffer.error('Failed to match tag: "' + tag + '"'); - if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); - let state = buffer.save(), - res = this._skipUntilEnd(buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); - return buffer.isError(res) - ? res - : ((len = buffer.offset - state.offset), - buffer.restore(state), - buffer.skip(len, 'Failed to match body of: "' + tag + '"')); - }; - DERNode.prototype._skipUntilEnd = function (buffer, fail) { - for (;;) { - let tag = derDecodeTag(buffer, fail); - if (buffer.isError(tag)) return tag; - let len = derDecodeLen(buffer, tag.primitive, fail); - if (buffer.isError(len)) return len; - let res; - if ( - (tag.primitive || len !== null ? (res = buffer.skip(len)) : (res = this._skipUntilEnd(buffer, fail)), - buffer.isError(res)) - ) - return res; - if (tag.tagStr === "end") break; - } - }; - DERNode.prototype._decodeList = function (buffer, tag, decoder, options) { - let result = []; - for (; !buffer.isEmpty(); ) { - let possibleEnd = this._peekTag(buffer, "end"); - if (buffer.isError(possibleEnd)) return possibleEnd; - let res = decoder.decode(buffer, "der", options); - if (buffer.isError(res) && possibleEnd) break; - result.push(res); - } - return result; - }; - DERNode.prototype._decodeStr = function (buffer, tag) { - if (tag === "bitstr") { - let unused = buffer.readUInt8(); - return buffer.isError(unused) ? unused : { unused, data: buffer.raw() }; - } else if (tag === "bmpstr") { - let raw = buffer.raw(); - if (raw.length % 2 === 1) return buffer.error("Decoding of string type: bmpstr length mismatch"); - let str = ""; - for (let i = 0; i < raw.length / 2; i++) str += String.fromCharCode(raw.readUInt16BE(i * 2)); - return str; - } else if (tag === "numstr") { - let numstr = buffer.raw().toString("ascii"); - return this._isNumstr(numstr) ? numstr : buffer.error("Decoding of string type: numstr unsupported characters"); - } else { - if (tag === "octstr") return buffer.raw(); - if (tag === "objDesc") return buffer.raw(); - if (tag === "printstr") { - let printstr = buffer.raw().toString("ascii"); - return this._isPrintstr(printstr) - ? printstr - : buffer.error("Decoding of string type: printstr unsupported characters"); - } else - return /str$/.test(tag) - ? buffer.raw().toString() - : buffer.error("Decoding of string type: " + tag + " unsupported"); - } - }; - DERNode.prototype._decodeObjid = function (buffer, values, relative) { - let result, - identifiers = [], - ident = 0, - subident = 0; - for (; !buffer.isEmpty(); ) - (subident = buffer.readUInt8()), - (ident <<= 7), - (ident |= subident & 127), - (subident & 128) === 0 && (identifiers.push(ident), (ident = 0)); - subident & 128 && identifiers.push(ident); - let first = (identifiers[0] / 40) | 0, - second = identifiers[0] % 40; - if ((relative ? (result = identifiers) : (result = [first, second].concat(identifiers.slice(1))), values)) { - let tmp = values[result.join(" ")]; - tmp === void 0 && (tmp = values[result.join(".")]), tmp !== void 0 && (result = tmp); - } - return result; - }; - DERNode.prototype._decodeTime = function (buffer, tag) { - let str = buffer.raw().toString(), - year, - mon, - day, - hour, - min, - sec; - if (tag === "gentime") - (year = str.slice(0, 4) | 0), - (mon = str.slice(4, 6) | 0), - (day = str.slice(6, 8) | 0), - (hour = str.slice(8, 10) | 0), - (min = str.slice(10, 12) | 0), - (sec = str.slice(12, 14) | 0); - else if (tag === "utctime") - (year = str.slice(0, 2) | 0), - (mon = str.slice(2, 4) | 0), - (day = str.slice(4, 6) | 0), - (hour = str.slice(6, 8) | 0), - (min = str.slice(8, 10) | 0), - (sec = str.slice(10, 12) | 0), - year < 70 ? (year = 2e3 + year) : (year = 1900 + year); - else return buffer.error("Decoding " + tag + " time is not supported yet"); - return Date.UTC(year, mon - 1, day, hour, min, sec, 0); - }; - DERNode.prototype._decodeNull = function () { - return null; - }; - DERNode.prototype._decodeBool = function (buffer) { - let res = buffer.readUInt8(); - return buffer.isError(res) ? res : res !== 0; - }; - DERNode.prototype._decodeInt = function (buffer, values) { - let raw = buffer.raw(), - res = new bignum(raw); - return values && (res = values[res.toString(10)] || res), res; - }; - DERNode.prototype._use = function (entity, obj) { - return typeof entity == "function" && (entity = entity(obj)), entity._getDecoder("der").tree; - }; - function derDecodeTag(buf, fail) { - let tag = buf.readUInt8(fail); - if (buf.isError(tag)) return tag; - let cls = der.tagClass[tag >> 6], - primitive = (tag & 32) === 0; - if ((tag & 31) === 31) { - let oct = tag; - for (tag = 0; (oct & 128) === 128; ) { - if (((oct = buf.readUInt8(fail)), buf.isError(oct))) return oct; - (tag <<= 7), (tag |= oct & 127); - } - } else tag &= 31; - let tagStr = der.tag[tag]; - return { - cls, - primitive, - tag, - tagStr, - }; - } - function derDecodeLen(buf, primitive, fail) { - let len = buf.readUInt8(fail); - if (buf.isError(len)) return len; - if (!primitive && len === 128) return null; - if ((len & 128) === 0) return len; - let num = len & 127; - if (num > 4) return buf.error("length octect is too long"); - len = 0; - for (let i = 0; i < num; i++) { - len <<= 8; - let j = buf.readUInt8(fail); - if (buf.isError(j)) return j; - len |= j; - } - return len; - } - }, -}); - -// node_modules/asn1.js/lib/asn1/decoders/pem.js -var require_pem2 = __commonJS({ - "node_modules/asn1.js/lib/asn1/decoders/pem.js"(exports, module) { - "use strict"; - var inherits = require_inherits_browser(), - Buffer2 = require_safer().Buffer, - DERDecoder = require_der3(); - function PEMDecoder(entity) { - DERDecoder.call(this, entity), (this.enc = "pem"); - } - inherits(PEMDecoder, DERDecoder); - module.exports = PEMDecoder; - PEMDecoder.prototype.decode = function (data, options) { - let lines = data.toString().split(/[\r\n]+/g), - label = options.label.toUpperCase(), - re = /^-----(BEGIN|END) ([^-]+)-----$/, - start = -1, - end = -1; - for (let i = 0; i < lines.length; i++) { - let match = lines[i].match(re); - if (match !== null && match[2] === label) - if (start === -1) { - if (match[1] !== "BEGIN") break; - start = i; - } else { - if (match[1] !== "END") break; - end = i; - break; - } - } - if (start === -1 || end === -1) throw new Error("PEM section not found for: " + label); - let base64 = lines.slice(start + 1, end).join(""); - base64.replace(/[^a-z0-9+/=]+/gi, ""); - let input = Buffer2.from(base64, "base64"); - return DERDecoder.prototype.decode.call(this, input, options); - }; - }, -}); - -// node_modules/asn1.js/lib/asn1/decoders/index.js -var require_decoders = __commonJS({ - "node_modules/asn1.js/lib/asn1/decoders/index.js"(exports) { - "use strict"; - var decoders = exports; - decoders.der = require_der3(); - decoders.pem = require_pem2(); - }, -}); - -// node_modules/asn1.js/lib/asn1/api.js -var require_api = __commonJS({ - "node_modules/asn1.js/lib/asn1/api.js"(exports) { - "use strict"; - var encoders = require_encoders(), - decoders = require_decoders(), - inherits = require_inherits_browser(), - api = exports; - api.define = function (name, body) { - return new Entity(name, body); - }; - function Entity(name, body) { - (this.name = name), (this.body = body), (this.decoders = {}), (this.encoders = {}); - } - Entity.prototype._createNamed = function (Base) { - let name = this.name; - function Generated(entity) { - this._initNamed(entity, name); - } - return ( - inherits(Generated, Base), - (Generated.prototype._initNamed = function (entity, name2) { - Base.call(this, entity, name2); - }), - new Generated(this) - ); - }; - Entity.prototype._getDecoder = function (enc) { - return ( - (enc = enc || "der"), - this.decoders.hasOwnProperty(enc) || (this.decoders[enc] = this._createNamed(decoders[enc])), - this.decoders[enc] - ); - }; - Entity.prototype.decode = function (data, enc, options) { - return this._getDecoder(enc).decode(data, options); - }; - Entity.prototype._getEncoder = function (enc) { - return ( - (enc = enc || "der"), - this.encoders.hasOwnProperty(enc) || (this.encoders[enc] = this._createNamed(encoders[enc])), - this.encoders[enc] - ); - }; - Entity.prototype.encode = function (data, enc, reporter) { - return this._getEncoder(enc).encode(data, reporter); - }; - }, -}); - -// node_modules/asn1.js/lib/asn1/base/index.js -var require_base2 = __commonJS({ - "node_modules/asn1.js/lib/asn1/base/index.js"(exports) { - "use strict"; - var base = exports; - base.Reporter = require_reporter().Reporter; - base.DecoderBuffer = require_buffer().DecoderBuffer; - base.EncoderBuffer = require_buffer().EncoderBuffer; - base.Node = require_node(); - }, -}); - -// node_modules/asn1.js/lib/asn1/constants/index.js -var require_constants = __commonJS({ - "node_modules/asn1.js/lib/asn1/constants/index.js"(exports) { - "use strict"; - var constants = exports; - constants._reverse = function (map) { - let res = {}; - return ( - Object.keys(map).forEach(function (key) { - (key | 0) == key && (key = key | 0); - let value = map[key]; - res[value] = key; - }), - res - ); - }; - constants.der = require_der(); - }, -}); - -// node_modules/asn1.js/lib/asn1.js -var require_asn1 = __commonJS({ - "node_modules/asn1.js/lib/asn1.js"(exports) { - "use strict"; - var asn1 = exports; - asn1.bignum = require_bn5(); - asn1.define = require_api().define; - asn1.base = require_base2(); - asn1.constants = require_constants(); - asn1.decoders = require_decoders(); - asn1.encoders = require_encoders(); - }, -}); - -// node_modules/parse-asn1/certificate.js -var require_certificate = __commonJS({ - "node_modules/parse-asn1/certificate.js"(exports, module) { - "use strict"; - var asn = require_asn1(), - Time = asn.define("Time", function () { - this.choice({ - utcTime: this.utctime(), - generalTime: this.gentime(), - }); - }), - AttributeTypeValue = asn.define("AttributeTypeValue", function () { - this.seq().obj(this.key("type").objid(), this.key("value").any()); - }), - AlgorithmIdentifier = asn.define("AlgorithmIdentifier", function () { - this.seq().obj( - this.key("algorithm").objid(), - this.key("parameters").optional(), - this.key("curve").objid().optional(), - ); - }), - SubjectPublicKeyInfo = asn.define("SubjectPublicKeyInfo", function () { - this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier), this.key("subjectPublicKey").bitstr()); - }), - RelativeDistinguishedName = asn.define("RelativeDistinguishedName", function () { - this.setof(AttributeTypeValue); - }), - RDNSequence = asn.define("RDNSequence", function () { - this.seqof(RelativeDistinguishedName); - }), - Name = asn.define("Name", function () { - this.choice({ - rdnSequence: this.use(RDNSequence), - }); - }), - Validity = asn.define("Validity", function () { - this.seq().obj(this.key("notBefore").use(Time), this.key("notAfter").use(Time)); - }), - Extension = asn.define("Extension", function () { - this.seq().obj(this.key("extnID").objid(), this.key("critical").bool().def(!1), this.key("extnValue").octstr()); - }), - TBSCertificate = asn.define("TBSCertificate", function () { - this.seq().obj( - this.key("version").explicit(0).int().optional(), - this.key("serialNumber").int(), - this.key("signature").use(AlgorithmIdentifier), - this.key("issuer").use(Name), - this.key("validity").use(Validity), - this.key("subject").use(Name), - this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo), - this.key("issuerUniqueID").implicit(1).bitstr().optional(), - this.key("subjectUniqueID").implicit(2).bitstr().optional(), - this.key("extensions").explicit(3).seqof(Extension).optional(), - ); - }), - X509Certificate = asn.define("X509Certificate", function () { - this.seq().obj( - this.key("tbsCertificate").use(TBSCertificate), - this.key("signatureAlgorithm").use(AlgorithmIdentifier), - this.key("signatureValue").bitstr(), - ); - }); - module.exports = X509Certificate; - }, -}); - -// node_modules/parse-asn1/asn1.js -var require_asn12 = __commonJS({ - "node_modules/parse-asn1/asn1.js"(exports) { - "use strict"; - var asn1 = require_asn1(); - exports.certificate = require_certificate(); - var RSAPrivateKey = asn1.define("RSAPrivateKey", function () { - this.seq().obj( - this.key("version").int(), - this.key("modulus").int(), - this.key("publicExponent").int(), - this.key("privateExponent").int(), - this.key("prime1").int(), - this.key("prime2").int(), - this.key("exponent1").int(), - this.key("exponent2").int(), - this.key("coefficient").int(), - ); - }); - exports.RSAPrivateKey = RSAPrivateKey; - var RSAPublicKey = asn1.define("RSAPublicKey", function () { - this.seq().obj(this.key("modulus").int(), this.key("publicExponent").int()); - }); - exports.RSAPublicKey = RSAPublicKey; - var PublicKey = asn1.define("SubjectPublicKeyInfo", function () { - this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier), this.key("subjectPublicKey").bitstr()); - }); - exports.PublicKey = PublicKey; - var AlgorithmIdentifier = asn1.define("AlgorithmIdentifier", function () { - this.seq().obj( - this.key("algorithm").objid(), - this.key("none").null_().optional(), - this.key("curve").objid().optional(), - this.key("params").seq().obj(this.key("p").int(), this.key("q").int(), this.key("g").int()).optional(), - ); - }), - PrivateKeyInfo = asn1.define("PrivateKeyInfo", function () { - this.seq().obj( - this.key("version").int(), - this.key("algorithm").use(AlgorithmIdentifier), - this.key("subjectPrivateKey").octstr(), - ); - }); - exports.PrivateKey = PrivateKeyInfo; - var EncryptedPrivateKeyInfo = asn1.define("EncryptedPrivateKeyInfo", function () { - this.seq().obj( - this.key("algorithm") - .seq() - .obj( - this.key("id").objid(), - this.key("decrypt") - .seq() - .obj( - this.key("kde") - .seq() - .obj( - this.key("id").objid(), - this.key("kdeparams").seq().obj(this.key("salt").octstr(), this.key("iters").int()), - ), - this.key("cipher").seq().obj(this.key("algo").objid(), this.key("iv").octstr()), - ), - ), - this.key("subjectPrivateKey").octstr(), - ); - }); - exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo; - var DSAPrivateKey = asn1.define("DSAPrivateKey", function () { - this.seq().obj( - this.key("version").int(), - this.key("p").int(), - this.key("q").int(), - this.key("g").int(), - this.key("pub_key").int(), - this.key("priv_key").int(), - ); - }); - exports.DSAPrivateKey = DSAPrivateKey; - exports.DSAparam = asn1.define("DSAparam", function () { - this.int(); - }); - var ECPrivateKey = asn1.define("ECPrivateKey", function () { - this.seq().obj( - this.key("version").int(), - this.key("privateKey").octstr(), - this.key("parameters").optional().explicit(0).use(ECParameters), - this.key("publicKey").optional().explicit(1).bitstr(), - ); - }); - exports.ECPrivateKey = ECPrivateKey; - var ECParameters = asn1.define("ECParameters", function () { - this.choice({ - namedCurve: this.objid(), - }); - }); - exports.signature = asn1.define("signature", function () { - this.seq().obj(this.key("r").int(), this.key("s").int()); - }); - }, -}); - -// node_modules/parse-asn1/aesid.json -var require_aesid = __commonJS({ - "node_modules/parse-asn1/aesid.json"(exports, module) { - module.exports = { - "2.16.840.1.101.3.4.1.1": "aes-128-ecb", - "2.16.840.1.101.3.4.1.2": "aes-128-cbc", - "2.16.840.1.101.3.4.1.3": "aes-128-ofb", - "2.16.840.1.101.3.4.1.4": "aes-128-cfb", - "2.16.840.1.101.3.4.1.21": "aes-192-ecb", - "2.16.840.1.101.3.4.1.22": "aes-192-cbc", - "2.16.840.1.101.3.4.1.23": "aes-192-ofb", - "2.16.840.1.101.3.4.1.24": "aes-192-cfb", - "2.16.840.1.101.3.4.1.41": "aes-256-ecb", - "2.16.840.1.101.3.4.1.42": "aes-256-cbc", - "2.16.840.1.101.3.4.1.43": "aes-256-ofb", - "2.16.840.1.101.3.4.1.44": "aes-256-cfb", - }; - }, -}); - -// node_modules/parse-asn1/fixProc.js -var require_fixProc = __commonJS({ - "node_modules/parse-asn1/fixProc.js"(exports, module) { - var findProc = - /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m, - startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m, - fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m, - evp = require_evp_bytestokey(), - ciphers = require_browser5(), - Buffer2 = require_safe_buffer().Buffer; - module.exports = function (okey, password) { - var key = okey.toString(), - match = key.match(findProc), - decrypted; - if (match) { - var suite = "aes" + match[1], - iv = Buffer2.from(match[2], "hex"), - cipherText = Buffer2.from(match[3].replace(/[\r\n]/g, ""), "base64"), - cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key, - out = [], - cipher = ciphers.createDecipheriv(suite, cipherKey, iv); - out.push(cipher.update(cipherText)), out.push(cipher.final()), (decrypted = Buffer2.concat(out)); - } else { - var match2 = key.match(fullRegex); - decrypted = Buffer2.from(match2[2].replace(/[\r\n]/g, ""), "base64"); - } - var tag = key.match(startRegex)[1]; - return { - tag, - data: decrypted, - }; - }; - }, -}); - -// node_modules/parse-asn1/index.js -var require_parse_asn1 = __commonJS({ - "node_modules/parse-asn1/index.js"(exports, module) { - var asn1 = require_asn12(), - aesid = require_aesid(), - fixProc = require_fixProc(), - ciphers = require_browser5(), - compat = require_browser4(), - Buffer2 = require_safe_buffer().Buffer; - module.exports = parseKeys; - function parseKeys(buffer) { - var password; - typeof buffer == "object" && !Buffer2.isBuffer(buffer) && ((password = buffer.passphrase), (buffer = buffer.key)), - typeof buffer == "string" && (buffer = Buffer2.from(buffer)); - var stripped = fixProc(buffer, password), - type = stripped.tag, - data = stripped.data, - subtype, - ndata; - switch (type) { - case "CERTIFICATE": - ndata = asn1.certificate.decode(data, "der").tbsCertificate.subjectPublicKeyInfo; - case "PUBLIC KEY": - switch ( - (ndata || (ndata = asn1.PublicKey.decode(data, "der")), - (subtype = ndata.algorithm.algorithm.join(".")), - subtype) - ) { - case "1.2.840.113549.1.1.1": - return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, "der"); - case "1.2.840.10045.2.1": - return ( - (ndata.subjectPrivateKey = ndata.subjectPublicKey), - { - type: "ec", - data: ndata, - } - ); - case "1.2.840.10040.4.1": - return ( - (ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, "der")), - { - type: "dsa", - data: ndata.algorithm.params, - } - ); - default: - throw new Error("unknown key id " + subtype); - } - case "ENCRYPTED PRIVATE KEY": - (data = asn1.EncryptedPrivateKey.decode(data, "der")), (data = decrypt(data, password)); - case "PRIVATE KEY": - switch ( - ((ndata = asn1.PrivateKey.decode(data, "der")), (subtype = ndata.algorithm.algorithm.join(".")), subtype) - ) { - case "1.2.840.113549.1.1.1": - return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, "der"); - case "1.2.840.10045.2.1": - return { - curve: ndata.algorithm.curve, - privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, "der").privateKey, - }; - case "1.2.840.10040.4.1": - return ( - (ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, "der")), - { - type: "dsa", - params: ndata.algorithm.params, - } - ); - default: - throw new Error("unknown key id " + subtype); - } - case "RSA PUBLIC KEY": - return asn1.RSAPublicKey.decode(data, "der"); - case "RSA PRIVATE KEY": - return asn1.RSAPrivateKey.decode(data, "der"); - case "DSA PRIVATE KEY": - return { - type: "dsa", - params: asn1.DSAPrivateKey.decode(data, "der"), - }; - case "EC PRIVATE KEY": - return ( - (data = asn1.ECPrivateKey.decode(data, "der")), - { - curve: data.parameters.value, - privateKey: data.privateKey, - } - ); - default: - throw new Error("unknown key type " + type); - } - } - parseKeys.signature = asn1.signature; - function decrypt(data, password) { - var salt = data.algorithm.decrypt.kde.kdeparams.salt, - iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10), - algo = aesid[data.algorithm.decrypt.cipher.algo.join(".")], - iv = data.algorithm.decrypt.cipher.iv, - cipherText = data.subjectPrivateKey, - keylen = parseInt(algo.split("-")[1], 10) / 8, - key = compat.pbkdf2Sync(password, salt, iters, keylen, "sha1"), - cipher = ciphers.createDecipheriv(algo, key, iv), - out = []; - return out.push(cipher.update(cipherText)), out.push(cipher.final()), Buffer2.concat(out); - } - }, -}); - -// node_modules/browserify-sign/browser/curves.json -var require_curves2 = __commonJS({ - "node_modules/browserify-sign/browser/curves.json"(exports, module) { - module.exports = { - "1.3.132.0.10": "secp256k1", - "1.3.132.0.33": "p224", - "1.2.840.10045.3.1.1": "p192", - "1.2.840.10045.3.1.7": "p256", - "1.3.132.0.34": "p384", - "1.3.132.0.35": "p521", - }; - }, -}); - -// node_modules/browserify-sign/browser/sign.js -var require_sign = __commonJS({ - "node_modules/browserify-sign/browser/sign.js"(exports, module) { - var Buffer2 = require_safe_buffer().Buffer, - createHmac = require_browser3(), - crt = require_browserify_rsa(), - EC = require_elliptic().ec, - BN = require_bn3(), - parseKeys = require_parse_asn1(), - curves = require_curves2(); - function sign(hash, key, hashType, signType, tag) { - var priv = parseKeys(key); - if (priv.curve) { - if (signType !== "ecdsa" && signType !== "ecdsa/rsa") throw new Error("wrong private key type"); - return ecSign(hash, priv); - } else if (priv.type === "dsa") { - if (signType !== "dsa") throw new Error("wrong private key type"); - return dsaSign(hash, priv, hashType); - } else if (signType !== "rsa" && signType !== "ecdsa/rsa") throw new Error("wrong private key type"); - hash = Buffer2.concat([tag, hash]); - for (var len = priv.modulus.byteLength(), pad = [0, 1]; hash.length + pad.length + 1 < len; ) pad.push(255); - pad.push(0); - for (var i = -1; ++i < hash.length; ) pad.push(hash[i]); - var out = crt(pad, priv); - return out; - } - function ecSign(hash, priv) { - var curveId = curves[priv.curve.join(".")]; - if (!curveId) throw new Error("unknown curve " + priv.curve.join(".")); - var curve = new EC(curveId), - key = curve.keyFromPrivate(priv.privateKey), - out = key.sign(hash); - return Buffer2.from(out.toDER()); - } - function dsaSign(hash, priv, algo) { - for ( - var x = priv.params.priv_key, - p = priv.params.p, - q = priv.params.q, - g = priv.params.g, - r = new BN(0), - k, - H = bits2int(hash, q).mod(q), - s = !1, - kv = getKey(x, q, hash, algo); - s === !1; - - ) - (k = makeKey(q, kv, algo)), - (r = makeR(g, k, p, q)), - (s = k - .invm(q) - .imul(H.add(x.mul(r))) - .mod(q)), - s.cmpn(0) === 0 && ((s = !1), (r = new BN(0))); - return toDER(r, s); - } - function toDER(r, s) { - (r = r.toArray()), (s = s.toArray()), r[0] & 128 && (r = [0].concat(r)), s[0] & 128 && (s = [0].concat(s)); - var total = r.length + s.length + 4, - res = [48, total, 2, r.length]; - return (res = res.concat(r, [2, s.length], s)), Buffer2.from(res); - } - function getKey(x, q, hash, algo) { - if (((x = Buffer2.from(x.toArray())), x.length < q.byteLength())) { - var zeros = Buffer2.alloc(q.byteLength() - x.length); - x = Buffer2.concat([zeros, x]); - } - var hlen = hash.length, - hbits = bits2octets(hash, q), - v = Buffer2.alloc(hlen); - v.fill(1); - var k = Buffer2.alloc(hlen); - return ( - (k = createHmac(algo, k) - .update(v) - .update(Buffer2.from([0])) - .update(x) - .update(hbits) - .digest()), - (v = createHmac(algo, k).update(v).digest()), - (k = createHmac(algo, k) - .update(v) - .update(Buffer2.from([1])) - .update(x) - .update(hbits) - .digest()), - (v = createHmac(algo, k).update(v).digest()), - { k, v } - ); - } - function bits2int(obits, q) { - var bits = new BN(obits), - shift = (obits.length << 3) - q.bitLength(); - return shift > 0 && bits.ishrn(shift), bits; - } - function bits2octets(bits, q) { - (bits = bits2int(bits, q)), (bits = bits.mod(q)); - var out = Buffer2.from(bits.toArray()); - if (out.length < q.byteLength()) { - var zeros = Buffer2.alloc(q.byteLength() - out.length); - out = Buffer2.concat([zeros, out]); - } - return out; - } - function makeKey(q, kv, algo) { - var t, k; - do { - for (t = Buffer2.alloc(0); t.length * 8 < q.bitLength(); ) - (kv.v = createHmac(algo, kv.k).update(kv.v).digest()), (t = Buffer2.concat([t, kv.v])); - (k = bits2int(t, q)), - (kv.k = createHmac(algo, kv.k) - .update(kv.v) - .update(Buffer2.from([0])) - .digest()), - (kv.v = createHmac(algo, kv.k).update(kv.v).digest()); - } while (k.cmp(q) !== -1); - return k; - } - function makeR(g, k, p, q) { - return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); - } - module.exports = sign; - module.exports.getKey = getKey; - module.exports.makeKey = makeKey; - }, -}); - -// node_modules/browserify-sign/browser/verify.js -var require_verify = __commonJS({ - "node_modules/browserify-sign/browser/verify.js"(exports, module) { - var Buffer2 = require_safe_buffer().Buffer, - BN = require_bn3(), - EC = require_elliptic().ec, - parseKeys = require_parse_asn1(), - curves = require_curves2(); - function verify(sig, hash, key, signType, tag) { - var pub = parseKeys(key); - if (pub.type === "ec") { - if (signType !== "ecdsa" && signType !== "ecdsa/rsa") throw new Error("wrong public key type"); - return ecVerify(sig, hash, pub); - } else if (pub.type === "dsa") { - if (signType !== "dsa") throw new Error("wrong public key type"); - return dsaVerify(sig, hash, pub); - } else if (signType !== "rsa" && signType !== "ecdsa/rsa") throw new Error("wrong public key type"); - hash = Buffer2.concat([tag, hash]); - for (var len = pub.modulus.byteLength(), pad = [1], padNum = 0; hash.length + pad.length + 2 < len; ) - pad.push(255), padNum++; - pad.push(0); - for (var i = -1; ++i < hash.length; ) pad.push(hash[i]); - pad = Buffer2.from(pad); - var red = BN.mont(pub.modulus); - (sig = new BN(sig).toRed(red)), - (sig = sig.redPow(new BN(pub.publicExponent))), - (sig = Buffer2.from(sig.fromRed().toArray())); - var out = padNum < 8 ? 1 : 0; - for (len = Math.min(sig.length, pad.length), sig.length !== pad.length && (out = 1), i = -1; ++i < len; ) - out |= sig[i] ^ pad[i]; - return out === 0; - } - function ecVerify(sig, hash, pub) { - var curveId = curves[pub.data.algorithm.curve.join(".")]; - if (!curveId) throw new Error("unknown curve " + pub.data.algorithm.curve.join(".")); - var curve = new EC(curveId), - pubkey = pub.data.subjectPrivateKey.data; - return curve.verify(hash, sig, pubkey); - } - function dsaVerify(sig, hash, pub) { - var p = pub.data.p, - q = pub.data.q, - g = pub.data.g, - y = pub.data.pub_key, - unpacked = parseKeys.signature.decode(sig, "der"), - s = unpacked.s, - r = unpacked.r; - checkValue(s, q), checkValue(r, q); - var montp = BN.mont(p), - w = s.invm(q), - v = g - .toRed(montp) - .redPow(new BN(hash).mul(w).mod(q)) - .fromRed() - .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) - .mod(p) - .mod(q); - return v.cmp(r) === 0; - } - function checkValue(b, q) { - if (b.cmpn(0) <= 0) throw new Error("invalid sig"); - if (b.cmp(q) >= q) throw new Error("invalid sig"); - } - module.exports = verify; - }, -}); - -// node_modules/browserify-sign/browser/index.js -var require_browser8 = __commonJS({ - "node_modules/browserify-sign/browser/index.js"(exports, module) { - var Buffer2 = require_safe_buffer().Buffer, - createHash = require_browser2(), - inherits = require_inherits_browser(), - sign = require_sign(), - verify = require_verify(), - algorithms = require_algorithms(); - Object.keys(algorithms).forEach(function (key) { - (algorithms[key].id = Buffer2.from(algorithms[key].id, "hex")), (algorithms[key.toLowerCase()] = algorithms[key]); - }); - function Sign(algorithm) { - StreamModule.Writable.call(this); - var data = algorithms[algorithm]; - if (!data) throw new Error("Unknown message digest"); - (this._hashType = data.hash), - (this._hash = createHash(data.hash)), - (this._tag = data.id), - (this._signType = data.sign); - } - inherits(Sign, StreamModule.Writable); - Sign.prototype._write = function (data, _, done) { - this._hash.update(data), done(); - }; - Sign.prototype.update = function (data, enc) { - return typeof data == "string" && (data = Buffer2.from(data, enc)), this._hash.update(data), this; - }; - Sign.prototype.sign = function (key, enc) { - this.end(); - var hash = this._hash.digest(), - sig = sign(hash, key, this._hashType, this._signType, this._tag); - return enc ? sig.toString(enc) : sig; - }; - function Verify(algorithm) { - StreamModule.Writable.call(this); - var data = algorithms[algorithm]; - if (!data) throw new Error("Unknown message digest"); - (this._hash = createHash(data.hash)), (this._tag = data.id), (this._signType = data.sign); - } - inherits(Verify, StreamModule.Writable); - Verify.prototype._write = function (data, _, done) { - this._hash.update(data), done(); - }; - Verify.prototype.update = function (data, enc) { - return typeof data == "string" && (data = Buffer2.from(data, enc)), this._hash.update(data), this; - }; - Verify.prototype.verify = function (key, sig, enc) { - typeof sig == "string" && (sig = Buffer2.from(sig, enc)), this.end(); - var hash = this._hash.digest(); - return verify(sig, hash, key, this._signType, this._tag); - }; - function createSign(algorithm) { - return new Sign(algorithm); - } - function createVerify(algorithm) { - return new Verify(algorithm); - } - module.exports = { - Sign: createSign, - Verify: createVerify, - createSign, - createVerify, - }; - }, -}); - -// node_modules/create-ecdh/node_modules/bn.js/lib/bn.js -var require_bn6 = __commonJS({ - "node_modules/create-ecdh/node_modules/bn.js/lib/bn.js"(exports, module) { - (function (module2, exports2) { - "use strict"; - function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); - } - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - (TempCtor.prototype = superCtor.prototype), - (ctor.prototype = new TempCtor()), - (ctor.prototype.constructor = ctor); - } - function BN(number, base, endian) { - if (BN.isBN(number)) return number; - (this.negative = 0), - (this.words = null), - (this.length = 0), - (this.red = null), - number !== null && - ((base === "le" || base === "be") && ((endian = base), (base = 10)), - this._init(number || 0, base || 10, endian || "be")); - } - typeof module2 == "object" ? (module2.exports = BN) : (exports2.BN = BN), (BN.BN = BN), (BN.wordSize = 26); - var Buffer2 = Buffer; - (BN.isBN = function (num) { - return num instanceof BN - ? !0 - : num !== null && - typeof num == "object" && - num.constructor.wordSize === BN.wordSize && - Array.isArray(num.words); - }), - (BN.max = function (left, right) { - return left.cmp(right) > 0 ? left : right; - }), - (BN.min = function (left, right) { - return left.cmp(right) < 0 ? left : right; - }), - (BN.prototype._init = function (number, base, endian) { - if (typeof number == "number") return this._initNumber(number, base, endian); - if (typeof number == "object") return this._initArray(number, base, endian); - base === "hex" && (base = 16), - assert(base === (base | 0) && base >= 2 && base <= 36), - (number = number.toString().replace(/\s+/g, "")); - var start = 0; - number[0] === "-" && (start++, (this.negative = 1)), - start < number.length && - (base === 16 - ? this._parseHex(number, start, endian) - : (this._parseBase(number, base, start), - endian === "le" && this._initArray(this.toArray(), base, endian))); - }), - (BN.prototype._initNumber = function (number, base, endian) { - number < 0 && ((this.negative = 1), (number = -number)), - number < 67108864 - ? ((this.words = [number & 67108863]), (this.length = 1)) - : number < 4503599627370496 - ? ((this.words = [number & 67108863, (number / 67108864) & 67108863]), (this.length = 2)) - : (assert(number < 9007199254740992), - (this.words = [number & 67108863, (number / 67108864) & 67108863, 1]), - (this.length = 3)), - endian === "le" && this._initArray(this.toArray(), base, endian); - }), - (BN.prototype._initArray = function (number, base, endian) { - if ((assert(typeof number.length == "number"), number.length <= 0)) - return (this.words = [0]), (this.length = 1), this; - (this.length = Math.ceil(number.length / 3)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var j, - w, - off = 0; - if (endian === "be") - for (i = number.length - 1, j = 0; i >= 0; i -= 3) - (w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - else if (endian === "le") - for (i = 0, j = 0; i < number.length; i += 3) - (w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - return this.strip(); - }); - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - return c >= 65 && c <= 70 ? c - 55 : c >= 97 && c <= 102 ? c - 87 : (c - 48) & 15; - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - return index - 1 >= lowerBound && (r |= parseHex4Bits(string, index - 1) << 4), r; - } - BN.prototype._parseHex = function (number, start, endian) { - (this.length = Math.ceil((number.length - start) / 6)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var off = 0, - j = 0, - w; - if (endian === "be") - for (i = number.length - 1; i >= start; i -= 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - } - this.strip(); - }; - function parseBase(str, start, end, mul) { - for (var r = 0, len = Math.min(str.length, end), i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - (r *= mul), c >= 49 ? (r += c - 49 + 10) : c >= 17 ? (r += c - 17 + 10) : (r += c); - } - return r; - } - (BN.prototype._parseBase = function (number, base, start) { - (this.words = [0]), (this.length = 1); - for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base) limbLen++; - limbLen--, (limbPow = (limbPow / base) | 0); - for ( - var total = number.length - start, - mod = total % limbLen, - end = Math.min(total, total - mod) + start, - word = 0, - i = start; - i < end; - i += limbLen - ) - (word = parseBase(number, i, i + limbLen, base)), - this.imuln(limbPow), - this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - if (mod !== 0) { - var pow = 1; - for (word = parseBase(number, i, number.length, base), i = 0; i < mod; i++) pow *= base; - this.imuln(pow), this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - } - this.strip(); - }), - (BN.prototype.copy = function (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) dest.words[i] = this.words[i]; - (dest.length = this.length), (dest.negative = this.negative), (dest.red = this.red); - }), - (BN.prototype.clone = function () { - var r = new BN(null); - return this.copy(r), r; - }), - (BN.prototype._expand = function (size) { - for (; this.length < size; ) this.words[this.length++] = 0; - return this; - }), - (BN.prototype.strip = function () { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; - return this._normSign(); - }), - (BN.prototype._normSign = function () { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }), - (BN.prototype.inspect = function () { - return (this.red ? ""; - }); - var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000", - ], - groupSizes = [ - 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, - ], - groupBases = [ - 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, - 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, - 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, - 60466176, - ]; - (BN.prototype.toString = function (base, padding) { - (base = base || 10), (padding = padding | 0 || 1); - var out; - if (base === 16 || base === "hex") { - out = ""; - for (var off = 0, carry = 0, i = 0; i < this.length; i++) { - var w = this.words[i], - word = (((w << off) | carry) & 16777215).toString(16); - (carry = (w >>> (24 - off)) & 16777215), - carry !== 0 || i !== this.length - 1 ? (out = zeros[6 - word.length] + word + out) : (out = word + out), - (off += 2), - off >= 26 && ((off -= 26), i--); - } - for (carry !== 0 && (out = carry.toString(16) + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - if (base === (base | 0) && base >= 2 && base <= 36) { - var groupSize = groupSizes[base], - groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - for (c.negative = 0; !c.isZero(); ) { - var r = c.modn(groupBase).toString(base); - (c = c.idivn(groupBase)), c.isZero() ? (out = r + out) : (out = zeros[groupSize - r.length] + r + out); - } - for (this.isZero() && (out = "0" + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - assert(!1, "Base should be between 2 and 36"); - }), - (BN.prototype.toNumber = function () { - var ret = this.words[0]; - return ( - this.length === 2 - ? (ret += this.words[1] * 67108864) - : this.length === 3 && this.words[2] === 1 - ? (ret += 4503599627370496 + this.words[1] * 67108864) - : this.length > 2 && assert(!1, "Number can only safely store up to 53 bits"), - this.negative !== 0 ? -ret : ret - ); - }), - (BN.prototype.toJSON = function () { - return this.toString(16); - }), - (BN.prototype.toBuffer = function (endian, length) { - return assert(typeof Buffer2 < "u"), this.toArrayLike(Buffer2, endian, length); - }), - (BN.prototype.toArray = function (endian, length) { - return this.toArrayLike(Array, endian, length); - }), - (BN.prototype.toArrayLike = function (ArrayType, endian, length) { - var byteLength = this.byteLength(), - reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"), - assert(reqLength > 0, "Requested array length <= 0"), - this.strip(); - var littleEndian = endian === "le", - res = new ArrayType(reqLength), - b, - i, - q = this.clone(); - if (littleEndian) { - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[i] = b); - for (; i < reqLength; i++) res[i] = 0; - } else { - for (i = 0; i < reqLength - byteLength; i++) res[i] = 0; - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[reqLength - i - 1] = b); - } - return res; - }), - Math.clz32 - ? (BN.prototype._countBits = function (w) { - return 32 - Math.clz32(w); - }) - : (BN.prototype._countBits = function (w) { - var t = w, - r = 0; - return ( - t >= 4096 && ((r += 13), (t >>>= 13)), - t >= 64 && ((r += 7), (t >>>= 7)), - t >= 8 && ((r += 4), (t >>>= 4)), - t >= 2 && ((r += 2), (t >>>= 2)), - r + t - ); - }), - (BN.prototype._zeroBits = function (w) { - if (w === 0) return 26; - var t = w, - r = 0; - return ( - (t & 8191) === 0 && ((r += 13), (t >>>= 13)), - (t & 127) === 0 && ((r += 7), (t >>>= 7)), - (t & 15) === 0 && ((r += 4), (t >>>= 4)), - (t & 3) === 0 && ((r += 2), (t >>>= 2)), - (t & 1) === 0 && r++, - r - ); - }), - (BN.prototype.bitLength = function () { - var w = this.words[this.length - 1], - hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }); - function toBitArray(num) { - for (var w = new Array(num.bitLength()), bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0, - wbit = bit % 26; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - return w; - } - (BN.prototype.zeroBits = function () { - if (this.isZero()) return 0; - for (var r = 0, i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - if (((r += b), b !== 26)) break; - } - return r; - }), - (BN.prototype.byteLength = function () { - return Math.ceil(this.bitLength() / 8); - }), - (BN.prototype.toTwos = function (width) { - return this.negative !== 0 ? this.abs().inotn(width).iaddn(1) : this.clone(); - }), - (BN.prototype.fromTwos = function (width) { - return this.testn(width - 1) ? this.notn(width).iaddn(1).ineg() : this.clone(); - }), - (BN.prototype.isNeg = function () { - return this.negative !== 0; - }), - (BN.prototype.neg = function () { - return this.clone().ineg(); - }), - (BN.prototype.ineg = function () { - return this.isZero() || (this.negative ^= 1), this; - }), - (BN.prototype.iuor = function (num) { - for (; this.length < num.length; ) this.words[this.length++] = 0; - for (var i = 0; i < num.length; i++) this.words[i] = this.words[i] | num.words[i]; - return this.strip(); - }), - (BN.prototype.ior = function (num) { - return assert((this.negative | num.negative) === 0), this.iuor(num); - }), - (BN.prototype.or = function (num) { - return this.length > num.length ? this.clone().ior(num) : num.clone().ior(this); - }), - (BN.prototype.uor = function (num) { - return this.length > num.length ? this.clone().iuor(num) : num.clone().iuor(this); - }), - (BN.prototype.iuand = function (num) { - var b; - this.length > num.length ? (b = num) : (b = this); - for (var i = 0; i < b.length; i++) this.words[i] = this.words[i] & num.words[i]; - return (this.length = b.length), this.strip(); - }), - (BN.prototype.iand = function (num) { - return assert((this.negative | num.negative) === 0), this.iuand(num); - }), - (BN.prototype.and = function (num) { - return this.length > num.length ? this.clone().iand(num) : num.clone().iand(this); - }), - (BN.prototype.uand = function (num) { - return this.length > num.length ? this.clone().iuand(num) : num.clone().iuand(this); - }), - (BN.prototype.iuxor = function (num) { - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var i = 0; i < b.length; i++) this.words[i] = a.words[i] ^ b.words[i]; - if (this !== a) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = a.length), this.strip(); - }), - (BN.prototype.ixor = function (num) { - return assert((this.negative | num.negative) === 0), this.iuxor(num); - }), - (BN.prototype.xor = function (num) { - return this.length > num.length ? this.clone().ixor(num) : num.clone().ixor(this); - }), - (BN.prototype.uxor = function (num) { - return this.length > num.length ? this.clone().iuxor(num) : num.clone().iuxor(this); - }), - (BN.prototype.inotn = function (width) { - assert(typeof width == "number" && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0, - bitsLeft = width % 26; - this._expand(bytesNeeded), bitsLeft > 0 && bytesNeeded--; - for (var i = 0; i < bytesNeeded; i++) this.words[i] = ~this.words[i] & 67108863; - return bitsLeft > 0 && (this.words[i] = ~this.words[i] & (67108863 >> (26 - bitsLeft))), this.strip(); - }), - (BN.prototype.notn = function (width) { - return this.clone().inotn(width); - }), - (BN.prototype.setn = function (bit, val) { - assert(typeof bit == "number" && bit >= 0); - var off = (bit / 26) | 0, - wbit = bit % 26; - return ( - this._expand(off + 1), - val - ? (this.words[off] = this.words[off] | (1 << wbit)) - : (this.words[off] = this.words[off] & ~(1 << wbit)), - this.strip() - ); - }), - (BN.prototype.iadd = function (num) { - var r; - if (this.negative !== 0 && num.negative === 0) - return (this.negative = 0), (r = this.isub(num)), (this.negative ^= 1), this._normSign(); - if (this.negative === 0 && num.negative !== 0) - return (num.negative = 0), (r = this.isub(num)), (num.negative = 1), r._normSign(); - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) + (b.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - if (((this.length = a.length), carry !== 0)) (this.words[this.length] = carry), this.length++; - else if (a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return this; - }), - (BN.prototype.add = function (num) { - var res; - return num.negative !== 0 && this.negative === 0 - ? ((num.negative = 0), (res = this.sub(num)), (num.negative ^= 1), res) - : num.negative === 0 && this.negative !== 0 - ? ((this.negative = 0), (res = num.sub(this)), (this.negative = 1), res) - : this.length > num.length - ? this.clone().iadd(num) - : num.clone().iadd(this); - }), - (BN.prototype.isub = function (num) { - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - return (num.negative = 1), r._normSign(); - } else if (this.negative !== 0) - return (this.negative = 0), this.iadd(num), (this.negative = 1), this._normSign(); - var cmp = this.cmp(num); - if (cmp === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; - var a, b; - cmp > 0 ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) - (b.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - if (carry === 0 && i < a.length && a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = Math.max(this.length, i)), a !== this && (this.negative = 1), this.strip(); - }), - (BN.prototype.sub = function (num) { - return this.clone().isub(num); - }); - function smallMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - var len = (self2.length + num.length) | 0; - (out.length = len), (len = (len - 1) | 0); - var a = self2.words[0] | 0, - b = num.words[0] | 0, - r = a * b, - lo = r & 67108863, - carry = (r / 67108864) | 0; - out.words[0] = lo; - for (var k = 1; k < len; k++) { - for ( - var ncarry = carry >>> 26, - rword = carry & 67108863, - maxJ = Math.min(k, num.length - 1), - j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = (k - j) | 0; - (a = self2.words[i] | 0), - (b = num.words[j] | 0), - (r = a * b + rword), - (ncarry += (r / 67108864) | 0), - (rword = r & 67108863); - } - (out.words[k] = rword | 0), (carry = ncarry | 0); - } - return carry !== 0 ? (out.words[k] = carry | 0) : out.length--, out.strip(); - } - var comb10MulTo = function (self2, num, out) { - var a = self2.words, - b = num.words, - o = out.words, - c = 0, - lo, - mid, - hi, - a0 = a[0] | 0, - al0 = a0 & 8191, - ah0 = a0 >>> 13, - a1 = a[1] | 0, - al1 = a1 & 8191, - ah1 = a1 >>> 13, - a2 = a[2] | 0, - al2 = a2 & 8191, - ah2 = a2 >>> 13, - a3 = a[3] | 0, - al3 = a3 & 8191, - ah3 = a3 >>> 13, - a4 = a[4] | 0, - al4 = a4 & 8191, - ah4 = a4 >>> 13, - a5 = a[5] | 0, - al5 = a5 & 8191, - ah5 = a5 >>> 13, - a6 = a[6] | 0, - al6 = a6 & 8191, - ah6 = a6 >>> 13, - a7 = a[7] | 0, - al7 = a7 & 8191, - ah7 = a7 >>> 13, - a8 = a[8] | 0, - al8 = a8 & 8191, - ah8 = a8 >>> 13, - a9 = a[9] | 0, - al9 = a9 & 8191, - ah9 = a9 >>> 13, - b0 = b[0] | 0, - bl0 = b0 & 8191, - bh0 = b0 >>> 13, - b1 = b[1] | 0, - bl1 = b1 & 8191, - bh1 = b1 >>> 13, - b2 = b[2] | 0, - bl2 = b2 & 8191, - bh2 = b2 >>> 13, - b3 = b[3] | 0, - bl3 = b3 & 8191, - bh3 = b3 >>> 13, - b4 = b[4] | 0, - bl4 = b4 & 8191, - bh4 = b4 >>> 13, - b5 = b[5] | 0, - bl5 = b5 & 8191, - bh5 = b5 >>> 13, - b6 = b[6] | 0, - bl6 = b6 & 8191, - bh6 = b6 >>> 13, - b7 = b[7] | 0, - bl7 = b7 & 8191, - bh7 = b7 >>> 13, - b8 = b[8] | 0, - bl8 = b8 & 8191, - bh8 = b8 >>> 13, - b9 = b[9] | 0, - bl9 = b9 & 8191, - bh9 = b9 >>> 13; - (out.negative = self2.negative ^ num.negative), - (out.length = 19), - (lo = Math.imul(al0, bl0)), - (mid = Math.imul(al0, bh0)), - (mid = (mid + Math.imul(ah0, bl0)) | 0), - (hi = Math.imul(ah0, bh0)); - var w0 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0), - (w0 &= 67108863), - (lo = Math.imul(al1, bl0)), - (mid = Math.imul(al1, bh0)), - (mid = (mid + Math.imul(ah1, bl0)) | 0), - (hi = Math.imul(ah1, bh0)), - (lo = (lo + Math.imul(al0, bl1)) | 0), - (mid = (mid + Math.imul(al0, bh1)) | 0), - (mid = (mid + Math.imul(ah0, bl1)) | 0), - (hi = (hi + Math.imul(ah0, bh1)) | 0); - var w1 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0), - (w1 &= 67108863), - (lo = Math.imul(al2, bl0)), - (mid = Math.imul(al2, bh0)), - (mid = (mid + Math.imul(ah2, bl0)) | 0), - (hi = Math.imul(ah2, bh0)), - (lo = (lo + Math.imul(al1, bl1)) | 0), - (mid = (mid + Math.imul(al1, bh1)) | 0), - (mid = (mid + Math.imul(ah1, bl1)) | 0), - (hi = (hi + Math.imul(ah1, bh1)) | 0), - (lo = (lo + Math.imul(al0, bl2)) | 0), - (mid = (mid + Math.imul(al0, bh2)) | 0), - (mid = (mid + Math.imul(ah0, bl2)) | 0), - (hi = (hi + Math.imul(ah0, bh2)) | 0); - var w2 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0), - (w2 &= 67108863), - (lo = Math.imul(al3, bl0)), - (mid = Math.imul(al3, bh0)), - (mid = (mid + Math.imul(ah3, bl0)) | 0), - (hi = Math.imul(ah3, bh0)), - (lo = (lo + Math.imul(al2, bl1)) | 0), - (mid = (mid + Math.imul(al2, bh1)) | 0), - (mid = (mid + Math.imul(ah2, bl1)) | 0), - (hi = (hi + Math.imul(ah2, bh1)) | 0), - (lo = (lo + Math.imul(al1, bl2)) | 0), - (mid = (mid + Math.imul(al1, bh2)) | 0), - (mid = (mid + Math.imul(ah1, bl2)) | 0), - (hi = (hi + Math.imul(ah1, bh2)) | 0), - (lo = (lo + Math.imul(al0, bl3)) | 0), - (mid = (mid + Math.imul(al0, bh3)) | 0), - (mid = (mid + Math.imul(ah0, bl3)) | 0), - (hi = (hi + Math.imul(ah0, bh3)) | 0); - var w3 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0), - (w3 &= 67108863), - (lo = Math.imul(al4, bl0)), - (mid = Math.imul(al4, bh0)), - (mid = (mid + Math.imul(ah4, bl0)) | 0), - (hi = Math.imul(ah4, bh0)), - (lo = (lo + Math.imul(al3, bl1)) | 0), - (mid = (mid + Math.imul(al3, bh1)) | 0), - (mid = (mid + Math.imul(ah3, bl1)) | 0), - (hi = (hi + Math.imul(ah3, bh1)) | 0), - (lo = (lo + Math.imul(al2, bl2)) | 0), - (mid = (mid + Math.imul(al2, bh2)) | 0), - (mid = (mid + Math.imul(ah2, bl2)) | 0), - (hi = (hi + Math.imul(ah2, bh2)) | 0), - (lo = (lo + Math.imul(al1, bl3)) | 0), - (mid = (mid + Math.imul(al1, bh3)) | 0), - (mid = (mid + Math.imul(ah1, bl3)) | 0), - (hi = (hi + Math.imul(ah1, bh3)) | 0), - (lo = (lo + Math.imul(al0, bl4)) | 0), - (mid = (mid + Math.imul(al0, bh4)) | 0), - (mid = (mid + Math.imul(ah0, bl4)) | 0), - (hi = (hi + Math.imul(ah0, bh4)) | 0); - var w4 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0), - (w4 &= 67108863), - (lo = Math.imul(al5, bl0)), - (mid = Math.imul(al5, bh0)), - (mid = (mid + Math.imul(ah5, bl0)) | 0), - (hi = Math.imul(ah5, bh0)), - (lo = (lo + Math.imul(al4, bl1)) | 0), - (mid = (mid + Math.imul(al4, bh1)) | 0), - (mid = (mid + Math.imul(ah4, bl1)) | 0), - (hi = (hi + Math.imul(ah4, bh1)) | 0), - (lo = (lo + Math.imul(al3, bl2)) | 0), - (mid = (mid + Math.imul(al3, bh2)) | 0), - (mid = (mid + Math.imul(ah3, bl2)) | 0), - (hi = (hi + Math.imul(ah3, bh2)) | 0), - (lo = (lo + Math.imul(al2, bl3)) | 0), - (mid = (mid + Math.imul(al2, bh3)) | 0), - (mid = (mid + Math.imul(ah2, bl3)) | 0), - (hi = (hi + Math.imul(ah2, bh3)) | 0), - (lo = (lo + Math.imul(al1, bl4)) | 0), - (mid = (mid + Math.imul(al1, bh4)) | 0), - (mid = (mid + Math.imul(ah1, bl4)) | 0), - (hi = (hi + Math.imul(ah1, bh4)) | 0), - (lo = (lo + Math.imul(al0, bl5)) | 0), - (mid = (mid + Math.imul(al0, bh5)) | 0), - (mid = (mid + Math.imul(ah0, bl5)) | 0), - (hi = (hi + Math.imul(ah0, bh5)) | 0); - var w5 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0), - (w5 &= 67108863), - (lo = Math.imul(al6, bl0)), - (mid = Math.imul(al6, bh0)), - (mid = (mid + Math.imul(ah6, bl0)) | 0), - (hi = Math.imul(ah6, bh0)), - (lo = (lo + Math.imul(al5, bl1)) | 0), - (mid = (mid + Math.imul(al5, bh1)) | 0), - (mid = (mid + Math.imul(ah5, bl1)) | 0), - (hi = (hi + Math.imul(ah5, bh1)) | 0), - (lo = (lo + Math.imul(al4, bl2)) | 0), - (mid = (mid + Math.imul(al4, bh2)) | 0), - (mid = (mid + Math.imul(ah4, bl2)) | 0), - (hi = (hi + Math.imul(ah4, bh2)) | 0), - (lo = (lo + Math.imul(al3, bl3)) | 0), - (mid = (mid + Math.imul(al3, bh3)) | 0), - (mid = (mid + Math.imul(ah3, bl3)) | 0), - (hi = (hi + Math.imul(ah3, bh3)) | 0), - (lo = (lo + Math.imul(al2, bl4)) | 0), - (mid = (mid + Math.imul(al2, bh4)) | 0), - (mid = (mid + Math.imul(ah2, bl4)) | 0), - (hi = (hi + Math.imul(ah2, bh4)) | 0), - (lo = (lo + Math.imul(al1, bl5)) | 0), - (mid = (mid + Math.imul(al1, bh5)) | 0), - (mid = (mid + Math.imul(ah1, bl5)) | 0), - (hi = (hi + Math.imul(ah1, bh5)) | 0), - (lo = (lo + Math.imul(al0, bl6)) | 0), - (mid = (mid + Math.imul(al0, bh6)) | 0), - (mid = (mid + Math.imul(ah0, bl6)) | 0), - (hi = (hi + Math.imul(ah0, bh6)) | 0); - var w6 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0), - (w6 &= 67108863), - (lo = Math.imul(al7, bl0)), - (mid = Math.imul(al7, bh0)), - (mid = (mid + Math.imul(ah7, bl0)) | 0), - (hi = Math.imul(ah7, bh0)), - (lo = (lo + Math.imul(al6, bl1)) | 0), - (mid = (mid + Math.imul(al6, bh1)) | 0), - (mid = (mid + Math.imul(ah6, bl1)) | 0), - (hi = (hi + Math.imul(ah6, bh1)) | 0), - (lo = (lo + Math.imul(al5, bl2)) | 0), - (mid = (mid + Math.imul(al5, bh2)) | 0), - (mid = (mid + Math.imul(ah5, bl2)) | 0), - (hi = (hi + Math.imul(ah5, bh2)) | 0), - (lo = (lo + Math.imul(al4, bl3)) | 0), - (mid = (mid + Math.imul(al4, bh3)) | 0), - (mid = (mid + Math.imul(ah4, bl3)) | 0), - (hi = (hi + Math.imul(ah4, bh3)) | 0), - (lo = (lo + Math.imul(al3, bl4)) | 0), - (mid = (mid + Math.imul(al3, bh4)) | 0), - (mid = (mid + Math.imul(ah3, bl4)) | 0), - (hi = (hi + Math.imul(ah3, bh4)) | 0), - (lo = (lo + Math.imul(al2, bl5)) | 0), - (mid = (mid + Math.imul(al2, bh5)) | 0), - (mid = (mid + Math.imul(ah2, bl5)) | 0), - (hi = (hi + Math.imul(ah2, bh5)) | 0), - (lo = (lo + Math.imul(al1, bl6)) | 0), - (mid = (mid + Math.imul(al1, bh6)) | 0), - (mid = (mid + Math.imul(ah1, bl6)) | 0), - (hi = (hi + Math.imul(ah1, bh6)) | 0), - (lo = (lo + Math.imul(al0, bl7)) | 0), - (mid = (mid + Math.imul(al0, bh7)) | 0), - (mid = (mid + Math.imul(ah0, bl7)) | 0), - (hi = (hi + Math.imul(ah0, bh7)) | 0); - var w7 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0), - (w7 &= 67108863), - (lo = Math.imul(al8, bl0)), - (mid = Math.imul(al8, bh0)), - (mid = (mid + Math.imul(ah8, bl0)) | 0), - (hi = Math.imul(ah8, bh0)), - (lo = (lo + Math.imul(al7, bl1)) | 0), - (mid = (mid + Math.imul(al7, bh1)) | 0), - (mid = (mid + Math.imul(ah7, bl1)) | 0), - (hi = (hi + Math.imul(ah7, bh1)) | 0), - (lo = (lo + Math.imul(al6, bl2)) | 0), - (mid = (mid + Math.imul(al6, bh2)) | 0), - (mid = (mid + Math.imul(ah6, bl2)) | 0), - (hi = (hi + Math.imul(ah6, bh2)) | 0), - (lo = (lo + Math.imul(al5, bl3)) | 0), - (mid = (mid + Math.imul(al5, bh3)) | 0), - (mid = (mid + Math.imul(ah5, bl3)) | 0), - (hi = (hi + Math.imul(ah5, bh3)) | 0), - (lo = (lo + Math.imul(al4, bl4)) | 0), - (mid = (mid + Math.imul(al4, bh4)) | 0), - (mid = (mid + Math.imul(ah4, bl4)) | 0), - (hi = (hi + Math.imul(ah4, bh4)) | 0), - (lo = (lo + Math.imul(al3, bl5)) | 0), - (mid = (mid + Math.imul(al3, bh5)) | 0), - (mid = (mid + Math.imul(ah3, bl5)) | 0), - (hi = (hi + Math.imul(ah3, bh5)) | 0), - (lo = (lo + Math.imul(al2, bl6)) | 0), - (mid = (mid + Math.imul(al2, bh6)) | 0), - (mid = (mid + Math.imul(ah2, bl6)) | 0), - (hi = (hi + Math.imul(ah2, bh6)) | 0), - (lo = (lo + Math.imul(al1, bl7)) | 0), - (mid = (mid + Math.imul(al1, bh7)) | 0), - (mid = (mid + Math.imul(ah1, bl7)) | 0), - (hi = (hi + Math.imul(ah1, bh7)) | 0), - (lo = (lo + Math.imul(al0, bl8)) | 0), - (mid = (mid + Math.imul(al0, bh8)) | 0), - (mid = (mid + Math.imul(ah0, bl8)) | 0), - (hi = (hi + Math.imul(ah0, bh8)) | 0); - var w8 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0), - (w8 &= 67108863), - (lo = Math.imul(al9, bl0)), - (mid = Math.imul(al9, bh0)), - (mid = (mid + Math.imul(ah9, bl0)) | 0), - (hi = Math.imul(ah9, bh0)), - (lo = (lo + Math.imul(al8, bl1)) | 0), - (mid = (mid + Math.imul(al8, bh1)) | 0), - (mid = (mid + Math.imul(ah8, bl1)) | 0), - (hi = (hi + Math.imul(ah8, bh1)) | 0), - (lo = (lo + Math.imul(al7, bl2)) | 0), - (mid = (mid + Math.imul(al7, bh2)) | 0), - (mid = (mid + Math.imul(ah7, bl2)) | 0), - (hi = (hi + Math.imul(ah7, bh2)) | 0), - (lo = (lo + Math.imul(al6, bl3)) | 0), - (mid = (mid + Math.imul(al6, bh3)) | 0), - (mid = (mid + Math.imul(ah6, bl3)) | 0), - (hi = (hi + Math.imul(ah6, bh3)) | 0), - (lo = (lo + Math.imul(al5, bl4)) | 0), - (mid = (mid + Math.imul(al5, bh4)) | 0), - (mid = (mid + Math.imul(ah5, bl4)) | 0), - (hi = (hi + Math.imul(ah5, bh4)) | 0), - (lo = (lo + Math.imul(al4, bl5)) | 0), - (mid = (mid + Math.imul(al4, bh5)) | 0), - (mid = (mid + Math.imul(ah4, bl5)) | 0), - (hi = (hi + Math.imul(ah4, bh5)) | 0), - (lo = (lo + Math.imul(al3, bl6)) | 0), - (mid = (mid + Math.imul(al3, bh6)) | 0), - (mid = (mid + Math.imul(ah3, bl6)) | 0), - (hi = (hi + Math.imul(ah3, bh6)) | 0), - (lo = (lo + Math.imul(al2, bl7)) | 0), - (mid = (mid + Math.imul(al2, bh7)) | 0), - (mid = (mid + Math.imul(ah2, bl7)) | 0), - (hi = (hi + Math.imul(ah2, bh7)) | 0), - (lo = (lo + Math.imul(al1, bl8)) | 0), - (mid = (mid + Math.imul(al1, bh8)) | 0), - (mid = (mid + Math.imul(ah1, bl8)) | 0), - (hi = (hi + Math.imul(ah1, bh8)) | 0), - (lo = (lo + Math.imul(al0, bl9)) | 0), - (mid = (mid + Math.imul(al0, bh9)) | 0), - (mid = (mid + Math.imul(ah0, bl9)) | 0), - (hi = (hi + Math.imul(ah0, bh9)) | 0); - var w9 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0), - (w9 &= 67108863), - (lo = Math.imul(al9, bl1)), - (mid = Math.imul(al9, bh1)), - (mid = (mid + Math.imul(ah9, bl1)) | 0), - (hi = Math.imul(ah9, bh1)), - (lo = (lo + Math.imul(al8, bl2)) | 0), - (mid = (mid + Math.imul(al8, bh2)) | 0), - (mid = (mid + Math.imul(ah8, bl2)) | 0), - (hi = (hi + Math.imul(ah8, bh2)) | 0), - (lo = (lo + Math.imul(al7, bl3)) | 0), - (mid = (mid + Math.imul(al7, bh3)) | 0), - (mid = (mid + Math.imul(ah7, bl3)) | 0), - (hi = (hi + Math.imul(ah7, bh3)) | 0), - (lo = (lo + Math.imul(al6, bl4)) | 0), - (mid = (mid + Math.imul(al6, bh4)) | 0), - (mid = (mid + Math.imul(ah6, bl4)) | 0), - (hi = (hi + Math.imul(ah6, bh4)) | 0), - (lo = (lo + Math.imul(al5, bl5)) | 0), - (mid = (mid + Math.imul(al5, bh5)) | 0), - (mid = (mid + Math.imul(ah5, bl5)) | 0), - (hi = (hi + Math.imul(ah5, bh5)) | 0), - (lo = (lo + Math.imul(al4, bl6)) | 0), - (mid = (mid + Math.imul(al4, bh6)) | 0), - (mid = (mid + Math.imul(ah4, bl6)) | 0), - (hi = (hi + Math.imul(ah4, bh6)) | 0), - (lo = (lo + Math.imul(al3, bl7)) | 0), - (mid = (mid + Math.imul(al3, bh7)) | 0), - (mid = (mid + Math.imul(ah3, bl7)) | 0), - (hi = (hi + Math.imul(ah3, bh7)) | 0), - (lo = (lo + Math.imul(al2, bl8)) | 0), - (mid = (mid + Math.imul(al2, bh8)) | 0), - (mid = (mid + Math.imul(ah2, bl8)) | 0), - (hi = (hi + Math.imul(ah2, bh8)) | 0), - (lo = (lo + Math.imul(al1, bl9)) | 0), - (mid = (mid + Math.imul(al1, bh9)) | 0), - (mid = (mid + Math.imul(ah1, bl9)) | 0), - (hi = (hi + Math.imul(ah1, bh9)) | 0); - var w10 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0), - (w10 &= 67108863), - (lo = Math.imul(al9, bl2)), - (mid = Math.imul(al9, bh2)), - (mid = (mid + Math.imul(ah9, bl2)) | 0), - (hi = Math.imul(ah9, bh2)), - (lo = (lo + Math.imul(al8, bl3)) | 0), - (mid = (mid + Math.imul(al8, bh3)) | 0), - (mid = (mid + Math.imul(ah8, bl3)) | 0), - (hi = (hi + Math.imul(ah8, bh3)) | 0), - (lo = (lo + Math.imul(al7, bl4)) | 0), - (mid = (mid + Math.imul(al7, bh4)) | 0), - (mid = (mid + Math.imul(ah7, bl4)) | 0), - (hi = (hi + Math.imul(ah7, bh4)) | 0), - (lo = (lo + Math.imul(al6, bl5)) | 0), - (mid = (mid + Math.imul(al6, bh5)) | 0), - (mid = (mid + Math.imul(ah6, bl5)) | 0), - (hi = (hi + Math.imul(ah6, bh5)) | 0), - (lo = (lo + Math.imul(al5, bl6)) | 0), - (mid = (mid + Math.imul(al5, bh6)) | 0), - (mid = (mid + Math.imul(ah5, bl6)) | 0), - (hi = (hi + Math.imul(ah5, bh6)) | 0), - (lo = (lo + Math.imul(al4, bl7)) | 0), - (mid = (mid + Math.imul(al4, bh7)) | 0), - (mid = (mid + Math.imul(ah4, bl7)) | 0), - (hi = (hi + Math.imul(ah4, bh7)) | 0), - (lo = (lo + Math.imul(al3, bl8)) | 0), - (mid = (mid + Math.imul(al3, bh8)) | 0), - (mid = (mid + Math.imul(ah3, bl8)) | 0), - (hi = (hi + Math.imul(ah3, bh8)) | 0), - (lo = (lo + Math.imul(al2, bl9)) | 0), - (mid = (mid + Math.imul(al2, bh9)) | 0), - (mid = (mid + Math.imul(ah2, bl9)) | 0), - (hi = (hi + Math.imul(ah2, bh9)) | 0); - var w11 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0), - (w11 &= 67108863), - (lo = Math.imul(al9, bl3)), - (mid = Math.imul(al9, bh3)), - (mid = (mid + Math.imul(ah9, bl3)) | 0), - (hi = Math.imul(ah9, bh3)), - (lo = (lo + Math.imul(al8, bl4)) | 0), - (mid = (mid + Math.imul(al8, bh4)) | 0), - (mid = (mid + Math.imul(ah8, bl4)) | 0), - (hi = (hi + Math.imul(ah8, bh4)) | 0), - (lo = (lo + Math.imul(al7, bl5)) | 0), - (mid = (mid + Math.imul(al7, bh5)) | 0), - (mid = (mid + Math.imul(ah7, bl5)) | 0), - (hi = (hi + Math.imul(ah7, bh5)) | 0), - (lo = (lo + Math.imul(al6, bl6)) | 0), - (mid = (mid + Math.imul(al6, bh6)) | 0), - (mid = (mid + Math.imul(ah6, bl6)) | 0), - (hi = (hi + Math.imul(ah6, bh6)) | 0), - (lo = (lo + Math.imul(al5, bl7)) | 0), - (mid = (mid + Math.imul(al5, bh7)) | 0), - (mid = (mid + Math.imul(ah5, bl7)) | 0), - (hi = (hi + Math.imul(ah5, bh7)) | 0), - (lo = (lo + Math.imul(al4, bl8)) | 0), - (mid = (mid + Math.imul(al4, bh8)) | 0), - (mid = (mid + Math.imul(ah4, bl8)) | 0), - (hi = (hi + Math.imul(ah4, bh8)) | 0), - (lo = (lo + Math.imul(al3, bl9)) | 0), - (mid = (mid + Math.imul(al3, bh9)) | 0), - (mid = (mid + Math.imul(ah3, bl9)) | 0), - (hi = (hi + Math.imul(ah3, bh9)) | 0); - var w12 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0), - (w12 &= 67108863), - (lo = Math.imul(al9, bl4)), - (mid = Math.imul(al9, bh4)), - (mid = (mid + Math.imul(ah9, bl4)) | 0), - (hi = Math.imul(ah9, bh4)), - (lo = (lo + Math.imul(al8, bl5)) | 0), - (mid = (mid + Math.imul(al8, bh5)) | 0), - (mid = (mid + Math.imul(ah8, bl5)) | 0), - (hi = (hi + Math.imul(ah8, bh5)) | 0), - (lo = (lo + Math.imul(al7, bl6)) | 0), - (mid = (mid + Math.imul(al7, bh6)) | 0), - (mid = (mid + Math.imul(ah7, bl6)) | 0), - (hi = (hi + Math.imul(ah7, bh6)) | 0), - (lo = (lo + Math.imul(al6, bl7)) | 0), - (mid = (mid + Math.imul(al6, bh7)) | 0), - (mid = (mid + Math.imul(ah6, bl7)) | 0), - (hi = (hi + Math.imul(ah6, bh7)) | 0), - (lo = (lo + Math.imul(al5, bl8)) | 0), - (mid = (mid + Math.imul(al5, bh8)) | 0), - (mid = (mid + Math.imul(ah5, bl8)) | 0), - (hi = (hi + Math.imul(ah5, bh8)) | 0), - (lo = (lo + Math.imul(al4, bl9)) | 0), - (mid = (mid + Math.imul(al4, bh9)) | 0), - (mid = (mid + Math.imul(ah4, bl9)) | 0), - (hi = (hi + Math.imul(ah4, bh9)) | 0); - var w13 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0), - (w13 &= 67108863), - (lo = Math.imul(al9, bl5)), - (mid = Math.imul(al9, bh5)), - (mid = (mid + Math.imul(ah9, bl5)) | 0), - (hi = Math.imul(ah9, bh5)), - (lo = (lo + Math.imul(al8, bl6)) | 0), - (mid = (mid + Math.imul(al8, bh6)) | 0), - (mid = (mid + Math.imul(ah8, bl6)) | 0), - (hi = (hi + Math.imul(ah8, bh6)) | 0), - (lo = (lo + Math.imul(al7, bl7)) | 0), - (mid = (mid + Math.imul(al7, bh7)) | 0), - (mid = (mid + Math.imul(ah7, bl7)) | 0), - (hi = (hi + Math.imul(ah7, bh7)) | 0), - (lo = (lo + Math.imul(al6, bl8)) | 0), - (mid = (mid + Math.imul(al6, bh8)) | 0), - (mid = (mid + Math.imul(ah6, bl8)) | 0), - (hi = (hi + Math.imul(ah6, bh8)) | 0), - (lo = (lo + Math.imul(al5, bl9)) | 0), - (mid = (mid + Math.imul(al5, bh9)) | 0), - (mid = (mid + Math.imul(ah5, bl9)) | 0), - (hi = (hi + Math.imul(ah5, bh9)) | 0); - var w14 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0), - (w14 &= 67108863), - (lo = Math.imul(al9, bl6)), - (mid = Math.imul(al9, bh6)), - (mid = (mid + Math.imul(ah9, bl6)) | 0), - (hi = Math.imul(ah9, bh6)), - (lo = (lo + Math.imul(al8, bl7)) | 0), - (mid = (mid + Math.imul(al8, bh7)) | 0), - (mid = (mid + Math.imul(ah8, bl7)) | 0), - (hi = (hi + Math.imul(ah8, bh7)) | 0), - (lo = (lo + Math.imul(al7, bl8)) | 0), - (mid = (mid + Math.imul(al7, bh8)) | 0), - (mid = (mid + Math.imul(ah7, bl8)) | 0), - (hi = (hi + Math.imul(ah7, bh8)) | 0), - (lo = (lo + Math.imul(al6, bl9)) | 0), - (mid = (mid + Math.imul(al6, bh9)) | 0), - (mid = (mid + Math.imul(ah6, bl9)) | 0), - (hi = (hi + Math.imul(ah6, bh9)) | 0); - var w15 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0), - (w15 &= 67108863), - (lo = Math.imul(al9, bl7)), - (mid = Math.imul(al9, bh7)), - (mid = (mid + Math.imul(ah9, bl7)) | 0), - (hi = Math.imul(ah9, bh7)), - (lo = (lo + Math.imul(al8, bl8)) | 0), - (mid = (mid + Math.imul(al8, bh8)) | 0), - (mid = (mid + Math.imul(ah8, bl8)) | 0), - (hi = (hi + Math.imul(ah8, bh8)) | 0), - (lo = (lo + Math.imul(al7, bl9)) | 0), - (mid = (mid + Math.imul(al7, bh9)) | 0), - (mid = (mid + Math.imul(ah7, bl9)) | 0), - (hi = (hi + Math.imul(ah7, bh9)) | 0); - var w16 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0), - (w16 &= 67108863), - (lo = Math.imul(al9, bl8)), - (mid = Math.imul(al9, bh8)), - (mid = (mid + Math.imul(ah9, bl8)) | 0), - (hi = Math.imul(ah9, bh8)), - (lo = (lo + Math.imul(al8, bl9)) | 0), - (mid = (mid + Math.imul(al8, bh9)) | 0), - (mid = (mid + Math.imul(ah8, bl9)) | 0), - (hi = (hi + Math.imul(ah8, bh9)) | 0); - var w17 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0), - (w17 &= 67108863), - (lo = Math.imul(al9, bl9)), - (mid = Math.imul(al9, bh9)), - (mid = (mid + Math.imul(ah9, bl9)) | 0), - (hi = Math.imul(ah9, bh9)); - var w18 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - return ( - (c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0), - (w18 &= 67108863), - (o[0] = w0), - (o[1] = w1), - (o[2] = w2), - (o[3] = w3), - (o[4] = w4), - (o[5] = w5), - (o[6] = w6), - (o[7] = w7), - (o[8] = w8), - (o[9] = w9), - (o[10] = w10), - (o[11] = w11), - (o[12] = w12), - (o[13] = w13), - (o[14] = w14), - (o[15] = w15), - (o[16] = w16), - (o[17] = w17), - (o[18] = w18), - c !== 0 && ((o[19] = c), out.length++), - out - ); - }; - Math.imul || (comb10MulTo = smallMulTo); - function bigMulTo(self2, num, out) { - (out.negative = num.negative ^ self2.negative), (out.length = self2.length + num.length); - for (var carry = 0, hncarry = 0, k = 0; k < out.length - 1; k++) { - var ncarry = hncarry; - hncarry = 0; - for ( - var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1), j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = k - j, - a = self2.words[i] | 0, - b = num.words[j] | 0, - r = a * b, - lo = r & 67108863; - (ncarry = (ncarry + ((r / 67108864) | 0)) | 0), - (lo = (lo + rword) | 0), - (rword = lo & 67108863), - (ncarry = (ncarry + (lo >>> 26)) | 0), - (hncarry += ncarry >>> 26), - (ncarry &= 67108863); - } - (out.words[k] = rword), (carry = ncarry), (ncarry = hncarry); - } - return carry !== 0 ? (out.words[k] = carry) : out.length--, out.strip(); - } - function jumboMulTo(self2, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self2, num, out); - } - BN.prototype.mulTo = function (num, out) { - var res, - len = this.length + num.length; - return ( - this.length === 10 && num.length === 10 - ? (res = comb10MulTo(this, num, out)) - : len < 63 - ? (res = smallMulTo(this, num, out)) - : len < 1024 - ? (res = bigMulTo(this, num, out)) - : (res = jumboMulTo(this, num, out)), - res - ); - }; - function FFTM(x, y) { - (this.x = x), (this.y = y); - } - (FFTM.prototype.makeRBT = function (N) { - for (var t = new Array(N), l = BN.prototype._countBits(N) - 1, i = 0; i < N; i++) t[i] = this.revBin(i, l, N); - return t; - }), - (FFTM.prototype.revBin = function (x, l, N) { - if (x === 0 || x === N - 1) return x; - for (var rb = 0, i = 0; i < l; i++) (rb |= (x & 1) << (l - i - 1)), (x >>= 1); - return rb; - }), - (FFTM.prototype.permute = function (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) (rtws[i] = rws[rbt[i]]), (itws[i] = iws[rbt[i]]); - }), - (FFTM.prototype.transform = function (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - for (var s = 1; s < N; s <<= 1) - for ( - var l = s << 1, rtwdf = Math.cos((2 * Math.PI) / l), itwdf = Math.sin((2 * Math.PI) / l), p = 0; - p < N; - p += l - ) - for (var rtwdf_ = rtwdf, itwdf_ = itwdf, j = 0; j < s; j++) { - var re = rtws[p + j], - ie = itws[p + j], - ro = rtws[p + j + s], - io = itws[p + j + s], - rx = rtwdf_ * ro - itwdf_ * io; - (io = rtwdf_ * io + itwdf_ * ro), - (ro = rx), - (rtws[p + j] = re + ro), - (itws[p + j] = ie + io), - (rtws[p + j + s] = re - ro), - (itws[p + j + s] = ie - io), - j !== l && - ((rx = rtwdf * rtwdf_ - itwdf * itwdf_), (itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_), (rtwdf_ = rx)); - } - }), - (FFTM.prototype.guessLen13b = function (n, m) { - var N = Math.max(m, n) | 1, - odd = N & 1, - i = 0; - for (N = (N / 2) | 0; N; N = N >>> 1) i++; - return 1 << (i + 1 + odd); - }), - (FFTM.prototype.conjugate = function (rws, iws, N) { - if (!(N <= 1)) - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - (rws[i] = rws[N - i - 1]), - (rws[N - i - 1] = t), - (t = iws[i]), - (iws[i] = -iws[N - i - 1]), - (iws[N - i - 1] = -t); - } - }), - (FFTM.prototype.normalize13b = function (ws, N) { - for (var carry = 0, i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 8192 + Math.round(ws[2 * i] / N) + carry; - (ws[i] = w & 67108863), w < 67108864 ? (carry = 0) : (carry = (w / 67108864) | 0); - } - return ws; - }), - (FFTM.prototype.convert13b = function (ws, len, rws, N) { - for (var carry = 0, i = 0; i < len; i++) - (carry = carry + (ws[i] | 0)), - (rws[2 * i] = carry & 8191), - (carry = carry >>> 13), - (rws[2 * i + 1] = carry & 8191), - (carry = carry >>> 13); - for (i = 2 * len; i < N; ++i) rws[i] = 0; - assert(carry === 0), assert((carry & -8192) === 0); - }), - (FFTM.prototype.stub = function (N) { - for (var ph = new Array(N), i = 0; i < N; i++) ph[i] = 0; - return ph; - }), - (FFTM.prototype.mulp = function (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length), - rbt = this.makeRBT(N), - _ = this.stub(N), - rws = new Array(N), - rwst = new Array(N), - iwst = new Array(N), - nrws = new Array(N), - nrwst = new Array(N), - niwst = new Array(N), - rmws = out.words; - (rmws.length = N), - this.convert13b(x.words, x.length, rws, N), - this.convert13b(y.words, y.length, nrws, N), - this.transform(rws, _, rwst, iwst, N, rbt), - this.transform(nrws, _, nrwst, niwst, N, rbt); - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - (iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]), (rwst[i] = rx); - } - return ( - this.conjugate(rwst, iwst, N), - this.transform(rwst, iwst, rmws, _, N, rbt), - this.conjugate(rmws, _, N), - this.normalize13b(rmws, N), - (out.negative = x.negative ^ y.negative), - (out.length = x.length + y.length), - out.strip() - ); - }), - (BN.prototype.mul = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), this.mulTo(num, out); - }), - (BN.prototype.mulf = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), jumboMulTo(this, num, out); - }), - (BN.prototype.imul = function (num) { - return this.clone().mulTo(num, this); - }), - (BN.prototype.imuln = function (num) { - assert(typeof num == "number"), assert(num < 67108864); - for (var carry = 0, i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num, - lo = (w & 67108863) + (carry & 67108863); - (carry >>= 26), (carry += (w / 67108864) | 0), (carry += lo >>> 26), (this.words[i] = lo & 67108863); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.muln = function (num) { - return this.clone().imuln(num); - }), - (BN.prototype.sqr = function () { - return this.mul(this); - }), - (BN.prototype.isqr = function () { - return this.imul(this.clone()); - }), - (BN.prototype.pow = function (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - for (var res = this, i = 0; i < w.length && w[i] === 0; i++, res = res.sqr()); - if (++i < w.length) for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) w[i] !== 0 && (res = res.mul(q)); - return res; - }), - (BN.prototype.iushln = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26, - carryMask = (67108863 >>> (26 - r)) << (26 - r), - i; - if (r !== 0) { - var carry = 0; - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask, - c = ((this.words[i] | 0) - newCarry) << r; - (this.words[i] = c | carry), (carry = newCarry >>> (26 - r)); - } - carry && ((this.words[i] = carry), this.length++); - } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) this.words[i + s] = this.words[i]; - for (i = 0; i < s; i++) this.words[i] = 0; - this.length += s; - } - return this.strip(); - }), - (BN.prototype.ishln = function (bits) { - return assert(this.negative === 0), this.iushln(bits); - }), - (BN.prototype.iushrn = function (bits, hint, extended) { - assert(typeof bits == "number" && bits >= 0); - var h; - hint ? (h = (hint - (hint % 26)) / 26) : (h = 0); - var r = bits % 26, - s = Math.min((bits - r) / 26, this.length), - mask = 67108863 ^ ((67108863 >>> r) << r), - maskedWords = extended; - if (((h -= s), (h = Math.max(0, h)), maskedWords)) { - for (var i = 0; i < s; i++) maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - if (s !== 0) - if (this.length > s) for (this.length -= s, i = 0; i < this.length; i++) this.words[i] = this.words[i + s]; - else (this.words[0] = 0), (this.length = 1); - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - (this.words[i] = (carry << (26 - r)) | (word >>> r)), (carry = word & mask); - } - return ( - maskedWords && carry !== 0 && (maskedWords.words[maskedWords.length++] = carry), - this.length === 0 && ((this.words[0] = 0), (this.length = 1)), - this.strip() - ); - }), - (BN.prototype.ishrn = function (bits, hint, extended) { - return assert(this.negative === 0), this.iushrn(bits, hint, extended); - }), - (BN.prototype.shln = function (bits) { - return this.clone().ishln(bits); - }), - (BN.prototype.ushln = function (bits) { - return this.clone().iushln(bits); - }), - (BN.prototype.shrn = function (bits) { - return this.clone().ishrn(bits); - }), - (BN.prototype.ushrn = function (bits) { - return this.clone().iushrn(bits); - }), - (BN.prototype.testn = function (bit) { - assert(typeof bit == "number" && bit >= 0); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return !1; - var w = this.words[s]; - return !!(w & q); - }), - (BN.prototype.imaskn = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26; - if ((assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)) return this; - if ((r !== 0 && s++, (this.length = Math.min(s, this.length)), r !== 0)) { - var mask = 67108863 ^ ((67108863 >>> r) << r); - this.words[this.length - 1] &= mask; - } - return this.strip(); - }), - (BN.prototype.maskn = function (bits) { - return this.clone().imaskn(bits); - }), - (BN.prototype.iaddn = function (num) { - return ( - assert(typeof num == "number"), - assert(num < 67108864), - num < 0 - ? this.isubn(-num) - : this.negative !== 0 - ? this.length === 1 && (this.words[0] | 0) < num - ? ((this.words[0] = num - (this.words[0] | 0)), (this.negative = 0), this) - : ((this.negative = 0), this.isubn(num), (this.negative = 1), this) - : this._iaddn(num) - ); - }), - (BN.prototype._iaddn = function (num) { - this.words[0] += num; - for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) - (this.words[i] -= 67108864), i === this.length - 1 ? (this.words[i + 1] = 1) : this.words[i + 1]++; - return (this.length = Math.max(this.length, i + 1)), this; - }), - (BN.prototype.isubn = function (num) { - if ((assert(typeof num == "number"), assert(num < 67108864), num < 0)) return this.iaddn(-num); - if (this.negative !== 0) return (this.negative = 0), this.iaddn(num), (this.negative = 1), this; - if (((this.words[0] -= num), this.length === 1 && this.words[0] < 0)) - (this.words[0] = -this.words[0]), (this.negative = 1); - else - for (var i = 0; i < this.length && this.words[i] < 0; i++) - (this.words[i] += 67108864), (this.words[i + 1] -= 1); - return this.strip(); - }), - (BN.prototype.addn = function (num) { - return this.clone().iaddn(num); - }), - (BN.prototype.subn = function (num) { - return this.clone().isubn(num); - }), - (BN.prototype.iabs = function () { - return (this.negative = 0), this; - }), - (BN.prototype.abs = function () { - return this.clone().iabs(); - }), - (BN.prototype._ishlnsubmul = function (num, mul, shift) { - var len = num.length + shift, - i; - this._expand(len); - var w, - carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - (w -= right & 67108863), - (carry = (w >> 26) - ((right / 67108864) | 0)), - (this.words[i + shift] = w & 67108863); - } - for (; i < this.length - shift; i++) - (w = (this.words[i + shift] | 0) + carry), (carry = w >> 26), (this.words[i + shift] = w & 67108863); - if (carry === 0) return this.strip(); - for (assert(carry === -1), carry = 0, i = 0; i < this.length; i++) - (w = -(this.words[i] | 0) + carry), (carry = w >> 26), (this.words[i] = w & 67108863); - return (this.negative = 1), this.strip(); - }), - (BN.prototype._wordDiv = function (num, mode) { - var shift = this.length - num.length, - a = this.clone(), - b = num, - bhi = b.words[b.length - 1] | 0, - bhiBits = this._countBits(bhi); - (shift = 26 - bhiBits), - shift !== 0 && ((b = b.ushln(shift)), a.iushln(shift), (bhi = b.words[b.length - 1] | 0)); - var m = a.length - b.length, - q; - if (mode !== "mod") { - (q = new BN(null)), (q.length = m + 1), (q.words = new Array(q.length)); - for (var i = 0; i < q.length; i++) q.words[i] = 0; - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - diff.negative === 0 && ((a = diff), q && (q.words[m] = 1)); - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); - for (qj = Math.min((qj / bhi) | 0, 67108863), a._ishlnsubmul(b, qj, j); a.negative !== 0; ) - qj--, (a.negative = 0), a._ishlnsubmul(b, 1, j), a.isZero() || (a.negative ^= 1); - q && (q.words[j] = qj); - } - return ( - q && q.strip(), - a.strip(), - mode !== "div" && shift !== 0 && a.iushrn(shift), - { - div: q || null, - mod: a, - } - ); - }), - (BN.prototype.divmod = function (num, mode, positive) { - if ((assert(!num.isZero()), this.isZero())) - return { - div: new BN(0), - mod: new BN(0), - }; - var div, mod, res; - return this.negative !== 0 && num.negative === 0 - ? ((res = this.neg().divmod(num, mode)), - mode !== "mod" && (div = res.div.neg()), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.iadd(num)), - { - div, - mod, - }) - : this.negative === 0 && num.negative !== 0 - ? ((res = this.divmod(num.neg(), mode)), - mode !== "mod" && (div = res.div.neg()), - { - div, - mod: res.mod, - }) - : (this.negative & num.negative) !== 0 - ? ((res = this.neg().divmod(num.neg(), mode)), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.isub(num)), - { - div: res.div, - mod, - }) - : num.length > this.length || this.cmp(num) < 0 - ? { - div: new BN(0), - mod: this, - } - : num.length === 1 - ? mode === "div" - ? { - div: this.divn(num.words[0]), - mod: null, - } - : mode === "mod" - ? { - div: null, - mod: new BN(this.modn(num.words[0])), - } - : { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])), - } - : this._wordDiv(num, mode); - }), - (BN.prototype.div = function (num) { - return this.divmod(num, "div", !1).div; - }), - (BN.prototype.mod = function (num) { - return this.divmod(num, "mod", !1).mod; - }), - (BN.prototype.umod = function (num) { - return this.divmod(num, "mod", !0).mod; - }), - (BN.prototype.divRound = function (num) { - var dm = this.divmod(num); - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, - half = num.ushrn(1), - r2 = num.andln(1), - cmp = mod.cmp(half); - return cmp < 0 || (r2 === 1 && cmp === 0) - ? dm.div - : dm.div.negative !== 0 - ? dm.div.isubn(1) - : dm.div.iaddn(1); - }), - (BN.prototype.modn = function (num) { - assert(num <= 67108863); - for (var p = (1 << 26) % num, acc = 0, i = this.length - 1; i >= 0; i--) - acc = (p * acc + (this.words[i] | 0)) % num; - return acc; - }), - (BN.prototype.idivn = function (num) { - assert(num <= 67108863); - for (var carry = 0, i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 67108864; - (this.words[i] = (w / num) | 0), (carry = w % num); - } - return this.strip(); - }), - (BN.prototype.divn = function (num) { - return this.clone().idivn(num); - }), - (BN.prototype.egcd = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var x = this, - y = p.clone(); - x.negative !== 0 ? (x = x.umod(p)) : (x = x.clone()); - for (var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0; x.isEven() && y.isEven(); ) - x.iushrn(1), y.iushrn(1), ++g; - for (var yp = y.clone(), xp = x.clone(); !x.isZero(); ) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) - for (x.iushrn(i); i-- > 0; ) - (A.isOdd() || B.isOdd()) && (A.iadd(yp), B.isub(xp)), A.iushrn(1), B.iushrn(1); - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) - for (y.iushrn(j); j-- > 0; ) - (C.isOdd() || D.isOdd()) && (C.iadd(yp), D.isub(xp)), C.iushrn(1), D.iushrn(1); - x.cmp(y) >= 0 ? (x.isub(y), A.isub(C), B.isub(D)) : (y.isub(x), C.isub(A), D.isub(B)); - } - return { - a: C, - b: D, - gcd: y.iushln(g), - }; - }), - (BN.prototype._invmp = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var a = this, - b = p.clone(); - a.negative !== 0 ? (a = a.umod(p)) : (a = a.clone()); - for (var x1 = new BN(1), x2 = new BN(0), delta = b.clone(); a.cmpn(1) > 0 && b.cmpn(1) > 0; ) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) for (a.iushrn(i); i-- > 0; ) x1.isOdd() && x1.iadd(delta), x1.iushrn(1); - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) for (b.iushrn(j); j-- > 0; ) x2.isOdd() && x2.iadd(delta), x2.iushrn(1); - a.cmp(b) >= 0 ? (a.isub(b), x1.isub(x2)) : (b.isub(a), x2.isub(x1)); - } - var res; - return a.cmpn(1) === 0 ? (res = x1) : (res = x2), res.cmpn(0) < 0 && res.iadd(p), res; - }), - (BN.prototype.gcd = function (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(), - b = num.clone(); - (a.negative = 0), (b.negative = 0); - for (var shift = 0; a.isEven() && b.isEven(); shift++) a.iushrn(1), b.iushrn(1); - do { - for (; a.isEven(); ) a.iushrn(1); - for (; b.isEven(); ) b.iushrn(1); - var r = a.cmp(b); - if (r < 0) { - var t = a; - (a = b), (b = t); - } else if (r === 0 || b.cmpn(1) === 0) break; - a.isub(b); - } while (!0); - return b.iushln(shift); - }), - (BN.prototype.invm = function (num) { - return this.egcd(num).a.umod(num); - }), - (BN.prototype.isEven = function () { - return (this.words[0] & 1) === 0; - }), - (BN.prototype.isOdd = function () { - return (this.words[0] & 1) === 1; - }), - (BN.prototype.andln = function (num) { - return this.words[0] & num; - }), - (BN.prototype.bincn = function (bit) { - assert(typeof bit == "number"); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return this._expand(s + 1), (this.words[s] |= q), this; - for (var carry = q, i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - (w += carry), (carry = w >>> 26), (w &= 67108863), (this.words[i] = w); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.isZero = function () { - return this.length === 1 && this.words[0] === 0; - }), - (BN.prototype.cmpn = function (num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - this.strip(); - var res; - if (this.length > 1) res = 1; - else { - negative && (num = -num), assert(num <= 67108863, "Number is too big"); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.cmp = function (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.ucmp = function (num) { - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - for (var res = 0, i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0, - b = num.words[i] | 0; - if (a !== b) { - a < b ? (res = -1) : a > b && (res = 1); - break; - } - } - return res; - }), - (BN.prototype.gtn = function (num) { - return this.cmpn(num) === 1; - }), - (BN.prototype.gt = function (num) { - return this.cmp(num) === 1; - }), - (BN.prototype.gten = function (num) { - return this.cmpn(num) >= 0; - }), - (BN.prototype.gte = function (num) { - return this.cmp(num) >= 0; - }), - (BN.prototype.ltn = function (num) { - return this.cmpn(num) === -1; - }), - (BN.prototype.lt = function (num) { - return this.cmp(num) === -1; - }), - (BN.prototype.lten = function (num) { - return this.cmpn(num) <= 0; - }), - (BN.prototype.lte = function (num) { - return this.cmp(num) <= 0; - }), - (BN.prototype.eqn = function (num) { - return this.cmpn(num) === 0; - }), - (BN.prototype.eq = function (num) { - return this.cmp(num) === 0; - }), - (BN.red = function (num) { - return new Red(num); - }), - (BN.prototype.toRed = function (ctx) { - return ( - assert(!this.red, "Already a number in reduction context"), - assert(this.negative === 0, "red works only with positives"), - ctx.convertTo(this)._forceRed(ctx) - ); - }), - (BN.prototype.fromRed = function () { - return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }), - (BN.prototype._forceRed = function (ctx) { - return (this.red = ctx), this; - }), - (BN.prototype.forceRed = function (ctx) { - return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx); - }), - (BN.prototype.redAdd = function (num) { - return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num); - }), - (BN.prototype.redIAdd = function (num) { - return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num); - }), - (BN.prototype.redSub = function (num) { - return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num); - }), - (BN.prototype.redISub = function (num) { - return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num); - }), - (BN.prototype.redShl = function (num) { - return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num); - }), - (BN.prototype.redMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.mul(this, num) - ); - }), - (BN.prototype.redIMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.imul(this, num) - ); - }), - (BN.prototype.redSqr = function () { - return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }), - (BN.prototype.redISqr = function () { - return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }), - (BN.prototype.redSqrt = function () { - return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }), - (BN.prototype.redInvm = function () { - return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); - }), - (BN.prototype.redNeg = function () { - return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); - }), - (BN.prototype.redPow = function (num) { - return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num); - }); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null, - }; - function MPrime(name, p) { - (this.name = name), - (this.p = new BN(p, 16)), - (this.n = this.p.bitLength()), - (this.k = new BN(1).iushln(this.n).isub(this.p)), - (this.tmp = this._tmp()); - } - (MPrime.prototype._tmp = function () { - var tmp = new BN(null); - return (tmp.words = new Array(Math.ceil(this.n / 13))), tmp; - }), - (MPrime.prototype.ireduce = function (num) { - var r = num, - rlen; - do this.split(r, this.tmp), (r = this.imulK(r)), (r = r.iadd(this.tmp)), (rlen = r.bitLength()); - while (rlen > this.n); - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - return ( - cmp === 0 - ? ((r.words[0] = 0), (r.length = 1)) - : cmp > 0 - ? r.isub(this.p) - : r.strip !== void 0 - ? r.strip() - : r._strip(), - r - ); - }), - (MPrime.prototype.split = function (input, out) { - input.iushrn(this.n, 0, out); - }), - (MPrime.prototype.imulK = function (num) { - return num.imul(this.k); - }); - function K256() { - MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - inherits(K256, MPrime), - (K256.prototype.split = function (input, output) { - for (var mask = 4194303, outLen = Math.min(input.length, 9), i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - if (((output.length = outLen), input.length <= 9)) { - (input.words[0] = 0), (input.length = 1); - return; - } - var prev = input.words[9]; - for (output.words[output.length++] = prev & mask, i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - (input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22)), (prev = next); - } - (prev >>>= 22), - (input.words[i - 10] = prev), - prev === 0 && input.length > 10 ? (input.length -= 10) : (input.length -= 9); - }), - (K256.prototype.imulK = function (num) { - (num.words[num.length] = 0), (num.words[num.length + 1] = 0), (num.length += 2); - for (var lo = 0, i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - (lo += w * 977), (num.words[i] = lo & 67108863), (lo = w * 64 + ((lo / 67108864) | 0)); - } - return ( - num.words[num.length - 1] === 0 && (num.length--, num.words[num.length - 1] === 0 && num.length--), num - ); - }); - function P224() { - MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - inherits(P224, MPrime); - function P192() { - MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - inherits(P192, MPrime); - function P25519() { - MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - inherits(P25519, MPrime), - (P25519.prototype.imulK = function (num) { - for (var carry = 0, i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 19 + carry, - lo = hi & 67108863; - (hi >>>= 26), (num.words[i] = lo), (carry = hi); - } - return carry !== 0 && (num.words[num.length++] = carry), num; - }), - (BN._prime = function (name) { - if (primes[name]) return primes[name]; - var prime2; - if (name === "k256") prime2 = new K256(); - else if (name === "p224") prime2 = new P224(); - else if (name === "p192") prime2 = new P192(); - else if (name === "p25519") prime2 = new P25519(); - else throw new Error("Unknown prime " + name); - return (primes[name] = prime2), prime2; - }); - function Red(m) { - if (typeof m == "string") { - var prime = BN._prime(m); - (this.m = prime.p), (this.prime = prime); - } else assert(m.gtn(1), "modulus must be greater than 1"), (this.m = m), (this.prime = null); - } - (Red.prototype._verify1 = function (a) { - assert(a.negative === 0, "red works only with positives"), assert(a.red, "red works only with red numbers"); - }), - (Red.prototype._verify2 = function (a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"), - assert(a.red && a.red === b.red, "red works only with red numbers"); - }), - (Red.prototype.imod = function (a) { - return this.prime ? this.prime.ireduce(a)._forceRed(this) : a.umod(this.m)._forceRed(this); - }), - (Red.prototype.neg = function (a) { - return a.isZero() ? a.clone() : this.m.sub(a)._forceRed(this); - }), - (Red.prototype.add = function (a, b) { - this._verify2(a, b); - var res = a.add(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res._forceRed(this); - }), - (Red.prototype.iadd = function (a, b) { - this._verify2(a, b); - var res = a.iadd(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res; - }), - (Red.prototype.sub = function (a, b) { - this._verify2(a, b); - var res = a.sub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res._forceRed(this); - }), - (Red.prototype.isub = function (a, b) { - this._verify2(a, b); - var res = a.isub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res; - }), - (Red.prototype.shl = function (a, num) { - return this._verify1(a), this.imod(a.ushln(num)); - }), - (Red.prototype.imul = function (a, b) { - return this._verify2(a, b), this.imod(a.imul(b)); - }), - (Red.prototype.mul = function (a, b) { - return this._verify2(a, b), this.imod(a.mul(b)); - }), - (Red.prototype.isqr = function (a) { - return this.imul(a, a.clone()); - }), - (Red.prototype.sqr = function (a) { - return this.mul(a, a); - }), - (Red.prototype.sqrt = function (a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - if ((assert(mod3 % 2 === 1), mod3 === 3)) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - for (var q = this.m.subn(1), s = 0; !q.isZero() && q.andln(1) === 0; ) s++, q.iushrn(1); - assert(!q.isZero()); - var one = new BN(1).toRed(this), - nOne = one.redNeg(), - lpow = this.m.subn(1).iushrn(1), - z = this.m.bitLength(); - for (z = new BN(2 * z * z).toRed(this); this.pow(z, lpow).cmp(nOne) !== 0; ) z.redIAdd(nOne); - for ( - var c = this.pow(z, q), r = this.pow(a, q.addn(1).iushrn(1)), t = this.pow(a, q), m = s; - t.cmp(one) !== 0; - - ) { - for (var tmp = t, i = 0; tmp.cmp(one) !== 0; i++) tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - (r = r.redMul(b)), (c = b.redSqr()), (t = t.redMul(c)), (m = i); - } - return r; - }), - (Red.prototype.invm = function (a) { - var inv = a._invmp(this.m); - return inv.negative !== 0 ? ((inv.negative = 0), this.imod(inv).redNeg()) : this.imod(inv); - }), - (Red.prototype.pow = function (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4, - wnd = new Array(1 << windowSize); - (wnd[0] = new BN(1).toRed(this)), (wnd[1] = a); - for (var i = 2; i < wnd.length; i++) wnd[i] = this.mul(wnd[i - 1], a); - var res = wnd[0], - current = 0, - currentLen = 0, - start = num.bitLength() % 26; - for (start === 0 && (start = 26), i = num.length - 1; i >= 0; i--) { - for (var word = num.words[i], j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if ((res !== wnd[0] && (res = this.sqr(res)), bit === 0 && current === 0)) { - currentLen = 0; - continue; - } - (current <<= 1), - (current |= bit), - currentLen++, - !(currentLen !== windowSize && (i !== 0 || j !== 0)) && - ((res = this.mul(res, wnd[current])), (currentLen = 0), (current = 0)); - } - start = 26; - } - return res; - }), - (Red.prototype.convertTo = function (num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }), - (Red.prototype.convertFrom = function (num) { - var res = num.clone(); - return (res.red = null), res; - }), - (BN.mont = function (num) { - return new Mont(num); - }); - function Mont(m) { - Red.call(this, m), - (this.shift = this.m.bitLength()), - this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), - (this.r = new BN(1).iushln(this.shift)), - (this.r2 = this.imod(this.r.sqr())), - (this.rinv = this.r._invmp(this.m)), - (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), - (this.minv = this.minv.umod(this.r)), - (this.minv = this.r.sub(this.minv)); - } - inherits(Mont, Red), - (Mont.prototype.convertTo = function (num) { - return this.imod(num.ushln(this.shift)); - }), - (Mont.prototype.convertFrom = function (num) { - var r = this.imod(num.mul(this.rinv)); - return (r.red = null), r; - }), - (Mont.prototype.imul = function (a, b) { - if (a.isZero() || b.isZero()) return (a.words[0] = 0), (a.length = 1), a; - var t = a.imul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.mul = function (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.invm = function (a) { - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }); - })(typeof module > "u" || module, exports); - }, -}); - -// node_modules/create-ecdh/browser.js -var require_browser9 = __commonJS({ - "node_modules/create-ecdh/browser.js"(exports, module) { - var elliptic = require_elliptic(), - BN = require_bn6(); - module.exports = function (curve) { - return new ECDH(curve); - }; - var aliases = { - secp256k1: { - name: "secp256k1", - byteLength: 32, - }, - secp224r1: { - name: "p224", - byteLength: 28, - }, - prime256v1: { - name: "p256", - byteLength: 32, - }, - prime192v1: { - name: "p192", - byteLength: 24, - }, - ed25519: { - name: "ed25519", - byteLength: 32, - }, - secp384r1: { - name: "p384", - byteLength: 48, - }, - secp521r1: { - name: "p521", - byteLength: 66, - }, - }; - aliases.p224 = aliases.secp224r1; - aliases.p256 = aliases.secp256r1 = aliases.prime256v1; - aliases.p192 = aliases.secp192r1 = aliases.prime192v1; - aliases.p384 = aliases.secp384r1; - aliases.p521 = aliases.secp521r1; - function ECDH(curve) { - (this.curveType = aliases[curve]), - this.curveType || - (this.curveType = { - name: curve, - }), - (this.curve = new elliptic.ec(this.curveType.name)), - (this.keys = void 0); - } - ECDH.prototype.generateKeys = function (enc, format) { - return (this.keys = this.curve.genKeyPair()), this.getPublicKey(enc, format); - }; - ECDH.prototype.computeSecret = function (other, inenc, enc) { - (inenc = inenc || "utf8"), Buffer.isBuffer(other) || (other = new Buffer(other, inenc)); - var otherPub = this.curve.keyFromPublic(other).getPublic(), - out = otherPub.mul(this.keys.getPrivate()).getX(); - return formatReturnValue(out, enc, this.curveType.byteLength); - }; - ECDH.prototype.getPublicKey = function (enc, format) { - var key = this.keys.getPublic(format === "compressed", !0); - return ( - format === "hybrid" && (key[key.length - 1] % 2 ? (key[0] = 7) : (key[0] = 6)), formatReturnValue(key, enc) - ); - }; - ECDH.prototype.getPrivateKey = function (enc) { - return formatReturnValue(this.keys.getPrivate(), enc); - }; - ECDH.prototype.setPublicKey = function (pub, enc) { - return ( - (enc = enc || "utf8"), Buffer.isBuffer(pub) || (pub = new Buffer(pub, enc)), this.keys._importPublic(pub), this - ); - }; - ECDH.prototype.setPrivateKey = function (priv, enc) { - (enc = enc || "utf8"), Buffer.isBuffer(priv) || (priv = new Buffer(priv, enc)); - var _priv = new BN(priv); - return (_priv = _priv.toString(16)), (this.keys = this.curve.genKeyPair()), this.keys._importPrivate(_priv), this; - }; - function formatReturnValue(bn, enc, len) { - Array.isArray(bn) || (bn = bn.toArray()); - var buf = new Buffer(bn); - if (len && buf.length < len) { - var zeros = new Buffer(len - buf.length); - zeros.fill(0), (buf = Buffer.concat([zeros, buf])); - } - return enc ? buf.toString(enc) : buf; - } - }, -}); - -// node_modules/public-encrypt/mgf.js -var require_mgf = __commonJS({ - "node_modules/public-encrypt/mgf.js"(exports, module) { - var createHash = require_browser2(), - Buffer2 = require_safe_buffer().Buffer; - module.exports = function (seed, len) { - for (var t = Buffer2.alloc(0), i = 0, c; t.length < len; ) - (c = i2ops(i++)), (t = Buffer2.concat([t, createHash("sha1").update(seed).update(c).digest()])); - return t.slice(0, len); - }; - function i2ops(c) { - var out = Buffer2.allocUnsafe(4); - return out.writeUInt32BE(c, 0), out; - } - }, -}); - -// node_modules/public-encrypt/xor.js -var require_xor = __commonJS({ - "node_modules/public-encrypt/xor.js"(exports, module) { - module.exports = function (a, b) { - for (var len = a.length, i = -1; ++i < len; ) a[i] ^= b[i]; - return a; - }; - }, -}); - -// node_modules/public-encrypt/node_modules/bn.js/lib/bn.js -var require_bn7 = __commonJS({ - "node_modules/public-encrypt/node_modules/bn.js/lib/bn.js"(exports, module) { - (function (module2, exports2) { - "use strict"; - function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); - } - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - (TempCtor.prototype = superCtor.prototype), - (ctor.prototype = new TempCtor()), - (ctor.prototype.constructor = ctor); - } - function BN(number, base, endian) { - if (BN.isBN(number)) return number; - (this.negative = 0), - (this.words = null), - (this.length = 0), - (this.red = null), - number !== null && - ((base === "le" || base === "be") && ((endian = base), (base = 10)), - this._init(number || 0, base || 10, endian || "be")); - } - typeof module2 == "object" ? (module2.exports = BN) : (exports2.BN = BN), (BN.BN = BN), (BN.wordSize = 26); - var Buffer2 = globalThis.Buffer; - (BN.isBN = function (num) { - return num instanceof BN - ? !0 - : num !== null && - typeof num == "object" && - num.constructor.wordSize === BN.wordSize && - Array.isArray(num.words); - }), - (BN.max = function (left, right) { - return left.cmp(right) > 0 ? left : right; - }), - (BN.min = function (left, right) { - return left.cmp(right) < 0 ? left : right; - }), - (BN.prototype._init = function (number, base, endian) { - if (typeof number == "number") return this._initNumber(number, base, endian); - if (typeof number == "object") return this._initArray(number, base, endian); - base === "hex" && (base = 16), - assert(base === (base | 0) && base >= 2 && base <= 36), - (number = number.toString().replace(/\s+/g, "")); - var start = 0; - number[0] === "-" && (start++, (this.negative = 1)), - start < number.length && - (base === 16 - ? this._parseHex(number, start, endian) - : (this._parseBase(number, base, start), - endian === "le" && this._initArray(this.toArray(), base, endian))); - }), - (BN.prototype._initNumber = function (number, base, endian) { - number < 0 && ((this.negative = 1), (number = -number)), - number < 67108864 - ? ((this.words = [number & 67108863]), (this.length = 1)) - : number < 4503599627370496 - ? ((this.words = [number & 67108863, (number / 67108864) & 67108863]), (this.length = 2)) - : (assert(number < 9007199254740992), - (this.words = [number & 67108863, (number / 67108864) & 67108863, 1]), - (this.length = 3)), - endian === "le" && this._initArray(this.toArray(), base, endian); - }), - (BN.prototype._initArray = function (number, base, endian) { - if ((assert(typeof number.length == "number"), number.length <= 0)) - return (this.words = [0]), (this.length = 1), this; - (this.length = Math.ceil(number.length / 3)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var j, - w, - off = 0; - if (endian === "be") - for (i = number.length - 1, j = 0; i >= 0; i -= 3) - (w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - else if (endian === "le") - for (i = 0, j = 0; i < number.length; i += 3) - (w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16)), - (this.words[j] |= (w << off) & 67108863), - (this.words[j + 1] = (w >>> (26 - off)) & 67108863), - (off += 24), - off >= 26 && ((off -= 26), j++); - return this.strip(); - }); - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - return c >= 65 && c <= 70 ? c - 55 : c >= 97 && c <= 102 ? c - 87 : (c - 48) & 15; - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - return index - 1 >= lowerBound && (r |= parseHex4Bits(string, index - 1) << 4), r; - } - BN.prototype._parseHex = function (number, start, endian) { - (this.length = Math.ceil((number.length - start) / 6)), (this.words = new Array(this.length)); - for (var i = 0; i < this.length; i++) this.words[i] = 0; - var off = 0, - j = 0, - w; - if (endian === "be") - for (i = number.length - 1; i >= start; i -= 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) - (w = parseHexByte(number, start, i) << off), - (this.words[j] |= w & 67108863), - off >= 18 ? ((off -= 18), (j += 1), (this.words[j] |= w >>> 26)) : (off += 8); - } - this.strip(); - }; - function parseBase(str, start, end, mul) { - for (var r = 0, len = Math.min(str.length, end), i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - (r *= mul), c >= 49 ? (r += c - 49 + 10) : c >= 17 ? (r += c - 17 + 10) : (r += c); - } - return r; - } - (BN.prototype._parseBase = function (number, base, start) { - (this.words = [0]), (this.length = 1); - for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base) limbLen++; - limbLen--, (limbPow = (limbPow / base) | 0); - for ( - var total = number.length - start, - mod = total % limbLen, - end = Math.min(total, total - mod) + start, - word = 0, - i = start; - i < end; - i += limbLen - ) - (word = parseBase(number, i, i + limbLen, base)), - this.imuln(limbPow), - this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - if (mod !== 0) { - var pow = 1; - for (word = parseBase(number, i, number.length, base), i = 0; i < mod; i++) pow *= base; - this.imuln(pow), this.words[0] + word < 67108864 ? (this.words[0] += word) : this._iaddn(word); - } - this.strip(); - }), - (BN.prototype.copy = function (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) dest.words[i] = this.words[i]; - (dest.length = this.length), (dest.negative = this.negative), (dest.red = this.red); - }), - (BN.prototype.clone = function () { - var r = new BN(null); - return this.copy(r), r; - }), - (BN.prototype._expand = function (size) { - for (; this.length < size; ) this.words[this.length++] = 0; - return this; - }), - (BN.prototype.strip = function () { - for (; this.length > 1 && this.words[this.length - 1] === 0; ) this.length--; - return this._normSign(); - }), - (BN.prototype._normSign = function () { - return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; - }), - (BN.prototype.inspect = function () { - return (this.red ? ""; - }); - var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000", - ], - groupSizes = [ - 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, - ], - groupBases = [ - 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, - 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, - 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, - 60466176, - ]; - (BN.prototype.toString = function (base, padding) { - (base = base || 10), (padding = padding | 0 || 1); - var out; - if (base === 16 || base === "hex") { - out = ""; - for (var off = 0, carry = 0, i = 0; i < this.length; i++) { - var w = this.words[i], - word = (((w << off) | carry) & 16777215).toString(16); - (carry = (w >>> (24 - off)) & 16777215), - carry !== 0 || i !== this.length - 1 ? (out = zeros[6 - word.length] + word + out) : (out = word + out), - (off += 2), - off >= 26 && ((off -= 26), i--); - } - for (carry !== 0 && (out = carry.toString(16) + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - if (base === (base | 0) && base >= 2 && base <= 36) { - var groupSize = groupSizes[base], - groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - for (c.negative = 0; !c.isZero(); ) { - var r = c.modn(groupBase).toString(base); - (c = c.idivn(groupBase)), c.isZero() ? (out = r + out) : (out = zeros[groupSize - r.length] + r + out); - } - for (this.isZero() && (out = "0" + out); out.length % padding !== 0; ) out = "0" + out; - return this.negative !== 0 && (out = "-" + out), out; - } - assert(!1, "Base should be between 2 and 36"); - }), - (BN.prototype.toNumber = function () { - var ret = this.words[0]; - return ( - this.length === 2 - ? (ret += this.words[1] * 67108864) - : this.length === 3 && this.words[2] === 1 - ? (ret += 4503599627370496 + this.words[1] * 67108864) - : this.length > 2 && assert(!1, "Number can only safely store up to 53 bits"), - this.negative !== 0 ? -ret : ret - ); - }), - (BN.prototype.toJSON = function () { - return this.toString(16); - }), - (BN.prototype.toBuffer = function (endian, length) { - return assert(typeof Buffer2 < "u"), this.toArrayLike(Buffer2, endian, length); - }), - (BN.prototype.toArray = function (endian, length) { - return this.toArrayLike(Array, endian, length); - }), - (BN.prototype.toArrayLike = function (ArrayType, endian, length) { - var byteLength = this.byteLength(), - reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"), - assert(reqLength > 0, "Requested array length <= 0"), - this.strip(); - var littleEndian = endian === "le", - res = new ArrayType(reqLength), - b, - i, - q = this.clone(); - if (littleEndian) { - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[i] = b); - for (; i < reqLength; i++) res[i] = 0; - } else { - for (i = 0; i < reqLength - byteLength; i++) res[i] = 0; - for (i = 0; !q.isZero(); i++) (b = q.andln(255)), q.iushrn(8), (res[reqLength - i - 1] = b); - } - return res; - }), - Math.clz32 - ? (BN.prototype._countBits = function (w) { - return 32 - Math.clz32(w); - }) - : (BN.prototype._countBits = function (w) { - var t = w, - r = 0; - return ( - t >= 4096 && ((r += 13), (t >>>= 13)), - t >= 64 && ((r += 7), (t >>>= 7)), - t >= 8 && ((r += 4), (t >>>= 4)), - t >= 2 && ((r += 2), (t >>>= 2)), - r + t - ); - }), - (BN.prototype._zeroBits = function (w) { - if (w === 0) return 26; - var t = w, - r = 0; - return ( - (t & 8191) === 0 && ((r += 13), (t >>>= 13)), - (t & 127) === 0 && ((r += 7), (t >>>= 7)), - (t & 15) === 0 && ((r += 4), (t >>>= 4)), - (t & 3) === 0 && ((r += 2), (t >>>= 2)), - (t & 1) === 0 && r++, - r - ); - }), - (BN.prototype.bitLength = function () { - var w = this.words[this.length - 1], - hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }); - function toBitArray(num) { - for (var w = new Array(num.bitLength()), bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0, - wbit = bit % 26; - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - return w; - } - (BN.prototype.zeroBits = function () { - if (this.isZero()) return 0; - for (var r = 0, i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - if (((r += b), b !== 26)) break; - } - return r; - }), - (BN.prototype.byteLength = function () { - return Math.ceil(this.bitLength() / 8); - }), - (BN.prototype.toTwos = function (width) { - return this.negative !== 0 ? this.abs().inotn(width).iaddn(1) : this.clone(); - }), - (BN.prototype.fromTwos = function (width) { - return this.testn(width - 1) ? this.notn(width).iaddn(1).ineg() : this.clone(); - }), - (BN.prototype.isNeg = function () { - return this.negative !== 0; - }), - (BN.prototype.neg = function () { - return this.clone().ineg(); - }), - (BN.prototype.ineg = function () { - return this.isZero() || (this.negative ^= 1), this; - }), - (BN.prototype.iuor = function (num) { - for (; this.length < num.length; ) this.words[this.length++] = 0; - for (var i = 0; i < num.length; i++) this.words[i] = this.words[i] | num.words[i]; - return this.strip(); - }), - (BN.prototype.ior = function (num) { - return assert((this.negative | num.negative) === 0), this.iuor(num); - }), - (BN.prototype.or = function (num) { - return this.length > num.length ? this.clone().ior(num) : num.clone().ior(this); - }), - (BN.prototype.uor = function (num) { - return this.length > num.length ? this.clone().iuor(num) : num.clone().iuor(this); - }), - (BN.prototype.iuand = function (num) { - var b; - this.length > num.length ? (b = num) : (b = this); - for (var i = 0; i < b.length; i++) this.words[i] = this.words[i] & num.words[i]; - return (this.length = b.length), this.strip(); - }), - (BN.prototype.iand = function (num) { - return assert((this.negative | num.negative) === 0), this.iuand(num); - }), - (BN.prototype.and = function (num) { - return this.length > num.length ? this.clone().iand(num) : num.clone().iand(this); - }), - (BN.prototype.uand = function (num) { - return this.length > num.length ? this.clone().iuand(num) : num.clone().iuand(this); - }), - (BN.prototype.iuxor = function (num) { - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var i = 0; i < b.length; i++) this.words[i] = a.words[i] ^ b.words[i]; - if (this !== a) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = a.length), this.strip(); - }), - (BN.prototype.ixor = function (num) { - return assert((this.negative | num.negative) === 0), this.iuxor(num); - }), - (BN.prototype.xor = function (num) { - return this.length > num.length ? this.clone().ixor(num) : num.clone().ixor(this); - }), - (BN.prototype.uxor = function (num) { - return this.length > num.length ? this.clone().iuxor(num) : num.clone().iuxor(this); - }), - (BN.prototype.inotn = function (width) { - assert(typeof width == "number" && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0, - bitsLeft = width % 26; - this._expand(bytesNeeded), bitsLeft > 0 && bytesNeeded--; - for (var i = 0; i < bytesNeeded; i++) this.words[i] = ~this.words[i] & 67108863; - return bitsLeft > 0 && (this.words[i] = ~this.words[i] & (67108863 >> (26 - bitsLeft))), this.strip(); - }), - (BN.prototype.notn = function (width) { - return this.clone().inotn(width); - }), - (BN.prototype.setn = function (bit, val) { - assert(typeof bit == "number" && bit >= 0); - var off = (bit / 26) | 0, - wbit = bit % 26; - return ( - this._expand(off + 1), - val - ? (this.words[off] = this.words[off] | (1 << wbit)) - : (this.words[off] = this.words[off] & ~(1 << wbit)), - this.strip() - ); - }), - (BN.prototype.iadd = function (num) { - var r; - if (this.negative !== 0 && num.negative === 0) - return (this.negative = 0), (r = this.isub(num)), (this.negative ^= 1), this._normSign(); - if (this.negative === 0 && num.negative !== 0) - return (num.negative = 0), (r = this.isub(num)), (num.negative = 1), r._normSign(); - var a, b; - this.length > num.length ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) + (b.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (this.words[i] = r & 67108863), (carry = r >>> 26); - if (((this.length = a.length), carry !== 0)) (this.words[this.length] = carry), this.length++; - else if (a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return this; - }), - (BN.prototype.add = function (num) { - var res; - return num.negative !== 0 && this.negative === 0 - ? ((num.negative = 0), (res = this.sub(num)), (num.negative ^= 1), res) - : num.negative === 0 && this.negative !== 0 - ? ((this.negative = 0), (res = num.sub(this)), (this.negative = 1), res) - : this.length > num.length - ? this.clone().iadd(num) - : num.clone().iadd(this); - }), - (BN.prototype.isub = function (num) { - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - return (num.negative = 1), r._normSign(); - } else if (this.negative !== 0) - return (this.negative = 0), this.iadd(num), (this.negative = 1), this._normSign(); - var cmp = this.cmp(num); - if (cmp === 0) return (this.negative = 0), (this.length = 1), (this.words[0] = 0), this; - var a, b; - cmp > 0 ? ((a = this), (b = num)) : ((a = num), (b = this)); - for (var carry = 0, i = 0; i < b.length; i++) - (r = (a.words[i] | 0) - (b.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - for (; carry !== 0 && i < a.length; i++) - (r = (a.words[i] | 0) + carry), (carry = r >> 26), (this.words[i] = r & 67108863); - if (carry === 0 && i < a.length && a !== this) for (; i < a.length; i++) this.words[i] = a.words[i]; - return (this.length = Math.max(this.length, i)), a !== this && (this.negative = 1), this.strip(); - }), - (BN.prototype.sub = function (num) { - return this.clone().isub(num); - }); - function smallMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - var len = (self2.length + num.length) | 0; - (out.length = len), (len = (len - 1) | 0); - var a = self2.words[0] | 0, - b = num.words[0] | 0, - r = a * b, - lo = r & 67108863, - carry = (r / 67108864) | 0; - out.words[0] = lo; - for (var k = 1; k < len; k++) { - for ( - var ncarry = carry >>> 26, - rword = carry & 67108863, - maxJ = Math.min(k, num.length - 1), - j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = (k - j) | 0; - (a = self2.words[i] | 0), - (b = num.words[j] | 0), - (r = a * b + rword), - (ncarry += (r / 67108864) | 0), - (rword = r & 67108863); - } - (out.words[k] = rword | 0), (carry = ncarry | 0); - } - return carry !== 0 ? (out.words[k] = carry | 0) : out.length--, out.strip(); - } - var comb10MulTo = function (self2, num, out) { - var a = self2.words, - b = num.words, - o = out.words, - c = 0, - lo, - mid, - hi, - a0 = a[0] | 0, - al0 = a0 & 8191, - ah0 = a0 >>> 13, - a1 = a[1] | 0, - al1 = a1 & 8191, - ah1 = a1 >>> 13, - a2 = a[2] | 0, - al2 = a2 & 8191, - ah2 = a2 >>> 13, - a3 = a[3] | 0, - al3 = a3 & 8191, - ah3 = a3 >>> 13, - a4 = a[4] | 0, - al4 = a4 & 8191, - ah4 = a4 >>> 13, - a5 = a[5] | 0, - al5 = a5 & 8191, - ah5 = a5 >>> 13, - a6 = a[6] | 0, - al6 = a6 & 8191, - ah6 = a6 >>> 13, - a7 = a[7] | 0, - al7 = a7 & 8191, - ah7 = a7 >>> 13, - a8 = a[8] | 0, - al8 = a8 & 8191, - ah8 = a8 >>> 13, - a9 = a[9] | 0, - al9 = a9 & 8191, - ah9 = a9 >>> 13, - b0 = b[0] | 0, - bl0 = b0 & 8191, - bh0 = b0 >>> 13, - b1 = b[1] | 0, - bl1 = b1 & 8191, - bh1 = b1 >>> 13, - b2 = b[2] | 0, - bl2 = b2 & 8191, - bh2 = b2 >>> 13, - b3 = b[3] | 0, - bl3 = b3 & 8191, - bh3 = b3 >>> 13, - b4 = b[4] | 0, - bl4 = b4 & 8191, - bh4 = b4 >>> 13, - b5 = b[5] | 0, - bl5 = b5 & 8191, - bh5 = b5 >>> 13, - b6 = b[6] | 0, - bl6 = b6 & 8191, - bh6 = b6 >>> 13, - b7 = b[7] | 0, - bl7 = b7 & 8191, - bh7 = b7 >>> 13, - b8 = b[8] | 0, - bl8 = b8 & 8191, - bh8 = b8 >>> 13, - b9 = b[9] | 0, - bl9 = b9 & 8191, - bh9 = b9 >>> 13; - (out.negative = self2.negative ^ num.negative), - (out.length = 19), - (lo = Math.imul(al0, bl0)), - (mid = Math.imul(al0, bh0)), - (mid = (mid + Math.imul(ah0, bl0)) | 0), - (hi = Math.imul(ah0, bh0)); - var w0 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0), - (w0 &= 67108863), - (lo = Math.imul(al1, bl0)), - (mid = Math.imul(al1, bh0)), - (mid = (mid + Math.imul(ah1, bl0)) | 0), - (hi = Math.imul(ah1, bh0)), - (lo = (lo + Math.imul(al0, bl1)) | 0), - (mid = (mid + Math.imul(al0, bh1)) | 0), - (mid = (mid + Math.imul(ah0, bl1)) | 0), - (hi = (hi + Math.imul(ah0, bh1)) | 0); - var w1 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0), - (w1 &= 67108863), - (lo = Math.imul(al2, bl0)), - (mid = Math.imul(al2, bh0)), - (mid = (mid + Math.imul(ah2, bl0)) | 0), - (hi = Math.imul(ah2, bh0)), - (lo = (lo + Math.imul(al1, bl1)) | 0), - (mid = (mid + Math.imul(al1, bh1)) | 0), - (mid = (mid + Math.imul(ah1, bl1)) | 0), - (hi = (hi + Math.imul(ah1, bh1)) | 0), - (lo = (lo + Math.imul(al0, bl2)) | 0), - (mid = (mid + Math.imul(al0, bh2)) | 0), - (mid = (mid + Math.imul(ah0, bl2)) | 0), - (hi = (hi + Math.imul(ah0, bh2)) | 0); - var w2 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0), - (w2 &= 67108863), - (lo = Math.imul(al3, bl0)), - (mid = Math.imul(al3, bh0)), - (mid = (mid + Math.imul(ah3, bl0)) | 0), - (hi = Math.imul(ah3, bh0)), - (lo = (lo + Math.imul(al2, bl1)) | 0), - (mid = (mid + Math.imul(al2, bh1)) | 0), - (mid = (mid + Math.imul(ah2, bl1)) | 0), - (hi = (hi + Math.imul(ah2, bh1)) | 0), - (lo = (lo + Math.imul(al1, bl2)) | 0), - (mid = (mid + Math.imul(al1, bh2)) | 0), - (mid = (mid + Math.imul(ah1, bl2)) | 0), - (hi = (hi + Math.imul(ah1, bh2)) | 0), - (lo = (lo + Math.imul(al0, bl3)) | 0), - (mid = (mid + Math.imul(al0, bh3)) | 0), - (mid = (mid + Math.imul(ah0, bl3)) | 0), - (hi = (hi + Math.imul(ah0, bh3)) | 0); - var w3 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0), - (w3 &= 67108863), - (lo = Math.imul(al4, bl0)), - (mid = Math.imul(al4, bh0)), - (mid = (mid + Math.imul(ah4, bl0)) | 0), - (hi = Math.imul(ah4, bh0)), - (lo = (lo + Math.imul(al3, bl1)) | 0), - (mid = (mid + Math.imul(al3, bh1)) | 0), - (mid = (mid + Math.imul(ah3, bl1)) | 0), - (hi = (hi + Math.imul(ah3, bh1)) | 0), - (lo = (lo + Math.imul(al2, bl2)) | 0), - (mid = (mid + Math.imul(al2, bh2)) | 0), - (mid = (mid + Math.imul(ah2, bl2)) | 0), - (hi = (hi + Math.imul(ah2, bh2)) | 0), - (lo = (lo + Math.imul(al1, bl3)) | 0), - (mid = (mid + Math.imul(al1, bh3)) | 0), - (mid = (mid + Math.imul(ah1, bl3)) | 0), - (hi = (hi + Math.imul(ah1, bh3)) | 0), - (lo = (lo + Math.imul(al0, bl4)) | 0), - (mid = (mid + Math.imul(al0, bh4)) | 0), - (mid = (mid + Math.imul(ah0, bl4)) | 0), - (hi = (hi + Math.imul(ah0, bh4)) | 0); - var w4 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0), - (w4 &= 67108863), - (lo = Math.imul(al5, bl0)), - (mid = Math.imul(al5, bh0)), - (mid = (mid + Math.imul(ah5, bl0)) | 0), - (hi = Math.imul(ah5, bh0)), - (lo = (lo + Math.imul(al4, bl1)) | 0), - (mid = (mid + Math.imul(al4, bh1)) | 0), - (mid = (mid + Math.imul(ah4, bl1)) | 0), - (hi = (hi + Math.imul(ah4, bh1)) | 0), - (lo = (lo + Math.imul(al3, bl2)) | 0), - (mid = (mid + Math.imul(al3, bh2)) | 0), - (mid = (mid + Math.imul(ah3, bl2)) | 0), - (hi = (hi + Math.imul(ah3, bh2)) | 0), - (lo = (lo + Math.imul(al2, bl3)) | 0), - (mid = (mid + Math.imul(al2, bh3)) | 0), - (mid = (mid + Math.imul(ah2, bl3)) | 0), - (hi = (hi + Math.imul(ah2, bh3)) | 0), - (lo = (lo + Math.imul(al1, bl4)) | 0), - (mid = (mid + Math.imul(al1, bh4)) | 0), - (mid = (mid + Math.imul(ah1, bl4)) | 0), - (hi = (hi + Math.imul(ah1, bh4)) | 0), - (lo = (lo + Math.imul(al0, bl5)) | 0), - (mid = (mid + Math.imul(al0, bh5)) | 0), - (mid = (mid + Math.imul(ah0, bl5)) | 0), - (hi = (hi + Math.imul(ah0, bh5)) | 0); - var w5 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0), - (w5 &= 67108863), - (lo = Math.imul(al6, bl0)), - (mid = Math.imul(al6, bh0)), - (mid = (mid + Math.imul(ah6, bl0)) | 0), - (hi = Math.imul(ah6, bh0)), - (lo = (lo + Math.imul(al5, bl1)) | 0), - (mid = (mid + Math.imul(al5, bh1)) | 0), - (mid = (mid + Math.imul(ah5, bl1)) | 0), - (hi = (hi + Math.imul(ah5, bh1)) | 0), - (lo = (lo + Math.imul(al4, bl2)) | 0), - (mid = (mid + Math.imul(al4, bh2)) | 0), - (mid = (mid + Math.imul(ah4, bl2)) | 0), - (hi = (hi + Math.imul(ah4, bh2)) | 0), - (lo = (lo + Math.imul(al3, bl3)) | 0), - (mid = (mid + Math.imul(al3, bh3)) | 0), - (mid = (mid + Math.imul(ah3, bl3)) | 0), - (hi = (hi + Math.imul(ah3, bh3)) | 0), - (lo = (lo + Math.imul(al2, bl4)) | 0), - (mid = (mid + Math.imul(al2, bh4)) | 0), - (mid = (mid + Math.imul(ah2, bl4)) | 0), - (hi = (hi + Math.imul(ah2, bh4)) | 0), - (lo = (lo + Math.imul(al1, bl5)) | 0), - (mid = (mid + Math.imul(al1, bh5)) | 0), - (mid = (mid + Math.imul(ah1, bl5)) | 0), - (hi = (hi + Math.imul(ah1, bh5)) | 0), - (lo = (lo + Math.imul(al0, bl6)) | 0), - (mid = (mid + Math.imul(al0, bh6)) | 0), - (mid = (mid + Math.imul(ah0, bl6)) | 0), - (hi = (hi + Math.imul(ah0, bh6)) | 0); - var w6 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0), - (w6 &= 67108863), - (lo = Math.imul(al7, bl0)), - (mid = Math.imul(al7, bh0)), - (mid = (mid + Math.imul(ah7, bl0)) | 0), - (hi = Math.imul(ah7, bh0)), - (lo = (lo + Math.imul(al6, bl1)) | 0), - (mid = (mid + Math.imul(al6, bh1)) | 0), - (mid = (mid + Math.imul(ah6, bl1)) | 0), - (hi = (hi + Math.imul(ah6, bh1)) | 0), - (lo = (lo + Math.imul(al5, bl2)) | 0), - (mid = (mid + Math.imul(al5, bh2)) | 0), - (mid = (mid + Math.imul(ah5, bl2)) | 0), - (hi = (hi + Math.imul(ah5, bh2)) | 0), - (lo = (lo + Math.imul(al4, bl3)) | 0), - (mid = (mid + Math.imul(al4, bh3)) | 0), - (mid = (mid + Math.imul(ah4, bl3)) | 0), - (hi = (hi + Math.imul(ah4, bh3)) | 0), - (lo = (lo + Math.imul(al3, bl4)) | 0), - (mid = (mid + Math.imul(al3, bh4)) | 0), - (mid = (mid + Math.imul(ah3, bl4)) | 0), - (hi = (hi + Math.imul(ah3, bh4)) | 0), - (lo = (lo + Math.imul(al2, bl5)) | 0), - (mid = (mid + Math.imul(al2, bh5)) | 0), - (mid = (mid + Math.imul(ah2, bl5)) | 0), - (hi = (hi + Math.imul(ah2, bh5)) | 0), - (lo = (lo + Math.imul(al1, bl6)) | 0), - (mid = (mid + Math.imul(al1, bh6)) | 0), - (mid = (mid + Math.imul(ah1, bl6)) | 0), - (hi = (hi + Math.imul(ah1, bh6)) | 0), - (lo = (lo + Math.imul(al0, bl7)) | 0), - (mid = (mid + Math.imul(al0, bh7)) | 0), - (mid = (mid + Math.imul(ah0, bl7)) | 0), - (hi = (hi + Math.imul(ah0, bh7)) | 0); - var w7 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0), - (w7 &= 67108863), - (lo = Math.imul(al8, bl0)), - (mid = Math.imul(al8, bh0)), - (mid = (mid + Math.imul(ah8, bl0)) | 0), - (hi = Math.imul(ah8, bh0)), - (lo = (lo + Math.imul(al7, bl1)) | 0), - (mid = (mid + Math.imul(al7, bh1)) | 0), - (mid = (mid + Math.imul(ah7, bl1)) | 0), - (hi = (hi + Math.imul(ah7, bh1)) | 0), - (lo = (lo + Math.imul(al6, bl2)) | 0), - (mid = (mid + Math.imul(al6, bh2)) | 0), - (mid = (mid + Math.imul(ah6, bl2)) | 0), - (hi = (hi + Math.imul(ah6, bh2)) | 0), - (lo = (lo + Math.imul(al5, bl3)) | 0), - (mid = (mid + Math.imul(al5, bh3)) | 0), - (mid = (mid + Math.imul(ah5, bl3)) | 0), - (hi = (hi + Math.imul(ah5, bh3)) | 0), - (lo = (lo + Math.imul(al4, bl4)) | 0), - (mid = (mid + Math.imul(al4, bh4)) | 0), - (mid = (mid + Math.imul(ah4, bl4)) | 0), - (hi = (hi + Math.imul(ah4, bh4)) | 0), - (lo = (lo + Math.imul(al3, bl5)) | 0), - (mid = (mid + Math.imul(al3, bh5)) | 0), - (mid = (mid + Math.imul(ah3, bl5)) | 0), - (hi = (hi + Math.imul(ah3, bh5)) | 0), - (lo = (lo + Math.imul(al2, bl6)) | 0), - (mid = (mid + Math.imul(al2, bh6)) | 0), - (mid = (mid + Math.imul(ah2, bl6)) | 0), - (hi = (hi + Math.imul(ah2, bh6)) | 0), - (lo = (lo + Math.imul(al1, bl7)) | 0), - (mid = (mid + Math.imul(al1, bh7)) | 0), - (mid = (mid + Math.imul(ah1, bl7)) | 0), - (hi = (hi + Math.imul(ah1, bh7)) | 0), - (lo = (lo + Math.imul(al0, bl8)) | 0), - (mid = (mid + Math.imul(al0, bh8)) | 0), - (mid = (mid + Math.imul(ah0, bl8)) | 0), - (hi = (hi + Math.imul(ah0, bh8)) | 0); - var w8 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0), - (w8 &= 67108863), - (lo = Math.imul(al9, bl0)), - (mid = Math.imul(al9, bh0)), - (mid = (mid + Math.imul(ah9, bl0)) | 0), - (hi = Math.imul(ah9, bh0)), - (lo = (lo + Math.imul(al8, bl1)) | 0), - (mid = (mid + Math.imul(al8, bh1)) | 0), - (mid = (mid + Math.imul(ah8, bl1)) | 0), - (hi = (hi + Math.imul(ah8, bh1)) | 0), - (lo = (lo + Math.imul(al7, bl2)) | 0), - (mid = (mid + Math.imul(al7, bh2)) | 0), - (mid = (mid + Math.imul(ah7, bl2)) | 0), - (hi = (hi + Math.imul(ah7, bh2)) | 0), - (lo = (lo + Math.imul(al6, bl3)) | 0), - (mid = (mid + Math.imul(al6, bh3)) | 0), - (mid = (mid + Math.imul(ah6, bl3)) | 0), - (hi = (hi + Math.imul(ah6, bh3)) | 0), - (lo = (lo + Math.imul(al5, bl4)) | 0), - (mid = (mid + Math.imul(al5, bh4)) | 0), - (mid = (mid + Math.imul(ah5, bl4)) | 0), - (hi = (hi + Math.imul(ah5, bh4)) | 0), - (lo = (lo + Math.imul(al4, bl5)) | 0), - (mid = (mid + Math.imul(al4, bh5)) | 0), - (mid = (mid + Math.imul(ah4, bl5)) | 0), - (hi = (hi + Math.imul(ah4, bh5)) | 0), - (lo = (lo + Math.imul(al3, bl6)) | 0), - (mid = (mid + Math.imul(al3, bh6)) | 0), - (mid = (mid + Math.imul(ah3, bl6)) | 0), - (hi = (hi + Math.imul(ah3, bh6)) | 0), - (lo = (lo + Math.imul(al2, bl7)) | 0), - (mid = (mid + Math.imul(al2, bh7)) | 0), - (mid = (mid + Math.imul(ah2, bl7)) | 0), - (hi = (hi + Math.imul(ah2, bh7)) | 0), - (lo = (lo + Math.imul(al1, bl8)) | 0), - (mid = (mid + Math.imul(al1, bh8)) | 0), - (mid = (mid + Math.imul(ah1, bl8)) | 0), - (hi = (hi + Math.imul(ah1, bh8)) | 0), - (lo = (lo + Math.imul(al0, bl9)) | 0), - (mid = (mid + Math.imul(al0, bh9)) | 0), - (mid = (mid + Math.imul(ah0, bl9)) | 0), - (hi = (hi + Math.imul(ah0, bh9)) | 0); - var w9 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0), - (w9 &= 67108863), - (lo = Math.imul(al9, bl1)), - (mid = Math.imul(al9, bh1)), - (mid = (mid + Math.imul(ah9, bl1)) | 0), - (hi = Math.imul(ah9, bh1)), - (lo = (lo + Math.imul(al8, bl2)) | 0), - (mid = (mid + Math.imul(al8, bh2)) | 0), - (mid = (mid + Math.imul(ah8, bl2)) | 0), - (hi = (hi + Math.imul(ah8, bh2)) | 0), - (lo = (lo + Math.imul(al7, bl3)) | 0), - (mid = (mid + Math.imul(al7, bh3)) | 0), - (mid = (mid + Math.imul(ah7, bl3)) | 0), - (hi = (hi + Math.imul(ah7, bh3)) | 0), - (lo = (lo + Math.imul(al6, bl4)) | 0), - (mid = (mid + Math.imul(al6, bh4)) | 0), - (mid = (mid + Math.imul(ah6, bl4)) | 0), - (hi = (hi + Math.imul(ah6, bh4)) | 0), - (lo = (lo + Math.imul(al5, bl5)) | 0), - (mid = (mid + Math.imul(al5, bh5)) | 0), - (mid = (mid + Math.imul(ah5, bl5)) | 0), - (hi = (hi + Math.imul(ah5, bh5)) | 0), - (lo = (lo + Math.imul(al4, bl6)) | 0), - (mid = (mid + Math.imul(al4, bh6)) | 0), - (mid = (mid + Math.imul(ah4, bl6)) | 0), - (hi = (hi + Math.imul(ah4, bh6)) | 0), - (lo = (lo + Math.imul(al3, bl7)) | 0), - (mid = (mid + Math.imul(al3, bh7)) | 0), - (mid = (mid + Math.imul(ah3, bl7)) | 0), - (hi = (hi + Math.imul(ah3, bh7)) | 0), - (lo = (lo + Math.imul(al2, bl8)) | 0), - (mid = (mid + Math.imul(al2, bh8)) | 0), - (mid = (mid + Math.imul(ah2, bl8)) | 0), - (hi = (hi + Math.imul(ah2, bh8)) | 0), - (lo = (lo + Math.imul(al1, bl9)) | 0), - (mid = (mid + Math.imul(al1, bh9)) | 0), - (mid = (mid + Math.imul(ah1, bl9)) | 0), - (hi = (hi + Math.imul(ah1, bh9)) | 0); - var w10 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0), - (w10 &= 67108863), - (lo = Math.imul(al9, bl2)), - (mid = Math.imul(al9, bh2)), - (mid = (mid + Math.imul(ah9, bl2)) | 0), - (hi = Math.imul(ah9, bh2)), - (lo = (lo + Math.imul(al8, bl3)) | 0), - (mid = (mid + Math.imul(al8, bh3)) | 0), - (mid = (mid + Math.imul(ah8, bl3)) | 0), - (hi = (hi + Math.imul(ah8, bh3)) | 0), - (lo = (lo + Math.imul(al7, bl4)) | 0), - (mid = (mid + Math.imul(al7, bh4)) | 0), - (mid = (mid + Math.imul(ah7, bl4)) | 0), - (hi = (hi + Math.imul(ah7, bh4)) | 0), - (lo = (lo + Math.imul(al6, bl5)) | 0), - (mid = (mid + Math.imul(al6, bh5)) | 0), - (mid = (mid + Math.imul(ah6, bl5)) | 0), - (hi = (hi + Math.imul(ah6, bh5)) | 0), - (lo = (lo + Math.imul(al5, bl6)) | 0), - (mid = (mid + Math.imul(al5, bh6)) | 0), - (mid = (mid + Math.imul(ah5, bl6)) | 0), - (hi = (hi + Math.imul(ah5, bh6)) | 0), - (lo = (lo + Math.imul(al4, bl7)) | 0), - (mid = (mid + Math.imul(al4, bh7)) | 0), - (mid = (mid + Math.imul(ah4, bl7)) | 0), - (hi = (hi + Math.imul(ah4, bh7)) | 0), - (lo = (lo + Math.imul(al3, bl8)) | 0), - (mid = (mid + Math.imul(al3, bh8)) | 0), - (mid = (mid + Math.imul(ah3, bl8)) | 0), - (hi = (hi + Math.imul(ah3, bh8)) | 0), - (lo = (lo + Math.imul(al2, bl9)) | 0), - (mid = (mid + Math.imul(al2, bh9)) | 0), - (mid = (mid + Math.imul(ah2, bl9)) | 0), - (hi = (hi + Math.imul(ah2, bh9)) | 0); - var w11 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0), - (w11 &= 67108863), - (lo = Math.imul(al9, bl3)), - (mid = Math.imul(al9, bh3)), - (mid = (mid + Math.imul(ah9, bl3)) | 0), - (hi = Math.imul(ah9, bh3)), - (lo = (lo + Math.imul(al8, bl4)) | 0), - (mid = (mid + Math.imul(al8, bh4)) | 0), - (mid = (mid + Math.imul(ah8, bl4)) | 0), - (hi = (hi + Math.imul(ah8, bh4)) | 0), - (lo = (lo + Math.imul(al7, bl5)) | 0), - (mid = (mid + Math.imul(al7, bh5)) | 0), - (mid = (mid + Math.imul(ah7, bl5)) | 0), - (hi = (hi + Math.imul(ah7, bh5)) | 0), - (lo = (lo + Math.imul(al6, bl6)) | 0), - (mid = (mid + Math.imul(al6, bh6)) | 0), - (mid = (mid + Math.imul(ah6, bl6)) | 0), - (hi = (hi + Math.imul(ah6, bh6)) | 0), - (lo = (lo + Math.imul(al5, bl7)) | 0), - (mid = (mid + Math.imul(al5, bh7)) | 0), - (mid = (mid + Math.imul(ah5, bl7)) | 0), - (hi = (hi + Math.imul(ah5, bh7)) | 0), - (lo = (lo + Math.imul(al4, bl8)) | 0), - (mid = (mid + Math.imul(al4, bh8)) | 0), - (mid = (mid + Math.imul(ah4, bl8)) | 0), - (hi = (hi + Math.imul(ah4, bh8)) | 0), - (lo = (lo + Math.imul(al3, bl9)) | 0), - (mid = (mid + Math.imul(al3, bh9)) | 0), - (mid = (mid + Math.imul(ah3, bl9)) | 0), - (hi = (hi + Math.imul(ah3, bh9)) | 0); - var w12 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0), - (w12 &= 67108863), - (lo = Math.imul(al9, bl4)), - (mid = Math.imul(al9, bh4)), - (mid = (mid + Math.imul(ah9, bl4)) | 0), - (hi = Math.imul(ah9, bh4)), - (lo = (lo + Math.imul(al8, bl5)) | 0), - (mid = (mid + Math.imul(al8, bh5)) | 0), - (mid = (mid + Math.imul(ah8, bl5)) | 0), - (hi = (hi + Math.imul(ah8, bh5)) | 0), - (lo = (lo + Math.imul(al7, bl6)) | 0), - (mid = (mid + Math.imul(al7, bh6)) | 0), - (mid = (mid + Math.imul(ah7, bl6)) | 0), - (hi = (hi + Math.imul(ah7, bh6)) | 0), - (lo = (lo + Math.imul(al6, bl7)) | 0), - (mid = (mid + Math.imul(al6, bh7)) | 0), - (mid = (mid + Math.imul(ah6, bl7)) | 0), - (hi = (hi + Math.imul(ah6, bh7)) | 0), - (lo = (lo + Math.imul(al5, bl8)) | 0), - (mid = (mid + Math.imul(al5, bh8)) | 0), - (mid = (mid + Math.imul(ah5, bl8)) | 0), - (hi = (hi + Math.imul(ah5, bh8)) | 0), - (lo = (lo + Math.imul(al4, bl9)) | 0), - (mid = (mid + Math.imul(al4, bh9)) | 0), - (mid = (mid + Math.imul(ah4, bl9)) | 0), - (hi = (hi + Math.imul(ah4, bh9)) | 0); - var w13 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0), - (w13 &= 67108863), - (lo = Math.imul(al9, bl5)), - (mid = Math.imul(al9, bh5)), - (mid = (mid + Math.imul(ah9, bl5)) | 0), - (hi = Math.imul(ah9, bh5)), - (lo = (lo + Math.imul(al8, bl6)) | 0), - (mid = (mid + Math.imul(al8, bh6)) | 0), - (mid = (mid + Math.imul(ah8, bl6)) | 0), - (hi = (hi + Math.imul(ah8, bh6)) | 0), - (lo = (lo + Math.imul(al7, bl7)) | 0), - (mid = (mid + Math.imul(al7, bh7)) | 0), - (mid = (mid + Math.imul(ah7, bl7)) | 0), - (hi = (hi + Math.imul(ah7, bh7)) | 0), - (lo = (lo + Math.imul(al6, bl8)) | 0), - (mid = (mid + Math.imul(al6, bh8)) | 0), - (mid = (mid + Math.imul(ah6, bl8)) | 0), - (hi = (hi + Math.imul(ah6, bh8)) | 0), - (lo = (lo + Math.imul(al5, bl9)) | 0), - (mid = (mid + Math.imul(al5, bh9)) | 0), - (mid = (mid + Math.imul(ah5, bl9)) | 0), - (hi = (hi + Math.imul(ah5, bh9)) | 0); - var w14 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0), - (w14 &= 67108863), - (lo = Math.imul(al9, bl6)), - (mid = Math.imul(al9, bh6)), - (mid = (mid + Math.imul(ah9, bl6)) | 0), - (hi = Math.imul(ah9, bh6)), - (lo = (lo + Math.imul(al8, bl7)) | 0), - (mid = (mid + Math.imul(al8, bh7)) | 0), - (mid = (mid + Math.imul(ah8, bl7)) | 0), - (hi = (hi + Math.imul(ah8, bh7)) | 0), - (lo = (lo + Math.imul(al7, bl8)) | 0), - (mid = (mid + Math.imul(al7, bh8)) | 0), - (mid = (mid + Math.imul(ah7, bl8)) | 0), - (hi = (hi + Math.imul(ah7, bh8)) | 0), - (lo = (lo + Math.imul(al6, bl9)) | 0), - (mid = (mid + Math.imul(al6, bh9)) | 0), - (mid = (mid + Math.imul(ah6, bl9)) | 0), - (hi = (hi + Math.imul(ah6, bh9)) | 0); - var w15 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0), - (w15 &= 67108863), - (lo = Math.imul(al9, bl7)), - (mid = Math.imul(al9, bh7)), - (mid = (mid + Math.imul(ah9, bl7)) | 0), - (hi = Math.imul(ah9, bh7)), - (lo = (lo + Math.imul(al8, bl8)) | 0), - (mid = (mid + Math.imul(al8, bh8)) | 0), - (mid = (mid + Math.imul(ah8, bl8)) | 0), - (hi = (hi + Math.imul(ah8, bh8)) | 0), - (lo = (lo + Math.imul(al7, bl9)) | 0), - (mid = (mid + Math.imul(al7, bh9)) | 0), - (mid = (mid + Math.imul(ah7, bl9)) | 0), - (hi = (hi + Math.imul(ah7, bh9)) | 0); - var w16 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0), - (w16 &= 67108863), - (lo = Math.imul(al9, bl8)), - (mid = Math.imul(al9, bh8)), - (mid = (mid + Math.imul(ah9, bl8)) | 0), - (hi = Math.imul(ah9, bh8)), - (lo = (lo + Math.imul(al8, bl9)) | 0), - (mid = (mid + Math.imul(al8, bh9)) | 0), - (mid = (mid + Math.imul(ah8, bl9)) | 0), - (hi = (hi + Math.imul(ah8, bh9)) | 0); - var w17 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - (c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0), - (w17 &= 67108863), - (lo = Math.imul(al9, bl9)), - (mid = Math.imul(al9, bh9)), - (mid = (mid + Math.imul(ah9, bl9)) | 0), - (hi = Math.imul(ah9, bh9)); - var w18 = (((c + lo) | 0) + ((mid & 8191) << 13)) | 0; - return ( - (c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0), - (w18 &= 67108863), - (o[0] = w0), - (o[1] = w1), - (o[2] = w2), - (o[3] = w3), - (o[4] = w4), - (o[5] = w5), - (o[6] = w6), - (o[7] = w7), - (o[8] = w8), - (o[9] = w9), - (o[10] = w10), - (o[11] = w11), - (o[12] = w12), - (o[13] = w13), - (o[14] = w14), - (o[15] = w15), - (o[16] = w16), - (o[17] = w17), - (o[18] = w18), - c !== 0 && ((o[19] = c), out.length++), - out - ); - }; - Math.imul || (comb10MulTo = smallMulTo); - function bigMulTo(self2, num, out) { - (out.negative = num.negative ^ self2.negative), (out.length = self2.length + num.length); - for (var carry = 0, hncarry = 0, k = 0; k < out.length - 1; k++) { - var ncarry = hncarry; - hncarry = 0; - for ( - var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1), j = Math.max(0, k - self2.length + 1); - j <= maxJ; - j++ - ) { - var i = k - j, - a = self2.words[i] | 0, - b = num.words[j] | 0, - r = a * b, - lo = r & 67108863; - (ncarry = (ncarry + ((r / 67108864) | 0)) | 0), - (lo = (lo + rword) | 0), - (rword = lo & 67108863), - (ncarry = (ncarry + (lo >>> 26)) | 0), - (hncarry += ncarry >>> 26), - (ncarry &= 67108863); - } - (out.words[k] = rword), (carry = ncarry), (ncarry = hncarry); - } - return carry !== 0 ? (out.words[k] = carry) : out.length--, out.strip(); - } - function jumboMulTo(self2, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self2, num, out); - } - BN.prototype.mulTo = function (num, out) { - var res, - len = this.length + num.length; - return ( - this.length === 10 && num.length === 10 - ? (res = comb10MulTo(this, num, out)) - : len < 63 - ? (res = smallMulTo(this, num, out)) - : len < 1024 - ? (res = bigMulTo(this, num, out)) - : (res = jumboMulTo(this, num, out)), - res - ); - }; - function FFTM(x, y) { - (this.x = x), (this.y = y); - } - (FFTM.prototype.makeRBT = function (N) { - for (var t = new Array(N), l = BN.prototype._countBits(N) - 1, i = 0; i < N; i++) t[i] = this.revBin(i, l, N); - return t; - }), - (FFTM.prototype.revBin = function (x, l, N) { - if (x === 0 || x === N - 1) return x; - for (var rb = 0, i = 0; i < l; i++) (rb |= (x & 1) << (l - i - 1)), (x >>= 1); - return rb; - }), - (FFTM.prototype.permute = function (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) (rtws[i] = rws[rbt[i]]), (itws[i] = iws[rbt[i]]); - }), - (FFTM.prototype.transform = function (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - for (var s = 1; s < N; s <<= 1) - for ( - var l = s << 1, rtwdf = Math.cos((2 * Math.PI) / l), itwdf = Math.sin((2 * Math.PI) / l), p = 0; - p < N; - p += l - ) - for (var rtwdf_ = rtwdf, itwdf_ = itwdf, j = 0; j < s; j++) { - var re = rtws[p + j], - ie = itws[p + j], - ro = rtws[p + j + s], - io = itws[p + j + s], - rx = rtwdf_ * ro - itwdf_ * io; - (io = rtwdf_ * io + itwdf_ * ro), - (ro = rx), - (rtws[p + j] = re + ro), - (itws[p + j] = ie + io), - (rtws[p + j + s] = re - ro), - (itws[p + j + s] = ie - io), - j !== l && - ((rx = rtwdf * rtwdf_ - itwdf * itwdf_), (itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_), (rtwdf_ = rx)); - } - }), - (FFTM.prototype.guessLen13b = function (n, m) { - var N = Math.max(m, n) | 1, - odd = N & 1, - i = 0; - for (N = (N / 2) | 0; N; N = N >>> 1) i++; - return 1 << (i + 1 + odd); - }), - (FFTM.prototype.conjugate = function (rws, iws, N) { - if (!(N <= 1)) - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - (rws[i] = rws[N - i - 1]), - (rws[N - i - 1] = t), - (t = iws[i]), - (iws[i] = -iws[N - i - 1]), - (iws[N - i - 1] = -t); - } - }), - (FFTM.prototype.normalize13b = function (ws, N) { - for (var carry = 0, i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 8192 + Math.round(ws[2 * i] / N) + carry; - (ws[i] = w & 67108863), w < 67108864 ? (carry = 0) : (carry = (w / 67108864) | 0); - } - return ws; - }), - (FFTM.prototype.convert13b = function (ws, len, rws, N) { - for (var carry = 0, i = 0; i < len; i++) - (carry = carry + (ws[i] | 0)), - (rws[2 * i] = carry & 8191), - (carry = carry >>> 13), - (rws[2 * i + 1] = carry & 8191), - (carry = carry >>> 13); - for (i = 2 * len; i < N; ++i) rws[i] = 0; - assert(carry === 0), assert((carry & -8192) === 0); - }), - (FFTM.prototype.stub = function (N) { - for (var ph = new Array(N), i = 0; i < N; i++) ph[i] = 0; - return ph; - }), - (FFTM.prototype.mulp = function (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length), - rbt = this.makeRBT(N), - _ = this.stub(N), - rws = new Array(N), - rwst = new Array(N), - iwst = new Array(N), - nrws = new Array(N), - nrwst = new Array(N), - niwst = new Array(N), - rmws = out.words; - (rmws.length = N), - this.convert13b(x.words, x.length, rws, N), - this.convert13b(y.words, y.length, nrws, N), - this.transform(rws, _, rwst, iwst, N, rbt), - this.transform(nrws, _, nrwst, niwst, N, rbt); - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - (iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]), (rwst[i] = rx); - } - return ( - this.conjugate(rwst, iwst, N), - this.transform(rwst, iwst, rmws, _, N, rbt), - this.conjugate(rmws, _, N), - this.normalize13b(rmws, N), - (out.negative = x.negative ^ y.negative), - (out.length = x.length + y.length), - out.strip() - ); - }), - (BN.prototype.mul = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), this.mulTo(num, out); - }), - (BN.prototype.mulf = function (num) { - var out = new BN(null); - return (out.words = new Array(this.length + num.length)), jumboMulTo(this, num, out); - }), - (BN.prototype.imul = function (num) { - return this.clone().mulTo(num, this); - }), - (BN.prototype.imuln = function (num) { - assert(typeof num == "number"), assert(num < 67108864); - for (var carry = 0, i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num, - lo = (w & 67108863) + (carry & 67108863); - (carry >>= 26), (carry += (w / 67108864) | 0), (carry += lo >>> 26), (this.words[i] = lo & 67108863); - } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.muln = function (num) { - return this.clone().imuln(num); - }), - (BN.prototype.sqr = function () { - return this.mul(this); - }), - (BN.prototype.isqr = function () { - return this.imul(this.clone()); - }), - (BN.prototype.pow = function (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - for (var res = this, i = 0; i < w.length && w[i] === 0; i++, res = res.sqr()); - if (++i < w.length) for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) w[i] !== 0 && (res = res.mul(q)); - return res; - }), - (BN.prototype.iushln = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26, - carryMask = (67108863 >>> (26 - r)) << (26 - r), - i; - if (r !== 0) { - var carry = 0; - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask, - c = ((this.words[i] | 0) - newCarry) << r; - (this.words[i] = c | carry), (carry = newCarry >>> (26 - r)); - } - carry && ((this.words[i] = carry), this.length++); - } - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) this.words[i + s] = this.words[i]; - for (i = 0; i < s; i++) this.words[i] = 0; - this.length += s; - } - return this.strip(); - }), - (BN.prototype.ishln = function (bits) { - return assert(this.negative === 0), this.iushln(bits); - }), - (BN.prototype.iushrn = function (bits, hint, extended) { - assert(typeof bits == "number" && bits >= 0); - var h; - hint ? (h = (hint - (hint % 26)) / 26) : (h = 0); - var r = bits % 26, - s = Math.min((bits - r) / 26, this.length), - mask = 67108863 ^ ((67108863 >>> r) << r), - maskedWords = extended; - if (((h -= s), (h = Math.max(0, h)), maskedWords)) { - for (var i = 0; i < s; i++) maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - if (s !== 0) - if (this.length > s) for (this.length -= s, i = 0; i < this.length; i++) this.words[i] = this.words[i + s]; - else (this.words[0] = 0), (this.length = 1); - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - (this.words[i] = (carry << (26 - r)) | (word >>> r)), (carry = word & mask); - } - return ( - maskedWords && carry !== 0 && (maskedWords.words[maskedWords.length++] = carry), - this.length === 0 && ((this.words[0] = 0), (this.length = 1)), - this.strip() - ); - }), - (BN.prototype.ishrn = function (bits, hint, extended) { - return assert(this.negative === 0), this.iushrn(bits, hint, extended); - }), - (BN.prototype.shln = function (bits) { - return this.clone().ishln(bits); - }), - (BN.prototype.ushln = function (bits) { - return this.clone().iushln(bits); - }), - (BN.prototype.shrn = function (bits) { - return this.clone().ishrn(bits); - }), - (BN.prototype.ushrn = function (bits) { - return this.clone().iushrn(bits); - }), - (BN.prototype.testn = function (bit) { - assert(typeof bit == "number" && bit >= 0); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return !1; - var w = this.words[s]; - return !!(w & q); - }), - (BN.prototype.imaskn = function (bits) { - assert(typeof bits == "number" && bits >= 0); - var r = bits % 26, - s = (bits - r) / 26; - if ((assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)) return this; - if ((r !== 0 && s++, (this.length = Math.min(s, this.length)), r !== 0)) { - var mask = 67108863 ^ ((67108863 >>> r) << r); - this.words[this.length - 1] &= mask; - } - return this.strip(); - }), - (BN.prototype.maskn = function (bits) { - return this.clone().imaskn(bits); - }), - (BN.prototype.iaddn = function (num) { - return ( - assert(typeof num == "number"), - assert(num < 67108864), - num < 0 - ? this.isubn(-num) - : this.negative !== 0 - ? this.length === 1 && (this.words[0] | 0) < num - ? ((this.words[0] = num - (this.words[0] | 0)), (this.negative = 0), this) - : ((this.negative = 0), this.isubn(num), (this.negative = 1), this) - : this._iaddn(num) - ); - }), - (BN.prototype._iaddn = function (num) { - this.words[0] += num; - for (var i = 0; i < this.length && this.words[i] >= 67108864; i++) - (this.words[i] -= 67108864), i === this.length - 1 ? (this.words[i + 1] = 1) : this.words[i + 1]++; - return (this.length = Math.max(this.length, i + 1)), this; - }), - (BN.prototype.isubn = function (num) { - if ((assert(typeof num == "number"), assert(num < 67108864), num < 0)) return this.iaddn(-num); - if (this.negative !== 0) return (this.negative = 0), this.iaddn(num), (this.negative = 1), this; - if (((this.words[0] -= num), this.length === 1 && this.words[0] < 0)) - (this.words[0] = -this.words[0]), (this.negative = 1); - else - for (var i = 0; i < this.length && this.words[i] < 0; i++) - (this.words[i] += 67108864), (this.words[i + 1] -= 1); - return this.strip(); - }), - (BN.prototype.addn = function (num) { - return this.clone().iaddn(num); - }), - (BN.prototype.subn = function (num) { - return this.clone().isubn(num); - }), - (BN.prototype.iabs = function () { - return (this.negative = 0), this; - }), - (BN.prototype.abs = function () { - return this.clone().iabs(); - }), - (BN.prototype._ishlnsubmul = function (num, mul, shift) { - var len = num.length + shift, - i; - this._expand(len); - var w, - carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - (w -= right & 67108863), - (carry = (w >> 26) - ((right / 67108864) | 0)), - (this.words[i + shift] = w & 67108863); + for (i = 0; i < len; i++) wnd[i] = null; + return jacobianResult ? acc : acc.toP(); + }; + function BasePoint(curve, type) { + (this.curve = curve), (this.type = type), (this.precomputed = null); + } + BasePoint.prototype = {}; + BaseCurve.BasePoint = BasePoint; + BasePoint.prototype.eq = function () { + throw new Error("Not implemented"); + }; + BasePoint.prototype.validate = function () { + return this.curve.validate(this); + }; + BaseCurve.prototype.decodePoint = function (bytes, enc) { + bytes = utils.toArray(bytes, enc); + var len = this.p.byteLength(); + if ((bytes[0] === 4 || bytes[0] === 6 || bytes[0] === 7) && bytes.length - 1 === 2 * len) { + bytes[0] === 6 + ? assert(bytes[bytes.length - 1] % 2 === 0) + : bytes[0] === 7 && assert(bytes[bytes.length - 1] % 2 === 1); + var res = this.point(bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len)); + return res; + } else if ((bytes[0] === 2 || bytes[0] === 3) && bytes.length - 1 === len) + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 3); + throw new Error("Unknown point format"); + }; + BasePoint.prototype.encodeCompressed = function (enc) { + return this.encode(enc, !0); + }; + BasePoint.prototype._encode = function (compact) { + var len = this.curve.p.byteLength(), + x = this.getX().toArray("be", len); + return compact ? [this.getY().isEven() ? 2 : 3].concat(x) : [4].concat(x, this.getY().toArray("be", len)); + }; + BasePoint.prototype.encode = function (enc, compact) { + return utils.encode(this._encode(compact), enc); + }; + BasePoint.prototype.precompute = function (power) { + if (this.precomputed) return this; + var precomputed = { + doubles: null, + naf: null, + beta: null, + }; + return ( + (precomputed.naf = this._getNAFPoints(8)), + (precomputed.doubles = this._getDoubles(4, power)), + (precomputed.beta = this._getBeta()), + (this.precomputed = precomputed), + this + ); + }; + BasePoint.prototype._hasDoubles = function (k) { + if (!this.precomputed) return !1; + var doubles = this.precomputed.doubles; + return doubles ? doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step) : !1; + }; + BasePoint.prototype._getDoubles = function (step, power) { + if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; + for (var doubles = [this], acc = this, i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) acc = acc.dbl(); + doubles.push(acc); + } + return { + step, + points: doubles, + }; + }; + BasePoint.prototype._getNAFPoints = function (wnd) { + if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; + for (var res = [this], max = (1 << wnd) - 1, dbl = max === 1 ? null : this.dbl(), i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd, + points: res, + }; + }; + BasePoint.prototype._getBeta = function () { + return null; + }; + BasePoint.prototype.dblp = function (k) { + for (var r = this, i = 0; i < k; i++) r = r.dbl(); + return r; + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/curve/short.js +var require_short = __commonJS({ + "node_modules/elliptic/lib/elliptic/curve/short.js"(exports, module) { + "use strict"; + var utils = require_utils3(), + BN = require_bn4(), + inherits = require_inherits_browser(), + Base = require_base(), + assert = utils.assert; + function ShortCurve(conf) { + Base.call(this, "short", conf), + (this.a = new BN(conf.a, 16).toRed(this.red)), + (this.b = new BN(conf.b, 16).toRed(this.red)), + (this.tinv = this.two.redInvm()), + (this.zeroA = this.a.fromRed().cmpn(0) === 0), + (this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0), + (this.endo = this._getEndomorphism(conf)), + (this._endoWnafT1 = new Array(4)), + (this._endoWnafT2 = new Array(4)); + } + inherits(ShortCurve, Base); + module.exports = ShortCurve; + ShortCurve.prototype._getEndomorphism = function (conf) { + if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { + var beta, lambda; + if (conf.beta) beta = new BN(conf.beta, 16).toRed(this.red); + else { + var betas = this._getEndoRoots(this.p); + (beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]), (beta = beta.toRed(this.red)); + } + if (conf.lambda) lambda = new BN(conf.lambda, 16); + else { + var lambdas = this._getEndoRoots(this.n); + this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0 + ? (lambda = lambdas[0]) + : ((lambda = lambdas[1]), assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0)); + } + var basis; + return ( + conf.basis + ? (basis = conf.basis.map(function (vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16), + }; + })) + : (basis = this._getEndoBasis(lambda)), + { + beta, + lambda, + basis, } - for (; i < this.length - shift; i++) - (w = (this.words[i + shift] | 0) + carry), (carry = w >> 26), (this.words[i + shift] = w & 67108863); - if (carry === 0) return this.strip(); - for (assert(carry === -1), carry = 0, i = 0; i < this.length; i++) - (w = -(this.words[i] | 0) + carry), (carry = w >> 26), (this.words[i] = w & 67108863); - return (this.negative = 1), this.strip(); + ); + } + }; + ShortCurve.prototype._getEndoRoots = function (num) { + var red = num === this.p ? this.red : BN.mont(num), + tinv = new BN(2).toRed(red).redInvm(), + ntinv = tinv.redNeg(), + s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv), + l1 = ntinv.redAdd(s).fromRed(), + l2 = ntinv.redSub(s).fromRed(); + return [l1, l2]; + }; + ShortCurve.prototype._getEndoBasis = function (lambda) { + for ( + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), + u = lambda, + v = this.n.clone(), + x1 = new BN(1), + y1 = new BN(0), + x2 = new BN(0), + y2 = new BN(1), + a0, + b0, + a1, + b1, + a2, + b2, + prevR, + i = 0, + r, + x; + u.cmpn(0) !== 0; + + ) { + var q = v.div(u); + (r = v.sub(q.mul(u))), (x = x2.sub(q.mul(x1))); + var y = y2.sub(q.mul(y1)); + if (!a1 && r.cmp(aprxSqrt) < 0) (a0 = prevR.neg()), (b0 = x1), (a1 = r.neg()), (b1 = x); + else if (a1 && ++i === 2) break; + (prevR = r), (v = u), (u = r), (x2 = x1), (x1 = x), (y2 = y1), (y1 = y); + } + (a2 = r.neg()), (b2 = x); + var len1 = a1.sqr().add(b1.sqr()), + len2 = a2.sqr().add(b2.sqr()); + return ( + len2.cmp(len1) >= 0 && ((a2 = a0), (b2 = b0)), + a1.negative && ((a1 = a1.neg()), (b1 = b1.neg())), + a2.negative && ((a2 = a2.neg()), (b2 = b2.neg())), + [ + { a: a1, b: b1 }, + { a: a2, b: b2 }, + ] + ); + }; + ShortCurve.prototype._endoSplit = function (k) { + var basis = this.endo.basis, + v1 = basis[0], + v2 = basis[1], + c1 = v2.b.mul(k).divRound(this.n), + c2 = v1.b.neg().mul(k).divRound(this.n), + p1 = c1.mul(v1.a), + p2 = c2.mul(v2.a), + q1 = c1.mul(v1.b), + q2 = c2.mul(v2.b), + k1 = k.sub(p1).sub(p2), + k2 = q1.add(q2).neg(); + return { k1, k2 }; + }; + ShortCurve.prototype.pointFromX = function (x, odd) { + (x = new BN(x, 16)), x.red || (x = x.toRed(this.red)); + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b), + y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error("invalid point"); + var isOdd = y.fromRed().isOdd(); + return ((odd && !isOdd) || (!odd && isOdd)) && (y = y.redNeg()), this.point(x, y); + }; + ShortCurve.prototype.validate = function (point) { + if (point.inf) return !0; + var x = point.x, + y = point.y, + ax = this.a.redMul(x), + rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; + }; + ShortCurve.prototype._endoWnafMulAdd = function (points, coeffs, jacobianResult) { + for (var npoints = this._endoWnafT1, ncoeffs = this._endoWnafT2, i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]), + p = points[i], + beta = p._getBeta(); + split.k1.negative && (split.k1.ineg(), (p = p.neg(!0))), + split.k2.negative && (split.k2.ineg(), (beta = beta.neg(!0))), + (npoints[i * 2] = p), + (npoints[i * 2 + 1] = beta), + (ncoeffs[i * 2] = split.k1), + (ncoeffs[i * 2 + 1] = split.k2); + } + for (var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult), j = 0; j < i * 2; j++) + (npoints[j] = null), (ncoeffs[j] = null); + return res; + }; + function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, "affine"), + x === null && y === null + ? ((this.x = null), (this.y = null), (this.inf = !0)) + : ((this.x = new BN(x, 16)), + (this.y = new BN(y, 16)), + isRed && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), + this.x.red || (this.x = this.x.toRed(this.curve.red)), + this.y.red || (this.y = this.y.toRed(this.curve.red)), + (this.inf = !1)); + } + inherits(Point, Base.BasePoint); + ShortCurve.prototype.point = function (x, y, isRed) { + return new Point(this, x, y, isRed); + }; + ShortCurve.prototype.pointFromJSON = function (obj, red) { + return Point.fromJSON(this, obj, red); + }; + Point.prototype._getBeta = function () { + if (!!this.curve.endo) { + var pre = this.precomputed; + if (pre && pre.beta) return pre.beta; + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve, + endoMul = function (p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + (pre.beta = beta), + (beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul), + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul), + }, + }); + } + return beta; + } + }; + Point.prototype.toJSON = function () { + return this.precomputed + ? [ + this.x, + this.y, + this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1), + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1), + }, + }, + ] + : [this.x, this.y]; + }; + Point.fromJSON = function (curve, obj, red) { + typeof obj == "string" && (obj = JSON.parse(obj)); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) return res; + function obj2point(obj2) { + return curve.point(obj2[0], obj2[1], red); + } + var pre = obj[2]; + return ( + (res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [res].concat(pre.doubles.points.map(obj2point)), + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [res].concat(pre.naf.points.map(obj2point)), + }, }), - (BN.prototype._wordDiv = function (num, mode) { - var shift = this.length - num.length, - a = this.clone(), - b = num, - bhi = b.words[b.length - 1] | 0, - bhiBits = this._countBits(bhi); - (shift = 26 - bhiBits), - shift !== 0 && ((b = b.ushln(shift)), a.iushln(shift), (bhi = b.words[b.length - 1] | 0)); - var m = a.length - b.length, - q; - if (mode !== "mod") { - (q = new BN(null)), (q.length = m + 1), (q.words = new Array(q.length)); - for (var i = 0; i < q.length; i++) q.words[i] = 0; - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - diff.negative === 0 && ((a = diff), q && (q.words[m] = 1)); - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); - for (qj = Math.min((qj / bhi) | 0, 67108863), a._ishlnsubmul(b, qj, j); a.negative !== 0; ) - qj--, (a.negative = 0), a._ishlnsubmul(b, 1, j), a.isZero() || (a.negative ^= 1); - q && (q.words[j] = qj); + res + ); + }; + Point.prototype.inspect = function () { + return this.isInfinity() + ? "" + : ""; + }; + Point.prototype.isInfinity = function () { + return this.inf; + }; + Point.prototype.add = function (p) { + if (this.inf) return p; + if (p.inf) return this; + if (this.eq(p)) return this.dbl(); + if (this.neg().eq(p)) return this.curve.point(null, null); + if (this.x.cmp(p.x) === 0) return this.curve.point(null, null); + var c = this.y.redSub(p.y); + c.cmpn(0) !== 0 && (c = c.redMul(this.x.redSub(p.x).redInvm())); + var nx = c.redSqr().redISub(this.x).redISub(p.x), + ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + Point.prototype.dbl = function () { + if (this.inf) return this; + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) return this.curve.point(null, null); + var a = this.curve.a, + x2 = this.x.redSqr(), + dyinv = ys1.redInvm(), + c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv), + nx = c.redSqr().redISub(this.x.redAdd(this.x)), + ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); + }; + Point.prototype.getX = function () { + return this.x.fromRed(); + }; + Point.prototype.getY = function () { + return this.y.fromRed(); + }; + Point.prototype.mul = function (k) { + return ( + (k = new BN(k, 16)), + this.isInfinity() + ? this + : this._hasDoubles(k) + ? this.curve._fixedNafMul(this, k) + : this.curve.endo + ? this.curve._endoWnafMulAdd([this], [k]) + : this.curve._wnafMul(this, k) + ); + }; + Point.prototype.mulAdd = function (k1, p2, k2) { + var points = [this, p2], + coeffs = [k1, k2]; + return this.curve.endo + ? this.curve._endoWnafMulAdd(points, coeffs) + : this.curve._wnafMulAdd(1, points, coeffs, 2); + }; + Point.prototype.jmulAdd = function (k1, p2, k2) { + var points = [this, p2], + coeffs = [k1, k2]; + return this.curve.endo + ? this.curve._endoWnafMulAdd(points, coeffs, !0) + : this.curve._wnafMulAdd(1, points, coeffs, 2, !0); + }; + Point.prototype.eq = function (p) { + return this === p || (this.inf === p.inf && (this.inf || (this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0))); + }; + Point.prototype.neg = function (_precompute) { + if (this.inf) return this; + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed, + negate = function (p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate), + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate), + }, + }; + } + return res; + }; + Point.prototype.toJ = function () { + if (this.inf) return this.curve.jpoint(null, null, null); + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; + }; + function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, "jacobian"), + x === null && y === null && z === null + ? ((this.x = this.curve.one), (this.y = this.curve.one), (this.z = new BN(0))) + : ((this.x = new BN(x, 16)), (this.y = new BN(y, 16)), (this.z = new BN(z, 16))), + this.x.red || (this.x = this.x.toRed(this.curve.red)), + this.y.red || (this.y = this.y.toRed(this.curve.red)), + this.z.red || (this.z = this.z.toRed(this.curve.red)), + (this.zOne = this.z === this.curve.one); + } + inherits(JPoint, Base.BasePoint); + ShortCurve.prototype.jpoint = function (x, y, z) { + return new JPoint(this, x, y, z); + }; + JPoint.prototype.toP = function () { + if (this.isInfinity()) return this.curve.point(null, null); + var zinv = this.z.redInvm(), + zinv2 = zinv.redSqr(), + ax = this.x.redMul(zinv2), + ay = this.y.redMul(zinv2).redMul(zinv); + return this.curve.point(ax, ay); + }; + JPoint.prototype.neg = function () { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }; + JPoint.prototype.add = function (p) { + if (this.isInfinity()) return p; + if (p.isInfinity()) return this; + var pz2 = p.z.redSqr(), + z2 = this.z.redSqr(), + u1 = this.x.redMul(pz2), + u2 = p.x.redMul(z2), + s1 = this.y.redMul(pz2.redMul(p.z)), + s2 = p.y.redMul(z2.redMul(this.z)), + h = u1.redSub(u2), + r = s1.redSub(s2); + if (h.cmpn(0) === 0) return r.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var h2 = h.redSqr(), + h3 = h2.redMul(h), + v = u1.redMul(h2), + nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v), + ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)), + nz = this.z.redMul(p.z).redMul(h); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.mixedAdd = function (p) { + if (this.isInfinity()) return p.toJ(); + if (p.isInfinity()) return this; + var z2 = this.z.redSqr(), + u1 = this.x, + u2 = p.x.redMul(z2), + s1 = this.y, + s2 = p.y.redMul(z2).redMul(this.z), + h = u1.redSub(u2), + r = s1.redSub(s2); + if (h.cmpn(0) === 0) return r.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var h2 = h.redSqr(), + h3 = h2.redMul(h), + v = u1.redMul(h2), + nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v), + ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)), + nz = this.z.redMul(h); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.dblp = function (pow) { + if (pow === 0) return this; + if (this.isInfinity()) return this; + if (!pow) return this.dbl(); + var i; + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (i = 0; i < pow; i++) r = r.dbl(); + return r; + } + var a = this.curve.a, + tinv = this.curve.tinv, + jx = this.x, + jy = this.y, + jz = this.z, + jz4 = jz.redSqr().redSqr(), + jyd = jy.redAdd(jy); + for (i = 0; i < pow; i++) { + var jx2 = jx.redSqr(), + jyd2 = jyd.redSqr(), + jyd4 = jyd2.redSqr(), + c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)), + t1 = jx.redMul(jyd2), + nx = c.redSqr().redISub(t1.redAdd(t1)), + t2 = t1.redISub(nx), + dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + i + 1 < pow && (jz4 = jz4.redMul(jyd4)), (jx = nx), (jz = nz), (jyd = dny); + } + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); + }; + JPoint.prototype.dbl = function () { + return this.isInfinity() + ? this + : this.curve.zeroA + ? this._zeroDbl() + : this.curve.threeA + ? this._threeDbl() + : this._dbl(); + }; + JPoint.prototype._zeroDbl = function () { + var nx, ny, nz; + if (this.zOne) { + var xx = this.x.redSqr(), + yy = this.y.redSqr(), + yyyy = yy.redSqr(), + s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + var m = xx.redAdd(xx).redIAdd(xx), + t = m.redSqr().redISub(s).redISub(s), + yyyy8 = yyyy.redIAdd(yyyy); + (yyyy8 = yyyy8.redIAdd(yyyy8)), + (yyyy8 = yyyy8.redIAdd(yyyy8)), + (nx = t), + (ny = m.redMul(s.redISub(t)).redISub(yyyy8)), + (nz = this.y.redAdd(this.y)); + } else { + var a = this.x.redSqr(), + b = this.y.redSqr(), + c = b.redSqr(), + d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + var e = a.redAdd(a).redIAdd(a), + f = e.redSqr(), + c8 = c.redIAdd(c); + (c8 = c8.redIAdd(c8)), + (c8 = c8.redIAdd(c8)), + (nx = f.redISub(d).redISub(d)), + (ny = e.redMul(d.redISub(nx)).redISub(c8)), + (nz = this.y.redMul(this.z)), + (nz = nz.redIAdd(nz)); + } + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype._threeDbl = function () { + var nx, ny, nz; + if (this.zOne) { + var xx = this.x.redSqr(), + yy = this.y.redSqr(), + yyyy = yy.redSqr(), + s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a), + t = m.redSqr().redISub(s).redISub(s); + nx = t; + var yyyy8 = yyyy.redIAdd(yyyy); + (yyyy8 = yyyy8.redIAdd(yyyy8)), + (yyyy8 = yyyy8.redIAdd(yyyy8)), + (ny = m.redMul(s.redISub(t)).redISub(yyyy8)), + (nz = this.y.redAdd(this.y)); + } else { + var delta = this.z.redSqr(), + gamma = this.y.redSqr(), + beta = this.x.redMul(gamma), + alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + (nx = alpha.redSqr().redISub(beta8)), (nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta)); + var ggamma8 = gamma.redSqr(); + (ggamma8 = ggamma8.redIAdd(ggamma8)), + (ggamma8 = ggamma8.redIAdd(ggamma8)), + (ggamma8 = ggamma8.redIAdd(ggamma8)), + (ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8)); + } + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype._dbl = function () { + var a = this.curve.a, + jx = this.x, + jy = this.y, + jz = this.z, + jz4 = jz.redSqr().redSqr(), + jx2 = jx.redSqr(), + jy2 = jy.redSqr(), + c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)), + jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2), + nx = c.redSqr().redISub(t1.redAdd(t1)), + t2 = t1.redISub(nx), + jyd8 = jy2.redSqr(); + (jyd8 = jyd8.redIAdd(jyd8)), (jyd8 = jyd8.redIAdd(jyd8)), (jyd8 = jyd8.redIAdd(jyd8)); + var ny = c.redMul(t2).redISub(jyd8), + nz = jy.redAdd(jy).redMul(jz); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.trpl = function () { + if (!this.curve.zeroA) return this.dbl().add(this); + var xx = this.x.redSqr(), + yy = this.y.redSqr(), + zz = this.z.redSqr(), + yyyy = yy.redSqr(), + m = xx.redAdd(xx).redIAdd(xx), + mm = m.redSqr(), + e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + (e = e.redIAdd(e)), (e = e.redAdd(e).redIAdd(e)), (e = e.redISub(mm)); + var ee = e.redSqr(), + t = yyyy.redIAdd(yyyy); + (t = t.redIAdd(t)), (t = t.redIAdd(t)), (t = t.redIAdd(t)); + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t), + yyu4 = yy.redMul(u); + (yyu4 = yyu4.redIAdd(yyu4)), (yyu4 = yyu4.redIAdd(yyu4)); + var nx = this.x.redMul(ee).redISub(yyu4); + (nx = nx.redIAdd(nx)), (nx = nx.redIAdd(nx)); + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + (ny = ny.redIAdd(ny)), (ny = ny.redIAdd(ny)), (ny = ny.redIAdd(ny)); + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + return this.curve.jpoint(nx, ny, nz); + }; + JPoint.prototype.mul = function (k, kbase) { + return (k = new BN(k, kbase)), this.curve._wnafMul(this, k); + }; + JPoint.prototype.eq = function (p) { + if (p.type === "affine") return this.eq(p.toJ()); + if (this === p) return !0; + var z2 = this.z.redSqr(), + pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return !1; + var z3 = z2.redMul(this.z), + pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; + }; + JPoint.prototype.eqXToP = function (x) { + var zs = this.z.redSqr(), + rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) return !0; + for (var xc = x.clone(), t = this.curve.redN.redMul(zs); ; ) { + if ((xc.iadd(this.curve.n), xc.cmp(this.curve.p) >= 0)) return !1; + if ((rx.redIAdd(t), this.x.cmp(rx) === 0)) return !0; + } + }; + JPoint.prototype.inspect = function () { + return this.isInfinity() + ? "" + : ""; + }; + JPoint.prototype.isInfinity = function () { + return this.z.cmpn(0) === 0; + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/curve/mont.js +var require_mont = __commonJS({ + "node_modules/elliptic/lib/elliptic/curve/mont.js"(exports, module) { + "use strict"; + var BN = require_bn4(), + inherits = require_inherits_browser(), + Base = require_base(), + utils = require_utils3(); + function MontCurve(conf) { + Base.call(this, "mont", conf), + (this.a = new BN(conf.a, 16).toRed(this.red)), + (this.b = new BN(conf.b, 16).toRed(this.red)), + (this.i4 = new BN(4).toRed(this.red).redInvm()), + (this.two = new BN(2).toRed(this.red)), + (this.a24 = this.i4.redMul(this.a.redAdd(this.two))); + } + inherits(MontCurve, Base); + module.exports = MontCurve; + MontCurve.prototype.validate = function (point) { + var x = point.normalize().x, + x2 = x.redSqr(), + rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x), + y = rhs.redSqrt(); + return y.redSqr().cmp(rhs) === 0; + }; + function Point(curve, x, z) { + Base.BasePoint.call(this, curve, "projective"), + x === null && z === null + ? ((this.x = this.curve.one), (this.z = this.curve.zero)) + : ((this.x = new BN(x, 16)), + (this.z = new BN(z, 16)), + this.x.red || (this.x = this.x.toRed(this.curve.red)), + this.z.red || (this.z = this.z.toRed(this.curve.red))); + } + inherits(Point, Base.BasePoint); + MontCurve.prototype.decodePoint = function (bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); + }; + MontCurve.prototype.point = function (x, z) { + return new Point(this, x, z); + }; + MontCurve.prototype.pointFromJSON = function (obj) { + return Point.fromJSON(this, obj); + }; + Point.prototype.precompute = function () {}; + Point.prototype._encode = function () { + return this.getX().toArray("be", this.curve.p.byteLength()); + }; + Point.fromJSON = function (curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); + }; + Point.prototype.inspect = function () { + return this.isInfinity() + ? "" + : ""; + }; + Point.prototype.isInfinity = function () { + return this.z.cmpn(0) === 0; + }; + Point.prototype.dbl = function () { + var a = this.x.redAdd(this.z), + aa = a.redSqr(), + b = this.x.redSub(this.z), + bb = b.redSqr(), + c = aa.redSub(bb), + nx = aa.redMul(bb), + nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); + }; + Point.prototype.add = function () { + throw new Error("Not supported on Montgomery curve"); + }; + Point.prototype.diffAdd = function (p, diff) { + var a = this.x.redAdd(this.z), + b = this.x.redSub(this.z), + c = p.x.redAdd(p.z), + d = p.x.redSub(p.z), + da = d.redMul(a), + cb = c.redMul(b), + nx = diff.z.redMul(da.redAdd(cb).redSqr()), + nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); + }; + Point.prototype.mul = function (k) { + for ( + var t = k.clone(), a = this, b = this.curve.point(null, null), c = this, bits = []; + t.cmpn(0) !== 0; + t.iushrn(1) + ) + bits.push(t.andln(1)); + for (var i = bits.length - 1; i >= 0; i--) + bits[i] === 0 ? ((a = a.diffAdd(b, c)), (b = b.dbl())) : ((b = a.diffAdd(b, c)), (a = a.dbl())); + return b; + }; + Point.prototype.mulAdd = function () { + throw new Error("Not supported on Montgomery curve"); + }; + Point.prototype.jumlAdd = function () { + throw new Error("Not supported on Montgomery curve"); + }; + Point.prototype.eq = function (other) { + return this.getX().cmp(other.getX()) === 0; + }; + Point.prototype.normalize = function () { + return (this.x = this.x.redMul(this.z.redInvm())), (this.z = this.curve.one), this; + }; + Point.prototype.getX = function () { + return this.normalize(), this.x.fromRed(); + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/curve/edwards.js +var require_edwards = __commonJS({ + "node_modules/elliptic/lib/elliptic/curve/edwards.js"(exports, module) { + "use strict"; + var utils = require_utils3(), + BN = require_bn4(), + inherits = require_inherits_browser(), + Base = require_base(), + assert = utils.assert; + function EdwardsCurve(conf) { + (this.twisted = (conf.a | 0) !== 1), + (this.mOneA = this.twisted && (conf.a | 0) === -1), + (this.extended = this.mOneA), + Base.call(this, "edwards", conf), + (this.a = new BN(conf.a, 16).umod(this.red.m)), + (this.a = this.a.toRed(this.red)), + (this.c = new BN(conf.c, 16).toRed(this.red)), + (this.c2 = this.c.redSqr()), + (this.d = new BN(conf.d, 16).toRed(this.red)), + (this.dd = this.d.redAdd(this.d)), + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0), + (this.oneC = (conf.c | 0) === 1); + } + inherits(EdwardsCurve, Base); + module.exports = EdwardsCurve; + EdwardsCurve.prototype._mulA = function (num) { + return this.mOneA ? num.redNeg() : this.a.redMul(num); + }; + EdwardsCurve.prototype._mulC = function (num) { + return this.oneC ? num : this.c.redMul(num); + }; + EdwardsCurve.prototype.jpoint = function (x, y, z, t) { + return this.point(x, y, z, t); + }; + EdwardsCurve.prototype.pointFromX = function (x, odd) { + (x = new BN(x, 16)), x.red || (x = x.toRed(this.red)); + var x2 = x.redSqr(), + rhs = this.c2.redSub(this.a.redMul(x2)), + lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)), + y2 = rhs.redMul(lhs.redInvm()), + y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error("invalid point"); + var isOdd = y.fromRed().isOdd(); + return ((odd && !isOdd) || (!odd && isOdd)) && (y = y.redNeg()), this.point(x, y); + }; + EdwardsCurve.prototype.pointFromY = function (y, odd) { + (y = new BN(y, 16)), y.red || (y = y.toRed(this.red)); + var y2 = y.redSqr(), + lhs = y2.redSub(this.c2), + rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a), + x2 = lhs.redMul(rhs.redInvm()); + if (x2.cmp(this.zero) === 0) { + if (odd) throw new Error("invalid point"); + return this.point(this.zero, y); + } + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) throw new Error("invalid point"); + return x.fromRed().isOdd() !== odd && (x = x.redNeg()), this.point(x, y); + }; + EdwardsCurve.prototype.validate = function (point) { + if (point.isInfinity()) return !0; + point.normalize(); + var x2 = point.x.redSqr(), + y2 = point.y.redSqr(), + lhs = x2.redMul(this.a).redAdd(y2), + rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + return lhs.cmp(rhs) === 0; + }; + function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, "projective"), + x === null && y === null && z === null + ? ((this.x = this.curve.zero), + (this.y = this.curve.one), + (this.z = this.curve.one), + (this.t = this.curve.zero), + (this.zOne = !0)) + : ((this.x = new BN(x, 16)), + (this.y = new BN(y, 16)), + (this.z = z ? new BN(z, 16) : this.curve.one), + (this.t = t && new BN(t, 16)), + this.x.red || (this.x = this.x.toRed(this.curve.red)), + this.y.red || (this.y = this.y.toRed(this.curve.red)), + this.z.red || (this.z = this.z.toRed(this.curve.red)), + this.t && !this.t.red && (this.t = this.t.toRed(this.curve.red)), + (this.zOne = this.z === this.curve.one), + this.curve.extended && + !this.t && + ((this.t = this.x.redMul(this.y)), this.zOne || (this.t = this.t.redMul(this.z.redInvm())))); + } + inherits(Point, Base.BasePoint); + EdwardsCurve.prototype.pointFromJSON = function (obj) { + return Point.fromJSON(this, obj); + }; + EdwardsCurve.prototype.point = function (x, y, z, t) { + return new Point(this, x, y, z, t); + }; + Point.fromJSON = function (curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); + }; + Point.prototype.inspect = function () { + return this.isInfinity() + ? "" + : ""; + }; + Point.prototype.isInfinity = function () { + return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || (this.zOne && this.y.cmp(this.curve.c) === 0)); + }; + Point.prototype._extDbl = function () { + var a = this.x.redSqr(), + b = this.y.redSqr(), + c = this.z.redSqr(); + c = c.redIAdd(c); + var d = this.curve._mulA(a), + e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b), + g = d.redAdd(b), + f = g.redSub(c), + h = d.redSub(b), + nx = e.redMul(f), + ny = g.redMul(h), + nt = e.redMul(h), + nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + Point.prototype._projDbl = function () { + var b = this.x.redAdd(this.y).redSqr(), + c = this.x.redSqr(), + d = this.y.redSqr(), + nx, + ny, + nz, + e, + h, + j; + if (this.curve.twisted) { + e = this.curve._mulA(c); + var f = e.redAdd(d); + this.zOne + ? ((nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two))), + (ny = f.redMul(e.redSub(d))), + (nz = f.redSqr().redSub(f).redSub(f))) + : ((h = this.z.redSqr()), + (j = f.redSub(h).redISub(h)), + (nx = b.redSub(c).redISub(d).redMul(j)), + (ny = f.redMul(e.redSub(d))), + (nz = f.redMul(j))); + } else + (e = c.redAdd(d)), + (h = this.curve._mulC(this.z).redSqr()), + (j = e.redSub(h).redSub(h)), + (nx = this.curve._mulC(b.redISub(e)).redMul(j)), + (ny = this.curve._mulC(e).redMul(c.redISub(d))), + (nz = e.redMul(j)); + return this.curve.point(nx, ny, nz); + }; + Point.prototype.dbl = function () { + return this.isInfinity() ? this : this.curve.extended ? this._extDbl() : this._projDbl(); + }; + Point.prototype._extAdd = function (p) { + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)), + b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)), + c = this.t.redMul(this.curve.dd).redMul(p.t), + d = this.z.redMul(p.z.redAdd(p.z)), + e = b.redSub(a), + f = d.redSub(c), + g = d.redAdd(c), + h = b.redAdd(a), + nx = e.redMul(f), + ny = g.redMul(h), + nt = e.redMul(h), + nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); + }; + Point.prototype._projAdd = function (p) { + var a = this.z.redMul(p.z), + b = a.redSqr(), + c = this.x.redMul(p.x), + d = this.y.redMul(p.y), + e = this.curve.d.redMul(c).redMul(d), + f = b.redSub(e), + g = b.redAdd(e), + tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d), + nx = a.redMul(f).redMul(tmp), + ny, + nz; + return ( + this.curve.twisted + ? ((ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)))), (nz = f.redMul(g))) + : ((ny = a.redMul(g).redMul(d.redSub(c))), (nz = this.curve._mulC(f).redMul(g))), + this.curve.point(nx, ny, nz) + ); + }; + Point.prototype.add = function (p) { + return this.isInfinity() ? p : p.isInfinity() ? this : this.curve.extended ? this._extAdd(p) : this._projAdd(p); + }; + Point.prototype.mul = function (k) { + return this._hasDoubles(k) ? this.curve._fixedNafMul(this, k) : this.curve._wnafMul(this, k); + }; + Point.prototype.mulAdd = function (k1, p, k2) { + return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, !1); + }; + Point.prototype.jmulAdd = function (k1, p, k2) { + return this.curve._wnafMulAdd(1, [this, p], [k1, k2], 2, !0); + }; + Point.prototype.normalize = function () { + if (this.zOne) return this; + var zi = this.z.redInvm(); + return ( + (this.x = this.x.redMul(zi)), + (this.y = this.y.redMul(zi)), + this.t && (this.t = this.t.redMul(zi)), + (this.z = this.curve.one), + (this.zOne = !0), + this + ); + }; + Point.prototype.neg = function () { + return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg()); + }; + Point.prototype.getX = function () { + return this.normalize(), this.x.fromRed(); + }; + Point.prototype.getY = function () { + return this.normalize(), this.y.fromRed(); + }; + Point.prototype.eq = function (other) { + return this === other || (this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0); + }; + Point.prototype.eqXToP = function (x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) return !0; + for (var xc = x.clone(), t = this.curve.redN.redMul(this.z); ; ) { + if ((xc.iadd(this.curve.n), xc.cmp(this.curve.p) >= 0)) return !1; + if ((rx.redIAdd(t), this.x.cmp(rx) === 0)) return !0; + } + }; + Point.prototype.toP = Point.prototype.normalize; + Point.prototype.mixedAdd = Point.prototype.add; + }, +}); + +// node_modules/elliptic/lib/elliptic/curve/index.js +var require_curve = __commonJS({ + "node_modules/elliptic/lib/elliptic/curve/index.js"(exports) { + "use strict"; + var curve = exports; + curve.base = require_base(); + curve.short = require_short(); + curve.mont = require_mont(); + curve.edwards = require_edwards(); + }, +}); + +// node_modules/hash.js/lib/hash/utils.js +var require_utils4 = __commonJS({ + "node_modules/hash.js/lib/hash/utils.js"(exports) { + "use strict"; + var assert = require_minimalistic_assert(), + inherits = require_inherits_browser(); + exports.inherits = inherits; + function isSurrogatePair(msg, i) { + return (msg.charCodeAt(i) & 64512) !== 55296 || i < 0 || i + 1 >= msg.length + ? !1 + : (msg.charCodeAt(i + 1) & 64512) === 56320; + } + function toArray(msg, enc) { + if (Array.isArray(msg)) return msg.slice(); + if (!msg) return []; + var res = []; + if (typeof msg == "string") + if (enc) { + if (enc === "hex") + for ( + msg = msg.replace(/[^a-z0-9]+/gi, ""), msg.length % 2 !== 0 && (msg = "0" + msg), i = 0; + i < msg.length; + i += 2 + ) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else + for (var p = 0, i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + c < 128 + ? (res[p++] = c) + : c < 2048 + ? ((res[p++] = (c >> 6) | 192), (res[p++] = (c & 63) | 128)) + : isSurrogatePair(msg, i) + ? ((c = 65536 + ((c & 1023) << 10) + (msg.charCodeAt(++i) & 1023)), + (res[p++] = (c >> 18) | 240), + (res[p++] = ((c >> 12) & 63) | 128), + (res[p++] = ((c >> 6) & 63) | 128), + (res[p++] = (c & 63) | 128)) + : ((res[p++] = (c >> 12) | 224), (res[p++] = ((c >> 6) & 63) | 128), (res[p++] = (c & 63) | 128)); } + else for (i = 0; i < msg.length; i++) res[i] = msg[i] | 0; + return res; + } + exports.toArray = toArray; + function toHex(msg) { + for (var res = "", i = 0; i < msg.length; i++) res += zero2(msg[i].toString(16)); + return res; + } + exports.toHex = toHex; + function htonl(w) { + var res = (w >>> 24) | ((w >>> 8) & 65280) | ((w << 8) & 16711680) | ((w & 255) << 24); + return res >>> 0; + } + exports.htonl = htonl; + function toHex32(msg, endian) { + for (var res = "", i = 0; i < msg.length; i++) { + var w = msg[i]; + endian === "little" && (w = htonl(w)), (res += zero8(w.toString(16))); + } + return res; + } + exports.toHex32 = toHex32; + function zero2(word) { + return word.length === 1 ? "0" + word : word; + } + exports.zero2 = zero2; + function zero8(word) { + return word.length === 7 + ? "0" + word + : word.length === 6 + ? "00" + word + : word.length === 5 + ? "000" + word + : word.length === 4 + ? "0000" + word + : word.length === 3 + ? "00000" + word + : word.length === 2 + ? "000000" + word + : word.length === 1 + ? "0000000" + word + : word; + } + exports.zero8 = zero8; + function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + for (var res = new Array(len / 4), i = 0, k = start; i < res.length; i++, k += 4) { + var w; + endian === "big" + ? (w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]) + : (w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]), + (res[i] = w >>> 0); + } + return res; + } + exports.join32 = join32; + function split32(msg, endian) { + for (var res = new Array(msg.length * 4), i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + endian === "big" + ? ((res[k] = m >>> 24), + (res[k + 1] = (m >>> 16) & 255), + (res[k + 2] = (m >>> 8) & 255), + (res[k + 3] = m & 255)) + : ((res[k + 3] = m >>> 24), + (res[k + 2] = (m >>> 16) & 255), + (res[k + 1] = (m >>> 8) & 255), + (res[k] = m & 255)); + } + return res; + } + exports.split32 = split32; + function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); + } + exports.rotr32 = rotr32; + function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); + } + exports.rotl32 = rotl32; + function sum32(a, b) { + return (a + b) >>> 0; + } + exports.sum32 = sum32; + function sum32_3(a, b, c) { + return (a + b + c) >>> 0; + } + exports.sum32_3 = sum32_3; + function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; + } + exports.sum32_4 = sum32_4; + function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; + } + exports.sum32_5 = sum32_5; + function sum64(buf, pos, ah, al) { + var bh = buf[pos], + bl = buf[pos + 1], + lo = (al + bl) >>> 0, + hi = (lo < al ? 1 : 0) + ah + bh; + (buf[pos] = hi >>> 0), (buf[pos + 1] = lo); + } + exports.sum64 = sum64; + function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0, + hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; + } + exports.sum64_hi = sum64_hi; + function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; + } + exports.sum64_lo = sum64_lo; + function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0, + lo = al; + (lo = (lo + bl) >>> 0), + (carry += lo < al ? 1 : 0), + (lo = (lo + cl) >>> 0), + (carry += lo < cl ? 1 : 0), + (lo = (lo + dl) >>> 0), + (carry += lo < dl ? 1 : 0); + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; + } + exports.sum64_4_hi = sum64_4_hi; + function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; + } + exports.sum64_4_lo = sum64_4_lo; + function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0, + lo = al; + (lo = (lo + bl) >>> 0), + (carry += lo < al ? 1 : 0), + (lo = (lo + cl) >>> 0), + (carry += lo < cl ? 1 : 0), + (lo = (lo + dl) >>> 0), + (carry += lo < dl ? 1 : 0), + (lo = (lo + el) >>> 0), + (carry += lo < el ? 1 : 0); + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; + } + exports.sum64_5_hi = sum64_5_hi; + function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + return lo >>> 0; + } + exports.sum64_5_lo = sum64_5_lo; + function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; + } + exports.rotr64_hi = rotr64_hi; + function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + exports.rotr64_lo = rotr64_lo; + function shr64_hi(ah, al, num) { + return ah >>> num; + } + exports.shr64_hi = shr64_hi; + function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; + } + exports.shr64_lo = shr64_lo; + }, +}); + +// node_modules/hash.js/lib/hash/common.js +var require_common = __commonJS({ + "node_modules/hash.js/lib/hash/common.js"(exports) { + "use strict"; + var utils = require_utils4(), + assert = require_minimalistic_assert(); + function BlockHash() { + (this.pending = null), + (this.pendingTotal = 0), + (this.blockSize = this.constructor.blockSize), + (this.outSize = this.constructor.outSize), + (this.hmacStrength = this.constructor.hmacStrength), + (this.padLength = this.constructor.padLength / 8), + (this.endian = "big"), + (this._delta8 = this.blockSize / 8), + (this._delta32 = this.blockSize / 32); + } + BlockHash.prototype = {}; + exports.BlockHash = BlockHash; + BlockHash.prototype.update = function (msg, enc) { + if ( + ((msg = utils.toArray(msg, enc)), + this.pending ? (this.pending = this.pending.concat(msg)) : (this.pending = msg), + (this.pendingTotal += msg.length), + this.pending.length >= this._delta8) + ) { + msg = this.pending; + var r = msg.length % this._delta8; + (this.pending = msg.slice(msg.length - r, msg.length)), + this.pending.length === 0 && (this.pending = null), + (msg = utils.join32(msg, 0, msg.length - r, this.endian)); + for (var i = 0; i < msg.length; i += this._delta32) this._update(msg, i, i + this._delta32); + } + return this; + }; + BlockHash.prototype.digest = function (enc) { + return this.update(this._pad()), assert(this.pending === null), this._digest(enc); + }; + BlockHash.prototype._pad = function () { + var len = this.pendingTotal, + bytes = this._delta8, + k = bytes - ((len + this.padLength) % bytes), + res = new Array(k + this.padLength); + res[0] = 128; + for (var i = 1; i < k; i++) res[i] = 0; + if (((len <<= 3), this.endian === "big")) { + for (var t = 8; t < this.padLength; t++) res[i++] = 0; + (res[i++] = 0), + (res[i++] = 0), + (res[i++] = 0), + (res[i++] = 0), + (res[i++] = (len >>> 24) & 255), + (res[i++] = (len >>> 16) & 255), + (res[i++] = (len >>> 8) & 255), + (res[i++] = len & 255); + } else + for ( + res[i++] = len & 255, + res[i++] = (len >>> 8) & 255, + res[i++] = (len >>> 16) & 255, + res[i++] = (len >>> 24) & 255, + res[i++] = 0, + res[i++] = 0, + res[i++] = 0, + res[i++] = 0, + t = 8; + t < this.padLength; + t++ + ) + res[i++] = 0; + return res; + }; + }, +}); + +// node_modules/hash.js/lib/hash/sha/common.js +var require_common2 = __commonJS({ + "node_modules/hash.js/lib/hash/sha/common.js"(exports) { + "use strict"; + var utils = require_utils4(), + rotr32 = utils.rotr32; + function ft_1(s, x, y, z) { + if (s === 0) return ch32(x, y, z); + if (s === 1 || s === 3) return p32(x, y, z); + if (s === 2) return maj32(x, y, z); + } + exports.ft_1 = ft_1; + function ch32(x, y, z) { + return (x & y) ^ (~x & z); + } + exports.ch32 = ch32; + function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); + } + exports.maj32 = maj32; + function p32(x, y, z) { + return x ^ y ^ z; + } + exports.p32 = p32; + function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); + } + exports.s0_256 = s0_256; + function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); + } + exports.s1_256 = s1_256; + function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); + } + exports.g0_256 = g0_256; + function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); + } + exports.g1_256 = g1_256; + }, +}); + +// node_modules/hash.js/lib/hash/sha/1.js +var require__ = __commonJS({ + "node_modules/hash.js/lib/hash/sha/1.js"(exports, module) { + "use strict"; + var utils = require_utils4(), + common = require_common(), + shaCommon = require_common2(), + rotl32 = utils.rotl32, + sum32 = utils.sum32, + sum32_5 = utils.sum32_5, + ft_1 = shaCommon.ft_1, + BlockHash = common.BlockHash, + sha1_K = [1518500249, 1859775393, 2400959708, 3395469782]; + function SHA1() { + if (!(this instanceof SHA1)) return new SHA1(); + BlockHash.call(this), + (this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]), + (this.W = new Array(80)); + } + utils.inherits(SHA1, BlockHash); + module.exports = SHA1; + SHA1.blockSize = 512; + SHA1.outSize = 160; + SHA1.hmacStrength = 80; + SHA1.padLength = 64; + SHA1.prototype._update = function (msg, start) { + for (var W = this.W, i = 0; i < 16; i++) W[i] = msg[start + i]; + for (; i < W.length; i++) W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + var a = this.h[0], + b = this.h[1], + c = this.h[2], + d = this.h[3], + e = this.h[4]; + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20), + t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + (e = d), (d = c), (c = rotl32(b, 30)), (b = a), (a = t); + } + (this.h[0] = sum32(this.h[0], a)), + (this.h[1] = sum32(this.h[1], b)), + (this.h[2] = sum32(this.h[2], c)), + (this.h[3] = sum32(this.h[3], d)), + (this.h[4] = sum32(this.h[4], e)); + }; + SHA1.prototype._digest = function (enc) { + return enc === "hex" ? utils.toHex32(this.h, "big") : utils.split32(this.h, "big"); + }; + }, +}); + +// node_modules/hash.js/lib/hash/sha/256.js +var require__2 = __commonJS({ + "node_modules/hash.js/lib/hash/sha/256.js"(exports, module) { + "use strict"; + var utils = require_utils4(), + common = require_common(), + shaCommon = require_common2(), + assert = require_minimalistic_assert(), + sum32 = utils.sum32, + sum32_4 = utils.sum32_4, + sum32_5 = utils.sum32_5, + ch32 = shaCommon.ch32, + maj32 = shaCommon.maj32, + s0_256 = shaCommon.s0_256, + s1_256 = shaCommon.s1_256, + g0_256 = shaCommon.g0_256, + g1_256 = shaCommon.g1_256, + BlockHash = common.BlockHash, + sha256_K = [ + 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, + 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, + 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, + 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, + 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, + 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, + 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, + 3329325298, + ]; + function SHA256() { + if (!(this instanceof SHA256)) return new SHA256(); + BlockHash.call(this), + (this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]), + (this.k = sha256_K), + (this.W = new Array(64)); + } + utils.inherits(SHA256, BlockHash); + module.exports = SHA256; + SHA256.blockSize = 512; + SHA256.outSize = 256; + SHA256.hmacStrength = 192; + SHA256.padLength = 64; + SHA256.prototype._update = function (msg, start) { + for (var W = this.W, i = 0; i < 16; i++) W[i] = msg[start + i]; + for (; i < W.length; i++) W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + var a = this.h[0], + b = this.h[1], + c = this.h[2], + d = this.h[3], + e = this.h[4], + f = this.h[5], + g = this.h[6], + h = this.h[7]; + for (assert(this.k.length === W.length), i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]), + T2 = sum32(s0_256(a), maj32(a, b, c)); + (h = g), (g = f), (f = e), (e = sum32(d, T1)), (d = c), (c = b), (b = a), (a = sum32(T1, T2)); + } + (this.h[0] = sum32(this.h[0], a)), + (this.h[1] = sum32(this.h[1], b)), + (this.h[2] = sum32(this.h[2], c)), + (this.h[3] = sum32(this.h[3], d)), + (this.h[4] = sum32(this.h[4], e)), + (this.h[5] = sum32(this.h[5], f)), + (this.h[6] = sum32(this.h[6], g)), + (this.h[7] = sum32(this.h[7], h)); + }; + SHA256.prototype._digest = function (enc) { + return enc === "hex" ? utils.toHex32(this.h, "big") : utils.split32(this.h, "big"); + }; + }, +}); + +// node_modules/hash.js/lib/hash/sha/224.js +var require__3 = __commonJS({ + "node_modules/hash.js/lib/hash/sha/224.js"(exports, module) { + "use strict"; + var utils = require_utils4(), + SHA256 = require__2(); + function SHA224() { + if (!(this instanceof SHA224)) return new SHA224(); + SHA256.call(this), + (this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]); + } + utils.inherits(SHA224, SHA256); + module.exports = SHA224; + SHA224.blockSize = 512; + SHA224.outSize = 224; + SHA224.hmacStrength = 192; + SHA224.padLength = 64; + SHA224.prototype._digest = function (enc) { + return enc === "hex" ? utils.toHex32(this.h.slice(0, 7), "big") : utils.split32(this.h.slice(0, 7), "big"); + }; + }, +}); + +// node_modules/hash.js/lib/hash/sha/512.js +var require__4 = __commonJS({ + "node_modules/hash.js/lib/hash/sha/512.js"(exports, module) { + "use strict"; + var utils = require_utils4(), + common = require_common(), + assert = require_minimalistic_assert(), + rotr64_hi = utils.rotr64_hi, + rotr64_lo = utils.rotr64_lo, + shr64_hi = utils.shr64_hi, + shr64_lo = utils.shr64_lo, + sum64 = utils.sum64, + sum64_hi = utils.sum64_hi, + sum64_lo = utils.sum64_lo, + sum64_4_hi = utils.sum64_4_hi, + sum64_4_lo = utils.sum64_4_lo, + sum64_5_hi = utils.sum64_5_hi, + sum64_5_lo = utils.sum64_5_lo, + BlockHash = common.BlockHash, + sha512_K = [ + 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, + 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, + 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, + 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, + 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, + 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, + 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, + 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, + 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, + 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, + 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, + 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, + 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, + 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, + 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, + 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, + 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, + 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591, + ]; + function SHA512() { + if (!(this instanceof SHA512)) return new SHA512(); + BlockHash.call(this), + (this.h = [ + 1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, + 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209, + ]), + (this.k = sha512_K), + (this.W = new Array(160)); + } + utils.inherits(SHA512, BlockHash); + module.exports = SHA512; + SHA512.blockSize = 1024; + SHA512.outSize = 512; + SHA512.hmacStrength = 192; + SHA512.padLength = 128; + SHA512.prototype._prepareBlock = function (msg, start) { + for (var W = this.W, i = 0; i < 32; i++) W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]), + c0_lo = g1_512_lo(W[i - 4], W[i - 3]), + c1_hi = W[i - 14], + c1_lo = W[i - 13], + c2_hi = g0_512_hi(W[i - 30], W[i - 29]), + c2_lo = g0_512_lo(W[i - 30], W[i - 29]), + c3_hi = W[i - 32], + c3_lo = W[i - 31]; + (W[i] = sum64_4_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo)), + (W[i + 1] = sum64_4_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo)); + } + }; + SHA512.prototype._update = function (msg, start) { + this._prepareBlock(msg, start); + var W = this.W, + ah = this.h[0], + al = this.h[1], + bh = this.h[2], + bl = this.h[3], + ch = this.h[4], + cl = this.h[5], + dh = this.h[6], + dl = this.h[7], + eh = this.h[8], + el = this.h[9], + fh = this.h[10], + fl = this.h[11], + gh = this.h[12], + gl = this.h[13], + hh = this.h[14], + hl = this.h[15]; + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh, + c0_lo = hl, + c1_hi = s1_512_hi(eh, el), + c1_lo = s1_512_lo(eh, el), + c2_hi = ch64_hi(eh, el, fh, fl, gh, gl), + c2_lo = ch64_lo(eh, el, fh, fl, gh, gl), + c3_hi = this.k[i], + c3_lo = this.k[i + 1], + c4_hi = W[i], + c4_lo = W[i + 1], + T1_hi = sum64_5_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo), + T1_lo = sum64_5_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); + (c0_hi = s0_512_hi(ah, al)), + (c0_lo = s0_512_lo(ah, al)), + (c1_hi = maj64_hi(ah, al, bh, bl, ch, cl)), + (c1_lo = maj64_lo(ah, al, bh, bl, ch, cl)); + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo), + T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + (hh = gh), + (hl = gl), + (gh = fh), + (gl = fl), + (fh = eh), + (fl = el), + (eh = sum64_hi(dh, dl, T1_hi, T1_lo)), + (el = sum64_lo(dl, dl, T1_hi, T1_lo)), + (dh = ch), + (dl = cl), + (ch = bh), + (cl = bl), + (bh = ah), + (bl = al), + (ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo)), + (al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo)); + } + sum64(this.h, 0, ah, al), + sum64(this.h, 2, bh, bl), + sum64(this.h, 4, ch, cl), + sum64(this.h, 6, dh, dl), + sum64(this.h, 8, eh, el), + sum64(this.h, 10, fh, fl), + sum64(this.h, 12, gh, gl), + sum64(this.h, 14, hh, hl); + }; + SHA512.prototype._digest = function (enc) { + return enc === "hex" ? utils.toHex32(this.h, "big") : utils.split32(this.h, "big"); + }; + function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (~xh & zh); + return r < 0 && (r += 4294967296), r; + } + function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (~xl & zl); + return r < 0 && (r += 4294967296), r; + } + function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + return r < 0 && (r += 4294967296), r; + } + function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + return r < 0 && (r += 4294967296), r; + } + function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28), + c1_hi = rotr64_hi(xl, xh, 2), + c2_hi = rotr64_hi(xl, xh, 7), + r = c0_hi ^ c1_hi ^ c2_hi; + return r < 0 && (r += 4294967296), r; + } + function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28), + c1_lo = rotr64_lo(xl, xh, 2), + c2_lo = rotr64_lo(xl, xh, 7), + r = c0_lo ^ c1_lo ^ c2_lo; + return r < 0 && (r += 4294967296), r; + } + function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14), + c1_hi = rotr64_hi(xh, xl, 18), + c2_hi = rotr64_hi(xl, xh, 9), + r = c0_hi ^ c1_hi ^ c2_hi; + return r < 0 && (r += 4294967296), r; + } + function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14), + c1_lo = rotr64_lo(xh, xl, 18), + c2_lo = rotr64_lo(xl, xh, 9), + r = c0_lo ^ c1_lo ^ c2_lo; + return r < 0 && (r += 4294967296), r; + } + function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1), + c1_hi = rotr64_hi(xh, xl, 8), + c2_hi = shr64_hi(xh, xl, 7), + r = c0_hi ^ c1_hi ^ c2_hi; + return r < 0 && (r += 4294967296), r; + } + function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1), + c1_lo = rotr64_lo(xh, xl, 8), + c2_lo = shr64_lo(xh, xl, 7), + r = c0_lo ^ c1_lo ^ c2_lo; + return r < 0 && (r += 4294967296), r; + } + function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19), + c1_hi = rotr64_hi(xl, xh, 29), + c2_hi = shr64_hi(xh, xl, 6), + r = c0_hi ^ c1_hi ^ c2_hi; + return r < 0 && (r += 4294967296), r; + } + function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19), + c1_lo = rotr64_lo(xl, xh, 29), + c2_lo = shr64_lo(xh, xl, 6), + r = c0_lo ^ c1_lo ^ c2_lo; + return r < 0 && (r += 4294967296), r; + } + }, +}); + +// node_modules/hash.js/lib/hash/sha/384.js +var require__5 = __commonJS({ + "node_modules/hash.js/lib/hash/sha/384.js"(exports, module) { + "use strict"; + var utils = require_utils4(), + SHA512 = require__4(); + function SHA384() { + if (!(this instanceof SHA384)) return new SHA384(); + SHA512.call(this), + (this.h = [ + 3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, + 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428, + ]); + } + utils.inherits(SHA384, SHA512); + module.exports = SHA384; + SHA384.blockSize = 1024; + SHA384.outSize = 384; + SHA384.hmacStrength = 192; + SHA384.padLength = 128; + SHA384.prototype._digest = function (enc) { + return enc === "hex" ? utils.toHex32(this.h.slice(0, 12), "big") : utils.split32(this.h.slice(0, 12), "big"); + }; + }, +}); + +// node_modules/hash.js/lib/hash/sha.js +var require_sha3 = __commonJS({ + "node_modules/hash.js/lib/hash/sha.js"(exports) { + "use strict"; + exports.sha1 = require__(); + exports.sha224 = require__3(); + exports.sha256 = require__2(); + exports.sha384 = require__5(); + exports.sha512 = require__4(); + }, +}); + +// node_modules/hash.js/lib/hash/ripemd.js +var require_ripemd = __commonJS({ + "node_modules/hash.js/lib/hash/ripemd.js"(exports) { + "use strict"; + var utils = require_utils4(), + common = require_common(), + rotl32 = utils.rotl32, + sum32 = utils.sum32, + sum32_3 = utils.sum32_3, + sum32_4 = utils.sum32_4, + BlockHash = common.BlockHash; + function RIPEMD160() { + if (!(this instanceof RIPEMD160)) return new RIPEMD160(); + BlockHash.call(this), + (this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]), + (this.endian = "little"); + } + utils.inherits(RIPEMD160, BlockHash); + exports.ripemd160 = RIPEMD160; + RIPEMD160.blockSize = 512; + RIPEMD160.outSize = 160; + RIPEMD160.hmacStrength = 192; + RIPEMD160.padLength = 64; + RIPEMD160.prototype._update = function (msg, start) { + for ( + var A = this.h[0], + B = this.h[1], + C = this.h[2], + D = this.h[3], + E = this.h[4], + Ah = A, + Bh = B, + Ch = C, + Dh = D, + Eh = E, + j = 0; + j < 80; + j++ + ) { + var T = sum32(rotl32(sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), s[j]), E); + (A = E), + (E = D), + (D = rotl32(C, 10)), + (C = B), + (B = T), + (T = sum32(rotl32(sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh)), + (Ah = Eh), + (Eh = Dh), + (Dh = rotl32(Ch, 10)), + (Ch = Bh), + (Bh = T); + } + (T = sum32_3(this.h[1], C, Dh)), + (this.h[1] = sum32_3(this.h[2], D, Eh)), + (this.h[2] = sum32_3(this.h[3], E, Ah)), + (this.h[3] = sum32_3(this.h[4], A, Bh)), + (this.h[4] = sum32_3(this.h[0], B, Ch)), + (this.h[0] = T); + }; + RIPEMD160.prototype._digest = function (enc) { + return enc === "hex" ? utils.toHex32(this.h, "little") : utils.split32(this.h, "little"); + }; + function f(j, x, y, z) { + return j <= 15 + ? x ^ y ^ z + : j <= 31 + ? (x & y) | (~x & z) + : j <= 47 + ? (x | ~y) ^ z + : j <= 63 + ? (x & z) | (y & ~z) + : x ^ (y | ~z); + } + function K(j) { + return j <= 15 ? 0 : j <= 31 ? 1518500249 : j <= 47 ? 1859775393 : j <= 63 ? 2400959708 : 2840853838; + } + function Kh(j) { + return j <= 15 ? 1352829926 : j <= 31 ? 1548603684 : j <= 47 ? 1836072691 : j <= 63 ? 2053994217 : 0; + } + var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, + 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, + 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, + ], + rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, + 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, + 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11, + ], + s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, + ], + sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11, + ]; + }, +}); + +// node_modules/hash.js/lib/hash/hmac.js +var require_hmac = __commonJS({ + "node_modules/hash.js/lib/hash/hmac.js"(exports, module) { + "use strict"; + var utils = require_utils4(), + assert = require_minimalistic_assert(); + function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) return new Hmac(hash, key, enc); + (this.Hash = hash), + (this.blockSize = hash.blockSize / 8), + (this.outSize = hash.outSize / 8), + (this.inner = null), + (this.outer = null), + this._init(utils.toArray(key, enc)); + } + Hmac.prototype = {}; + module.exports = Hmac; + Hmac.prototype._init = function (key) { + key.length > this.blockSize && (key = new this.Hash().update(key).digest()), assert(key.length <= this.blockSize); + for (var i = key.length; i < this.blockSize; i++) key.push(0); + for (i = 0; i < key.length; i++) key[i] ^= 54; + for (this.inner = new this.Hash().update(key), i = 0; i < key.length; i++) key[i] ^= 106; + this.outer = new this.Hash().update(key); + }; + Hmac.prototype.update = function (msg, enc) { + return this.inner.update(msg, enc), this; + }; + Hmac.prototype.digest = function (enc) { + return this.outer.update(this.inner.digest()), this.outer.digest(enc); + }; + }, +}); + +// node_modules/hash.js/lib/hash.js +var require_hash2 = __commonJS({ + "node_modules/hash.js/lib/hash.js"(exports) { + var hash = exports; + hash.utils = require_utils4(); + hash.common = require_common(); + hash.sha = require_sha3(); + hash.ripemd = require_ripemd(); + hash.hmac = require_hmac(); + hash.sha1 = hash.sha.sha1; + hash.sha256 = hash.sha.sha256; + hash.sha224 = hash.sha.sha224; + hash.sha384 = hash.sha.sha384; + hash.sha512 = hash.sha.sha512; + hash.ripemd160 = hash.ripemd.ripemd160; + }, +}); + +// node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js +var require_secp256k1 = __commonJS({ + "node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js"(exports, module) { + module.exports = { + doubles: { + step: 4, + points: [ + [ + "e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a", + "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821", + ], + [ + "8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508", + "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf", + ], + [ + "175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739", + "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695", + ], + [ + "363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640", + "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9", + ], + [ + "8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c", + "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36", + ], + [ + "723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda", + "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f", + ], + [ + "eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa", + "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999", + ], + [ + "100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0", + "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09", + ], + [ + "e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d", + "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d", + ], + [ + "feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d", + "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088", + ], + [ + "da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1", + "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d", + ], + [ + "53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0", + "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8", + ], + [ + "8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047", + "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a", + ], + [ + "385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862", + "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453", + ], + [ + "6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7", + "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160", + ], + [ + "3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd", + "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0", + ], + [ + "85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83", + "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6", + ], + [ + "948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a", + "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589", + ], + [ + "6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8", + "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17", + ], + [ + "e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d", + "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda", + ], + [ + "e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725", + "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd", + ], + [ + "213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754", + "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2", + ], + [ + "4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c", + "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6", + ], + [ + "fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6", + "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f", + ], + [ + "76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39", + "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01", + ], + [ + "c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891", + "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3", + ], + [ + "d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b", + "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f", + ], + [ + "b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03", + "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7", + ], + [ + "e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d", + "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78", + ], + [ + "a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070", + "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1", + ], + [ + "90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4", + "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150", + ], + [ + "8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da", + "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82", + ], + [ + "e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11", + "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc", + ], + [ + "8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e", + "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b", + ], + [ + "e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41", + "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51", + ], + [ + "b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef", + "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45", + ], + [ + "d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8", + "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120", + ], + [ + "324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d", + "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84", + ], + [ + "4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96", + "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d", + ], + [ + "9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd", + "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d", + ], + [ + "6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5", + "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8", + ], + [ + "a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266", + "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8", + ], + [ + "7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71", + "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac", + ], + [ + "928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac", + "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f", + ], + [ + "85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751", + "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962", + ], + [ + "ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e", + "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907", + ], + [ + "827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241", + "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec", + ], + [ + "eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3", + "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d", + ], + [ + "e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f", + "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414", + ], + [ + "1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19", + "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd", + ], + [ + "146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be", + "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0", + ], + [ + "fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9", + "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811", + ], + [ + "da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2", + "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1", + ], + [ + "a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13", + "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c", + ], + [ + "174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c", + "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73", + ], + [ + "959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba", + "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd", + ], + [ + "d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151", + "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405", + ], + [ + "64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073", + "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589", + ], + [ + "8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458", + "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e", + ], + [ + "13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b", + "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27", + ], + [ + "bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366", + "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1", + ], + [ + "8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa", + "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482", + ], + [ + "8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0", + "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945", + ], + [ + "dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787", + "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573", + ], + [ + "f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e", + "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82", + ], + ], + }, + naf: { + wnd: 7, + points: [ + [ + "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", + "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672", + ], + [ + "2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4", + "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6", + ], + [ + "5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", + "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da", + ], + [ + "acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe", + "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37", + ], + [ + "774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb", + "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b", + ], + [ + "f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8", + "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81", + ], + [ + "d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e", + "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58", + ], + [ + "defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34", + "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77", + ], + [ + "2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c", + "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a", + ], + [ + "352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5", + "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c", + ], + [ + "2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f", + "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67", + ], + [ + "9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714", + "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402", + ], + [ + "daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729", + "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55", + ], + [ + "c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db", + "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482", + ], + [ + "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", + "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82", + ], + [ + "1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5", + "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396", + ], + [ + "605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479", + "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49", + ], + [ + "62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d", + "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf", + ], + [ + "80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f", + "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a", + ], + [ + "7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb", + "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7", + ], + [ + "d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9", + "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933", + ], + [ + "49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963", + "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a", + ], + [ + "77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74", + "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6", + ], + [ + "f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530", + "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37", + ], + [ + "463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b", + "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e", + ], + [ + "f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247", + "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6", + ], + [ + "caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1", + "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476", + ], + [ + "2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120", + "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40", + ], + [ + "7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435", + "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61", + ], + [ + "754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18", + "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683", + ], + [ + "e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8", + "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5", + ], + [ + "186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb", + "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b", + ], + [ + "df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f", + "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417", + ], + [ + "5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143", + "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868", + ], + [ + "290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba", + "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a", + ], + [ + "af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45", + "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6", + ], + [ + "766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a", + "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996", + ], + [ + "59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e", + "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e", + ], + [ + "f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8", + "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d", + ], + [ + "7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c", + "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2", + ], + [ + "948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519", + "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e", + ], + [ + "7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab", + "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437", + ], + [ + "3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca", + "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311", + ], + [ + "d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf", + "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4", + ], + [ + "1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610", + "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575", + ], + [ + "733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4", + "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d", + ], + [ + "15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c", + "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d", + ], + [ + "a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940", + "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629", + ], + [ + "e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980", + "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06", + ], + [ + "311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3", + "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374", + ], + [ + "34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf", + "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee", + ], + [ + "f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63", + "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1", + ], + [ + "d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448", + "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b", + ], + [ + "32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf", + "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661", + ], + [ + "7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5", + "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6", + ], + [ + "ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6", + "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e", + ], + [ + "16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5", + "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d", + ], + [ + "eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99", + "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc", + ], + [ + "78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51", + "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4", + ], + [ + "494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5", + "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c", + ], + [ + "a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5", + "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b", + ], + [ + "c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997", + "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913", + ], + [ + "841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881", + "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154", + ], + [ + "5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5", + "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865", + ], + [ + "36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66", + "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc", + ], + [ + "336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726", + "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224", + ], + [ + "8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede", + "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e", + ], + [ + "1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94", + "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6", + ], + [ + "85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31", + "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511", + ], + [ + "29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51", + "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b", + ], + [ + "a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252", + "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2", + ], + [ + "4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5", + "cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c", + ], + [ + "d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b", + "6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3", + ], + [ + "ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4", + "322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d", + ], + [ + "af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f", + "6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700", + ], + [ + "e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889", + "2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4", + ], + [ + "591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246", + "b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196", + ], + [ + "11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984", + "998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4", + ], + [ + "3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a", + "b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257", + ], + [ + "cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030", + "bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13", + ], + [ + "c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197", + "6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096", + ], + [ + "c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593", + "c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38", + ], + [ + "a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef", + "21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f", + ], + [ + "347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38", + "60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448", + ], + [ + "da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a", + "49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a", + ], + [ + "c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111", + "5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4", + ], + [ + "4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502", + "7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437", + ], + [ + "3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea", + "be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7", + ], + [ + "cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26", + "8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d", + ], + [ + "b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986", + "39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a", + ], + [ + "d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e", + "62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54", + ], + [ + "48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4", + "25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77", + ], + [ + "dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda", + "ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517", + ], + [ + "6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859", + "cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10", + ], + [ + "e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f", + "f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125", + ], + [ + "eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c", + "6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e", + ], + [ + "13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942", + "fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1", + ], + [ + "ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a", + "1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2", + ], + [ + "b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80", + "5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423", + ], + [ + "ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d", + "438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8", + ], + [ + "8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1", + "cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758", + ], + [ + "52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63", + "c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375", + ], + [ + "e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352", + "6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d", + ], + [ + "7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193", + "ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec", + ], + [ + "5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00", + "9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0", + ], + [ + "32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58", + "ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c", + ], + [ + "e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7", + "d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4", + ], + [ + "8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8", + "c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f", + ], + [ + "4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e", + "67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649", + ], + [ + "3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d", + "cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826", + ], + [ + "674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b", + "299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5", + ], + [ + "d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f", + "f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87", + ], + [ + "30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6", + "462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b", + ], + [ + "be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297", + "62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc", + ], + [ + "93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a", + "7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c", + ], + [ + "b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c", + "ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f", + ], + [ + "d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52", + "4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a", + ], + [ + "d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb", + "bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46", + ], + [ + "463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065", + "bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f", + ], + [ + "7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917", + "603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03", + ], + [ + "74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9", + "cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08", + ], + [ + "30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3", + "553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8", + ], + [ + "9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57", + "712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373", + ], + [ + "176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66", + "ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3", + ], + [ + "75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8", + "9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8", + ], + [ + "809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721", + "9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1", + ], + [ + "1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180", + "4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9", + ], + ], + }, + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/curves.js +var require_curves = __commonJS({ + "node_modules/elliptic/lib/elliptic/curves.js"(exports) { + "use strict"; + var curves = exports, + hash = require_hash2(), + curve = require_curve(), + utils = require_utils3(), + assert = utils.assert; + function PresetCurve(options) { + options.type === "short" + ? (this.curve = new curve.short(options)) + : options.type === "edwards" + ? (this.curve = new curve.edwards(options)) + : (this.curve = new curve.mont(options)), + (this.g = this.curve.g), + (this.n = this.curve.n), + (this.hash = options.hash), + assert(this.g.validate(), "Invalid curve"), + assert(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); + } + curves.PresetCurve = PresetCurve; + function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: !0, + enumerable: !0, + get: function () { + var curve2 = new PresetCurve(options); return ( - q && q.strip(), - a.strip(), - mode !== "div" && shift !== 0 && a.iushrn(shift), - { - div: q || null, - mod: a, - } + Object.defineProperty(curves, name, { + configurable: !0, + enumerable: !0, + value: curve2, + }), + curve2 ); - }), - (BN.prototype.divmod = function (num, mode, positive) { - if ((assert(!num.isZero()), this.isZero())) - return { - div: new BN(0), - mod: new BN(0), - }; - var div, mod, res; - return this.negative !== 0 && num.negative === 0 - ? ((res = this.neg().divmod(num, mode)), - mode !== "mod" && (div = res.div.neg()), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.iadd(num)), - { - div, - mod, - }) - : this.negative === 0 && num.negative !== 0 - ? ((res = this.divmod(num.neg(), mode)), - mode !== "mod" && (div = res.div.neg()), - { - div, - mod: res.mod, - }) - : (this.negative & num.negative) !== 0 - ? ((res = this.neg().divmod(num.neg(), mode)), - mode !== "div" && ((mod = res.mod.neg()), positive && mod.negative !== 0 && mod.isub(num)), - { - div: res.div, - mod, - }) - : num.length > this.length || this.cmp(num) < 0 - ? { - div: new BN(0), - mod: this, + }, + }); + } + defineCurve("p192", { + type: "short", + prime: "p192", + p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", + a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", + b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", + n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", + hash: hash.sha256, + gRed: !1, + g: [ + "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", + "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811", + ], + }); + defineCurve("p224", { + type: "short", + prime: "p224", + p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", + a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", + b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", + n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", + hash: hash.sha256, + gRed: !1, + g: [ + "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", + "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34", + ], + }); + defineCurve("p256", { + type: "short", + prime: null, + p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", + a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", + b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", + n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", + hash: hash.sha256, + gRed: !1, + g: [ + "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", + "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5", + ], + }); + defineCurve("p384", { + type: "short", + prime: null, + p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", + a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", + b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", + n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", + hash: hash.sha384, + gRed: !1, + g: [ + "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", + "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f", + ], + }); + defineCurve("p521", { + type: "short", + prime: null, + p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", + a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", + b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", + n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", + hash: hash.sha512, + gRed: !1, + g: [ + "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", + "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650", + ], + }); + defineCurve("curve25519", { + type: "mont", + prime: "p25519", + p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", + a: "76d06", + b: "1", + n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", + hash: hash.sha256, + gRed: !1, + g: ["9"], + }); + defineCurve("ed25519", { + type: "edwards", + prime: "p25519", + p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", + a: "-1", + c: "1", + d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", + n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", + hash: hash.sha256, + gRed: !1, + g: [ + "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", + "6666666666666666666666666666666666666666666666666666666666666658", + ], + }); + var pre; + try { + pre = require_secp256k1(); + } catch { + pre = void 0; + } + defineCurve("secp256k1", { + type: "short", + prime: "k256", + p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", + a: "0", + b: "7", + n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", + h: "1", + hash: hash.sha256, + beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", + lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", + basis: [ + { + a: "3086d221a7d46bcde86c90e49284eb15", + b: "-e4437ed6010e88286f547fa90abfe4c3", + }, + { + a: "114ca50f7a8e2f3f657c1108d9d44cfd8", + b: "3086d221a7d46bcde86c90e49284eb15", + }, + ], + gRed: !1, + g: [ + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", + pre, + ], + }); + }, +}); + +// node_modules/hmac-drbg/lib/hmac-drbg.js +var require_hmac_drbg = __commonJS({ + "node_modules/hmac-drbg/lib/hmac-drbg.js"(exports, module) { + "use strict"; + var hash = require_hash2(), + utils = require_utils2(), + assert = require_minimalistic_assert(); + function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); + (this.hash = options.hash), + (this.predResist = !!options.predResist), + (this.outLen = this.hash.outSize), + (this.minEntropy = options.minEntropy || this.hash.hmacStrength), + (this._reseed = null), + (this.reseedInterval = null), + (this.K = null), + (this.V = null); + var entropy = utils.toArray(options.entropy, options.entropyEnc || "hex"), + nonce = utils.toArray(options.nonce, options.nonceEnc || "hex"), + pers = utils.toArray(options.pers, options.persEnc || "hex"); + assert(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), + this._init(entropy, nonce, pers); + } + HmacDRBG.prototype = {}; + module.exports = HmacDRBG; + HmacDRBG.prototype._init = function (entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + (this.K = new Array(this.outLen / 8)), (this.V = new Array(this.outLen / 8)); + for (var i = 0; i < this.V.length; i++) (this.K[i] = 0), (this.V[i] = 1); + this._update(seed), (this._reseed = 1), (this.reseedInterval = 281474976710656); + }; + HmacDRBG.prototype._hmac = function () { + return new hash.hmac(this.hash, this.K); + }; + HmacDRBG.prototype._update = function (seed) { + var kmac = this._hmac().update(this.V).update([0]); + seed && (kmac = kmac.update(seed)), + (this.K = kmac.digest()), + (this.V = this._hmac().update(this.V).digest()), + seed && + ((this.K = this._hmac().update(this.V).update([1]).update(seed).digest()), + (this.V = this._hmac().update(this.V).digest())); + }; + HmacDRBG.prototype.reseed = function (entropy, entropyEnc, add, addEnc) { + typeof entropyEnc != "string" && ((addEnc = add), (add = entropyEnc), (entropyEnc = null)), + (entropy = utils.toArray(entropy, entropyEnc)), + (add = utils.toArray(add, addEnc)), + assert(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), + this._update(entropy.concat(add || [])), + (this._reseed = 1); + }; + HmacDRBG.prototype.generate = function (len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) throw new Error("Reseed is required"); + typeof enc != "string" && ((addEnc = add), (add = enc), (enc = null)), + add && ((add = utils.toArray(add, addEnc || "hex")), this._update(add)); + for (var temp = []; temp.length < len; ) + (this.V = this._hmac().update(this.V).digest()), (temp = temp.concat(this.V)); + var res = temp.slice(0, len); + return this._update(add), this._reseed++, utils.encode(res, enc); + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/ec/key.js +var require_key = __commonJS({ + "node_modules/elliptic/lib/elliptic/ec/key.js"(exports, module) { + "use strict"; + var BN = require_bn4(), + utils = require_utils3(), + assert = utils.assert; + function KeyPair(ec, options) { + (this.ec = ec), + (this.priv = null), + (this.pub = null), + options.priv && this._importPrivate(options.priv, options.privEnc), + options.pub && this._importPublic(options.pub, options.pubEnc); + } + KeyPair.prototype = {}; + module.exports = KeyPair; + KeyPair.fromPublic = function (ec, pub, enc) { + return pub instanceof KeyPair + ? pub + : new KeyPair(ec, { + pub, + pubEnc: enc, + }); + }; + KeyPair.fromPrivate = function (ec, priv, enc) { + return priv instanceof KeyPair + ? priv + : new KeyPair(ec, { + priv, + privEnc: enc, + }); + }; + KeyPair.prototype.validate = function () { + var pub = this.getPublic(); + return pub.isInfinity() + ? { result: !1, reason: "Invalid public key" } + : pub.validate() + ? pub.mul(this.ec.curve.n).isInfinity() + ? { result: !0, reason: null } + : { result: !1, reason: "Public key * N != O" } + : { result: !1, reason: "Public key is not a point" }; + }; + KeyPair.prototype.getPublic = function (compact, enc) { + return ( + typeof compact == "string" && ((enc = compact), (compact = null)), + this.pub || (this.pub = this.ec.g.mul(this.priv)), + enc ? this.pub.encode(enc, compact) : this.pub + ); + }; + KeyPair.prototype.getPrivate = function (enc) { + return enc === "hex" ? this.priv.toString(16, 2) : this.priv; + }; + KeyPair.prototype._importPrivate = function (key, enc) { + (this.priv = new BN(key, enc || 16)), (this.priv = this.priv.umod(this.ec.curve.n)); + }; + KeyPair.prototype._importPublic = function (key, enc) { + if (key.x || key.y) { + this.ec.curve.type === "mont" + ? assert(key.x, "Need x coordinate") + : (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") && + assert(key.x && key.y, "Need both x and y coordinate"), + (this.pub = this.ec.curve.point(key.x, key.y)); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); + }; + KeyPair.prototype.derive = function (pub) { + return pub.validate() || assert(pub.validate(), "public point not validated"), pub.mul(this.priv).getX(); + }; + KeyPair.prototype.sign = function (msg, enc, options) { + return this.ec.sign(msg, this, enc, options); + }; + KeyPair.prototype.verify = function (msg, signature) { + return this.ec.verify(msg, signature, this); + }; + KeyPair.prototype.inspect = function () { + return ( + "" + ); + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/ec/signature.js +var require_signature = __commonJS({ + "node_modules/elliptic/lib/elliptic/ec/signature.js"(exports, module) { + "use strict"; + var BN = require_bn4(), + utils = require_utils3(), + assert = utils.assert; + function Signature(options, enc) { + if (options instanceof Signature) return options; + this._importDER(options, enc) || + (assert(options.r && options.s, "Signature without r or s"), + (this.r = new BN(options.r, 16)), + (this.s = new BN(options.s, 16)), + options.recoveryParam === void 0 ? (this.recoveryParam = null) : (this.recoveryParam = options.recoveryParam)); + } + Signature.prototype = {}; + module.exports = Signature; + function Position() { + this.place = 0; + } + function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 128)) return initial; + var octetLen = initial & 15; + if (octetLen === 0 || octetLen > 4) return !1; + for (var val = 0, i = 0, off = p.place; i < octetLen; i++, off++) (val <<= 8), (val |= buf[off]), (val >>>= 0); + return val <= 127 ? !1 : ((p.place = off), val); + } + function rmPadding(buf) { + for (var i = 0, len = buf.length - 1; !buf[i] && !(buf[i + 1] & 128) && i < len; ) i++; + return i === 0 ? buf : buf.slice(i); + } + Signature.prototype._importDER = function (data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 48) return !1; + var len = getLength(data, p); + if (len === !1 || len + p.place !== data.length || data[p.place++] !== 2) return !1; + var rlen = getLength(data, p); + if (rlen === !1) return !1; + var r = data.slice(p.place, rlen + p.place); + if (((p.place += rlen), data[p.place++] !== 2)) return !1; + var slen = getLength(data, p); + if (slen === !1 || data.length !== slen + p.place) return !1; + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0) + if (r[1] & 128) r = r.slice(1); + else return !1; + if (s[0] === 0) + if (s[1] & 128) s = s.slice(1); + else return !1; + return (this.r = new BN(r)), (this.s = new BN(s)), (this.recoveryParam = null), !0; + }; + function constructLength(arr, len) { + if (len < 128) { + arr.push(len); + return; + } + var octets = 1 + ((Math.log(len) / Math.LN2) >>> 3); + for (arr.push(octets | 128); --octets; ) arr.push((len >>> (octets << 3)) & 255); + arr.push(len); + } + Signature.prototype.toDER = function (enc) { + var r = this.r.toArray(), + s = this.s.toArray(); + for ( + r[0] & 128 && (r = [0].concat(r)), s[0] & 128 && (s = [0].concat(s)), r = rmPadding(r), s = rmPadding(s); + !s[0] && !(s[1] & 128); + + ) + s = s.slice(1); + var arr = [2]; + constructLength(arr, r.length), (arr = arr.concat(r)), arr.push(2), constructLength(arr, s.length); + var backHalf = arr.concat(s), + res = [48]; + return constructLength(res, backHalf.length), (res = res.concat(backHalf)), utils.encode(res, enc); + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/ec/index.js +var require_ec = __commonJS({ + "node_modules/elliptic/lib/elliptic/ec/index.js"(exports, module) { + "use strict"; + var BN = require_bn4(), + HmacDRBG = require_hmac_drbg(), + utils = require_utils3(), + curves = require_curves(), + rand = require_brorand(), + assert = utils.assert, + KeyPair = require_key(), + Signature = require_signature(); + function EC(options) { + if (!(this instanceof EC)) return new EC(options); + typeof options == "string" && + (assert(Object.prototype.hasOwnProperty.call(curves, options), "Unknown curve " + options), + (options = curves[options])), + options instanceof curves.PresetCurve && (options = { curve: options }), + (this.curve = options.curve.curve), + (this.n = this.curve.n), + (this.nh = this.n.ushrn(1)), + (this.g = this.curve.g), + (this.g = options.curve.g), + this.g.precompute(options.curve.n.bitLength() + 1), + (this.hash = options.hash || options.curve.hash); + } + EC.prototype = {}; + module.exports = EC; + EC.prototype.keyPair = function (options) { + return new KeyPair(this, options); + }; + EC.prototype.keyFromPrivate = function (priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); + }; + EC.prototype.keyFromPublic = function (pub, enc) { + return KeyPair.fromPublic(this, pub, enc); + }; + EC.prototype.genKeyPair = function (options) { + options || (options = {}); + for ( + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || "utf8", + entropy: options.entropy || rand(this.hash.hmacStrength), + entropyEnc: (options.entropy && options.entropyEnc) || "utf8", + nonce: this.n.toArray(), + }), + bytes = this.n.byteLength(), + ns2 = this.n.sub(new BN(2)); + ; + + ) { + var priv = new BN(drbg.generate(bytes)); + if (!(priv.cmp(ns2) > 0)) return priv.iaddn(1), this.keyFromPrivate(priv); + } + }; + EC.prototype._truncateToN = function (msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + return delta > 0 && (msg = msg.ushrn(delta)), !truncOnly && msg.cmp(this.n) >= 0 ? msg.sub(this.n) : msg; + }; + EC.prototype.sign = function (msg, key, enc, options) { + typeof enc == "object" && ((options = enc), (enc = null)), + options || (options = {}), + (key = this.keyFromPrivate(key, enc)), + (msg = this._truncateToN(new BN(msg, 16))); + for ( + var bytes = this.n.byteLength(), + bkey = key.getPrivate().toArray("be", bytes), + nonce = msg.toArray("be", bytes), + drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce, + pers: options.pers, + persEnc: options.persEnc || "utf8", + }), + ns1 = this.n.sub(new BN(1)), + iter = 0; + ; + iter++ + ) { + var k = options.k ? options.k(iter) : new BN(drbg.generate(this.n.byteLength())); + if (((k = this._truncateToN(k, !0)), !(k.cmpn(1) <= 0 || k.cmp(ns1) >= 0))) { + var kp = this.g.mul(k); + if (!kp.isInfinity()) { + var kpX = kp.getX(), + r = kpX.umod(this.n); + if (r.cmpn(0) !== 0) { + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + if (((s = s.umod(this.n)), s.cmpn(0) !== 0)) { + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); + return ( + options.canonical && s.cmp(this.nh) > 0 && ((s = this.n.sub(s)), (recoveryParam ^= 1)), + new Signature({ r, s, recoveryParam }) + ); } - : num.length === 1 - ? mode === "div" - ? { - div: this.divn(num.words[0]), - mod: null, - } - : mode === "mod" - ? { - div: null, - mod: new BN(this.modn(num.words[0])), - } - : { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])), - } - : this._wordDiv(num, mode); - }), - (BN.prototype.div = function (num) { - return this.divmod(num, "div", !1).div; - }), - (BN.prototype.mod = function (num) { - return this.divmod(num, "mod", !1).mod; - }), - (BN.prototype.umod = function (num) { - return this.divmod(num, "mod", !0).mod; - }), - (BN.prototype.divRound = function (num) { - var dm = this.divmod(num); - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, - half = num.ushrn(1), - r2 = num.andln(1), - cmp = mod.cmp(half); - return cmp < 0 || (r2 === 1 && cmp === 0) - ? dm.div - : dm.div.negative !== 0 - ? dm.div.isubn(1) - : dm.div.iaddn(1); - }), - (BN.prototype.modn = function (num) { - assert(num <= 67108863); - for (var p = (1 << 26) % num, acc = 0, i = this.length - 1; i >= 0; i--) - acc = (p * acc + (this.words[i] | 0)) % num; - return acc; - }), - (BN.prototype.idivn = function (num) { - assert(num <= 67108863); - for (var carry = 0, i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 67108864; - (this.words[i] = (w / num) | 0), (carry = w % num); - } - return this.strip(); - }), - (BN.prototype.divn = function (num) { - return this.clone().idivn(num); - }), - (BN.prototype.egcd = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var x = this, - y = p.clone(); - x.negative !== 0 ? (x = x.umod(p)) : (x = x.clone()); - for (var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0; x.isEven() && y.isEven(); ) - x.iushrn(1), y.iushrn(1), ++g; - for (var yp = y.clone(), xp = x.clone(); !x.isZero(); ) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) - for (x.iushrn(i); i-- > 0; ) - (A.isOdd() || B.isOdd()) && (A.iadd(yp), B.isub(xp)), A.iushrn(1), B.iushrn(1); - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) - for (y.iushrn(j); j-- > 0; ) - (C.isOdd() || D.isOdd()) && (C.iadd(yp), D.isub(xp)), C.iushrn(1), D.iushrn(1); - x.cmp(y) >= 0 ? (x.isub(y), A.isub(C), B.isub(D)) : (y.isub(x), C.isub(A), D.isub(B)); - } - return { - a: C, - b: D, - gcd: y.iushln(g), - }; - }), - (BN.prototype._invmp = function (p) { - assert(p.negative === 0), assert(!p.isZero()); - var a = this, - b = p.clone(); - a.negative !== 0 ? (a = a.umod(p)) : (a = a.clone()); - for (var x1 = new BN(1), x2 = new BN(0), delta = b.clone(); a.cmpn(1) > 0 && b.cmpn(1) > 0; ) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) for (a.iushrn(i); i-- > 0; ) x1.isOdd() && x1.iadd(delta), x1.iushrn(1); - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) for (b.iushrn(j); j-- > 0; ) x2.isOdd() && x2.iadd(delta), x2.iushrn(1); - a.cmp(b) >= 0 ? (a.isub(b), x1.isub(x2)) : (b.isub(a), x2.isub(x1)); + } } - var res; - return a.cmpn(1) === 0 ? (res = x1) : (res = x2), res.cmpn(0) < 0 && res.iadd(p), res; - }), - (BN.prototype.gcd = function (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(), - b = num.clone(); - (a.negative = 0), (b.negative = 0); - for (var shift = 0; a.isEven() && b.isEven(); shift++) a.iushrn(1), b.iushrn(1); - do { - for (; a.isEven(); ) a.iushrn(1); - for (; b.isEven(); ) b.iushrn(1); - var r = a.cmp(b); - if (r < 0) { - var t = a; - (a = b), (b = t); - } else if (r === 0 || b.cmpn(1) === 0) break; - a.isub(b); - } while (!0); - return b.iushln(shift); - }), - (BN.prototype.invm = function (num) { - return this.egcd(num).a.umod(num); - }), - (BN.prototype.isEven = function () { - return (this.words[0] & 1) === 0; - }), - (BN.prototype.isOdd = function () { - return (this.words[0] & 1) === 1; - }), - (BN.prototype.andln = function (num) { - return this.words[0] & num; - }), - (BN.prototype.bincn = function (bit) { - assert(typeof bit == "number"); - var r = bit % 26, - s = (bit - r) / 26, - q = 1 << r; - if (this.length <= s) return this._expand(s + 1), (this.words[s] |= q), this; - for (var carry = q, i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - (w += carry), (carry = w >>> 26), (w &= 67108863), (this.words[i] = w); + } + } + }; + EC.prototype.verify = function (msg, signature, key, enc) { + (msg = this._truncateToN(new BN(msg, 16))), + (key = this.keyFromPublic(key, enc)), + (signature = new Signature(signature, "hex")); + var r = signature.r, + s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0 || s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return !1; + var sinv = s.invm(this.n), + u1 = sinv.mul(msg).umod(this.n), + u2 = sinv.mul(r).umod(this.n), + p; + return this.curve._maxwellTrick + ? ((p = this.g.jmulAdd(u1, key.getPublic(), u2)), p.isInfinity() ? !1 : p.eqXToP(r)) + : ((p = this.g.mulAdd(u1, key.getPublic(), u2)), p.isInfinity() ? !1 : p.getX().umod(this.n).cmp(r) === 0); + }; + EC.prototype.recoverPubKey = function (msg, signature, j, enc) { + assert((3 & j) === j, "The recovery param is more than two bits"), (signature = new Signature(signature, enc)); + var n = this.n, + e = new BN(msg), + r = signature.r, + s = signature.s, + isYOdd = j & 1, + isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error("Unable to find sencond key candinate"); + isSecondKey ? (r = this.curve.pointFromX(r.add(this.curve.n), isYOdd)) : (r = this.curve.pointFromX(r, isYOdd)); + var rInv = signature.r.invm(n), + s1 = n.sub(e).mul(rInv).umod(n), + s2 = s.mul(rInv).umod(n); + return this.g.mulAdd(s1, r, s2); + }; + EC.prototype.getKeyRecoveryParam = function (e, signature, Q, enc) { + if (((signature = new Signature(signature, enc)), signature.recoveryParam !== null)) + return signature.recoveryParam; + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch { + continue; + } + if (Qprime.eq(Q)) return i; + } + throw new Error("Unable to find valid recovery factor"); + }; + }, +}); + +// node_modules/elliptic/lib/elliptic/eddsa/key.js +var require_key2 = __commonJS({ + "node_modules/elliptic/lib/elliptic/eddsa/key.js"(exports, module) { + "use strict"; + var utils = require_utils3(), + assert = utils.assert, + parseBytes = utils.parseBytes, + cachedProperty = utils.cachedProperty; + function KeyPair(eddsa, params) { + (this.eddsa = eddsa), + (this._secret = parseBytes(params.secret)), + eddsa.isPoint(params.pub) ? (this._pub = params.pub) : (this._pubBytes = parseBytes(params.pub)); + } + KeyPair.prototype = {}; + KeyPair.fromPublic = function (eddsa, pub) { + return pub instanceof KeyPair ? pub : new KeyPair(eddsa, { pub }); + }; + KeyPair.fromSecret = function (eddsa, secret) { + return secret instanceof KeyPair ? secret : new KeyPair(eddsa, { secret }); + }; + KeyPair.prototype.secret = function () { + return this._secret; + }; + cachedProperty(KeyPair, "pubBytes", function () { + return this.eddsa.encodePoint(this.pub()); + }); + cachedProperty(KeyPair, "pub", function () { + return this._pubBytes ? this.eddsa.decodePoint(this._pubBytes) : this.eddsa.g.mul(this.priv()); + }); + cachedProperty(KeyPair, "privBytes", function () { + var eddsa = this.eddsa, + hash = this.hash(), + lastIx = eddsa.encodingLength - 1, + a = hash.slice(0, eddsa.encodingLength); + return (a[0] &= 248), (a[lastIx] &= 127), (a[lastIx] |= 64), a; + }); + cachedProperty(KeyPair, "priv", function () { + return this.eddsa.decodeInt(this.privBytes()); + }); + cachedProperty(KeyPair, "hash", function () { + return this.eddsa.hash().update(this.secret()).digest(); + }); + cachedProperty(KeyPair, "messagePrefix", function () { + return this.hash().slice(this.eddsa.encodingLength); + }); + KeyPair.prototype.sign = function (message) { + return assert(this._secret, "KeyPair can only verify"), this.eddsa.sign(message, this); + }; + KeyPair.prototype.verify = function (message, sig) { + return this.eddsa.verify(message, sig, this); + }; + KeyPair.prototype.getSecret = function (enc) { + return assert(this._secret, "KeyPair is public only"), utils.encode(this.secret(), enc); + }; + KeyPair.prototype.getPublic = function (enc) { + return utils.encode(this.pubBytes(), enc); + }; + module.exports = KeyPair; + }, +}); + +// node_modules/elliptic/lib/elliptic/eddsa/signature.js +var require_signature2 = __commonJS({ + "node_modules/elliptic/lib/elliptic/eddsa/signature.js"(exports, module) { + "use strict"; + var BN = require_bn4(), + utils = require_utils3(), + assert = utils.assert, + cachedProperty = utils.cachedProperty, + parseBytes = utils.parseBytes; + function Signature(eddsa, sig) { + (this.eddsa = eddsa), + typeof sig != "object" && (sig = parseBytes(sig)), + Array.isArray(sig) && + (sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength), + }), + assert(sig.R && sig.S, "Signature without R or S"), + eddsa.isPoint(sig.R) && (this._R = sig.R), + sig.S instanceof BN && (this._S = sig.S), + (this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded), + (this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded); + } + Signature.prototype = {}; + cachedProperty(Signature, "S", function () { + return this.eddsa.decodeInt(this.Sencoded()); + }); + cachedProperty(Signature, "R", function () { + return this.eddsa.decodePoint(this.Rencoded()); + }); + cachedProperty(Signature, "Rencoded", function () { + return this.eddsa.encodePoint(this.R()); + }); + cachedProperty(Signature, "Sencoded", function () { + return this.eddsa.encodeInt(this.S()); + }); + Signature.prototype.toBytes = function () { + return this.Rencoded().concat(this.Sencoded()); + }; + Signature.prototype.toHex = function () { + return utils.encode(this.toBytes(), "hex").toUpperCase(); + }; + module.exports = Signature; + }, +}); + +// node_modules/elliptic/lib/elliptic/eddsa/index.js +var require_eddsa = __commonJS({ + "node_modules/elliptic/lib/elliptic/eddsa/index.js"(exports, module) { + "use strict"; + var hash = require_hash2(), + curves = require_curves(), + utils = require_utils3(), + assert = utils.assert, + parseBytes = utils.parseBytes, + KeyPair = require_key2(), + Signature = require_signature2(); + function EDDSA(curve) { + if ((assert(curve === "ed25519", "only tested with ed25519 so far"), !(this instanceof EDDSA))) + return new EDDSA(curve); + (curve = curves[curve].curve), + (this.curve = curve), + (this.g = curve.g), + this.g.precompute(curve.n.bitLength() + 1), + (this.pointClass = curve.point().constructor), + (this.encodingLength = Math.ceil(curve.n.bitLength() / 8)), + (this.hash = hash.sha512); + } + EDDSA.prototype = {}; + module.exports = EDDSA; + EDDSA.prototype.sign = function (message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret), + r = this.hashInt(key.messagePrefix(), message), + R = this.g.mul(r), + Rencoded = this.encodePoint(R), + s_ = this.hashInt(Rencoded, key.pubBytes(), message).mul(key.priv()), + S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R, S, Rencoded }); + }; + EDDSA.prototype.verify = function (message, sig, pub) { + (message = parseBytes(message)), (sig = this.makeSignature(sig)); + var key = this.keyFromPublic(pub), + h = this.hashInt(sig.Rencoded(), key.pubBytes(), message), + SG = this.g.mul(sig.S()), + RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); + }; + EDDSA.prototype.hashInt = function () { + for (var hash2 = this.hash(), i = 0; i < arguments.length; i++) hash2.update(arguments[i]); + return utils.intFromLE(hash2.digest()).umod(this.curve.n); + }; + EDDSA.prototype.keyFromPublic = function (pub) { + return KeyPair.fromPublic(this, pub); + }; + EDDSA.prototype.keyFromSecret = function (secret) { + return KeyPair.fromSecret(this, secret); + }; + EDDSA.prototype.makeSignature = function (sig) { + return sig instanceof Signature ? sig : new Signature(this, sig); + }; + EDDSA.prototype.encodePoint = function (point) { + var enc = point.getY().toArray("le", this.encodingLength); + return (enc[this.encodingLength - 1] |= point.getX().isOdd() ? 128 : 0), enc; + }; + EDDSA.prototype.decodePoint = function (bytes) { + bytes = utils.parseBytes(bytes); + var lastIx = bytes.length - 1, + normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & -129), + xIsOdd = (bytes[lastIx] & 128) !== 0, + y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); + }; + EDDSA.prototype.encodeInt = function (num) { + return num.toArray("le", this.encodingLength); + }; + EDDSA.prototype.decodeInt = function (bytes) { + return utils.intFromLE(bytes); + }; + EDDSA.prototype.isPoint = function (val) { + return val instanceof this.pointClass; + }; + }, +}); + +// node_modules/elliptic/lib/elliptic.js +var require_elliptic = __commonJS({ + "node_modules/elliptic/lib/elliptic.js"(exports) { + "use strict"; + var elliptic = exports; + elliptic.version = require_package().version; + elliptic.utils = require_utils3(); + elliptic.rand = require_brorand(); + elliptic.curve = require_curve(); + elliptic.curves = require_curves(); + elliptic.ec = require_ec(); + elliptic.eddsa = require_eddsa(); + }, +}); + +// node_modules/asn1.js/node_modules/bn.js/lib/bn.js +var require_bn5 = require_bn; + +// node_modules/safer-buffer/safer.js +var require_safer = __commonJS({ + "node_modules/safer-buffer/safer.js"(exports, module) { + "use strict"; + var buffer = BufferModule, + Buffer2 = Buffer, + safer = {}, + key; + for (key in buffer) + !buffer.hasOwnProperty(key) || key === "SlowBuffer" || key === "Buffer" || (safer[key] = buffer[key]); + var Safer = (safer.Buffer = {}); + for (key in Buffer2) + !Buffer2.hasOwnProperty(key) || key === "allocUnsafe" || key === "allocUnsafeSlow" || (Safer[key] = Buffer2[key]); + safer.Buffer.prototype = Buffer2.prototype; + (!Safer.from || Safer.from === Uint8Array.from) && + (Safer.from = function (value, encodingOrOffset, length) { + if (typeof value == "number") + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value); + if (value && typeof value.length > "u") + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + + typeof value, + ); + return Buffer2(value, encodingOrOffset, length); + }); + Safer.alloc || + (Safer.alloc = function (size, fill, encoding) { + if (typeof size != "number") + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size); + if (size < 0 || size >= 2 * (1 << 30)) + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + var buf = Buffer2(size); + return ( + !fill || fill.length === 0 + ? buf.fill(0) + : typeof encoding == "string" + ? buf.fill(fill, encoding) + : buf.fill(fill), + buf + ); + }); + if (!safer.kStringMaxLength) + try { + safer.kStringMaxLength = MAX_STRING_LENGTH; + } catch {} + safer.constants || + ((safer.constants = { + MAX_LENGTH: safer.kMaxLength, + }), + safer.kStringMaxLength && (safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength)); + module.exports = safer; + }, +}); + +// node_modules/asn1.js/lib/asn1/base/reporter.js +var require_reporter = __commonJS({ + "node_modules/asn1.js/lib/asn1/base/reporter.js"(exports) { + "use strict"; + var inherits = require_inherits_browser(); + function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [], + }; + } + Reporter.prototype = {}; + exports.Reporter = Reporter; + Reporter.prototype.isError = function (obj) { + return obj instanceof ReporterError; + }; + Reporter.prototype.save = function () { + let state = this._reporterState; + return { obj: state.obj, pathLen: state.path.length }; + }; + Reporter.prototype.restore = function (data) { + let state = this._reporterState; + (state.obj = data.obj), (state.path = state.path.slice(0, data.pathLen)); + }; + Reporter.prototype.enterKey = function (key) { + return this._reporterState.path.push(key); + }; + Reporter.prototype.exitKey = function (index) { + let state = this._reporterState; + state.path = state.path.slice(0, index - 1); + }; + Reporter.prototype.leaveKey = function (index, key, value) { + let state = this._reporterState; + this.exitKey(index), state.obj !== null && (state.obj[key] = value); + }; + Reporter.prototype.path = function () { + return this._reporterState.path.join("/"); + }; + Reporter.prototype.enterObject = function () { + let state = this._reporterState, + prev = state.obj; + return (state.obj = {}), prev; + }; + Reporter.prototype.leaveObject = function (prev) { + let state = this._reporterState, + now = state.obj; + return (state.obj = prev), now; + }; + Reporter.prototype.error = function (msg) { + let err, + state = this._reporterState, + inherited = msg instanceof ReporterError; + if ( + (inherited + ? (err = msg) + : (err = new ReporterError( + state.path + .map(function (elem) { + return "[" + JSON.stringify(elem) + "]"; + }) + .join(""), + msg.message || msg, + msg.stack, + )), + !state.options.partial) + ) + throw err; + return inherited || state.errors.push(err), err; + }; + Reporter.prototype.wrapResult = function (result) { + let state = this._reporterState; + return state.options.partial + ? { + result: this.isError(result) ? null : result, + errors: state.errors, + } + : result; + }; + function ReporterError(path, msg) { + (this.path = path), this.rethrow(msg); + } + inherits(ReporterError, Error); + ReporterError.prototype.rethrow = function (msg) { + if ( + ((this.message = msg + " at: " + (this.path || "(shallow)")), + Error.captureStackTrace && Error.captureStackTrace(this, ReporterError), + !this.stack) + ) + try { + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + return this; + }; + }, +}); + +// node_modules/asn1.js/lib/asn1/base/buffer.js +var require_buffer = __commonJS({ + "node_modules/asn1.js/lib/asn1/base/buffer.js"(exports) { + "use strict"; + var inherits = require_inherits_browser(), + Reporter = require_reporter().Reporter, + Buffer2 = require_safer().Buffer; + function DecoderBuffer(base, options) { + if ((Reporter.call(this, options), !Buffer2.isBuffer(base))) { + this.error("Input not Buffer"); + return; + } + (this.base = base), (this.offset = 0), (this.length = base.length); + } + inherits(DecoderBuffer, Reporter); + exports.DecoderBuffer = DecoderBuffer; + DecoderBuffer.isDecoderBuffer = function (data) { + return data instanceof DecoderBuffer + ? !0 + : typeof data == "object" && + Buffer2.isBuffer(data.base) && + data.constructor.name === "DecoderBuffer" && + typeof data.offset == "number" && + typeof data.length == "number" && + typeof data.save == "function" && + typeof data.restore == "function" && + typeof data.isEmpty == "function" && + typeof data.readUInt8 == "function" && + typeof data.skip == "function" && + typeof data.raw == "function"; + }; + DecoderBuffer.prototype.save = function () { + return { + offset: this.offset, + reporter: Reporter.prototype.save.call(this), + }; + }; + DecoderBuffer.prototype.restore = function (save) { + let res = new DecoderBuffer(this.base); + return ( + (res.offset = save.offset), + (res.length = this.offset), + (this.offset = save.offset), + Reporter.prototype.restore.call(this, save.reporter), + res + ); + }; + DecoderBuffer.prototype.isEmpty = function () { + return this.offset === this.length; + }; + DecoderBuffer.prototype.readUInt8 = function (fail) { + return this.offset + 1 <= this.length + ? this.base.readUInt8(this.offset++, !0) + : this.error(fail || "DecoderBuffer overrun"); + }; + DecoderBuffer.prototype.skip = function (bytes, fail) { + if (!(this.offset + bytes <= this.length)) return this.error(fail || "DecoderBuffer overrun"); + let res = new DecoderBuffer(this.base); + return ( + (res._reporterState = this._reporterState), + (res.offset = this.offset), + (res.length = this.offset + bytes), + (this.offset += bytes), + res + ); + }; + DecoderBuffer.prototype.raw = function (save) { + return this.base.slice(save ? save.offset : this.offset, this.length); + }; + function EncoderBuffer(value, reporter) { + if (Array.isArray(value)) + (this.length = 0), + (this.value = value.map(function (item) { + return ( + EncoderBuffer.isEncoderBuffer(item) || (item = new EncoderBuffer(item, reporter)), + (this.length += item.length), + item + ); + }, this)); + else if (typeof value == "number") { + if (!(0 <= value && value <= 255)) return reporter.error("non-byte EncoderBuffer value"); + (this.value = value), (this.length = 1); + } else if (typeof value == "string") (this.value = value), (this.length = Buffer2.byteLength(value)); + else if (Buffer2.isBuffer(value)) (this.value = value), (this.length = value.length); + else return reporter.error("Unsupported type: " + typeof value); + } + EncoderBuffer.prototype = {}; + exports.EncoderBuffer = EncoderBuffer; + EncoderBuffer.isEncoderBuffer = function (data) { + return data instanceof EncoderBuffer + ? !0 + : typeof data == "object" && + data.constructor.name === "EncoderBuffer" && + typeof data.length == "number" && + typeof data.join == "function"; + }; + EncoderBuffer.prototype.join = function (out, offset) { + return ( + out || (out = Buffer2.alloc(this.length)), + offset || (offset = 0), + this.length === 0 || + (Array.isArray(this.value) + ? this.value.forEach(function (item) { + item.join(out, offset), (offset += item.length); + }) + : (typeof this.value == "number" + ? (out[offset] = this.value) + : typeof this.value == "string" + ? out.write(this.value, offset) + : Buffer2.isBuffer(this.value) && this.value.copy(out, offset), + (offset += this.length))), + out + ); + }; + }, +}); + +// node_modules/asn1.js/lib/asn1/base/node.js +var require_node = __commonJS({ + "node_modules/asn1.js/lib/asn1/base/node.js"(exports, module) { + "use strict"; + var Reporter = require_reporter().Reporter, + EncoderBuffer = require_buffer().EncoderBuffer, + DecoderBuffer = require_buffer().DecoderBuffer, + assert = require_minimalistic_assert(), + tags = [ + "seq", + "seqof", + "set", + "setof", + "objid", + "bool", + "gentime", + "utctime", + "null_", + "enum", + "int", + "objDesc", + "bitstr", + "bmpstr", + "charstr", + "genstr", + "graphstr", + "ia5str", + "iso646str", + "numstr", + "octstr", + "printstr", + "t61str", + "unistr", + "utf8str", + "videostr", + ], + methods = ["key", "obj", "use", "optional", "explicit", "implicit", "def", "choice", "any", "contains"].concat( + tags, + ), + overrided = [ + "_peekTag", + "_decodeTag", + "_use", + "_decodeStr", + "_decodeObjid", + "_decodeTime", + "_decodeNull", + "_decodeInt", + "_decodeBool", + "_decodeList", + "_encodeComposite", + "_encodeStr", + "_encodeObjid", + "_encodeTime", + "_encodeNull", + "_encodeInt", + "_encodeBool", + ]; + function Node(enc, parent, name) { + let state = {}; + (this._baseState = state), + (state.name = name), + (state.enc = enc), + (state.parent = parent || null), + (state.children = null), + (state.tag = null), + (state.args = null), + (state.reverseArgs = null), + (state.choice = null), + (state.optional = !1), + (state.any = !1), + (state.obj = !1), + (state.use = null), + (state.useDecoder = null), + (state.key = null), + (state.default = null), + (state.explicit = null), + (state.implicit = null), + (state.contains = null), + state.parent || ((state.children = []), this._wrap()); + } + Node.prototype = {}; + module.exports = Node; + var stateProps = [ + "enc", + "parent", + "children", + "tag", + "args", + "reverseArgs", + "choice", + "optional", + "any", + "obj", + "use", + "alteredUse", + "key", + "default", + "explicit", + "implicit", + "contains", + ]; + Node.prototype.clone = function () { + let state = this._baseState, + cstate = {}; + stateProps.forEach(function (prop) { + cstate[prop] = state[prop]; + }); + let res = new this.constructor(cstate.parent); + return (res._baseState = cstate), res; + }; + Node.prototype._wrap = function () { + let state = this._baseState; + methods.forEach(function (method) { + this[method] = function () { + let clone = new this.constructor(this); + return state.children.push(clone), clone[method].apply(clone, arguments); + }; + }, this); + }; + Node.prototype._init = function (body) { + let state = this._baseState; + assert(state.parent === null), + body.call(this), + (state.children = state.children.filter(function (child) { + return child._baseState.parent === this; + }, this)), + assert.equal(state.children.length, 1, "Root node can have only one child"); + }; + Node.prototype._useArgs = function (args) { + let state = this._baseState, + children = args.filter(function (arg) { + return arg instanceof this.constructor; + }, this); + (args = args.filter(function (arg) { + return !(arg instanceof this.constructor); + }, this)), + children.length !== 0 && + (assert(state.children === null), + (state.children = children), + children.forEach(function (child) { + child._baseState.parent = this; + }, this)), + args.length !== 0 && + (assert(state.args === null), + (state.args = args), + (state.reverseArgs = args.map(function (arg) { + if (typeof arg != "object" || arg.constructor !== Object) return arg; + let res = {}; + return ( + Object.keys(arg).forEach(function (key) { + key == (key | 0) && (key |= 0); + let value = arg[key]; + res[value] = key; + }), + res + ); + }))); + }; + overrided.forEach(function (method) { + Node.prototype[method] = function () { + let state = this._baseState; + throw new Error(method + " not implemented for encoding: " + state.enc); + }; + }); + tags.forEach(function (tag) { + Node.prototype[tag] = function () { + let state = this._baseState, + args = Array.prototype.slice.call(arguments); + return assert(state.tag === null), (state.tag = tag), this._useArgs(args), this; + }; + }); + Node.prototype.use = function (item) { + assert(item); + let state = this._baseState; + return assert(state.use === null), (state.use = item), this; + }; + Node.prototype.optional = function () { + let state = this._baseState; + return (state.optional = !0), this; + }; + Node.prototype.def = function (val) { + let state = this._baseState; + return assert(state.default === null), (state.default = val), (state.optional = !0), this; + }; + Node.prototype.explicit = function (num) { + let state = this._baseState; + return assert(state.explicit === null && state.implicit === null), (state.explicit = num), this; + }; + Node.prototype.implicit = function (num) { + let state = this._baseState; + return assert(state.explicit === null && state.implicit === null), (state.implicit = num), this; + }; + Node.prototype.obj = function () { + let state = this._baseState, + args = Array.prototype.slice.call(arguments); + return (state.obj = !0), args.length !== 0 && this._useArgs(args), this; + }; + Node.prototype.key = function (newKey) { + let state = this._baseState; + return assert(state.key === null), (state.key = newKey), this; + }; + Node.prototype.any = function () { + let state = this._baseState; + return (state.any = !0), this; + }; + Node.prototype.choice = function (obj) { + let state = this._baseState; + return ( + assert(state.choice === null), + (state.choice = obj), + this._useArgs( + Object.keys(obj).map(function (key) { + return obj[key]; + }), + ), + this + ); + }; + Node.prototype.contains = function (item) { + let state = this._baseState; + return assert(state.use === null), (state.contains = item), this; + }; + Node.prototype._decode = function (input, options) { + let state = this._baseState; + if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); + let result = state.default, + present = !0, + prevKey = null; + if ((state.key !== null && (prevKey = input.enterKey(state.key)), state.optional)) { + let tag = null; + if ( + (state.explicit !== null + ? (tag = state.explicit) + : state.implicit !== null + ? (tag = state.implicit) + : state.tag !== null && (tag = state.tag), + tag === null && !state.any) + ) { + let save = input.save(); + try { + state.choice === null ? this._decodeGeneric(state.tag, input, options) : this._decodeChoice(input, options), + (present = !0); + } catch { + present = !1; } - return carry !== 0 && ((this.words[i] = carry), this.length++), this; - }), - (BN.prototype.isZero = function () { - return this.length === 1 && this.words[0] === 0; - }), - (BN.prototype.cmpn = function (num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - this.strip(); - var res; - if (this.length > 1) res = 1; - else { - negative && (num = -num), assert(num <= 67108863, "Number is too big"); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; + input.restore(save); + } else if (((present = this._peekTag(input, tag, state.any)), input.isError(present))) return present; + } + let prevObj; + if ((state.obj && present && (prevObj = input.enterObject()), present)) { + if (state.explicit !== null) { + let explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) return explicit; + input = explicit; + } + let start = input.offset; + if (state.use === null && state.choice === null) { + let save; + state.any && (save = input.save()); + let body = this._decodeTag(input, state.implicit !== null ? state.implicit : state.tag, state.any); + if (input.isError(body)) return body; + state.any ? (result = input.raw(save)) : (input = body); + } + if ( + (options && options.track && state.tag !== null && options.track(input.path(), start, input.length, "tagged"), + options && + options.track && + state.tag !== null && + options.track(input.path(), input.offset, input.length, "content"), + state.any || + (state.choice === null + ? (result = this._decodeGeneric(state.tag, input, options)) + : (result = this._decodeChoice(input, options))), + input.isError(result)) + ) + return result; + if ( + (!state.any && + state.choice === null && + state.children !== null && + state.children.forEach(function (child) { + child._decode(input, options); + }), + state.contains && (state.tag === "octstr" || state.tag === "bitstr")) + ) { + let data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj)._decode(data, options); + } + } + return ( + state.obj && present && (result = input.leaveObject(prevObj)), + state.key !== null && (result !== null || present === !0) + ? input.leaveKey(prevKey, state.key, result) + : prevKey !== null && input.exitKey(prevKey), + result + ); + }; + Node.prototype._decodeGeneric = function (tag, input, options) { + let state = this._baseState; + return tag === "seq" || tag === "set" + ? null + : tag === "seqof" || tag === "setof" + ? this._decodeList(input, tag, state.args[0], options) + : /str$/.test(tag) + ? this._decodeStr(input, tag, options) + : tag === "objid" && state.args + ? this._decodeObjid(input, state.args[0], state.args[1], options) + : tag === "objid" + ? this._decodeObjid(input, null, null, options) + : tag === "gentime" || tag === "utctime" + ? this._decodeTime(input, tag, options) + : tag === "null_" + ? this._decodeNull(input, options) + : tag === "bool" + ? this._decodeBool(input, options) + : tag === "objDesc" + ? this._decodeStr(input, tag, options) + : tag === "int" || tag === "enum" + ? this._decodeInt(input, state.args && state.args[0], options) + : state.use !== null + ? this._getUse(state.use, input._reporterState.obj)._decode(input, options) + : input.error("unknown tag: " + tag); + }; + Node.prototype._getUse = function (entity, obj) { + let state = this._baseState; + return ( + (state.useDecoder = this._use(entity, obj)), + assert(state.useDecoder._baseState.parent === null), + (state.useDecoder = state.useDecoder._baseState.children[0]), + state.implicit !== state.useDecoder._baseState.implicit && + ((state.useDecoder = state.useDecoder.clone()), (state.useDecoder._baseState.implicit = state.implicit)), + state.useDecoder + ); + }; + Node.prototype._decodeChoice = function (input, options) { + let state = this._baseState, + result = null, + match = !1; + return ( + Object.keys(state.choice).some(function (key) { + let save = input.save(), + node = state.choice[key]; + try { + let value = node._decode(input, options); + if (input.isError(value)) return !1; + (result = { type: key, value }), (match = !0); + } catch { + return input.restore(save), !1; } - return this.negative !== 0 ? -res | 0 : res; - }), - (BN.prototype.cmp = function (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - return this.negative !== 0 ? -res | 0 : res; + return !0; + }, this), + match ? result : input.error("Choice not matched") + ); + }; + Node.prototype._createEncoderBuffer = function (data) { + return new EncoderBuffer(data, this.reporter); + }; + Node.prototype._encode = function (data, reporter, parent) { + let state = this._baseState; + if (state.default !== null && state.default === data) return; + let result = this._encodeValue(data, reporter, parent); + if (result !== void 0 && !this._skipDefault(result, reporter, parent)) return result; + }; + Node.prototype._encodeValue = function (data, reporter, parent) { + let state = this._baseState; + if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); + let result = null; + if (((this.reporter = reporter), state.optional && data === void 0)) + if (state.default !== null) data = state.default; + else return; + let content = null, + primitive = !1; + if (state.any) result = this._createEncoderBuffer(data); + else if (state.choice) result = this._encodeChoice(data, reporter); + else if (state.contains) + (content = this._getUse(state.contains, parent)._encode(data, reporter)), (primitive = !0); + else if (state.children) + (content = state.children + .map(function (child) { + if (child._baseState.tag === "null_") return child._encode(null, reporter, data); + if (child._baseState.key === null) return reporter.error("Child should have a key"); + let prevKey = reporter.enterKey(child._baseState.key); + if (typeof data != "object") return reporter.error("Child expected, but input is not object"); + let res = child._encode(data[child._baseState.key], reporter, data); + return reporter.leaveKey(prevKey), res; + }, this) + .filter(function (child) { + return child; + })), + (content = this._createEncoderBuffer(content)); + else if (state.tag === "seqof" || state.tag === "setof") { + if (!(state.args && state.args.length === 1)) return reporter.error("Too many args for : " + state.tag); + if (!Array.isArray(data)) return reporter.error("seqof/setof, but data is not Array"); + let child = this.clone(); + (child._baseState.implicit = null), + (content = this._createEncoderBuffer( + data.map(function (item) { + let state2 = this._baseState; + return this._getUse(state2.args[0], data)._encode(item, reporter); + }, child), + )); + } else + state.use !== null + ? (result = this._getUse(state.use, parent)._encode(data, reporter)) + : ((content = this._encodePrimitive(state.tag, data)), (primitive = !0)); + if (!state.any && state.choice === null) { + let tag = state.implicit !== null ? state.implicit : state.tag, + cls = state.implicit === null ? "universal" : "context"; + tag === null + ? state.use === null && reporter.error("Tag could be omitted only for .use()") + : state.use === null && (result = this._encodeComposite(tag, primitive, cls, content)); + } + return state.explicit !== null && (result = this._encodeComposite(state.explicit, !1, "context", result)), result; + }; + Node.prototype._encodeChoice = function (data, reporter) { + let state = this._baseState, + node = state.choice[data.type]; + return ( + node || assert(!1, data.type + " not found in " + JSON.stringify(Object.keys(state.choice))), + node._encode(data.value, reporter) + ); + }; + Node.prototype._encodePrimitive = function (tag, data) { + let state = this._baseState; + if (/str$/.test(tag)) return this._encodeStr(data, tag); + if (tag === "objid" && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + if (tag === "objid") return this._encodeObjid(data, null, null); + if (tag === "gentime" || tag === "utctime") return this._encodeTime(data, tag); + if (tag === "null_") return this._encodeNull(); + if (tag === "int" || tag === "enum") return this._encodeInt(data, state.args && state.reverseArgs[0]); + if (tag === "bool") return this._encodeBool(data); + if (tag === "objDesc") return this._encodeStr(data, tag); + throw new Error("Unsupported tag: " + tag); + }; + Node.prototype._isNumstr = function (str) { + return /^[0-9 ]*$/.test(str); + }; + Node.prototype._isPrintstr = function (str) { + return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str); + }; + }, +}); + +// node_modules/asn1.js/lib/asn1/constants/der.js +var require_der = __commonJS({ + "node_modules/asn1.js/lib/asn1/constants/der.js"(exports) { + "use strict"; + function reverse(map) { + let res = {}; + return ( + Object.keys(map).forEach(function (key) { + (key | 0) == key && (key = key | 0); + let value = map[key]; + res[value] = key; }), - (BN.prototype.ucmp = function (num) { - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - for (var res = 0, i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0, - b = num.words[i] | 0; - if (a !== b) { - a < b ? (res = -1) : a > b && (res = 1); - break; - } + res + ); + } + exports.tagClass = { + 0: "universal", + 1: "application", + 2: "context", + 3: "private", + }; + exports.tagClassByName = reverse(exports.tagClass); + exports.tag = { + 0: "end", + 1: "bool", + 2: "int", + 3: "bitstr", + 4: "octstr", + 5: "null_", + 6: "objid", + 7: "objDesc", + 8: "external", + 9: "real", + 10: "enum", + 11: "embed", + 12: "utf8str", + 13: "relativeOid", + 16: "seq", + 17: "set", + 18: "numstr", + 19: "printstr", + 20: "t61str", + 21: "videostr", + 22: "ia5str", + 23: "utctime", + 24: "gentime", + 25: "graphstr", + 26: "iso646str", + 27: "genstr", + 28: "unistr", + 29: "charstr", + 30: "bmpstr", + }; + exports.tagByName = reverse(exports.tag); + }, +}); + +// node_modules/asn1.js/lib/asn1/encoders/der.js +var require_der2 = __commonJS({ + "node_modules/asn1.js/lib/asn1/encoders/der.js"(exports, module) { + "use strict"; + var inherits = require_inherits_browser(), + Buffer2 = require_safer().Buffer, + Node = require_node(), + der = require_der(); + function DEREncoder(entity) { + (this.enc = "der"), + (this.name = entity.name), + (this.entity = entity), + (this.tree = new DERNode()), + this.tree._init(entity.body); + } + DEREncoder.prototype = {}; + module.exports = DEREncoder; + DEREncoder.prototype.encode = function (data, reporter) { + return this.tree._encode(data, reporter).join(); + }; + function DERNode(parent) { + Node.call(this, "der", parent); + } + inherits(DERNode, Node); + DERNode.prototype._encodeComposite = function (tag, primitive, cls, content) { + let encodedTag = encodeTag(tag, primitive, cls, this.reporter); + if (content.length < 128) { + let header2 = Buffer2.alloc(2); + return (header2[0] = encodedTag), (header2[1] = content.length), this._createEncoderBuffer([header2, content]); + } + let lenOctets = 1; + for (let i = content.length; i >= 256; i >>= 8) lenOctets++; + let header = Buffer2.alloc(1 + 1 + lenOctets); + (header[0] = encodedTag), (header[1] = 128 | lenOctets); + for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 255; + return this._createEncoderBuffer([header, content]); + }; + DERNode.prototype._encodeStr = function (str, tag) { + if (tag === "bitstr") return this._createEncoderBuffer([str.unused | 0, str.data]); + if (tag === "bmpstr") { + let buf = Buffer2.alloc(str.length * 2); + for (let i = 0; i < str.length; i++) buf.writeUInt16BE(str.charCodeAt(i), i * 2); + return this._createEncoderBuffer(buf); + } else + return tag === "numstr" + ? this._isNumstr(str) + ? this._createEncoderBuffer(str) + : this.reporter.error("Encoding of string type: numstr supports only digits and space") + : tag === "printstr" + ? this._isPrintstr(str) + ? this._createEncoderBuffer(str) + : this.reporter.error( + "Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark", + ) + : /str$/.test(tag) + ? this._createEncoderBuffer(str) + : tag === "objDesc" + ? this._createEncoderBuffer(str) + : this.reporter.error("Encoding of string type: " + tag + " unsupported"); + }; + DERNode.prototype._encodeObjid = function (id, values, relative) { + if (typeof id == "string") { + if (!values) return this.reporter.error("string objid given, but no values map found"); + if (!values.hasOwnProperty(id)) return this.reporter.error("objid not found in values map"); + id = values[id].split(/[\s.]+/g); + for (let i = 0; i < id.length; i++) id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (let i = 0; i < id.length; i++) id[i] |= 0; + } + if (!Array.isArray(id)) + return this.reporter.error("objid() should be either array or string, got: " + JSON.stringify(id)); + if (!relative) { + if (id[1] >= 40) return this.reporter.error("Second objid identifier OOB"); + id.splice(0, 2, id[0] * 40 + id[1]); + } + let size = 0; + for (let i = 0; i < id.length; i++) { + let ident = id[i]; + for (size++; ident >= 128; ident >>= 7) size++; + } + let objid = Buffer2.alloc(size), + offset = objid.length - 1; + for (let i = id.length - 1; i >= 0; i--) { + let ident = id[i]; + for (objid[offset--] = ident & 127; (ident >>= 7) > 0; ) objid[offset--] = 128 | (ident & 127); + } + return this._createEncoderBuffer(objid); + }; + function two(num) { + return num < 10 ? "0" + num : num; + } + DERNode.prototype._encodeTime = function (time, tag) { + let str, + date = new Date(time); + return ( + tag === "gentime" + ? (str = [ + two(date.getUTCFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + "Z", + ].join("")) + : tag === "utctime" + ? (str = [ + two(date.getUTCFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + "Z", + ].join("")) + : this.reporter.error("Encoding " + tag + " time is not supported yet"), + this._encodeStr(str, "octstr") + ); + }; + DERNode.prototype._encodeNull = function () { + return this._createEncoderBuffer(""); + }; + DERNode.prototype._encodeInt = function (num, values) { + if (typeof num == "string") { + if (!values) return this.reporter.error("String int or enum given, but no values map"); + if (!values.hasOwnProperty(num)) + return this.reporter.error("Values map doesn't contain: " + JSON.stringify(num)); + num = values[num]; + } + if (typeof num != "number" && !Buffer2.isBuffer(num)) { + let numArray = num.toArray(); + !num.sign && numArray[0] & 128 && numArray.unshift(0), (num = Buffer2.from(numArray)); + } + if (Buffer2.isBuffer(num)) { + let size2 = num.length; + num.length === 0 && size2++; + let out2 = Buffer2.alloc(size2); + return num.copy(out2), num.length === 0 && (out2[0] = 0), this._createEncoderBuffer(out2); + } + if (num < 128) return this._createEncoderBuffer(num); + if (num < 256) return this._createEncoderBuffer([0, num]); + let size = 1; + for (let i = num; i >= 256; i >>= 8) size++; + let out = new Array(size); + for (let i = out.length - 1; i >= 0; i--) (out[i] = num & 255), (num >>= 8); + return out[0] & 128 && out.unshift(0), this._createEncoderBuffer(Buffer2.from(out)); + }; + DERNode.prototype._encodeBool = function (value) { + return this._createEncoderBuffer(value ? 255 : 0); + }; + DERNode.prototype._use = function (entity, obj) { + return typeof entity == "function" && (entity = entity(obj)), entity._getEncoder("der").tree; + }; + DERNode.prototype._skipDefault = function (dataBuffer, reporter, parent) { + let state = this._baseState, + i; + if (state.default === null) return !1; + let data = dataBuffer.join(); + if ( + (state.defaultBuffer === void 0 && + (state.defaultBuffer = this._encodeValue(state.default, reporter, parent).join()), + data.length !== state.defaultBuffer.length) + ) + return !1; + for (i = 0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return !1; + return !0; + }; + function encodeTag(tag, primitive, cls, reporter) { + let res; + if ((tag === "seqof" ? (tag = "seq") : tag === "setof" && (tag = "set"), der.tagByName.hasOwnProperty(tag))) + res = der.tagByName[tag]; + else if (typeof tag == "number" && (tag | 0) === tag) res = tag; + else return reporter.error("Unknown tag: " + tag); + return res >= 31 + ? reporter.error("Multi-octet tag encoding unsupported") + : (primitive || (res |= 32), (res |= der.tagClassByName[cls || "universal"] << 6), res); + } + }, +}); + +// node_modules/asn1.js/lib/asn1/encoders/pem.js +var require_pem = __commonJS({ + "node_modules/asn1.js/lib/asn1/encoders/pem.js"(exports, module) { + "use strict"; + var inherits = require_inherits_browser(), + DEREncoder = require_der2(); + function PEMEncoder(entity) { + DEREncoder.call(this, entity), (this.enc = "pem"); + } + inherits(PEMEncoder, DEREncoder); + module.exports = PEMEncoder; + PEMEncoder.prototype.encode = function (data, options) { + let p = DEREncoder.prototype.encode.call(this, data).toString("base64"), + out = ["-----BEGIN " + options.label + "-----"]; + for (let i = 0; i < p.length; i += 64) out.push(p.slice(i, i + 64)); + return ( + out.push("-----END " + options.label + "-----"), + out.join(` +`) + ); + }; + }, +}); + +// node_modules/asn1.js/lib/asn1/encoders/index.js +var require_encoders = __commonJS({ + "node_modules/asn1.js/lib/asn1/encoders/index.js"(exports) { + "use strict"; + var encoders = exports; + encoders.der = require_der2(); + encoders.pem = require_pem(); + }, +}); + +// node_modules/asn1.js/lib/asn1/decoders/der.js +var require_der3 = __commonJS({ + "node_modules/asn1.js/lib/asn1/decoders/der.js"(exports, module) { + "use strict"; + var inherits = require_inherits_browser(), + bignum = require_bn5(), + DecoderBuffer = require_buffer().DecoderBuffer, + Node = require_node(), + der = require_der(); + function DERDecoder(entity) { + (this.enc = "der"), + (this.name = entity.name), + (this.entity = entity), + (this.tree = new DERNode()), + this.tree._init(entity.body); + } + DERDecoder.prototype = {}; + module.exports = DERDecoder; + DERDecoder.prototype.decode = function (data, options) { + return ( + DecoderBuffer.isDecoderBuffer(data) || (data = new DecoderBuffer(data, options)), + this.tree._decode(data, options) + ); + }; + function DERNode(parent) { + Node.call(this, "der", parent); + } + inherits(DERNode, Node); + DERNode.prototype._peekTag = function (buffer, tag, any) { + if (buffer.isEmpty()) return !1; + let state = buffer.save(), + decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + return buffer.isError(decodedTag) + ? decodedTag + : (buffer.restore(state), + decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + "of" === tag || any); + }; + DERNode.prototype._decodeTag = function (buffer, tag, any) { + let decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) return decodedTag; + let len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); + if (buffer.isError(len)) return len; + if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + "of" !== tag) + return buffer.error('Failed to match tag: "' + tag + '"'); + if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + let state = buffer.save(), + res = this._skipUntilEnd(buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); + return buffer.isError(res) + ? res + : ((len = buffer.offset - state.offset), + buffer.restore(state), + buffer.skip(len, 'Failed to match body of: "' + tag + '"')); + }; + DERNode.prototype._skipUntilEnd = function (buffer, fail) { + for (;;) { + let tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) return tag; + let len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) return len; + let res; + if ( + (tag.primitive || len !== null ? (res = buffer.skip(len)) : (res = this._skipUntilEnd(buffer, fail)), + buffer.isError(res)) + ) + return res; + if (tag.tagStr === "end") break; + } + }; + DERNode.prototype._decodeList = function (buffer, tag, decoder, options) { + let result = []; + for (; !buffer.isEmpty(); ) { + let possibleEnd = this._peekTag(buffer, "end"); + if (buffer.isError(possibleEnd)) return possibleEnd; + let res = decoder.decode(buffer, "der", options); + if (buffer.isError(res) && possibleEnd) break; + result.push(res); + } + return result; + }; + DERNode.prototype._decodeStr = function (buffer, tag) { + if (tag === "bitstr") { + let unused = buffer.readUInt8(); + return buffer.isError(unused) ? unused : { unused, data: buffer.raw() }; + } else if (tag === "bmpstr") { + let raw = buffer.raw(); + if (raw.length % 2 === 1) return buffer.error("Decoding of string type: bmpstr length mismatch"); + let str = ""; + for (let i = 0; i < raw.length / 2; i++) str += String.fromCharCode(raw.readUInt16BE(i * 2)); + return str; + } else if (tag === "numstr") { + let numstr = buffer.raw().toString("ascii"); + return this._isNumstr(numstr) ? numstr : buffer.error("Decoding of string type: numstr unsupported characters"); + } else { + if (tag === "octstr") return buffer.raw(); + if (tag === "objDesc") return buffer.raw(); + if (tag === "printstr") { + let printstr = buffer.raw().toString("ascii"); + return this._isPrintstr(printstr) + ? printstr + : buffer.error("Decoding of string type: printstr unsupported characters"); + } else + return /str$/.test(tag) + ? buffer.raw().toString() + : buffer.error("Decoding of string type: " + tag + " unsupported"); + } + }; + DERNode.prototype._decodeObjid = function (buffer, values, relative) { + let result, + identifiers = [], + ident = 0, + subident = 0; + for (; !buffer.isEmpty(); ) + (subident = buffer.readUInt8()), + (ident <<= 7), + (ident |= subident & 127), + (subident & 128) === 0 && (identifiers.push(ident), (ident = 0)); + subident & 128 && identifiers.push(ident); + let first = (identifiers[0] / 40) | 0, + second = identifiers[0] % 40; + if ((relative ? (result = identifiers) : (result = [first, second].concat(identifiers.slice(1))), values)) { + let tmp = values[result.join(" ")]; + tmp === void 0 && (tmp = values[result.join(".")]), tmp !== void 0 && (result = tmp); + } + return result; + }; + DERNode.prototype._decodeTime = function (buffer, tag) { + let str = buffer.raw().toString(), + year, + mon, + day, + hour, + min, + sec; + if (tag === "gentime") + (year = str.slice(0, 4) | 0), + (mon = str.slice(4, 6) | 0), + (day = str.slice(6, 8) | 0), + (hour = str.slice(8, 10) | 0), + (min = str.slice(10, 12) | 0), + (sec = str.slice(12, 14) | 0); + else if (tag === "utctime") + (year = str.slice(0, 2) | 0), + (mon = str.slice(2, 4) | 0), + (day = str.slice(4, 6) | 0), + (hour = str.slice(6, 8) | 0), + (min = str.slice(8, 10) | 0), + (sec = str.slice(10, 12) | 0), + year < 70 ? (year = 2e3 + year) : (year = 1900 + year); + else return buffer.error("Decoding " + tag + " time is not supported yet"); + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); + }; + DERNode.prototype._decodeNull = function () { + return null; + }; + DERNode.prototype._decodeBool = function (buffer) { + let res = buffer.readUInt8(); + return buffer.isError(res) ? res : res !== 0; + }; + DERNode.prototype._decodeInt = function (buffer, values) { + let raw = buffer.raw(), + res = new bignum(raw); + return values && (res = values[res.toString(10)] || res), res; + }; + DERNode.prototype._use = function (entity, obj) { + return typeof entity == "function" && (entity = entity(obj)), entity._getDecoder("der").tree; + }; + function derDecodeTag(buf, fail) { + let tag = buf.readUInt8(fail); + if (buf.isError(tag)) return tag; + let cls = der.tagClass[tag >> 6], + primitive = (tag & 32) === 0; + if ((tag & 31) === 31) { + let oct = tag; + for (tag = 0; (oct & 128) === 128; ) { + if (((oct = buf.readUInt8(fail)), buf.isError(oct))) return oct; + (tag <<= 7), (tag |= oct & 127); + } + } else tag &= 31; + let tagStr = der.tag[tag]; + return { + cls, + primitive, + tag, + tagStr, + }; + } + function derDecodeLen(buf, primitive, fail) { + let len = buf.readUInt8(fail); + if (buf.isError(len)) return len; + if (!primitive && len === 128) return null; + if ((len & 128) === 0) return len; + let num = len & 127; + if (num > 4) return buf.error("length octect is too long"); + len = 0; + for (let i = 0; i < num; i++) { + len <<= 8; + let j = buf.readUInt8(fail); + if (buf.isError(j)) return j; + len |= j; + } + return len; + } + }, +}); + +// node_modules/asn1.js/lib/asn1/decoders/pem.js +var require_pem2 = __commonJS({ + "node_modules/asn1.js/lib/asn1/decoders/pem.js"(exports, module) { + "use strict"; + var inherits = require_inherits_browser(), + Buffer2 = require_safer().Buffer, + DERDecoder = require_der3(); + function PEMDecoder(entity) { + DERDecoder.call(this, entity), (this.enc = "pem"); + } + inherits(PEMDecoder, DERDecoder); + module.exports = PEMDecoder; + PEMDecoder.prototype.decode = function (data, options) { + let lines = data.toString().split(/[\r\n]+/g), + label = options.label.toUpperCase(), + re = /^-----(BEGIN|END) ([^-]+)-----$/, + start = -1, + end = -1; + for (let i = 0; i < lines.length; i++) { + let match = lines[i].match(re); + if (match !== null && match[2] === label) + if (start === -1) { + if (match[1] !== "BEGIN") break; + start = i; + } else { + if (match[1] !== "END") break; + end = i; + break; } - return res; - }), - (BN.prototype.gtn = function (num) { - return this.cmpn(num) === 1; - }), - (BN.prototype.gt = function (num) { - return this.cmp(num) === 1; - }), - (BN.prototype.gten = function (num) { - return this.cmpn(num) >= 0; - }), - (BN.prototype.gte = function (num) { - return this.cmp(num) >= 0; - }), - (BN.prototype.ltn = function (num) { - return this.cmpn(num) === -1; - }), - (BN.prototype.lt = function (num) { - return this.cmp(num) === -1; - }), - (BN.prototype.lten = function (num) { - return this.cmpn(num) <= 0; - }), - (BN.prototype.lte = function (num) { - return this.cmp(num) <= 0; - }), - (BN.prototype.eqn = function (num) { - return this.cmpn(num) === 0; - }), - (BN.prototype.eq = function (num) { - return this.cmp(num) === 0; - }), - (BN.red = function (num) { - return new Red(num); - }), - (BN.prototype.toRed = function (ctx) { - return ( - assert(!this.red, "Already a number in reduction context"), - assert(this.negative === 0, "red works only with positives"), - ctx.convertTo(this)._forceRed(ctx) - ); - }), - (BN.prototype.fromRed = function () { - return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); - }), - (BN.prototype._forceRed = function (ctx) { - return (this.red = ctx), this; - }), - (BN.prototype.forceRed = function (ctx) { - return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx); - }), - (BN.prototype.redAdd = function (num) { - return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num); - }), - (BN.prototype.redIAdd = function (num) { - return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num); - }), - (BN.prototype.redSub = function (num) { - return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num); - }), - (BN.prototype.redISub = function (num) { - return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num); - }), - (BN.prototype.redShl = function (num) { - return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num); - }), - (BN.prototype.redMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.mul(this, num) - ); - }), - (BN.prototype.redIMul = function (num) { - return ( - assert(this.red, "redMul works only with red numbers"), - this.red._verify2(this, num), - this.red.imul(this, num) - ); - }), - (BN.prototype.redSqr = function () { - return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); - }), - (BN.prototype.redISqr = function () { - return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); - }), - (BN.prototype.redSqrt = function () { - return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); - }), - (BN.prototype.redInvm = function () { - return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + } + if (start === -1 || end === -1) throw new Error("PEM section not found for: " + label); + let base64 = lines.slice(start + 1, end).join(""); + base64.replace(/[^a-z0-9+/=]+/gi, ""); + let input = Buffer2.from(base64, "base64"); + return DERDecoder.prototype.decode.call(this, input, options); + }; + }, +}); + +// node_modules/asn1.js/lib/asn1/decoders/index.js +var require_decoders = __commonJS({ + "node_modules/asn1.js/lib/asn1/decoders/index.js"(exports) { + "use strict"; + var decoders = exports; + decoders.der = require_der3(); + decoders.pem = require_pem2(); + }, +}); + +// node_modules/asn1.js/lib/asn1/api.js +var require_api = __commonJS({ + "node_modules/asn1.js/lib/asn1/api.js"(exports) { + "use strict"; + var encoders = require_encoders(), + decoders = require_decoders(), + inherits = require_inherits_browser(), + api = exports; + api.define = function (name, body) { + return new Entity(name, body); + }; + function Entity(name, body) { + (this.name = name), (this.body = body), (this.decoders = {}), (this.encoders = {}); + } + Entity.prototype = {}; + Entity.prototype._createNamed = function (Base) { + let name = this.name; + function Generated(entity) { + this._initNamed(entity, name); + } + return ( + inherits(Generated, Base), + (Generated.prototype._initNamed = function (entity, name2) { + Base.call(this, entity, name2); }), - (BN.prototype.redNeg = function () { - return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + new Generated(this) + ); + }; + Entity.prototype._getDecoder = function (enc) { + return ( + (enc = enc || "der"), + this.decoders.hasOwnProperty(enc) || (this.decoders[enc] = this._createNamed(decoders[enc])), + this.decoders[enc] + ); + }; + Entity.prototype.decode = function (data, enc, options) { + return this._getDecoder(enc).decode(data, options); + }; + Entity.prototype._getEncoder = function (enc) { + return ( + (enc = enc || "der"), + this.encoders.hasOwnProperty(enc) || (this.encoders[enc] = this._createNamed(encoders[enc])), + this.encoders[enc] + ); + }; + Entity.prototype.encode = function (data, enc, reporter) { + return this._getEncoder(enc).encode(data, reporter); + }; + }, +}); + +// node_modules/asn1.js/lib/asn1/base/index.js +var require_base2 = __commonJS({ + "node_modules/asn1.js/lib/asn1/base/index.js"(exports) { + "use strict"; + var base = exports; + base.Reporter = require_reporter().Reporter; + base.DecoderBuffer = require_buffer().DecoderBuffer; + base.EncoderBuffer = require_buffer().EncoderBuffer; + base.Node = require_node(); + }, +}); + +// node_modules/asn1.js/lib/asn1/constants/index.js +var require_constants = __commonJS({ + "node_modules/asn1.js/lib/asn1/constants/index.js"(exports) { + "use strict"; + var constants = exports; + constants._reverse = function (map) { + let res = {}; + return ( + Object.keys(map).forEach(function (key) { + (key | 0) == key && (key = key | 0); + let value = map[key]; + res[value] = key; }), - (BN.prototype.redPow = function (num) { - return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num); + res + ); + }; + constants.der = require_der(); + }, +}); + +// node_modules/asn1.js/lib/asn1.js +var require_asn1 = __commonJS({ + "node_modules/asn1.js/lib/asn1.js"(exports) { + "use strict"; + var asn1 = exports; + asn1.bignum = require_bn5(); + asn1.define = require_api().define; + asn1.base = require_base2(); + asn1.constants = require_constants(); + asn1.decoders = require_decoders(); + asn1.encoders = require_encoders(); + }, +}); + +// node_modules/parse-asn1/certificate.js +var require_certificate = __commonJS({ + "node_modules/parse-asn1/certificate.js"(exports, module) { + "use strict"; + var asn = require_asn1(), + Time = asn.define("Time", function () { + this.choice({ + utcTime: this.utctime(), + generalTime: this.gentime(), }); - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null, - }; - function MPrime(name, p) { - (this.name = name), - (this.p = new BN(p, 16)), - (this.n = this.p.bitLength()), - (this.k = new BN(1).iushln(this.n).isub(this.p)), - (this.tmp = this._tmp()); - } - (MPrime.prototype._tmp = function () { - var tmp = new BN(null); - return (tmp.words = new Array(Math.ceil(this.n / 13))), tmp; }), - (MPrime.prototype.ireduce = function (num) { - var r = num, - rlen; - do this.split(r, this.tmp), (r = this.imulK(r)), (r = r.iadd(this.tmp)), (rlen = r.bitLength()); - while (rlen > this.n); - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - return ( - cmp === 0 - ? ((r.words[0] = 0), (r.length = 1)) - : cmp > 0 - ? r.isub(this.p) - : r.strip !== void 0 - ? r.strip() - : r._strip(), - r - ); - }), - (MPrime.prototype.split = function (input, out) { - input.iushrn(this.n, 0, out); - }), - (MPrime.prototype.imulK = function (num) { - return num.imul(this.k); + AttributeTypeValue = asn.define("AttributeTypeValue", function () { + this.seq().obj(this.key("type").objid(), this.key("value").any()); + }), + AlgorithmIdentifier = asn.define("AlgorithmIdentifier", function () { + this.seq().obj( + this.key("algorithm").objid(), + this.key("parameters").optional(), + this.key("curve").objid().optional(), + ); + }), + SubjectPublicKeyInfo = asn.define("SubjectPublicKeyInfo", function () { + this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier), this.key("subjectPublicKey").bitstr()); + }), + RelativeDistinguishedName = asn.define("RelativeDistinguishedName", function () { + this.setof(AttributeTypeValue); + }), + RDNSequence = asn.define("RDNSequence", function () { + this.seqof(RelativeDistinguishedName); + }), + Name = asn.define("Name", function () { + this.choice({ + rdnSequence: this.use(RDNSequence), }); - function K256() { - MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + }), + Validity = asn.define("Validity", function () { + this.seq().obj(this.key("notBefore").use(Time), this.key("notAfter").use(Time)); + }), + Extension = asn.define("Extension", function () { + this.seq().obj(this.key("extnID").objid(), this.key("critical").bool().def(!1), this.key("extnValue").octstr()); + }), + TBSCertificate = asn.define("TBSCertificate", function () { + this.seq().obj( + this.key("version").explicit(0).int().optional(), + this.key("serialNumber").int(), + this.key("signature").use(AlgorithmIdentifier), + this.key("issuer").use(Name), + this.key("validity").use(Validity), + this.key("subject").use(Name), + this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo), + this.key("issuerUniqueID").implicit(1).bitstr().optional(), + this.key("subjectUniqueID").implicit(2).bitstr().optional(), + this.key("extensions").explicit(3).seqof(Extension).optional(), + ); + }), + X509Certificate = asn.define("X509Certificate", function () { + this.seq().obj( + this.key("tbsCertificate").use(TBSCertificate), + this.key("signatureAlgorithm").use(AlgorithmIdentifier), + this.key("signatureValue").bitstr(), + ); + }); + module.exports = X509Certificate; + }, +}); + +// node_modules/parse-asn1/asn1.js +var require_asn12 = __commonJS({ + "node_modules/parse-asn1/asn1.js"(exports) { + "use strict"; + var asn1 = require_asn1(); + exports.certificate = require_certificate(); + var RSAPrivateKey = asn1.define("RSAPrivateKey", function () { + this.seq().obj( + this.key("version").int(), + this.key("modulus").int(), + this.key("publicExponent").int(), + this.key("privateExponent").int(), + this.key("prime1").int(), + this.key("prime2").int(), + this.key("exponent1").int(), + this.key("exponent2").int(), + this.key("coefficient").int(), + ); + }); + exports.RSAPrivateKey = RSAPrivateKey; + var RSAPublicKey = asn1.define("RSAPublicKey", function () { + this.seq().obj(this.key("modulus").int(), this.key("publicExponent").int()); + }); + exports.RSAPublicKey = RSAPublicKey; + var PublicKey = asn1.define("SubjectPublicKeyInfo", function () { + this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier), this.key("subjectPublicKey").bitstr()); + }); + exports.PublicKey = PublicKey; + var AlgorithmIdentifier = asn1.define("AlgorithmIdentifier", function () { + this.seq().obj( + this.key("algorithm").objid(), + this.key("none").null_().optional(), + this.key("curve").objid().optional(), + this.key("params").seq().obj(this.key("p").int(), this.key("q").int(), this.key("g").int()).optional(), + ); + }), + PrivateKeyInfo = asn1.define("PrivateKeyInfo", function () { + this.seq().obj( + this.key("version").int(), + this.key("algorithm").use(AlgorithmIdentifier), + this.key("subjectPrivateKey").octstr(), + ); + }); + exports.PrivateKey = PrivateKeyInfo; + var EncryptedPrivateKeyInfo = asn1.define("EncryptedPrivateKeyInfo", function () { + this.seq().obj( + this.key("algorithm") + .seq() + .obj( + this.key("id").objid(), + this.key("decrypt") + .seq() + .obj( + this.key("kde") + .seq() + .obj( + this.key("id").objid(), + this.key("kdeparams").seq().obj(this.key("salt").octstr(), this.key("iters").int()), + ), + this.key("cipher").seq().obj(this.key("algo").objid(), this.key("iv").octstr()), + ), + ), + this.key("subjectPrivateKey").octstr(), + ); + }); + exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo; + var DSAPrivateKey = asn1.define("DSAPrivateKey", function () { + this.seq().obj( + this.key("version").int(), + this.key("p").int(), + this.key("q").int(), + this.key("g").int(), + this.key("pub_key").int(), + this.key("priv_key").int(), + ); + }); + exports.DSAPrivateKey = DSAPrivateKey; + exports.DSAparam = asn1.define("DSAparam", function () { + this.int(); + }); + var ECPrivateKey = asn1.define("ECPrivateKey", function () { + this.seq().obj( + this.key("version").int(), + this.key("privateKey").octstr(), + this.key("parameters").optional().explicit(0).use(ECParameters), + this.key("publicKey").optional().explicit(1).bitstr(), + ); + }); + exports.ECPrivateKey = ECPrivateKey; + var ECParameters = asn1.define("ECParameters", function () { + this.choice({ + namedCurve: this.objid(), + }); + }); + exports.signature = asn1.define("signature", function () { + this.seq().obj(this.key("r").int(), this.key("s").int()); + }); + }, +}); + +// node_modules/parse-asn1/aesid.json +var require_aesid = __commonJS({ + "node_modules/parse-asn1/aesid.json"(exports, module) { + module.exports = { + "2.16.840.1.101.3.4.1.1": "aes-128-ecb", + "2.16.840.1.101.3.4.1.2": "aes-128-cbc", + "2.16.840.1.101.3.4.1.3": "aes-128-ofb", + "2.16.840.1.101.3.4.1.4": "aes-128-cfb", + "2.16.840.1.101.3.4.1.21": "aes-192-ecb", + "2.16.840.1.101.3.4.1.22": "aes-192-cbc", + "2.16.840.1.101.3.4.1.23": "aes-192-ofb", + "2.16.840.1.101.3.4.1.24": "aes-192-cfb", + "2.16.840.1.101.3.4.1.41": "aes-256-ecb", + "2.16.840.1.101.3.4.1.42": "aes-256-cbc", + "2.16.840.1.101.3.4.1.43": "aes-256-ofb", + "2.16.840.1.101.3.4.1.44": "aes-256-cfb", + }; + }, +}); + +// node_modules/parse-asn1/fixProc.js +var require_fixProc = __commonJS({ + "node_modules/parse-asn1/fixProc.js"(exports, module) { + var findProc = + /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m, + startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m, + fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m, + evp = require_evp_bytestokey(), + ciphers = require_browser5(), + Buffer2 = require_safe_buffer().Buffer; + module.exports = function (okey, password) { + var key = okey.toString(), + match = key.match(findProc), + decrypted; + if (match) { + var suite = "aes" + match[1], + iv = Buffer2.from(match[2], "hex"), + cipherText = Buffer2.from(match[3].replace(/[\r\n]/g, ""), "base64"), + cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key, + out = [], + cipher = ciphers.createDecipheriv(suite, cipherKey, iv); + out.push(cipher.update(cipherText)), out.push(cipher.final()), (decrypted = Buffer2.concat(out)); + } else { + var match2 = key.match(fullRegex); + decrypted = Buffer2.from(match2[2].replace(/[\r\n]/g, ""), "base64"); } - inherits(K256, MPrime), - (K256.prototype.split = function (input, output) { - for (var mask = 4194303, outLen = Math.min(input.length, 9), i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - if (((output.length = outLen), input.length <= 9)) { - (input.words[0] = 0), (input.length = 1); - return; - } - var prev = input.words[9]; - for (output.words[output.length++] = prev & mask, i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - (input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22)), (prev = next); + var tag = key.match(startRegex)[1]; + return { + tag, + data: decrypted, + }; + }; + }, +}); + +// node_modules/parse-asn1/index.js +var require_parse_asn1 = __commonJS({ + "node_modules/parse-asn1/index.js"(exports, module) { + var asn1 = require_asn12(), + aesid = require_aesid(), + fixProc = require_fixProc(), + ciphers = require_browser5(), + compat = require_browser4(), + Buffer2 = require_safe_buffer().Buffer; + module.exports = parseKeys; + function parseKeys(buffer) { + var password; + typeof buffer == "object" && !Buffer2.isBuffer(buffer) && ((password = buffer.passphrase), (buffer = buffer.key)), + typeof buffer == "string" && (buffer = Buffer2.from(buffer)); + var stripped = fixProc(buffer, password), + type = stripped.tag, + data = stripped.data, + subtype, + ndata; + switch (type) { + case "CERTIFICATE": + ndata = asn1.certificate.decode(data, "der").tbsCertificate.subjectPublicKeyInfo; + case "PUBLIC KEY": + switch ( + (ndata || (ndata = asn1.PublicKey.decode(data, "der")), + (subtype = ndata.algorithm.algorithm.join(".")), + subtype) + ) { + case "1.2.840.113549.1.1.1": + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, "der"); + case "1.2.840.10045.2.1": + return ( + (ndata.subjectPrivateKey = ndata.subjectPublicKey), + { + type: "ec", + data: ndata, + } + ); + case "1.2.840.10040.4.1": + return ( + (ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, "der")), + { + type: "dsa", + data: ndata.algorithm.params, + } + ); + default: + throw new Error("unknown key id " + subtype); } - (prev >>>= 22), - (input.words[i - 10] = prev), - prev === 0 && input.length > 10 ? (input.length -= 10) : (input.length -= 9); - }), - (K256.prototype.imulK = function (num) { - (num.words[num.length] = 0), (num.words[num.length + 1] = 0), (num.length += 2); - for (var lo = 0, i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - (lo += w * 977), (num.words[i] = lo & 67108863), (lo = w * 64 + ((lo / 67108864) | 0)); + case "ENCRYPTED PRIVATE KEY": + (data = asn1.EncryptedPrivateKey.decode(data, "der")), (data = decrypt(data, password)); + case "PRIVATE KEY": + switch ( + ((ndata = asn1.PrivateKey.decode(data, "der")), (subtype = ndata.algorithm.algorithm.join(".")), subtype) + ) { + case "1.2.840.113549.1.1.1": + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, "der"); + case "1.2.840.10045.2.1": + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, "der").privateKey, + }; + case "1.2.840.10040.4.1": + return ( + (ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, "der")), + { + type: "dsa", + params: ndata.algorithm.params, + } + ); + default: + throw new Error("unknown key id " + subtype); } + case "RSA PUBLIC KEY": + return asn1.RSAPublicKey.decode(data, "der"); + case "RSA PRIVATE KEY": + return asn1.RSAPrivateKey.decode(data, "der"); + case "DSA PRIVATE KEY": + return { + type: "dsa", + params: asn1.DSAPrivateKey.decode(data, "der"), + }; + case "EC PRIVATE KEY": return ( - num.words[num.length - 1] === 0 && (num.length--, num.words[num.length - 1] === 0 && num.length--), num + (data = asn1.ECPrivateKey.decode(data, "der")), + { + curve: data.parameters.value, + privateKey: data.privateKey, + } ); - }); - function P224() { - MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - inherits(P224, MPrime); - function P192() { - MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + default: + throw new Error("unknown key type " + type); } - inherits(P192, MPrime); - function P25519() { - MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + parseKeys.signature = asn1.signature; + function decrypt(data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt, + iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10), + algo = aesid[data.algorithm.decrypt.cipher.algo.join(".")], + iv = data.algorithm.decrypt.cipher.iv, + cipherText = data.subjectPrivateKey, + keylen = parseInt(algo.split("-")[1], 10) / 8, + key = compat.pbkdf2Sync(password, salt, iters, keylen, "sha1"), + cipher = ciphers.createDecipheriv(algo, key, iv), + out = []; + return out.push(cipher.update(cipherText)), out.push(cipher.final()), Buffer2.concat(out); + } + }, +}); + +// node_modules/browserify-sign/browser/curves.json +var require_curves2 = __commonJS({ + "node_modules/browserify-sign/browser/curves.json"(exports, module) { + module.exports = { + "1.3.132.0.10": "secp256k1", + "1.3.132.0.33": "p224", + "1.2.840.10045.3.1.1": "p192", + "1.2.840.10045.3.1.7": "p256", + "1.3.132.0.34": "p384", + "1.3.132.0.35": "p521", + }; + }, +}); + +// node_modules/browserify-sign/browser/sign.js +var require_sign = __commonJS({ + "node_modules/browserify-sign/browser/sign.js"(exports, module) { + var Buffer2 = require_safe_buffer().Buffer, + createHmac = require_browser3(), + crt = require_browserify_rsa(), + EC = require_elliptic().ec, + BN = require_bn3(), + parseKeys = require_parse_asn1(), + curves = require_curves2(); + function sign(hash, key, hashType, signType, tag) { + var priv = parseKeys(key); + if (priv.curve) { + if (signType !== "ecdsa" && signType !== "ecdsa/rsa") throw new Error("wrong private key type"); + return ecSign(hash, priv); + } else if (priv.type === "dsa") { + if (signType !== "dsa") throw new Error("wrong private key type"); + return dsaSign(hash, priv, hashType); + } else if (signType !== "rsa" && signType !== "ecdsa/rsa") throw new Error("wrong private key type"); + hash = Buffer2.concat([tag, hash]); + for (var len = priv.modulus.byteLength(), pad = [0, 1]; hash.length + pad.length + 1 < len; ) pad.push(255); + pad.push(0); + for (var i = -1; ++i < hash.length; ) pad.push(hash[i]); + var out = crt(pad, priv); + return out; + } + function ecSign(hash, priv) { + var curveId = curves[priv.curve.join(".")]; + if (!curveId) throw new Error("unknown curve " + priv.curve.join(".")); + var curve = new EC(curveId), + key = curve.keyFromPrivate(priv.privateKey), + out = key.sign(hash); + return Buffer2.from(out.toDER()); + } + function dsaSign(hash, priv, algo) { + for ( + var x = priv.params.priv_key, + p = priv.params.p, + q = priv.params.q, + g = priv.params.g, + r = new BN(0), + k, + H = bits2int(hash, q).mod(q), + s = !1, + kv = getKey(x, q, hash, algo); + s === !1; + + ) + (k = makeKey(q, kv, algo)), + (r = makeR(g, k, p, q)), + (s = k + .invm(q) + .imul(H.add(x.mul(r))) + .mod(q)), + s.cmpn(0) === 0 && ((s = !1), (r = new BN(0))); + return toDER(r, s); + } + function toDER(r, s) { + (r = r.toArray()), (s = s.toArray()), r[0] & 128 && (r = [0].concat(r)), s[0] & 128 && (s = [0].concat(s)); + var total = r.length + s.length + 4, + res = [48, total, 2, r.length]; + return (res = res.concat(r, [2, s.length], s)), Buffer2.from(res); + } + function getKey(x, q, hash, algo) { + if (((x = Buffer2.from(x.toArray())), x.length < q.byteLength())) { + var zeros = Buffer2.alloc(q.byteLength() - x.length); + x = Buffer2.concat([zeros, x]); } - inherits(P25519, MPrime), - (P25519.prototype.imulK = function (num) { - for (var carry = 0, i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 19 + carry, - lo = hi & 67108863; - (hi >>>= 26), (num.words[i] = lo), (carry = hi); - } - return carry !== 0 && (num.words[num.length++] = carry), num; - }), - (BN._prime = function (name) { - if (primes[name]) return primes[name]; - var prime2; - if (name === "k256") prime2 = new K256(); - else if (name === "p224") prime2 = new P224(); - else if (name === "p192") prime2 = new P192(); - else if (name === "p25519") prime2 = new P25519(); - else throw new Error("Unknown prime " + name); - return (primes[name] = prime2), prime2; - }); - function Red(m) { - if (typeof m == "string") { - var prime = BN._prime(m); - (this.m = prime.p), (this.prime = prime); - } else assert(m.gtn(1), "modulus must be greater than 1"), (this.m = m), (this.prime = null); + var hlen = hash.length, + hbits = bits2octets(hash, q), + v = Buffer2.alloc(hlen); + v.fill(1); + var k = Buffer2.alloc(hlen); + return ( + (k = createHmac(algo, k) + .update(v) + .update(Buffer2.from([0])) + .update(x) + .update(hbits) + .digest()), + (v = createHmac(algo, k).update(v).digest()), + (k = createHmac(algo, k) + .update(v) + .update(Buffer2.from([1])) + .update(x) + .update(hbits) + .digest()), + (v = createHmac(algo, k).update(v).digest()), + { k, v } + ); + } + function bits2int(obits, q) { + var bits = new BN(obits), + shift = (obits.length << 3) - q.bitLength(); + return shift > 0 && bits.ishrn(shift), bits; + } + function bits2octets(bits, q) { + (bits = bits2int(bits, q)), (bits = bits.mod(q)); + var out = Buffer2.from(bits.toArray()); + if (out.length < q.byteLength()) { + var zeros = Buffer2.alloc(q.byteLength() - out.length); + out = Buffer2.concat([zeros, out]); } - (Red.prototype._verify1 = function (a) { - assert(a.negative === 0, "red works only with positives"), assert(a.red, "red works only with red numbers"); - }), - (Red.prototype._verify2 = function (a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"), - assert(a.red && a.red === b.red, "red works only with red numbers"); - }), - (Red.prototype.imod = function (a) { - return this.prime ? this.prime.ireduce(a)._forceRed(this) : a.umod(this.m)._forceRed(this); - }), - (Red.prototype.neg = function (a) { - return a.isZero() ? a.clone() : this.m.sub(a)._forceRed(this); - }), - (Red.prototype.add = function (a, b) { - this._verify2(a, b); - var res = a.add(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res._forceRed(this); - }), - (Red.prototype.iadd = function (a, b) { - this._verify2(a, b); - var res = a.iadd(b); - return res.cmp(this.m) >= 0 && res.isub(this.m), res; - }), - (Red.prototype.sub = function (a, b) { - this._verify2(a, b); - var res = a.sub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res._forceRed(this); - }), - (Red.prototype.isub = function (a, b) { - this._verify2(a, b); - var res = a.isub(b); - return res.cmpn(0) < 0 && res.iadd(this.m), res; - }), - (Red.prototype.shl = function (a, num) { - return this._verify1(a), this.imod(a.ushln(num)); - }), - (Red.prototype.imul = function (a, b) { - return this._verify2(a, b), this.imod(a.imul(b)); - }), - (Red.prototype.mul = function (a, b) { - return this._verify2(a, b), this.imod(a.mul(b)); - }), - (Red.prototype.isqr = function (a) { - return this.imul(a, a.clone()); - }), - (Red.prototype.sqr = function (a) { - return this.mul(a, a); - }), - (Red.prototype.sqrt = function (a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - if ((assert(mod3 % 2 === 1), mod3 === 3)) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - for (var q = this.m.subn(1), s = 0; !q.isZero() && q.andln(1) === 0; ) s++, q.iushrn(1); - assert(!q.isZero()); - var one = new BN(1).toRed(this), - nOne = one.redNeg(), - lpow = this.m.subn(1).iushrn(1), - z = this.m.bitLength(); - for (z = new BN(2 * z * z).toRed(this); this.pow(z, lpow).cmp(nOne) !== 0; ) z.redIAdd(nOne); - for ( - var c = this.pow(z, q), r = this.pow(a, q.addn(1).iushrn(1)), t = this.pow(a, q), m = s; - t.cmp(one) !== 0; + return out; + } + function makeKey(q, kv, algo) { + var t, k; + do { + for (t = Buffer2.alloc(0); t.length * 8 < q.bitLength(); ) + (kv.v = createHmac(algo, kv.k).update(kv.v).digest()), (t = Buffer2.concat([t, kv.v])); + (k = bits2int(t, q)), + (kv.k = createHmac(algo, kv.k) + .update(kv.v) + .update(Buffer2.from([0])) + .digest()), + (kv.v = createHmac(algo, kv.k).update(kv.v).digest()); + } while (k.cmp(q) !== -1); + return k; + } + function makeR(g, k, p, q) { + return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q); + } + module.exports = sign; + module.exports.getKey = getKey; + module.exports.makeKey = makeKey; + }, +}); + +// node_modules/browserify-sign/browser/verify.js +var require_verify = __commonJS({ + "node_modules/browserify-sign/browser/verify.js"(exports, module) { + var Buffer2 = require_safe_buffer().Buffer, + BN = require_bn3(), + EC = require_elliptic().ec, + parseKeys = require_parse_asn1(), + curves = require_curves2(); + function verify(sig, hash, key, signType, tag) { + var pub = parseKeys(key); + if (pub.type === "ec") { + if (signType !== "ecdsa" && signType !== "ecdsa/rsa") throw new Error("wrong public key type"); + return ecVerify(sig, hash, pub); + } else if (pub.type === "dsa") { + if (signType !== "dsa") throw new Error("wrong public key type"); + return dsaVerify(sig, hash, pub); + } else if (signType !== "rsa" && signType !== "ecdsa/rsa") throw new Error("wrong public key type"); + hash = Buffer2.concat([tag, hash]); + for (var len = pub.modulus.byteLength(), pad = [1], padNum = 0; hash.length + pad.length + 2 < len; ) + pad.push(255), padNum++; + pad.push(0); + for (var i = -1; ++i < hash.length; ) pad.push(hash[i]); + pad = Buffer2.from(pad); + var red = BN.mont(pub.modulus); + (sig = new BN(sig).toRed(red)), + (sig = sig.redPow(new BN(pub.publicExponent))), + (sig = Buffer2.from(sig.fromRed().toArray())); + var out = padNum < 8 ? 1 : 0; + for (len = Math.min(sig.length, pad.length), sig.length !== pad.length && (out = 1), i = -1; ++i < len; ) + out |= sig[i] ^ pad[i]; + return out === 0; + } + function ecVerify(sig, hash, pub) { + var curveId = curves[pub.data.algorithm.curve.join(".")]; + if (!curveId) throw new Error("unknown curve " + pub.data.algorithm.curve.join(".")); + var curve = new EC(curveId), + pubkey = pub.data.subjectPrivateKey.data; + return curve.verify(hash, sig, pubkey); + } + function dsaVerify(sig, hash, pub) { + var p = pub.data.p, + q = pub.data.q, + g = pub.data.g, + y = pub.data.pub_key, + unpacked = parseKeys.signature.decode(sig, "der"), + s = unpacked.s, + r = unpacked.r; + checkValue(s, q), checkValue(r, q); + var montp = BN.mont(p), + w = s.invm(q), + v = g + .toRed(montp) + .redPow(new BN(hash).mul(w).mod(q)) + .fromRed() + .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) + .mod(p) + .mod(q); + return v.cmp(r) === 0; + } + function checkValue(b, q) { + if (b.cmpn(0) <= 0) throw new Error("invalid sig"); + if (b.cmp(q) >= q) throw new Error("invalid sig"); + } + module.exports = verify; + }, +}); + +// node_modules/browserify-sign/browser/index.js +var require_browser8 = __commonJS({ + "node_modules/browserify-sign/browser/index.js"(exports, module) { + var Buffer2 = require_safe_buffer().Buffer; + var createHash = require_browser2(); + var inherits = require_inherits_browser(); + var sign = require_sign(); + var verify = require_verify(); + var algorithms = require_algorithms(); + Object.keys(algorithms).forEach(function (key) { + (algorithms[key].id = Buffer2.from(algorithms[key].id, "hex")), (algorithms[key.toLowerCase()] = algorithms[key]); + }); + function Sign(algorithm) { + StreamModule.Writable.call(this); + var data = algorithms[algorithm]; + if (!data) throw new Error("Unknown message digest"); + (this._hashType = data.hash), + (this._hash = createHash(data.hash)), + (this._tag = data.id), + (this._signType = data.sign); + } + inherits(Sign, StreamModule.Writable); + Sign.prototype._write = function (data, _, done) { + this._hash.update(data), done(); + }; + Sign.prototype.update = function (data, enc) { + return typeof data == "string" && (data = Buffer2.from(data, enc)), this._hash.update(data), this; + }; + Sign.prototype.sign = function (key, enc) { + this.end(); + var hash = this._hash.digest(), + sig = sign(hash, key, this._hashType, this._signType, this._tag); + return enc ? sig.toString(enc) : sig; + }; + function Verify(algorithm) { + StreamModule.Writable.call(this); + var data = algorithms[algorithm]; + if (!data) throw new Error("Unknown message digest"); + (this._hash = createHash(data.hash)), (this._tag = data.id), (this._signType = data.sign); + } + inherits(Verify, StreamModule.Writable); + Verify.prototype._write = function (data, _, done) { + this._hash.update(data), done(); + }; + Verify.prototype.update = function (data, enc) { + return typeof data == "string" && (data = Buffer2.from(data, enc)), this._hash.update(data), this; + }; + Verify.prototype.verify = function (key, sig, enc) { + typeof sig == "string" && (sig = Buffer2.from(sig, enc)), this.end(); + var hash = this._hash.digest(); + return verify(sig, hash, key, this._signType, this._tag); + }; + function createSign(algorithm) { + return new Sign(algorithm); + } + function createVerify(algorithm) { + return new Verify(algorithm); + } + module.exports = { + Sign: createSign, + Verify: createVerify, + createSign, + createVerify, + }; + }, +}); - ) { - for (var tmp = t, i = 0; tmp.cmp(one) !== 0; i++) tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - (r = r.redMul(b)), (c = b.redSqr()), (t = t.redMul(c)), (m = i); - } - return r; - }), - (Red.prototype.invm = function (a) { - var inv = a._invmp(this.m); - return inv.negative !== 0 ? ((inv.negative = 0), this.imod(inv).redNeg()) : this.imod(inv); - }), - (Red.prototype.pow = function (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4, - wnd = new Array(1 << windowSize); - (wnd[0] = new BN(1).toRed(this)), (wnd[1] = a); - for (var i = 2; i < wnd.length; i++) wnd[i] = this.mul(wnd[i - 1], a); - var res = wnd[0], - current = 0, - currentLen = 0, - start = num.bitLength() % 26; - for (start === 0 && (start = 26), i = num.length - 1; i >= 0; i--) { - for (var word = num.words[i], j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if ((res !== wnd[0] && (res = this.sqr(res)), bit === 0 && current === 0)) { - currentLen = 0; - continue; - } - (current <<= 1), - (current |= bit), - currentLen++, - !(currentLen !== windowSize && (i !== 0 || j !== 0)) && - ((res = this.mul(res, wnd[current])), (currentLen = 0), (current = 0)); - } - start = 26; - } - return res; - }), - (Red.prototype.convertTo = function (num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }), - (Red.prototype.convertFrom = function (num) { - var res = num.clone(); - return (res.red = null), res; - }), - (BN.mont = function (num) { - return new Mont(num); - }); - function Mont(m) { - Red.call(this, m), - (this.shift = this.m.bitLength()), - this.shift % 26 !== 0 && (this.shift += 26 - (this.shift % 26)), - (this.r = new BN(1).iushln(this.shift)), - (this.r2 = this.imod(this.r.sqr())), - (this.rinv = this.r._invmp(this.m)), - (this.minv = this.rinv.mul(this.r).isubn(1).div(this.m)), - (this.minv = this.minv.umod(this.r)), - (this.minv = this.r.sub(this.minv)); +// node_modules/create-ecdh/node_modules/bn.js/lib/bn.js +var require_bn6 = require_bn; + +// node_modules/create-ecdh/browser.js +var require_browser9 = __commonJS({ + "node_modules/create-ecdh/browser.js"(exports, module) { + var elliptic = require_elliptic(), + BN = require_bn6(); + module.exports = function (curve) { + return new ECDH(curve); + }; + var aliases = { + secp256k1: { + name: "secp256k1", + byteLength: 32, + }, + secp224r1: { + name: "p224", + byteLength: 28, + }, + prime256v1: { + name: "p256", + byteLength: 32, + }, + prime192v1: { + name: "p192", + byteLength: 24, + }, + ed25519: { + name: "ed25519", + byteLength: 32, + }, + secp384r1: { + name: "p384", + byteLength: 48, + }, + secp521r1: { + name: "p521", + byteLength: 66, + }, + }; + aliases.p224 = aliases.secp224r1; + aliases.p256 = aliases.secp256r1 = aliases.prime256v1; + aliases.p192 = aliases.secp192r1 = aliases.prime192v1; + aliases.p384 = aliases.secp384r1; + aliases.p521 = aliases.secp521r1; + function ECDH(curve) { + (this.curveType = aliases[curve]), + this.curveType || + (this.curveType = { + name: curve, + }), + (this.curve = new elliptic.ec(this.curveType.name)), + (this.keys = void 0); + } + ECDH.prototype = {}; + ECDH.prototype.generateKeys = function (enc, format) { + return (this.keys = this.curve.genKeyPair()), this.getPublicKey(enc, format); + }; + ECDH.prototype.computeSecret = function (other, inenc, enc) { + (inenc = inenc || "utf8"), Buffer.isBuffer(other) || (other = new Buffer(other, inenc)); + var otherPub = this.curve.keyFromPublic(other).getPublic(), + out = otherPub.mul(this.keys.getPrivate()).getX(); + return formatReturnValue(out, enc, this.curveType.byteLength); + }; + ECDH.prototype.getPublicKey = function (enc, format) { + var key = this.keys.getPublic(format === "compressed", !0); + return ( + format === "hybrid" && (key[key.length - 1] % 2 ? (key[0] = 7) : (key[0] = 6)), formatReturnValue(key, enc) + ); + }; + ECDH.prototype.getPrivateKey = function (enc) { + return formatReturnValue(this.keys.getPrivate(), enc); + }; + ECDH.prototype.setPublicKey = function (pub, enc) { + return ( + (enc = enc || "utf8"), Buffer.isBuffer(pub) || (pub = new Buffer(pub, enc)), this.keys._importPublic(pub), this + ); + }; + ECDH.prototype.setPrivateKey = function (priv, enc) { + (enc = enc || "utf8"), Buffer.isBuffer(priv) || (priv = new Buffer(priv, enc)); + var _priv = new BN(priv); + return (_priv = _priv.toString(16)), (this.keys = this.curve.genKeyPair()), this.keys._importPrivate(_priv), this; + }; + function formatReturnValue(bn, enc, len) { + Array.isArray(bn) || (bn = bn.toArray()); + var buf = new Buffer(bn); + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length); + zeros.fill(0), (buf = Buffer.concat([zeros, buf])); } - inherits(Mont, Red), - (Mont.prototype.convertTo = function (num) { - return this.imod(num.ushln(this.shift)); - }), - (Mont.prototype.convertFrom = function (num) { - var r = this.imod(num.mul(this.rinv)); - return (r.red = null), r; - }), - (Mont.prototype.imul = function (a, b) { - if (a.isZero() || b.isZero()) return (a.words[0] = 0), (a.length = 1), a; - var t = a.imul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.mul = function (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - var t = a.mul(b), - c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), - u = t.isub(c).iushrn(this.shift), - res = u; - return ( - u.cmp(this.m) >= 0 ? (res = u.isub(this.m)) : u.cmpn(0) < 0 && (res = u.iadd(this.m)), res._forceRed(this) - ); - }), - (Mont.prototype.invm = function (a) { - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }); - })(typeof module > "u" || module, exports); + return enc ? buf.toString(enc) : buf; + } + }, +}); + +// node_modules/public-encrypt/mgf.js +var require_mgf = __commonJS({ + "node_modules/public-encrypt/mgf.js"(exports, module) { + var createHash = require_browser2(), + Buffer2 = require_safe_buffer().Buffer; + module.exports = function (seed, len) { + for (var t = Buffer2.alloc(0), i = 0, c; t.length < len; ) + (c = i2ops(i++)), (t = Buffer2.concat([t, createHash("sha1").update(seed).update(c).digest()])); + return t.slice(0, len); + }; + function i2ops(c) { + var out = Buffer2.allocUnsafe(4); + return out.writeUInt32BE(c, 0), out; + } + }, +}); + +// node_modules/public-encrypt/xor.js +var require_xor = __commonJS({ + "node_modules/public-encrypt/xor.js"(exports, module) { + module.exports = function (a, b) { + for (var len = a.length, i = -1; ++i < len; ) a[i] ^= b[i]; + return a; + }; }, }); +// node_modules/public-encrypt/node_modules/bn.js/lib/bn.js +var require_bn7 = require_bn; + const { CryptoHasher } = globalThis.Bun; // node_modules/public-encrypt/withPublic.js @@ -23768,31 +11806,13 @@ var require_crypto_browserify2 = __commonJS({ `), ); }; - exports.constants = { - DH_CHECK_P_NOT_SAFE_PRIME: 2, - DH_CHECK_P_NOT_PRIME: 1, - DH_UNABLE_TO_CHECK_GENERATOR: 4, - DH_NOT_SUITABLE_GENERATOR: 8, - NPN_ENABLED: 1, - ALPN_ENABLED: 1, - RSA_PKCS1_PADDING: 1, - RSA_SSLV23_PADDING: 2, - RSA_NO_PADDING: 3, - RSA_PKCS1_OAEP_PADDING: 4, - RSA_X931_PADDING: 5, - RSA_PKCS1_PSS_PADDING: 6, - POINT_CONVERSION_COMPRESSED: 2, - POINT_CONVERSION_UNCOMPRESSED: 4, - POINT_CONVERSION_HYBRID: 6, - }; + exports.constants = $processBindingConstants.crypto; }, }); // crypto.js -var crypto_exports = { - ...require_crypto_browserify2(), - [Symbol.for("CommonJS")]: 0, -}; +var crypto_exports = require_crypto_browserify2(); + var DEFAULT_ENCODING = "buffer", getRandomValues = array => crypto.getRandomValues(array), randomUUID = () => crypto.randomUUID(), @@ -23882,58 +11902,5 @@ __export(crypto_exports, { subtle: () => webcrypto.subtle, }); -export const { - randomBytes, - rng, - pseudoRandomBytes, - prng, - Hash, - createHash, - createHmac, - Hmac, - getHashes, - pbkdf2, - pbkdf2Sync, - Cipher, - createCipher, - Cipheriv, - createCipheriv, - Decipher, - createDecipher, - Decipheriv, - createDecipheriv, - getCiphers, - listCiphers, - DiffieHellmanGroup, - createDiffieHellmanGroup, - getDiffieHellman, - createDiffieHellman, - DiffieHellman, - createSign, - Sign, - createVerify, - Verify, - createECDH, - publicEncrypt, - privateEncrypt, - publicDecrypt, - privateDecrypt, - randomFill, - randomFillSync, - createCredentials, - constants, -} = crypto_exports; - -export { - DEFAULT_ENCODING, - getRandomValues, - getCurves, - randomUUID, - randomInt, - scrypt, - scryptSync, - timingSafeEqual, - webcrypto, -}; export default crypto_exports; /*! safe-buffer. MIT License. Feross Aboukhadijeh */ diff --git a/src/js/node/dgram.ts b/src/js/node/dgram.ts index ba5a058a3b1a04..dd6f2895d44a7f 100644 --- a/src/js/node/dgram.ts +++ b/src/js/node/dgram.ts @@ -1,6 +1,6 @@ // Hardcoded module "node:dgram" // This is a stub! None of this is actually implemented yet. -import { hideFromStack, throwNotImplemented } from "../shared"; +const { hideFromStack, throwNotImplemented } = require("$shared"); function createSocket() { throwNotImplemented("node:dgram createSocket", 1630); @@ -14,13 +14,10 @@ function _createSocketHandle() { throwNotImplemented("node:dgram _createSocketHandle", 1630); } -const defaultObject = { +export default { createSocket, Socket, _createSocketHandle, - [Symbol.for("CommonJS")]: 0, }; -export { defaultObject as default, Socket, createSocket, _createSocketHandle }; - hideFromStack(createSocket, Socket, _createSocketHandle); diff --git a/src/js/node/diagnostics_channel.js b/src/js/node/diagnostics_channel.js index 72eb47d2e7ada5..664c80693257b3 100644 --- a/src/js/node/diagnostics_channel.js +++ b/src/js/node/diagnostics_channel.js @@ -1,38 +1,416 @@ // Hardcoded module "node:diagnostics_channel" -// This is a stub! None of this is actually implemented yet. +// Reference: https://github.com/nodejs/node/blob/fb47afc335ef78a8cef7eac52b8ee7f045300696/lib/diagnostics_channel.js +const SafeMap = Map; +const SafeFinalizationRegistry = FinalizationRegistry; -import { hideFromStack, throwNotImplemented } from "../shared"; +const ArrayPrototypeAt = (array, index) => array[index]; +const ArrayPrototypeIndexOf = (array, value) => array.indexOf(value); +const ArrayPrototypePush = (array, value) => array.push(value); +const ArrayPrototypeSplice = (array, start, deleteCount) => array.splice(start, deleteCount); +const ObjectGetPrototypeOf = Object.getPrototypeOf; +const ObjectSetPrototypeOf = Object.setPrototypeOf; +const SymbolHasInstance = Symbol.hasInstance; +const ReflectApply = Reflect.apply; +const PromiseResolve = Promise.resolve; +const PromiseReject = Promise.reject; +const PromisePrototypeThen = (promise, onFulfilled, onRejected) => promise.then(onFulfilled, onRejected); + +// TODO: https://github.com/nodejs/node/blob/fb47afc335ef78a8cef7eac52b8ee7f045300696/src/node_util.h#L13 +class WeakReference extends WeakRef { + #refs = 0; + + get() { + return this.deref(); + } + + incRef() { + return ++this.#refs; + } + + decRef() { + return --this.#refs; + } +} + +// Can't delete when weakref count reaches 0 as it could increment again. +// Only GC can be used as a valid time to clean up the channels map. +class WeakRefMap extends SafeMap { + #finalizers = new SafeFinalizationRegistry(key => { + this.delete(key); + }); + + set(key, value) { + this.#finalizers.register(value, key); + return super.set(key, new WeakReference(value)); + } + + get(key) { + return super.get(key)?.get(); + } + + incRef(key) { + return super.get(key)?.incRef(); + } + + decRef(key) { + return super.get(key)?.decRef(); + } +} + +function markActive(channel) { + ObjectSetPrototypeOf(channel, ActiveChannel.prototype); + channel._subscribers = []; + channel._stores = new SafeMap(); +} + +function maybeMarkInactive(channel) { + // When there are no more active subscribers or bound, restore to fast prototype. + if (!channel._subscribers.length && !channel._stores.size) { + ObjectSetPrototypeOf(channel, Channel.prototype); + channel._subscribers = undefined; + channel._stores = undefined; + } +} + +function defaultTransform(data) { + return data; +} + +function wrapStoreRun(store, data, next, transform = defaultTransform) { + return () => { + let context; + try { + context = transform(data); + } catch (err) { + process.nextTick(() => reportError(err)); + return next(); + } + + return store.run(context, next); + }; +} + +class ActiveChannel { + subscribe(subscription) { + validateFunction(subscription, "subscription"); + + ArrayPrototypePush(this._subscribers, subscription); + channels.incRef(this.name); + } + + unsubscribe(subscription) { + const index = ArrayPrototypeIndexOf(this._subscribers, subscription); + if (index === -1) return false; + + ArrayPrototypeSplice(this._subscribers, index, 1); + + channels.decRef(this.name); + maybeMarkInactive(this); + + return true; + } + + bindStore(store, transform) { + const replacing = this._stores.has(store); + if (!replacing) channels.incRef(this.name); + this._stores.set(store, transform); + } + + unbindStore(store) { + if (!this._stores.has(store)) { + return false; + } + + this._stores.delete(store); + + channels.decRef(this.name); + maybeMarkInactive(this); + + return true; + } + + get hasSubscribers() { + return true; + } + + publish(data) { + for (let i = 0; i < (this._subscribers?.length || 0); i++) { + try { + const onMessage = this._subscribers[i]; + onMessage(data, this.name); + } catch (err) { + process.nextTick(() => reportError(err)); + } + } + } + + runStores(data, fn, thisArg, ...args) { + let run = () => { + this.publish(data); + return ReflectApply(fn, thisArg, args); + }; + + for (const entry of this._stores.entries()) { + const store = entry[0]; + const transform = entry[1]; + run = wrapStoreRun(store, data, run, transform); + } + + return run(); + } +} class Channel { constructor(name) { - throwNotImplemented("node:diagnostics_channel", 2688); + this._subscribers = undefined; + this._stores = undefined; + this.name = name; + + channels.set(name, this); + } + + static [SymbolHasInstance](instance) { + const prototype = ObjectGetPrototypeOf(instance); + return prototype === Channel.prototype || prototype === ActiveChannel.prototype; + } + + subscribe(subscription) { + markActive(this); + this.subscribe(subscription); + } + + unsubscribe() { + return false; + } + + bindStore(store, transform) { + markActive(this); + this.bindStore(store, transform); + } + + unbindStore() { + return false; + } + + get hasSubscribers() { + return false; + } + + publish() {} + + runStores(data, fn, thisArg, ...args) { + return ReflectApply(fn, thisArg, args); } } -function channel() { - throwNotImplemented("node:diagnostics_channel", 2688); +const channels = new WeakRefMap(); + +function channel(name) { + const channel = channels.get(name); + if (channel) return channel; + + if (typeof name !== "string" && typeof name !== "symbol") { + throw new ERR_INVALID_ARG_TYPE("channel", ["string", "symbol"], name); + } + + return new Channel(name); +} + +function subscribe(name, subscription) { + return channel(name).subscribe(subscription); +} + +function unsubscribe(name, subscription) { + return channel(name).unsubscribe(subscription); +} + +function hasSubscribers(name) { + const channel = channels.get(name); + if (!channel) return false; + + return channel.hasSubscribers; +} + +const traceEvents = ["start", "end", "asyncStart", "asyncEnd", "error"]; + +function assertChannel(value, name) { + if (!(value instanceof Channel)) { + throw new ERR_INVALID_ARG_TYPE(name, ["Channel"], value); + } +} + +class TracingChannel { + constructor(nameOrChannels) { + if (typeof nameOrChannels === "string") { + this.start = channel(`tracing:${nameOrChannels}:start`); + this.end = channel(`tracing:${nameOrChannels}:end`); + this.asyncStart = channel(`tracing:${nameOrChannels}:asyncStart`); + this.asyncEnd = channel(`tracing:${nameOrChannels}:asyncEnd`); + this.error = channel(`tracing:${nameOrChannels}:error`); + } else if (typeof nameOrChannels === "object") { + const { start, end, asyncStart, asyncEnd, error } = nameOrChannels; + + assertChannel(start, "nameOrChannels.start"); + assertChannel(end, "nameOrChannels.end"); + assertChannel(asyncStart, "nameOrChannels.asyncStart"); + assertChannel(asyncEnd, "nameOrChannels.asyncEnd"); + assertChannel(error, "nameOrChannels.error"); + + this.start = start; + this.end = end; + this.asyncStart = asyncStart; + this.asyncEnd = asyncEnd; + this.error = error; + } else { + throw new ERR_INVALID_ARG_TYPE("nameOrChannels", ["string", "object", "Channel"], nameOrChannels); + } + } + + subscribe(handlers) { + for (const name of traceEvents) { + if (!handlers[name]) continue; + + this[name]?.subscribe(handlers[name]); + } + } + + unsubscribe(handlers) { + let done = true; + + for (const name of traceEvents) { + if (!handlers[name]) continue; + + if (!this[name]?.unsubscribe(handlers[name])) { + done = false; + } + } + + return done; + } + + traceSync(fn, context = {}, thisArg, ...args) { + const { start, end, error } = this; + + return start.runStores(context, () => { + try { + const result = ReflectApply(fn, thisArg, args); + context.result = result; + return result; + } catch (err) { + context.error = err; + error.publish(context); + throw err; + } finally { + end.publish(context); + } + }); + } + + tracePromise(fn, context = {}, thisArg, ...args) { + const { start, end, asyncStart, asyncEnd, error } = this; + + function reject(err) { + context.error = err; + error.publish(context); + asyncStart.publish(context); + // TODO: Is there a way to have asyncEnd _after_ the continuation? + asyncEnd.publish(context); + return PromiseReject(err); + } + + function resolve(result) { + context.result = result; + asyncStart.publish(context); + // TODO: Is there a way to have asyncEnd _after_ the continuation? + asyncEnd.publish(context); + return result; + } + + return start.runStores(context, () => { + try { + let promise = ReflectApply(fn, thisArg, args); + // Convert thenables to native promises + if (!(promise instanceof Promise)) { + promise = PromiseResolve(promise); + } + return PromisePrototypeThen(promise, resolve, reject); + } catch (err) { + context.error = err; + error.publish(context); + throw err; + } finally { + end.publish(context); + } + }); + } + + traceCallback(fn, position = -1, context = {}, thisArg, ...args) { + const { start, end, asyncStart, asyncEnd, error } = this; + + function wrappedCallback(err, res) { + if (err) { + context.error = err; + error.publish(context); + } else { + context.result = res; + } + + // Using runStores here enables manual context failure recovery + asyncStart.runStores(context, () => { + try { + if (callback) { + return ReflectApply(callback, this, arguments); + } + } finally { + asyncEnd.publish(context); + } + }); + } + + const callback = ArrayPrototypeAt(args, position); + if (typeof callback !== "function") { + throw new ERR_INVALID_ARG_TYPE("callback", ["function"], callback); + } + ArrayPrototypeSplice(args, position, 1, wrappedCallback); + + return start.runStores(context, () => { + try { + return ReflectApply(fn, thisArg, args); + } catch (err) { + context.error = err; + error.publish(context); + throw err; + } finally { + end.publish(context); + } + }); + } } -function hasSubscribers() { - throwNotImplemented("node:diagnostics_channel", 2688); +function tracingChannel(nameOrChannels) { + return new TracingChannel(nameOrChannels); } -function subscribe() { - throwNotImplemented("node:diagnostics_channel", 2688); + +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 unsubscribe() { - throwNotImplemented("node:diagnostics_channel", 2688); +function validateFunction(callable, field) { + if (typeof callable !== "function") { + throw new ERR_INVALID_ARG_TYPE(field, "Function", callable); + } + + return callable; } -const defaultObject = { +export default { channel, hasSubscribers, subscribe, + tracingChannel, unsubscribe, Channel, - [Symbol.for("CommonJS")]: 0, }; - -export { defaultObject as default, Channel, channel, hasSubscribers, subscribe, unsubscribe }; - -hideFromStack([channel, hasSubscribers, subscribe, unsubscribe, Channel]); diff --git a/src/js/node/dns.js b/src/js/node/dns.js index 17621f1a589fc2..f8e5366f99034e 100644 --- a/src/js/node/dns.js +++ b/src/js/node/dns.js @@ -1,7 +1,10 @@ // Hardcoded module "node:dns" // only resolve4, resolve, lookup, resolve6 and resolveSrv are implemented. +const dns = Bun.dns; -const { dns } = globalThis.Bun; +function getServers() { + return dns.getServers(); +} function lookup(domain, options, callback) { if (typeof options == "function") { @@ -432,10 +435,11 @@ function resolve(hostname, rrtype, callback) { function Resolver(options) { return new InternalResolver(options); } +Resolver.prototype = {}; Object.setPrototypeOf(Resolver.prototype, InternalResolver.prototype); Object.setPrototypeOf(Resolver, InternalResolver); -export var { +var { resolve, resolve4, resolve6, @@ -478,7 +482,7 @@ const promisifyResolveX = res => { }; // promisified versions -export const promises = { +const promises = { lookup(domain, options) { if (options?.all) { return dns.lookup(domain, options).then(promisifyLookupAll); @@ -633,7 +637,7 @@ for (const key of ["resolveAny", "reverse"]) { promises[key] = () => Promise.resolve(undefined); } -const exports = { +export default { // these are wrong ADDRCONFIG: 0, ALL: 1, @@ -685,36 +689,5 @@ const exports = { resolveTxt, resolveNaptr, promises, - [Symbol.for("CommonJS")]: 0, + getServers, }; -export default exports; -export const { - ADDRCONFIG, - ALL, - V4MAPPED, - NODATA, - FORMERR, - SERVFAIL, - NOTFOUND, - NOTIMP, - REFUSED, - BADQUERY, - BADNAME, - BADFAMILY, - BADRESP, - CONNREFUSED, - TIMEOUT, - EOF, - FILE, - NOMEM, - DESTRUCTION, - BADSTR, - BADFLAGS, - NONAME, - BADHINTS, - NOTINITIALIZED, - LOADIPHLPAPI, - ADDRGETNETWORKPARAMS, - CANCELLED, -} = exports; -export { lookup, lookupService, Resolver, setServers, setDefaultResultOrder }; diff --git a/src/js/node/dns.promises.js b/src/js/node/dns.promises.js deleted file mode 100644 index bcc47faee73abc..00000000000000 --- a/src/js/node/dns.promises.js +++ /dev/null @@ -1,47 +0,0 @@ -// Hardcoded module "node:dns/promises" -import { promises } from "node:dns"; - -export const { - lookup, - lookupService, - resolve, - resolve4, - resolve6, - resolveAny, - resolveCname, - resolveCaa, - resolveMx, - resolveNaptr, - resolveNs, - resolvePtr, - resolveSoa, - resolveSrv, - resolveTxt, - reverse, - Resolver, - setServers, - setDefaultResultOrder, -} = promises; - -export default { - lookup, - lookupService, - resolve, - resolve4, - resolve6, - resolveAny, - resolveCname, - resolveCaa, - resolveMx, - resolveNaptr, - resolveNs, - resolvePtr, - resolveSoa, - resolveSrv, - resolveTxt, - reverse, - Resolver, - setServers, - setDefaultResultOrder, - [Symbol.for("CommonJS")]: 0, -}; diff --git a/src/js/node/dns.promises.ts b/src/js/node/dns.promises.ts new file mode 100644 index 00000000000000..e0bfbc123f4298 --- /dev/null +++ b/src/js/node/dns.promises.ts @@ -0,0 +1,2 @@ +// Hardcoded module "node:dns/promises" +export default require("node:dns").promises; diff --git a/src/js/node/domain.ts b/src/js/node/domain.ts new file mode 100644 index 00000000000000..b03367ff475115 --- /dev/null +++ b/src/js/node/domain.ts @@ -0,0 +1,60 @@ +// Import Events +var EventEmitter = require("node:events"); + +// Export Domain +var domain: any = {}; +domain.createDomain = domain.create = function () { + var d = new EventEmitter(); + + function emitError(e) { + d.emit("error", e); + } + + d.add = function (emitter) { + emitter.on("error", emitError); + }; + d.remove = function (emitter) { + emitter.removeListener("error", emitError); + }; + d.bind = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + try { + fn.apply(null, args); + } catch (err) { + emitError(err); + } + }; + }; + d.intercept = function (fn) { + return function (err) { + if (err) { + emitError(err); + } else { + var args = Array.prototype.slice.call(arguments, 1); + try { + fn.apply(null, args); + } catch (err) { + emitError(err); + } + } + }; + }; + d.run = function (fn) { + try { + fn(); + } catch (err) { + emitError(err); + } + return this; + }; + d.dispose = function () { + this.removeAllListeners(); + return this; + }; + d.enter = d.exit = function () { + return this; + }; + return d; +}; +export default domain; diff --git a/src/js/node/events.js b/src/js/node/events.js index 09f89084a22c80..da7cfd57ca20d4 100644 --- a/src/js/node/events.js +++ b/src/js/node/events.js @@ -1,10 +1,8 @@ // Reimplementation of https://nodejs.org/api/events.html // Reference: https://github.com/nodejs/node/blob/main/lib/events.js -import { throwNotImplemented } from "../shared"; +const { throwNotImplemented } = require("$shared"); -var { isPromise, Array, Object } = $lazy("primordials"); const SymbolFor = Symbol.for; -const ObjectDefineProperty = Object.defineProperty; const kCapture = Symbol("kCapture"); const kErrorMonitor = SymbolFor("events.errorMonitor"); const kMaxEventTargetListeners = Symbol("events.maxEventTargetListeners"); @@ -17,7 +15,7 @@ const ArrayPrototypeSlice = Array.prototype.slice; var defaultMaxListeners = 10; // EventEmitter must be a standard function because some old code will do weird tricks like `EventEmitter.apply(this)`. -function EventEmitter(opts) { +const EventEmitter = function EventEmitter(opts) { if (this._events === undefined || this._events === this.__proto__._events) { this._events = { __proto__: null }; this._eventsCount = 0; @@ -27,8 +25,9 @@ function EventEmitter(opts) { if ((this[kCapture] = opts?.captureRejections ? Boolean(opts?.captureRejections) : EventEmitterPrototype[kCapture])) { this.emit = emitWithRejectionCapture; } -} -const EventEmitterPrototype = EventEmitter.prototype; +}; +const EventEmitterPrototype = (EventEmitter.prototype = {}); + EventEmitterPrototype._events = undefined; EventEmitterPrototype._eventsCount = 0; EventEmitterPrototype._maxListeners = undefined; @@ -108,7 +107,7 @@ const emitWithRejectionCapture = function emit(type, ...args) { if (handlers === undefined) return false; for (var handler of [...handlers]) { var result = handler.apply(this, args); - if (result !== undefined && isPromise(result)) { + if (result !== undefined && $isPromise(result)) { addCatch(this, result, type, args); } } @@ -308,13 +307,11 @@ function once(emitter, type, options) { } }); } -EventEmitter.once = once; function on(emitter, type, options) { var { signal, close, highWatermark = Number.MAX_SAFE_INTEGER, lowWatermark = 1 } = options || {}; throwNotImplemented("events.on", 2679); } -EventEmitter.on = on; function getEventListeners(emitter, type) { if (emitter instanceof EventTarget) { @@ -322,7 +319,6 @@ function getEventListeners(emitter, type) { } return emitter.listeners(type); } -EventEmitter.getEventListeners = getEventListeners; function setMaxListeners(n, ...eventTargets) { validateNumber(n, "setMaxListeners", 0); @@ -335,57 +331,10 @@ function setMaxListeners(n, ...eventTargets) { defaultMaxListeners = n; } } -EventEmitter.setMaxListeners = setMaxListeners; function listenerCount(emitter, type) { return emitter.listenerCount(type); } -EventEmitter.listenerCount = listenerCount; - -EventEmitter.EventEmitter = EventEmitter; -EventEmitter.usingDomains = false; -EventEmitter.captureRejectionSymbol = captureRejectionSymbol; -ObjectDefineProperty(EventEmitter, "captureRejections", { - __proto__: null, - get() { - return EventEmitterPrototype[kCapture]; - }, - set(value) { - validateBoolean(value, "EventEmitter.captureRejections"); - - EventEmitterPrototype[kCapture] = value; - }, - enumerable: true, -}); -EventEmitter.errorMonitor = kErrorMonitor; -Object.defineProperties(EventEmitter, { - defaultMaxListeners: { - enumerable: true, - get: () => { - return defaultMaxListeners; - }, - set: arg => { - validateNumber(arg, "defaultMaxListeners", 0); - defaultMaxListeners = arg; - }, - }, - kMaxEventTargetListeners: { - __proto__: null, - value: kMaxEventTargetListeners, - enumerable: false, - configurable: false, - writable: false, - }, - kMaxEventTargetListenersWarned: { - __proto__: null, - value: kMaxEventTargetListenersWarned, - enumerable: false, - configurable: false, - writable: false, - }, -}); -EventEmitter.init = EventEmitter; -EventEmitter[Symbol.for("CommonJS")] = 0; function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) { if (typeof emitter.removeListener === "function") { @@ -460,7 +409,9 @@ class EventEmitterAsyncResource extends EventEmitter { asyncResource; constructor(options) { - if (!AsyncResource) AsyncResource = import.meta.require("async_hooks").AsyncResource; + if (!AsyncResource) { + AsyncResource = require("node:async_hooks").AsyncResource; + } var { captureRejections = false, triggerAsyncId, name = new.target.name, requireManualDestroy } = options || {}; super({ captureRejections }); this.triggerAsyncId = triggerAsyncId ?? 0; @@ -476,19 +427,55 @@ class EventEmitterAsyncResource extends EventEmitter { } } -const usingDomains = false; -// EventEmitter[Symbol.for("CommonJS")] = 0; -Object.assign(EventEmitter, { once, on, getEventListeners, setMaxListeners, listenerCount, EventEmitterAsyncResource }); -export { - EventEmitter, - captureRejectionSymbol, - kErrorMonitor as errorMonitor, - getEventListeners, - listenerCount, - on, +Object.defineProperties(EventEmitter, { + captureRejections: { + get() { + return EventEmitterPrototype[kCapture]; + }, + set(value) { + validateBoolean(value, "EventEmitter.captureRejections"); + + EventEmitterPrototype[kCapture] = value; + }, + enumerable: true, + }, + defaultMaxListeners: { + enumerable: true, + get: () => { + return defaultMaxListeners; + }, + set: arg => { + validateNumber(arg, "defaultMaxListeners", 0); + defaultMaxListeners = arg; + }, + }, + kMaxEventTargetListeners: { + value: kMaxEventTargetListeners, + enumerable: false, + configurable: false, + writable: false, + }, + kMaxEventTargetListenersWarned: { + value: kMaxEventTargetListenersWarned, + enumerable: false, + configurable: false, + writable: false, + }, +}); +Object.assign(EventEmitter, { once, + on, + getEventListeners, + // getMaxListeners, setMaxListeners, - usingDomains, + EventEmitter, + usingDomains: false, + captureRejectionSymbol, EventEmitterAsyncResource, -}; + errorMonitor: kErrorMonitor, + setMaxListeners, + init: EventEmitter, + listenerCount, +}); + export default EventEmitter; diff --git a/src/js/node/fs.js b/src/js/node/fs.js index 5e72d6e273fdbe..27f1a7b4c9080c 100644 --- a/src/js/node/fs.js +++ b/src/js/node/fs.js @@ -1,17 +1,11 @@ -export var ReadStream; -export var WriteStream; - -import { EventEmitter } from "node:events"; - // Hardcoded module "node:fs" -var { direct, isPromise, isCallable } = $lazy("primordials"); -import promises from "node:fs/promises"; -export { default as promises } from "node:fs/promises"; -import * as Stream from "node:stream"; +var ReadStream; +var WriteStream; +const EventEmitter = require("node:events"); +const promises = require("node:fs/promises"); +const Stream = require("node:stream"); var fs = Bun.fs(); -var debug = process.env.DEBUG ? console.log : () => {}; - class FSWatcher extends EventEmitter { #watcher; #listener; @@ -68,7 +62,8 @@ class FSWatcher extends EventEmitter { this.#watcher?.unref(); } } -export var access = function access(...args) { + +var access = function access(...args) { callbackify(fs.accessSync, args); }, appendFile = function appendFile(...args) { @@ -122,9 +117,6 @@ export var access = function access(...args) { link = function link(...args) { callbackify(fs.linkSync, args); }, - lstat = function lstat(...args) { - callbackify(fs.lstatSync, args); - }, mkdir = function mkdir(...args) { callbackify(fs.mkdirSync, args); }, @@ -141,10 +133,22 @@ export var access = function access(...args) { callbackify(fs.writeSync, args); }, readdir = function readdir(...args) { - callbackify(fs.readdirSync, args); + const callback = args[args.length - 1]; + if (typeof callback !== "function") { + // TODO: set code + throw new TypeError("Callback must be a function"); + } + + fs.readdir(...args).then(result => callback(null, result), callback); }, readFile = function readFile(...args) { - callbackify(fs.readFileSync, args); + const callback = args[args.length - 1]; + if (typeof callback !== "function") { + // TODO: set code + throw new TypeError("Callback must be a function"); + } + + fs.readFile(...args).then(result => callback(null, result), callback); }, writeFile = function writeFile(...args) { callbackify(fs.writeFileSync, args); @@ -158,8 +162,23 @@ export var access = function access(...args) { rename = function rename(...args) { callbackify(fs.renameSync, args); }, + lstat = function lstat(...args) { + const callback = args[args.length - 1]; + if (typeof callback !== "function") { + // TODO: set code + throw new TypeError("Callback must be a function"); + } + + fs.lstat(...args).then(result => callback(null, result), callback); + }, stat = function stat(...args) { - callbackify(fs.statSync, args); + const callback = args[args.length - 1]; + if (typeof callback !== "function") { + // TODO: set code + throw new TypeError("Callback must be a function"); + } + + fs.stat(...args).then(result => callback(null, result), callback); }, symlink = function symlink(...args) { callbackify(fs.symlinkSync, args); @@ -326,18 +345,15 @@ ReadStream = (function (InternalReadStream) { value: "ReadStream", enumerable: false, }); - - return Object.defineProperty( - function ReadStream(path, options) { - return new InternalReadStream(path, options); - }, - Symbol.hasInstance, - { - value(instance) { - return instance instanceof InternalReadStream; - }, + function ReadStream(path, options) { + return new InternalReadStream(path, options); + } + ReadStream.prototype = InternalReadStream.prototype; + return Object.defineProperty(ReadStream, Symbol.hasInstance, { + value(instance) { + return instance instanceof InternalReadStream; }, - ); + }); })( class ReadStream extends Stream._getNativeReadableStreamPrototype(2, Stream.Readable) { constructor(pathOrFd, options = defaultReadStreamOptions) { @@ -395,9 +411,9 @@ ReadStream = (function (InternalReadStream) { // Get the stream controller // We need the pointer to the underlying stream controller for the NativeReadable var stream = fileRef.stream(); - var native = direct(stream); + var native = $direct(stream); if (!native) { - debug("no native readable stream"); + $debug("no native readable stream"); throw new Error("no native readable stream"); } var { stream: ptr } = native; @@ -516,15 +532,15 @@ ReadStream = (function (InternalReadStream) { chunk = chunk.slice(-n); var [_, ...rest] = arguments; this.pos = this.bytesRead; - if (this.end && this.bytesRead >= this.end) { - chunk = chunk.slice(0, this.end - this.start); + if (this.end !== undefined && this.bytesRead > this.end) { + chunk = chunk.slice(0, this.end - this.start + 1); } return super.push(chunk, ...rest); } var end = this.end; // This is multi-chunk read case where we go passed the end of the what we want to read in the last chunk - if (end && this.bytesRead >= end) { - chunk = chunk.slice(0, end - currPos); + if (end !== undefined && this.bytesRead > end) { + chunk = chunk.slice(0, end - currPos + 1); var [_, ...rest] = arguments; this.pos = this.bytesRead; return super.push(chunk, ...rest); @@ -549,7 +565,7 @@ ReadStream = (function (InternalReadStream) { ? Math.min(end - pos + 1, n) // takes smaller of length of the rest of the file to read minus the cursor position, or the highwatermark : Math.min(end - bytesRead + 1, n); // takes the smaller of the length of the rest of the file from the bytes that we have marked read, or the highwatermark - debug("n @ fs.ReadStream.#internalRead, after clamp", n); + $debug("n @ fs.ReadStream.#internalRead, after clamp", n); // If n is 0 or less, then we read all the file, push null to stream, ending it if (n <= 0) { @@ -569,16 +585,16 @@ ReadStream = (function (InternalReadStream) { if (this.#fileSize > 0 && n > this.#fileSize) { n = this.#fileSize + 1; } - debug("fileSize", this.#fileSize); + $debug("fileSize", this.#fileSize); } // At this point, we know the file size and how much we want to read of the file this[kIoDone] = false; var res = super._read(n); - debug("res -- undefined? why?", res); - if (isPromise(res)) { + $debug("res -- undefined? why?", res); + if ($isPromise(res)) { var then = res?.then; - if (then && isCallable(then)) { + if (then && $isCallable(then)) { then( () => { this[kIoDone] = true; @@ -647,7 +663,7 @@ ReadStream = (function (InternalReadStream) { }, ); -export function createReadStream(path, options) { +function createReadStream(path, options) { return new ReadStream(path, options); } @@ -674,17 +690,15 @@ WriteStream = (function (InternalWriteStream) { enumerable: false, }); - return Object.defineProperty( - function WriteStream(path, options) { - return new InternalWriteStream(path, options); - }, - Symbol.hasInstance, - { - value(instance) { - return instance instanceof InternalWriteStream; - }, + function WriteStream(path, options) { + return new InternalWriteStream(path, options); + } + WriteStream.prototype = InternalWriteStream.prototype; + return Object.defineProperty(WriteStream, Symbol.hasInstance, { + value(instance) { + return instance instanceof InternalWriteStream; }, - ); + }); })( class WriteStream extends Stream.NativeWritable { constructor(path, options = defaultWriteStreamOptions) { @@ -969,7 +983,7 @@ WriteStream = (function (InternalWriteStream) { }, ); -export function createWriteStream(path, options) { +function createWriteStream(path, options) { // const WriteStream = getLazyWriteStream(); return new WriteStream(path, options); } @@ -1019,7 +1033,6 @@ realpath.native = realpath; realpathSync.native = realpathSync; export default { - [Symbol.for("CommonJS")]: 0, access, accessSync, appendFile, @@ -1117,5 +1130,3 @@ export default { // return getLazyReadStream(); // }, }; - -export { constants } from "node:fs/promises"; diff --git a/src/js/node/fs.promises.ts b/src/js/node/fs.promises.ts index 12278ef5333275..6a1c42ecd6d0ab 100644 --- a/src/js/node/fs.promises.ts +++ b/src/js/node/fs.promises.ts @@ -1,7 +1,5 @@ // Hardcoded module "node:fs/promises" - -// Note: `constants` is injected into the top of this file -declare var constants: typeof import("node:fs/promises").constants; +const constants = $processBindingConstants.fs; var fs = Bun.fs(); @@ -11,35 +9,14 @@ var fs = Bun.fs(); const notrace = "::bunternal::"; var promisify = { [notrace]: fsFunction => { - // TODO: remove variadic arguments - // we can use new Function() here instead - // based on fsFucntion.length - var func = { - [notrace]: function (resolve, reject, args) { - var result; - try { - result = fsFunction.apply(fs, args); - args = undefined; - } catch (err) { - args = undefined; - reject(err); - return; - } - - resolve(result); - }, - }[notrace]; - return async function (...args) { - // we await it so that the stack is captured - return await new Promise((resolve, reject) => { - process.nextTick(func, resolve, reject, args); - }); + await 1; + return fsFunction.apply(fs, args); }; }, }[notrace]; -export function watch( +function watch( filename: string | Buffer | URL, options: { encoding?: BufferEncoding; persistent?: boolean; recursive?: boolean; signal?: AbortSignal } = {}, ) { @@ -47,7 +24,7 @@ export function watch( eventType: string; filename: string | Buffer | undefined; }; - const events: Array = []; + if (filename instanceof URL) { throw new TypeError("Watch URLs are not supported yet"); } else if (Buffer.isBuffer(filename)) { @@ -59,72 +36,97 @@ export function watch( if (typeof options === "string") { options = { encoding: options }; } - fs.watch(filename, options || {}, (eventType: string, filename: string | Buffer | undefined) => { - events.push({ eventType, filename }); + const queue = $createFIFO(); + + const watcher = fs.watch(filename, options || {}, (eventType: string, filename: string | Buffer | undefined) => { + queue.push({ eventType, filename }); if (nextEventResolve) { const resolve = nextEventResolve; nextEventResolve = null; resolve(); } }); + return { - async *[Symbol.asyncIterator]() { + [Symbol.asyncIterator]() { let closed = false; - while (!closed) { - while (events.length) { - let event = events.shift() as Event; - if (event.eventType === "close") { - closed = true; - break; + return { + async next() { + while (!closed) { + let event: Event; + while ((event = queue.shift() as Event)) { + if (event.eventType === "close") { + closed = true; + return { value: undefined, done: true }; + } + if (event.eventType === "error") { + closed = true; + throw event.filename; + } + return { value: event, done: false }; + } + const { promise, resolve } = Promise.withResolvers(); + nextEventResolve = resolve; + await promise; } - if (event.eventType === "error") { + return { value: undefined, done: true }; + }, + + return() { + if (!closed) { + watcher.close(); closed = true; - throw event.filename; + if (nextEventResolve) { + const resolve = nextEventResolve; + nextEventResolve = null; + resolve(); + } } - yield event; - } - await new Promise((resolve: Function) => (nextEventResolve = resolve)); - } + return { value: undefined, done: true }; + }, + }; }, }; } -export var access = promisify(fs.accessSync), - appendFile = promisify(fs.appendFileSync), - close = promisify(fs.closeSync), - copyFile = promisify(fs.copyFileSync), - exists = promisify(fs.existsSync), - chown = promisify(fs.chownSync), - chmod = promisify(fs.chmodSync), - fchmod = promisify(fs.fchmodSync), - fchown = promisify(fs.fchownSync), - fstat = promisify(fs.fstatSync), - fsync = promisify(fs.fsyncSync), - ftruncate = promisify(fs.ftruncateSync), - futimes = promisify(fs.futimesSync), - lchmod = promisify(fs.lchmodSync), - lchown = promisify(fs.lchownSync), - link = promisify(fs.linkSync), - lstat = promisify(fs.lstatSync), - mkdir = promisify(fs.mkdirSync), - mkdtemp = promisify(fs.mkdtempSync), - open = promisify(fs.openSync), - read = promisify(fs.readSync), - write = promisify(fs.writeSync), - readdir = promisify(fs.readdirSync), - readFile = promisify(fs.readFileSync), - writeFile = promisify(fs.writeFileSync), - readlink = promisify(fs.readlinkSync), - realpath = promisify(fs.realpathSync), - rename = promisify(fs.renameSync), - stat = promisify(fs.statSync), - symlink = promisify(fs.symlinkSync), - truncate = promisify(fs.truncateSync), - unlink = promisify(fs.unlinkSync), - utimes = promisify(fs.utimesSync), - lutimes = promisify(fs.lutimesSync), - rm = promisify(fs.rmSync), - rmdir = promisify(fs.rmdirSync), - writev = (fd, buffers, position) => { + +export default { + access: promisify(fs.accessSync), + appendFile: promisify(fs.appendFileSync), + close: promisify(fs.closeSync), + copyFile: promisify(fs.copyFileSync), + exists: promisify(fs.existsSync), + chown: promisify(fs.chownSync), + chmod: promisify(fs.chmodSync), + fchmod: promisify(fs.fchmodSync), + fchown: promisify(fs.fchownSync), + fstat: promisify(fs.fstatSync), + fsync: promisify(fs.fsyncSync), + ftruncate: promisify(fs.ftruncateSync), + futimes: promisify(fs.futimesSync), + lchmod: promisify(fs.lchmodSync), + lchown: promisify(fs.lchownSync), + link: promisify(fs.linkSync), + lstat: fs.lstat.bind(fs), + mkdir: promisify(fs.mkdirSync), + mkdtemp: promisify(fs.mkdtempSync), + open: promisify(fs.openSync), + read: promisify(fs.readSync), + write: promisify(fs.writeSync), + readdir: fs.readdir.bind(fs), + readFile: fs.readFile.bind(fs), + writeFile: promisify(fs.writeFileSync), + readlink: promisify(fs.readlinkSync), + realpath: promisify(fs.realpathSync), + rename: promisify(fs.renameSync), + stat: fs.stat.bind(fs), + symlink: promisify(fs.symlinkSync), + truncate: promisify(fs.truncateSync), + unlink: promisify(fs.unlinkSync), + utimes: promisify(fs.utimesSync), + lutimes: promisify(fs.lutimesSync), + rm: promisify(fs.rmSync), + rmdir: promisify(fs.rmdirSync), + writev: (fd, buffers, position) => { return new Promise((resolve, reject) => { try { var bytesWritten = fs.writevSync(fd, buffers, position); @@ -139,7 +141,7 @@ export var access = promisify(fs.accessSync), }); }); }, - readv = (fd, buffers, position) => { + readv: (fd, buffers, position) => { return new Promise((resolve, reject) => { try { var bytesRead = fs.readvSync(fd, buffers, position); @@ -153,48 +155,7 @@ export var access = promisify(fs.accessSync), buffers, }); }); - }; - -export default { - access, - appendFile, - close, - copyFile, - exists, - chown, - chmod, - fchmod, - fchown, - fstat, - fsync, - ftruncate, - futimes, - lchmod, - lchown, - link, - lstat, - mkdir, - mkdtemp, - open, - read, - write, - readdir, - readFile, - writeFile, - readlink, - realpath, - rename, - stat, - symlink, - truncate, - unlink, - utimes, - lutimes, - rm, - rmdir, - watch, - writev, - readv, + }, constants, - [Symbol.for("CommonJS")]: 0, + watch, }; diff --git a/src/js/node/http.ts b/src/js/node/http.ts index 2eb5231d58ae49..4d56a34cf6f0f6 100644 --- a/src/js/node/http.ts +++ b/src/js/node/http.ts @@ -1,7 +1,7 @@ // Hardcoded module "node:http" -import { EventEmitter } from "node:events"; -import { Readable, Writable, Duplex } from "node:stream"; -import { isTypedArray } from "util/types"; +const EventEmitter = require("node:events"); +const { isTypedArray } = require("node:util/types"); +const { Duplex, Readable, Writable } = require("node:stream"); const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/; /** @@ -14,14 +14,14 @@ function checkInvalidHeaderChar(val: string) { return RegExpPrototypeExec.call(headerCharRegex, val) !== null; } -export const validateHeaderName = (name, label) => { +const validateHeaderName = (name, label) => { if (typeof name !== "string" || !name || !checkIsHttpToken(name)) { // throw new ERR_INVALID_HTTP_TOKEN(label || "Header name", name); throw new Error("ERR_INVALID_HTTP_TOKEN"); } }; -export const validateHeaderValue = (name, value) => { +const validateHeaderValue = (name, value) => { if (value === undefined) { // throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); throw new Error("ERR_HTTP_INVALID_HEADER_VALUE"); @@ -57,16 +57,11 @@ function isIPv6(input) { // Importing from node:url is unnecessary const { URL } = globalThis; -const { newArrayWithSize, String, Object, Array } = $lazy("primordials"); - const globalReportError = globalThis.reportError; const setTimeout = globalThis.setTimeout; const fetch = Bun.fetch; const nop = () => {}; -const __DEBUG__ = process.env.__DEBUG__; -const debug = __DEBUG__ ? (...args) => console.log("node:http", ...args) : nop; - const kEmptyObject = Object.freeze(Object.create(null)); const kOutHeaders = Symbol.for("kOutHeaders"); const kEndCalled = Symbol.for("kEndCalled"); @@ -218,11 +213,11 @@ var FakeSocket = class Socket extends Duplex { _write(chunk, encoding, callback) {} }; -export function createServer(options, callback) { +function createServer(options, callback) { return new Server(options, callback); } -export class Agent extends EventEmitter { +class Agent extends EventEmitter { defaultPort = 80; protocol = "http:"; options; @@ -270,7 +265,7 @@ export class Agent extends EventEmitter { } createConnection() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createConnection is a no-op, returns fake socket"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createConnection is a no-op, returns fake socket"); return (this.#fakeSocket ??= new FakeSocket()); } @@ -287,30 +282,30 @@ export class Agent extends EventEmitter { } addRequest() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.addRequest is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.addRequest is a no-op"); } createSocket(req, options, cb) { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createSocket returns fake socket"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createSocket returns fake socket"); cb(null, (this.#fakeSocket ??= new FakeSocket())); } removeSocket() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.removeSocket is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.removeSocket is a no-op"); } keepSocketAlive() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.keepSocketAlive is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.keepSocketAlive is a no-op"); return true; } reuseSocket() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.reuseSocket is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.reuseSocket is a no-op"); } destroy() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.destroy is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.destroy is a no-op"); } } function emitListeningNextTick(self, onListen, err, hostname, port) { @@ -331,7 +326,7 @@ function emitListeningNextTick(self, onListen, err, hostname, port) { } } -export class Server extends EventEmitter { +class Server extends EventEmitter { #server; #options; #tls; @@ -558,7 +553,7 @@ export class Server extends EventEmitter { function assignHeaders(object, req) { var headers = req.headers.toJSON(); - const rawHeaders = newArrayWithSize(req.headers.count * 2); + const rawHeaders = $newArrayWithSize(req.headers.count * 2); var i = 0; for (const key in headers) { rawHeaders[i++] = key; @@ -577,7 +572,7 @@ function getDefaultHTTPSAgent() { return (_defaultHTTPSAgent ??= new Agent({ defaultPort: 443, protocol: "https:" })); } -export class IncomingMessage extends Readable { +class IncomingMessage extends Readable { method: string; complete: boolean; @@ -796,7 +791,7 @@ function write_(msg, chunk, encoding, callback, fromEnd) { } if (!msg._hasBody) { - debug("This type of response MUST NOT have a body. " + "Ignoring write() calls."); + $debug("This type of response MUST NOT have a body. " + "Ignoring write() calls."); process.nextTick(callback); return true; } @@ -809,7 +804,7 @@ function write_(msg, chunk, encoding, callback, fromEnd) { return true; } -export class OutgoingMessage extends Writable { +class OutgoingMessage extends Writable { #headers; headersSent = false; sendDate = true; @@ -958,7 +953,7 @@ export class OutgoingMessage extends Writable { } let OriginalWriteHeadFn, OriginalImplicitHeadFn; -export class ServerResponse extends Writable { +class ServerResponse extends Writable { declare _writableState: any; constructor({ req, reply }) { @@ -1196,7 +1191,7 @@ export class ServerResponse extends Writable { OriginalWriteHeadFn = ServerResponse.prototype.writeHead; OriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader; -export class ClientRequest extends OutgoingMessage { +class ClientRequest extends OutgoingMessage { #timeout; #res: IncomingMessage | null = null; #upgradeOrConnect = false; @@ -1214,7 +1209,7 @@ export class ClientRequest extends OutgoingMessage { #path; #socketPath; - #body: string | null = null; + #bodyChunks: Buffer[] | null = null; #fetchRequest; #signal: AbortSignal | null = null; [kAbortController]: AbortController | null = null; @@ -1243,24 +1238,22 @@ export class ClientRequest extends OutgoingMessage { } _write(chunk, encoding, callback) { - var body = this.#body; - if (!body) { - this.#body = chunk; + if (!this.#bodyChunks) { + this.#bodyChunks = [chunk]; callback(); return; } - this.#body = body + chunk; + this.#bodyChunks.push(chunk); callback(); } _writev(chunks, callback) { - var body = this.#body; - if (!body) { - this.#body = chunks.join(); + if (!this.#bodyChunks) { + this.#bodyChunks = chunks; callback(); return; } - this.#body = body + chunks.join(); + this.#bodyChunks.push(...chunks); callback(); } @@ -1275,7 +1268,7 @@ export class ClientRequest extends OutgoingMessage { } var method = this.#method, - body = this.#body; + body = this.#bodyChunks?.length === 1 ? this.#bodyChunks[0] : Buffer.concat(this.#bodyChunks || []); try { this.#fetchRequest = fetch( @@ -1285,7 +1278,7 @@ export class ClientRequest extends OutgoingMessage { headers: this.getHeaders(), body: body && method !== "GET" && method !== "HEAD" && method !== "OPTIONS" ? body : undefined, redirect: "manual", - verbose: Boolean(__DEBUG__), + verbose: !!$debug, signal: this[kAbortController].signal, // Timeouts are handled via this.setTimeout. @@ -1300,7 +1293,7 @@ export class ClientRequest extends OutgoingMessage { this.emit("response", res); }) .catch(err => { - if (__DEBUG__) globalReportError(err); + if (!!$debug) globalReportError(err); this.emit("error", err); }) .finally(() => { @@ -1308,7 +1301,7 @@ export class ClientRequest extends OutgoingMessage { this[kClearTimeout](); }); } catch (err) { - if (__DEBUG__) globalReportError(err); + if (!!$debug) globalReportError(err); this.emit("error", err); } finally { callback(); @@ -1388,7 +1381,7 @@ export class ClientRequest extends OutgoingMessage { if (options.path) { const path = String(options.path); if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null) { - debug('Path contains unescaped characters: "%s"', path); + $debug('Path contains unescaped characters: "%s"', path); throw new Error("Path contains unescaped characters"); // throw new ERR_UNESCAPED_CHARACTERS("Request path"); } @@ -1467,8 +1460,7 @@ export class ClientRequest extends OutgoingMessage { this.once("response", cb); } - __DEBUG__ && - debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`); + $debug(`new ClientRequest: ${this.#method} ${this.#protocol}//${this.#host}:${this.#port}${this.#path}`); // if ( // method === "GET" || @@ -1556,12 +1548,13 @@ export class ClientRequest extends OutgoingMessage { } setSocketKeepAlive(enable = true, initialDelay = 0) { - __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); } setNoDelay(noDelay = true) { - __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setNoDelay is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setNoDelay is a no-op"); } + [kClearTimeout]() { if (this.#timeoutTimer) { clearTimeout(this.#timeoutTimer); @@ -1666,7 +1659,7 @@ function checkIsHttpToken(val) { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -export const METHODS = [ +const METHODS = [ "ACL", "BIND", "CHECKOUT", @@ -1703,7 +1696,7 @@ export const METHODS = [ "UNSUBSCRIBE", ]; -export const STATUS_CODES = { +const STATUS_CODES = { 100: "Continue", 101: "Switching Protocols", 102: "Processing", @@ -1863,7 +1856,7 @@ function _writeHead(statusCode, reason, obj, response) { * @param {Function} [cb] * @returns {ClientRequest} */ -export function request(url, options, cb) { +function request(url, options, cb) { return new ClientRequest(url, options, cb); } @@ -1874,14 +1867,14 @@ export function request(url, options, cb) { * @param {Function} [cb] * @returns {ClientRequest} */ -export function get(url, options, cb) { +function get(url, options, cb) { const req = request(url, options, cb); req.end(); return req; } -export var globalAgent = new Agent(); -var defaultObject = { +var globalAgent = new Agent(); +export default { Agent, Server, METHODS, @@ -1895,12 +1888,9 @@ var defaultObject = { validateHeaderName, validateHeaderValue, setMaxIdleHTTPParsers(max) { - debug(`${NODE_HTTP_WARNING}\n`, "setMaxIdleHTTPParsers() is a no-op"); + $debug(`${NODE_HTTP_WARNING}\n`, "setMaxIdleHTTPParsers() is a no-op"); }, globalAgent, ClientRequest, OutgoingMessage, - [Symbol.for("CommonJS")]: 0, }; - -export default defaultObject; diff --git a/src/js/node/http2.ts b/src/js/node/http2.ts index b19e38a6d7bb13..fce1a8c7286f08 100644 --- a/src/js/node/http2.ts +++ b/src/js/node/http2.ts @@ -1,6 +1,6 @@ // Hardcoded module "node:http2" // This is a stub! None of this is actually implemented yet. -import { hideFromStack, throwNotImplemented } from "../shared"; +const { hideFromStack, throwNotImplemented } = require("$shared"); function connect() { throwNotImplemented("node:http2 connect", 887); @@ -280,7 +280,7 @@ function Http2ServerResponse() { throwNotImplemented("node:http2 Http2ServerResponse", 887); } -const defaultObject = { +export default { constants, createServer, createSecureServer, @@ -290,21 +290,6 @@ const defaultObject = { sensitiveHeaders, Http2ServerRequest, Http2ServerResponse, - [Symbol.for("CommonJS")]: 0, - connect, -}; - -export { - constants, - createServer, - createSecureServer, - getDefaultSettings, - getPackedSettings, - getUnpackedSettings, - sensitiveHeaders, - Http2ServerRequest, - Http2ServerResponse, - defaultObject as default, connect, }; diff --git a/src/js/node/https.ts b/src/js/node/https.ts index 08eb89a01a03cd..d75fb3132ea7b9 100644 --- a/src/js/node/https.ts +++ b/src/js/node/https.ts @@ -1,19 +1,5 @@ // Hardcoded module "node:https" -import * as http from "node:http"; - -var { - Agent, - Server, - METHODS, - STATUS_CODES, - createServer, - ServerResponse, - IncomingMessage, - maxHeaderSize, - validateHeaderName, - validateHeaderValue, - globalAgent, -} = http; +const http = require("node:http"); function request(input, options, cb) { if (input && typeof input === "object" && !(input instanceof URL)) { @@ -31,35 +17,8 @@ function get(input, options, cb) { return req; } -var defaultExport = { - Agent, - Server, - METHODS, - STATUS_CODES, - createServer, - ServerResponse, - IncomingMessage, - request, +export default { + ...http, get, - maxHeaderSize, - validateHeaderName, - validateHeaderValue, - globalAgent, -}; - -export { - Agent, - Server, - METHODS, - STATUS_CODES, - createServer, - ServerResponse, - IncomingMessage, request, - get, - maxHeaderSize, - validateHeaderName, - validateHeaderValue, - globalAgent, }; -export default defaultExport; diff --git a/src/js/node/inspector.ts b/src/js/node/inspector.ts index f81084274ed6c3..1fd7316f749362 100644 --- a/src/js/node/inspector.ts +++ b/src/js/node/inspector.ts @@ -1,7 +1,7 @@ // Hardcoded module "node:inspector" and "node:inspector/promises" // This is a stub! None of this is actually implemented yet. -import { hideFromStack, throwNotImplemented } from "../shared"; -import EventEmitter from "node:events"; +const { hideFromStack, throwNotImplemented } = require("$shared"); +const EventEmitter = require("node:events"); function open() { throwNotImplemented("node:inspector open", 2445); @@ -33,15 +33,13 @@ const console = { }, }; -var defaultObject = { +export default { console, open, close, url, waitForDebugger, Session, - [Symbol.for("CommonJS")]: 0, }; -export { console, open, close, url, waitForDebugger, Session, defaultObject as default }; hideFromStack(open, close, url, waitForDebugger, Session.prototype.constructor); diff --git a/src/js/node/net.js b/src/js/node/net.js index 5501d327b64beb..0513f44d3f1126 100644 --- a/src/js/node/net.js +++ b/src/js/node/net.js @@ -19,8 +19,8 @@ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -import { Duplex } from "node:stream"; -import { EventEmitter } from "node:events"; +const { Duplex } = require("node:stream"); +const EventEmitter = require("node:events"); // IPv4 Segment const v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; @@ -56,7 +56,6 @@ function isIP(s) { return 0; } -const { Bun, createFIFO, Object } = $lazy("primordials"); const { connect: bunConnect } = Bun; var { setTimeout } = globalThis; @@ -294,7 +293,7 @@ const Socket = (function (InternalSocket) { #closed = false; connecting = false; localAddress = "127.0.0.1"; - #readQueue = createFIFO(); + #readQueue = $createFIFO(); remotePort; [bunSocketInternal] = null; [bunTLSConnectOptions] = null; @@ -891,8 +890,5 @@ export default { isIPv4, isIPv6, Socket, - [Symbol.for("CommonJS")]: 0, [Symbol.for("::bunternal::")]: SocketClass, }; - -export { createServer, Server, createConnection, connect, isIP, isIPv4, isIPv6, Socket }; diff --git a/src/js/node/os.js b/src/js/node/os.js deleted file mode 100644 index 2ff98beea16688..00000000000000 --- a/src/js/node/os.js +++ /dev/null @@ -1,73 +0,0 @@ -// Hardcoded module "node:os" - -export var tmpdir = function () { - var { Bun } = $lazy("primordials"); - var env = Bun.env; - - tmpdir = function () { - var path = env["TMPDIR"] || env["TMP"] || env["TEMP"] || "/tmp"; - const length = path.length; - if (length > 1 && path[length - 1] === "/") path = path.slice(0, -1); - return path; - }; - - return tmpdir(); -}; - -function bound(obj) { - return { - arch: obj.arch.bind(obj), - cpus: obj.cpus.bind(obj), - endianness: obj.endianness.bind(obj), - freemem: obj.freemem.bind(obj), - getPriority: obj.getPriority.bind(obj), - homedir: obj.homedir.bind(obj), - hostname: obj.hostname.bind(obj), - loadavg: obj.loadavg.bind(obj), - networkInterfaces: obj.networkInterfaces.bind(obj), - platform: obj.platform.bind(obj), - release: obj.release.bind(obj), - setPriority: obj.setPriority.bind(obj), - get tmpdir() { - return tmpdir; - }, - totalmem: obj.totalmem.bind(obj), - type: obj.type.bind(obj), - uptime: obj.uptime.bind(obj), - userInfo: obj.userInfo.bind(obj), - version: obj.version.bind(obj), - machine: obj.machine.bind(obj), - devNull: obj.devNull, - EOL: obj.EOL, - constants: obj.constants, - [Symbol.for("CommonJS")]: 0, - }; -} - -var os = bound(Bun._Os()); - -export var { - arch, - cpus, - endianness, - freemem, - getPriority, - homedir, - hostname, - loadavg, - networkInterfaces, - platform, - release, - setPriority, - totalmem, - type, - uptime, - userInfo, - version, - machine, - devNull, - EOL, - constants, -} = os; - -export default os; diff --git a/src/js/node/os.ts b/src/js/node/os.ts new file mode 100644 index 00000000000000..c5b202444f8af0 --- /dev/null +++ b/src/js/node/os.ts @@ -0,0 +1,107 @@ +// Hardcoded module "node:os" + +var tmpdir = function () { + var env = Bun.env; + + tmpdir = function () { + var path = env["TMPDIR"] || env["TMP"] || env["TEMP"] || "/tmp"; + const length = path.length; + if (length > 1 && path[length - 1] === "/") path = path.slice(0, -1); + return path; + }; + + return tmpdir(); +}; + +// os.cpus() is super expensive +// Specifically: getting the CPU speed on Linux is very expensive +// Some packages like FastGlob only bother to read the length of the array +// so instead of actually populating the entire object +// we turn them into getters +function lazyCpus({ cpus }) { + return () => { + const array = new Array(navigator.hardwareConcurrency); + function populate() { + const results = cpus(); + const length = results.length; + array.length = length; + for (let i = 0; i < length; i++) { + array[i] = results[i]; + } + } + + for (let i = 0; i < array.length; i++) { + // This is technically still observable via + // Object.getOwnPropertyDescriptors(), but it should be okay. + const instance = { + get model() { + if (array[i] === instance) populate(); + return array[i].model; + }, + set model(value) { + if (array[i] === instance) populate(); + array[i].model = value; + }, + + get speed() { + if (array[i] === instance) populate(); + return array[i].speed; + }, + + set speed(value) { + if (array[i] === instance) populate(); + array[i].speed = value; + }, + + get times() { + if (array[i] === instance) populate(); + return array[i].times; + }, + set times(value) { + if (array[i] === instance) populate(); + array[i].times = value; + }, + + toJSON() { + if (array[i] === instance) populate(); + return array[i]; + }, + }; + + array[i] = instance; + } + + return array; + }; +} + +function bound(obj) { + return { + arch: obj.arch.bind(obj), + cpus: lazyCpus(obj), + endianness: obj.endianness.bind(obj), + freemem: obj.freemem.bind(obj), + getPriority: obj.getPriority.bind(obj), + homedir: obj.homedir.bind(obj), + hostname: obj.hostname.bind(obj), + loadavg: obj.loadavg.bind(obj), + networkInterfaces: obj.networkInterfaces.bind(obj), + platform: obj.platform.bind(obj), + release: obj.release.bind(obj), + setPriority: obj.setPriority.bind(obj), + get tmpdir() { + return tmpdir; + }, + totalmem: obj.totalmem.bind(obj), + type: obj.type.bind(obj), + uptime: obj.uptime.bind(obj), + userInfo: obj.userInfo.bind(obj), + version: obj.version.bind(obj), + machine: obj.machine.bind(obj), + devNull: obj.devNull, + EOL: obj.EOL, + constants: $processBindingConstants.os, + }; +} + +export default bound(Bun._Os()); diff --git a/src/js/node/path.posix.ts b/src/js/node/path.posix.ts index e94da9cea44fdd..d4aeddd859fecc 100644 --- a/src/js/node/path.posix.ts +++ b/src/js/node/path.posix.ts @@ -1,37 +1,2 @@ // Hardcoded module "node:path/posix" -function bound(obj) { - return { - basename: obj.basename.bind(obj), - dirname: obj.dirname.bind(obj), - extname: obj.extname.bind(obj), - format: obj.format.bind(obj), - isAbsolute: obj.isAbsolute.bind(obj), - join: obj.join.bind(obj), - normalize: obj.normalize.bind(obj), - parse: obj.parse.bind(obj), - relative: obj.relative.bind(obj), - resolve: obj.resolve.bind(obj), - toNamespacedPath: obj.toNamespacedPath.bind(obj), - sep: obj.sep, - delimiter: obj.delimiter, - }; -} -var path = bound(Bun._Path(false)); -path[Symbol.for("CommonJS")] = 0; - -export var { - basename, - dirname, - extname, - format, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - toNamespacedPath, - sep, - delimiter, -} = path; -export default path; +export default require("node:path").posix; diff --git a/src/js/node/path.ts b/src/js/node/path.ts index 7c20d520b2592d..ba797774011ae0 100644 --- a/src/js/node/path.ts +++ b/src/js/node/path.ts @@ -1,49 +1,31 @@ // Hardcoded module "node:path" -export const createModule = obj => Object.assign(Object.create(null), obj); function bound(obj) { - var result = createModule({ - basename: obj.basename.bind(obj), + const toNamespacedPath = obj.toNamespacedPath.bind(obj); + const result = { + resolve: obj.resolve.bind(obj), + normalize: obj.normalize.bind(obj), + isAbsolute: obj.isAbsolute.bind(obj), + join: obj.join.bind(obj), + relative: obj.relative.bind(obj), + toNamespacedPath, dirname: obj.dirname.bind(obj), + basename: obj.basename.bind(obj), extname: obj.extname.bind(obj), format: obj.format.bind(obj), - isAbsolute: obj.isAbsolute.bind(obj), - join: obj.join.bind(obj), - normalize: obj.normalize.bind(obj), parse: obj.parse.bind(obj), - relative: obj.relative.bind(obj), - resolve: obj.resolve.bind(obj), - toNamespacedPath: obj.toNamespacedPath.bind(obj), sep: obj.sep, delimiter: obj.delimiter, - }); - result.default = result; + win32: undefined, + posix: undefined, + _makeLong: toNamespacedPath, + }; return result; } -var path = bound(Bun._Path()); - -export var posix = bound(Bun._Path(false)); -export var win32 = bound(Bun._Path(true)); -path.win32 = win32; -path.posix = posix; +const posix: any = bound(Bun._Path(false)); +const win32: any = bound(Bun._Path(true)); -export var { - basename, - dirname, - extname, - format, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - toNamespacedPath, - sep, - delimiter, - __esModule, -} = path; +posix.win32 = win32.win32 = win32; +posix.posix = win32.posix = posix; -path[Symbol.for("CommonJS")] = 0; -path.__esModule = true; -export default path; +export default process.platform === "win32" ? win32 : posix; diff --git a/src/js/node/path.win32.ts b/src/js/node/path.win32.ts index 1c8bda4baae3ff..a8a74fbb2378fc 100644 --- a/src/js/node/path.win32.ts +++ b/src/js/node/path.win32.ts @@ -1,36 +1,2 @@ // Hardcoded module "node:path/win32" -function bound(obj) { - return { - basename: obj.basename.bind(obj), - dirname: obj.dirname.bind(obj), - extname: obj.extname.bind(obj), - format: obj.format.bind(obj), - isAbsolute: obj.isAbsolute.bind(obj), - join: obj.join.bind(obj), - normalize: obj.normalize.bind(obj), - parse: obj.parse.bind(obj), - relative: obj.relative.bind(obj), - resolve: obj.resolve.bind(obj), - toNamespacedPath: obj.toNamespacedPath.bind(obj), - sep: obj.sep, - delimiter: obj.delimiter, - }; -} -var path = bound(Bun._Path(true)); - -export var { - basename, - dirname, - extname, - format, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - toNamespacedPath, - sep, - delimiter, -} = path; -export default path; +export default require("node:path").win32; diff --git a/src/js/node/perf_hooks.js b/src/js/node/perf_hooks.js deleted file mode 100644 index 592868ab5c6cc8..00000000000000 --- a/src/js/node/perf_hooks.js +++ /dev/null @@ -1,43 +0,0 @@ -// Hardcoded module "node:perf_hooks" -import { throwNotImplemented } from "../shared"; - -export var constants = { - NODE_PERFORMANCE_GC_MAJOR: 4, - NODE_PERFORMANCE_GC_MINOR: 1, - NODE_PERFORMANCE_GC_INCREMENTAL: 8, - NODE_PERFORMANCE_GC_WEAKCB: 16, - NODE_PERFORMANCE_GC_FLAGS_NO: 0, - NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: 2, - NODE_PERFORMANCE_GC_FLAGS_FORCED: 4, - NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: 8, - NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: 16, - NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: 32, - NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: 64, -}; - -export var performance = globalThis.performance; - -export class PerformanceObserver { - constructor() { - throwNotImplemented("PerformanceObserver"); - } -} - -export class PerformanceEntry { - constructor() { - throwNotImplemented("PerformanceEntry"); - } -} -export class PerformanceNodeTiming { - constructor() { - throw new Error("PerformanceNodeTiming is not supported in this environment."); - } -} - -export default { - performance, - constants, - PerformanceEntry, - PerformanceNodeTiming, - [Symbol.for("CommonJS")]: 0, -}; diff --git a/src/js/node/perf_hooks.ts b/src/js/node/perf_hooks.ts new file mode 100644 index 00000000000000..c40d335aed4b49 --- /dev/null +++ b/src/js/node/perf_hooks.ts @@ -0,0 +1,59 @@ +// Hardcoded module "node:perf_hooks" +const { throwNotImplemented } = require("$shared"); + +var constants = { + NODE_PERFORMANCE_GC_MAJOR: 4, + NODE_PERFORMANCE_GC_MINOR: 1, + NODE_PERFORMANCE_GC_INCREMENTAL: 8, + NODE_PERFORMANCE_GC_WEAKCB: 16, + NODE_PERFORMANCE_GC_FLAGS_NO: 0, + NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: 2, + NODE_PERFORMANCE_GC_FLAGS_FORCED: 4, + NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: 8, + NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: 16, + NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: 32, + NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: 64, +}; + +var performance = globalThis.performance; + +class PerformanceObserver { + constructor() { + throwNotImplemented("PerformanceObserver"); + } +} + +class PerformanceEntry { + constructor() { + throwNotImplemented("PerformanceEntry"); + } +} + +export default { + performance, + // performance: { + // clearMarks: [Function: clearMarks], + // clearMeasures: [Function: clearMeasures], + // clearResourceTimings: [Function: clearResourceTimings], + // getEntries: [Function: getEntries], + // getEntriesByName: [Function: getEntriesByName], + // getEntriesByType: [Function: getEntriesByType], + // mark: [Function: mark], + // measure: [Function: measure], + // now: performance.now, + // setResourceTimingBufferSize: [Function: setResourceTimingBufferSize], + // timeOrigin: performance.timeOrigin, + // toJSON: [Function: toJSON], + // onresourcetimingbufferfull: [Getter/Setter] + // }, + constants, + // Performance: [class Performance extends EventTarget], + PerformanceEntry, + // PerformanceMark: [class PerformanceMark extends PerformanceEntry], + // PerformanceMeasure: [class PerformanceMeasure extends PerformanceEntry], + PerformanceObserver, + // PerformanceObserverEntryList: [class PerformanceObserverEntryList], + // PerformanceResourceTiming: [class PerformanceResourceTiming extends PerformanceEntry], + // monitorEventLoopDelay: [Function: monitorEventLoopDelay], + // createHistogram: [Function: createHistogram], +}; diff --git a/src/js/node/punycode.js b/src/js/node/punycode.js new file mode 100644 index 00000000000000..6d41161fd59029 --- /dev/null +++ b/src/js/node/punycode.js @@ -0,0 +1,431 @@ +// taken directly from https://www.npmjs.com/package/punycode +"use strict"; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = "-"; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too. +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + "overflow": "Overflow: input needs wider integers to process", + "not-basic": "Illegal input >= 0x80 (not a basic code point)", + "invalid-input": "Invalid input", +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.split("@"); + let result = ""; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + "@"; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, "\x2E"); + const labels = domain.split("."); + const encoded = map(labels, callback).join("."); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xd800 && value <= 0xdbff && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xfc00) == 0xdc00) { + // Low surrogate. + output.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = codePoints => String.fromCodePoint(...codePoints); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function (codePoint) { + if (codePoint >= 0x30 && codePoint < 0x3a) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5b) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7b) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function (digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function (delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */ delta > (baseMinusTMin * tMax) >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + ((baseMinusTMin + 1) * delta) / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function (input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error("not-basic"); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength /* no final expression */; ) { + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + const oldi = i; + for (let w = 1, k = base /* no condition */; ; k += base) { + if (index >= inputLength) { + error("invalid-input"); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base) { + error("invalid-input"); + } + if (digit > floor((maxInt - i) / w)) { + error("overflow"); + } + + i += digit * w; + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error("overflow"); + } + + w *= baseMinusT; + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error("overflow"); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function (input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + const inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + const basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error("overflow"); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error("overflow"); + } + if (currentValue === n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base /* no condition */; ; k += base) { + const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + (qMinusT % baseMinusT), 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + } + return output.join(""); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function (input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function (input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? "xn--" + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +export default { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + "version": "2.1.0", + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + "ucs2": { + "decode": ucs2decode, + "encode": ucs2encode, + }, + "decode": decode, + "encode": encode, + "toASCII": toASCII, + "toUnicode": toUnicode, +}; diff --git a/src/js/node/querystring.js b/src/js/node/querystring.js new file mode 100644 index 00000000000000..232bdac75369f9 --- /dev/null +++ b/src/js/node/querystring.js @@ -0,0 +1,396 @@ +var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); + +var Buffer = require("node:buffer").Buffer; + +// src/node-fallbacks/node_modules/querystring-es3/src/object-keys.js +var require_object_keys = __commonJS((exports, module) => { + var objectKeys = + Object.keys || + (function () { + var hasOwnProperty = Object.prototype.hasOwnProperty; + var hasDontEnumBug = !{ toString: null }.propertyIsEnumerable("toString"); + var dontEnums = [ + "toString", + "toLocaleString", + "valueOf", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "constructor", + ]; + var dontEnumsLength = dontEnums.length; + return function (obj) { + if (typeof obj !== "function" && (typeof obj !== "object" || obj === null)) { + throw new TypeError("Object.keys called on non-object"); + } + var result = []; + var prop; + var i; + for (prop in obj) { + if (hasOwnProperty.call(obj, prop)) { + result.push(prop); + } + } + if (hasDontEnumBug) { + for (i = 0; i < dontEnumsLength; i++) { + if (hasOwnProperty.call(obj, dontEnums[i])) { + result.push(dontEnums[i]); + } + } + } + return result; + }; + })(); + module.exports = objectKeys; +}); + +// src/node-fallbacks/node_modules/querystring-es3/src/index.js +var require_src = __commonJS((exports, module) => { + var ParsedQueryString = function () {}; + var unescapeBuffer = function (s, decodeSpaces) { + var out = Buffer.allocUnsafe(s.length); + var state = 0; + var n, m, hexchar, c; + for (var inIndex = 0, outIndex = 0; ; inIndex++) { + if (inIndex < s.length) { + c = s.charCodeAt(inIndex); + } else { + if (state > 0) { + out[outIndex++] = 37; + if (state === 2) out[outIndex++] = hexchar; + } + break; + } + switch (state) { + case 0: + switch (c) { + case 37: + n = 0; + m = 0; + state = 1; + break; + case 43: + if (decodeSpaces) c = 32; + default: + out[outIndex++] = c; + break; + } + break; + case 1: + hexchar = c; + n = unhexTable[c]; + if (!(n >= 0)) { + out[outIndex++] = 37; + out[outIndex++] = c; + state = 0; + break; + } + state = 2; + break; + case 2: + state = 0; + m = unhexTable[c]; + if (!(m >= 0)) { + out[outIndex++] = 37; + out[outIndex++] = hexchar; + out[outIndex++] = c; + break; + } + out[outIndex++] = 16 * n + m; + break; + } + } + return out.slice(0, outIndex); + }; + var qsUnescape = function (s, decodeSpaces) { + try { + return decodeURIComponent(s); + } catch (e) { + return QueryString.unescapeBuffer(s, decodeSpaces).toString(); + } + }; + var qsEscape = function (str) { + if (typeof str !== "string") { + if (typeof str === "object") str = String(str); + else str += ""; + } + var out = ""; + var lastPos = 0; + for (var i2 = 0; i2 < str.length; ++i2) { + var c = str.charCodeAt(i2); + if (c < 128) { + if (noEscape[c] === 1) continue; + if (lastPos < i2) out += str.slice(lastPos, i2); + lastPos = i2 + 1; + out += hexTable[c]; + continue; + } + if (lastPos < i2) out += str.slice(lastPos, i2); + if (c < 2048) { + lastPos = i2 + 1; + out += hexTable[192 | (c >> 6)] + hexTable[128 | (c & 63)]; + continue; + } + if (c < 55296 || c >= 57344) { + lastPos = i2 + 1; + out += hexTable[224 | (c >> 12)] + hexTable[128 | ((c >> 6) & 63)] + hexTable[128 | (c & 63)]; + continue; + } + ++i2; + var c2; + if (i2 < str.length) c2 = str.charCodeAt(i2) & 1023; + else throw new URIError("URI malformed"); + lastPos = i2 + 1; + c = 65536 + (((c & 1023) << 10) | c2); + out += + hexTable[240 | (c >> 18)] + + hexTable[128 | ((c >> 12) & 63)] + + hexTable[128 | ((c >> 6) & 63)] + + hexTable[128 | (c & 63)]; + } + if (lastPos === 0) return str; + if (lastPos < str.length) return out + str.slice(lastPos); + return out; + }; + var stringifyPrimitive = function (v) { + if (typeof v === "string") return v; + if (typeof v === "number" && isFinite(v)) return "" + v; + if (typeof v === "boolean") return v ? "true" : "false"; + return ""; + }; + var stringify = function (obj, sep, eq, options) { + sep = sep || "&"; + eq = eq || "="; + var encode = QueryString.escape; + if (options && typeof options.encodeURIComponent === "function") { + encode = options.encodeURIComponent; + } + if (obj !== null && typeof obj === "object") { + var keys = objectKeys(obj); + var len = keys.length; + var flast = len - 1; + var fields = ""; + for (var i2 = 0; i2 < len; ++i2) { + var k = keys[i2]; + var v = obj[k]; + var ks = encode(stringifyPrimitive(k)) + eq; + if (isArray(v)) { + var vlen = v.length; + var vlast = vlen - 1; + for (var j = 0; j < vlen; ++j) { + fields += ks + encode(stringifyPrimitive(v[j])); + if (j < vlast) fields += sep; + } + if (vlen && i2 < flast) fields += sep; + } else { + fields += ks + encode(stringifyPrimitive(v)); + if (i2 < flast) fields += sep; + } + } + return fields; + } + return ""; + }; + var charCodes = function (str) { + if (str.length === 0) return []; + if (str.length === 1) return [str.charCodeAt(0)]; + const ret = []; + for (var i2 = 0; i2 < str.length; ++i2) ret[ret.length] = str.charCodeAt(i2); + return ret; + }; + var parse = function (qs, sep, eq, options) { + const obj = new ParsedQueryString(); + if (typeof qs !== "string" || qs.length === 0) { + return obj; + } + var sepCodes = !sep ? defSepCodes : charCodes(sep + ""); + var eqCodes = !eq ? defEqCodes : charCodes(eq + ""); + const sepLen = sepCodes.length; + const eqLen = eqCodes.length; + var pairs = 1000; + if (options && typeof options.maxKeys === "number") { + pairs = options.maxKeys > 0 ? options.maxKeys : -1; + } + var decode = QueryString.unescape; + if (options && typeof options.decodeURIComponent === "function") { + decode = options.decodeURIComponent; + } + const customDecode = decode !== qsUnescape; + const keys = []; + var posIdx = 0; + var lastPos = 0; + var sepIdx = 0; + var eqIdx = 0; + var key = ""; + var value = ""; + var keyEncoded = customDecode; + var valEncoded = customDecode; + var encodeCheck = 0; + for (var i2 = 0; i2 < qs.length; ++i2) { + const code = qs.charCodeAt(i2); + if (code === sepCodes[sepIdx]) { + if (++sepIdx === sepLen) { + const end = i2 - sepIdx + 1; + if (eqIdx < eqLen) { + if (lastPos < end) key += qs.slice(lastPos, end); + } else if (lastPos < end) value += qs.slice(lastPos, end); + if (keyEncoded) key = decodeStr(key, decode); + if (valEncoded) value = decodeStr(value, decode); + if (key || value || lastPos - posIdx > sepLen || i2 === 0) { + if (indexOf(keys, key) === -1) { + obj[key] = value; + keys[keys.length] = key; + } else { + const curValue = obj[key] || ""; + if (curValue.pop) curValue[curValue.length] = value; + else if (curValue) obj[key] = [curValue, value]; + } + } else if (i2 === 1) { + delete obj[key]; + } + if (--pairs === 0) break; + keyEncoded = valEncoded = customDecode; + encodeCheck = 0; + key = value = ""; + posIdx = lastPos; + lastPos = i2 + 1; + sepIdx = eqIdx = 0; + } + continue; + } else { + sepIdx = 0; + if (!valEncoded) { + if (code === 37) { + encodeCheck = 1; + } else if ( + encodeCheck > 0 && + ((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102)) + ) { + if (++encodeCheck === 3) valEncoded = true; + } else { + encodeCheck = 0; + } + } + } + if (eqIdx < eqLen) { + if (code === eqCodes[eqIdx]) { + if (++eqIdx === eqLen) { + const end = i2 - eqIdx + 1; + if (lastPos < end) key += qs.slice(lastPos, end); + encodeCheck = 0; + lastPos = i2 + 1; + } + continue; + } else { + eqIdx = 0; + if (!keyEncoded) { + if (code === 37) { + encodeCheck = 1; + } else if ( + encodeCheck > 0 && + ((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102)) + ) { + if (++encodeCheck === 3) keyEncoded = true; + } else { + encodeCheck = 0; + } + } + } + } + if (code === 43) { + if (eqIdx < eqLen) { + if (lastPos < i2) key += qs.slice(lastPos, i2); + key += "%20"; + keyEncoded = true; + } else { + if (lastPos < i2) value += qs.slice(lastPos, i2); + value += "%20"; + valEncoded = true; + } + lastPos = i2 + 1; + } + } + if (pairs !== 0 && (lastPos < qs.length || eqIdx > 0)) { + if (lastPos < qs.length) { + if (eqIdx < eqLen) key += qs.slice(lastPos); + else if (sepIdx < sepLen) value += qs.slice(lastPos); + } + if (keyEncoded) key = decodeStr(key, decode); + if (valEncoded) value = decodeStr(value, decode); + if (indexOf(keys, key) === -1) { + obj[key] = value; + keys[keys.length] = key; + } else { + const curValue = obj[key]; + if (curValue.pop) curValue[curValue.length] = value; + else obj[key] = [curValue, value]; + } + } + return obj; + }; + var decodeStr = function (s, decoder) { + try { + return decoder(s); + } catch (e) { + return QueryString.unescape(s, true); + } + }; + var QueryString = (module.exports = { + unescapeBuffer, + unescape: qsUnescape, + escape: qsEscape, + stringify, + encode: stringify, + parse, + decode: parse, + }); + var objectKeys = require_object_keys(); + var isArray = arg => Object.prototype.toString.call(arg) === "[object Array]"; + var indexOf = (arr, searchElement, fromIndex) => { + var k; + if (arr == null) { + throw new TypeError('"arr" is null or not defined'); + } + var o = Object(arr); + var len = o.length >>> 0; + if (len === 0) { + return -1; + } + var n = fromIndex | 0; + if (n >= len) { + return -1; + } + k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + while (k < len) { + if (k in o && o[k] === searchElement) { + return k; + } + k++; + } + return -1; + }; + ParsedQueryString.prototype = Object.create ? Object.create(null) : {}; + var unhexTable = [ + -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, + -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -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, 10, 11, 12, 13, 14, 15, -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, -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, -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, -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + ]; + var hexTable = []; + for (i = 0; i < 256; ++i) hexTable[i] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase(); + var i; + var noEscape = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 1, 0, 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, 0, 0, 0, 1, 0, + ]; + var defSepCodes = [38]; + var defEqCodes = [61]; +}); +export default require_src(); diff --git a/src/js/node/readline.js b/src/js/node/readline.js index b1613e34d71f94..0811fb95f39a7c 100644 --- a/src/js/node/readline.js +++ b/src/js/node/readline.js @@ -25,10 +25,8 @@ // ---------------------------------------------------------------------------- // Section: Imports // ---------------------------------------------------------------------------- -var { Array, RegExp, String, Bun } = $lazy("primordials"); -import { EventEmitter } from "node:events"; -import { clearTimeout, setTimeout } from "timers"; -import { StringDecoder } from "string_decoder"; +const EventEmitter = require("node:events"); +const { StringDecoder } = require("node:string_decoder"); var isWritable; var { inspect } = Bun; @@ -1571,6 +1569,7 @@ function InterfaceConstructor(input, output, completer, terminal) { input.resume(); } +InterfaceConstructor.prototype = {}; ObjectSetPrototypeOf(InterfaceConstructor.prototype, EventEmitter.prototype); // ObjectSetPrototypeOf(InterfaceConstructor, EventEmitter); @@ -2555,6 +2554,7 @@ function Interface(input, output, completer, terminal) { this._ttyWrite = _ttyWriteDumb.bind(this); } } +Interface.prototype = {}; ObjectSetPrototypeOf(Interface.prototype, _Interface.prototype); ObjectSetPrototypeOf(Interface, _Interface); @@ -2957,7 +2957,7 @@ class Readline { #todo = []; constructor(stream, options = undefined) { - isWritable ??= import.meta.require("node:stream").isWritable; + isWritable ??= require("node:stream").isWritable; if (!isWritable(stream)) throw new ERR_INVALID_ARG_TYPE("stream", "Writable", stream); this.#stream = stream; if (options?.autoCommit != null) { @@ -3101,21 +3101,6 @@ var PromisesInterface = class Interface extends _Interface { // ---------------------------------------------------------------------------- // Exports // ---------------------------------------------------------------------------- -export var Interface = Interface; -export var clearLine = clearLine; -export var clearScreenDown = clearScreenDown; -export var createInterface = createInterface; -export var cursorTo = cursorTo; -export var emitKeypressEvents = emitKeypressEvents; -export var moveCursor = moveCursor; -export var promises = { - Readline, - Interface: PromisesInterface, - createInterface(input, output, completer, terminal) { - return new PromisesInterface(input, output, completer, terminal); - }, -}; - export default { Interface, clearLine, @@ -3124,7 +3109,13 @@ export default { cursorTo, emitKeypressEvents, moveCursor, - promises, + promises: { + Readline, + Interface: PromisesInterface, + createInterface(input, output, completer, terminal) { + return new PromisesInterface(input, output, completer, terminal); + }, + }, [SymbolFor("__BUN_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED__")]: { CSI, @@ -3133,5 +3124,4 @@ export default { stripVTControlCharacters, }, }, - [SymbolFor("CommonJS")]: 0, }; diff --git a/src/js/node/readline.promises.js b/src/js/node/readline.promises.js deleted file mode 100644 index 6890235b4fa071..00000000000000 --- a/src/js/node/readline.promises.js +++ /dev/null @@ -1,11 +0,0 @@ -// Hardcoded module "node:readline/promises" -import { promises } from "node:readline"; - -export const { Readline, Interface, createInterface } = promises; - -export default { - Readline, - Interface, - createInterface, - [Symbol.for("CommonJS")]: 0, -}; diff --git a/src/js/node/readline.promises.ts b/src/js/node/readline.promises.ts new file mode 100644 index 00000000000000..6ab60f0b2b9888 --- /dev/null +++ b/src/js/node/readline.promises.ts @@ -0,0 +1,2 @@ +// Hardcoded module "node:readline/promises" +export default require("node:readline").promises; diff --git a/src/js/node/repl.ts b/src/js/node/repl.ts index 33065e2ed2d562..ff1474a47bd3e2 100644 --- a/src/js/node/repl.ts +++ b/src/js/node/repl.ts @@ -1,7 +1,7 @@ // Hardcoded module "node:repl" // This is a stub! None of this is actually implemented yet. // It only exists to make some packages which import this module work. -import { throwNotImplemented } from "../shared"; +const { throwNotImplemented } = require("$shared"); function REPLServer() { throwNotImplemented("node:repl REPLServer"); @@ -18,8 +18,7 @@ function start() { throwNotImplemented("node:repl"); } -var repl = { - [Symbol.for("CommonJS")]: 0, +export default { lines: [], context: globalThis, historyIndex: -1, @@ -76,5 +75,3 @@ var repl = { }, ), }; - -export { repl as default, repl, REPLServer, Recoverable, REPL_MODE_SLOPPY, REPL_MODE_STRICT, start }; diff --git a/src/js/node/stream.consumers.js b/src/js/node/stream.consumers.js index 8dbe2920a06d26..4df51d1bf075d7 100644 --- a/src/js/node/stream.consumers.js +++ b/src/js/node/stream.consumers.js @@ -1,18 +1,15 @@ // Hardcoded module "node:stream/consumers" / "readable-stream/consumer" -const { Bun } = $lazy("primordials"); +const arrayBuffer = Bun.readableStreamToArrayBuffer; +const text = Bun.readableStreamToText; +const json = stream => Bun.readableStreamToText(stream).then(JSON.parse); -export const arrayBuffer = Bun.readableStreamToArrayBuffer; -export const text = Bun.readableStreamToText; -export const json = stream => Bun.readableStreamToText(stream).then(JSON.parse); - -export const buffer = async readableStream => { +const buffer = async readableStream => { return new Buffer(await arrayBuffer(readableStream)); }; -export const blob = Bun.readableStreamToBlob; +const blob = Bun.readableStreamToBlob; export default { - [Symbol.for("CommonJS")]: 0, arrayBuffer, text, json, diff --git a/src/js/node/stream.js b/src/js/node/stream.js index 474ada8d86d6a9..9f5d14bf818cdc 100644 --- a/src/js/node/stream.js +++ b/src/js/node/stream.js @@ -1,68 +1,16 @@ // Hardcoded module "node:stream" / "readable-stream" // "readable-stream" npm package -// just transpiled - -// 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 - -// You can include comma-delimited IDs as the value to either DEBUG_STREAMS or DEBUG_TRACK_EE and it will track -// The events and/or all of the outputs for the given stream IDs assigned at stream construction -// By default, child_process gives - -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 - (...args) => { - const lastItem = args[args.length - 1]; - if (!globalThis.__IDS_TO_TRACK.includes(lastItem)) return; - console.log(`ID: ${lastItem}`, ...args.slice(0, -1)); - } - : (...args) => console.log(...args.slice(0, -1)) - : () => {}; +// just transpiled and debug logs added. -var { isPromise, isCallable, direct, Object } = $lazy("primordials"); -import { EventEmitter as EE } from "bun:events_native"; -import { StringDecoder } from "node:string_decoder"; +const EE = $lazy("events"); +const StringDecoder = require("node:string_decoder").StringDecoder; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __ObjectSetPrototypeOf = Object.setPrototypeOf; var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; -var __copyProps = (to, from, except, desc) => { - if ((from && typeof from === "object") || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { - get: () => from[key], - set: val => (from[key] = val), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, - configurable: true, - }); - } - return to; -}; var runOnNextTick = process.nextTick; @@ -74,6 +22,8 @@ function validateBoolean(value, name) { if (typeof value !== "boolean") throw new ERR_INVALID_ARG_TYPE(name, "boolean", value); } +$debug("node:stream loaded"); + /** * @callback validateObject * @param {*} value @@ -2053,6 +2003,7 @@ var require_legacy = __commonJS({ if (!(this instanceof Stream)) return new Stream(options); EE.call(this, options); } + Stream.prototype = {}; ObjectSetPrototypeOf(Stream.prototype, EE.prototype); ObjectSetPrototypeOf(Stream, EE); @@ -2331,6 +2282,7 @@ var require_readable = __commonJS({ } }); } + Readable.prototype = {}; ObjectSetPrototypeOf(Readable.prototype, Stream.prototype); ObjectSetPrototypeOf(Readable, Stream); @@ -2340,32 +2292,31 @@ var require_readable = __commonJS({ if (ev === "data") { state.readableListening = this.listenerCount("readable") > 0; if (state.flowing !== false) { - __DEBUG__ && debug("in flowing mode!", this.__id); + $debug("in flowing mode!", this.__id); this.resume(); } else { - __DEBUG__ && debug("in readable mode!", this.__id); + $debug("in readable mode!", this.__id); } } else if (ev === "readable") { - __DEBUG__ && debug("readable listener added!", this.__id); + $debug("readable listener added!", this.__id); if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; - __DEBUG__ && - debug( - "on readable - state.length, reading, emittedReadable", - state.length, - state.reading, - state.emittedReadable, - this.__id, - ); + $debug( + "on readable - state.length, reading, emittedReadable", + state.length, + state.reading, + state.emittedReadable, + this.__id, + ); if (state.length) { emitReadable(this, state); } else if (!state.reading) { runOnNextTick(nReadingNextTick, this); } } else if (state.endEmitted) { - __DEBUG__ && debug("end already emitted...", this.__id); + $debug("end already emitted...", this.__id); } } return res; @@ -2421,7 +2372,7 @@ var require_readable = __commonJS({ } async _read() { - __DEBUG__ && debug("ReadableFromWeb _read()", this.__id); + $debug("ReadableFromWeb _read()", this.__id); var stream = this.#stream, reader = this.#reader; if (stream) { @@ -2438,7 +2389,7 @@ var require_readable = __commonJS({ value; const firstResult = reader.readMany(); - if (isPromise(firstResult)) { + if ($isPromise(firstResult)) { ({ done, value } = await firstResult); if (this.#closed) { @@ -2565,7 +2516,7 @@ var require_readable = __commonJS({ } // REVERT ME function emitReadable(stream, state) { - __DEBUG__ && debug("NativeReadable - emitReadable", stream.__id); + $debug("NativeReadable - emitReadable", stream.__id); _emitReadable(stream, state); } var destroyImpl = require_destroy(); @@ -2599,7 +2550,7 @@ var require_readable = __commonJS({ return readableAddChunk(this, chunk, encoding, true); }; function readableAddChunk(stream, chunk, encoding, addToFront) { - __DEBUG__ && debug("readableAddChunk", chunk, stream.__id); + $debug("readableAddChunk", chunk, stream.__id); const state = stream._readableState; let err; if (!state.objectMode) { @@ -2655,8 +2606,8 @@ var require_readable = __commonJS({ return !state.ended && (state.length < state.highWaterMark || state.length === 0); } function addChunk(stream, state, chunk, addToFront) { - __DEBUG__ && debug("adding chunk", stream.__id); - __DEBUG__ && debug("chunk", chunk.toString(), stream.__id); + $debug("adding chunk", stream.__id); + $debug("chunk", chunk.toString(), stream.__id); if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount("data") > 0) { if (state.multiAwaitDrain) { state.awaitDrainWriters.clear(); @@ -2669,9 +2620,10 @@ var require_readable = __commonJS({ state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk); else state.buffer.push(chunk); - __DEBUG__ && debug("needReadable @ addChunk", state.needReadable, stream.__id); + $debug("needReadable @ addChunk", state.needReadable, stream.__id); if (state.needReadable) emitReadable(stream, state); } + $debug("about to maybereadmore"); maybeReadMore(stream, state); } Readable.prototype.isPaused = function () { @@ -2723,7 +2675,7 @@ var require_readable = __commonJS({ } // You can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { - __DEBUG__ && debug("read - n =", n, this.__id); + $debug("read - n =", n, this.__id); if (!NumberIsInteger(n)) { n = NumberParseInt(n, 10); } @@ -2743,7 +2695,7 @@ var require_readable = __commonJS({ state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) ) { - __DEBUG__ && debug("read: emitReadable or endReadable", state.length, state.ended, this.__id); + $debug("read: emitReadable or endReadable", state.length, state.ended, this.__id); if (state.length === 0 && state.ended) endReadable(this); else emitReadable(this, state); return null; @@ -2753,8 +2705,7 @@ var require_readable = __commonJS({ // If we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { - __DEBUG__ && - debug("read: calling endReadable if length 0 -- length, state.ended", state.length, state.ended, this.__id); + $debug("read: calling endReadable if length 0 -- length, state.ended", state.length, state.ended, this.__id); if (state.length === 0) endReadable(this); return null; } @@ -2783,23 +2734,23 @@ var require_readable = __commonJS({ // if we need a readable event, then we need to do some reading. let doRead = state.needReadable; - __DEBUG__ && debug("need readable", doRead, this.__id); + $debug("need readable", doRead, this.__id); // If we currently have less than the highWaterMark, then also read some. if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; - __DEBUG__ && debug("length less than watermark", doRead, this.__id); + $debug("length less than watermark", doRead, this.__id); } // However, if we've ended, then there's no point, if we're already // reading, then it's unnecessary, if we're constructing we have to wait, // and if we're destroyed or errored, then it's not allowed, if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { - __DEBUG__ && debug("state.constructed?", state.constructed, this.__id); + $debug("state.constructed?", state.constructed, this.__id); doRead = false; - __DEBUG__ && debug("reading, ended or constructing", doRead, this.__id); + $debug("reading, ended or constructing", doRead, this.__id); } else if (doRead) { - __DEBUG__ && debug("do read", this.__id); + $debug("do read", this.__id); state.reading = true; state.sync = true; // If the length is currently zero, then we *need* a readable event. @@ -2808,17 +2759,17 @@ var require_readable = __commonJS({ // Call internal read method try { var result = this._read(state.highWaterMark); - if (isPromise(result)) { - __DEBUG__ && debug("async _read", this.__id); + if ($isPromise(result)) { + $debug("async _read", this.__id); const peeked = Bun.peek(result); - __DEBUG__ && debug("peeked promise", peeked, this.__id); + $debug("peeked promise", peeked, this.__id); if (peeked !== result) { result = peeked; } } - if (isPromise(result) && result?.then && isCallable(result.then)) { - __DEBUG__ && debug("async _read result.then setup", this.__id); + if ($isPromise(result) && result?.then && $isCallable(result.then)) { + $debug("async _read result.then setup", this.__id); result.then(nop, function (err) { errorOrDestroy(this, err); }); @@ -2833,16 +2784,16 @@ var require_readable = __commonJS({ if (!state.reading) n = howMuchToRead(nOrig, state); } - __DEBUG__ && debug("n @ fromList", n, this.__id); + $debug("n @ fromList", n, this.__id); let ret; if (n > 0) ret = fromList(n, state); else ret = null; - __DEBUG__ && debug("ret @ read", ret, this.__id); + $debug("ret @ read", ret, this.__id); if (ret === null) { state.needReadable = state.length <= state.highWaterMark; - __DEBUG__ && debug("state.length while ret = null", state.length, this.__id); + $debug("state.length while ret = null", state.length, this.__id); n = 0; } else { state.length -= n; @@ -2882,14 +2833,14 @@ var require_readable = __commonJS({ } } state.pipes.push(dest); - __DEBUG__ && debug("pipe count=%d opts=%j", state.pipes.length, pipeOpts, src.__id); + $debug("pipe count=%d opts=%j", state.pipes.length, pipeOpts, src.__id); const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; const endFn = doEnd ? onend : unpipe; if (state.endEmitted) runOnNextTick(endFn); else src.once("end", endFn); dest.on("unpipe", onunpipe); function onunpipe(readable, unpipeInfo) { - __DEBUG__ && debug("onunpipe", src.__id); + $debug("onunpipe", src.__id); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; @@ -2898,13 +2849,13 @@ var require_readable = __commonJS({ } } function onend() { - __DEBUG__ && debug("onend", src.__id); + $debug("onend", src.__id); dest.end(); } let ondrain; let cleanedUp = false; function cleanup() { - __DEBUG__ && debug("cleanup", src.__id); + $debug("cleanup", src.__id); dest.removeListener("close", onclose); dest.removeListener("finish", onfinish); if (ondrain) { @@ -2921,11 +2872,11 @@ var require_readable = __commonJS({ function pause() { if (!cleanedUp) { if (state.pipes.length === 1 && state.pipes[0] === dest) { - __DEBUG__ && debug("false write response, pause", 0, src.__id); + $debug("false write response, pause", 0, src.__id); state.awaitDrainWriters = dest; state.multiAwaitDrain = false; } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { - __DEBUG__ && debug("false write response, pause", state.awaitDrainWriters.size, src.__id); + $debug("false write response, pause", state.awaitDrainWriters.size, src.__id); state.awaitDrainWriters.add(dest); } src.pause(); @@ -2937,15 +2888,15 @@ var require_readable = __commonJS({ } src.on("data", ondata); function ondata(chunk) { - __DEBUG__ && debug("ondata", src.__id); + $debug("ondata", src.__id); const ret = dest.write(chunk); - __DEBUG__ && debug("dest.write", ret, src.__id); + $debug("dest.write", ret, src.__id); if (ret === false) { pause(); } } function onerror(er) { - debug("onerror", er); + $debug("onerror", er); unpipe(); dest.removeListener("error", onerror); if (dest.listenerCount("error") === 0) { @@ -2964,13 +2915,13 @@ var require_readable = __commonJS({ } dest.once("close", onclose); function onfinish() { - debug("onfinish"); + $debug("onfinish"); dest.removeListener("close", onclose); unpipe(); } dest.once("finish", onfinish); function unpipe() { - debug("unpipe"); + $debug("unpipe"); src.unpipe(dest); } dest.emit("pipe", src); @@ -2979,7 +2930,7 @@ var require_readable = __commonJS({ pause(); } } else if (!state.flowing) { - debug("pipe resume"); + $debug("pipe resume"); src.resume(); } return dest; @@ -2988,10 +2939,10 @@ var require_readable = __commonJS({ return function pipeOnDrainFunctionResult() { const state = src._readableState; if (state.awaitDrainWriters === dest) { - debug("pipeOnDrain", 1); + $debug("pipeOnDrain", 1); state.awaitDrainWriters = null; } else if (state.multiAwaitDrain) { - debug("pipeOnDrain", state.awaitDrainWriters.size); + $debug("pipeOnDrain", state.awaitDrainWriters.size); state.awaitDrainWriters.delete(dest); } if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount("data")) { @@ -3050,13 +3001,13 @@ var require_readable = __commonJS({ } } function nReadingNextTick(self) { - __DEBUG__ && debug("on readable nextTick, calling read(0)", self.__id); + $debug("on readable nextTick, calling read(0)", self.__id); self.read(0); } Readable.prototype.resume = function () { const state = this._readableState; if (!state.flowing) { - __DEBUG__ && debug("resume", this.__id); + $debug("resume", this.__id); state.flowing = !state.readableListening; resume(this, state); } @@ -3064,9 +3015,9 @@ var require_readable = __commonJS({ return this; }; Readable.prototype.pause = function () { - __DEBUG__ && debug("call pause flowing=%j", this._readableState.flowing, this.__id); + $debug("call pause flowing=%j", this._readableState.flowing, this.__id); if (this._readableState.flowing !== false) { - __DEBUG__ && debug("pause", this.__id); + $debug("pause", this.__id); this._readableState.flowing = false; this.emit("pause"); } @@ -3294,18 +3245,18 @@ var require_readable = __commonJS({ } function endReadable(stream) { const state = stream._readableState; - __DEBUG__ && debug("endEmitted @ endReadable", state.endEmitted, stream.__id); + $debug("endEmitted @ endReadable", state.endEmitted, stream.__id); if (!state.endEmitted) { state.ended = true; runOnNextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { - __DEBUG__ && debug("endReadableNT -- endEmitted, state.length", state.endEmitted, state.length, stream.__id); + $debug("endReadableNT -- endEmitted, state.length", state.endEmitted, state.length, stream.__id); if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { state.endEmitted = true; stream.emit("end"); - __DEBUG__ && debug("end emitted @ endReadableNT", stream.__id); + $debug("end emitted @ endReadableNT", stream.__id); if (stream.writable && stream.allowHalfOpen === false) { runOnNextTick(endWritableNT, stream); } else if (state.autoDestroy) { @@ -3328,16 +3279,94 @@ var require_readable = __commonJS({ }; var webStreamsAdapters = { newStreamReadableFromReadableStream, + + newReadableStreamFromStreamReadable(streamReadable, options = {}) { + // Not using the internal/streams/utils isReadableNodeStream utility + // here because it will return false if streamReadable is a Duplex + // whose readable option is false. For a Duplex that is not readable, + // we want it to pass this check but return a closed ReadableStream. + if (typeof streamReadable?._readableState !== "object") { + throw new ERR_INVALID_ARG_TYPE("streamReadable", "stream.Readable", streamReadable); + } + var { isDestroyed, isReadable } = require_utils(); + + if (isDestroyed(streamReadable) || !isReadable(streamReadable)) { + const readable = new ReadableStream(); + readable.cancel(); + return readable; + } + + const objectMode = streamReadable.readableObjectMode; + const highWaterMark = streamReadable.readableHighWaterMark; + + const evaluateStrategyOrFallback = strategy => { + // If there is a strategy available, use it + if (strategy) return strategy; + + if (objectMode) { + // When running in objectMode explicitly but no strategy, we just fall + // back to CountQueuingStrategy + return new CountQueuingStrategy({ highWaterMark }); + } + + // When not running in objectMode explicitly, we just fall + // back to a minimal strategy that just specifies the highWaterMark + // and no size algorithm. Using a ByteLengthQueuingStrategy here + // is unnecessary. + return { highWaterMark }; + }; + + const strategy = evaluateStrategyOrFallback(options?.strategy); + + let controller; + + function onData(chunk) { + controller.enqueue(chunk); + if (controller.desiredSize <= 0) streamReadable.pause(); + } + + streamReadable.pause(); + + const cleanup = finished(streamReadable, error => { + if (error?.code === "ERR_STREAM_PREMATURE_CLOSE") { + const err = new AbortError(undefined, { cause: error }); + error = err; + } + + cleanup(); + // This is a protection against non-standard, legacy streams + // that happen to emit an error event again after finished is called. + streamReadable.on("error", () => {}); + if (error) return controller.error(error); + controller.close(); + }); + + streamReadable.on("data", onData); + + return new ReadableStream( + { + start(c) { + controller = c; + }, + + pull() { + streamReadable.resume(); + }, + + cancel(reason) { + destroy(streamReadable, reason); + }, + }, + strategy, + ); + }, }; - function lazyWebStreams() { - if (webStreamsAdapters === void 0) webStreamsAdapters = {}; - return webStreamsAdapters; - } + Readable.fromWeb = function (readableStream, options) { - return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options); + return webStreamsAdapters.newStreamReadableFromReadableStream(readableStream, options); }; - Readable.toWeb = function (streamReadable) { - return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable); + Readable.toWeb = function (streamReadable, options) { + return webStreamsAdapters.newReadableStreamFromStreamReadable(streamReadable, options); }; Readable.wrap = function (src, options) { var _ref, _src$readableObjectMo; @@ -3414,6 +3443,7 @@ var require_writable = __commonJS({ finishMaybe(this, state); }); } + Writable.prototype = {}; ObjectSetPrototypeOf(Writable.prototype, Stream.prototype); ObjectSetPrototypeOf(Writable, Stream); module.exports = Writable; @@ -3457,6 +3487,7 @@ var require_writable = __commonJS({ this.closeEmitted = false; this[kOnFinished] = []; } + WritableState.prototype = {}; function resetBuffer(state) { state.buffered = []; state.bufferedIndex = 0; @@ -3736,7 +3767,7 @@ var require_writable = __commonJS({ Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb, native = false) { const state = this._writableState; - __DEBUG__ && debug("end", state, this.__id); + $debug("end", state, this.__id); if (typeof chunk === "function") { cb = chunk; chunk = null; @@ -3793,7 +3824,7 @@ var require_writable = __commonJS({ !state.writing && !state.errorEmitted && !state.closeEmitted; - debug("needFinish", needFinish, tag); + $debug("needFinish", needFinish, tag); return needFinish; } function callFinal(stream, state) { @@ -3839,7 +3870,7 @@ var require_writable = __commonJS({ } } function finishMaybe(stream, state, sync) { - __DEBUG__ && debug("finishMaybe -- state, sync", state, sync, stream.__id); + $debug("finishMaybe -- state, sync", state, sync, stream.__id); if (!needFinish(state, stream.__id)) return; @@ -4376,8 +4407,8 @@ var require_duplex = __commonJS({ this.allowHalfOpen = true; } } + Duplex.prototype = {}; module.exports = Duplex; - ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype); ObjectSetPrototypeOf(Duplex, Readable); @@ -4454,6 +4485,7 @@ var require_transform = __commonJS({ this.on("prefinish", prefinish.bind(this)); } + Transform.prototype = {}; ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype); ObjectSetPrototypeOf(Transform, Duplex); @@ -4540,6 +4572,7 @@ var require_passthrough = __commonJS({ if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } + PassThrough.prototype = {}; ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype); ObjectSetPrototypeOf(PassThrough, Transform); @@ -5162,47 +5195,6 @@ var require_stream = __commonJS({ }, }); -// node_modules/readable-stream/lib/ours/index.js -var require_ours = __commonJS({ - "node_modules/readable-stream/lib/ours/index.js"(exports, module) { - "use strict"; - const CustomStream = require_stream(); - const promises = require_promises(); - const originalDestroy = CustomStream.Readable.destroy; - module.exports = CustomStream; - module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer; - module.exports._isUint8Array = CustomStream._isUint8Array; - module.exports.isDisturbed = CustomStream.isDisturbed; - module.exports.isErrored = CustomStream.isErrored; - module.exports.isWritable = CustomStream.isWritable; - module.exports.isReadable = CustomStream.isReadable; - module.exports.Readable = CustomStream.Readable; - module.exports.Writable = CustomStream.Writable; - module.exports.Duplex = CustomStream.Duplex; - module.exports.Transform = CustomStream.Transform; - module.exports.PassThrough = CustomStream.PassThrough; - module.exports.addAbortSignal = CustomStream.addAbortSignal; - module.exports.finished = CustomStream.finished; - module.exports.destroy = CustomStream.destroy; - module.exports.destroy = originalDestroy; - module.exports.pipeline = CustomStream.pipeline; - module.exports.compose = CustomStream.compose; - - module.exports._getNativeReadableStreamPrototype = getNativeReadableStreamPrototype; - module.exports.NativeWritable = NativeWritable; - - Object.defineProperty(CustomStream, "promises", { - configurable: true, - enumerable: true, - get() { - return promises; - }, - }); - module.exports.Stream = CustomStream.Stream; - module.exports.default = module.exports; - }, -}); - /** * Bun native stream wrapper * @@ -5279,21 +5271,21 @@ function createNativeStreamReadable(nativeType, Readable) { // However, in the case of an fs.ReadStream, we can pass the number of bytes we want to read // which may be significantly less than the actual highWaterMark _read(maxToRead) { - __DEBUG__ && debug("NativeReadable._read", this.__id); + $debug("NativeReadable._read", this.__id); if (this.#pendingRead) { - __DEBUG__ && debug("pendingRead is true", this.__id); + $debug("pendingRead is true", this.__id); return; } var ptr = this.#bunNativePtr; - __DEBUG__ && debug("ptr @ NativeReadable._read", ptr, this.__id); + $debug("ptr @ NativeReadable._read", ptr, this.__id); if (ptr === 0) { this.push(null); return; } if (!this.#constructed) { - __DEBUG__ && debug("NativeReadable not constructed yet", this.__id); + $debug("NativeReadable not constructed yet", this.__id); this.#internalConstruct(ptr); } @@ -5320,18 +5312,18 @@ function createNativeStreamReadable(nativeType, Readable) { #internalConstruct(ptr) { this.#constructed = true; const result = start(ptr, this.#highWaterMark); - __DEBUG__ && debug("NativeReadable internal `start` result", result, this.__id); + $debug("NativeReadable internal `start` result", result, this.__id); if (typeof result === "number" && result > 1) { this.#hasResized = true; - __DEBUG__ && debug("NativeReadable resized", this.__id); + $debug("NativeReadable resized", this.__id); this.#highWaterMark = Math.min(this.#highWaterMark, result); } if (drainFn) { const drainResult = drainFn(ptr); - __DEBUG__ && debug("NativeReadable drain result", drainResult, this.__id); + $debug("NativeReadable drain result", drainResult, this.__id); if ((drainResult?.byteLength ?? 0) > 0) { this.push(drainResult); } @@ -5343,7 +5335,7 @@ function createNativeStreamReadable(nativeType, Readable) { // how many bytes they want to read (ie. when reading only part of a file) #getRemainingChunk(maxToRead = this.#highWaterMark) { var chunk = this.#remainingChunk; - __DEBUG__ && debug("chunk @ #getRemainingChunk", chunk, this.__id); + $debug("chunk @ #getRemainingChunk", chunk, this.__id); if (chunk?.byteLength ?? 0 < MIN_BUFFER_SIZE) { var size = maxToRead > MIN_BUFFER_SIZE ? maxToRead : MIN_BUFFER_SIZE; this.#remainingChunk = chunk = new Buffer(size); @@ -5352,12 +5344,12 @@ function createNativeStreamReadable(nativeType, Readable) { } // push(result, encoding) { - // __DEBUG__ && debug("NativeReadable push -- result, encoding", result, encoding, this.__id); + // debug("NativeReadable push -- result, encoding", result, encoding, this.__id); // return super.push(...arguments); // } #handleResult(result, view, isClosed) { - __DEBUG__ && debug("result, isClosed @ #handleResult", result, isClosed, this.__id); + $debug("result, isClosed @ #handleResult", result, isClosed, this.__id); if (typeof result === "number") { if (result >= this.#highWaterMark && !this.#hasResized && !isClosed) { @@ -5375,30 +5367,30 @@ function createNativeStreamReadable(nativeType, Readable) { if (result.byteLength >= this.#highWaterMark && !this.#hasResized && !isClosed) { this.#highWaterMark *= 2; this.#hasResized = true; - __DEBUG__ && debug("Resized", this.__id); + $debug("Resized", this.__id); } return handleArrayBufferViewResult(this, result, view, isClosed); } else { - __DEBUG__ && debug("Unknown result type", result, this.__id); + $debug("Unknown result type", result, this.__id); throw new Error("Invalid result from pull"); } } #internalRead(view, ptr) { - __DEBUG__ && debug("#internalRead()", this.__id); + $debug("#internalRead()", this.__id); closer[0] = false; var result = pull(ptr, view, closer); - if (isPromise(result)) { + if ($isPromise(result)) { this.#pendingRead = true; return result.then( result => { this.#pendingRead = false; - __DEBUG__ && debug("pending no longerrrrrrrr (result returned from pull)", this.__id); + $debug("pending no longerrrrrrrr (result returned from pull)", this.__id); this.#remainingChunk = this.#handleResult(result, view, closer[0]); }, reason => { - __DEBUG__ && debug("error from pull", reason, this.__id); + $debug("error from pull", reason, this.__id); errorOrDestroy(this, reason); }, ); @@ -5419,7 +5411,7 @@ function createNativeStreamReadable(nativeType, Readable) { if (updateRef) { updateRef(ptr, false); } - __DEBUG__ && debug("NativeReadable destroyed", this.__id); + $debug("NativeReadable destroyed", this.__id); cancel(ptr, error); callback(error); } @@ -5466,9 +5458,9 @@ function getNativeReadableStream(Readable, stream, options) { return undefined; } - const native = direct(stream); + const native = $direct(stream); if (!native) { - debug("no native readable stream"); + $debug("no native readable stream"); return undefined; } const { stream: ptr, data: type } = native; @@ -5533,7 +5525,7 @@ var NativeWritable = class NativeWritable extends Writable { var fileSink = this.#fileSink; var result = fileSink.write(chunk); - if (isPromise(result)) { + if ($isPromise(result)) { // var writePromises = this.#writePromises; // var i = writePromises.length; // writePromises[i] = result; @@ -5580,28 +5572,19 @@ var NativeWritable = class NativeWritable extends Writable { } }; -const stream_exports = require_ours(); -stream_exports[Symbol.for("CommonJS")] = 0; -stream_exports[Symbol.for("::bunternal::")] = { _ReadableFromWeb, _ReadableFromWebForUndici }; -export default stream_exports; -export var _uint8ArrayToBuffer = stream_exports._uint8ArrayToBuffer; -export var _isUint8Array = stream_exports._isUint8Array; -export var isDisturbed = stream_exports.isDisturbed; -export var isErrored = stream_exports.isErrored; -export var isWritable = stream_exports.isWritable; -export var isReadable = stream_exports.isReadable; -export var Readable = stream_exports.Readable; -export var Writable = stream_exports.Writable; -export var Duplex = stream_exports.Duplex; -export var Transform = stream_exports.Transform; -export var PassThrough = stream_exports.PassThrough; -export var addAbortSignal = stream_exports.addAbortSignal; -export var finished = stream_exports.finished; -export var destroy = stream_exports.destroy; -export var pipeline = stream_exports.pipeline; -export var compose = stream_exports.compose; -export var Stream = stream_exports.Stream; -export var eos = (stream_exports["eos"] = require_end_of_stream); -export var _getNativeReadableStreamPrototype = stream_exports._getNativeReadableStreamPrototype; -export var NativeWritable = stream_exports.NativeWritable; -export var promises = Stream.promises; +const exports = require_stream(); +const promises = require_promises(); +exports._getNativeReadableStreamPrototype = getNativeReadableStreamPrototype; +exports.NativeWritable = NativeWritable; +Object.defineProperty(exports, "promises", { + configurable: true, + enumerable: true, + get() { + return promises; + }, +}); + +exports[Symbol.for("::bunternal::")] = { _ReadableFromWeb, _ReadableFromWebForUndici }; +exports.eos = require_end_of_stream(); + +export default exports; diff --git a/src/js/node/stream.promises.js b/src/js/node/stream.promises.js deleted file mode 100644 index 323785a4c1ca59..00000000000000 --- a/src/js/node/stream.promises.js +++ /dev/null @@ -1,10 +0,0 @@ -// Hardcoded module "node:stream/promises" -import { promises } from "node:stream"; - -export var { pipeline, finished } = promises; - -export default { - pipeline, - finished, - [Symbol.for("CommonJS")]: 0, -}; diff --git a/src/js/node/stream.promises.ts b/src/js/node/stream.promises.ts new file mode 100644 index 00000000000000..04aaf0b0c5a909 --- /dev/null +++ b/src/js/node/stream.promises.ts @@ -0,0 +1,2 @@ +// Hardcoded module "node:stream/promises" +export default require("node:stream").promises; diff --git a/src/js/node/stream.web.js b/src/js/node/stream.web.js index b7b947af9c4f9b..ab3458d2d24c1e 100644 --- a/src/js/node/stream.web.js +++ b/src/js/node/stream.web.js @@ -1,23 +1,4 @@ // Hardcoded module "node:stream/web" / "readable-stream/web" -export const { - ReadableStream, - ReadableStreamDefaultReader, - ReadableStreamBYOBReader, - ReadableStreamBYOBRequest, - ReadableByteStreamController, - ReadableStreamDefaultController, - TransformStream, - TransformStreamDefaultController, - WritableStream, - WritableStreamDefaultWriter, - WritableStreamDefaultController, - ByteLengthQueuingStrategy, - CountQueuingStrategy, - TextEncoderStream, - TextDecoderStream, - CompressionStream, - DecompressionStream, -} = globalThis; export default { ReadableStream, ReadableStreamDefaultReader, @@ -32,9 +13,8 @@ export default { WritableStreamDefaultController, ByteLengthQueuingStrategy, CountQueuingStrategy, - TextEncoderStream, - TextDecoderStream, - CompressionStream, - DecompressionStream, - [Symbol.for("CommonJS")]: 0, + // TextEncoderStream, + // TextDecoderStream, + // CompressionStream, + // DecompressionStream, }; diff --git a/src/js/node/timers.js b/src/js/node/timers.js index 4e907a7ab262bf..221fa181a0aaf8 100644 --- a/src/js/node/timers.js +++ b/src/js/node/timers.js @@ -1,14 +1,11 @@ // Hardcoded module "node:timers" // This implementation isn't 100% correct // Ref/unref does not impact whether the process is kept alive - -export var { setTimeout, clearTimeout, setInterval, setImmediate, clearInterval, clearImmediate } = globalThis; - export default { + setTimeout, + clearTimeout, setInterval, setImmediate, - setTimeout, clearInterval, - clearTimeout, - [Symbol.for("CommonJS")]: 0, + clearImmediate, }; diff --git a/src/js/node/timers.promises.js b/src/js/node/timers.promises.js index 3e2e7bcd57fdad..eb171941a597dd 100644 --- a/src/js/node/timers.promises.js +++ b/src/js/node/timers.promises.js @@ -232,5 +232,12 @@ function setIntervalPromise(after = 1, value, options = {}) { } } -export { setTimeoutPromise as setTimeout, setImmediatePromise as setImmediate, setIntervalPromise as setInterval }; -export default { setTimeout: setTimeoutPromise, setImmediate: setImmediatePromise, setInterval: setIntervalPromise }; +export default { + setTimeout: setTimeoutPromise, + setImmediate: setImmediatePromise, + setInterval: setIntervalPromise, + scheduler: { + wait: (delay, options) => setTimeoutPromise(delay, undefined, options), + yield: setImmediatePromise, + }, +}; diff --git a/src/js/node/tls.js b/src/js/node/tls.js index e8c2dd9985e687..fc2d9065a24af4 100644 --- a/src/js/node/tls.js +++ b/src/js/node/tls.js @@ -1,10 +1,10 @@ // Hardcoded module "node:tls" -import { isArrayBufferView, isTypedArray } from "util/types"; -import net, { Server as NetServer } from "node:net"; -const InternalTCPSocket = net[Symbol.for("::bunternal::")]; +const { isArrayBufferView, isTypedArray } = require("node:util/types"); +const net = require("node:net"); +const { Server: NetServer, [Symbol.for("::bunternal::")]: InternalTCPSocket } = net; const bunSocketInternal = Symbol.for("::bunnetsocketinternal::"); +const { rootCertificates, canonicalizeIP } = $lazy("internal/tls"); -const { RegExp, Array, String } = $lazy("primordials"); const SymbolReplace = Symbol.replace; const RegExpPrototypeSymbolReplace = RegExp.prototype[SymbolReplace]; const RegExpPrototypeExec = RegExp.prototype.exec; @@ -145,6 +145,7 @@ function splitEscapedAltNames(altNames) { ArrayPrototypePush.call(result, currentToken); return result; } + function checkServerIdentity(hostname, cert) { const subject = cert.subject; const altNames = cert.subjectaltname; @@ -624,10 +625,6 @@ function getCiphers() { return DEFAULT_CIPHERS.split(":"); } -function getCurves() { - return; -} - // Convert protocols array into valid OpenSSL protocols list // ("\x06spdy/2\x08http/1.1\x08http/1.0") function convertProtocols(protocols) { @@ -677,31 +674,8 @@ function convertALPNProtocols(protocols, out) { out.ALPNProtocols = protocols; } } -var rootCertificates = $lazy("rootCertificates"); -var exports = { - [Symbol.for("CommonJS")]: 0, - CLIENT_RENEG_LIMIT, - CLIENT_RENEG_WINDOW, - connect, - convertALPNProtocols, - createConnection, - createSecureContext, - createServer, - DEFAULT_CIPHERS, - DEFAULT_ECDH_CURVE, - DEFAULT_MAX_VERSION, - DEFAULT_MIN_VERSION, - getCiphers, - getCurves, - parseCertString, - SecureContext, - Server, - TLSSocket, - checkServerIdentity, - rootCertificates, -}; -export { +export default { CLIENT_RENEG_LIMIT, CLIENT_RENEG_WINDOW, connect, @@ -714,12 +688,10 @@ export { DEFAULT_MAX_VERSION, DEFAULT_MIN_VERSION, getCiphers, - getCurves, parseCertString, SecureContext, - checkServerIdentity, Server, TLSSocket, + checkServerIdentity, rootCertificates, - exports as default, }; diff --git a/src/js/node/trace_events.ts b/src/js/node/trace_events.ts index 7edcc57d0c166a..e0cb82f3444897 100644 --- a/src/js/node/trace_events.ts +++ b/src/js/node/trace_events.ts @@ -26,10 +26,7 @@ function getEnabledCategories() { return ""; } -var defaultObject = { +export default { createTracing, getEnabledCategories, - [Symbol.for("CommonJS")]: 0, }; - -export { defaultObject as default, createTracing, getEnabledCategories }; diff --git a/src/js/node/url.js b/src/js/node/url.js index 92754340549194..3b6b57ac2459cd 100644 --- a/src/js/node/url.js +++ b/src/js/node/url.js @@ -39,6 +39,7 @@ function Url() { this.path = null; this.href = null; } +Url.prototype = {}; // Reference: RFC 3986, RFC 1808, RFC 2396 @@ -820,10 +821,10 @@ function urlToHttpOptions(url) { return options; } -const lazy = $lazy; -const pathToFileURL = lazy("pathToFileURL"); -const fileURLToPath = lazy("fileURLToPath"); -const defaultObject = { +const pathToFileURL = $lazy("pathToFileURL"); +const fileURLToPath = $lazy("fileURLToPath"); + +export default { parse: urlParse, resolve: urlResolve, resolveObject: urlResolveObject, @@ -834,19 +835,4 @@ const defaultObject = { pathToFileURL, fileURLToPath, urlToHttpOptions, - [Symbol.for("CommonJS")]: 0, -}; - -export { - defaultObject as default, - urlParse as parse, - urlResolve as resolve, - urlResolveObject as resolveObject, - urlFormat as format, - Url, - URLSearchParams, - URL, - pathToFileURL, - fileURLToPath, - urlToHttpOptions, }; diff --git a/src/js/node/util.js b/src/js/node/util.js index 2ec4aadb9dc048..92d77701eb11b7 100644 --- a/src/js/node/util.js +++ b/src/js/node/util.js @@ -1,22 +1,13 @@ // Hardcoded module "node:util" -import * as types from "node:util/types"; -export { default as types } from "node:util/types"; +const types = require("node:util/types"); var cjs_exports = {}; -export default cjs_exports; - -var __getOwnPropNames = Object.getOwnPropertyNames; -var __commonJS = (cb, mod) => - function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; - }; - function isBufferInterface({ copy, fill, readUint8 }) { return typeof copy === "function" && typeof fill === "function" && typeof readUint8 === "function"; } -export function isBuffer(value) { +function isBuffer(value) { return ( Buffer.isBuffer(value) || // incase it ends up as a browserify buffer @@ -28,22 +19,6 @@ function isFunction(value) { return typeof value === "function"; } -// node_modules/inherits/inherits_browser.js -var require_inherits_browser = __commonJS({ - "node_modules/inherits/inherits_browser.js"(exports, module2) { - module2.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true, - }, - }); - }; - }, -}); const deepEquals = Bun.deepEquals; const isDeepStrictEqual = (a, b) => deepEquals(a, b, true); var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors; @@ -244,7 +219,7 @@ function formatValue(ctx, value, recurseTimes) { var base = "", array = false, braces = ["{", "}"]; - if (isArray(value)) { + if ($isArray(value)) { array = true; braces = ["[", "]"]; } @@ -393,10 +368,6 @@ function reduceToSingleString(output, base, braces) { return braces[0] + base + " " + output.join(", ") + " " + braces[1]; } -function isArray(ar) { - return Array.isArray(ar); -} - function isBoolean(arg) { return typeof arg === "boolean"; } @@ -416,6 +387,7 @@ function isNumber(arg) { function isString(arg) { return typeof arg === "string"; } + function isSymbol(arg) { return typeof arg === "symbol"; } @@ -450,7 +422,17 @@ function timestamp() { var log = function log() { console.log("%s - %s", timestamp(), format.apply(cjs_exports, arguments)); }; -var inherits = (inherits = require_inherits_browser()); +var inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true, + }, + }); +}; var _extend = function (origin, add) { if (!add || !isObject(add)) return origin; var keys = Object.keys(add); @@ -550,20 +532,18 @@ function callbackify(original) { Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); return callbackified; } -export var TextDecoder = globalThis.TextDecoder; -export var TextEncoder = globalThis.TextEncoder; var toUSVString = input => { return (input + "").toWellFormed(); }; -Object.assign(cjs_exports, { +export default Object.assign(cjs_exports, { format, deprecate, debuglog, _extend, inspect, types, - isArray, + isArray: $isArray, isBoolean, isNull, isNullOrUndefined, @@ -586,32 +566,4 @@ Object.assign(cjs_exports, { isDeepStrictEqual, TextDecoder, TextEncoder, - [Symbol.for("CommonJS")]: 0, }); - -export { - format, - deprecate, - debuglog, - inspect, - isArray, - isBoolean, - isNull, - isNullOrUndefined, - isNumber, - isString, - isSymbol, - isUndefined, - isRegExp, - isObject, - isDate, - isError, - isFunction, - isPrimitive, - log, - inherits, - promisify, - callbackify, - isDeepStrictEqual, - toUSVString, -}; diff --git a/src/js/node/v8.ts b/src/js/node/v8.ts index b043e10fe9e267..f74422de812fa6 100644 --- a/src/js/node/v8.ts +++ b/src/js/node/v8.ts @@ -1,7 +1,7 @@ // Hardcoded module "node:v8" // This is a stub! None of this is actually implemented yet. -import { hideFromStack, throwNotImplemented } from "../shared"; -import { serialize as jscSerialize, deserialize as jscDeserialize } from "bun:jsc"; +const { hideFromStack, throwNotImplemented } = require("$shared"); +const jsc = require("bun:jsc"); function notimpl(message) { throwNotImplemented("node:v8 " + message); @@ -44,7 +44,7 @@ function setFlagsFromString() { notimpl("setFlagsFromString"); } function deserialize(value) { - return jscDeserialize(value); + return jsc.deserialize(value); } function takeCoverage() { notimpl("takeCoverage"); @@ -53,7 +53,7 @@ function stopCoverage() { notimpl("stopCoverage"); } function serialize(arg1) { - return jscSerialize(arg1, { binaryType: "nodebuffer" }); + return jsc.serialize(arg1, { binaryType: "nodebuffer" }); } function writeHeapSnapshot() { notimpl("writeHeapSnapshot"); @@ -85,7 +85,7 @@ const promiseHooks = { isBuildingSnapshot: () => notimpl("isBuildingSnapshot"), }; -const defaultObject = { +export default { cachedDataVersionTag, getHeapSnapshot, getHeapStatistics, @@ -102,30 +102,6 @@ const defaultObject = { startupSnapshot, Deserializer, Serializer, - [Symbol.for("CommonJS")]: 0, -}; - -export { - cachedDataVersionTag, - getHeapSnapshot, - getHeapStatistics, - getHeapSpaceStatistics, - getHeapCodeStatistics, - setFlagsFromString, - deserialize, - takeCoverage, - stopCoverage, - serialize, - writeHeapSnapshot, - setHeapSnapshotNearHeapLimit, - promiseHooks, - startupSnapshot, - Deserializer, - Serializer, - DefaultDeserializer, - DefaultSerializer, - GCProfiler, - defaultObject as default, }; hideFromStack( diff --git a/src/js/node/vm.ts b/src/js/node/vm.ts index 331f4fbc69a525..e3058780ae103a 100644 --- a/src/js/node/vm.ts +++ b/src/js/node/vm.ts @@ -1,5 +1,5 @@ // Hardcoded module "node:vm" -import { throwNotImplemented } from "../shared"; +const { throwNotImplemented } = require("$shared"); const vm = $lazy("vm"); @@ -10,26 +10,31 @@ function runInContext(code, context, options) { } function compileFunction() { - throwNotImplemented("node:vm compileFunction", 401); + throwNotImplemented("node:vm compileFunction"); } function measureMemory() { - throwNotImplemented("node:vm measureMemory", 401); + throwNotImplemented("node:vm measureMemory"); } -const defaultObject = { - createContext, - runInContext, - runInNewContext, - runInThisContext, - isContext, - compileFunction, - measureMemory, - Script, - [Symbol.for("CommonJS")]: 0, -}; +class Module { + constructor() { + throwNotImplemented("node:vm Module"); + } +} + +class SourceTextModule { + constructor() { + throwNotImplemented("node:vm Module"); + } +} + +class SyntheticModule { + constructor() { + throwNotImplemented("node:vm Module"); + } +} -export { - defaultObject as default, +export default { createContext, runInContext, runInNewContext, @@ -38,4 +43,7 @@ export { compileFunction, measureMemory, Script, + Module, + SourceTextModule, + SyntheticModule, }; diff --git a/src/js/node/wasi.js b/src/js/node/wasi.js index ea693585a1b2e7..c8b051cd3ec0cd 100644 --- a/src/js/node/wasi.js +++ b/src/js/node/wasi.js @@ -8,7 +8,7 @@ /** **/ // constants is injected into the top of this file -const nodeFsConstants = constants; +const nodeFsConstants = $processBindingConstants.fs; var __getOwnPropNames = Object.getOwnPropertyNames; @@ -769,9 +769,9 @@ var require_wasi = __commonJS({ process.kill(process.pid, signal); }, randomFillSync: array => crypto.getRandomValues(array), - isTTY: fd => import.meta.require("node:tty").isatty(fd), + isTTY: fd => require("node:tty").isatty(fd), fs: Bun.fs(), - path: import.meta.require("node:path"), + path: require("node:path"), }; return (defaultConfig = { @@ -1936,8 +1936,4 @@ var require_wasi = __commonJS({ exports.default = WASI; }, }); -const WASIExport = require_wasi(); -const WASI = WASIExport.default; -WASIExport[Symbol.for("CommonJS")] = 0; -export { WASIExport as WASI }; -export default WASIExport; +export default { WASI: require_wasi().default }; diff --git a/src/js/node/worker_threads.ts b/src/js/node/worker_threads.ts new file mode 100644 index 00000000000000..1cc778fd05c218 --- /dev/null +++ b/src/js/node/worker_threads.ts @@ -0,0 +1,329 @@ +// import type { Readable, Writable } from "node:stream"; +// import type { WorkerOptions } from "node:worker_threads"; +declare const self: typeof globalThis; +type WebWorker = InstanceType; + +const EventEmitter = require("node:events"); +const { throwNotImplemented } = require("../internal/shared"); + +const { MessageChannel, BroadcastChannel, Worker: WebWorker } = globalThis; +const SHARE_ENV = Symbol("nodejs.worker_threads.SHARE_ENV"); + +const isMainThread = Bun.isMainThread; +let [_workerData, _threadId, _receiveMessageOnPort] = $lazy("worker_threads"); + +type NodeWorkerOptions = import("node:worker_threads").WorkerOptions; + +const emittedWarnings = new Set(); +function emitWarning(type, message) { + if (emittedWarnings.has(type)) return; + emittedWarnings.add(type); + // process.emitWarning(message); // our printing is bad + console.warn("[bun] Warning:", message); +} + +function injectFakeEmitter(Class) { + function messageEventHandler(event: MessageEvent) { + return event.data; + } + + function errorEventHandler(event: ErrorEvent) { + return event.error; + } + + const wrappedListener = Symbol("wrappedListener"); + + function wrapped(run, listener) { + const callback = function (event) { + return listener(run(event)); + }; + listener[wrappedListener] = callback; + return callback; + } + + function functionForEventType(event, listener) { + switch (event) { + case "error": + case "messageerror": { + return wrapped(errorEventHandler, listener); + } + + default: { + return wrapped(messageEventHandler, listener); + } + } + } + + Class.prototype.on = function (event, listener) { + this.addEventListener(event, functionForEventType(event, listener)); + + return this; + }; + + Class.prototype.off = function (event, listener) { + if (listener) { + this.removeEventListener(event, listener[wrappedListener] || listener); + } else { + this.removeEventListener(event); + } + + return this; + }; + + Class.prototype.once = function (event, listener) { + this.addEventListener(event, functionForEventType(event, listener), { once: true }); + + return this; + }; + + function EventClass(eventName) { + if (eventName === "error" || eventName === "messageerror") { + return ErrorEvent; + } + + return MessageEvent; + } + + Class.prototype.emit = function (event, ...args) { + this.dispatchEvent(new (EventClass(event))(event, ...args)); + return this; + }; + + Class.prototype.prependListener = Class.prototype.on; + Class.prototype.prependOnceListener = Class.prototype.once; +} + +const _MessagePort = globalThis.MessagePort; +injectFakeEmitter(_MessagePort); + +const MessagePort = _MessagePort; + +let resourceLimits = {}; + +let workerData = _workerData; +let threadId = _threadId; +function receiveMessageOnPort(port: MessagePort) { + let res = _receiveMessageOnPort(port); + if (!res) return undefined; + return { + message: res, + }; +} + +function fakeParentPort() { + const fake = Object.create(MessagePort.prototype); + Object.defineProperty(fake, "onmessage", { + get() { + return self.onmessage; + }, + set(value) { + self.onmessage = value; + }, + }); + + Object.defineProperty(fake, "onmessageerror", { + get() { + return self.onmessageerror; + }, + set(value) {}, + }); + + Object.defineProperty(fake, "postMessage", { + value(...args: [any, any]) { + return self.postMessage(...args); + }, + }); + + Object.defineProperty(fake, "close", { + value() { + return process.exit(0); + }, + }); + + Object.defineProperty(fake, "start", { + value() {}, + }); + + Object.defineProperty(fake, "unref", { + value() {}, + }); + + Object.defineProperty(fake, "ref", { + value() {}, + }); + + Object.defineProperty(fake, "hasRef", { + value() { + return false; + }, + }); + + Object.defineProperty(fake, "setEncoding", { + value() {}, + }); + + Object.defineProperty(fake, "addEventListener", { + value: self.addEventListener.bind(self), + }); + + Object.defineProperty(fake, "removeEventListener", { + value: self.removeEventListener.bind(self), + }); + + return fake; +} +let parentPort: MessagePort | null = isMainThread ? null : fakeParentPort(); + +function getEnvironmentData() { + return process.env; +} + +function setEnvironmentData(env: any) { + process.env = env; +} + +function markAsUntransferable() { + throwNotImplemented("worker_threads.markAsUntransferable"); +} + +function moveMessagePortToContext() { + throwNotImplemented("worker_threads.moveMessagePortToContext"); +} + +const unsupportedOptions = [ + "eval", + "argv", + "execArgv", + "stdin", + "stdout", + "stderr", + "trackedUnmanagedFds", + "resourceLimits", +]; + +class Worker extends EventEmitter { + #worker: WebWorker; + #performance; + #onExitPromise: Promise | number | undefined = undefined; + + constructor(filename: string, options: NodeWorkerOptions = {}) { + super(); + for (const key of unsupportedOptions) { + if (key in options) { + emitWarning("option." + key, `worker_threads.Worker option "${key}" is not implemented.`); + } + } + this.#worker = new WebWorker(filename, options); + this.#worker.addEventListener("close", this.#onClose.bind(this)); + this.#worker.addEventListener("error", this.#onError.bind(this)); + this.#worker.addEventListener("message", this.#onMessage.bind(this)); + this.#worker.addEventListener("messageerror", this.#onMessageError.bind(this)); + this.#worker.addEventListener("open", this.#onOpen.bind(this)); + } + + ref() { + this.#worker.ref(); + } + + unref() { + this.#worker.unref(); + } + + get stdin() { + // TODO: + return null; + } + + get stdout() { + // TODO: + return null; + } + + get stderr() { + // TODO: + return null; + } + + get performance() { + return (this.#performance ??= { + eventLoopUtilization() { + emitWarning("performance", "worker_threads.Worker.performance is not implemented."); + return { + idle: 0, + active: 0, + utilization: 0, + }; + }, + }); + } + + terminate() { + if (this.#onExitPromise) { + return this.#onExitPromise; + } + + const { resolve, promise } = Promise.withResolvers(); + this.#worker.addEventListener( + "close", + event => { + resolve(event.code); + }, + { once: true }, + ); + this.#worker.terminate(); + + return (this.#onExitPromise = promise); + } + + postMessage(...args: [any, any]) { + return this.#worker.postMessage(...args); + } + + #onClose(e) { + this.#onExitPromise = e.code; + this.emit("exit", e.code); + } + + #onError(event: ErrorEvent) { + // TODO: is this right? + this.emit("error", event.error); + } + + #onMessage(event: MessageEvent) { + // TODO: is this right? + this.emit("message", event.data); + } + + #onMessageError(event: MessageEvent) { + // TODO: is this right? + this.emit("messageerror", (event as any).error ?? event.data ?? event); + } + + #onOpen() { + this.emit("online"); + } + + async getHeapSnapshot() { + throwNotImplemented("worker_threads.Worker.getHeapSnapshot"); + } +} +export default { + Worker, + workerData, + parentPort, + resourceLimits, + isMainThread, + MessageChannel, + BroadcastChannel, + MessagePort, + getEnvironmentData, + setEnvironmentData, + getHeapSnapshot() { + return {}; + }, + markAsUntransferable, + moveMessagePortToContext, + receiveMessageOnPort, + SHARE_ENV, + threadId, +}; diff --git a/src/js/node/zlib.js b/src/js/node/zlib.js index 77a9e808993567..9fb9633b91c413 100644 --- a/src/js/node/zlib.js +++ b/src/js/node/zlib.js @@ -3,76 +3,17 @@ // This is a very slow module! // It should really be fixed. It will show up in benchmarking. It also loads // slowly. We need to fix it! -import { default as assert } from "node:assert"; -import * as AssertModule from "node:assert"; -import * as BufferModule from "node:buffer"; -import * as StreamModule from "node:stream"; -import * as Util from "node:util"; +const assert = require("node:assert"); +const BufferModule = require("node:buffer"); +const StreamModule = require("node:stream"); +const Util = require("node:util"); -export var Deflate, - Inflate, - Gzip, - Gunzip, - DeflateRaw, - InflateRaw, - Unzip, - createDeflate, - createInflate, - createDeflateRaw, - createInflateRaw, - createGzip, - createGunzip, - createUnzip, - deflate, - deflateSync, - gzip, - gzipSync, - deflateRaw, - deflateRawSync, - unzip, - unzipSync, - inflate, - inflateSync, - gunzip, - gunzipSync, - inflateRaw, - inflateRawSync, - constants; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; -var __copyProps = (to, from, except, desc) => { - if ((from && typeof from === "object") || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { - get: () => from[key], - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, - }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => ( - __copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default") -); -var __toESM = (mod, isNodeMode, target) => ( - (target = mod != null ? __create(__getProtoOf(mod)) : {}), - __copyProps( - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod, - ) -); -var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - // node_modules/pako/lib/zlib/zstream.js var require_zstream = __commonJS({ "node_modules/pako/lib/zlib/zstream.js"(exports, module2) { @@ -3662,6 +3603,7 @@ var require_binding = __commonJS({ this.pending_close = false; this.gzip_id_bytes_read = 0; } + Zlib.prototype = {}; Zlib.prototype.close = function () { if (this.write_in_progress) { this.pending_close = true; @@ -3974,7 +3916,6 @@ var require_lib = __commonJS({ var Transform = StreamModule.Transform; var binding = require_binding(); var util = Util; - var assert = AssertModule.ok; var kMaxLength = BufferModule.kMaxLength; var kRangeErrorMessage = "Cannot create final Buffer. It would be larger than 0x" + kMaxLength.toString(16) + " bytes"; @@ -4468,37 +4409,4 @@ var require_lib = __commonJS({ }); // zlib.js -var zlib_exports = require_lib(); -zlib_exports[Symbol.for("CommonJS")] = 0; - -export default zlib_exports; - -Deflate = zlib_exports.Deflate; -Inflate = zlib_exports.Inflate; -Gzip = zlib_exports.Gzip; -Gunzip = zlib_exports.Gunzip; -DeflateRaw = zlib_exports.DeflateRaw; -InflateRaw = zlib_exports.InflateRaw; -Unzip = zlib_exports.Unzip; -createDeflate = zlib_exports.createDeflate; -createInflate = zlib_exports.createInflate; -createDeflateRaw = zlib_exports.createDeflateRaw; -createInflateRaw = zlib_exports.createInflateRaw; -createGzip = zlib_exports.createGzip; -createGunzip = zlib_exports.createGunzip; -createUnzip = zlib_exports.createUnzip; -deflate = zlib_exports.deflate; -deflateSync = zlib_exports.deflateSync; -gzip = zlib_exports.gzip; -gzipSync = zlib_exports.gzipSync; -deflateRaw = zlib_exports.deflateRaw; -deflateRawSync = zlib_exports.deflateRawSync; -unzip = zlib_exports.unzip; -unzipSync = zlib_exports.unzipSync; -inflate = zlib_exports.inflate; -inflateSync = zlib_exports.inflateSync; -gunzip = zlib_exports.gunzip; -gunzipSync = zlib_exports.gunzipSync; -inflateRaw = zlib_exports.inflateRaw; -inflateRawSync = zlib_exports.inflateRawSync; -constants = zlib_exports.constants; +export default require_lib(); diff --git a/src/js/out/InternalModuleRegistry+create.h b/src/js/out/InternalModuleRegistry+create.h new file mode 100644 index 00000000000000..7804dd395144a7 --- /dev/null +++ b/src/js/out/InternalModuleRegistry+create.h @@ -0,0 +1,193 @@ +registry->m_internalModule[0].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "bun:ffi"_s, "/Users/dave/code/bun/src/js/out/modules/bun/ffi.js"_s, InternalModuleRegistryConstants::BunFFICode); +}); +registry->m_internalModule[1].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "bun:sqlite"_s, "/Users/dave/code/bun/src/js/out/modules/bun/sqlite.js"_s, InternalModuleRegistryConstants::BunSqliteCode); +}); +registry->m_internalModule[2].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "internal:shared"_s, "/Users/dave/code/bun/src/js/out/modules/internal/shared.js"_s, InternalModuleRegistryConstants::InternalSharedCode); +}); +registry->m_internalModule[3].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:assert"_s, "/Users/dave/code/bun/src/js/out/modules/node/assert.js"_s, InternalModuleRegistryConstants::NodeAssertCode); +}); +registry->m_internalModule[4].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:assert/strict"_s, "/Users/dave/code/bun/src/js/out/modules/node/assert.strict.js"_s, InternalModuleRegistryConstants::NodeAssertStrictCode); +}); +registry->m_internalModule[5].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:async_hooks"_s, "/Users/dave/code/bun/src/js/out/modules/node/async_hooks.js"_s, InternalModuleRegistryConstants::NodeAsyncHooksCode); +}); +registry->m_internalModule[6].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:child_process"_s, "/Users/dave/code/bun/src/js/out/modules/node/child_process.js"_s, InternalModuleRegistryConstants::NodeChildProcessCode); +}); +registry->m_internalModule[7].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:cluster"_s, "/Users/dave/code/bun/src/js/out/modules/node/cluster.js"_s, InternalModuleRegistryConstants::NodeClusterCode); +}); +registry->m_internalModule[8].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:crypto"_s, "/Users/dave/code/bun/src/js/out/modules/node/crypto.js"_s, InternalModuleRegistryConstants::NodeCryptoCode); +}); +registry->m_internalModule[9].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:dgram"_s, "/Users/dave/code/bun/src/js/out/modules/node/dgram.js"_s, InternalModuleRegistryConstants::NodeDgramCode); +}); +registry->m_internalModule[10].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:diagnostics_channel"_s, "/Users/dave/code/bun/src/js/out/modules/node/diagnostics_channel.js"_s, InternalModuleRegistryConstants::NodeDiagnosticsChannelCode); +}); +registry->m_internalModule[11].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:dns"_s, "/Users/dave/code/bun/src/js/out/modules/node/dns.js"_s, InternalModuleRegistryConstants::NodeDNSCode); +}); +registry->m_internalModule[12].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:dns/promises"_s, "/Users/dave/code/bun/src/js/out/modules/node/dns.promises.js"_s, InternalModuleRegistryConstants::NodeDNSPromisesCode); +}); +registry->m_internalModule[13].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:events"_s, "/Users/dave/code/bun/src/js/out/modules/node/events.js"_s, InternalModuleRegistryConstants::NodeEventsCode); +}); +registry->m_internalModule[14].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:fs"_s, "/Users/dave/code/bun/src/js/out/modules/node/fs.js"_s, InternalModuleRegistryConstants::NodeFSCode); +}); +registry->m_internalModule[15].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:fs/promises"_s, "/Users/dave/code/bun/src/js/out/modules/node/fs.promises.js"_s, InternalModuleRegistryConstants::NodeFSPromisesCode); +}); +registry->m_internalModule[16].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:http"_s, "/Users/dave/code/bun/src/js/out/modules/node/http.js"_s, InternalModuleRegistryConstants::NodeHttpCode); +}); +registry->m_internalModule[17].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:http2"_s, "/Users/dave/code/bun/src/js/out/modules/node/http2.js"_s, InternalModuleRegistryConstants::NodeHttp2Code); +}); +registry->m_internalModule[18].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:https"_s, "/Users/dave/code/bun/src/js/out/modules/node/https.js"_s, InternalModuleRegistryConstants::NodeHttpsCode); +}); +registry->m_internalModule[19].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:inspector"_s, "/Users/dave/code/bun/src/js/out/modules/node/inspector.js"_s, InternalModuleRegistryConstants::NodeInspectorCode); +}); +registry->m_internalModule[20].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:net"_s, "/Users/dave/code/bun/src/js/out/modules/node/net.js"_s, InternalModuleRegistryConstants::NodeNetCode); +}); +registry->m_internalModule[21].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:os"_s, "/Users/dave/code/bun/src/js/out/modules/node/os.js"_s, InternalModuleRegistryConstants::NodeOSCode); +}); +registry->m_internalModule[22].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:path/posix"_s, "/Users/dave/code/bun/src/js/out/modules/node/path.posix.js"_s, InternalModuleRegistryConstants::NodePathPosixCode); +}); +registry->m_internalModule[23].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:path"_s, "/Users/dave/code/bun/src/js/out/modules/node/path.js"_s, InternalModuleRegistryConstants::NodePathCode); +}); +registry->m_internalModule[24].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:path/win32"_s, "/Users/dave/code/bun/src/js/out/modules/node/path.win32.js"_s, InternalModuleRegistryConstants::NodePathWin32Code); +}); +registry->m_internalModule[25].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:perf_hooks"_s, "/Users/dave/code/bun/src/js/out/modules/node/perf_hooks.js"_s, InternalModuleRegistryConstants::NodePerfHooksCode); +}); +registry->m_internalModule[26].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:readline"_s, "/Users/dave/code/bun/src/js/out/modules/node/readline.js"_s, InternalModuleRegistryConstants::NodeReadlineCode); +}); +registry->m_internalModule[27].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:readline/promises"_s, "/Users/dave/code/bun/src/js/out/modules/node/readline.promises.js"_s, InternalModuleRegistryConstants::NodeReadlinePromisesCode); +}); +registry->m_internalModule[28].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:repl"_s, "/Users/dave/code/bun/src/js/out/modules/node/repl.js"_s, InternalModuleRegistryConstants::NodeReplCode); +}); +registry->m_internalModule[29].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:stream/consumers"_s, "/Users/dave/code/bun/src/js/out/modules/node/stream.consumers.js"_s, InternalModuleRegistryConstants::NodeStreamConsumersCode); +}); +registry->m_internalModule[30].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:stream"_s, "/Users/dave/code/bun/src/js/out/modules/node/stream.js"_s, InternalModuleRegistryConstants::NodeStreamCode); +}); +registry->m_internalModule[31].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:stream/promises"_s, "/Users/dave/code/bun/src/js/out/modules/node/stream.promises.js"_s, InternalModuleRegistryConstants::NodeStreamPromisesCode); +}); +registry->m_internalModule[32].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:stream/web"_s, "/Users/dave/code/bun/src/js/out/modules/node/stream.web.js"_s, InternalModuleRegistryConstants::NodeStreamWebCode); +}); +registry->m_internalModule[33].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:timers"_s, "/Users/dave/code/bun/src/js/out/modules/node/timers.js"_s, InternalModuleRegistryConstants::NodeTimersCode); +}); +registry->m_internalModule[34].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:timers/promises"_s, "/Users/dave/code/bun/src/js/out/modules/node/timers.promises.js"_s, InternalModuleRegistryConstants::NodeTimersPromisesCode); +}); +registry->m_internalModule[35].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:tls"_s, "/Users/dave/code/bun/src/js/out/modules/node/tls.js"_s, InternalModuleRegistryConstants::NodeTLSCode); +}); +registry->m_internalModule[36].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:trace_events"_s, "/Users/dave/code/bun/src/js/out/modules/node/trace_events.js"_s, InternalModuleRegistryConstants::NodeTraceEventsCode); +}); +registry->m_internalModule[37].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:url"_s, "/Users/dave/code/bun/src/js/out/modules/node/url.js"_s, InternalModuleRegistryConstants::NodeUrlCode); +}); +registry->m_internalModule[38].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:util"_s, "/Users/dave/code/bun/src/js/out/modules/node/util.js"_s, InternalModuleRegistryConstants::NodeUtilCode); +}); +registry->m_internalModule[39].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:v8"_s, "/Users/dave/code/bun/src/js/out/modules/node/v8.js"_s, InternalModuleRegistryConstants::NodeV8Code); +}); +registry->m_internalModule[40].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:vm"_s, "/Users/dave/code/bun/src/js/out/modules/node/vm.js"_s, InternalModuleRegistryConstants::NodeVMCode); +}); +registry->m_internalModule[41].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:wasi"_s, "/Users/dave/code/bun/src/js/out/modules/node/wasi.js"_s, InternalModuleRegistryConstants::NodeWasiCode); +}); +registry->m_internalModule[42].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "node:zlib"_s, "/Users/dave/code/bun/src/js/out/modules/node/zlib.js"_s, InternalModuleRegistryConstants::NodeZlibCode); +}); +registry->m_internalModule[43].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "depd"_s, "/Users/dave/code/bun/src/js/out/modules/thirdparty/depd.js"_s, InternalModuleRegistryConstants::ThirdpartyDepdCode); +}); +registry->m_internalModule[44].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "detect-libc"_s, "/Users/dave/code/bun/src/js/out/modules/thirdparty/detect-libc.js"_s, InternalModuleRegistryConstants::ThirdpartyDetectLibcCode); +}); +registry->m_internalModule[45].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "detect-libc/linux"_s, "/Users/dave/code/bun/src/js/out/modules/thirdparty/detect-libc.linux.js"_s, InternalModuleRegistryConstants::ThirdpartyDetectLibcLinuxCode); +}); +registry->m_internalModule[46].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "undici"_s, "/Users/dave/code/bun/src/js/out/modules/thirdparty/undici.js"_s, InternalModuleRegistryConstants::ThirdpartyUndiciCode); +}); +registry->m_internalModule[47].initLater([](const JSC::LazyProperty::Initializer& init) { + INTERNAL_MODULE_REGISTRY_GENERATE(init, "ws"_s, "/Users/dave/code/bun/src/js/out/modules/thirdparty/ws.js"_s, InternalModuleRegistryConstants::ThirdpartyWSCode); +}); + +registry->m_internalFields[0].set(vm, this, jsUndefined()) +registry->m_internalFields[1].set(vm, this, jsUndefined()) +registry->m_internalFields[2].set(vm, this, jsUndefined()) +registry->m_internalFields[3].set(vm, this, jsUndefined()) +registry->m_internalFields[4].set(vm, this, jsUndefined()) +registry->m_internalFields[5].set(vm, this, jsUndefined()) +registry->m_internalFields[6].set(vm, this, jsUndefined()) +registry->m_internalFields[7].set(vm, this, jsUndefined()) +registry->m_internalFields[8].set(vm, this, jsUndefined()) +registry->m_internalFields[9].set(vm, this, jsUndefined()) +registry->m_internalFields[10].set(vm, this, jsUndefined()) +registry->m_internalFields[11].set(vm, this, jsUndefined()) +registry->m_internalFields[12].set(vm, this, jsUndefined()) +registry->m_internalFields[13].set(vm, this, jsUndefined()) +registry->m_internalFields[14].set(vm, this, jsUndefined()) +registry->m_internalFields[15].set(vm, this, jsUndefined()) +registry->m_internalFields[16].set(vm, this, jsUndefined()) +registry->m_internalFields[17].set(vm, this, jsUndefined()) +registry->m_internalFields[18].set(vm, this, jsUndefined()) +registry->m_internalFields[19].set(vm, this, jsUndefined()) +registry->m_internalFields[20].set(vm, this, jsUndefined()) +registry->m_internalFields[21].set(vm, this, jsUndefined()) +registry->m_internalFields[22].set(vm, this, jsUndefined()) +registry->m_internalFields[23].set(vm, this, jsUndefined()) +registry->m_internalFields[24].set(vm, this, jsUndefined()) +registry->m_internalFields[25].set(vm, this, jsUndefined()) +registry->m_internalFields[26].set(vm, this, jsUndefined()) +registry->m_internalFields[27].set(vm, this, jsUndefined()) +registry->m_internalFields[28].set(vm, this, jsUndefined()) +registry->m_internalFields[29].set(vm, this, jsUndefined()) +registry->m_internalFields[30].set(vm, this, jsUndefined()) +registry->m_internalFields[31].set(vm, this, jsUndefined()) +registry->m_internalFields[32].set(vm, this, jsUndefined()) +registry->m_internalFields[33].set(vm, this, jsUndefined()) +registry->m_internalFields[34].set(vm, this, jsUndefined()) +registry->m_internalFields[35].set(vm, this, jsUndefined()) +registry->m_internalFields[36].set(vm, this, jsUndefined()) +registry->m_internalFields[37].set(vm, this, jsUndefined()) +registry->m_internalFields[38].set(vm, this, jsUndefined()) +registry->m_internalFields[39].set(vm, this, jsUndefined()) +registry->m_internalFields[40].set(vm, this, jsUndefined()) +registry->m_internalFields[41].set(vm, this, jsUndefined()) +registry->m_internalFields[42].set(vm, this, jsUndefined()) +registry->m_internalFields[43].set(vm, this, jsUndefined()) +registry->m_internalFields[44].set(vm, this, jsUndefined()) +registry->m_internalFields[45].set(vm, this, jsUndefined()) +registry->m_internalFields[46].set(vm, this, jsUndefined()) +registry->m_internalFields[47].set(vm, this, jsUndefined()) diff --git a/src/js/out/InternalModuleRegistry+createInternalModuleById.h b/src/js/out/InternalModuleRegistry+createInternalModuleById.h new file mode 100644 index 00000000000000..e64c71ff44f3d0 --- /dev/null +++ b/src/js/out/InternalModuleRegistry+createInternalModuleById.h @@ -0,0 +1,174 @@ +JSValue InternalModuleRegistry::createInternalModuleById(JSGlobalObject* globalObject, VM& vm, Field id) +{ + switch (id) { + // JS internal modules + case Field::BunFFI: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "bun:ffi"_s, "bun/ffi.js"_s, InternalModuleRegistryConstants::BunFFICode); + } + case Field::BunSqlite: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "bun:sqlite"_s, "bun/sqlite.js"_s, InternalModuleRegistryConstants::BunSqliteCode); + } + case Field::InternalShared: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "internal:shared"_s, "internal/shared.js"_s, InternalModuleRegistryConstants::InternalSharedCode); + } + case Field::NodeAssert: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:assert"_s, "node/assert.js"_s, InternalModuleRegistryConstants::NodeAssertCode); + } + case Field::NodeAssertStrict: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:assert/strict"_s, "node/assert.strict.js"_s, InternalModuleRegistryConstants::NodeAssertStrictCode); + } + case Field::NodeAsyncHooks: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:async_hooks"_s, "node/async_hooks.js"_s, InternalModuleRegistryConstants::NodeAsyncHooksCode); + } + case Field::NodeChildProcess: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:child_process"_s, "node/child_process.js"_s, InternalModuleRegistryConstants::NodeChildProcessCode); + } + case Field::NodeCluster: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:cluster"_s, "node/cluster.js"_s, InternalModuleRegistryConstants::NodeClusterCode); + } + case Field::NodeConsole: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:console"_s, "node/console.js"_s, InternalModuleRegistryConstants::NodeConsoleCode); + } + case Field::NodeCrypto: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:crypto"_s, "node/crypto.js"_s, InternalModuleRegistryConstants::NodeCryptoCode); + } + case Field::NodeDgram: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:dgram"_s, "node/dgram.js"_s, InternalModuleRegistryConstants::NodeDgramCode); + } + case Field::NodeDiagnosticsChannel: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:diagnostics_channel"_s, "node/diagnostics_channel.js"_s, InternalModuleRegistryConstants::NodeDiagnosticsChannelCode); + } + case Field::NodeDNS: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:dns"_s, "node/dns.js"_s, InternalModuleRegistryConstants::NodeDNSCode); + } + case Field::NodeDNSPromises: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:dns/promises"_s, "node/dns.promises.js"_s, InternalModuleRegistryConstants::NodeDNSPromisesCode); + } + case Field::NodeDomain: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:domain"_s, "node/domain.js"_s, InternalModuleRegistryConstants::NodeDomainCode); + } + case Field::NodeEvents: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:events"_s, "node/events.js"_s, InternalModuleRegistryConstants::NodeEventsCode); + } + case Field::NodeFS: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:fs"_s, "node/fs.js"_s, InternalModuleRegistryConstants::NodeFSCode); + } + case Field::NodeFSPromises: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:fs/promises"_s, "node/fs.promises.js"_s, InternalModuleRegistryConstants::NodeFSPromisesCode); + } + case Field::NodeHttp: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:http"_s, "node/http.js"_s, InternalModuleRegistryConstants::NodeHttpCode); + } + case Field::NodeHttp2: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:http2"_s, "node/http2.js"_s, InternalModuleRegistryConstants::NodeHttp2Code); + } + case Field::NodeHttps: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:https"_s, "node/https.js"_s, InternalModuleRegistryConstants::NodeHttpsCode); + } + case Field::NodeInspector: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:inspector"_s, "node/inspector.js"_s, InternalModuleRegistryConstants::NodeInspectorCode); + } + case Field::NodeNet: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:net"_s, "node/net.js"_s, InternalModuleRegistryConstants::NodeNetCode); + } + case Field::NodeOS: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:os"_s, "node/os.js"_s, InternalModuleRegistryConstants::NodeOSCode); + } + case Field::NodePathPosix: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:path/posix"_s, "node/path.posix.js"_s, InternalModuleRegistryConstants::NodePathPosixCode); + } + case Field::NodePath: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:path"_s, "node/path.js"_s, InternalModuleRegistryConstants::NodePathCode); + } + case Field::NodePathWin32: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:path/win32"_s, "node/path.win32.js"_s, InternalModuleRegistryConstants::NodePathWin32Code); + } + case Field::NodePerfHooks: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:perf_hooks"_s, "node/perf_hooks.js"_s, InternalModuleRegistryConstants::NodePerfHooksCode); + } + case Field::NodePunycode: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:punycode"_s, "node/punycode.js"_s, InternalModuleRegistryConstants::NodePunycodeCode); + } + case Field::NodeQuerystring: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:querystring"_s, "node/querystring.js"_s, InternalModuleRegistryConstants::NodeQuerystringCode); + } + case Field::NodeReadline: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:readline"_s, "node/readline.js"_s, InternalModuleRegistryConstants::NodeReadlineCode); + } + case Field::NodeReadlinePromises: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:readline/promises"_s, "node/readline.promises.js"_s, InternalModuleRegistryConstants::NodeReadlinePromisesCode); + } + case Field::NodeRepl: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:repl"_s, "node/repl.js"_s, InternalModuleRegistryConstants::NodeReplCode); + } + case Field::NodeStreamConsumers: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:stream/consumers"_s, "node/stream.consumers.js"_s, InternalModuleRegistryConstants::NodeStreamConsumersCode); + } + case Field::NodeStream: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:stream"_s, "node/stream.js"_s, InternalModuleRegistryConstants::NodeStreamCode); + } + case Field::NodeStreamPromises: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:stream/promises"_s, "node/stream.promises.js"_s, InternalModuleRegistryConstants::NodeStreamPromisesCode); + } + case Field::NodeStreamWeb: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:stream/web"_s, "node/stream.web.js"_s, InternalModuleRegistryConstants::NodeStreamWebCode); + } + case Field::NodeTimers: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:timers"_s, "node/timers.js"_s, InternalModuleRegistryConstants::NodeTimersCode); + } + case Field::NodeTimersPromises: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:timers/promises"_s, "node/timers.promises.js"_s, InternalModuleRegistryConstants::NodeTimersPromisesCode); + } + case Field::NodeTLS: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:tls"_s, "node/tls.js"_s, InternalModuleRegistryConstants::NodeTLSCode); + } + case Field::NodeTraceEvents: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:trace_events"_s, "node/trace_events.js"_s, InternalModuleRegistryConstants::NodeTraceEventsCode); + } + case Field::NodeUrl: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:url"_s, "node/url.js"_s, InternalModuleRegistryConstants::NodeUrlCode); + } + case Field::NodeUtil: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:util"_s, "node/util.js"_s, InternalModuleRegistryConstants::NodeUtilCode); + } + case Field::NodeV8: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:v8"_s, "node/v8.js"_s, InternalModuleRegistryConstants::NodeV8Code); + } + case Field::NodeVM: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:vm"_s, "node/vm.js"_s, InternalModuleRegistryConstants::NodeVMCode); + } + case Field::NodeWasi: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:wasi"_s, "node/wasi.js"_s, InternalModuleRegistryConstants::NodeWasiCode); + } + case Field::NodeWorkerThreads: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:worker_threads"_s, "node/worker_threads.js"_s, InternalModuleRegistryConstants::NodeWorkerThreadsCode); + } + case Field::NodeZlib: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node:zlib"_s, "node/zlib.js"_s, InternalModuleRegistryConstants::NodeZlibCode); + } + case Field::ThirdpartyDepd: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "depd"_s, "thirdparty/depd.js"_s, InternalModuleRegistryConstants::ThirdpartyDepdCode); + } + case Field::ThirdpartyDetectLibc: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "detect-libc"_s, "thirdparty/detect-libc.js"_s, InternalModuleRegistryConstants::ThirdpartyDetectLibcCode); + } + case Field::ThirdpartyDetectLibcLinux: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "detect-libc/linux"_s, "thirdparty/detect-libc.linux.js"_s, InternalModuleRegistryConstants::ThirdpartyDetectLibcLinuxCode); + } + case Field::ThirdpartyIsomorphicFetch: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "isomorphic-fetch"_s, "thirdparty/isomorphic-fetch.js"_s, InternalModuleRegistryConstants::ThirdpartyIsomorphicFetchCode); + } + case Field::ThirdpartyNodeFetch: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "node-fetch"_s, "thirdparty/node-fetch.js"_s, InternalModuleRegistryConstants::ThirdpartyNodeFetchCode); + } + case Field::ThirdpartyUndici: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "undici"_s, "thirdparty/undici.js"_s, InternalModuleRegistryConstants::ThirdpartyUndiciCode); + } + case Field::ThirdpartyVercelFetch: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "vercel_fetch"_s, "thirdparty/vercel_fetch.js"_s, InternalModuleRegistryConstants::ThirdpartyVercelFetchCode); + } + case Field::ThirdpartyWS: { + INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "ws"_s, "thirdparty/ws.js"_s, InternalModuleRegistryConstants::ThirdpartyWSCode); + } + } +} diff --git a/src/js/out/InternalModuleRegistry+enum.h b/src/js/out/InternalModuleRegistry+enum.h new file mode 100644 index 00000000000000..7d72e3d261081f --- /dev/null +++ b/src/js/out/InternalModuleRegistry+enum.h @@ -0,0 +1,57 @@ +BunFFI = 0, +BunSqlite = 1, +InternalShared = 2, +NodeAssert = 3, +NodeAssertStrict = 4, +NodeAsyncHooks = 5, +NodeChildProcess = 6, +NodeCluster = 7, +NodeConsole = 8, +NodeCrypto = 9, +NodeDgram = 10, +NodeDiagnosticsChannel = 11, +NodeDNS = 12, +NodeDNSPromises = 13, +NodeDomain = 14, +NodeEvents = 15, +NodeFS = 16, +NodeFSPromises = 17, +NodeHttp = 18, +NodeHttp2 = 19, +NodeHttps = 20, +NodeInspector = 21, +NodeNet = 22, +NodeOS = 23, +NodePathPosix = 24, +NodePath = 25, +NodePathWin32 = 26, +NodePerfHooks = 27, +NodePunycode = 28, +NodeQuerystring = 29, +NodeReadline = 30, +NodeReadlinePromises = 31, +NodeRepl = 32, +NodeStreamConsumers = 33, +NodeStream = 34, +NodeStreamPromises = 35, +NodeStreamWeb = 36, +NodeTimers = 37, +NodeTimersPromises = 38, +NodeTLS = 39, +NodeTraceEvents = 40, +NodeUrl = 41, +NodeUtil = 42, +NodeV8 = 43, +NodeVM = 44, +NodeWasi = 45, +NodeWorkerThreads = 46, +NodeZlib = 47, +ThirdpartyDepd = 48, +ThirdpartyDetectLibc = 49, +ThirdpartyDetectLibcLinux = 50, +ThirdpartyIsomorphicFetch = 51, +ThirdpartyNodeFetch = 52, +ThirdpartyUndici = 53, +ThirdpartyVercelFetch = 54, +ThirdpartyWS = 55, + diff --git a/src/js/out/InternalModuleRegistry+numberOfModules.h b/src/js/out/InternalModuleRegistry+numberOfModules.h new file mode 100644 index 00000000000000..67d159029849d9 --- /dev/null +++ b/src/js/out/InternalModuleRegistry+numberOfModules.h @@ -0,0 +1 @@ +#define BUN_INTERNAL_MODULE_COUNT 56 diff --git a/src/js/out/InternalModuleRegistry+visitImpl.h b/src/js/out/InternalModuleRegistry+visitImpl.h new file mode 100644 index 00000000000000..0c4a8f7659246f --- /dev/null +++ b/src/js/out/InternalModuleRegistry+visitImpl.h @@ -0,0 +1,48 @@ +m_internalModule[0].visit(visitor); +m_internalModule[1].visit(visitor); +m_internalModule[2].visit(visitor); +m_internalModule[3].visit(visitor); +m_internalModule[4].visit(visitor); +m_internalModule[5].visit(visitor); +m_internalModule[6].visit(visitor); +m_internalModule[7].visit(visitor); +m_internalModule[8].visit(visitor); +m_internalModule[9].visit(visitor); +m_internalModule[10].visit(visitor); +m_internalModule[11].visit(visitor); +m_internalModule[12].visit(visitor); +m_internalModule[13].visit(visitor); +m_internalModule[14].visit(visitor); +m_internalModule[15].visit(visitor); +m_internalModule[16].visit(visitor); +m_internalModule[17].visit(visitor); +m_internalModule[18].visit(visitor); +m_internalModule[19].visit(visitor); +m_internalModule[20].visit(visitor); +m_internalModule[21].visit(visitor); +m_internalModule[22].visit(visitor); +m_internalModule[23].visit(visitor); +m_internalModule[24].visit(visitor); +m_internalModule[25].visit(visitor); +m_internalModule[26].visit(visitor); +m_internalModule[27].visit(visitor); +m_internalModule[28].visit(visitor); +m_internalModule[29].visit(visitor); +m_internalModule[30].visit(visitor); +m_internalModule[31].visit(visitor); +m_internalModule[32].visit(visitor); +m_internalModule[33].visit(visitor); +m_internalModule[34].visit(visitor); +m_internalModule[35].visit(visitor); +m_internalModule[36].visit(visitor); +m_internalModule[37].visit(visitor); +m_internalModule[38].visit(visitor); +m_internalModule[39].visit(visitor); +m_internalModule[40].visit(visitor); +m_internalModule[41].visit(visitor); +m_internalModule[42].visit(visitor); +m_internalModule[43].visit(visitor); +m_internalModule[44].visit(visitor); +m_internalModule[45].visit(visitor); +m_internalModule[46].visit(visitor); +m_internalModule[47].visit(visitor); diff --git a/src/js/out/InternalModuleRegistryConstants.h b/src/js/out/InternalModuleRegistryConstants.h new file mode 100644 index 00000000000000..99140663ddd1ad --- /dev/null +++ b/src/js/out/InternalModuleRegistryConstants.h @@ -0,0 +1,685 @@ +#pragma once + + namespace Bun { + namespace InternalModuleRegistryConstants { + + #if __APPLE__ + // +static constexpr ASCIILiteral BunFFICode = "(function (){\"use strict\";const FFIType={\"0\":0,\"1\":1,\"2\":2,\"3\":3,\"4\":4,\"5\":5,\"6\":6,\"7\":7,\"8\":8,\"9\":9,\"10\":10,\"11\":11,\"12\":12,\"13\":13,\"14\":14,\"15\":15,\"16\":16,\"17\":17,bool:11,c_int:5,c_uint:6,char:0,\"char*\":12,double:9,f32:10,f64:9,float:10,i16:3,i32:5,i64:7,i8:1,int:5,int16_t:3,int32_t:5,int64_t:7,int8_t:1,isize:7,u16:4,u32:6,u64:8,u8:2,uint16_t:4,uint32_t:6,uint64_t:8,uint8_t:2,usize:8,\"void*\":12,ptr:12,pointer:12,void:13,cstring:14,i64_fast:15,u64_fast:16,function:17,callback:17,fn:17};var ffi=globalThis.Bun.FFI;const ptr=(arg1,arg2)=>typeof arg2===\"undefined\"\?ffi.ptr(arg1):ffi.ptr(arg1,arg2),toBuffer=ffi.toBuffer,toArrayBuffer=ffi.toArrayBuffer,viewSource=ffi.viewSource,BunCString=ffi.CString,nativeLinkSymbols=ffi.linkSymbols,nativeDLOpen=ffi.dlopen,nativeCallback=ffi.callback,closeCallback=ffi.closeCallback;delete ffi.callback,delete ffi.closeCallback;class JSCallback{constructor(cb,options){const{ctx,ptr:ptr2}=nativeCallback(options,cb);this.#ctx=ctx,this.ptr=ptr2,this.#threadsafe=!!options\?.threadsafe}ptr;#ctx;#threadsafe;get threadsafe(){return this.#threadsafe}[Symbol.toPrimitive](){const{ptr:ptr2}=this;return typeof ptr2===\"number\"\?ptr2:0}close(){const ctx=this.#ctx;if(this.ptr=null,this.#ctx=null,ctx)closeCallback(ctx)}}class CString extends String{constructor(ptr2,byteOffset,byteLength){super(ptr2\?typeof byteLength===\"number\"&&Number.isSafeInteger(byteLength)\?new BunCString(ptr2,byteOffset||0,byteLength):new BunCString(ptr2):\"\");if(this.ptr=typeof ptr2===\"number\"\?ptr2:0,typeof byteOffset!==\"undefined\")this.byteOffset=byteOffset;if(typeof byteLength!==\"undefined\")this.byteLength=byteLength}ptr;byteOffset;byteLength;#cachedArrayBuffer;get arrayBuffer(){if(this.#cachedArrayBuffer)return this.#cachedArrayBuffer;if(!this.ptr)return this.#cachedArrayBuffer=new ArrayBuffer(0);return this.#cachedArrayBuffer=toArrayBuffer(this.ptr,this.byteOffset,this.byteLength)}}Object.defineProperty(globalThis,\"__GlobalBunCString\",{value:CString,enumerable:!1,configurable:!1});const ffiWrappers=new Array(18);var char=\"val|0\";ffiWrappers.fill(char),ffiWrappers[FFIType.uint8_t]=\"val<0\?0:val>=255\?255:val|0\",ffiWrappers[FFIType.int16_t]=\"val<=-32768\?-32768:val>=32768\?32768:val|0\",ffiWrappers[FFIType.uint16_t]=\"val<=0\?0:val>=65536\?65536:val|0\",ffiWrappers[FFIType.int32_t]=\"val|0\",ffiWrappers[FFIType.uint32_t]=\"val<=0\?0:val>=0xffffffff\?0xffffffff:+val||0\",ffiWrappers[FFIType.i64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.i64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.u64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= 0) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.int64_t]=`{\n if (typeof val === \"bigint\") {\n return val;\n }\n\n if (typeof val === \"number\") {\n return BigInt(val || 0);\n }\n\n return BigInt(+val || 0);\n}`,ffiWrappers[FFIType.uint64_t]=`{\n if (typeof val === \"bigint\") {\n return val;\n }\n\n if (typeof val === \"number\") {\n return val <= 0 \? BigInt(0) : BigInt(val || 0);\n }\n\n return BigInt(+val || 0);\n}`,ffiWrappers[FFIType.u64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(0)) return Number(val);\n return val;\n }\n\n return typeof val === \"number\" \? (val <= 0 \? 0 : +val || 0) : +val || 0;\n}`,ffiWrappers[FFIType.uint16_t]=`{\n const ret = (typeof val === \"bigint\" \? Number(val) : val) | 0;\n return ret <= 0 \? 0 : ret > 0xffff \? 0xffff : ret;\n}`,ffiWrappers[FFIType.double]=`{\n if (typeof val === \"bigint\") {\n if (val.valueOf() < BigInt(Number.MAX_VALUE)) {\n return Math.abs(Number(val).valueOf()) + 0.00000000000001 - 0.00000000000001;\n }\n }\n\n if (!val) {\n return 0 + 0.00000000000001 - 0.00000000000001;\n }\n\n return val + 0.00000000000001 - 0.00000000000001;\n}`,ffiWrappers[FFIType.float]=ffiWrappers[10]=`{\n return Math.fround(val);\n}`,ffiWrappers[FFIType.bool]=`{\n return !!val;\n}`,Object.defineProperty(globalThis,\"__GlobalBunFFIPtrFunctionForWrapper\",{value:ptr,enumerable:!1,configurable:!0}),ffiWrappers[FFIType.cstring]=ffiWrappers[FFIType.pointer]=`{\n if (typeof val === \"number\") return val;\n if (!val) {\n return null;\n }\n\n if (ArrayBuffer.isView(val) || val instanceof ArrayBuffer) {\n return __GlobalBunFFIPtrFunctionForWrapper(val);\n }\n\n if (typeof val === \"string\") {\n throw new TypeError(\"To convert a string to a pointer, encode it as a buffer\");\n }\n\n throw new TypeError(\\`Unable to convert \\${ val } to a pointer\\`);\n}`,ffiWrappers[FFIType.function]=`{\n if (typeof val === \"number\") {\n return val;\n }\n\n if (typeof val === \"bigint\") {\n return Number(val);\n }\n\n var ptr = val && val.ptr;\n\n if (!ptr) {\n throw new TypeError(\"Expected function to be a JSCallback or a number\");\n }\n\n return ptr;\n}`;function FFIBuilder(params,returnType,functionToCall,name){const hasReturnType=typeof FFIType[returnType]===\"number\"&&FFIType[returnType]!==FFIType.void;var paramNames=new Array(params.length),args=new Array(params.length);for(let i=0;i${wrapper})(p${i})`;else @throwTypeError(`Unsupported type ${params[i]}. Must be one of: ${Object.keys(FFIType).sort().join(\", \")}`)}var code=`functionToCall(${args.join(\", \")})`;if(hasReturnType)if(FFIType[returnType]===FFIType.cstring)code=`return new __GlobalBunCString(${code})`;else code=`return ${code}`;var func=new Function(\"functionToCall\",...paramNames,code);Object.defineProperty(func,\"name\",{value:name});var wrap;switch(paramNames.length){case 0:wrap=()=>func(functionToCall);break;case 1:wrap=(arg1)=>func(functionToCall,arg1);break;case 2:wrap=(arg1,arg2)=>func(functionToCall,arg1,arg2);break;case 3:wrap=(arg1,arg2,arg3)=>func(functionToCall,arg1,arg2,arg3);break;case 4:wrap=(arg1,arg2,arg3,arg4)=>func(functionToCall,arg1,arg2,arg3,arg4);break;case 5:wrap=(arg1,arg2,arg3,arg4,arg5)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5);break;case 6:wrap=(arg1,arg2,arg3,arg4,arg5,arg6)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6);break;case 7:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7);break;case 8:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);break;case 9:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);break;default:{wrap=(...args2)=>func(functionToCall,...args2);break}}return wrap.native=functionToCall,wrap.ptr=functionToCall.ptr,wrap}const native={dlopen:nativeDLOpen,callback:()=>{throw new Error(\"Deprecated. Use new JSCallback(options, fn) instead\")}};function dlopen(path,options){const result=nativeDLOpen(path,options);for(let key in result.symbols){var symbol=result.symbols[key];if(options[key]\?.args\?.length||FFIType[options[key]\?.returns]===FFIType.cstring)result.symbols[key]=FFIBuilder(options[key].args\?\?[],options[key].returns\?\?FFIType.void,symbol,path.includes(\"/\")\?`${key} (${path.split(\"/\").pop()})`:`${key} (${path})`);else result.symbols[key].native=result.symbols[key]}return result}function linkSymbols(options){const result=nativeLinkSymbols(options);for(let key in result.symbols){var symbol=result.symbols[key];if(options[key]\?.args\?.length||FFIType[options[key]\?.returns]===FFIType.cstring)result.symbols[key]=FFIBuilder(options[key].args\?\?[],options[key].returns\?\?FFIType.void,symbol,key);else result.symbols[key].native=result.symbols[key]}return result}var cFunctionI=0,cFunctionRegistry;function onCloseCFunction(close){close()}function CFunction(options){const identifier=`CFunction${cFunctionI++}`;var result=linkSymbols({[identifier]:options}),hasClosed=!1,close=result.close;return result.symbols[identifier].close=()=>{if(hasClosed||!close)return;hasClosed=!0,close(),close=void 0},cFunctionRegistry||=new FinalizationRegistry(onCloseCFunction),cFunctionRegistry.register(result.symbols[identifier],result.symbols[identifier].close),result.symbols[identifier]}const read=ffi.read;return{CFunction,CString,FFIType,JSCallback,dlopen,linkSymbols,native,ptr,read,suffix:\"dylib\",toArrayBuffer,toBuffer,viewSource}})\n"_s; +// + +// +static constexpr ASCIILiteral BunSqliteCode = "(function (){\"use strict\";var defineProperties=Object.defineProperties,toStringTag=Symbol.toStringTag,isArray=Array.isArray,isTypedArray=ArrayBuffer.isView;const constants={SQLITE_OPEN_READONLY:1,SQLITE_OPEN_READWRITE:2,SQLITE_OPEN_CREATE:4,SQLITE_OPEN_DELETEONCLOSE:8,SQLITE_OPEN_EXCLUSIVE:16,SQLITE_OPEN_AUTOPROXY:32,SQLITE_OPEN_URI:64,SQLITE_OPEN_MEMORY:128,SQLITE_OPEN_MAIN_DB:256,SQLITE_OPEN_TEMP_DB:512,SQLITE_OPEN_TRANSIENT_DB:1024,SQLITE_OPEN_MAIN_JOURNAL:2048,SQLITE_OPEN_TEMP_JOURNAL:4096,SQLITE_OPEN_SUBJOURNAL:8192,SQLITE_OPEN_SUPER_JOURNAL:16384,SQLITE_OPEN_NOMUTEX:32768,SQLITE_OPEN_FULLMUTEX:65536,SQLITE_OPEN_SHAREDCACHE:131072,SQLITE_OPEN_PRIVATECACHE:262144,SQLITE_OPEN_WAL:524288,SQLITE_OPEN_NOFOLLOW:16777216,SQLITE_OPEN_EXRESCODE:33554432,SQLITE_PREPARE_PERSISTENT:1,SQLITE_PREPARE_NORMALIZE:2,SQLITE_PREPARE_NO_VTAB:4};var SQL,controllers;class Statement{constructor(raw){switch(this.#raw=raw,raw.paramsCount){case 0:{this.get=this.#getNoArgs,this.all=this.#allNoArgs,this.values=this.#valuesNoArgs,this.run=this.#runNoArgs;break}default:{this.get=this.#get,this.all=this.#all,this.values=this.#values,this.run=this.#run;break}}}#raw;get;all;values;run;isFinalized=!1;toJSON(){return{sql:this.native.toString(),isFinalized:this.isFinalized,paramsCount:this.paramsCount,columnNames:this.columnNames}}get[toStringTag](){return`\"${this.native.toString()}\"`}toString(){return this.native.toString()}get native(){return this.#raw}#getNoArgs(){return this.#raw.get()}#allNoArgs(){return this.#raw.all()}#valuesNoArgs(){return this.#raw.values()}#runNoArgs(){this.#raw.run()}#get(...args){if(args.length===0)return this.#getNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.get(args):this.#raw.get(...args)}#all(...args){if(args.length===0)return this.#allNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.all(args):this.#raw.all(...args)}#values(...args){if(args.length===0)return this.#valuesNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.values(args):this.#raw.values(...args)}#run(...args){if(args.length===0)return this.#runNoArgs();var arg0=args[0];!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.run(args):this.#raw.run(...args)}get columnNames(){return this.#raw.columns}get paramsCount(){return this.#raw.paramsCount}finalize(...args){return this.isFinalized=!0,this.#raw.finalize(...args)}}var cachedCount=Symbol.for(\"Bun.Database.cache.count\");class Database{constructor(filenameGiven,options){if(typeof filenameGiven===\"undefined\");else if(typeof filenameGiven!==\"string\"){if(isTypedArray(filenameGiven)){this.#handle=Database.deserialize(filenameGiven,typeof options===\"object\"&&options\?!!options.readonly:((options|0)&constants.SQLITE_OPEN_READONLY)!=0),this.filename=\":memory:\";return}@throwTypeError(`Expected 'filename' to be a string, got '${typeof filenameGiven}'`)}var filename=typeof filenameGiven===\"string\"\?filenameGiven.trim():\":memory:\",flags=constants.SQLITE_OPEN_READWRITE|constants.SQLITE_OPEN_CREATE;if(typeof options===\"object\"&&options){if(flags=0,options.readonly)flags=constants.SQLITE_OPEN_READONLY;if(\"readOnly\"in options)@throwTypeError('Misspelled option \"readOnly\" should be \"readonly\"');if(options.create)flags=constants.SQLITE_OPEN_READWRITE|constants.SQLITE_OPEN_CREATE;if(options.readwrite)flags|=constants.SQLITE_OPEN_READWRITE}else if(typeof options===\"number\")flags=options;const anonymous=filename===\"\"||filename===\":memory:\";if(anonymous&&(flags&constants.SQLITE_OPEN_READONLY)!==0)throw new Error(\"Cannot open an anonymous database in read-only mode.\");if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");this.#handle=SQL.open(anonymous\?\":memory:\":filename,flags),this.filename=filename}#handle;#cachedQueriesKeys=[];#cachedQueriesLengths=[];#cachedQueriesValues=[];filename;get handle(){return this.#handle}get inTransaction(){return SQL.isInTransaction(this.#handle)}static open(filename,options){return new Database(filename,options)}loadExtension(name,entryPoint){return SQL.loadExtension(this.#handle,name,entryPoint)}serialize(optionalName){return SQL.serialize(this.#handle,optionalName||\"main\")}static deserialize(serialized,isReadOnly=!1){if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");return SQL.deserialize(serialized,isReadOnly)}static setCustomSQLite(path){if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");return SQL.setCustomSQLite(path)}close(){return this.clearQueryCache(),SQL.close(this.#handle)}clearQueryCache(){for(let item of this.#cachedQueriesValues)item.finalize();this.#cachedQueriesKeys.length=0,this.#cachedQueriesValues.length=0,this.#cachedQueriesLengths.length=0}run(query,...params){if(params.length===0){SQL.run(this.#handle,query);return}var arg0=params[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?SQL.run(this.#handle,query,params):SQL.run(this.#handle,query,...params)}prepare(query,params,flags){return new Statement(SQL.prepare(this.#handle,query,params,flags||0))}static MAX_QUERY_CACHE_SIZE=20;get[cachedCount](){return this.#cachedQueriesKeys.length}query(query){if(typeof query!==\"string\")@throwTypeError(`Expected 'query' to be a string, got '${typeof query}'`);if(query.length===0)throw new Error(\"SQL query cannot be empty.\");var index=this.#cachedQueriesLengths.indexOf(query.length);while(index!==-1){if(this.#cachedQueriesKeys[index]!==query){index=this.#cachedQueriesLengths.indexOf(query.length,index+1);continue}var stmt=this.#cachedQueriesValues[index];if(stmt.isFinalized)return this.#cachedQueriesValues[index]=this.prepare(query,void 0,willCache\?constants.SQLITE_PREPARE_PERSISTENT:0);return stmt}const willCache=this.#cachedQueriesKeys.length{let controller=(controllers||=new WeakMap).get(db);if(!controller){const shared={commit:db.prepare(\"COMMIT\",void 0,0),rollback:db.prepare(\"ROLLBACK\",void 0,0),savepoint:db.prepare(\"SAVEPOINT `\\t_bs3.\\t`\",void 0,0),release:db.prepare(\"RELEASE `\\t_bs3.\\t`\",void 0,0),rollbackTo:db.prepare(\"ROLLBACK TO `\\t_bs3.\\t`\",void 0,0)};controllers.set(db,controller={default:Object.assign({begin:db.prepare(\"BEGIN\",void 0,0)},shared),deferred:Object.assign({begin:db.prepare(\"BEGIN DEFERRED\",void 0,0)},shared),immediate:Object.assign({begin:db.prepare(\"BEGIN IMMEDIATE\",void 0,0)},shared),exclusive:Object.assign({begin:db.prepare(\"BEGIN EXCLUSIVE\",void 0,0)},shared)})}return controller},wrapTransaction=(fn,db,{begin,commit,rollback,savepoint,release,rollbackTo})=>function transaction(...args){let before,after,undo;if(db.inTransaction)before=savepoint,after=release,undo=rollbackTo;else before=begin,after=commit,undo=rollback;try{before.run();const result=fn.apply(this,args);return after.run(),result}catch(ex){if(db.inTransaction){if(undo.run(),undo!==rollback)after.run()}throw ex}};return{__esModule:!0,Database,Statement,constants,default:Database}})\n"_s; +// + +// +static constexpr ASCIILiteral InternalSharedCode = "(function (){\"use strict\";class NotImplementedError extends Error{code;constructor(feature,issue){super(feature+\" is not yet implemented in Bun.\"+(issue\?\" Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/\"+issue:\"\"));this.name=\"NotImplementedError\",this.code=\"ERR_NOT_IMPLEMENTED\",hideFromStack(NotImplementedError)}}function throwNotImplemented(feature,issue){throw hideFromStack(throwNotImplemented),new NotImplementedError(feature,issue)}function hideFromStack(...fns){for(let fn of fns)Object.defineProperty(fn,\"name\",{value:\"::bunternal::\"})}return{NotImplementedError,throwNotImplemented,hideFromStack}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeAssertCode = "(function (){\"use strict\";const util=@getInternalField(@internalModuleRegistry,42)||@createInternalModuleById(42);var isDeepEqual=Bun.deepEquals,__commonJS=(cb,mod)=>function(){return mod||(0,cb[Object.keys(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_errors=__commonJS({\"assert/build/internal/errors.js\"(exports,module2){function _typeof(obj){return typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"\?_typeof=function(obj2){return typeof obj2}:_typeof=function(obj2){return obj2&&typeof Symbol==\"function\"&&obj2.constructor===Symbol&&obj2!==Symbol.prototype\?\"symbol\":typeof obj2},_typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))@throwTypeError(\"Cannot call a class as a function\")}function _possibleConstructorReturn(self,call){return call&&(_typeof(call)===\"object\"||typeof call==\"function\")\?call:_assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return self}function _getPrototypeOf(o){return _getPrototypeOf=Object.setPrototypeOf\?Object.getPrototypeOf:function(o2){return o2.__proto__||Object.getPrototypeOf(o2)},_getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=\"function\"&&superClass!==null)@throwTypeError(\"Super expression must either be null or a function\");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),superClass&&_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){return _setPrototypeOf=Object.setPrototypeOf||function(o2,p2){return o2.__proto__=p2,o2},_setPrototypeOf(o,p)}var codes={},assert,util2;function createErrorType(code,message,Base){Base||(Base=Error);function getMessage(arg1,arg2,arg3){return typeof message==\"string\"\?message:message(arg1,arg2,arg3)}var NodeError=function(_Base){_inherits(NodeError2,_Base);function NodeError2(arg1,arg2,arg3){var _this;return _classCallCheck(this,NodeError2),_this=_possibleConstructorReturn(this,_getPrototypeOf(NodeError2).call(this,getMessage(arg1,arg2,arg3))),_this.code=code,_this}return NodeError2}(Base);codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return String(i)}),len>2\?\"one of \".concat(thing,\" \").concat(expected.slice(0,len-1).join(\", \"),\", or \")+expected[len-1]:len===2\?\"one of \".concat(thing,\" \").concat(expected[0],\" or \").concat(expected[1]):\"of \".concat(thing,\" \").concat(expected[0])}else return\"of \".concat(thing,\" \").concat(String(expected))}function startsWith(str,search,pos){return str.substr(!pos||pos<0\?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(this_len===void 0||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return typeof start!=\"number\"&&(start=0),start+search.length>str.length\?!1:str.indexOf(search,start)!==-1}createErrorType(\"ERR_AMBIGUOUS_ARGUMENT\",'The \"%s\" argument is ambiguous. %s',TypeError),createErrorType(\"ERR_INVALID_ARG_TYPE\",function(name,expected,actual){assert===void 0&&(assert=require_assert()),assert(typeof name==\"string\",\"'name' must be a string\");var determiner;typeof expected==\"string\"&&startsWith(expected,\"not \")\?(determiner=\"must not be\",expected=expected.replace(/^not /,\"\")):determiner=\"must be\";var msg;if(endsWith(name,\" argument\"))msg=\"The \".concat(name,\" \").concat(determiner,\" \").concat(oneOf(expected,\"type\"));else{var type=includes(name,\".\")\?\"property\":\"argument\";msg='The \"'.concat(name,'\" ').concat(type,\" \").concat(determiner,\" \").concat(oneOf(expected,\"type\"))}return msg+=\". Received type \".concat(_typeof(actual)),msg},TypeError),createErrorType(\"ERR_INVALID_ARG_VALUE\",function(name,value){var reason=arguments.length>2&&arguments[2]!==void 0\?arguments[2]:\"is invalid\",inspected=util2.inspect(value);return inspected.length>128&&(inspected=\"\".concat(inspected.slice(0,128),\"...\")),\"The argument '\".concat(name,\"' \").concat(reason,\". Received \").concat(inspected)},TypeError,RangeError),createErrorType(\"ERR_INVALID_RETURN_VALUE\",function(input,name,value){var type;return value&&value.constructor&&value.constructor.name\?type=\"instance of \".concat(value.constructor.name):type=\"type \".concat(_typeof(value)),\"Expected \".concat(input,' to be returned from the \"').concat(name,'\"')+\" function but got \".concat(type,\".\")},TypeError),createErrorType(\"ERR_MISSING_ARGS\",function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];assert===void 0&&(assert=require_assert()),assert(args.length>0,\"At least one arg needs to be specified\");var msg=\"The \",len=args.length;switch(args=args.map(function(a){return'\"'.concat(a,'\"')}),len){case 1:msg+=\"\".concat(args[0],\" argument\");break;case 2:msg+=\"\".concat(args[0],\" and \").concat(args[1],\" arguments\");break;default:msg+=args.slice(0,len-1).join(\", \"),msg+=\", and \".concat(args[len-1],\" arguments\");break}return\"\".concat(msg,\" must be specified\")},TypeError),module2.exports.codes=codes}}),require_assertion_error=__commonJS({\"assert/build/internal/assert/assertion_error.js\"(exports,module2){function _objectSpread(target){for(var i=1;istr.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function repeat(str,count){if(count=Math.floor(count),str.length==0||count==0)return\"\";var maxCount=str.length*count;for(count=Math.floor(Math.log(count)/Math.log(2));count;)str+=str,count--;return str+=str.substring(0,maxCount-str.length),str}var blue=\"\",green=\"\",red=\"\",white=\"\",kReadableOperator={deepStrictEqual:\"Expected values to be strictly deep-equal:\",strictEqual:\"Expected values to be strictly equal:\",strictEqualObject:'Expected \"actual\" to be reference-equal to \"expected\":',deepEqual:\"Expected values to be loosely deep-equal:\",equal:\"Expected values to be loosely equal:\",notDeepStrictEqual:'Expected \"actual\" not to be strictly deep-equal to:',notStrictEqual:'Expected \"actual\" to be strictly unequal to:',notStrictEqualObject:'Expected \"actual\" not to be reference-equal to \"expected\":',notDeepEqual:'Expected \"actual\" not to be loosely deep-equal to:',notEqual:'Expected \"actual\" to be loosely unequal to:',notIdentical:\"Values identical but not reference-equal:\"},kMaxShortLength=10;function copyError(source){var keys=Object.keys(source),target=Object.create(Object.getPrototypeOf(source));return keys.forEach(function(key){target[key]=source[key]}),Object.defineProperty(target,\"message\",{value:source.message}),target}function inspectValue(val){return inspect(val,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:Infinity,showHidden:!1,breakLength:Infinity,showProxy:!1,sorted:!0,getters:!0})}function createErrDiff(actual,expected,operator){var other=\"\",res=\"\",lastPos=0,end=\"\",skipped=!1,actualInspected=inspectValue(actual),actualLines=actualInspected.split(`\n`),expectedLines=inspectValue(expected).split(`\n`),i=0,indicator=\"\";if(operator===\"strictEqual\"&&_typeof(actual)===\"object\"&&_typeof(expected)===\"object\"&&actual!==null&&expected!==null&&(operator=\"strictEqualObject\"),actualLines.length===1&&expectedLines.length===1&&actualLines[0]!==expectedLines[0]){var inputLength=actualLines[0].length+expectedLines[0].length;if(inputLength<=kMaxShortLength){if((_typeof(actual)!==\"object\"||actual===null)&&(_typeof(expected)!==\"object\"||expected===null)&&(actual!==0||expected!==0))return\"\".concat(kReadableOperator[operator],`\n\n`)+\"\".concat(actualLines[0],\" !== \").concat(expectedLines[0],`\n`)}else if(operator!==\"strictEqualObject\"){var maxLength=process.stderr&&process.stderr.isTTY\?process.stderr.columns:80;if(inputLength2&&(indicator=`\n `.concat(repeat(\" \",i),\"^\"),i=0)}}}for(var a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];a===b&&(i++<2\?end=`\n `.concat(a).concat(end):other=a,actualLines.pop(),expectedLines.pop(),!(actualLines.length===0||expectedLines.length===0));)a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];var maxLines=Math.max(actualLines.length,expectedLines.length);if(maxLines===0){var _actualLines=actualInspected.split(`\n`);if(_actualLines.length>30)for(_actualLines[26]=\"\".concat(blue,\"...\").concat(white);_actualLines.length>27;)_actualLines.pop();return\"\".concat(kReadableOperator.notIdentical,`\n\n`).concat(_actualLines.join(`\n`),`\n`)}i>3&&(end=`\n`.concat(blue,\"...\").concat(white).concat(end),skipped=!0),other!==\"\"&&(end=`\n `.concat(other).concat(end),other=\"\");var printedLines=0,msg=kReadableOperator[operator]+`\n`.concat(green,\"+ actual\").concat(white,\" \").concat(red,\"- expected\").concat(white),skippedMsg=\" \".concat(blue,\"...\").concat(white,\" Lines skipped\");for(i=0;i1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(expectedLines[i-2]),printedLines++),res+=`\n `.concat(expectedLines[i-1]),printedLines++),lastPos=i,other+=`\n`.concat(red,\"-\").concat(white,\" \").concat(expectedLines[i]),printedLines++;else if(expectedLines.length1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(actualLines[i-2]),printedLines++),res+=`\n `.concat(actualLines[i-1]),printedLines++),lastPos=i,res+=`\n`.concat(green,\"+\").concat(white,\" \").concat(actualLines[i]),printedLines++;else{var expectedLine=expectedLines[i],actualLine=actualLines[i],divergingLines=actualLine!==expectedLine&&(!endsWith(actualLine,\",\")||actualLine.slice(0,-1)!==expectedLine);divergingLines&&endsWith(expectedLine,\",\")&&expectedLine.slice(0,-1)===actualLine&&(divergingLines=!1,actualLine+=\",\"),divergingLines\?(cur>1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(actualLines[i-2]),printedLines++),res+=`\n `.concat(actualLines[i-1]),printedLines++),lastPos=i,res+=`\n`.concat(green,\"+\").concat(white,\" \").concat(actualLine),other+=`\n`.concat(red,\"-\").concat(white,\" \").concat(expectedLine),printedLines+=2):(res+=other,other=\"\",(cur===1||i===0)&&(res+=`\n `.concat(actualLine),printedLines++))}if(printedLines>20&&i30)for(res[26]=\"\".concat(blue,\"...\").concat(white);res.length>27;)res.pop();res.length===1\?_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(base,\" \").concat(res[0]))):_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(base,`\n\n`).concat(res.join(`\n`),`\n`)))}else{var _res=inspectValue(actual),other=\"\",knownOperators=kReadableOperator[operator];operator===\"notDeepEqual\"||operator===\"notEqual\"\?(_res=\"\".concat(kReadableOperator[operator],`\n\n`).concat(_res),_res.length>1024&&(_res=\"\".concat(_res.slice(0,1021),\"...\"))):(other=\"\".concat(inspectValue(expected)),_res.length>512&&(_res=\"\".concat(_res.slice(0,509),\"...\")),other.length>512&&(other=\"\".concat(other.slice(0,509),\"...\")),operator===\"deepEqual\"||operator===\"equal\"\?_res=\"\".concat(knownOperators,`\n\n`).concat(_res,`\n\nshould equal\n\n`):other=\" \".concat(operator,\" \").concat(other)),_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(_res).concat(other)))}return Error.stackTraceLimit=limit,_this.generatedMessage=!message,Object.defineProperty(_assertThisInitialized(_this),\"name\",{value:\"AssertionError [ERR_ASSERTION]\",enumerable:!1,writable:!0,configurable:!0}),_this.code=\"ERR_ASSERTION\",_this.actual=actual,_this.expected=expected,_this.operator=operator,Error.captureStackTrace&&Error.captureStackTrace(_assertThisInitialized(_this),stackStartFn),_this.stack,_this.name=\"AssertionError\",_possibleConstructorReturn(_this)}return AssertionError2.prototype={},_inherits(AssertionError2,_Error),_createClass(AssertionError2,[{key:\"toString\",value:function(){return\"\".concat(this.name,\" [\").concat(this.code,\"]: \").concat(this.message)}},{key:inspect.custom,value:function(recurseTimes,ctx){return inspect(this,_objectSpread({},ctx,{customInspect:!1,depth:0}))}}]),AssertionError2}(_wrapNativeSuper(Error));module2.exports=AssertionError}}),require_assert=__commonJS({\"assert/build/assert.js\"(exports,module2){function _typeof(obj){return typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"\?_typeof=function(obj2){return typeof obj2}:_typeof=function(obj2){return obj2&&typeof Symbol==\"function\"&&obj2.constructor===Symbol&&obj2!==Symbol.prototype\?\"symbol\":typeof obj2},_typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))@throwTypeError(\"Cannot call a class as a function\")}var _require=require_errors(),_require$codes=_require.codes,ERR_AMBIGUOUS_ARGUMENT=_require$codes.ERR_AMBIGUOUS_ARGUMENT,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_INVALID_ARG_VALUE=_require$codes.ERR_INVALID_ARG_VALUE,ERR_INVALID_RETURN_VALUE=_require$codes.ERR_INVALID_RETURN_VALUE,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,AssertionError=require_assertion_error(),_require2=util,inspect=_require2.inspect,_require$types=util.types,isPromise=_require$types.isPromise,isRegExp=_require$types.isRegExp,objectAssign=Object.assign,objectIs=Object.is,errorCache=new Map,warned=!1,assert=module2.exports=ok,NO_EXCEPTION_SENTINEL={};function innerFail(obj){throw obj.message instanceof Error\?obj.message:new AssertionError(obj)}function fail(actual,expected,message,operator,stackStartFn){var argsLen=arguments.length,internalMessage;if(argsLen===0)internalMessage=\"Failed\";else if(argsLen===1)message=actual,actual=void 0;else{if(warned===!1){warned=!0;var warn=process.emitWarning\?process.emitWarning:console.warn.bind(console);warn(\"assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.\",\"DeprecationWarning\",\"DEP0094\")}argsLen===2&&(operator=\"!=\")}if(message instanceof Error)throw message;var errArgs={actual,expected,operator:operator===void 0\?\"fail\":operator,stackStartFn:stackStartFn||fail};message!==void 0&&(errArgs.message=message);var err=new AssertionError(errArgs);throw internalMessage&&(err.message=internalMessage,err.generatedMessage=!0),err}assert.fail=fail,assert.AssertionError=AssertionError;function innerOk(fn,argLen,value,message){if(!value){var generatedMessage=!1;if(argLen===0)generatedMessage=!0,message=\"No value argument passed to `assert.ok()`\";else if(message instanceof Error)throw message;var err=new AssertionError({actual:value,expected:!0,message,operator:\"==\",stackStartFn:fn});throw err.generatedMessage=generatedMessage,err}}function ok(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];innerOk.apply(void 0,[ok,args.length].concat(args))}assert.ok=ok,assert.equal=function equal(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");actual!=expected&&innerFail({actual,expected,message,operator:\"==\",stackStartFn:equal})},assert.notEqual=function notEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");actual==expected&&innerFail({actual,expected,message,operator:\"!=\",stackStartFn:notEqual})},assert.deepEqual=function deepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!1)||innerFail({actual,expected,message,operator:\"deepEqual\",stackStartFn:deepEqual})},assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!1)&&innerFail({actual,expected,message,operator:\"notDeepEqual\",stackStartFn:notDeepEqual})},assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!0)||innerFail({actual,expected,message,operator:\"deepStrictEqual\",stackStartFn:deepStrictEqual})},assert.notDeepStrictEqual=notDeepStrictEqual;function notDeepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!0)&&innerFail({actual,expected,message,operator:\"notDeepStrictEqual\",stackStartFn:notDeepStrictEqual})}assert.strictEqual=function strictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");objectIs(actual,expected)||innerFail({actual,expected,message,operator:\"strictEqual\",stackStartFn:strictEqual})},assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");objectIs(actual,expected)&&innerFail({actual,expected,message,operator:\"notStrictEqual\",stackStartFn:notStrictEqual})},assert.match=function match(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");if(!isRegExp(expected))throw new ERR_INVALID_ARG_TYPE(\"expected\",\"RegExp\",expected);expected.test(actual)||innerFail({actual,expected,message,operator:\"match\",stackStartFn:match})};var Comparison=function Comparison2(obj,keys,actual){var _this=this;_classCallCheck(this,Comparison2),keys.forEach(function(key){(key in obj)&&(actual!==void 0&&typeof actual[key]==\"string\"&&isRegExp(obj[key])&&obj[key].test(actual[key])\?_this[key]=actual[key]:_this[key]=obj[key])})};function compareExceptionKey(actual,expected,key,message,keys,fn){if(!(key in actual)||!isDeepEqual(actual[key],expected[key],!0)){if(!message){var a=new Comparison(actual,keys),b=new Comparison(expected,keys,actual),err=new AssertionError({actual:a,expected:b,operator:\"deepStrictEqual\",stackStartFn:fn});throw err.actual=actual,err.expected=expected,err.operator=fn.name,err}innerFail({actual,expected,message,operator:fn.name,stackStartFn:fn})}}function expectedException(actual,expected,msg,fn){if(typeof expected!=\"function\"){if(isRegExp(expected))return expected.test(actual);if(arguments.length===2)throw new ERR_INVALID_ARG_TYPE(\"expected\",[\"Function\",\"RegExp\"],expected);if(_typeof(actual)!==\"object\"||actual===null){var err=new AssertionError({actual,expected,message:msg,operator:\"deepStrictEqual\",stackStartFn:fn});throw err.operator=fn.name,err}var keys=Object.keys(expected);if(expected instanceof Error)keys.push(\"name\",\"message\");else if(keys.length===0)throw new ERR_INVALID_ARG_VALUE(\"error\",expected,\"may not be an empty object\");return keys.forEach(function(key){return typeof actual[key]==\"string\"&&isRegExp(expected[key])&&expected[key].test(actual[key])||compareExceptionKey(actual,expected,key,msg,keys,fn)}),!0}return expected.prototype!==void 0&&actual instanceof expected\?!0:Error.isPrototypeOf(expected)\?!1:expected.call({},actual)===!0}function getActual(fn){if(typeof fn!=\"function\")throw new ERR_INVALID_ARG_TYPE(\"fn\",\"Function\",fn);try{fn()}catch(e){return e}return NO_EXCEPTION_SENTINEL}function checkIsPromise(obj){return isPromise(obj)||obj!==null&&_typeof(obj)===\"object\"&&typeof obj.then==\"function\"&&typeof obj.catch==\"function\"}function waitForActual(promiseFn){return Promise.resolve().then(function(){var resultPromise;if(typeof promiseFn==\"function\"){if(resultPromise=promiseFn(),!checkIsPromise(resultPromise))throw new ERR_INVALID_RETURN_VALUE(\"instance of Promise\",\"promiseFn\",resultPromise)}else if(checkIsPromise(promiseFn))resultPromise=promiseFn;else throw new ERR_INVALID_ARG_TYPE(\"promiseFn\",[\"Function\",\"Promise\"],promiseFn);return Promise.resolve().then(function(){return resultPromise}).then(function(){return NO_EXCEPTION_SENTINEL}).catch(function(e){return e})})}function expectsError(stackStartFn,actual,error,message){if(typeof error==\"string\"){if(arguments.length===4)throw new ERR_INVALID_ARG_TYPE(\"error\",[\"Object\",\"Error\",\"Function\",\"RegExp\"],error);if(_typeof(actual)===\"object\"&&actual!==null){if(actual.message===error)throw new ERR_AMBIGUOUS_ARGUMENT(\"error/message\",'The error message \"'.concat(actual.message,'\" is identical to the message.'))}else if(actual===error)throw new ERR_AMBIGUOUS_ARGUMENT(\"error/message\",'The error \"'.concat(actual,'\" is identical to the message.'));message=error,error=void 0}else if(error!=null&&_typeof(error)!==\"object\"&&typeof error!=\"function\")throw new ERR_INVALID_ARG_TYPE(\"error\",[\"Object\",\"Error\",\"Function\",\"RegExp\"],error);if(actual===NO_EXCEPTION_SENTINEL){var details=\"\";error&&error.name&&(details+=\" (\".concat(error.name,\")\")),details+=message\?\": \".concat(message):\".\";var fnType=stackStartFn.name===\"rejects\"\?\"rejection\":\"exception\";innerFail({actual:void 0,expected:error,operator:stackStartFn.name,message:\"Missing expected \".concat(fnType).concat(details),stackStartFn})}if(error&&!expectedException(actual,error,message,stackStartFn))throw actual}function expectsNoError(stackStartFn,actual,error,message){if(actual!==NO_EXCEPTION_SENTINEL){if(typeof error==\"string\"&&(message=error,error=void 0),!error||expectedException(actual,error)){var details=message\?\": \".concat(message):\".\",fnType=stackStartFn.name===\"doesNotReject\"\?\"rejection\":\"exception\";innerFail({actual,expected:error,operator:stackStartFn.name,message:\"Got unwanted \".concat(fnType).concat(details,`\n`)+'Actual message: \"'.concat(actual&&actual.message,'\"'),stackStartFn})}throw actual}}assert.throws=function throws(promiseFn){for(var _len2=arguments.length,args=new Array(_len2>1\?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];expectsError.apply(void 0,[throws,getActual(promiseFn)].concat(args))},assert.rejects=function rejects(promiseFn){for(var _len3=arguments.length,args=new Array(_len3>1\?_len3-1:0),_key3=1;_key3<_len3;_key3++)args[_key3-1]=arguments[_key3];return waitForActual(promiseFn).then(function(result){return expectsError.apply(void 0,[rejects,result].concat(args))})},assert.doesNotThrow=function doesNotThrow(fn){for(var _len4=arguments.length,args=new Array(_len4>1\?_len4-1:0),_key4=1;_key4<_len4;_key4++)args[_key4-1]=arguments[_key4];expectsNoError.apply(void 0,[doesNotThrow,getActual(fn)].concat(args))},assert.doesNotReject=function doesNotReject(fn){for(var _len5=arguments.length,args=new Array(_len5>1\?_len5-1:0),_key5=1;_key5<_len5;_key5++)args[_key5-1]=arguments[_key5];return waitForActual(fn).then(function(result){return expectsNoError.apply(void 0,[doesNotReject,result].concat(args))})},assert.ifError=function ifError(err){if(err!=null){var message=\"ifError got unwanted exception: \";_typeof(err)===\"object\"&&typeof err.message==\"string\"\?err.message.length===0&&err.constructor\?message+=err.constructor.name:message+=err.message:message+=inspect(err);var newErr=new AssertionError({actual:err,expected:null,operator:\"ifError\",message,stackStartFn:ifError}),origStack=err.stack;if(typeof origStack==\"string\"){var tmp2=origStack.split(`\n`);tmp2.shift();for(var tmp1=newErr.stack.split(`\n`),i=0;i{var prev=get();set(context);try{return fn(...args)}catch(error){throw error}finally{set(prev)}}}enterWith(store){cleanupLater();var context=get();if(!context){set([this,store]);return}var{length}=context;for(var i=0;i-1)hasPrevious=!0,previous=context[i+1],context[i+1]=store;else context.push(this,store);set(context)}try{return callback(...args)}catch(e){throw e}finally{if(!this.#disableCalled){var context2=get();if(context2===context&&contextWasInit)set(void 0);else if(context2=context2.slice(),hasPrevious)context2[i+1]=previous,set(context2);else context2.splice(i,2),set(context2.length\?context2:void 0)}}}disable(){if(!this.#disableCalled){var context=get();if(context){var{length}=context;for(var i=0;i-1){try{child.kill(killSignal)}catch(err){child.emit(\"error\",err)}timeoutHolder.timeoutId=-1}}function spawn(file,args,options){options=normalizeSpawnArguments(file,args,options),validateTimeout(options.timeout),validateAbortSignal(options.signal,\"options.signal\");const killSignal2=sanitizeKillSignal(options.killSignal),child=new ChildProcess;if(child.spawn(options),options.timeout>0){let timeoutId=setTimeout(()=>{if(timeoutId){try{child.kill(killSignal2)}catch(err){child.emit(\"error\",err)}timeoutId=null}});child.once(\"exit\",()=>{if(timeoutId)clearTimeout(timeoutId),timeoutId=null})}if(options.signal){let onAbortListener2=function(){abortChildProcess(child,killSignal2,options.signal.reason)};var onAbortListener=onAbortListener2;const signal=options.signal;if(signal.aborted)process.nextTick(onAbortListener2);else signal.addEventListener(\"abort\",onAbortListener2,{once:!0}),child.once(\"exit\",()=>signal.removeEventListener(\"abort\",onAbortListener2))}return child}function execFile(file,args,options,callback){({file,args,options,callback}=normalizeExecFileArgs(file,args,options,callback)),options={encoding:\"utf8\",timeout:0,maxBuffer:MAX_BUFFER,killSignal:\"SIGTERM\",cwd:null,env:null,shell:!1,...options};const maxBuffer=options.maxBuffer;validateTimeout(options.timeout),validateMaxBuffer(maxBuffer),options.killSignal=sanitizeKillSignal(options.killSignal);const child=spawn(file,args,{cwd:options.cwd,env:options.env,shell:options.shell,signal:options.signal});let encoding;const _stdout=[],_stderr=[];if(options.encoding!==\"buffer\"&&BufferIsEncoding(options.encoding))encoding=options.encoding;else encoding=null;let stdoutLen=0,stderrLen=0,killed=!1,exited=!1,timeoutId,encodedStdoutLen,encodedStderrLen,ex=null,cmd=file;function exitHandler(code,signal){if(exited)return;if(exited=!0,timeoutId)clearTimeout(timeoutId),timeoutId=null;if(!callback)return;const readableEncoding=child\?.stdout\?.readableEncoding;let stdout,stderr;if(encoding||child.stdout&&readableEncoding)stdout=ArrayPrototypeJoin.call(_stdout,\"\");else stdout=BufferConcat(_stdout);if(encoding||child.stderr&&readableEncoding)stderr=ArrayPrototypeJoin.call(_stderr,\"\");else stderr=BufferConcat(_stderr);if(!ex&&code===0&&signal===null){callback(null,stdout,stderr);return}if(args\?.length)cmd+=` ${ArrayPrototypeJoin.call(args,\" \")}`;if(!ex){let message=`Command failed: ${cmd}`;if(stderr)message+=`\\n${stderr}`;ex=genericNodeError(message,{code,killed:child.killed||killed,signal})}ex.cmd=cmd,callback(ex,stdout,stderr)}function errorHandler(e){if(ex=e,child.stdout)child.stdout.destroy();if(child.stderr)child.stderr.destroy();exitHandler()}function kill(){if(child.stdout)child.stdout.destroy();if(child.stderr)child.stderr.destroy();killed=!0;try{child.kill(options.killSignal)}catch(e){ex=e,exitHandler()}}if(options.timeout>0)timeoutId=setTimeout(function delayedKill(){kill(),timeoutId=null},options.timeout);if(child.stdout){if(encoding)child.stdout.setEncoding(encoding);child.stdout.on(\"data\",maxBuffer===Infinity\?function onUnlimitedSizeBufferedData(chunk){ArrayPrototypePush.call(_stdout,chunk)}:encoding\?function onChildStdoutEncoded(chunk){if(stdoutLen+=chunk.length,stdoutLen*4>maxBuffer){const encoding2=child.stdout.readableEncoding,actualLen=Buffer.byteLength(chunk,encoding2);if(encodedStdoutLen===void 0)for(let i=0;i<_stdout.length;i++)encodedStdoutLen+=Buffer.byteLength(_stdout[i],encoding2);else encodedStdoutLen+=actualLen;const truncatedLen=maxBuffer-(encodedStdoutLen-actualLen);ArrayPrototypePush.call(_stdout,StringPrototypeSlice.apply(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stdout\"),kill()}else ArrayPrototypePush.call(_stdout,chunk)}:function onChildStdoutRaw(chunk){if(stdoutLen+=chunk.length,stdoutLen>maxBuffer){const truncatedLen=maxBuffer-(stdoutLen-chunk.length);ArrayPrototypePush.call(_stdout,chunk.slice(0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stdout\"),kill()}else ArrayPrototypePush.call(_stdout,chunk)})}if(child.stderr){if(encoding)child.stderr.setEncoding(encoding);child.stderr.on(\"data\",maxBuffer===Infinity\?function onUnlimitedSizeBufferedData(chunk){ArrayPrototypePush.call(_stderr,chunk)}:encoding\?function onChildStderrEncoded(chunk){if(stderrLen+=chunk.length,stderrLen*4>maxBuffer){const encoding2=child.stderr.readableEncoding,actualLen=Buffer.byteLength(chunk,encoding2);if(encodedStderrLen===void 0)for(let i=0;i<_stderr.length;i++)encodedStderrLen+=Buffer.byteLength(_stderr[i],encoding2);else encodedStderrLen+=actualLen;const truncatedLen=maxBuffer-(encodedStderrLen-actualLen);ArrayPrototypePush.call(_stderr,StringPrototypeSlice.call(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stderr\"),kill()}else ArrayPrototypePush.call(_stderr,chunk)}:function onChildStderrRaw(chunk){if(stderrLen+=chunk.length,stderrLen>maxBuffer){const truncatedLen=maxBuffer-(stderrLen-chunk.length);ArrayPrototypePush.call(_stderr,StringPrototypeSlice.call(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stderr\"),kill()}else ArrayPrototypePush.call(_stderr,chunk)})}return child.addListener(\"close\",exitHandler),child.addListener(\"error\",errorHandler),child}function exec(command,options,callback){const opts=normalizeExecArgs(command,options,callback);return execFile(opts.file,opts.options,opts.callback)}const customPromiseExecFunction=(orig)=>{return(...args)=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res,reject=rej});return promise.child=orig(...args,(err,stdout,stderr)=>{if(err!==null)err.stdout=stdout,err.stderr=stderr,reject(err);else resolve({stdout,stderr})}),promise}};ObjectDefineProperty(exec,promisify.custom,{__proto__:null,enumerable:!1,value:customPromiseExecFunction(exec)});function spawnSync(file,args,options){options={maxBuffer:MAX_BUFFER,...normalizeSpawnArguments(file,args,options)};const{maxBuffer,encoding}=options;validateTimeout(options.timeout),validateMaxBuffer(maxBuffer),options.killSignal=sanitizeKillSignal(options.killSignal);const stdio=options.stdio||\"pipe\",bunStdio=getBunStdioFromOptions(stdio);var{input}=options;if(input)if(ArrayBufferIsView(input))bunStdio[0]=input;else if(typeof input===\"string\")bunStdio[0]=Buffer.from(input,encoding||\"utf8\");else throw new ERR_INVALID_ARG_TYPE(\"options.stdio[0]\",[\"Buffer\",\"TypedArray\",\"DataView\",\"string\"],input);const{stdout,stderr,success,exitCode}=Bun.spawnSync({cmd:options.args,env:options.env||void 0,cwd:options.cwd||void 0,stdin:bunStdio[0],stdout:bunStdio[1],stderr:bunStdio[2]}),result={signal:null,status:exitCode,output:[null,stdout,stderr]};if(stdout&&encoding&&encoding!==\"buffer\")result.output[1]=result.output[1]\?.toString(encoding);if(stderr&&encoding&&encoding!==\"buffer\")result.output[2]=result.output[2]\?.toString(encoding);if(result.stdout=result.output[1],result.stderr=result.output[2],!success)result.error=new SystemError(result.output[2],options.file,\"spawnSync\",-1,result.status),result.error.spawnargs=ArrayPrototypeSlice.call(options.args,1);return result}function execFileSync(file,args,options){({file,args,options}=normalizeExecFileArgs(file,args,options));const ret=spawnSync(file,args,options),errArgs=[options.argv0||file];ArrayPrototypePush.apply(errArgs,args);const err=checkExecSyncError(ret,errArgs);if(err)throw err;return ret.stdout}function execSync(command,options){const opts=normalizeExecArgs(command,options,null),ret=spawnSync(opts.file,opts.options),err=checkExecSyncError(ret,void 0,command);if(err)throw err;return ret.stdout}function stdioStringToArray(stdio,channel){const options=[];switch(stdio){case\"ignore\":case\"overlapped\":case\"pipe\":ArrayPrototypePush.call(options,stdio,stdio,stdio);break;case\"inherit\":ArrayPrototypePush.call(options,0,1,2);break;default:throw new ERR_INVALID_ARG_VALUE(\"stdio\",stdio)}if(channel)ArrayPrototypePush.call(options,channel);return options}function fork(modulePath,args=[],options){modulePath=getValidatedPath(modulePath,\"modulePath\");let execArgv;if(args==null)args=[];else if(typeof args===\"object\"&&!ArrayIsArray(args))options=args,args=[];else validateArray(args,\"args\");if(options!=null)validateObject(options,\"options\");if(options={__proto__:null,...options,shell:!1},options.execPath=options.execPath||process.execPath,validateArgumentNullCheck(options.execPath,\"options.execPath\"),execArgv=options.execArgv||process.execArgv,validateArgumentsNullCheck(execArgv,\"options.execArgv\"),execArgv===process.execArgv&&process._eval!=null){const index=ArrayPrototypeLastIndexOf.call(execArgv,process._eval);if(index>0)execArgv=ArrayPrototypeSlice.call(execArgv),ArrayPrototypeSplice.call(execArgv,index-1,2)}if(args=[...execArgv,modulePath,...args],typeof options.stdio===\"string\")options.stdio=stdioStringToArray(options.stdio,\"ipc\");else if(!ArrayIsArray(options.stdio))options.stdio=stdioStringToArray(options.silent\?\"pipe\":\"inherit\",\"ipc\");else if(!ArrayPrototypeIncludes.call(options.stdio,\"ipc\"))throw new ERR_CHILD_PROCESS_IPC_REQUIRED(\"options.stdio\");return spawn(options.execPath,args,options)}function convertToValidSignal(signal){if(typeof signal===\"number\"&&getSignalsToNamesMapping()[signal])return signal;if(typeof signal===\"string\"){const signalName=signals[StringPrototypeToUpperCase.call(signal)];if(signalName)return signalName}throw new ERR_UNKNOWN_SIGNAL(signal)}function sanitizeKillSignal(killSignal2){if(typeof killSignal2===\"string\"||typeof killSignal2===\"number\")return convertToValidSignal(killSignal2);else if(killSignal2!=null)throw new ERR_INVALID_ARG_TYPE(\"options.killSignal\",[\"string\",\"number\"],killSignal2)}let signalsToNamesMapping;function getSignalsToNamesMapping(){if(signalsToNamesMapping!==void 0)return signalsToNamesMapping;signalsToNamesMapping=ObjectCreate(null);for(let key in signals)signalsToNamesMapping[signals[key]]=key;return signalsToNamesMapping}function normalizeExecFileArgs(file,args,options,callback){if(ArrayIsArray(args))args=ArrayPrototypeSlice.call(args);else if(args!=null&&typeof args===\"object\")callback=options,options=args,args=null;else if(typeof args===\"function\")callback=args,options=null,args=null;if(args==null)args=[];if(typeof options===\"function\")callback=options;else if(options!=null)validateObject(options,\"options\");if(options==null)options=kEmptyObject;if(callback!=null)validateFunction(callback,\"callback\");if(options.argv0!=null)validateString(options.argv0,\"options.argv0\"),validateArgumentNullCheck(options.argv0,\"options.argv0\");return{file,args,options,callback}}function normalizeExecArgs(command,options,callback){if(validateString(command,\"command\"),validateArgumentNullCheck(command,\"command\"),typeof options===\"function\")callback=options,options=void 0;return options={...options},options.shell=typeof options.shell===\"string\"\?options.shell:!0,{file:command,options,callback}}function normalizeSpawnArguments(file,args,options){if(validateString(file,\"file\"),validateArgumentNullCheck(file,\"file\"),file.length===0)throw new ERR_INVALID_ARG_VALUE(\"file\",file,\"cannot be empty\");if(ArrayIsArray(args))args=ArrayPrototypeSlice.call(args);else if(args==null)args=[];else if(typeof args!==\"object\")throw new ERR_INVALID_ARG_TYPE(\"args\",\"object\",args);else options=args,args=[];if(validateArgumentsNullCheck(args,\"args\"),options===void 0)options={};else validateObject(options,\"options\");let cwd=options.cwd;if(cwd!=null)cwd=getValidatedPath(cwd,\"options.cwd\");if(options.shell!=null&&typeof options.shell!==\"boolean\"&&typeof options.shell!==\"string\")throw new ERR_INVALID_ARG_TYPE(\"options.shell\",[\"boolean\",\"string\"],options.shell);if(options.argv0!=null)validateString(options.argv0,\"options.argv0\"),validateArgumentNullCheck(options.argv0,\"options.argv0\");if(options.shell){validateArgumentNullCheck(options.shell,\"options.shell\");const command=ArrayPrototypeJoin.call([file,...args],\" \");if(typeof options.shell===\"string\")file=options.shell;else file=\"sh\";args=[\"-c\",command]}if(typeof options.argv0===\"string\")ArrayPrototypeUnshift.call(args,options.argv0);else ArrayPrototypeUnshift.call(args,file);const envPairs=options.env||process.env;return{...options,file,args,cwd,envPairs}}function checkExecSyncError(ret,args,cmd){let err;if(ret.error)err=ret.error,ObjectAssign(err,ret);else if(ret.status!==0){let msg=\"Command failed: \";if(msg+=cmd||ArrayPrototypeJoin.call(args,\" \"),ret.stderr&&ret.stderr.length>0)msg+=`\\n${ret.stderr.toString()}`;err=genericNodeError(msg,ret)}return err}class ChildProcess extends EventEmitter{constructor(){super(...arguments)}#handle;#exited=!1;#closesNeeded=1;#closesGot=0;connected=!1;signalCode=null;exitCode=null;spawnfile;spawnargs;pid;channel;get killed(){if(this.#handle==null)return!1}#handleOnExit(exitCode,signalCode,err){if(this.#exited)return;if(signalCode)this.signalCode=signalCode;else this.exitCode=exitCode;if(this.#stdin)this.#stdin.destroy();if(this.#handle)this.#handle=null;if(exitCode<0){const err2=new SystemError(`Spawned process exited with error code: ${exitCode}`,void 0,\"spawn\",\"EUNKNOWN\",\"ERR_CHILD_PROCESS_UNKNOWN_ERROR\");if(this.spawnfile)err2.path=this.spawnfile;err2.spawnargs=ArrayPrototypeSlice.call(this.spawnargs,1),this.emit(\"error\",err2)}else this.emit(\"exit\",this.exitCode,this.signalCode);process.nextTick(flushStdio,this),this.#maybeClose(),this.#exited=!0,this.#stdioOptions=[\"destroyed\",\"destroyed\",\"destroyed\"]}#getBunSpawnIo(i,encoding){NativeWritable||=StreamModule.NativeWritable,ReadableFromWeb||=StreamModule.Readable.fromWeb;const io=this.#stdioOptions[i];switch(i){case 0:switch(io){case\"pipe\":return new NativeWritable(this.#handle.stdin);case\"inherit\":return process.stdin||null;case\"destroyed\":return new ShimmedStdin;default:return null}case 2:case 1:switch(io){case\"pipe\":return ReadableFromWeb(this.#handle[fdToStdioName(i)],{encoding});case\"inherit\":return process[fdToStdioName(i)]||null;case\"destroyed\":return new ShimmedStdioOutStream;default:return null}}}#stdin;#stdout;#stderr;#stdioObject;#encoding;#stdioOptions;#createStdioObject(){return Object.create(null,{0:{get:()=>this.stdin},1:{get:()=>this.stdout},2:{get:()=>this.stderr}})}get stdin(){return this.#stdin\?\?=this.#getBunSpawnIo(0,this.#encoding)}get stdout(){return this.#stdout\?\?=this.#getBunSpawnIo(1,this.#encoding)}get stderr(){return this.#stderr\?\?=this.#getBunSpawnIo(2,this.#encoding)}get stdio(){return this.#stdioObject\?\?=this.#createStdioObject()}spawn(options){validateObject(options,\"options\"),validateString(options.file,\"options.file\");var file=this.spawnfile=options.file,spawnargs;if(options.args==null)spawnargs=this.spawnargs=[];else validateArray(options.args,\"options.args\"),spawnargs=this.spawnargs=options.args;const stdio=options.stdio||[\"pipe\",\"pipe\",\"pipe\"],bunStdio=getBunStdioFromOptions(stdio);var env=options.envPairs||void 0;this.#encoding=options.encoding||void 0,this.#stdioOptions=bunStdio,this.#handle=Bun.spawn({cmd:spawnargs,stdin:bunStdio[0],stdout:bunStdio[1],stderr:bunStdio[2],cwd:options.cwd||void 0,env:env||process.env,onExit:(handle,exitCode,signalCode,err)=>{this.#handle=handle,this.pid=this.#handle.pid,process.nextTick((exitCode2,signalCode2,err2)=>this.#handleOnExit(exitCode2,signalCode2,err2),exitCode,signalCode,err)},lazy:!0}),this.pid=this.#handle.pid,onSpawnNT(this)}send(){console.log(\"ChildProcess.prototype.send() - Sorry! Not implemented yet\")}disconnect(){console.log(\"ChildProcess.prototype.disconnect() - Sorry! Not implemented yet\")}kill(sig){const signal=sig===0\?sig:convertToValidSignal(sig===void 0\?\"SIGTERM\":sig);if(this.#handle)this.#handle.kill(signal);return this.#maybeClose(),!0}#maybeClose(){if(this.#closesGot++,this.#closesGot===this.#closesNeeded)this.emit(\"close\",this.exitCode,this.signalCode)}ref(){if(this.#handle)this.#handle.ref()}unref(){if(this.#handle)this.#handle.unref()}}const nodeToBunLookup={ignore:null,pipe:\"pipe\",overlapped:\"pipe\",inherit:\"inherit\"};function nodeToBun(item){if(typeof item===\"number\")return item;else{const result=nodeToBunLookup[item];if(result===void 0)throw new Error(\"Invalid stdio option\");return result}}function fdToStdioName(fd){switch(fd){case 0:return\"stdin\";case 1:return\"stdout\";case 2:return\"stderr\";default:return null}}function getBunStdioFromOptions(stdio){return normalizeStdio(stdio).map((item)=>nodeToBun(item))}function normalizeStdio(stdio){if(typeof stdio===\"string\")switch(stdio){case\"ignore\":return[\"ignore\",\"ignore\",\"ignore\"];case\"pipe\":return[\"pipe\",\"pipe\",\"pipe\"];case\"inherit\":return[\"inherit\",\"inherit\",\"inherit\"];default:throw new ERR_INVALID_OPT_VALUE(\"stdio\",stdio)}else if(ArrayIsArray(stdio)){let processedStdio;if(stdio.length===0)processedStdio=[\"pipe\",\"pipe\",\"pipe\"];else if(stdio.length===1)processedStdio=[stdio[0],\"pipe\",\"pipe\"];else if(stdio.length===2)processedStdio=[stdio[0],stdio[1],\"pipe\"];else if(stdio.length>=3)processedStdio=[stdio[0],stdio[1],stdio[2]];return processedStdio.map((item)=>!item\?\"pipe\":item)}else throw new ERR_INVALID_OPT_VALUE(\"stdio\",stdio)}function flushStdio(subprocess){const stdio=subprocess.stdio;if(stdio==null)return;for(let i=0;i=0))throw new ERR_OUT_OF_RANGE(\"options.maxBuffer\",\"a positive number\",maxBuffer)}function validateArgumentNullCheck(arg,propName){if(typeof arg===\"string\"&&StringPrototypeIncludes.call(arg,\"\\0\"))throw new ERR_INVALID_ARG_VALUE(propName,arg,\"must be a string without null bytes\")}function validateArgumentsNullCheck(args,propName){for(let i=0;i=0))throw new ERR_OUT_OF_RANGE(\"timeout\",\"an unsigned integer\",timeout)}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}function validateFunction(value,name){if(typeof value!==\"function\")throw new ERR_INVALID_ARG_TYPE(name,\"Function\",value)}const validateAbortSignal=(signal,name)=>{if(signal!==void 0&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE(name,\"AbortSignal\",signal)},validateOneOf=(value,name,oneOf)=>{if(!ArrayPrototypeIncludes.call(oneOf,value)){const reason=\"must be one of: \"+ArrayPrototypeJoin.call(ArrayPrototypeMap.call(oneOf,(v)=>typeof v===\"string\"\?`'${v}'`:String(v)),\", \");throw new ERR_INVALID_ARG_VALUE(name,value,reason)}},validateObject=(value,name,options=null)=>{const allowArray=options\?.allowArray\?\?!1,allowFunction=options\?.allowFunction\?\?!1;if(!(options\?.nullable\?\?!1)&&value===null||!allowArray&&ArrayIsArray.call(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE(name,\"object\",value)},validateArray=(value,name,minLength=0)=>{if(!ArrayIsArray(value))throw new ERR_INVALID_ARG_TYPE(name,\"Array\",value);if(value.lengthfunction(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},require_safe_buffer=__commonJS({\"node_modules/safe-buffer/index.js\"(exports,module){var buffer=BufferModule,Buffer2=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}Buffer2.from&&Buffer2.alloc&&Buffer2.allocUnsafe&&Buffer2.allocUnsafeSlow\?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer);function SafeBuffer(arg,encodingOrOffset,length){return Buffer2(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer2.prototype),copyProps(Buffer2,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==\"number\")@throwTypeError(\"Argument must not be a number\");return Buffer2(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");var buf=Buffer2(size);return fill!==void 0\?typeof encoding==\"string\"\?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");return Buffer2(size)},SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");return buffer.SlowBuffer(size)}}}),require_browser=__commonJS({\"node_modules/randombytes/browser.js\"(exports,module){var MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser(){throw new Error(`Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11`)}var Buffer2=require_safe_buffer().Buffer,crypto2=globalCrypto;crypto2&&crypto2.getRandomValues\?module.exports=randomBytes:module.exports=oldBrowser;function randomBytes(size,cb){if(size>MAX_UINT32)@throwRangeError(\"requested too many random bytes\");var bytes=Buffer2.allocUnsafe(size);if(size>0)if(size>MAX_BYTES)for(var generated=0;generated=this._blockSize;){for(var i=this._blockOffset;i0;++j)this._length[j]+=carry,carry=this._length[j]/4294967296|0,carry>0&&(this._length[j]-=4294967296*carry);return this},HashBase.prototype._update=function(){throw new Error(\"_update is not implemented\")},HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error(\"Digest already called\");this._finalized=!0;var digest=this._digest();encoding!==void 0&&(digest=digest.toString(encoding)),this._block.fill(0),this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return digest},HashBase.prototype._digest=function(){throw new Error(\"_digest is not implemented\")},module.exports=HashBase}}),require_md5=__commonJS({\"node_modules/md5.js/index.js\"(exports,module){var inherits=require_inherits_browser(),HashBase=require_hash_base(),Buffer2=require_safe_buffer().Buffer,ARRAY16=new Array(16);function MD5(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}inherits(MD5,HashBase),MD5.prototype._update=function(){for(var M=ARRAY16,i=0;i<16;++i)M[i]=this._block.readInt32LE(i*4);var a=this._a,b=this._b,c=this._c,d=this._d;a=fnF(a,b,c,d,M[0],3614090360,7),d=fnF(d,a,b,c,M[1],3905402710,12),c=fnF(c,d,a,b,M[2],606105819,17),b=fnF(b,c,d,a,M[3],3250441966,22),a=fnF(a,b,c,d,M[4],4118548399,7),d=fnF(d,a,b,c,M[5],1200080426,12),c=fnF(c,d,a,b,M[6],2821735955,17),b=fnF(b,c,d,a,M[7],4249261313,22),a=fnF(a,b,c,d,M[8],1770035416,7),d=fnF(d,a,b,c,M[9],2336552879,12),c=fnF(c,d,a,b,M[10],4294925233,17),b=fnF(b,c,d,a,M[11],2304563134,22),a=fnF(a,b,c,d,M[12],1804603682,7),d=fnF(d,a,b,c,M[13],4254626195,12),c=fnF(c,d,a,b,M[14],2792965006,17),b=fnF(b,c,d,a,M[15],1236535329,22),a=fnG(a,b,c,d,M[1],4129170786,5),d=fnG(d,a,b,c,M[6],3225465664,9),c=fnG(c,d,a,b,M[11],643717713,14),b=fnG(b,c,d,a,M[0],3921069994,20),a=fnG(a,b,c,d,M[5],3593408605,5),d=fnG(d,a,b,c,M[10],38016083,9),c=fnG(c,d,a,b,M[15],3634488961,14),b=fnG(b,c,d,a,M[4],3889429448,20),a=fnG(a,b,c,d,M[9],568446438,5),d=fnG(d,a,b,c,M[14],3275163606,9),c=fnG(c,d,a,b,M[3],4107603335,14),b=fnG(b,c,d,a,M[8],1163531501,20),a=fnG(a,b,c,d,M[13],2850285829,5),d=fnG(d,a,b,c,M[2],4243563512,9),c=fnG(c,d,a,b,M[7],1735328473,14),b=fnG(b,c,d,a,M[12],2368359562,20),a=fnH(a,b,c,d,M[5],4294588738,4),d=fnH(d,a,b,c,M[8],2272392833,11),c=fnH(c,d,a,b,M[11],1839030562,16),b=fnH(b,c,d,a,M[14],4259657740,23),a=fnH(a,b,c,d,M[1],2763975236,4),d=fnH(d,a,b,c,M[4],1272893353,11),c=fnH(c,d,a,b,M[7],4139469664,16),b=fnH(b,c,d,a,M[10],3200236656,23),a=fnH(a,b,c,d,M[13],681279174,4),d=fnH(d,a,b,c,M[0],3936430074,11),c=fnH(c,d,a,b,M[3],3572445317,16),b=fnH(b,c,d,a,M[6],76029189,23),a=fnH(a,b,c,d,M[9],3654602809,4),d=fnH(d,a,b,c,M[12],3873151461,11),c=fnH(c,d,a,b,M[15],530742520,16),b=fnH(b,c,d,a,M[2],3299628645,23),a=fnI(a,b,c,d,M[0],4096336452,6),d=fnI(d,a,b,c,M[7],1126891415,10),c=fnI(c,d,a,b,M[14],2878612391,15),b=fnI(b,c,d,a,M[5],4237533241,21),a=fnI(a,b,c,d,M[12],1700485571,6),d=fnI(d,a,b,c,M[3],2399980690,10),c=fnI(c,d,a,b,M[10],4293915773,15),b=fnI(b,c,d,a,M[1],2240044497,21),a=fnI(a,b,c,d,M[8],1873313359,6),d=fnI(d,a,b,c,M[15],4264355552,10),c=fnI(c,d,a,b,M[6],2734768916,15),b=fnI(b,c,d,a,M[13],1309151649,21),a=fnI(a,b,c,d,M[4],4149444226,6),d=fnI(d,a,b,c,M[11],3174756917,10),c=fnI(c,d,a,b,M[2],718787259,15),b=fnI(b,c,d,a,M[9],3951481745,21),this._a=this._a+a|0,this._b=this._b+b|0,this._c=this._c+c|0,this._d=this._d+d|0},MD5.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer2.allocUnsafe(16);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer};function rotl(x,n){return x<>>32-n}function fnF(a,b,c,d,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+b|0}function fnG(a,b,c,d,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+b|0}function fnH(a,b,c,d,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+b|0}function fnI(a,b,c,d,m,k,s){return rotl(a+(c^(b|~d))+m+k|0,s)+b|0}module.exports=MD5}}),require_ripemd160=__commonJS({\"node_modules/ripemd160/index.js\"(exports,module){var Buffer2=Buffer,inherits=require_inherits_browser(),HashBase=require_hash_base(),ARRAY16=new Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;j<16;++j)words[j]=this._block.readInt32LE(j*4);for(var al=this._a|0,bl=this._b|0,cl=this._c|0,dl=this._d|0,el=this._e|0,ar=this._a|0,br=this._b|0,cr=this._c|0,dr=this._d|0,er=this._e|0,i=0;i<80;i+=1){var tl,tr;i<16\?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):i<32\?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):i<48\?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):i<64\?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=this._b+cl+dr|0;this._b=this._c+dl+er|0,this._c=this._d+el+ar|0,this._d=this._e+al+br|0,this._e=this._a+bl+cr|0,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer2.alloc\?Buffer2.alloc(20):new Buffer2(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer};function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+e|0}function fn2(a,b,c,d,e,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+e|0}function fn3(a,b,c,d,e,m,k,s){return rotl(a+((b|~c)^d)+m+k|0,s)+e|0}function fn4(a,b,c,d,e,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+e|0}function fn5(a,b,c,d,e,m,k,s){return rotl(a+(b^(c|~d))+m+k|0,s)+e|0}module.exports=RIPEMD160}}),require_hash=__commonJS({\"node_modules/sha.js/hash.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer;function Hash(blockSize,finalSize){this._block=Buffer2.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}Hash.prototype={},Hash.prototype.update=function(data,enc){typeof data==\"string\"&&(enc=enc||\"utf8\",data=Buffer2.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=this._len*8;if(bits<=4294967295)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(bits&4294967295)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc\?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error(\"_update must be implemented by subclass\")},module.exports=Hash}}),require_sha=__commonJS({\"node_modules/sha.js/sha.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return s===0\?b&c|~b&d:s===2\?b&c|b&d|c&d:b^c^d}Sha.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<80;++i)W2[i]=W2[i-3]^W2[i-8]^W2[i-14]^W2[i-16];for(var j=0;j<80;++j){var s=~~(j/20),t=rotl5(a)+ft(s,b,c,d)+e+W2[j]+K[s]|0;e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha.prototype._hash=function(){var H=Buffer2.allocUnsafe(20);return H.writeInt32BE(this._a|0,0),H.writeInt32BE(this._b|0,4),H.writeInt32BE(this._c|0,8),H.writeInt32BE(this._d|0,12),H.writeInt32BE(this._e|0,16),H},module.exports=Sha}}),require_sha1=__commonJS({\"node_modules/sha.js/sha1.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return s===0\?b&c|~b&d:s===2\?b&c|b&d|c&d:b^c^d}Sha1.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<80;++i)W2[i]=rotl1(W2[i-3]^W2[i-8]^W2[i-14]^W2[i-16]);for(var j=0;j<80;++j){var s=~~(j/20),t=rotl5(a)+ft(s,b,c,d)+e+W2[j]+K[s]|0;e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha1.prototype._hash=function(){var H=Buffer2.allocUnsafe(20);return H.writeInt32BE(this._a|0,0),H.writeInt32BE(this._b|0,4),H.writeInt32BE(this._c|0,8),H.writeInt32BE(this._d|0,12),H.writeInt32BE(this._e|0,16),H},module.exports=Sha1}}),require_sha256=__commonJS({\"node_modules/sha.js/sha256.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=new Array(64);function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,f=this._f|0,g=this._g|0,h=this._h|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<64;++i)W2[i]=gamma1(W2[i-2])+W2[i-7]+gamma0(W2[i-15])+W2[i-16]|0;for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W2[j]|0,T2=sigma0(a)+maj(a,b,c)|0;h=g,g=f,f=e,e=d+T1|0,d=c,c=b,b=a,a=T1+T2|0}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0,this._f=f+this._f|0,this._g=g+this._g|0,this._h=h+this._h|0},Sha256.prototype._hash=function(){var H=Buffer2.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256}}),require_sha224=__commonJS({\"node_modules/sha.js/sha224.js\"(exports,module){var inherits=require_inherits_browser(),Sha256=require_sha256(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,W=new Array(64);function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer2.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224}}),require_sha512=__commonJS({\"node_modules/sha.js/sha512.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=new Array(160);function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0\?1:0}Sha512.prototype._update=function(M){for(var W2=this._w,ah=this._ah|0,bh=this._bh|0,ch=this._ch|0,dh=this._dh|0,eh=this._eh|0,fh=this._fh|0,gh=this._gh|0,hh=this._hh|0,al=this._al|0,bl=this._bl|0,cl=this._cl|0,dl=this._dl|0,el=this._el|0,fl=this._fl|0,gl=this._gl|0,hl=this._hl|0,i=0;i<32;i+=2)W2[i]=M.readInt32BE(i*4),W2[i+1]=M.readInt32BE(i*4+4);for(;i<160;i+=2){var xh=W2[i-30],xl=W2[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh);xh=W2[i-4],xl=W2[i-4+1];var gamma1=Gamma1(xh,xl),gamma1l=Gamma1l(xl,xh),Wi7h=W2[i-14],Wi7l=W2[i-14+1],Wi16h=W2[i-32],Wi16l=W2[i-32+1],Wil=gamma0l+Wi7l|0,Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wil=Wil+gamma1l|0,Wih=Wih+gamma1+getCarry(Wil,gamma1l)|0,Wil=Wil+Wi16l|0,Wih=Wih+Wi16h+getCarry(Wil,Wi16l)|0,W2[i]=Wih,W2[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W2[j],Wil=W2[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=hl+sigma1l|0,t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1l=t1l+chl|0,t1h=t1h+chh+getCarry(t1l,chl)|0,t1l=t1l+Kil|0,t1h=t1h+Kih+getCarry(t1l,Kil)|0,t1l=t1l+Wil|0,t1h=t1h+Wih+getCarry(t1l,Wil)|0;var t2l=sigma0l+majl|0,t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,el=dl+t1l|0,eh=dh+t1h+getCarry(el,dl)|0,dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,al=t1l+t2l|0,ah=t1h+t2h+getCarry(al,t1l)|0}this._al=this._al+al|0,this._bl=this._bl+bl|0,this._cl=this._cl+cl|0,this._dl=this._dl+dl|0,this._el=this._el+el|0,this._fl=this._fl+fl|0,this._gl=this._gl+gl|0,this._hl=this._hl+hl|0,this._ah=this._ah+ah+getCarry(this._al,al)|0,this._bh=this._bh+bh+getCarry(this._bl,bl)|0,this._ch=this._ch+ch+getCarry(this._cl,cl)|0,this._dh=this._dh+dh+getCarry(this._dl,dl)|0,this._eh=this._eh+eh+getCarry(this._el,el)|0,this._fh=this._fh+fh+getCarry(this._fl,fl)|0,this._gh=this._gh+gh+getCarry(this._gl,gl)|0,this._hh=this._hh+hh+getCarry(this._hl,hl)|0},Sha512.prototype._hash=function(){var H=Buffer2.allocUnsafe(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512}}),require_sha384=__commonJS({\"node_modules/sha.js/sha384.js\"(exports,module){var inherits=require_inherits_browser(),SHA512=require_sha512(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,W=new Array(160);function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){var H=Buffer2.allocUnsafe(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384}}),require_sha2=__commonJS({\"node_modules/sha.js/index.js\"(exports,module){var exports=module.exports=function(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+\" is not supported (we accept pull requests)\");return new Algorithm};exports.sha=require_sha(),exports.sha1=require_sha1(),exports.sha224=require_sha224(),exports.sha256=require_sha256(),exports.sha384=require_sha384(),exports.sha512=require_sha512()}}),require_cipher_base=__commonJS({\"node_modules/cipher-base/index.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,inherits=require_inherits_browser();function CipherBase(hashMode){StreamModule.Transform.call(this),this.hashMode=typeof hashMode==\"string\",this.hashMode\?this[hashMode]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}inherits(CipherBase,StreamModule.Transform),CipherBase.prototype.update=function(data,inputEnc,outputEnc){typeof data==\"string\"&&(data=Buffer2.from(data,inputEnc));var outData=this._update(data);return this.hashMode\?this:(outputEnc&&(outData=this._toString(outData,outputEnc)),outData)},CipherBase.prototype.setAutoPadding=function(){},CipherBase.prototype.getAuthTag=function(){throw new Error(\"trying to get auth tag in unsupported state\")},CipherBase.prototype.setAuthTag=function(){throw new Error(\"trying to set auth tag in unsupported state\")},CipherBase.prototype.setAAD=function(){throw new Error(\"trying to set aad in unsupported state\")},CipherBase.prototype._transform=function(data,_,next){var err;try{this.hashMode\?this._update(data):this.push(this._update(data))}catch(e){err=e}finally{next(err)}},CipherBase.prototype._flush=function(done){var err;try{this.push(this.__final())}catch(e){err=e}done(err)},CipherBase.prototype._finalOrDigest=function(outputEnc){var outData=this.__final()||Buffer2.alloc(0);return outputEnc&&(outData=this._toString(outData,outputEnc,!0)),outData},CipherBase.prototype._toString=function(value,enc,fin){if(this._decoder||(this._decoder=new StringDecoder(enc),this._encoding=enc),this._encoding!==enc)throw new Error(\"can't switch encodings\");var out=this._decoder.write(value);return fin&&(out+=this._decoder.end()),out},module.exports=CipherBase}}),require_browser2=__commonJS({\"node_modules/create-hash/browser.js\"(exports,module){const LazyHash=function Hash(algorithm,options){this._options=options,this._hasher=new CryptoHasher(algorithm,options),this._finalized=!1};LazyHash.prototype=Object.create(StreamModule.Transform.prototype),LazyHash.prototype.update=function update(data,encoding){return this._checkFinalized(),this._hasher.update(data,encoding),this},LazyHash.prototype.digest=function update(data,encoding){return this._checkFinalized(),this._finalized=!0,this._hasher.digest(data,encoding)},LazyHash.prototype._checkFinalized=function _checkFinalized(){if(this._finalized){var err=new Error(\"Digest already called\");throw err.code=\"ERR_CRYPTO_HASH_FINALIZED\",err}},LazyHash.prototype.copy=function copy(){const copy=Object.create(LazyHash.prototype);return copy._options=this._options,copy._hasher=this._hasher.copy(),copy._finalized=this._finalized,copy};const lazyHashFullInitProto={__proto__:StreamModule.Transform.prototype,...LazyHash.prototype,_transform(data,encoding,callback){this.update(data,encoding),callback&&callback()},_flush(callback){this.push(this.digest()),callback()}},triggerMethods=[\"_events\",\"_eventsCount\",\"_final\",\"_maxListeners\",\"_maxListeners\",\"_read\",\"_undestroy\",\"_writableState\",\"_write\",\"_writev\",\"addListener\",\"asIndexedPairs\",\"closed\",\"compose\",\"constructor\",\"cork\",\"destroy\",\"destroyed\",\"drop\",\"emit\",\"end\",\"errored\",\"eventNames\",\"every\",\"filter\",\"find\",\"flatMap\",\"forEach\",\"getMaxListeners\",\"hasOwnProperty\",\"isPaused\",\"isPrototypeOf\",\"iterator\",\"listenerCount\",\"listeners\",\"map\",\"off\",\"on\",\"once\",\"pause\",\"pipe\",\"prependListener\",\"prependOnceListener\",\"propertyIsEnumerable\",\"push\",\"rawListeners\",\"read\",\"readable\",\"readableAborted\",\"readableBuffer\",\"readableDidRead\",\"readableEncoding\",\"readableEnded\",\"readableFlowing\",\"readableHighWaterMark\",\"readableLength\",\"readableObjectMode\",\"reduce\",\"removeAllListeners\",\"removeListener\",\"resume\",\"setDefaultEncoding\",\"setEncoding\",\"setMaxListeners\",\"some\",\"take\",\"toArray\",\"toLocaleString\",\"toString\",\"uncork\",\"unpipe\",\"unshift\",\"valueOf\",\"wrap\",\"writable\",\"writableBuffer\",\"writableCorked\",\"writableEnded\",\"writableFinished\",\"writableHighWaterMark\",\"writableLength\",\"writableNeedDrain\",\"writableObjectMode\",\"write\"];for(let method of triggerMethods)Object.defineProperty(LazyHash.prototype,method,{get(){return Object.setPrototypeOf(this,lazyHashFullInitProto),StreamModule.Transform.call(this,this._options),this[method]},enumerable:!1,configurable:!0});module.exports=function createHash(algorithm){return new LazyHash(algorithm)},module.exports.createHash=module.exports,module.exports.Hash=LazyHash}}),require_legacy=__commonJS({\"node_modules/create-hmac/legacy.js\"(exports,module){var inherits=require_inherits_browser(),Buffer2=require_safe_buffer().Buffer,Base=require_cipher_base(),ZEROS=Buffer2.alloc(128),blocksize=64;function Hmac(alg,key){Base.call(this,\"digest\"),typeof key==\"string\"&&(key=Buffer2.from(key)),this._alg=alg,this._key=key,key.length>blocksize\?key=alg(key):key.lengthblocksize){var hash=alg===\"rmd160\"\?new RIPEMD160:sha(alg);key=hash.update(key).digest()}else key.lengthMAX_ALLOC||keylen!==keylen)@throwTypeError(\"Bad key length\")}}}),require_default_encoding=__commonJS({\"node_modules/pbkdf2/lib/default-encoding.js\"(exports,module){var defaultEncoding;global.process&&global.process.browser\?defaultEncoding=\"utf-8\":global.process&&global.process.version\?(pVersionMajor=parseInt(process.version.split(\".\")[0].slice(1),10),defaultEncoding=pVersionMajor>=6\?\"utf-8\":\"binary\"):defaultEncoding=\"utf-8\";var pVersionMajor;module.exports=defaultEncoding}}),require_to_buffer=__commonJS({\"node_modules/pbkdf2/lib/to-buffer.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer;module.exports=function(thing,encoding,name){if(Buffer2.isBuffer(thing))return thing;if(typeof thing==\"string\")return Buffer2.from(thing,encoding);if(ArrayBuffer.isView(thing))return Buffer2.from(thing.buffer);@throwTypeError(name+\" must be a string, a Buffer, a typed array or a DataView\")}}}),require_sync_browser=__commonJS({\"node_modules/pbkdf2/lib/sync-browser.js\"(exports,module){var md5=require_md52(),RIPEMD160=require_ripemd160(),sha=require_sha2(),Buffer2=require_safe_buffer().Buffer,checkParameters=require_precondition(),defaultEncoding=require_default_encoding(),toBuffer=require_to_buffer(),ZEROS=Buffer2.alloc(128),sizes={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function Hmac(alg,key,saltLen){var hash=getDigest(alg),blocksize=alg===\"sha512\"||alg===\"sha384\"\?128:64;key.length>blocksize\?key=hash(key):key.length>>0},exports.writeUInt32BE=function(bytes,value,off){bytes[0+off]=value>>>24,bytes[1+off]=value>>>16&255,bytes[2+off]=value>>>8&255,bytes[3+off]=value&255},exports.ip=function(inL,inR,out,off){for(var outL=0,outR=0,i=6;i>=0;i-=2){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>>j+i&1;for(var j=0;j<=24;j+=8)outL<<=1,outL|=inL>>>j+i&1}for(var i=6;i>=0;i-=2){for(var j=1;j<=25;j+=8)outR<<=1,outR|=inR>>>j+i&1;for(var j=1;j<=25;j+=8)outR<<=1,outR|=inL>>>j+i&1}out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.rip=function(inL,inR,out,off){for(var outL=0,outR=0,i=0;i<4;i++)for(var j=24;j>=0;j-=8)outL<<=1,outL|=inR>>>j+i&1,outL<<=1,outL|=inL>>>j+i&1;for(var i=4;i<8;i++)for(var j=24;j>=0;j-=8)outR<<=1,outR|=inR>>>j+i&1,outR<<=1,outR|=inL>>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.pc1=function(inL,inR,out,off){for(var outL=0,outR=0,i=7;i>=5;i--){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(var j=0;j<=24;j+=8)outL<<=1,outL|=inL>>j+i&1}for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(var i=1;i<=3;i++){for(var j=0;j<=24;j+=8)outR<<=1,outR|=inR>>j+i&1;for(var j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1}for(var j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.r28shl=function(num,shift){return num<>>28-shift};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];exports.pc2=function(inL,inR,out,off){for(var outL=0,outR=0,len=pc2table.length>>>1,i=0;i>>pc2table[i]&1;for(var i=len;i>>pc2table[i]&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.expand=function(r,out,off){var outL=0,outR=0;outL=(r&1)<<5|r>>>27;for(var i=23;i>=15;i-=4)outL<<=6,outL|=r>>>i&63;for(var i=11;i>=3;i-=4)outR|=r>>>i&63,outR<<=6;outR|=(r&31)<<1|r>>>31,out[off+0]=outL>>>0,out[off+1]=outR>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];exports.substitute=function(inL,inR){for(var out=0,i=0;i<4;i++){var b=inL>>>18-i*6&63,sb=sTable[i*64+b];out<<=4,out|=sb}for(var i=0;i<4;i++){var b=inR>>>18-i*6&63,sb=sTable[256+i*64+b];out<<=4,out|=sb}return out>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];exports.permute=function(num){for(var out=0,i=0;i>>permuteTable[i]&1;return out>>>0},exports.padSplit=function(num,size,group){for(var str=num.toString(2);str.length0;count--)inputOff+=this._buffer(data,inputOff),outputOff+=this._flushBuffer(out,outputOff);return inputOff+=this._buffer(data,inputOff),out},Cipher.prototype.final=function(buffer){var first;buffer&&(first=this.update(buffer));var last;return this.type===\"encrypt\"\?last=this._finalEncrypt():last=this._finalDecrypt(),first\?first.concat(last):last},Cipher.prototype._pad=function(buffer,off){if(off===0)return!1;for(;off>>1];kL=utils.r28shl(kL,shift),kR=utils.r28shl(kR,shift),utils.pc2(kL,kR,state.keys,i)}},DES.prototype._update=function(inp,inOff,out,outOff){var state=this._desState,l=utils.readUInt32BE(inp,inOff),r=utils.readUInt32BE(inp,inOff+4);utils.ip(l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],this.type===\"encrypt\"\?this._encrypt(state,l,r,state.tmp,0):this._decrypt(state,l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],utils.writeUInt32BE(out,l,outOff),utils.writeUInt32BE(out,r,outOff+4)},DES.prototype._pad=function(buffer,off){for(var value=buffer.length-off,i=off;i>>0,l=t}utils.rip(r,l,out,off)},DES.prototype._decrypt=function(state,lStart,rStart,out,off){for(var l=rStart,r=lStart,i=state.keys.length-2;i>=0;i-=2){var keyL=state.keys[i],keyR=state.keys[i+1];utils.expand(l,state.tmp,0),keyL^=state.tmp[0],keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR),f=utils.permute(s),t=l;l=(r^f)>>>0,r=t}utils.rip(l,r,out,off)}}}),require_cbc=__commonJS({\"node_modules/des.js/lib/des/cbc.js\"(exports){var assert=require_minimalistic_assert(),inherits=require_inherits_browser(),proto={};function CBCState(iv){assert.equal(iv.length,8,\"Invalid IV length\"),this.iv=new Array(8);for(var i=0;i>i%8,self2._prev=shiftIn(self2._prev,decrypt\?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer2.allocUnsafe(buffer.length);for(buffer=Buffer2.concat([buffer,Buffer2.from([value])]);++i>7;return out}exports.encrypt=function(self2,chunk,decrypt){for(var len=chunk.length,out=Buffer2.allocUnsafe(len),i=-1;++i>>24]^SUB_MIX1[s1>>>16&255]^SUB_MIX2[s2>>>8&255]^SUB_MIX3[s3&255]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[s2>>>16&255]^SUB_MIX2[s3>>>8&255]^SUB_MIX3[s0&255]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[s3>>>16&255]^SUB_MIX2[s0>>>8&255]^SUB_MIX3[s1&255]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[s0>>>16&255]^SUB_MIX2[s1>>>8&255]^SUB_MIX3[s2&255]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[s3&255])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[s0&255])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[s1&255])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[s2&255])^keySchedule[ksRow++],t0=t0>>>0,t1=t1>>>0,t2=t2>>>0,t3=t3>>>0,[t0,t1,t2,t3]}var RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=new Array(256),j=0;j<256;j++)j<128\?d[j]=j<<1:d[j]=j<<1^283;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0;i<256;++i){var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^sx&255^99,SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=d[sx]*257^sx*16843008;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=x8*16843009^x4*65537^x2*257^x*16843008,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,x===0\?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX,INV_SBOX,SUB_MIX,INV_SUB_MIX}}();function AES(key){this._key=asUInt32Array(key),this._reset()}AES.prototype={},AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=(nRounds+1)*4,keySchedule=[],k=0;k>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255],t^=RCON[k/keySize|0]<<24):keySize>6&&k%keySize===4&&(t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik>>24]]^G.INV_SUB_MIX[1][G.SBOX[tt>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[tt>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[tt&255]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return M=asUInt32Array(M),cryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=asUInt32Array(M);var m1=M[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES}}),require_ghash=__commonJS({\"node_modules/browserify-aes/ghash.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,ZEROES=Buffer2.alloc(16,0);function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){var buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer2.alloc(16,0),this.cache=Buffer2.allocUnsafe(0)}GHASH.prototype={},GHASH.prototype.ghash=function(block){for(var i=-1;++i0;j--)Vi[j]=Vi[j]>>>1|(Vi[j-1]&1)<<31;Vi[0]=Vi[0]>>>1,lsbVi&&(Vi[0]=Vi[0]^225<<24)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer2.concat([this.cache,buf]);for(var chunk;this.cache.length>=16;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer2.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH}}),require_authCipher=__commonJS({\"node_modules/browserify-aes/authCipher.js\"(exports,module){var aes=require_aes(),Buffer2=require_safe_buffer().Buffer,Transform=require_cipher_base(),inherits=require_inherits_browser(),GHASH=require_ghash(),xor=require_buffer_xor(),incr32=require_incr32();function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=Math.min(a.length,b.length),i=0;i0||ivLen>0;){var hash=new MD5;hash.update(tmp),hash.update(password),salt&&hash.update(salt),tmp=hash.digest();var used=0;if(keyLen>0){var keyStart=key.length-keyLen;used=Math.min(keyLen,tmp.length),tmp.copy(key,keyStart,0,used),keyLen-=used}if(used0){var ivStart=iv.length-ivLen,length=Math.min(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length),ivLen-=length}}return tmp.fill(0),{key,iv}}module.exports=EVP_BytesToKey}}),require_encrypter=__commonJS({\"node_modules/browserify-aes/encrypter.js\"(exports){var MODES=require_modes(),AuthCipher=require_authCipher(),Buffer2=require_safe_buffer().Buffer,StreamCipher=require_streamCipher(),Transform=require_cipher_base(),aes=require_aes(),ebtk=require_evp_bytestokey(),inherits=require_inherits_browser();function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer2.from(iv),this._mode=mode,this._autopadding=!0}inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var chunk,thing,out=[];chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer2.concat(out)};var PADDING=Buffer2.alloc(16,16);Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error(\"data not multiple of block length\")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this};function Splitter(){this.cache=Buffer2.allocUnsafe(0)}Splitter.prototype={},Splitter.prototype.add=function(data){this.cache=Buffer2.concat([this.cache,data])},Splitter.prototype.get=function(){if(this.cache.length>15){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer2.allocUnsafe(len),i=-1;++i16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out}else if(this.cache.length>=16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache};function unpad(last){var padded=last[15];if(padded<1||padded>16)throw new Error(\"unable to decrypt data\");for(var i=-1;++i0\?left:right},BN.min=function(left,right){return left.cmp(right)<0\?left:right},BN.prototype._init=function(number,base,endian){if(typeof number==\"number\")return this._initNumber(number,base,endian);if(typeof number==\"object\")return this._initArray(number,base,endian);base===\"hex\"&&(base=16),assert(base===(base|0)&&base>=2&&base<=36),number=number.toString().replace(/\\s+/g,\"\");var start=0;number[0]===\"-\"&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);else if(endian===\"le\")for(i=0,j=0;i>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);return this.strip()};function parseHex4Bits(string,index){var c=string.charCodeAt(index);return c>=65&&c<=70\?c-55:c>=97&&c<=102\?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}BN.prototype._parseHex=function(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18\?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=parseLength%2===0\?start+1:start;i=18\?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this.strip()};function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49\?r+=c-49+10:c>=17\?r+=c-17+10:r+=c}return r}BN.prototype._parseBase=function(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},BN.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},BN.prototype.inspect=function(){return(this.red\?\"\"};var zeros=[\"\",\"0\",\"00\",\"000\",\"0000\",\"00000\",\"000000\",\"0000000\",\"00000000\",\"000000000\",\"0000000000\",\"00000000000\",\"000000000000\",\"0000000000000\",\"00000000000000\",\"000000000000000\",\"0000000000000000\",\"00000000000000000\",\"000000000000000000\",\"0000000000000000000\",\"00000000000000000000\",\"000000000000000000000\",\"0000000000000000000000\",\"00000000000000000000000\",\"000000000000000000000000\",\"0000000000000000000000000\"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function(base,padding){base=base||10,padding=padding|0||1;var out;if(base===16||base===\"hex\"){out=\"\";for(var off=0,carry=0,i=0;i>>24-off&16777215,carry!==0||i!==this.length-1\?out=zeros[6-word.length]+word+out:out=word+out,off+=2,off>=26&&(off-=26,i--)}for(carry!==0&&(out=carry.toString(16)+out);out.length%padding!==0;)out=\"0\"+out;return this.negative!==0&&(out=\"-\"+out),out}if(base===(base|0)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out=\"\";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),c.isZero()\?out=r+out:out=zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out=\"0\"+out);out.length%padding!==0;)out=\"0\"+out;return this.negative!==0&&(out=\"-\"+out),out}assert(!1,\"Base should be between 2 and 36\")},BN.prototype.toNumber=function(){var ret=this.words[0];return this.length===2\?ret+=this.words[1]*67108864:this.length===3&&this.words[2]===1\?ret+=4503599627370496+this.words[1]*67108864:this.length>2&&assert(!1,\"Number can only safely store up to 53 bits\"),this.negative!==0\?-ret:ret},BN.prototype.toJSON=function(){return this.toString(16)},BN.prototype.toBuffer=function(endian,length){return assert(typeof Buffer2<\"u\"),this.toArrayLike(Buffer2,endian,length)},BN.prototype.toArray=function(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,\"byte array longer than desired length\"),assert(reqLength>0,\"Requested array length <= 0\"),this.strip();var littleEndian=endian===\"le\",res=new ArrayType(reqLength),b,i,q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(w===0)return 26;var t=w,r=0;return(t&8191)===0&&(r+=13,t>>>=13),(t&127)===0&&(r+=7,t>>>=7),(t&15)===0&&(r+=4,t>>>=4),(t&3)===0&&(r+=2,t>>>=2),(t&1)===0&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return(this.length-1)*26+hi};function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0;inum.length\?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length\?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b;this.length>num.length\?b=num:b=this;for(var i=0;inum.length\?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length\?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length\?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length\?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length\?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert(typeof width==\"number\"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0,bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert(typeof bit==\"number\"&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),val\?this.words[off]=this.words[off]|1<num.length\?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;carry!==0&&i>>26;if(this.length=a.length,carry!==0)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length\?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(cmp===0)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;cmp>0\?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=r&67108863;for(;carry!==0&&i>26,this.words[i]=r&67108863;if(carry===0&&i>>26,rword=carry&67108863,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self2.length+1);j<=maxJ;j++){var i=k-j|0;a=self2.words[i]|0,b=num.words[j]|0,r=a*b+rword,ncarry+=r/67108864|0,rword=r&67108863}out.words[k]=rword|0,carry=ncarry|0}return carry!==0\?out.words[k]=carry|0:out.length--,out.strip()}var comb10MulTo=function(self2,num,out){var a=self2.words,b=num.words,o=out.words,c=0,lo,mid,hi,a0=a[0]|0,al0=a0&8191,ah0=a0>>>13,a1=a[1]|0,al1=a1&8191,ah1=a1>>>13,a2=a[2]|0,al2=a2&8191,ah2=a2>>>13,a3=a[3]|0,al3=a3&8191,ah3=a3>>>13,a4=a[4]|0,al4=a4&8191,ah4=a4>>>13,a5=a[5]|0,al5=a5&8191,ah5=a5>>>13,a6=a[6]|0,al6=a6&8191,ah6=a6>>>13,a7=a[7]|0,al7=a7&8191,ah7=a7>>>13,a8=a[8]|0,al8=a8&8191,ah8=a8>>>13,a9=a[9]|0,al9=a9&8191,ah9=a9>>>13,b0=b[0]|0,bl0=b0&8191,bh0=b0>>>13,b1=b[1]|0,bl1=b1&8191,bh1=b1>>>13,b2=b[2]|0,bl2=b2&8191,bh2=b2>>>13,b3=b[3]|0,bl3=b3&8191,bh3=b3>>>13,b4=b[4]|0,bl4=b4&8191,bh4=b4>>>13,b5=b[5]|0,bl5=b5&8191,bh5=b5>>>13,b6=b[6]|0,bl6=b6&8191,bh6=b6>>>13,b7=b[7]|0,bl7=b7&8191,bh7=b7>>>13,b8=b[8]|0,bl8=b8&8191,bh8=b8>>>13,b9=b[9]|0,bl9=b9&8191,bh9=b9>>>13;out.negative=self2.negative^num.negative,out.length=19,lo=Math.imul(al0,bl0),mid=Math.imul(al0,bh0),mid=mid+Math.imul(ah0,bl0)|0,hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=Math.imul(al1,bh0),mid=mid+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0),lo=lo+Math.imul(al0,bl1)|0,mid=mid+Math.imul(al0,bh1)|0,mid=mid+Math.imul(ah0,bl1)|0,hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=Math.imul(al2,bh0),mid=mid+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=mid+Math.imul(al1,bh1)|0,mid=mid+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0,lo=lo+Math.imul(al0,bl2)|0,mid=mid+Math.imul(al0,bh2)|0,mid=mid+Math.imul(ah0,bl2)|0,hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=Math.imul(al3,bh0),mid=mid+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=mid+Math.imul(al2,bh1)|0,mid=mid+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=mid+Math.imul(al1,bh2)|0,mid=mid+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0,lo=lo+Math.imul(al0,bl3)|0,mid=mid+Math.imul(al0,bh3)|0,mid=mid+Math.imul(ah0,bl3)|0,hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=Math.imul(al4,bh0),mid=mid+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=mid+Math.imul(al3,bh1)|0,mid=mid+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=mid+Math.imul(al2,bh2)|0,mid=mid+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=mid+Math.imul(al1,bh3)|0,mid=mid+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0,lo=lo+Math.imul(al0,bl4)|0,mid=mid+Math.imul(al0,bh4)|0,mid=mid+Math.imul(ah0,bl4)|0,hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=Math.imul(al5,bh0),mid=mid+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=mid+Math.imul(al4,bh1)|0,mid=mid+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=mid+Math.imul(al3,bh2)|0,mid=mid+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=mid+Math.imul(al2,bh3)|0,mid=mid+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=mid+Math.imul(al1,bh4)|0,mid=mid+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0,lo=lo+Math.imul(al0,bl5)|0,mid=mid+Math.imul(al0,bh5)|0,mid=mid+Math.imul(ah0,bl5)|0,hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=Math.imul(al6,bh0),mid=mid+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=mid+Math.imul(al5,bh1)|0,mid=mid+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=mid+Math.imul(al4,bh2)|0,mid=mid+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=mid+Math.imul(al3,bh3)|0,mid=mid+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=mid+Math.imul(al2,bh4)|0,mid=mid+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=mid+Math.imul(al1,bh5)|0,mid=mid+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0,lo=lo+Math.imul(al0,bl6)|0,mid=mid+Math.imul(al0,bh6)|0,mid=mid+Math.imul(ah0,bl6)|0,hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=Math.imul(al7,bh0),mid=mid+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=mid+Math.imul(al6,bh1)|0,mid=mid+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=mid+Math.imul(al5,bh2)|0,mid=mid+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=mid+Math.imul(al4,bh3)|0,mid=mid+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=mid+Math.imul(al3,bh4)|0,mid=mid+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=mid+Math.imul(al2,bh5)|0,mid=mid+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=mid+Math.imul(al1,bh6)|0,mid=mid+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0,lo=lo+Math.imul(al0,bl7)|0,mid=mid+Math.imul(al0,bh7)|0,mid=mid+Math.imul(ah0,bl7)|0,hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=Math.imul(al8,bh0),mid=mid+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=mid+Math.imul(al7,bh1)|0,mid=mid+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=mid+Math.imul(al6,bh2)|0,mid=mid+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=mid+Math.imul(al5,bh3)|0,mid=mid+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=mid+Math.imul(al4,bh4)|0,mid=mid+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=mid+Math.imul(al3,bh5)|0,mid=mid+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=mid+Math.imul(al2,bh6)|0,mid=mid+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=mid+Math.imul(al1,bh7)|0,mid=mid+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0,lo=lo+Math.imul(al0,bl8)|0,mid=mid+Math.imul(al0,bh8)|0,mid=mid+Math.imul(ah0,bl8)|0,hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=Math.imul(al9,bh0),mid=mid+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=mid+Math.imul(al8,bh1)|0,mid=mid+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=mid+Math.imul(al7,bh2)|0,mid=mid+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=mid+Math.imul(al6,bh3)|0,mid=mid+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=mid+Math.imul(al5,bh4)|0,mid=mid+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=mid+Math.imul(al4,bh5)|0,mid=mid+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=mid+Math.imul(al3,bh6)|0,mid=mid+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=mid+Math.imul(al2,bh7)|0,mid=mid+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=mid+Math.imul(al1,bh8)|0,mid=mid+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0,lo=lo+Math.imul(al0,bl9)|0,mid=mid+Math.imul(al0,bh9)|0,mid=mid+Math.imul(ah0,bl9)|0,hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=Math.imul(al9,bh1),mid=mid+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=mid+Math.imul(al8,bh2)|0,mid=mid+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=mid+Math.imul(al7,bh3)|0,mid=mid+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=mid+Math.imul(al6,bh4)|0,mid=mid+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=mid+Math.imul(al5,bh5)|0,mid=mid+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=mid+Math.imul(al4,bh6)|0,mid=mid+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=mid+Math.imul(al3,bh7)|0,mid=mid+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=mid+Math.imul(al2,bh8)|0,mid=mid+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0,lo=lo+Math.imul(al1,bl9)|0,mid=mid+Math.imul(al1,bh9)|0,mid=mid+Math.imul(ah1,bl9)|0,hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=Math.imul(al9,bh2),mid=mid+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=mid+Math.imul(al8,bh3)|0,mid=mid+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=mid+Math.imul(al7,bh4)|0,mid=mid+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=mid+Math.imul(al6,bh5)|0,mid=mid+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=mid+Math.imul(al5,bh6)|0,mid=mid+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=mid+Math.imul(al4,bh7)|0,mid=mid+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=mid+Math.imul(al3,bh8)|0,mid=mid+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0,lo=lo+Math.imul(al2,bl9)|0,mid=mid+Math.imul(al2,bh9)|0,mid=mid+Math.imul(ah2,bl9)|0,hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=Math.imul(al9,bh3),mid=mid+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=mid+Math.imul(al8,bh4)|0,mid=mid+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=mid+Math.imul(al7,bh5)|0,mid=mid+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=mid+Math.imul(al6,bh6)|0,mid=mid+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=mid+Math.imul(al5,bh7)|0,mid=mid+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=mid+Math.imul(al4,bh8)|0,mid=mid+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0,lo=lo+Math.imul(al3,bl9)|0,mid=mid+Math.imul(al3,bh9)|0,mid=mid+Math.imul(ah3,bl9)|0,hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=Math.imul(al9,bh4),mid=mid+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=mid+Math.imul(al8,bh5)|0,mid=mid+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=mid+Math.imul(al7,bh6)|0,mid=mid+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=mid+Math.imul(al6,bh7)|0,mid=mid+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=mid+Math.imul(al5,bh8)|0,mid=mid+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0,lo=lo+Math.imul(al4,bl9)|0,mid=mid+Math.imul(al4,bh9)|0,mid=mid+Math.imul(ah4,bl9)|0,hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=Math.imul(al9,bh5),mid=mid+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=mid+Math.imul(al8,bh6)|0,mid=mid+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=mid+Math.imul(al7,bh7)|0,mid=mid+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=mid+Math.imul(al6,bh8)|0,mid=mid+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0,lo=lo+Math.imul(al5,bl9)|0,mid=mid+Math.imul(al5,bh9)|0,mid=mid+Math.imul(ah5,bl9)|0,hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=Math.imul(al9,bh6),mid=mid+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=mid+Math.imul(al8,bh7)|0,mid=mid+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=mid+Math.imul(al7,bh8)|0,mid=mid+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0,lo=lo+Math.imul(al6,bl9)|0,mid=mid+Math.imul(al6,bh9)|0,mid=mid+Math.imul(ah6,bl9)|0,hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=Math.imul(al9,bh7),mid=mid+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=mid+Math.imul(al8,bh8)|0,mid=mid+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0,lo=lo+Math.imul(al7,bl9)|0,mid=mid+Math.imul(al7,bh9)|0,mid=mid+Math.imul(ah7,bl9)|0,hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=Math.imul(al9,bh8),mid=mid+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8),lo=lo+Math.imul(al8,bl9)|0,mid=mid+Math.imul(al8,bh9)|0,mid=mid+Math.imul(ah8,bl9)|0,hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863,lo=Math.imul(al9,bl9),mid=Math.imul(al9,bh9),mid=mid+Math.imul(ah9,bl9)|0,hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&8191)<<13)|0;return c=(hi+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,c!==0&&(o[19]=c,out.length++),out};Math.imul||(comb10MulTo=smallMulTo);function bigMulTo(self2,num,out){out.negative=num.negative^self2.negative,out.length=self2.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0,hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return carry!==0\?out.words[k]=carry:out.length--,out.strip()}function jumboMulTo(self2,num,out){var fftm=new FFTM;return fftm.mulp(self2,num,out)}BN.prototype.mulTo=function(num,out){var res,len=this.length+num.length;return this.length===10&&num.length===10\?res=comb10MulTo(this,num,out):len<63\?res=smallMulTo(this,num,out):len<1024\?res=bigMulTo(this,num,out):res=jumboMulTo(this,num,out),res};function FFTM(x,y){this.x=x,this.y=y}FFTM.prototype={},FFTM.prototype.makeRBT=function(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1)i++;return 1<>>13,rws[2*i+1]=carry&8191,carry=carry>>>13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=lo&67108863}return carry!==0&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(w.length===0)return new BN(1);for(var res=this,i=0;i=0);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(r!==0){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(s!==0){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0);var h;hint\?h=(hint-hint%26)/26:h=0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&carry!==0&&(maskedWords.words[maskedWords.length++]=carry),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function(bits,hint,extended){return assert(this.negative===0),this.iushrn(bits,hint,extended)},BN.prototype.shln=function(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function(bit){assert(typeof bit==\"number\"&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(this.negative===0,\"imaskn works only with positive numbers\"),this.length<=s)return this;if(r!==0&&s++,this.length=Math.min(s,this.length),r!==0){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1\?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function(num){if(assert(typeof num==\"number\"),assert(num<67108864),num<0)return this.iaddn(-num);if(this.negative!==0)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=w&67108863}for(;i>26,this.words[i+shift]=w&67108863;if(carry===0)return this.strip();for(assert(carry===-1),carry=0,i=0;i>26,this.words[i]=w&67108863;return this.negative=1,this.strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=b.words[b.length-1]|0,bhiBits=this._countBits(bhi);shift=26-bhiBits,shift!==0&&(b=b.ushln(shift),a.iushln(shift),bhi=b.words[b.length-1]|0);var m=a.length-b.length,q;if(mode!==\"mod\"){q=new BN(null),q.length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);a.negative!==0;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),mode!==\"div\"&&shift!==0&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return this.negative!==0&&num.negative===0\?(res=this.neg().divmod(num,mode),mode!==\"mod\"&&(div=res.div.neg()),mode!==\"div\"&&(mod=res.mod.neg(),positive&&mod.negative!==0&&mod.iadd(num)),{div,mod}):this.negative===0&&num.negative!==0\?(res=this.divmod(num.neg(),mode),mode!==\"mod\"&&(div=res.div.neg()),{div,mod:res.mod}):(this.negative&num.negative)!==0\?(res=this.neg().divmod(num.neg(),mode),mode!==\"div\"&&(mod=res.mod.neg(),positive&&mod.negative!==0&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0\?{div:new BN(0),mod:this}:num.length===1\?mode===\"div\"\?{div:this.divn(num.words[0]),mod:null}:mode===\"mod\"\?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode)},BN.prototype.div=function(num){return this.divmod(num,\"div\",!1).div},BN.prototype.mod=function(num){return this.divmod(num,\"mod\",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,\"mod\",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0\?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||r2===1&&cmp===0\?dm.div:dm.div.negative!==0\?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(this.words[i]|0))%num;return acc},BN.prototype.idivn=function(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(p.negative===0),assert(!p.isZero());var x=this,y=p.clone();x.negative!==0\?x=x.umod(p):x=x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0\?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function(p){assert(p.negative===0),assert(!p.isZero());var a=this,b=p.clone();a.negative!==0\?a=a.umod(p):a=a.clone();for(var x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0\?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return a.cmpn(1)===0\?res=x1:res=x2,res.cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(r===0||b.cmpn(1)===0)break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return(this.words[0]&1)===0},BN.prototype.isOdd=function(){return(this.words[0]&1)===1},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert(typeof bit==\"number\");var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return carry!==0&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return this.length===1&&this.words[0]===0},BN.prototype.cmpn=function(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this.strip();var res;if(this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,\"Number is too big\");var w=this.words[0]|0;res=w===num\?0:wnum.length)return 1;if(this.length=0;i--){var a=this.words[i]|0,b=num.words[i]|0;if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function(num){return this.cmpn(num)===1},BN.prototype.gt=function(num){return this.cmp(num)===1},BN.prototype.gten=function(num){return this.cmpn(num)>=0},BN.prototype.gte=function(num){return this.cmp(num)>=0},BN.prototype.ltn=function(num){return this.cmpn(num)===-1},BN.prototype.lt=function(num){return this.cmp(num)===-1},BN.prototype.lten=function(num){return this.cmpn(num)<=0},BN.prototype.lte=function(num){return this.cmp(num)<=0},BN.prototype.eqn=function(num){return this.cmpn(num)===0},BN.prototype.eq=function(num){return this.cmp(num)===0},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,\"Already a number in reduction context\"),assert(this.negative===0,\"red works only with positives\"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,\"fromRed works only with numbers in reduction context\"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,\"Already a number in reduction context\"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,\"redAdd works only with red numbers\"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,\"redIAdd works only with red numbers\"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,\"redSub works only with red numbers\"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,\"redISub works only with red numbers\"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,\"redShl works only with red numbers\"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,\"redMul works only with red numbers\"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,\"redMul works only with red numbers\"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,\"redSqr works only with red numbers\"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,\"redISqr works only with red numbers\"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,\"redSqrt works only with red numbers\"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,\"redInvm works only with red numbers\"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,\"redNeg works only with red numbers\"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,\"redPow(normalNum)\"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}MPrime.prototype={},MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen0\?r.isub(this.p):r.strip!==void 0\?r.strip():r._strip(),r},MPrime.prototype.split=function(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function(num){return num.imul(this.k)};function K256(){MPrime.call(this,\"k256\",\"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f\")}inherits(K256,MPrime),K256.prototype.split=function(input,output){for(var mask=4194303,outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,prev===0&&input.length>10\?input.length-=10:input.length-=9},K256.prototype.imulK=function(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return carry!==0&&(num.words[num.length++]=carry),num},BN._prime=function(name){if(primes[name])return primes[name];var prime2;if(name===\"k256\")prime2=new K256;else if(name===\"p224\")prime2=new P224;else if(name===\"p192\")prime2=new P192;else if(name===\"p25519\")prime2=new P25519;else throw new Error(\"Unknown prime \"+name);return primes[name]=prime2,prime2};function Red(m){if(typeof m==\"string\"){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),\"modulus must be greater than 1\"),this.m=m,this.prime=null}Red.prototype={},Red.prototype._verify1=function(a){assert(a.negative===0,\"red works only with positives\"),assert(a.red,\"red works only with red numbers\")},Red.prototype._verify2=function(a,b){assert((a.negative|b.negative)===0,\"red works only with positives\"),assert(a.red&&a.red===b.red,\"red works only with red numbers\")},Red.prototype.imod=function(a){return this.prime\?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function(a){return a.isZero()\?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2===1),mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&q.andln(1)===0;)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);this.pow(z,lpow).cmp(nOne)!==0;)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;t.cmp(one)!==0;){for(var tmp=t,i=0;tmp.cmp(one)!==0;i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]&&(res=this.sqr(res)),bit===0&¤t===0){currentLen=0;continue}current<<=1,current|=bit,currentLen++,!(currentLen!==windowSize&&(i!==0||j!==0))&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num\?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)};function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0\?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0\?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(typeof module>\"u\"||module,exports)}}),require_bn2=require_bn,require_brorand=__commonJS({\"node_modules/brorand/index.js\"(exports,module){var r;module.exports=function(len){return r||(r=new Rand(null)),r.generate(len)};function Rand(rand){this.rand=rand}Rand.prototype={},module.exports.Rand=Rand,Rand.prototype.generate=function(len){return this._rand(len)},Rand.prototype._rand=function(n){var out=new Buffer(n);return crypto.getRandomValues(out),out}}}),require_mr=__commonJS({\"node_modules/miller-rabin/lib/mr.js\"(exports,module){var bn=require_bn2(),brorand=require_brorand();function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin,MillerRabin.create=function(rand){return new MillerRabin(rand)},MillerRabin.prototype={},MillerRabin.prototype._randbelow=function(n){var len=n.bitLength(),min_bytes=Math.ceil(len/8);do var a=new bn(this.rand.generate(min_bytes));while(a.cmp(n)>=0);return a},MillerRabin.prototype._randrange=function(start,stop){var size=stop.sub(start);return start.add(this._randbelow(size))},MillerRabin.prototype.test=function(n,k,cb){var len=n.bitLength(),red=bn.mont(n),rone=new bn(1).toRed(red);k||(k=Math.max(1,len/48|0));for(var n1=n.subn(1),s=0;!n1.testn(s);s++);for(var d=n.shrn(s),rn1=n1.toRed(red),prime=!0;k>0;k--){var a=this._randrange(new bn(2),n1);cb&&cb(a);var x=a.toRed(red).redPow(d);if(!(x.cmp(rone)===0||x.cmp(rn1)===0)){for(var i=1;i0;k--){var a=this._randrange(new bn(2),n1),g=n.gcd(a);if(g.cmpn(1)!==0)return g;var x=a.toRed(red).redPow(d);if(!(x.cmp(rone)===0||x.cmp(rn1)===0)){for(var i=1;ibits;)num.ishrn(1);if(num.isEven()&&num.iadd(ONE),num.testn(1)||num.iadd(TWO),gen.cmp(TWO)){if(!gen.cmp(FIVE))for(;num.mod(TEN).cmp(THREE);)num.iadd(FOUR)}else for(;num.mod(TWENTYFOUR).cmp(ELEVEN);)num.iadd(FOUR);if(n2=num.shrn(1),simpleSieve(n2)&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num))return num}}}}),require_primes=__commonJS({\"node_modules/diffie-hellman/lib/primes.json\"(exports,module){module.exports={modp1:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff\"},modp2:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff\"},modp5:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff\"},modp14:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff\"},modp15:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff\"},modp16:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff\"},modp17:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff\"},modp18:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff\"}}}}),require_dh=__commonJS({\"node_modules/diffie-hellman/lib/dh.js\"(exports,module){var BN=require_bn(),MillerRabin=require_mr(),millerRabin=new MillerRabin,TWENTYFOUR=new BN(24),ELEVEN=new BN(11),TEN=new BN(10),THREE=new BN(3),SEVEN=new BN(7),primes=require_generatePrime(),randomBytes=require_browser();module.exports=DH;function setPublicKey(pub,enc){return enc=enc||\"utf8\",Buffer.isBuffer(pub)||(pub=new Buffer(pub,enc)),this._pub=new BN(pub),this}function setPrivateKey(priv,enc){return enc=enc||\"utf8\",Buffer.isBuffer(priv)||(priv=new Buffer(priv,enc)),this._priv=new BN(priv),this}var primeCache={};function checkPrime(prime,generator){var gen=generator.toString(\"hex\"),hex=[gen,prime.toString(16)].join(\"_\");if(hex in primeCache)return primeCache[hex];var error=0;if(prime.isEven()||!primes.simpleSieve||!primes.fermatTest(prime)||!millerRabin.test(prime))return error+=1,gen===\"02\"||gen===\"05\"\?error+=8:error+=4,primeCache[hex]=error,error;millerRabin.test(prime.shrn(1))||(error+=2);var rem;switch(gen){case\"02\":prime.mod(TWENTYFOUR).cmp(ELEVEN)&&(error+=8);break;case\"05\":rem=prime.mod(TEN),rem.cmp(THREE)&&rem.cmp(SEVEN)&&(error+=8);break;default:error+=4}return primeCache[hex]=error,error}function DH(prime,generator,malleable){this.setGenerator(generator),this.__prime=new BN(prime),this._prime=BN.mont(this.__prime),this._primeLen=prime.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,malleable\?(this.setPublicKey=setPublicKey,this.setPrivateKey=setPrivateKey):this._primeCode=8}DH.prototype={},Object.defineProperty(DH.prototype,\"verifyError\",{enumerable:!0,get:function(){return typeof this._primeCode!=\"number\"&&(this._primeCode=checkPrime(this.__prime,this.__gen)),this._primeCode}}),DH.prototype.generateKeys=function(){return this._priv||(this._priv=new BN(randomBytes(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},DH.prototype.computeSecret=function(other){other=new BN(other),other=other.toRed(this._prime);var secret=other.redPow(this._priv).fromRed(),out=new Buffer(secret.toArray()),prime=this.getPrime();if(out.length=0||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=blind(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,\"be\",len)}crt.getr=getr,module.exports=crt}}),require_package=__commonJS({\"node_modules/elliptic/package.json\"(exports,module){module.exports={name:\"elliptic\",version:\"6.5.4\",description:\"EC cryptography\",main:\"lib/elliptic.js\",files:[\"lib\"],scripts:{lint:\"eslint lib test\",\"lint:fix\":\"npm run lint -- --fix\",unit:\"istanbul test _mocha --reporter=spec test/index.js\",test:\"npm run lint && npm run unit\",version:\"grunt dist && git add dist/\"},repository:{type:\"git\",url:\"git@github.com:indutny/elliptic\"},keywords:[\"EC\",\"Elliptic\",\"curve\",\"Cryptography\"],author:\"Fedor Indutny \",license:\"MIT\",bugs:{url:\"https://github.com/indutny/elliptic/issues\"},homepage:\"https://github.com/indutny/elliptic\",devDependencies:{brfs:\"^2.0.2\",coveralls:\"^3.1.0\",eslint:\"^7.6.0\",grunt:\"^1.2.1\",\"grunt-browserify\":\"^5.3.0\",\"grunt-cli\":\"^1.3.2\",\"grunt-contrib-connect\":\"^3.0.0\",\"grunt-contrib-copy\":\"^1.0.0\",\"grunt-contrib-uglify\":\"^5.0.0\",\"grunt-mocha-istanbul\":\"^5.0.2\",\"grunt-saucelabs\":\"^9.0.1\",istanbul:\"^0.4.5\",mocha:\"^8.0.1\"},dependencies:{\"bn.js\":\"^4.11.9\",brorand:\"^1.1.0\",\"hash.js\":\"^1.0.0\",\"hmac-drbg\":\"^1.0.1\",inherits:\"^2.0.4\",\"minimalistic-assert\":\"^1.0.1\",\"minimalistic-crypto-utils\":\"^1.0.1\"}}}}),require_bn4=require_bn,require_utils2=__commonJS({\"node_modules/minimalistic-crypto-utils/lib/utils.js\"(exports){var utils=exports;function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg!=\"string\"){for(var i=0;i>8,lo=c&255;hi\?res.push(hi,lo):res.push(lo)}return res}utils.toArray=toArray;function zero2(word){return word.length===1\?\"0\"+word:word}utils.zero2=zero2;function toHex(msg){for(var res=\"\",i=0;i(ws>>1)-1\?z=(ws>>1)-mod:z=mod,k.isubn(z)):z=0,naf[i]=z,k.iushrn(1)}return naf}utils.getNAF=getNAF;function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone(),k2=k2.clone();for(var d1=0,d2=0,m8;k1.cmpn(-d1)>0||k2.cmpn(-d2)>0;){var m14=k1.andln(3)+d1&3,m24=k2.andln(3)+d2&3;m14===3&&(m14=-1),m24===3&&(m24=-1);var u1;(m14&1)===0\?u1=0:(m8=k1.andln(7)+d1&7,(m8===3||m8===5)&&m24===2\?u1=-m14:u1=m14),jsf[0].push(u1);var u2;(m24&1)===0\?u2=0:(m8=k2.andln(7)+d2&7,(m8===3||m8===5)&&m14===2\?u2=-m24:u2=m24),jsf[1].push(u2),2*d1===u1+1&&(d1=1-d1),2*d2===u2+1&&(d2=1-d2),k1.iushrn(1),k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key=\"_\"+name;obj.prototype[name]=function(){return this[key]!==void 0\?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==\"string\"\?utils.toArray(bytes,\"hex\"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,\"hex\",\"le\")}utils.intFromLE=intFromLE}}),require_base=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/base.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),getNAF=utils.getNAF,getJSF=utils.getJSF,assert=utils.assert;function BaseCurve(type,conf){this.type=type,this.p=new BN(conf.p,16),this.red=conf.prime\?BN.red(conf.prime):BN.mont(this.p),this.zero=new BN(0).toRed(this.red),this.one=new BN(1).toRed(this.red),this.two=new BN(2).toRed(this.red),this.n=conf.n&&new BN(conf.n,16),this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n\?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);!adjustCount||adjustCount.cmpn(100)>0\?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}module.exports=BaseCurve,BaseCurve.prototype={},BaseCurve.prototype.point=function(){throw new Error(\"Not implemented\")},BaseCurve.prototype.validate=function(){throw new Error(\"Not implemented\")},BaseCurve.prototype._fixedNafMul=function(p,k){assert(p.precomputed);var doubles=p._getDoubles(),naf=getNAF(k,1,this._bitLength),I=(1<=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}for(var a=this.jpoint(null,null,null),b=this.jpoint(null,null,null),i=I;i>0;i--){for(j=0;j=0;i--){for(var l=0;i>=0&&naf[i]===0;i--)l++;if(i>=0&&l++,acc=acc.dblp(l),i<0)break;var z=naf[i];assert(z!==0),p.type===\"affine\"\?z>0\?acc=acc.mixedAdd(wnd[z-1>>1]):acc=acc.mixedAdd(wnd[-z-1>>1].neg()):z>0\?acc=acc.add(wnd[z-1>>1]):acc=acc.add(wnd[-z-1>>1].neg())}return p.type===\"affine\"\?acc.toP():acc},BaseCurve.prototype._wnafMulAdd=function(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1,wnd=this._wnafT2,naf=this._wnafT3,max=0,i,j,p;for(i=0;i=1;i-=2){var a=i-1,b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a],this._bitLength),naf[b]=getNAF(coeffs[b],wndWidth[b],this._bitLength),max=Math.max(naf[a].length,max),max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];points[a].y.cmp(points[b].y)===0\?(comb[1]=points[a].add(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg())):points[a].y.cmp(points[b].y.redNeg())===0\?(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].add(points[b].neg())):(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg()));var index=[-3,-1,-5,-7,0,7,5,1,3],jsf=getJSF(coeffs[a],coeffs[b]);for(max=Math.max(jsf[0].length,max),naf[a]=new Array(max),naf[b]=new Array(max),j=0;j=0;i--){for(var k=0;i>=0;){var zero=!0;for(j=0;j=0&&k++,acc=acc.dblp(k),i<0)break;for(j=0;j0\?p=wnd[j][z-1>>1]:z<0&&(p=wnd[j][-z-1>>1].neg()),p.type===\"affine\"\?acc=acc.mixedAdd(p):acc=acc.add(p))}}for(i=0;i=Math.ceil((k.bitLength()+1)/doubles.step):!1},BasePoint.prototype._getDoubles=function(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var doubles=[this],acc=this,i=0;i=0&&(a2=a0,b2=b0),a1.negative&&(a1=a1.neg(),b1=b1.neg()),a2.negative&&(a2=a2.neg(),b2=b2.neg()),[{a:a1,b:b1},{a:a2,b:b2}]},ShortCurve.prototype._endoSplit=function(k){var basis=this.endo.basis,v1=basis[0],v2=basis[1],c1=v2.b.mul(k).divRound(this.n),c2=v1.b.neg().mul(k).divRound(this.n),p1=c1.mul(v1.a),p2=c2.mul(v2.a),q1=c1.mul(v1.b),q2=c2.mul(v2.b),k1=k.sub(p1).sub(p2),k2=q1.add(q2).neg();return{k1,k2}},ShortCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b),y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error(\"invalid point\");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},ShortCurve.prototype.validate=function(point){if(point.inf)return!0;var{x,y}=point,ax=this.a.redMul(x),rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0},ShortCurve.prototype._endoWnafMulAdd=function(points,coeffs,jacobianResult){for(var npoints=this._endoWnafT1,ncoeffs=this._endoWnafT2,i=0;i\":\"\"},Point.prototype.isInfinity=function(){return this.inf},Point.prototype.add=function(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);c.cmpn(0)!==0&&(c=c.redMul(this.x.redSub(p.x).redInvm()));var nx=c.redSqr().redISub(this.x).redISub(p.x),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.dbl=function(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a,x2=this.x.redSqr(),dyinv=ys1.redInvm(),c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv),nx=c.redSqr().redISub(this.x.redAdd(this.x)),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.getX=function(){return this.x.fromRed()},Point.prototype.getY=function(){return this.y.fromRed()},Point.prototype.mul=function(k){return k=new BN(k,16),this.isInfinity()\?this:this._hasDoubles(k)\?this.curve._fixedNafMul(this,k):this.curve.endo\?this.curve._endoWnafMulAdd([this],[k]):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo\?this.curve._endoWnafMulAdd(points,coeffs):this.curve._wnafMulAdd(1,points,coeffs,2)},Point.prototype.jmulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo\?this.curve._endoWnafMulAdd(points,coeffs,!0):this.curve._wnafMulAdd(1,points,coeffs,2,!0)},Point.prototype.eq=function(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)},Point.prototype.neg=function(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed,negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res},Point.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,\"jacobian\"),x===null&&y===null&&z===null\?(this.x=this.curve.one,this.y=this.curve.one,this.z=new BN(0)):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=new BN(z,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}inherits(JPoint,Base.BasePoint),ShortCurve.prototype.jpoint=function(x,y,z){return new JPoint(this,x,y,z)},JPoint.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm(),zinv2=zinv.redSqr(),ax=this.x.redMul(zinv2),ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)},JPoint.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},JPoint.prototype.add=function(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr(),z2=this.z.redSqr(),u1=this.x.redMul(pz2),u2=p.x.redMul(z2),s1=this.y.redMul(pz2.redMul(p.z)),s2=p.y.redMul(z2.redMul(this.z)),h=u1.redSub(u2),r=s1.redSub(s2);if(h.cmpn(0)===0)return r.cmpn(0)!==0\?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.mixedAdd=function(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr(),u1=this.x,u2=p.x.redMul(z2),s1=this.y,s2=p.y.redMul(z2).redMul(this.z),h=u1.redSub(u2),r=s1.redSub(s2);if(h.cmpn(0)===0)return r.cmpn(0)!==0\?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.dblp=function(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i=0)return!1;if(rx.redIAdd(t),this.x.cmp(rx)===0)return!0}},JPoint.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},JPoint.prototype.isInfinity=function(){return this.z.cmpn(0)===0}}}),require_mont=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/mont.js\"(exports,module){var BN=require_bn4(),inherits=require_inherits_browser(),Base=require_base(),utils=require_utils3();function MontCurve(conf){Base.call(this,\"mont\",conf),this.a=new BN(conf.a,16).toRed(this.red),this.b=new BN(conf.b,16).toRed(this.red),this.i4=new BN(4).toRed(this.red).redInvm(),this.two=new BN(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits(MontCurve,Base),module.exports=MontCurve,MontCurve.prototype.validate=function(point){var x=point.normalize().x,x2=x.redSqr(),rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x),y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point(curve,x,z){Base.BasePoint.call(this,curve,\"projective\"),x===null&&z===null\?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new BN(x,16),this.z=new BN(z,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}inherits(Point,Base.BasePoint),MontCurve.prototype.decodePoint=function(bytes,enc){return this.point(utils.toArray(bytes,enc),1)},MontCurve.prototype.point=function(x,z){return new Point(this,x,z)},MontCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},Point.prototype.precompute=function(){},Point.prototype._encode=function(){return this.getX().toArray(\"be\",this.curve.p.byteLength())},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)},Point.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},Point.prototype.isInfinity=function(){return this.z.cmpn(0)===0},Point.prototype.dbl=function(){var a=this.x.redAdd(this.z),aa=a.redSqr(),b=this.x.redSub(this.z),bb=b.redSqr(),c=aa.redSub(bb),nx=aa.redMul(bb),nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)},Point.prototype.add=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.diffAdd=function(p,diff){var a=this.x.redAdd(this.z),b=this.x.redSub(this.z),c=p.x.redAdd(p.z),d=p.x.redSub(p.z),da=d.redMul(a),cb=c.redMul(b),nx=diff.z.redMul(da.redAdd(cb).redSqr()),nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)},Point.prototype.mul=function(k){for(var t=k.clone(),a=this,b=this.curve.point(null,null),c=this,bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--)bits[i]===0\?(a=a.diffAdd(b,c),b=b.dbl()):(b=a.diffAdd(b,c),a=a.dbl());return b},Point.prototype.mulAdd=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.jumlAdd=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.eq=function(other){return this.getX().cmp(other.getX())===0},Point.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()}}}),require_edwards=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/edwards.js\"(exports,module){var utils=require_utils3(),BN=require_bn4(),inherits=require_inherits_browser(),Base=require_base(),assert=utils.assert;function EdwardsCurve(conf){this.twisted=(conf.a|0)!==1,this.mOneA=this.twisted&&(conf.a|0)===-1,this.extended=this.mOneA,Base.call(this,\"edwards\",conf),this.a=new BN(conf.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new BN(conf.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new BN(conf.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),assert(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(conf.c|0)===1}inherits(EdwardsCurve,Base),module.exports=EdwardsCurve,EdwardsCurve.prototype._mulA=function(num){return this.mOneA\?num.redNeg():this.a.redMul(num)},EdwardsCurve.prototype._mulC=function(num){return this.oneC\?num:this.c.redMul(num)},EdwardsCurve.prototype.jpoint=function(x,y,z,t){return this.point(x,y,z,t)},EdwardsCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var x2=x.redSqr(),rhs=this.c2.redSub(this.a.redMul(x2)),lhs=this.one.redSub(this.c2.redMul(this.d).redMul(x2)),y2=rhs.redMul(lhs.redInvm()),y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error(\"invalid point\");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},EdwardsCurve.prototype.pointFromY=function(y,odd){y=new BN(y,16),y.red||(y=y.toRed(this.red));var y2=y.redSqr(),lhs=y2.redSub(this.c2),rhs=y2.redMul(this.d).redMul(this.c2).redSub(this.a),x2=lhs.redMul(rhs.redInvm());if(x2.cmp(this.zero)===0){if(odd)throw new Error(\"invalid point\");return this.point(this.zero,y)}var x=x2.redSqrt();if(x.redSqr().redSub(x2).cmp(this.zero)!==0)throw new Error(\"invalid point\");return x.fromRed().isOdd()!==odd&&(x=x.redNeg()),this.point(x,y)},EdwardsCurve.prototype.validate=function(point){if(point.isInfinity())return!0;point.normalize();var x2=point.x.redSqr(),y2=point.y.redSqr(),lhs=x2.redMul(this.a).redAdd(y2),rhs=this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));return lhs.cmp(rhs)===0};function Point(curve,x,y,z,t){Base.BasePoint.call(this,curve,\"projective\"),x===null&&y===null&&z===null\?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=z\?new BN(z,16):this.curve.one,this.t=t&&new BN(t,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}inherits(Point,Base.BasePoint),EdwardsCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},EdwardsCurve.prototype.point=function(x,y,z,t){return new Point(this,x,y,z,t)},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1],obj[2])},Point.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},Point.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},Point.prototype._extDbl=function(){var a=this.x.redSqr(),b=this.y.redSqr(),c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a),e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b),g=d.redAdd(b),f=g.redSub(c),h=d.redSub(b),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projDbl=function(){var b=this.x.redAdd(this.y).redSqr(),c=this.x.redSqr(),d=this.y.redSqr(),nx,ny,nz,e,h,j;if(this.curve.twisted){e=this.curve._mulA(c);var f=e.redAdd(d);this.zOne\?(nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)),ny=f.redMul(e.redSub(d)),nz=f.redSqr().redSub(f).redSub(f)):(h=this.z.redSqr(),j=f.redSub(h).redISub(h),nx=b.redSub(c).redISub(d).redMul(j),ny=f.redMul(e.redSub(d)),nz=f.redMul(j))}else e=c.redAdd(d),h=this.curve._mulC(this.z).redSqr(),j=e.redSub(h).redSub(h),nx=this.curve._mulC(b.redISub(e)).redMul(j),ny=this.curve._mulC(e).redMul(c.redISub(d)),nz=e.redMul(j);return this.curve.point(nx,ny,nz)},Point.prototype.dbl=function(){return this.isInfinity()\?this:this.curve.extended\?this._extDbl():this._projDbl()},Point.prototype._extAdd=function(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x)),b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)),c=this.t.redMul(this.curve.dd).redMul(p.t),d=this.z.redMul(p.z.redAdd(p.z)),e=b.redSub(a),f=d.redSub(c),g=d.redAdd(c),h=b.redAdd(a),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projAdd=function(p){var a=this.z.redMul(p.z),b=a.redSqr(),c=this.x.redMul(p.x),d=this.y.redMul(p.y),e=this.curve.d.redMul(c).redMul(d),f=b.redSub(e),g=b.redAdd(e),tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d),nx=a.redMul(f).redMul(tmp),ny,nz;return this.curve.twisted\?(ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c))),nz=f.redMul(g)):(ny=a.redMul(g).redMul(d.redSub(c)),nz=this.curve._mulC(f).redMul(g)),this.curve.point(nx,ny,nz)},Point.prototype.add=function(p){return this.isInfinity()\?p:p.isInfinity()\?this:this.curve.extended\?this._extAdd(p):this._projAdd(p)},Point.prototype.mul=function(k){return this._hasDoubles(k)\?this.curve._fixedNafMul(this,k):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!1)},Point.prototype.jmulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!0)},Point.prototype.normalize=function(){if(this.zOne)return this;var zi=this.z.redInvm();return this.x=this.x.redMul(zi),this.y=this.y.redMul(zi),this.t&&(this.t=this.t.redMul(zi)),this.z=this.curve.one,this.zOne=!0,this},Point.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Point.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Point.prototype.eq=function(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0},Point.prototype.eqXToP=function(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return!0;for(var xc=x.clone(),t=this.curve.redN.redMul(this.z);;){if(xc.iadd(this.curve.n),xc.cmp(this.curve.p)>=0)return!1;if(rx.redIAdd(t),this.x.cmp(rx)===0)return!0}},Point.prototype.toP=Point.prototype.normalize,Point.prototype.mixedAdd=Point.prototype.add}}),require_curve=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/index.js\"(exports){var curve=exports;curve.base=require_base(),curve.short=require_short(),curve.mont=require_mont(),curve.edwards=require_edwards()}}),require_utils4=__commonJS({\"node_modules/hash.js/lib/hash/utils.js\"(exports){var assert=require_minimalistic_assert(),inherits=require_inherits_browser();exports.inherits=inherits;function isSurrogatePair(msg,i){return(msg.charCodeAt(i)&64512)!==55296||i<0||i+1>=msg.length\?!1:(msg.charCodeAt(i+1)&64512)===56320}function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg==\"string\")if(enc){if(enc===\"hex\")for(msg=msg.replace(/[^a-z0-9]+/gi,\"\"),msg.length%2!==0&&(msg=\"0\"+msg),i=0;i>6|192,res[p++]=c&63|128):isSurrogatePair(msg,i)\?(c=65536+((c&1023)<<10)+(msg.charCodeAt(++i)&1023),res[p++]=c>>18|240,res[p++]=c>>12&63|128,res[p++]=c>>6&63|128,res[p++]=c&63|128):(res[p++]=c>>12|224,res[p++]=c>>6&63|128,res[p++]=c&63|128)}else for(i=0;i>>24|w>>>8&65280|w<<8&16711680|(w&255)<<24;return res>>>0}exports.htonl=htonl;function toHex32(msg,endian){for(var res=\"\",i=0;i>>0}return res}exports.join32=join32;function split32(msg,endian){for(var res=new Array(msg.length*4),i=0,k=0;i>>24,res[k+1]=m>>>16&255,res[k+2]=m>>>8&255,res[k+3]=m&255):(res[k+3]=m>>>24,res[k+2]=m>>>16&255,res[k+1]=m>>>8&255,res[k]=m&255)}return res}exports.split32=split32;function rotr32(w,b){return w>>>b|w<<32-b}exports.rotr32=rotr32;function rotl32(w,b){return w<>>32-b}exports.rotl32=rotl32;function sum32(a,b){return a+b>>>0}exports.sum32=sum32;function sum32_3(a,b,c){return a+b+c>>>0}exports.sum32_3=sum32_3;function sum32_4(a,b,c,d){return a+b+c+d>>>0}exports.sum32_4=sum32_4;function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}exports.sum32_5=sum32_5;function sum64(buf,pos,ah,al){var bh=buf[pos],bl=buf[pos+1],lo=al+bl>>>0,hi=(lo>>0,buf[pos+1]=lo}exports.sum64=sum64;function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0,hi=(lo>>0}exports.sum64_hi=sum64_hi;function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}exports.sum64_lo=sum64_lo;function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}exports.sum64_4_hi=sum64_4_hi;function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}exports.sum64_4_lo=sum64_4_lo;function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}exports.sum64_5_hi=sum64_5_hi;function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}exports.sum64_5_lo=sum64_5_lo;function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}exports.rotr64_hi=rotr64_hi;function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.rotr64_lo=rotr64_lo;function shr64_hi(ah,al,num){return ah>>>num}exports.shr64_hi=shr64_hi;function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.shr64_lo=shr64_lo}}),require_common=__commonJS({\"node_modules/hash.js/lib/hash/common.js\"(exports){var utils=require_utils4(),assert=require_minimalistic_assert();function BlockHash(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian=\"big\",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}BlockHash.prototype={},exports.BlockHash=BlockHash,BlockHash.prototype.update=function(msg,enc){if(msg=utils.toArray(msg,enc),this.pending\?this.pending=this.pending.concat(msg):this.pending=msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),this.pending.length===0&&(this.pending=null),msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i>>24&255,res[i++]=len>>>16&255,res[i++]=len>>>8&255,res[i++]=len&255}else for(res[i++]=len&255,res[i++]=len>>>8&255,res[i++]=len>>>16&255,res[i++]=len>>>24&255,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,t=8;t>>3}exports.g0_256=g0_256;function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}exports.g1_256=g1_256}}),require__=__commonJS({\"node_modules/hash.js/lib/hash/sha/1.js\"(exports,module){var utils=require_utils4(),common=require_common(),shaCommon=require_common2(),rotl32=utils.rotl32,sum32=utils.sum32,sum32_5=utils.sum32_5,ft_1=shaCommon.ft_1,BlockHash=common.BlockHash,sha1_K=[1518500249,1859775393,2400959708,3395469782];function SHA1(){if(!(this instanceof SHA1))return new SHA1;BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}utils.inherits(SHA1,BlockHash),module.exports=SHA1,SHA1.blockSize=512,SHA1.outSize=160,SHA1.hmacStrength=80,SHA1.padLength=64,SHA1.prototype._update=function(msg,start){for(var W=this.W,i=0;i<16;i++)W[i]=msg[start+i];for(;ithis.blockSize&&(key=new this.Hash().update(key).digest()),assert(key.length<=this.blockSize);for(var i=key.length;i=this.minEntropy/8,\"Not enough entropy. Minimum is: \"+this.minEntropy+\" bits\"),this._init(entropy,nonce,pers)}HmacDRBG.prototype={},module.exports=HmacDRBG,HmacDRBG.prototype._init=function(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,\"Not enough entropy. Minimum is: \"+this.minEntropy+\" bits\"),this._update(entropy.concat(add||[])),this._reseed=1},HmacDRBG.prototype.generate=function(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error(\"Reseed is required\");typeof enc!=\"string\"&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc||\"hex\"),this._update(add));for(var temp=[];temp.length\"}}}),require_signature=__commonJS({\"node_modules/elliptic/lib/elliptic/ec/signature.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),assert=utils.assert;function Signature(options,enc){if(options instanceof Signature)return options;this._importDER(options,enc)||(assert(options.r&&options.s,\"Signature without r or s\"),this.r=new BN(options.r,16),this.s=new BN(options.s,16),options.recoveryParam===void 0\?this.recoveryParam=null:this.recoveryParam=options.recoveryParam)}Signature.prototype={},module.exports=Signature;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128))return initial;var octetLen=initial&15;if(octetLen===0||octetLen>4)return!1;for(var val=0,i=0,off=p.place;i>>=0;return val<=127\?!1:(p.place=off,val)}function rmPadding(buf){for(var i=0,len=buf.length-1;!buf[i]&&!(buf[i+1]&128)&&i>>3);for(arr.push(octets|128);--octets;)arr.push(len>>>(octets<<3)&255);arr.push(len)}Signature.prototype.toDER=function(enc){var r=this.r.toArray(),s=this.s.toArray();for(r[0]&128&&(r=[0].concat(r)),s[0]&128&&(s=[0].concat(s)),r=rmPadding(r),s=rmPadding(s);!s[0]&&!(s[1]&128);)s=s.slice(1);var arr=[2];constructLength(arr,r.length),arr=arr.concat(r),arr.push(2),constructLength(arr,s.length);var backHalf=arr.concat(s),res=[48];return constructLength(res,backHalf.length),res=res.concat(backHalf),utils.encode(res,enc)}}}),require_ec=__commonJS({\"node_modules/elliptic/lib/elliptic/ec/index.js\"(exports,module){var BN=require_bn4(),HmacDRBG=require_hmac_drbg(),utils=require_utils3(),curves=require_curves(),rand=require_brorand(),assert=utils.assert,KeyPair=require_key(),Signature=require_signature();function EC(options){if(!(this instanceof EC))return new EC(options);typeof options==\"string\"&&(assert(Object.prototype.hasOwnProperty.call(curves,options),\"Unknown curve \"+options),options=curves[options]),options instanceof curves.PresetCurve&&(options={curve:options}),this.curve=options.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=options.curve.g,this.g.precompute(options.curve.n.bitLength()+1),this.hash=options.hash||options.curve.hash}EC.prototype={},module.exports=EC,EC.prototype.keyPair=function(options){return new KeyPair(this,options)},EC.prototype.keyFromPrivate=function(priv,enc){return KeyPair.fromPrivate(this,priv,enc)},EC.prototype.keyFromPublic=function(pub,enc){return KeyPair.fromPublic(this,pub,enc)},EC.prototype.genKeyPair=function(options){options||(options={});for(var drbg=new HmacDRBG({hash:this.hash,pers:options.pers,persEnc:options.persEnc||\"utf8\",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||\"utf8\",nonce:this.n.toArray()}),bytes=this.n.byteLength(),ns2=this.n.sub(new BN(2));;){var priv=new BN(drbg.generate(bytes));if(!(priv.cmp(ns2)>0))return priv.iaddn(1),this.keyFromPrivate(priv)}},EC.prototype._truncateToN=function(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();return delta>0&&(msg=msg.ushrn(delta)),!truncOnly&&msg.cmp(this.n)>=0\?msg.sub(this.n):msg},EC.prototype.sign=function(msg,key,enc,options){typeof enc==\"object\"&&(options=enc,enc=null),options||(options={}),key=this.keyFromPrivate(key,enc),msg=this._truncateToN(new BN(msg,16));for(var bytes=this.n.byteLength(),bkey=key.getPrivate().toArray(\"be\",bytes),nonce=msg.toArray(\"be\",bytes),drbg=new HmacDRBG({hash:this.hash,entropy:bkey,nonce,pers:options.pers,persEnc:options.persEnc||\"utf8\"}),ns1=this.n.sub(new BN(1)),iter=0;;iter++){var k=options.k\?options.k(iter):new BN(drbg.generate(this.n.byteLength()));if(k=this._truncateToN(k,!0),!(k.cmpn(1)<=0||k.cmp(ns1)>=0)){var kp=this.g.mul(k);if(!kp.isInfinity()){var kpX=kp.getX(),r=kpX.umod(this.n);if(r.cmpn(0)!==0){var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));if(s=s.umod(this.n),s.cmpn(0)!==0){var recoveryParam=(kp.getY().isOdd()\?1:0)|(kpX.cmp(r)!==0\?2:0);return options.canonical&&s.cmp(this.nh)>0&&(s=this.n.sub(s),recoveryParam^=1),new Signature({r,s,recoveryParam})}}}}}},EC.prototype.verify=function(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16)),key=this.keyFromPublic(key,enc),signature=new Signature(signature,\"hex\");var{r,s}=signature;if(r.cmpn(1)<0||r.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var sinv=s.invm(this.n),u1=sinv.mul(msg).umod(this.n),u2=sinv.mul(r).umod(this.n),p;return this.curve._maxwellTrick\?(p=this.g.jmulAdd(u1,key.getPublic(),u2),p.isInfinity()\?!1:p.eqXToP(r)):(p=this.g.mulAdd(u1,key.getPublic(),u2),p.isInfinity()\?!1:p.getX().umod(this.n).cmp(r)===0)},EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,\"The recovery param is more than two bits\"),signature=new Signature(signature,enc);var n=this.n,e=new BN(msg),r=signature.r,s=signature.s,isYOdd=j&1,isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error(\"Unable to find sencond key candinate\");isSecondKey\?r=this.curve.pointFromX(r.add(this.curve.n),isYOdd):r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n),s1=n.sub(e).mul(rInv).umod(n),s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)},EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){if(signature=new Signature(signature,enc),signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch{continue}if(Qprime.eq(Q))return i}throw new Error(\"Unable to find valid recovery factor\")}}}),require_key2=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/key.js\"(exports,module){var utils=require_utils3(),assert=utils.assert,parseBytes=utils.parseBytes,cachedProperty=utils.cachedProperty;function KeyPair(eddsa,params){this.eddsa=eddsa,this._secret=parseBytes(params.secret),eddsa.isPoint(params.pub)\?this._pub=params.pub:this._pubBytes=parseBytes(params.pub)}KeyPair.prototype={},KeyPair.fromPublic=function(eddsa,pub){return pub instanceof KeyPair\?pub:new KeyPair(eddsa,{pub})},KeyPair.fromSecret=function(eddsa,secret){return secret instanceof KeyPair\?secret:new KeyPair(eddsa,{secret})},KeyPair.prototype.secret=function(){return this._secret},cachedProperty(KeyPair,\"pubBytes\",function(){return this.eddsa.encodePoint(this.pub())}),cachedProperty(KeyPair,\"pub\",function(){return this._pubBytes\?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())}),cachedProperty(KeyPair,\"privBytes\",function(){var eddsa=this.eddsa,hash=this.hash(),lastIx=eddsa.encodingLength-1,a=hash.slice(0,eddsa.encodingLength);return a[0]&=248,a[lastIx]&=127,a[lastIx]|=64,a}),cachedProperty(KeyPair,\"priv\",function(){return this.eddsa.decodeInt(this.privBytes())}),cachedProperty(KeyPair,\"hash\",function(){return this.eddsa.hash().update(this.secret()).digest()}),cachedProperty(KeyPair,\"messagePrefix\",function(){return this.hash().slice(this.eddsa.encodingLength)}),KeyPair.prototype.sign=function(message){return assert(this._secret,\"KeyPair can only verify\"),this.eddsa.sign(message,this)},KeyPair.prototype.verify=function(message,sig){return this.eddsa.verify(message,sig,this)},KeyPair.prototype.getSecret=function(enc){return assert(this._secret,\"KeyPair is public only\"),utils.encode(this.secret(),enc)},KeyPair.prototype.getPublic=function(enc){return utils.encode(this.pubBytes(),enc)},module.exports=KeyPair}}),require_signature2=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/signature.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),assert=utils.assert,cachedProperty=utils.cachedProperty,parseBytes=utils.parseBytes;function Signature(eddsa,sig){this.eddsa=eddsa,typeof sig!=\"object\"&&(sig=parseBytes(sig)),Array.isArray(sig)&&(sig={R:sig.slice(0,eddsa.encodingLength),S:sig.slice(eddsa.encodingLength)}),assert(sig.R&&sig.S,\"Signature without R or S\"),eddsa.isPoint(sig.R)&&(this._R=sig.R),sig.S instanceof BN&&(this._S=sig.S),this._Rencoded=Array.isArray(sig.R)\?sig.R:sig.Rencoded,this._Sencoded=Array.isArray(sig.S)\?sig.S:sig.Sencoded}Signature.prototype={},cachedProperty(Signature,\"S\",function(){return this.eddsa.decodeInt(this.Sencoded())}),cachedProperty(Signature,\"R\",function(){return this.eddsa.decodePoint(this.Rencoded())}),cachedProperty(Signature,\"Rencoded\",function(){return this.eddsa.encodePoint(this.R())}),cachedProperty(Signature,\"Sencoded\",function(){return this.eddsa.encodeInt(this.S())}),Signature.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Signature.prototype.toHex=function(){return utils.encode(this.toBytes(),\"hex\").toUpperCase()},module.exports=Signature}}),require_eddsa=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/index.js\"(exports,module){var hash=require_hash2(),curves=require_curves(),utils=require_utils3(),assert=utils.assert,parseBytes=utils.parseBytes,KeyPair=require_key2(),Signature=require_signature2();function EDDSA(curve){if(assert(curve===\"ed25519\",\"only tested with ed25519 so far\"),!(this instanceof EDDSA))return new EDDSA(curve);curve=curves[curve].curve,this.curve=curve,this.g=curve.g,this.g.precompute(curve.n.bitLength()+1),this.pointClass=curve.point().constructor,this.encodingLength=Math.ceil(curve.n.bitLength()/8),this.hash=hash.sha512}EDDSA.prototype={},module.exports=EDDSA,EDDSA.prototype.sign=function(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret),r=this.hashInt(key.messagePrefix(),message),R=this.g.mul(r),Rencoded=this.encodePoint(R),s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv()),S=r.add(s_).umod(this.curve.n);return this.makeSignature({R,S,Rencoded})},EDDSA.prototype.verify=function(message,sig,pub){message=parseBytes(message),sig=this.makeSignature(sig);var key=this.keyFromPublic(pub),h=this.hashInt(sig.Rencoded(),key.pubBytes(),message),SG=this.g.mul(sig.S()),RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)},EDDSA.prototype.hashInt=function(){for(var hash2=this.hash(),i=0;i\"u\")@throwTypeError(\"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type \"+typeof value);return Buffer2(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if(typeof size!=\"number\")@throwTypeError('The \"size\" argument must be of type number. Received type '+typeof size);if(size<0||size>=2*(1<<30))@throwRangeError('The value \"'+size+'\" is invalid for option \"size\"');var buf=Buffer2(size);return!fill||fill.length===0\?buf.fill(0):typeof encoding==\"string\"\?buf.fill(fill,encoding):buf.fill(fill),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=MAX_STRING_LENGTH}catch{}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}}),require_reporter=__commonJS({\"node_modules/asn1.js/lib/asn1/base/reporter.js\"(exports){var inherits=require_inherits_browser();function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}Reporter.prototype={},exports.Reporter=Reporter,Reporter.prototype.isError=function(obj){return obj instanceof ReporterError},Reporter.prototype.save=function(){let state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function(data){let state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function(index){let state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function(index,key,value){let state=this._reporterState;this.exitKey(index),state.obj!==null&&(state.obj[key]=value)},Reporter.prototype.path=function(){return this._reporterState.path.join(\"/\")},Reporter.prototype.enterObject=function(){let state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function(prev){let state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function(msg){let err,state=this._reporterState,inherited=msg instanceof ReporterError;if(inherited\?err=msg:err=new ReporterError(state.path.map(function(elem){return\"[\"+JSON.stringify(elem)+\"]\"}).join(\"\"),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function(result){let state=this._reporterState;return state.options.partial\?{result:this.isError(result)\?null:result,errors:state.errors}:result};function ReporterError(path,msg){this.path=path,this.rethrow(msg)}inherits(ReporterError,Error),ReporterError.prototype.rethrow=function(msg){if(this.message=msg+\" at: \"+(this.path||\"(shallow)\"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}}}),require_buffer=__commonJS({\"node_modules/asn1.js/lib/asn1/base/buffer.js\"(exports){var inherits=require_inherits_browser(),Reporter=require_reporter().Reporter,Buffer2=require_safer().Buffer;function DecoderBuffer(base,options){if(Reporter.call(this,options),!Buffer2.isBuffer(base)){this.error(\"Input not Buffer\");return}this.base=base,this.offset=0,this.length=base.length}inherits(DecoderBuffer,Reporter),exports.DecoderBuffer=DecoderBuffer,DecoderBuffer.isDecoderBuffer=function(data){return data instanceof DecoderBuffer\?!0:typeof data==\"object\"&&Buffer2.isBuffer(data.base)&&data.constructor.name===\"DecoderBuffer\"&&typeof data.offset==\"number\"&&typeof data.length==\"number\"&&typeof data.save==\"function\"&&typeof data.restore==\"function\"&&typeof data.isEmpty==\"function\"&&typeof data.readUInt8==\"function\"&&typeof data.skip==\"function\"&&typeof data.raw==\"function\"},DecoderBuffer.prototype.save=function(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function(save){let res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function(fail){return this.offset+1<=this.length\?this.base.readUInt8(this.offset++,!0):this.error(fail||\"DecoderBuffer overrun\")},DecoderBuffer.prototype.skip=function(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||\"DecoderBuffer overrun\");let res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function(save){return this.base.slice(save\?save.offset:this.offset,this.length)};function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return EncoderBuffer.isEncoderBuffer(item)||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if(typeof value==\"number\"){if(!(0<=value&&value<=255))return reporter.error(\"non-byte EncoderBuffer value\");this.value=value,this.length=1}else if(typeof value==\"string\")this.value=value,this.length=Buffer2.byteLength(value);else if(Buffer2.isBuffer(value))this.value=value,this.length=value.length;else return reporter.error(\"Unsupported type: \"+typeof value)}EncoderBuffer.prototype={},exports.EncoderBuffer=EncoderBuffer,EncoderBuffer.isEncoderBuffer=function(data){return data instanceof EncoderBuffer\?!0:typeof data==\"object\"&&data.constructor.name===\"EncoderBuffer\"&&typeof data.length==\"number\"&&typeof data.join==\"function\"},EncoderBuffer.prototype.join=function(out,offset){return out||(out=Buffer2.alloc(this.length)),offset||(offset=0),this.length===0||(Array.isArray(this.value)\?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):(typeof this.value==\"number\"\?out[offset]=this.value:typeof this.value==\"string\"\?out.write(this.value,offset):Buffer2.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length)),out}}}),require_node=__commonJS({\"node_modules/asn1.js/lib/asn1/base/node.js\"(exports,module){var Reporter=require_reporter().Reporter,EncoderBuffer=require_buffer().EncoderBuffer,DecoderBuffer=require_buffer().DecoderBuffer,assert=require_minimalistic_assert(),tags=[\"seq\",\"seqof\",\"set\",\"setof\",\"objid\",\"bool\",\"gentime\",\"utctime\",\"null_\",\"enum\",\"int\",\"objDesc\",\"bitstr\",\"bmpstr\",\"charstr\",\"genstr\",\"graphstr\",\"ia5str\",\"iso646str\",\"numstr\",\"octstr\",\"printstr\",\"t61str\",\"unistr\",\"utf8str\",\"videostr\"],methods=[\"key\",\"obj\",\"use\",\"optional\",\"explicit\",\"implicit\",\"def\",\"choice\",\"any\",\"contains\"].concat(tags),overrided=[\"_peekTag\",\"_decodeTag\",\"_use\",\"_decodeStr\",\"_decodeObjid\",\"_decodeTime\",\"_decodeNull\",\"_decodeInt\",\"_decodeBool\",\"_decodeList\",\"_encodeComposite\",\"_encodeStr\",\"_encodeObjid\",\"_encodeTime\",\"_encodeNull\",\"_encodeInt\",\"_encodeBool\"];function Node(enc,parent,name){let state={};this._baseState=state,state.name=name,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state.default=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}Node.prototype={},module.exports=Node;var stateProps=[\"enc\",\"parent\",\"children\",\"tag\",\"args\",\"reverseArgs\",\"choice\",\"optional\",\"any\",\"obj\",\"use\",\"alteredUse\",\"key\",\"default\",\"explicit\",\"implicit\",\"contains\"];Node.prototype.clone=function(){let state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});let res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function(){let state=this._baseState;methods.forEach(function(method){this[method]=function(){let clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function(body){let state=this._baseState;assert(state.parent===null),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,\"Root node can have only one child\")},Node.prototype._useArgs=function(args){let state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),children.length!==0&&(assert(state.children===null),state.children=children,children.forEach(function(child){child._baseState.parent=this},this)),args.length!==0&&(assert(state.args===null),state.args=args,state.reverseArgs=args.map(function(arg){if(typeof arg!=\"object\"||arg.constructor!==Object)return arg;let res={};return Object.keys(arg).forEach(function(key){key==(key|0)&&(key|=0);let value=arg[key];res[value]=key}),res}))},overrided.forEach(function(method){Node.prototype[method]=function(){let state=this._baseState;throw new Error(method+\" not implemented for encoding: \"+state.enc)}}),tags.forEach(function(tag){Node.prototype[tag]=function(){let state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(state.tag===null),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function(item){assert(item);let state=this._baseState;return assert(state.use===null),state.use=item,this},Node.prototype.optional=function(){let state=this._baseState;return state.optional=!0,this},Node.prototype.def=function(val){let state=this._baseState;return assert(state.default===null),state.default=val,state.optional=!0,this},Node.prototype.explicit=function(num){let state=this._baseState;return assert(state.explicit===null&&state.implicit===null),state.explicit=num,this},Node.prototype.implicit=function(num){let state=this._baseState;return assert(state.explicit===null&&state.implicit===null),state.implicit=num,this},Node.prototype.obj=function(){let state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,args.length!==0&&this._useArgs(args),this},Node.prototype.key=function(newKey){let state=this._baseState;return assert(state.key===null),state.key=newKey,this},Node.prototype.any=function(){let state=this._baseState;return state.any=!0,this},Node.prototype.choice=function(obj){let state=this._baseState;return assert(state.choice===null),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function(item){let state=this._baseState;return assert(state.use===null),state.contains=item,this},Node.prototype._decode=function(input,options){let state=this._baseState;if(state.parent===null)return input.wrapResult(state.children[0]._decode(input,options));let result=state.default,present=!0,prevKey=null;if(state.key!==null&&(prevKey=input.enterKey(state.key)),state.optional){let tag=null;if(state.explicit!==null\?tag=state.explicit:state.implicit!==null\?tag=state.implicit:state.tag!==null&&(tag=state.tag),tag===null&&!state.any){let save=input.save();try{state.choice===null\?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch{present=!1}input.restore(save)}else if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}let prevObj;if(state.obj&&present&&(prevObj=input.enterObject()),present){if(state.explicit!==null){let explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}let start=input.offset;if(state.use===null&&state.choice===null){let save;state.any&&(save=input.save());let body=this._decodeTag(input,state.implicit!==null\?state.implicit:state.tag,state.any);if(input.isError(body))return body;state.any\?result=input.raw(save):input=body}if(options&&options.track&&state.tag!==null&&options.track(input.path(),start,input.length,\"tagged\"),options&&options.track&&state.tag!==null&&options.track(input.path(),input.offset,input.length,\"content\"),state.any||(state.choice===null\?result=this._decodeGeneric(state.tag,input,options):result=this._decodeChoice(input,options)),input.isError(result))return result;if(!state.any&&state.choice===null&&state.children!==null&&state.children.forEach(function(child){child._decode(input,options)}),state.contains&&(state.tag===\"octstr\"||state.tag===\"bitstr\")){let data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),state.key!==null&&(result!==null||present===!0)\?input.leaveKey(prevKey,state.key,result):prevKey!==null&&input.exitKey(prevKey),result},Node.prototype._decodeGeneric=function(tag,input,options){let state=this._baseState;return tag===\"seq\"||tag===\"set\"\?null:tag===\"seqof\"||tag===\"setof\"\?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)\?this._decodeStr(input,tag,options):tag===\"objid\"&&state.args\?this._decodeObjid(input,state.args[0],state.args[1],options):tag===\"objid\"\?this._decodeObjid(input,null,null,options):tag===\"gentime\"||tag===\"utctime\"\?this._decodeTime(input,tag,options):tag===\"null_\"\?this._decodeNull(input,options):tag===\"bool\"\?this._decodeBool(input,options):tag===\"objDesc\"\?this._decodeStr(input,tag,options):tag===\"int\"||tag===\"enum\"\?this._decodeInt(input,state.args&&state.args[0],options):state.use!==null\?this._getUse(state.use,input._reporterState.obj)._decode(input,options):input.error(\"unknown tag: \"+tag)},Node.prototype._getUse=function(entity,obj){let state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(state.useDecoder._baseState.parent===null),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function(input,options){let state=this._baseState,result=null,match=!1;return Object.keys(state.choice).some(function(key){let save=input.save(),node=state.choice[key];try{let value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value},match=!0}catch{return input.restore(save),!1}return!0},this),match\?result:input.error(\"Choice not matched\")},Node.prototype._createEncoderBuffer=function(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function(data,reporter,parent){let state=this._baseState;if(state.default!==null&&state.default===data)return;let result=this._encodeValue(data,reporter,parent);if(result!==void 0&&!this._skipDefault(result,reporter,parent))return result},Node.prototype._encodeValue=function(data,reporter,parent){let state=this._baseState;if(state.parent===null)return state.children[0]._encode(data,reporter||new Reporter);let result=null;if(this.reporter=reporter,state.optional&&data===void 0)if(state.default!==null)data=state.default;else return;let content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){if(child._baseState.tag===\"null_\")return child._encode(null,reporter,data);if(child._baseState.key===null)return reporter.error(\"Child should have a key\");let prevKey=reporter.enterKey(child._baseState.key);if(typeof data!=\"object\")return reporter.error(\"Child expected, but input is not object\");let res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if(state.tag===\"seqof\"||state.tag===\"setof\"){if(!(state.args&&state.args.length===1))return reporter.error(\"Too many args for : \"+state.tag);if(!Array.isArray(data))return reporter.error(\"seqof/setof, but data is not Array\");let child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){let state2=this._baseState;return this._getUse(state2.args[0],data)._encode(item,reporter)},child))}else state.use!==null\?result=this._getUse(state.use,parent)._encode(data,reporter):(content=this._encodePrimitive(state.tag,data),primitive=!0);if(!state.any&&state.choice===null){let tag=state.implicit!==null\?state.implicit:state.tag,cls=state.implicit===null\?\"universal\":\"context\";tag===null\?state.use===null&&reporter.error(\"Tag could be omitted only for .use()\"):state.use===null&&(result=this._encodeComposite(tag,primitive,cls,content))}return state.explicit!==null&&(result=this._encodeComposite(state.explicit,!1,\"context\",result)),result},Node.prototype._encodeChoice=function(data,reporter){let state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+\" not found in \"+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function(tag,data){let state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if(tag===\"objid\"&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if(tag===\"objid\")return this._encodeObjid(data,null,null);if(tag===\"gentime\"||tag===\"utctime\")return this._encodeTime(data,tag);if(tag===\"null_\")return this._encodeNull();if(tag===\"int\"||tag===\"enum\")return this._encodeInt(data,state.args&&state.reverseArgs[0]);if(tag===\"bool\")return this._encodeBool(data);if(tag===\"objDesc\")return this._encodeStr(data,tag);throw new Error(\"Unsupported tag: \"+tag)},Node.prototype._isNumstr=function(str){return/^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function(str){return/^[A-Za-z0-9 '()+,-./:=\?]*$/.test(str)}}}),require_der=__commonJS({\"node_modules/asn1.js/lib/asn1/constants/der.js\"(exports){function reverse(map){let res={};return Object.keys(map).forEach(function(key){(key|0)==key&&(key=key|0);let value=map[key];res[value]=key}),res}exports.tagClass={0:\"universal\",1:\"application\",2:\"context\",3:\"private\"},exports.tagClassByName=reverse(exports.tagClass),exports.tag={0:\"end\",1:\"bool\",2:\"int\",3:\"bitstr\",4:\"octstr\",5:\"null_\",6:\"objid\",7:\"objDesc\",8:\"external\",9:\"real\",10:\"enum\",11:\"embed\",12:\"utf8str\",13:\"relativeOid\",16:\"seq\",17:\"set\",18:\"numstr\",19:\"printstr\",20:\"t61str\",21:\"videostr\",22:\"ia5str\",23:\"utctime\",24:\"gentime\",25:\"graphstr\",26:\"iso646str\",27:\"genstr\",28:\"unistr\",29:\"charstr\",30:\"bmpstr\"},exports.tagByName=reverse(exports.tag)}}),require_der2=__commonJS({\"node_modules/asn1.js/lib/asn1/encoders/der.js\"(exports,module){var inherits=require_inherits_browser(),Buffer2=require_safer().Buffer,Node=require_node(),der=require_der();function DEREncoder(entity){this.enc=\"der\",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}DEREncoder.prototype={},module.exports=DEREncoder,DEREncoder.prototype.encode=function(data,reporter){return this.tree._encode(data,reporter).join()};function DERNode(parent){Node.call(this,\"der\",parent)}inherits(DERNode,Node),DERNode.prototype._encodeComposite=function(tag,primitive,cls,content){let encodedTag=encodeTag(tag,primitive,cls,this.reporter);if(content.length<128){let header2=Buffer2.alloc(2);return header2[0]=encodedTag,header2[1]=content.length,this._createEncoderBuffer([header2,content])}let lenOctets=1;for(let i=content.length;i>=256;i>>=8)lenOctets++;let header=Buffer2.alloc(2+lenOctets);header[0]=encodedTag,header[1]=128|lenOctets;for(let i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=j&255;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function(str,tag){if(tag===\"bitstr\")return this._createEncoderBuffer([str.unused|0,str.data]);if(tag===\"bmpstr\"){let buf=Buffer2.alloc(str.length*2);for(let i=0;i=40)return this.reporter.error(\"Second objid identifier OOB\");id.splice(0,2,id[0]*40+id[1])}let size=0;for(let i=0;i=128;ident>>=7)size++}let objid=Buffer2.alloc(size),offset=objid.length-1;for(let i=id.length-1;i>=0;i--){let ident=id[i];for(objid[offset--]=ident&127;(ident>>=7)>0;)objid[offset--]=128|ident&127}return this._createEncoderBuffer(objid)};function two(num){return num<10\?\"0\"+num:num}DERNode.prototype._encodeTime=function(time,tag){let str,date=new Date(time);return tag===\"gentime\"\?str=[two(date.getUTCFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),\"Z\"].join(\"\"):tag===\"utctime\"\?str=[two(date.getUTCFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),\"Z\"].join(\"\"):this.reporter.error(\"Encoding \"+tag+\" time is not supported yet\"),this._encodeStr(str,\"octstr\")},DERNode.prototype._encodeNull=function(){return this._createEncoderBuffer(\"\")},DERNode.prototype._encodeInt=function(num,values){if(typeof num==\"string\"){if(!values)return this.reporter.error(\"String int or enum given, but no values map\");if(!values.hasOwnProperty(num))return this.reporter.error(\"Values map doesn't contain: \"+JSON.stringify(num));num=values[num]}if(typeof num!=\"number\"&&!Buffer2.isBuffer(num)){let numArray=num.toArray();!num.sign&&numArray[0]&128&&numArray.unshift(0),num=Buffer2.from(numArray)}if(Buffer2.isBuffer(num)){let size2=num.length;num.length===0&&size2++;let out2=Buffer2.alloc(size2);return num.copy(out2),num.length===0&&(out2[0]=0),this._createEncoderBuffer(out2)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);let size=1;for(let i=num;i>=256;i>>=8)size++;let out=new Array(size);for(let i=out.length-1;i>=0;i--)out[i]=num&255,num>>=8;return out[0]&128&&out.unshift(0),this._createEncoderBuffer(Buffer2.from(out))},DERNode.prototype._encodeBool=function(value){return this._createEncoderBuffer(value\?255:0)},DERNode.prototype._use=function(entity,obj){return typeof entity==\"function\"&&(entity=entity(obj)),entity._getEncoder(\"der\").tree},DERNode.prototype._skipDefault=function(dataBuffer,reporter,parent){let state=this._baseState,i;if(state.default===null)return!1;let data=dataBuffer.join();if(state.defaultBuffer===void 0&&(state.defaultBuffer=this._encodeValue(state.default,reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i=31\?reporter.error(\"Multi-octet tag encoding unsupported\"):(primitive||(res|=32),res|=der.tagClassByName[cls||\"universal\"]<<6,res)}}}),require_pem=__commonJS({\"node_modules/asn1.js/lib/asn1/encoders/pem.js\"(exports,module){var inherits=require_inherits_browser(),DEREncoder=require_der2();function PEMEncoder(entity){DEREncoder.call(this,entity),this.enc=\"pem\"}inherits(PEMEncoder,DEREncoder),module.exports=PEMEncoder,PEMEncoder.prototype.encode=function(data,options){let p=DEREncoder.prototype.encode.call(this,data).toString(\"base64\"),out=[\"-----BEGIN \"+options.label+\"-----\"];for(let i=0;i>6],primitive=(tag&32)===0;if((tag&31)===31){let oct=tag;for(tag=0;(oct&128)===128;){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=oct&127}}else tag&=31;let tagStr=der.tag[tag];return{cls,primitive,tag,tagStr}}function derDecodeLen(buf,primitive,fail){let len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&len===128)return null;if((len&128)===0)return len;let num=len&127;if(num>4)return buf.error(\"length octect is too long\");len=0;for(let i=0;i0&&bits.ishrn(shift),bits}function bits2octets(bits,q){bits=bits2int(bits,q),bits=bits.mod(q);var out=Buffer2.from(bits.toArray());if(out.length=q)throw new Error(\"invalid sig\")}module.exports=verify}}),require_browser8=__commonJS({\"node_modules/browserify-sign/browser/index.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,createHash=require_browser2(),inherits=require_inherits_browser(),sign=require_sign(),verify=require_verify(),algorithms=require_algorithms();Object.keys(algorithms).forEach(function(key){algorithms[key].id=Buffer2.from(algorithms[key].id,\"hex\"),algorithms[key.toLowerCase()]=algorithms[key]});function Sign(algorithm){StreamModule.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error(\"Unknown message digest\");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}inherits(Sign,StreamModule.Writable),Sign.prototype._write=function(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function(data,enc){return typeof data==\"string\"&&(data=Buffer2.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc\?sig.toString(enc):sig};function Verify(algorithm){StreamModule.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error(\"Unknown message digest\");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}inherits(Verify,StreamModule.Writable),Verify.prototype._write=function(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function(data,enc){return typeof data==\"string\"&&(data=Buffer2.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function(key,sig,enc){typeof sig==\"string\"&&(sig=Buffer2.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)};function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}module.exports={Sign:createSign,Verify:createVerify,createSign,createVerify}}}),require_bn6=require_bn,require_browser9=__commonJS({\"node_modules/create-ecdh/browser.js\"(exports,module){var elliptic=require_elliptic(),BN=require_bn6();module.exports=function(curve){return new ECDH(curve)};var aliases={secp256k1:{name:\"secp256k1\",byteLength:32},secp224r1:{name:\"p224\",byteLength:28},prime256v1:{name:\"p256\",byteLength:32},prime192v1:{name:\"p192\",byteLength:24},ed25519:{name:\"ed25519\",byteLength:32},secp384r1:{name:\"p384\",byteLength:48},secp521r1:{name:\"p521\",byteLength:66}};aliases.p224=aliases.secp224r1,aliases.p256=aliases.secp256r1=aliases.prime256v1,aliases.p192=aliases.secp192r1=aliases.prime192v1,aliases.p384=aliases.secp384r1,aliases.p521=aliases.secp521r1;function ECDH(curve){this.curveType=aliases[curve],this.curveType||(this.curveType={name:curve}),this.curve=new elliptic.ec(this.curveType.name),this.keys=void 0}ECDH.prototype={},ECDH.prototype.generateKeys=function(enc,format){return this.keys=this.curve.genKeyPair(),this.getPublicKey(enc,format)},ECDH.prototype.computeSecret=function(other,inenc,enc){inenc=inenc||\"utf8\",Buffer.isBuffer(other)||(other=new Buffer(other,inenc));var otherPub=this.curve.keyFromPublic(other).getPublic(),out=otherPub.mul(this.keys.getPrivate()).getX();return formatReturnValue(out,enc,this.curveType.byteLength)},ECDH.prototype.getPublicKey=function(enc,format){var key=this.keys.getPublic(format===\"compressed\",!0);return format===\"hybrid\"&&(key[key.length-1]%2\?key[0]=7:key[0]=6),formatReturnValue(key,enc)},ECDH.prototype.getPrivateKey=function(enc){return formatReturnValue(this.keys.getPrivate(),enc)},ECDH.prototype.setPublicKey=function(pub,enc){return enc=enc||\"utf8\",Buffer.isBuffer(pub)||(pub=new Buffer(pub,enc)),this.keys._importPublic(pub),this},ECDH.prototype.setPrivateKey=function(priv,enc){enc=enc||\"utf8\",Buffer.isBuffer(priv)||(priv=new Buffer(priv,enc));var _priv=new BN(priv);return _priv=_priv.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(_priv),this};function formatReturnValue(bn,enc,len){Array.isArray(bn)||(bn=bn.toArray());var buf=new Buffer(bn);if(len&&buf.length=0)throw new Error(\"data too long for modulus\")}else throw new Error(\"unknown padding\");return reverse\?crt(paddedMsg,key):withPublic(paddedMsg,key)};function oaep(key,msg){var k=key.modulus.byteLength(),mLen=msg.length,iHash=createHash(\"sha1\").update(Buffer2.alloc(0)).digest(),hLen=iHash.length,hLen2=2*hLen;if(mLen>k-hLen2-2)throw new Error(\"message too long\");var ps=Buffer2.alloc(k-mLen-hLen2-2),dblen=k-hLen-1,seed=randomBytes(hLen),maskedDb=xor(Buffer2.concat([iHash,ps,Buffer2.alloc(1,1),msg],dblen),mgf(seed,dblen)),maskedSeed=xor(seed,mgf(maskedDb,hLen));return new BN(Buffer2.concat([Buffer2.alloc(1),maskedSeed,maskedDb],k))}function pkcs1(key,msg,reverse){var mLen=msg.length,k=key.modulus.byteLength();if(mLen>k-11)throw new Error(\"message too long\");var ps;return reverse\?ps=Buffer2.alloc(k-mLen-3,255):ps=nonZero(k-mLen-3),new BN(Buffer2.concat([Buffer2.from([0,reverse\?1:2]),ps,Buffer2.alloc(1),msg],k))}function nonZero(len){for(var out=Buffer2.allocUnsafe(len),i=0,cache=randomBytes(len*2),cur=0,num;ik||new BN(enc).cmp(key.modulus)>=0)throw new Error(\"decryption error\");var msg;reverse\?msg=withPublic(new BN(enc),key):msg=crt(enc,key);var zBuffer=Buffer2.alloc(k-msg.length);if(msg=Buffer2.concat([zBuffer,msg],k),padding===4)return oaep(key,msg);if(padding===1)return pkcs1(key,msg,reverse);if(padding===3)return msg;throw new Error(\"unknown padding\")};function oaep(key,msg){var k=key.modulus.byteLength(),iHash=createHash(\"sha1\").update(Buffer2.alloc(0)).digest(),hLen=iHash.length;if(msg[0]!==0)throw new Error(\"decryption error\");var maskedSeed=msg.slice(1,hLen+1),maskedDb=msg.slice(hLen+1),seed=xor(maskedSeed,mgf(maskedDb,hLen)),db=xor(maskedDb,mgf(seed,k-hLen-1));if(compare(iHash,db.slice(0,hLen)))throw new Error(\"decryption error\");for(var i=hLen;db[i]===0;)i++;if(db[i++]!==1)throw new Error(\"decryption error\");return db.slice(i)}function pkcs1(key,msg,reverse){for(var p1=msg.slice(0,2),i=2,status=0;msg[i++]!==0;)if(i>=msg.length){status++;break}var ps=msg.slice(2,i-1);if((p1.toString(\"hex\")!==\"0002\"&&!reverse||p1.toString(\"hex\")!==\"0001\"&&reverse)&&status++,ps.length<8&&status++,status)throw new Error(\"decryption error\");return msg.slice(i)}function compare(a,b){a=Buffer2.from(a),b=Buffer2.from(b);var dif=0,len=a.length;a.length!==b.length&&(dif++,len=Math.min(a.length,b.length));for(var i=-1;++ikMaxUint32||offset<0)@throwTypeError(\"offset must be a uint32\");if(offset>kBufferMaxLength||offset>length)@throwRangeError(\"offset out of range\")}function assertSize(size,offset,length){if(typeof size!=\"number\"||size!==size)@throwTypeError(\"size must be a number\");if(size>kMaxUint32||size<0)@throwTypeError(\"size must be a uint32\");if(size+offset>length||size>kBufferMaxLength)@throwRangeError(\"buffer too small\")}exports.randomFill=randomFill,exports.randomFillSync=randomFillSync;function randomFill(buf,offset,size,cb){if(!Buffer2.isBuffer(buf)&&!(buf instanceof global.Uint8Array))@throwTypeError('\"buf\" argument must be a Buffer or Uint8Array');if(typeof offset==\"function\")cb=offset,offset=0,size=buf.length;else if(typeof size==\"function\")cb=size,size=buf.length-offset;else if(typeof cb!=\"function\")@throwTypeError('\"cb\" argument must be a function');return assertOffset(offset,buf.length),assertSize(size,offset,buf.length),actualFill(buf,offset,size,cb)}function actualFill(buf,offset,size,cb){if(cb){randombytes(size,function(err,bytes2){if(err)return cb(err);bytes2.copy(buf,offset),cb(null,buf)});return}var bytes=randombytes(size);return bytes.copy(buf,offset),buf}function randomFillSync(buf,offset,size){if(typeof offset>\"u\"&&(offset=0),!Buffer2.isBuffer(buf)&&!(buf instanceof global.Uint8Array))@throwTypeError('\"buf\" argument must be a Buffer or Uint8Array');return assertOffset(offset,buf.length),size===void 0&&(size=buf.length-offset),assertSize(size,offset,buf.length),actualFill(buf,offset,size)}}}),require_crypto_browserify2=__commonJS({\"node_modules/crypto-browserify/index.js\"(exports){exports.randomBytes=exports.rng=exports.pseudoRandomBytes=exports.prng=require_browser(),exports.createHash=require_browser2(),exports.Hash=exports.createHash.Hash,exports.createHmac=exports.Hmac=require_browser3();var algos=require_algos(),algoKeys=Object.keys(algos),hashes=[\"sha1\",\"sha224\",\"sha256\",\"sha384\",\"sha512\",\"md5\",\"rmd160\"].concat(algoKeys);exports.getHashes=function(){return hashes};var p=require_browser4();exports.pbkdf2=p.pbkdf2,exports.pbkdf2Sync=p.pbkdf2Sync;var aes=require_browser6();exports.Cipher=aes.Cipher,exports.createCipher=aes.createCipher,exports.Cipheriv=aes.Cipheriv,exports.createCipheriv=aes.createCipheriv,exports.Decipher=aes.Decipher,exports.createDecipher=aes.createDecipher,exports.Decipheriv=aes.Decipheriv,exports.createDecipheriv=aes.createDecipheriv,exports.getCiphers=aes.getCiphers,exports.listCiphers=aes.listCiphers;var dh=require_browser7();exports.DiffieHellmanGroup=dh.DiffieHellmanGroup,exports.createDiffieHellmanGroup=dh.createDiffieHellmanGroup,exports.getDiffieHellman=dh.getDiffieHellman,exports.createDiffieHellman=dh.createDiffieHellman,exports.DiffieHellman=dh.DiffieHellman;var sign=require_browser8();exports.createSign=sign.createSign,exports.Sign=sign.Sign,exports.createVerify=sign.createVerify,exports.Verify=sign.Verify,exports.createECDH=require_browser9();var publicEncrypt=require_browser10();exports.publicEncrypt=publicEncrypt.publicEncrypt,exports.privateEncrypt=publicEncrypt.privateEncrypt,exports.publicDecrypt=publicEncrypt.publicDecrypt,exports.privateDecrypt=publicEncrypt.privateDecrypt,exports.getRandomValues=(values)=>crypto.getRandomValues(values);var rf=require_browser11();exports.randomFill=rf.randomFill,exports.randomFillSync=rf.randomFillSync,exports.createCredentials=function(){throw new Error([\"sorry, createCredentials is not implemented yet\",\"we accept pull requests\",\"https://github.com/crypto-browserify/crypto-browserify\"].join(`\n`))},exports.constants=@processBindingConstants.crypto}}),crypto_exports=require_crypto_browserify2(),DEFAULT_ENCODING=\"buffer\",getRandomValues=(array)=>crypto.getRandomValues(array),randomUUID=()=>crypto.randomUUID(),randomInt=(...args)=>crypto.randomInt(...args),timingSafeEqual=\"timingSafeEqual\"in crypto\?(a,b)=>{let{byteLength:byteLengthA}=a,{byteLength:byteLengthB}=b;if(typeof byteLengthA!=\"number\"||typeof byteLengthB!=\"number\")@throwTypeError(\"Input must be an array buffer view\");if(byteLengthA!==byteLengthB)@throwRangeError(\"Input buffers must have the same length\");return crypto.timingSafeEqual(a,b)}:void 0,scryptSync=\"scryptSync\"in crypto\?(password,salt,keylen,options)=>{let res=crypto.scryptSync(password,salt,keylen,options);return DEFAULT_ENCODING!==\"buffer\"\?new Buffer(res).toString(DEFAULT_ENCODING):new Buffer(res)}:void 0,scrypt=\"scryptSync\"in crypto\?function(password,salt,keylen,options,callback){if(typeof options==\"function\"&&(callback=options,options=void 0),typeof callback!=\"function\"){var err=@makeTypeError(\"callback must be a function\");throw err.code=\"ERR_INVALID_CALLBACK\",err}try{let result=crypto.scryptSync(password,salt,keylen,options);process.nextTick(callback,null,DEFAULT_ENCODING!==\"buffer\"\?new Buffer(result).toString(DEFAULT_ENCODING):new Buffer(result))}catch(err2){throw err2}}:void 0;timingSafeEqual&&(Object.defineProperty(timingSafeEqual,\"name\",{value:\"::bunternal::\"}),Object.defineProperty(scrypt,\"name\",{value:\"::bunternal::\"}),Object.defineProperty(scryptSync,\"name\",{value:\"::bunternal::\"}));const harcoded_curves=[\"p192\",\"p224\",\"p256\",\"p384\",\"p521\",\"curve25519\",\"ed25519\",\"secp256k1\",\"secp224r1\",\"prime256v1\",\"prime192v1\",\"ed25519\",\"secp384r1\",\"secp521r1\"];function getCurves(){return harcoded_curves}var webcrypto=crypto;__export(crypto_exports,{DEFAULT_ENCODING:()=>DEFAULT_ENCODING,getRandomValues:()=>getRandomValues,randomUUID:()=>randomUUID,randomInt:()=>randomInt,getCurves:()=>getCurves,scrypt:()=>scrypt,scryptSync:()=>scryptSync,timingSafeEqual:()=>timingSafeEqual,webcrypto:()=>webcrypto,subtle:()=>webcrypto.subtle}),$=crypto_exports;/*! safe-buffer. MIT License. Feross Aboukhadijeh */return $})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDgramCode = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function createSocket(){throwNotImplemented(\"node:dgram createSocket\",1630)}function Socket(){throwNotImplemented(\"node:dgram Socket\",1630)}function _createSocketHandle(){throwNotImplemented(\"node:dgram _createSocketHandle\",1630)}return $={createSocket,Socket,_createSocketHandle},hideFromStack(createSocket,Socket,_createSocketHandle),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDiagnosticsChannelCode = "(function (){\"use strict\";const SafeMap=Map,SafeFinalizationRegistry=FinalizationRegistry,ArrayPrototypeAt=(array,index)=>array[index],ArrayPrototypeIndexOf=(array,value)=>array.indexOf(value),ArrayPrototypePush=(array,value)=>array.push(value),ArrayPrototypeSplice=(array,start,deleteCount)=>array.splice(start,deleteCount),ObjectGetPrototypeOf=Object.getPrototypeOf,ObjectSetPrototypeOf=Object.setPrototypeOf,SymbolHasInstance=Symbol.hasInstance,ReflectApply=Reflect.apply,PromiseResolve=Promise.resolve,PromiseReject=Promise.reject,PromisePrototypeThen=(promise,onFulfilled,onRejected)=>promise.then(onFulfilled,onRejected);class WeakReference extends WeakRef{constructor(){super(...arguments)}#refs=0;get(){return this.deref()}incRef(){return++this.#refs}decRef(){return--this.#refs}}class WeakRefMap extends SafeMap{constructor(){super(...arguments)}#finalizers=new SafeFinalizationRegistry((key)=>{this.delete(key)});set(key,value){return this.#finalizers.register(value,key),super.set(key,new WeakReference(value))}get(key){return super.get(key)\?.get()}incRef(key){return super.get(key)\?.incRef()}decRef(key){return super.get(key)\?.decRef()}}function markActive(channel2){ObjectSetPrototypeOf(channel2,ActiveChannel.prototype),channel2._subscribers=[],channel2._stores=new SafeMap}function maybeMarkInactive(channel2){if(!channel2._subscribers.length&&!channel2._stores.size)ObjectSetPrototypeOf(channel2,Channel.prototype),channel2._subscribers=void 0,channel2._stores=void 0}function defaultTransform(data){return data}function wrapStoreRun(store,data,next,transform=defaultTransform){return()=>{let context;try{context=transform(data)}catch(err){return process.nextTick(()=>reportError(err)),next()}return store.run(context,next)}}class ActiveChannel{subscribe(subscription){validateFunction(subscription,\"subscription\"),ArrayPrototypePush(this._subscribers,subscription),channels.incRef(this.name)}unsubscribe(subscription){const index=ArrayPrototypeIndexOf(this._subscribers,subscription);if(index===-1)return!1;return ArrayPrototypeSplice(this._subscribers,index,1),channels.decRef(this.name),maybeMarkInactive(this),!0}bindStore(store,transform){if(!this._stores.has(store))channels.incRef(this.name);this._stores.set(store,transform)}unbindStore(store){if(!this._stores.has(store))return!1;return this._stores.delete(store),channels.decRef(this.name),maybeMarkInactive(this),!0}get hasSubscribers(){return!0}publish(data){for(let i=0;i<(this._subscribers\?.length||0);i++)try{const onMessage=this._subscribers[i];onMessage(data,this.name)}catch(err){process.nextTick(()=>reportError(err))}}runStores(data,fn,thisArg,...args){let run=()=>{return this.publish(data),ReflectApply(fn,thisArg,args)};for(let entry of this._stores.entries()){const store=entry[0],transform=entry[1];run=wrapStoreRun(store,data,run,transform)}return run()}}class Channel{constructor(name){this._subscribers=void 0,this._stores=void 0,this.name=name,channels.set(name,this)}static[SymbolHasInstance](instance){const prototype=ObjectGetPrototypeOf(instance);return prototype===Channel.prototype||prototype===ActiveChannel.prototype}subscribe(subscription){markActive(this),this.subscribe(subscription)}unsubscribe(){return!1}bindStore(store,transform){markActive(this),this.bindStore(store,transform)}unbindStore(){return!1}get hasSubscribers(){return!1}publish(){}runStores(data,fn,thisArg,...args){return ReflectApply(fn,thisArg,args)}}const channels=new WeakRefMap;function channel(name){const channel2=channels.get(name);if(channel2)return channel2;if(typeof name!==\"string\"&&typeof name!==\"symbol\")throw new ERR_INVALID_ARG_TYPE(\"channel\",[\"string\",\"symbol\"],name);return new Channel(name)}function subscribe(name,subscription){return channel(name).subscribe(subscription)}function unsubscribe(name,subscription){return channel(name).unsubscribe(subscription)}function hasSubscribers(name){const channel2=channels.get(name);if(!channel2)return!1;return channel2.hasSubscribers}const traceEvents=[\"start\",\"end\",\"asyncStart\",\"asyncEnd\",\"error\"];function assertChannel(value,name){if(!(value instanceof Channel))throw new ERR_INVALID_ARG_TYPE(name,[\"Channel\"],value)}class TracingChannel{constructor(nameOrChannels){if(typeof nameOrChannels===\"string\")this.start=channel(`tracing:${nameOrChannels}:start`),this.end=channel(`tracing:${nameOrChannels}:end`),this.asyncStart=channel(`tracing:${nameOrChannels}:asyncStart`),this.asyncEnd=channel(`tracing:${nameOrChannels}:asyncEnd`),this.error=channel(`tracing:${nameOrChannels}:error`);else if(typeof nameOrChannels===\"object\"){const{start,end,asyncStart,asyncEnd,error}=nameOrChannels;assertChannel(start,\"nameOrChannels.start\"),assertChannel(end,\"nameOrChannels.end\"),assertChannel(asyncStart,\"nameOrChannels.asyncStart\"),assertChannel(asyncEnd,\"nameOrChannels.asyncEnd\"),assertChannel(error,\"nameOrChannels.error\"),this.start=start,this.end=end,this.asyncStart=asyncStart,this.asyncEnd=asyncEnd,this.error=error}else throw new ERR_INVALID_ARG_TYPE(\"nameOrChannels\",[\"string\",\"object\",\"Channel\"],nameOrChannels)}subscribe(handlers){for(let name of traceEvents){if(!handlers[name])continue;this[name]\?.subscribe(handlers[name])}}unsubscribe(handlers){let done=!0;for(let name of traceEvents){if(!handlers[name])continue;if(!this[name]\?.unsubscribe(handlers[name]))done=!1}return done}traceSync(fn,context={},thisArg,...args){const{start,end,error}=this;return start.runStores(context,()=>{try{const result=ReflectApply(fn,thisArg,args);return context.result=result,result}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}tracePromise(fn,context={},thisArg,...args){const{start,end,asyncStart,asyncEnd,error}=this;function reject(err){return context.error=err,error.publish(context),asyncStart.publish(context),asyncEnd.publish(context),PromiseReject(err)}function resolve(result){return context.result=result,asyncStart.publish(context),asyncEnd.publish(context),result}return start.runStores(context,()=>{try{let promise=ReflectApply(fn,thisArg,args);if(!(promise instanceof Promise))promise=PromiseResolve(promise);return PromisePrototypeThen(promise,resolve,reject)}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}traceCallback(fn,position=-1,context={},thisArg,...args){const{start,end,asyncStart,asyncEnd,error}=this;function wrappedCallback(err,res){if(err)context.error=err,error.publish(context);else context.result=res;asyncStart.runStores(context,()=>{try{if(callback)return ReflectApply(callback,this,arguments)}finally{asyncEnd.publish(context)}})}const callback=ArrayPrototypeAt(args,position);if(typeof callback!==\"function\")throw new ERR_INVALID_ARG_TYPE(\"callback\",[\"function\"],callback);return ArrayPrototypeSplice(args,position,1,wrappedCallback),start.runStores(context,()=>{try{return ReflectApply(fn,thisArg,args)}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}}function tracingChannel(nameOrChannels){return new TracingChannel(nameOrChannels)}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 validateFunction(callable,field){if(typeof callable!==\"function\")throw new ERR_INVALID_ARG_TYPE(field,\"Function\",callable);return callable}return{channel,hasSubscribers,subscribe,tracingChannel,unsubscribe,Channel}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDNSCode = "(function (){\"use strict\";const dns=Bun.dns;function getServers(){return dns.getServers()}function lookup(domain,options,callback){if(typeof options==\"function\")callback=options;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");if(typeof options==\"number\")options={family:options};dns.lookup(domain,options).then((res)=>{if(res.sort((a,b)=>a.family-b.family),options\?.all)callback(null,res.map(mapLookupAll));else{const[{address,family}]=res;callback(null,address,family)}},(error)=>{callback(error)})}function resolveSrv(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSrv(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveTxt(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveTxt(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveSoa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSoa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveNaptr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNaptr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveMx(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveMx(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveCaa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCaa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveNs(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNs(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolvePtr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolvePtr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveCname(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCname(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function lookupService(address,port,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");callback(null,address,port)}var InternalResolver=class Resolver2{constructor(options){}cancel(){}getServers(){return[]}resolve(hostname,rrtype,callback){if(typeof rrtype==\"function\")callback=rrtype,rrtype=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolve(hostname).then((results)=>{switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":callback(null,hostname,results.map(mapResolveX));break;default:callback(null,results);break}},(error)=>{callback(error)})}resolve4(hostname,options,callback){if(typeof options==\"function\")callback=options,options=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.lookup(hostname,{family:4}).then((addresses)=>{callback(null,options\?.ttl\?addresses:addresses.map(mapResolveX))},(error)=>{callback(error)})}resolve6(hostname,options,callback){if(typeof options==\"function\")callback=options,options=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.lookup(hostname,{family:6}).then((addresses)=>{callback(null,options\?.ttl\?addresses:addresses.map(({address})=>address))},(error)=>{callback(error)})}resolveAny(hostname,callback){callback(null,[])}resolveCname(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCname(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveMx(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveMx(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveNaptr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNaptr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveNs(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNs(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolvePtr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolvePtr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveSrv(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSrv(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveCaa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCaa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveTxt(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveTxt(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveSoa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSoa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}reverse(ip,callback){callback(null,[])}setServers(servers){}};function resolve(hostname,rrtype,callback){if(typeof rrtype==\"function\")callback=rrtype;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolve(hostname).then((results)=>{switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":callback(null,hostname,results.map(({address})=>address));break;default:callback(null,results);break}},(error)=>{callback(error)})}function Resolver(options){return new InternalResolver(options)}Resolver.prototype={},Object.setPrototypeOf(Resolver.prototype,InternalResolver.prototype),Object.setPrototypeOf(Resolver,InternalResolver);var{resolve,resolve4,resolve6,resolveAny,resolveCname,resolveCaa,resolveMx,resolveNaptr,resolveNs,resolvePtr,resolveSoa,resolveSrv,reverse,resolveTxt}=InternalResolver.prototype;function setDefaultResultOrder(){}function setServers(){}const promisifyLookup=(res)=>{res.sort((a,b)=>a.family-b.family);const[{address,family}]=res;return{address,family}},mapLookupAll=(res)=>{const{address,family}=res;return{address,family}},promisifyLookupAll=(res)=>{return res.sort((a,b)=>a.family-b.family),res.map(mapLookupAll)},mapResolveX=(a)=>a.address,promisifyResolveX=(res)=>{return res\?.map(mapResolveX)},promises={lookup(domain,options){if(options\?.all)return dns.lookup(domain,options).then(promisifyLookupAll);return dns.lookup(domain,options).then(promisifyLookup)},lookupService(address,port){return Promise.resolve([])},resolve(hostname,rrtype){if(typeof rrtype!==\"string\")rrtype=null;switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":return dns.resolve(hostname,rrtype).then(promisifyLookup);default:return dns.resolve(hostname,rrtype)}},resolve4(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:4});return dns.lookup(hostname,{family:4}).then(promisifyResolveX)},resolve6(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:6});return dns.lookup(hostname,{family:6}).then(promisifyResolveX)},resolveSrv(hostname){return dns.resolveSrv(hostname)},resolveTxt(hostname){return dns.resolveTxt(hostname)},resolveSoa(hostname){return dns.resolveSoa(hostname)},resolveNaptr(hostname){return dns.resolveNaptr(hostname)},resolveMx(hostname){return dns.resolveMx(hostname)},resolveCaa(hostname){return dns.resolveCaa(hostname)},resolveNs(hostname){return dns.resolveNs(hostname)},resolvePtr(hostname){return dns.resolvePtr(hostname)},resolveCname(hostname){return dns.resolveCname(hostname)},Resolver:class Resolver2{constructor(options){}cancel(){}getServers(){return[]}resolve(hostname,rrtype){if(typeof rrtype!==\"string\")rrtype=null;switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":return dns.resolve(hostname,rrtype).then(promisifyLookup);default:return dns.resolve(hostname,rrtype)}}resolve4(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:4});return dns.lookup(hostname,{family:4}).then(promisifyResolveX)}resolve6(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:6});return dns.lookup(hostname,{family:6}).then(promisifyResolveX)}resolveAny(hostname){return Promise.resolve([])}resolveCname(hostname){return dns.resolveCname(hostname)}resolveMx(hostname){return dns.resolveMx(hostname)}resolveNaptr(hostname){return dns.resolveNaptr(hostname)}resolveNs(hostname){return dns.resolveNs(hostname)}resolvePtr(hostname){return dns.resolvePtr(hostname)}resolveSoa(hostname){return dns.resolveSoa(hostname)}resolveSrv(hostname){return dns.resolveSrv(hostname)}resolveCaa(hostname){return dns.resolveCaa(hostname)}resolveTxt(hostname){return dns.resolveTxt(hostname)}reverse(ip){return Promise.resolve([])}setServers(servers){}}};for(let key of[\"resolveAny\",\"reverse\"])promises[key]=()=>Promise.resolve(void 0);return{ADDRCONFIG:0,ALL:1,V4MAPPED:2,NODATA:\"DNS_ENODATA\",FORMERR:\"DNS_EFORMERR\",SERVFAIL:\"DNS_ESERVFAIL\",NOTFOUND:\"DNS_ENOTFOUND\",NOTIMP:\"DNS_ENOTIMP\",REFUSED:\"DNS_EREFUSED\",BADQUERY:\"DNS_EBADQUERY\",BADNAME:\"DNS_EBADNAME\",BADFAMILY:\"DNS_EBADFAMILY\",BADRESP:\"DNS_EBADRESP\",CONNREFUSED:\"DNS_ECONNREFUSED\",TIMEOUT:\"DNS_ETIMEOUT\",EOF:\"DNS_EEOF\",FILE:\"DNS_EFILE\",NOMEM:\"DNS_ENOMEM\",DESTRUCTION:\"DNS_EDESTRUCTION\",BADSTR:\"DNS_EBADSTR\",BADFLAGS:\"DNS_EBADFLAGS\",NONAME:\"DNS_ENONAME\",BADHINTS:\"DNS_EBADHINTS\",NOTINITIALIZED:\"DNS_ENOTINITIALIZED\",LOADIPHLPAPI:\"DNS_ELOADIPHLPAPI\",ADDRGETNETWORKPARAMS:\"DNS_EADDRGETNETWORKPARAMS\",CANCELLED:\"DNS_ECANCELLED\",lookup,lookupService,Resolver,setServers,setDefaultResultOrder,resolve,reverse,resolve4,resolve6,resolveAny,resolveCname,resolveCaa,resolveMx,resolveNs,resolvePtr,resolveSoa,resolveSrv,resolveTxt,resolveNaptr,promises,getServers}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDNSPromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,12)||@createInternalModuleById(12)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDomainCode = "(function (){\"use strict\";var EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),domain={};return domain.createDomain=domain.create=function(){var d=new EventEmitter;function emitError(e){d.emit(\"error\",e)}return d.add=function(emitter){emitter.on(\"error\",emitError)},d.remove=function(emitter){emitter.removeListener(\"error\",emitError)},d.bind=function(fn){return function(){var args=Array.prototype.slice.call(arguments);try{fn.apply(null,args)}catch(err){emitError(err)}}},d.intercept=function(fn){return function(err){if(err)emitError(err);else{var args=Array.prototype.slice.call(arguments,1);try{fn.apply(null,args)}catch(err2){emitError(err2)}}}},d.run=function(fn){try{fn()}catch(err){emitError(err)}return this},d.dispose=function(){return this.removeAllListeners(),this},d.enter=d.exit=function(){return this},d},domain})\n"_s; +// + +// +static constexpr ASCIILiteral NodeEventsCode = "(function (){\"use strict\";const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),SymbolFor=Symbol.for,kCapture=Symbol(\"kCapture\"),kErrorMonitor=SymbolFor(\"events.errorMonitor\"),kMaxEventTargetListeners=Symbol(\"events.maxEventTargetListeners\"),kMaxEventTargetListenersWarned=Symbol(\"events.maxEventTargetListenersWarned\"),kWatermarkData=SymbolFor(\"nodejs.watermarkData\"),kRejection=SymbolFor(\"nodejs.rejection\"),captureRejectionSymbol=SymbolFor(\"nodejs.rejection\"),ArrayPrototypeSlice=Array.prototype.slice;var defaultMaxListeners=10;const EventEmitter=function EventEmitter(opts){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners\?\?=void 0,this[kCapture]=opts\?.captureRejections\?Boolean(opts\?.captureRejections):EventEmitterPrototype[kCapture])this.emit=emitWithRejectionCapture},EventEmitterPrototype=EventEmitter.prototype={};EventEmitterPrototype._events=void 0,EventEmitterPrototype._eventsCount=0,EventEmitterPrototype._maxListeners=void 0,EventEmitterPrototype.setMaxListeners=function setMaxListeners(n){return validateNumber(n,\"setMaxListeners\",0),this._maxListeners=n,this},EventEmitterPrototype.getMaxListeners=function getMaxListeners(){return this._maxListeners\?\?defaultMaxListeners};function emitError(emitter,args){var{_events:events}=emitter;if(args[0]\?\?=new Error(\"Unhandled error.\"),!events)throw args[0];var errorMonitor=events[kErrorMonitor];if(errorMonitor)for(var handler of ArrayPrototypeSlice.call(errorMonitor))handler.apply(emitter,args);var handlers=events.error;if(!handlers)throw args[0];for(var handler of ArrayPrototypeSlice.call(handlers))handler.apply(emitter,args);return!0}function addCatch(emitter,promise,type,args){promise.then(void 0,function(err){process.nextTick(emitUnhandledRejectionOrErr,emitter,err,type,args)})}function emitUnhandledRejectionOrErr(emitter,err,type,args){if(typeof emitter[kRejection]===\"function\")emitter[kRejection](err,type,...args);else try{emitter[kCapture]=!1,emitter.emit(\"error\",err)}finally{emitter[kCapture]=!0}}const emitWithoutRejectionCapture=function emit(type,...args){if(type===\"error\")return emitError(this,args);var{_events:events}=this;if(events===void 0)return!1;var handlers=events[type];if(handlers===void 0)return!1;for(var handler of[...handlers])handler.apply(this,args);return!0},emitWithRejectionCapture=function emit(type,...args){if(type===\"error\")return emitError(this,args);var{_events:events}=this;if(events===void 0)return!1;var handlers=events[type];if(handlers===void 0)return!1;for(var handler of[...handlers]){var result=handler.apply(this,args);if(result!==void 0&&@isPromise(result))addCatch(this,result,type,args)}return!0};EventEmitterPrototype.emit=emitWithoutRejectionCapture,EventEmitterPrototype.addListener=function addListener(type,fn){checkListener(fn);var events=this._events;if(!events)events=this._events={__proto__:null},this._eventsCount=0;else if(events.newListener)this.emit(\"newListener\",type,fn.listener\?\?fn);var handlers=events[type];if(!handlers)events[type]=[fn],this._eventsCount++;else{handlers.push(fn);var m=this._maxListeners\?\?defaultMaxListeners;if(m>0&&handlers.length>m&&!handlers.warned)overflowWarning(this,type,handlers)}return this},EventEmitterPrototype.on=EventEmitterPrototype.addListener,EventEmitterPrototype.prependListener=function prependListener(type,fn){checkListener(fn);var events=this._events;if(!events)events=this._events={__proto__:null},this._eventsCount=0;else if(events.newListener)this.emit(\"newListener\",type,fn.listener\?\?fn);var handlers=events[type];if(!handlers)events[type]=[fn],this._eventsCount++;else{handlers.unshift(fn);var m=this._maxListeners\?\?defaultMaxListeners;if(m>0&&handlers.length>m&&!handlers.warned)overflowWarning(this,type,handlers)}return this};function overflowWarning(emitter,type,handlers){handlers.warned=!0;const warn=new Error(`Possible EventEmitter memory leak detected. ${handlers.length} ${String(type)} listeners `+`added to [${emitter.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);warn.name=\"MaxListenersExceededWarning\",warn.emitter=emitter,warn.type=type,warn.count=handlers.length,process.emitWarning(warn)}function onceWrapper(type,listener,...args){this.removeListener(type,listener),listener.apply(this,args)}EventEmitterPrototype.once=function once(type,fn){checkListener(fn);const bound=onceWrapper.bind(this,type,fn);return bound.listener=fn,this.addListener(type,bound),this},EventEmitterPrototype.prependOnceListener=function prependOnceListener(type,fn){checkListener(fn);const bound=onceWrapper.bind(this,type,fn);return bound.listener=fn,this.prependListener(type,bound),this},EventEmitterPrototype.removeListener=function removeListener(type,fn){checkListener(fn);var{_events:events}=this;if(!events)return this;var handlers=events[type];if(!handlers)return this;var length=handlers.length;let position=-1;for(let i=length-1;i>=0;i--)if(handlers[i]===fn||handlers[i].listener===fn){position=i;break}if(position<0)return this;if(position===0)handlers.shift();else handlers.splice(position,1);if(handlers.length===0)delete events[type],this._eventsCount--;return this},EventEmitterPrototype.off=EventEmitterPrototype.removeListener,EventEmitterPrototype.removeAllListeners=function removeAllListeners(type){var{_events:events}=this;if(type&&events){if(events[type])delete events[type],this._eventsCount--}else this._events={__proto__:null};return this},EventEmitterPrototype.listeners=function listeners(type){var{_events:events}=this;if(!events)return[];var handlers=events[type];if(!handlers)return[];return handlers.map((x)=>x.listener\?\?x)},EventEmitterPrototype.rawListeners=function rawListeners(type){var{_events}=this;if(!_events)return[];var handlers=_events[type];if(!handlers)return[];return handlers.slice()},EventEmitterPrototype.listenerCount=function listenerCount(type){var{_events:events}=this;if(!events)return 0;return events[type]\?.length\?\?0},EventEmitterPrototype.eventNames=function eventNames(){return this._eventsCount>0\?Reflect.ownKeys(this._events):[]},EventEmitterPrototype[kCapture]=!1;function once(emitter,type,options){var signal=options\?.signal;if(validateAbortSignal(signal,\"options.signal\"),signal\?.aborted)throw new AbortError(void 0,{cause:signal\?.reason});return new Promise((resolve,reject)=>{const errorListener=(err)=>{if(emitter.removeListener(type,resolver),signal!=null)eventTargetAgnosticRemoveListener(signal,\"abort\",abortListener);reject(err)},resolver=(...args)=>{if(typeof emitter.removeListener===\"function\")emitter.removeListener(\"error\",errorListener);if(signal!=null)eventTargetAgnosticRemoveListener(signal,\"abort\",abortListener);resolve(args)};if(eventTargetAgnosticAddListener(emitter,type,resolver,{once:!0}),type!==\"error\"&&typeof emitter.once===\"function\")emitter.once(\"error\",errorListener);function abortListener(){eventTargetAgnosticRemoveListener(emitter,type,resolver),eventTargetAgnosticRemoveListener(emitter,\"error\",errorListener),reject(new AbortError(void 0,{cause:signal\?.reason}))}if(signal!=null)eventTargetAgnosticAddListener(signal,\"abort\",abortListener,{once:!0})})}function on(emitter,type,options){var{signal,close,highWatermark=Number.MAX_SAFE_INTEGER,lowWatermark=1}=options||{};throwNotImplemented(\"events.on\",2679)}function getEventListeners(emitter,type){if(emitter instanceof EventTarget)throwNotImplemented(\"getEventListeners with an EventTarget\",2678);return emitter.listeners(type)}function setMaxListeners(n,...eventTargets){validateNumber(n,\"setMaxListeners\",0);var length;if(eventTargets&&(length=eventTargets.length))for(let i=0;imax||(min!=null||max!=null)&&Number.isNaN(value))throw new ERR_OUT_OF_RANGE(name,`${min!=null\?`>= ${min}`:\"\"}${min!=null&&max!=null\?\" && \":\"\"}${max!=null\?`<= ${max}`:\"\"}`,value)}function checkListener(listener){if(typeof listener!==\"function\")@throwTypeError(\"The listener must be a function\")}let AsyncResource=null;class EventEmitterAsyncResource extends EventEmitter{triggerAsyncId;asyncResource;constructor(options){if(!AsyncResource)AsyncResource=(@getInternalField(@internalModuleRegistry,5)||@createInternalModuleById(5)).AsyncResource;var{captureRejections=!1,triggerAsyncId,name=new.target.name,requireManualDestroy}=options||{};super({captureRejections});this.triggerAsyncId=triggerAsyncId\?\?0,this.asyncResource=new AsyncResource(name,{triggerAsyncId,requireManualDestroy})}emit(...args){this.asyncResource.runInAsyncScope(()=>super.emit(...args))}emitDestroy(){this.asyncResource.emitDestroy()}}return Object.defineProperties(EventEmitter,{captureRejections:{get(){return EventEmitterPrototype[kCapture]},set(value){validateBoolean(value,\"EventEmitter.captureRejections\"),EventEmitterPrototype[kCapture]=value},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return defaultMaxListeners},set:(arg)=>{validateNumber(arg,\"defaultMaxListeners\",0),defaultMaxListeners=arg}},kMaxEventTargetListeners:{value:kMaxEventTargetListeners,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:kMaxEventTargetListenersWarned,enumerable:!1,configurable:!1,writable:!1}}),Object.assign(EventEmitter,{once,on,getEventListeners,setMaxListeners,EventEmitter,usingDomains:!1,captureRejectionSymbol,EventEmitterAsyncResource,errorMonitor:kErrorMonitor,setMaxListeners,init:EventEmitter,listenerCount}),EventEmitter})\n"_s; +// + +// +static constexpr ASCIILiteral NodeFSCode = "(function (){\"use strict\";var $,ReadStream,WriteStream;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),promises=@getInternalField(@internalModuleRegistry,17)||@createInternalModuleById(17),Stream=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34);var fs=Bun.fs();class FSWatcher extends EventEmitter{#watcher;#listener;constructor(path,options,listener){super();if(typeof options===\"function\")listener=options,options={};else if(typeof options===\"string\")options={encoding:options};if(typeof listener!==\"function\")listener=()=>{};this.#listener=listener;try{this.#watcher=fs.watch(path,options||{},this.#onEvent.bind(this))}catch(e){if(!e.message\?.startsWith(\"FileNotFound\"))throw e;const notFound=new Error(`ENOENT: no such file or directory, watch '${path}'`);throw notFound.code=\"ENOENT\",notFound.errno=-2,notFound.path=path,notFound.syscall=\"watch\",notFound.filename=path,notFound}}#onEvent(eventType,filenameOrError){if(eventType===\"error\"||eventType===\"close\")this.emit(eventType,filenameOrError);else this.emit(\"change\",eventType,filenameOrError),this.#listener(eventType,filenameOrError)}close(){this.#watcher\?.close(),this.#watcher=null}ref(){this.#watcher\?.ref()}unref(){this.#watcher\?.unref()}}var access=function access(...args){callbackify(fs.accessSync,args)},appendFile=function appendFile(...args){callbackify(fs.appendFileSync,args)},close=function close(...args){callbackify(fs.closeSync,args)},rm=function rm(...args){callbackify(fs.rmSync,args)},rmdir=function rmdir(...args){callbackify(fs.rmdirSync,args)},copyFile=function copyFile(...args){callbackify(fs.copyFileSync,args)},exists=function exists(...args){callbackify(fs.existsSync,args)},chown=function chown(...args){callbackify(fs.chownSync,args)},chmod=function chmod(...args){callbackify(fs.chmodSync,args)},fchmod=function fchmod(...args){callbackify(fs.fchmodSync,args)},fchown=function fchown(...args){callbackify(fs.fchownSync,args)},fstat=function fstat(...args){callbackify(fs.fstatSync,args)},fsync=function fsync(...args){callbackify(fs.fsyncSync,args)},ftruncate=function ftruncate(...args){callbackify(fs.ftruncateSync,args)},futimes=function futimes(...args){callbackify(fs.futimesSync,args)},lchmod=function lchmod(...args){callbackify(fs.lchmodSync,args)},lchown=function lchown(...args){callbackify(fs.lchownSync,args)},link=function link(...args){callbackify(fs.linkSync,args)},mkdir=function mkdir(...args){callbackify(fs.mkdirSync,args)},mkdtemp=function mkdtemp(...args){callbackify(fs.mkdtempSync,args)},open=function open(...args){callbackify(fs.openSync,args)},read=function read(...args){callbackify(fs.readSync,args)},write=function write(...args){callbackify(fs.writeSync,args)},readdir=function readdir(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.readdir(...args).then((result)=>callback(null,result),callback)},readFile=function readFile(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.readFile(...args).then((result)=>callback(null,result),callback)},writeFile=function writeFile(...args){callbackify(fs.writeFileSync,args)},readlink=function readlink(...args){callbackify(fs.readlinkSync,args)},realpath=function realpath(...args){callbackify(fs.realpathSync,args)},rename=function rename(...args){callbackify(fs.renameSync,args)},lstat=function lstat(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.lstat(...args).then((result)=>callback(null,result),callback)},stat=function stat(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.stat(...args).then((result)=>callback(null,result),callback)},symlink=function symlink(...args){callbackify(fs.symlinkSync,args)},truncate=function truncate(...args){callbackify(fs.truncateSync,args)},unlink=function unlink(...args){callbackify(fs.unlinkSync,args)},utimes=function utimes(...args){callbackify(fs.utimesSync,args)},lutimes=function lutimes(...args){callbackify(fs.lutimesSync,args)},accessSync=fs.accessSync.bind(fs),appendFileSync=fs.appendFileSync.bind(fs),closeSync=fs.closeSync.bind(fs),copyFileSync=fs.copyFileSync.bind(fs),existsSync=fs.existsSync.bind(fs),chownSync=fs.chownSync.bind(fs),chmodSync=fs.chmodSync.bind(fs),fchmodSync=fs.fchmodSync.bind(fs),fchownSync=fs.fchownSync.bind(fs),fstatSync=fs.fstatSync.bind(fs),fsyncSync=fs.fsyncSync.bind(fs),ftruncateSync=fs.ftruncateSync.bind(fs),futimesSync=fs.futimesSync.bind(fs),lchmodSync=fs.lchmodSync.bind(fs),lchownSync=fs.lchownSync.bind(fs),linkSync=fs.linkSync.bind(fs),lstatSync=fs.lstatSync.bind(fs),mkdirSync=fs.mkdirSync.bind(fs),mkdtempSync=fs.mkdtempSync.bind(fs),openSync=fs.openSync.bind(fs),readSync=fs.readSync.bind(fs),writeSync=fs.writeSync.bind(fs),readdirSync=fs.readdirSync.bind(fs),readFileSync=fs.readFileSync.bind(fs),writeFileSync=fs.writeFileSync.bind(fs),readlinkSync=fs.readlinkSync.bind(fs),realpathSync=fs.realpathSync.bind(fs),renameSync=fs.renameSync.bind(fs),statSync=fs.statSync.bind(fs),symlinkSync=fs.symlinkSync.bind(fs),truncateSync=fs.truncateSync.bind(fs),unlinkSync=fs.unlinkSync.bind(fs),utimesSync=fs.utimesSync.bind(fs),lutimesSync=fs.lutimesSync.bind(fs),rmSync=fs.rmSync.bind(fs),rmdirSync=fs.rmdirSync.bind(fs),writev=(fd,buffers,position,callback)=>{if(typeof position===\"function\")callback=position,position=null;queueMicrotask(()=>{try{var written=fs.writevSync(fd,buffers,position)}catch(e){callback(e)}callback(null,written,buffers)})},writevSync=fs.writevSync.bind(fs),readv=(fd,buffers,position,callback)=>{if(typeof position===\"function\")callback=position,position=null;queueMicrotask(()=>{try{var written=fs.readvSync(fd,buffers,position)}catch(e){callback(e)}callback(null,written,buffers)})},readvSync=fs.readvSync.bind(fs),Dirent=fs.Dirent,Stats=fs.Stats,watch=function watch(path,options,listener){return new FSWatcher(path,options,listener)};function callbackify(fsFunction,args){try{const result=fsFunction.apply(fs,args.slice(0,args.length-1)),callback=args[args.length-1];if(typeof callback===\"function\")queueMicrotask(()=>callback(null,result))}catch(e){const callback=args[args.length-1];if(typeof callback===\"function\")queueMicrotask(()=>callback(e))}}var readStreamPathFastPathSymbol=Symbol.for(\"Bun.Node.readStreamPathFastPath\");const readStreamSymbol=Symbol.for(\"Bun.NodeReadStream\"),readStreamPathOrFdSymbol=Symbol.for(\"Bun.NodeReadStreamPathOrFd\"),writeStreamSymbol=Symbol.for(\"Bun.NodeWriteStream\");var writeStreamPathFastPathSymbol=Symbol.for(\"Bun.NodeWriteStreamFastPath\"),writeStreamPathFastPathCallSymbol=Symbol.for(\"Bun.NodeWriteStreamFastPathCall\"),kIoDone=Symbol.for(\"kIoDone\"),defaultReadStreamOptions={file:void 0,fd:void 0,flags:\"r\",encoding:void 0,mode:438,autoClose:!0,emitClose:!0,start:0,end:Infinity,highWaterMark:65536,fs:{read,open:(path,flags,mode,cb)=>{var fd;try{fd=openSync(path,flags,mode)}catch(e){cb(e);return}cb(null,fd)},openSync,close},autoDestroy:!0},ReadStreamClass;ReadStream=function(InternalReadStream){ReadStreamClass=InternalReadStream,Object.defineProperty(ReadStreamClass.prototype,Symbol.toStringTag,{value:\"ReadStream\",enumerable:!1});function ReadStream2(path,options){return new InternalReadStream(path,options)}return ReadStream2.prototype=InternalReadStream.prototype,Object.defineProperty(ReadStream2,Symbol.hasInstance,{value(instance){return instance instanceof InternalReadStream}})}(class ReadStream2 extends Stream._getNativeReadableStreamPrototype(2,Stream.Readable){constructor(pathOrFd,options=defaultReadStreamOptions){if(typeof options!==\"object\"||!options)@throwTypeError(\"Expected options to be an object\");var{flags=defaultReadStreamOptions.flags,encoding=defaultReadStreamOptions.encoding,mode=defaultReadStreamOptions.mode,autoClose=defaultReadStreamOptions.autoClose,emitClose=defaultReadStreamOptions.emitClose,start=defaultReadStreamOptions.start,end=defaultReadStreamOptions.end,autoDestroy=defaultReadStreamOptions.autoClose,fs:fs2=defaultReadStreamOptions.fs,highWaterMark=defaultReadStreamOptions.highWaterMark}=options;if(pathOrFd\?.constructor\?.name===\"URL\")pathOrFd=Bun.fileURLToPath(pathOrFd);var tempThis={};if(typeof pathOrFd===\"string\"){if(pathOrFd.startsWith(\"file://\"))pathOrFd=Bun.fileURLToPath(pathOrFd);if(pathOrFd.length===0)@throwTypeError(\"Expected path to be a non-empty string\");tempThis.path=tempThis.file=tempThis[readStreamPathOrFdSymbol]=pathOrFd}else if(typeof pathOrFd===\"number\"){if(pathOrFd|=0,pathOrFd<0)@throwTypeError(\"Expected fd to be a positive integer\");tempThis.fd=tempThis[readStreamPathOrFdSymbol]=pathOrFd,tempThis.autoClose=!1}else @throwTypeError(\"Expected a path or file descriptor\");if(!tempThis.fd)tempThis.fd=fs2.openSync(pathOrFd,flags,mode);var fileRef=Bun.file(tempThis.fd),stream=fileRef.stream(),native=@direct(stream);if(!native)throw new Error(\"no native readable stream\");var{stream:ptr}=native;super(ptr,{...options,encoding,autoDestroy,autoClose,emitClose,highWaterMark});if(Object.assign(this,tempThis),this.#fileRef=fileRef,this.end=end,this._read=this.#internalRead,this.start=start,this.flags=flags,this.mode=mode,this.emitClose=emitClose,this[readStreamPathFastPathSymbol]=start===0&&end===Infinity&&autoClose&&fs2===defaultReadStreamOptions.fs&&(encoding===\"buffer\"||encoding===\"binary\"||encoding==null||encoding===\"utf-8\"||encoding===\"utf8\"),this._readableState.autoClose=autoDestroy=autoClose,this._readableState.highWaterMark=highWaterMark,start!==void 0)this.pos=start}#fileRef;#fs;file;path;fd=null;flags;mode;start;end;pos;bytesRead=0;#fileSize=-1;_read;[readStreamSymbol]=!0;[readStreamPathOrFdSymbol];[readStreamPathFastPathSymbol];_construct(callback){if(super._construct)super._construct(callback);else callback();this.emit(\"open\",this.fd),this.emit(\"ready\")}_destroy(err,cb){super._destroy(err,cb);try{var fd=this.fd;if(this[readStreamPathFastPathSymbol]=!1,!fd)cb(err);else this.#fs.close(fd,(er)=>{cb(er||err)}),this.fd=null}catch(e){throw e}}close(cb){if(typeof cb===\"function\")eos_()(this,cb);this.destroy()}push(chunk){var bytesRead=chunk\?.length\?\?0;if(bytesRead>0){this.bytesRead+=bytesRead;var currPos=this.pos;if(currPos!==void 0){if(this.bytesReadthis.end)chunk=chunk.slice(0,this.end-this.start+1);return super.push(chunk,...rest)}var end=this.end;if(end!==void 0&&this.bytesRead>end){chunk=chunk.slice(0,end-currPos+1);var[_,...rest]=arguments;return this.pos=this.bytesRead,super.push(chunk,...rest)}this.pos=this.bytesRead}}return super.push(...arguments)}#internalRead(n){var{pos,end,bytesRead,fd,encoding}=this;if(n=pos!==void 0\?Math.min(end-pos+1,n):Math.min(end-bytesRead+1,n),n<=0){this.push(null);return}if(this.#fileSize===-1&&bytesRead===0&&pos===void 0){var stat2=fstatSync(fd);if(this.#fileSize=stat2.size,this.#fileSize>0&&n>this.#fileSize)n=this.#fileSize+1}this[kIoDone]=!1;var res=super._read(n);if(@isPromise(res)){var then=res\?.then;if(then&&@isCallable(then))then(()=>{if(this[kIoDone]=!0,this.destroyed)this.emit(kIoDone)},(er)=>{this[kIoDone]=!0,this.#errorOrDestroy(er)})}else if(this[kIoDone]=!0,this.destroyed)this.emit(kIoDone),this.#errorOrDestroy(new Error(\"ERR_STREAM_PREMATURE_CLOSE\"))}#errorOrDestroy(err,sync=null){var{_readableState:r={destroyed:!1,autoDestroy:!1},_writableState:w={destroyed:!1,autoDestroy:!1}}=this;if(w\?.destroyed||r\?.destroyed)return this;if(r\?.autoDestroy||w\?.autoDestroy)this.destroy(err);else if(err)this.emit(\"error\",err)}pause(){return this[readStreamPathFastPathSymbol]=!1,super.pause()}resume(){return this[readStreamPathFastPathSymbol]=!1,super.resume()}unshift(...args){return this[readStreamPathFastPathSymbol]=!1,super.unshift(...args)}pipe(dest,pipeOpts){if(this[readStreamPathFastPathSymbol]&&(pipeOpts\?.end\?\?!0)&&this._readableState\?.pipes\?.length===0){if((writeStreamPathFastPathSymbol in dest)&&dest[writeStreamPathFastPathSymbol]){if(dest[writeStreamPathFastPathCallSymbol](this,pipeOpts))return this}}return this[readStreamPathFastPathSymbol]=!1,super.pipe(dest,pipeOpts)}});function createReadStream(path,options){return new ReadStream(path,options)}var defaultWriteStreamOptions={fd:null,start:void 0,pos:void 0,encoding:void 0,flags:\"w\",mode:438,fs:{write,close,open,openSync}},WriteStreamClass;WriteStream=function(InternalWriteStream){WriteStreamClass=InternalWriteStream,Object.defineProperty(WriteStreamClass.prototype,Symbol.toStringTag,{value:\"WritesStream\",enumerable:!1});function WriteStream2(path,options){return new InternalWriteStream(path,options)}return WriteStream2.prototype=InternalWriteStream.prototype,Object.defineProperty(WriteStream2,Symbol.hasInstance,{value(instance){return instance instanceof InternalWriteStream}})}(class WriteStream2 extends Stream.NativeWritable{constructor(path,options=defaultWriteStreamOptions){if(!options)@throwTypeError(\"Expected options to be an object\");var{fs:fs2=defaultWriteStreamOptions.fs,start=defaultWriteStreamOptions.start,flags=defaultWriteStreamOptions.flags,mode=defaultWriteStreamOptions.mode,autoClose=!0,emitClose=!1,autoDestroy=autoClose,encoding=defaultWriteStreamOptions.encoding,fd=defaultWriteStreamOptions.fd,pos=defaultWriteStreamOptions.pos}=options,tempThis={};if(typeof path===\"string\"){if(path.length===0)@throwTypeError(\"Expected a non-empty path\");if(path.startsWith(\"file:\"))path=Bun.fileURLToPath(path);tempThis.path=path,tempThis.fd=null,tempThis[writeStreamPathFastPathSymbol]=autoClose&&(start===void 0||start===0)&&fs2.write===defaultWriteStreamOptions.fs.write&&fs2.close===defaultWriteStreamOptions.fs.close}else tempThis.fd=fd,tempThis[writeStreamPathFastPathSymbol]=!1;if(!tempThis.fd)tempThis.fd=fs2.openSync(path,flags,mode);super(tempThis.fd,{...options,decodeStrings:!1,autoDestroy,emitClose,fd:tempThis});if(Object.assign(this,tempThis),typeof fs2\?.write!==\"function\")@throwTypeError(\"Expected fs.write to be a function\");if(typeof fs2\?.close!==\"function\")@throwTypeError(\"Expected fs.close to be a function\");if(typeof fs2\?.open!==\"function\")@throwTypeError(\"Expected fs.open to be a function\");if(typeof path===\"object\"&&path){if(path instanceof URL)path=Bun.fileURLToPath(path)}if(typeof path!==\"string\"&&typeof fd!==\"number\")@throwTypeError(\"Expected a path or file descriptor\");if(this.start=start,this.#fs=fs2,this.flags=flags,this.mode=mode,this.start!==void 0)this.pos=this.start;if(encoding!==defaultWriteStreamOptions.encoding){if(this.setDefaultEncoding(encoding),encoding!==\"buffer\"&&encoding!==\"utf8\"&&encoding!==\"utf-8\"&&encoding!==\"binary\")this[writeStreamPathFastPathSymbol]=!1}}get autoClose(){return this._writableState.autoDestroy}set autoClose(val){this._writableState.autoDestroy=val}destroySoon=this.end;open(){}path;fd;flags;mode;#fs;bytesWritten=0;pos;[writeStreamPathFastPathSymbol];[writeStreamSymbol]=!0;start;[writeStreamPathFastPathCallSymbol](readStream,pipeOpts){if(!this[writeStreamPathFastPathSymbol])return!1;if(this.fd!==null)return this[writeStreamPathFastPathSymbol]=!1,!1;return this[kIoDone]=!1,readStream[kIoDone]=!1,Bun.write(this[writeStreamPathFastPathSymbol],readStream[readStreamPathOrFdSymbol]).then((bytesWritten)=>{readStream[kIoDone]=this[kIoDone]=!0,this.bytesWritten+=bytesWritten,readStream.bytesRead+=bytesWritten,this.end(),readStream.close()},(err)=>{readStream[kIoDone]=this[kIoDone]=!0,this.#errorOrDestroy(err),readStream.emit(\"error\",err)})}isBunFastPathEnabled(){return this[writeStreamPathFastPathSymbol]}disableBunFastPath(){this[writeStreamPathFastPathSymbol]=!1}#handleWrite(er,bytes){if(er)return this.#errorOrDestroy(er);this.bytesWritten+=bytes}#internalClose(err,cb){this[writeStreamPathFastPathSymbol]=!1;var fd=this.fd;this.#fs.close(fd,(er)=>{this.fd=null,cb(err||er)})}_construct(callback){if(typeof this.fd===\"number\"){callback();return}callback(),this.emit(\"open\",this.fd),this.emit(\"ready\")}_destroy(err,cb){if(this.fd===null)return cb(err);if(this[kIoDone]){this.once(kIoDone,()=>this.#internalClose(err,cb));return}this.#internalClose(err,cb)}[kIoDone]=!1;close(cb){if(cb){if(this.closed){process.nextTick(cb);return}this.on(\"close\",cb)}if(!this.autoClose)this.on(\"finish\",this.destroy);this.end()}write(chunk,encoding=this._writableState.defaultEncoding,cb){if(this[writeStreamPathFastPathSymbol]=!1,typeof chunk===\"string\")chunk=Buffer.from(chunk,encoding);var native=this.pos===void 0;return this[kIoDone]=!0,super.write(chunk,encoding,native\?(err,bytes)=>{if(this[kIoDone]=!1,this.#handleWrite(err,bytes),this.emit(kIoDone),cb)!err\?cb():cb(err)}:()=>{},native)}#internalWriteSlow(chunk,encoding,cb){this.#fs.write(this.fd,chunk,0,chunk.length,this.pos,(err,bytes)=>{this[kIoDone]=!1,this.#handleWrite(err,bytes),this.emit(kIoDone),!err\?cb():cb(err)})}end(chunk,encoding,cb){var native=this.pos===void 0;return super.end(chunk,encoding,cb,native)}_write=this.#internalWriteSlow;_writev=void 0;get pending(){return this.fd===null}_destroy(err,cb){this.close(err,cb)}#errorOrDestroy(err){var{_readableState:r={destroyed:!1,autoDestroy:!1},_writableState:w={destroyed:!1,autoDestroy:!1}}=this;if(w\?.destroyed||r\?.destroyed)return this;if(r\?.autoDestroy||w\?.autoDestroy)this.destroy(err);else if(err)this.emit(\"error\",err)}});function createWriteStream(path,options){return new WriteStream(path,options)}return Object.defineProperties(fs,{createReadStream:{value:createReadStream},createWriteStream:{value:createWriteStream},ReadStream:{value:ReadStream},WriteStream:{value:WriteStream}}),realpath.native=realpath,realpathSync.native=realpathSync,$={access,accessSync,appendFile,appendFileSync,chmod,chmodSync,chown,chownSync,close,closeSync,constants:promises.constants,copyFile,copyFileSync,createReadStream,createWriteStream,Dirent,exists,existsSync,fchmod,fchmodSync,fchown,fchownSync,fstat,fstatSync,fsync,fsyncSync,ftruncate,ftruncateSync,futimes,futimesSync,lchmod,lchmodSync,lchown,lchownSync,link,linkSync,lstat,lstatSync,lutimes,lutimesSync,mkdir,mkdirSync,mkdtemp,mkdtempSync,open,openSync,promises,read,readFile,readFileSync,readSync,readdir,readdirSync,readlink,readlinkSync,realpath,realpathSync,rename,renameSync,rm,rmSync,rmdir,rmdirSync,stat,statSync,Stats,symlink,symlinkSync,truncate,truncateSync,unlink,unlinkSync,utimes,utimesSync,write,writeFile,writeFileSync,writeSync,WriteStream,ReadStream,watch,FSWatcher,writev,writevSync,readv,readvSync,[Symbol.for(\"::bunternal::\")]:{ReadStreamClass,WriteStreamClass}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeFSPromisesCode = "(function (){\"use strict\";var $;const constants=@processBindingConstants.fs;var fs=Bun.fs();const notrace=\"::bunternal::\";var promisify={[notrace]:(fsFunction)=>{return async function(...args){return await 1,fsFunction.apply(fs,args)}}}[notrace];function watch(filename,options={}){if(filename instanceof URL)@throwTypeError(\"Watch URLs are not supported yet\");else if(Buffer.isBuffer(filename))filename=filename.toString();else if(typeof filename!==\"string\")@throwTypeError(\"Expected path to be a string or Buffer\");let nextEventResolve=null;if(typeof options===\"string\")options={encoding:options};const queue=@createFIFO(),watcher=fs.watch(filename,options||{},(eventType,filename2)=>{if(queue.push({eventType,filename:filename2}),nextEventResolve){const resolve=nextEventResolve;nextEventResolve=null,resolve()}});return{[Symbol.asyncIterator](){let closed=!1;return{async next(){while(!closed){let event;while(event=queue.shift()){if(event.eventType===\"close\")return closed=!0,{value:void 0,done:!0};if(event.eventType===\"error\")throw closed=!0,event.filename;return{value:event,done:!1}}const{promise,resolve}=Promise.withResolvers();nextEventResolve=resolve,await promise}return{value:void 0,done:!0}},return(){if(!closed){if(watcher.close(),closed=!0,nextEventResolve){const resolve=nextEventResolve;nextEventResolve=null,resolve()}}return{value:void 0,done:!0}}}}}}return $={access:promisify(fs.accessSync),appendFile:promisify(fs.appendFileSync),close:promisify(fs.closeSync),copyFile:promisify(fs.copyFileSync),exists:promisify(fs.existsSync),chown:promisify(fs.chownSync),chmod:promisify(fs.chmodSync),fchmod:promisify(fs.fchmodSync),fchown:promisify(fs.fchownSync),fstat:promisify(fs.fstatSync),fsync:promisify(fs.fsyncSync),ftruncate:promisify(fs.ftruncateSync),futimes:promisify(fs.futimesSync),lchmod:promisify(fs.lchmodSync),lchown:promisify(fs.lchownSync),link:promisify(fs.linkSync),lstat:fs.lstat.bind(fs),mkdir:promisify(fs.mkdirSync),mkdtemp:promisify(fs.mkdtempSync),open:promisify(fs.openSync),read:promisify(fs.readSync),write:promisify(fs.writeSync),readdir:fs.readdir.bind(fs),readFile:fs.readFile.bind(fs),writeFile:promisify(fs.writeFileSync),readlink:promisify(fs.readlinkSync),realpath:promisify(fs.realpathSync),rename:promisify(fs.renameSync),stat:fs.stat.bind(fs),symlink:promisify(fs.symlinkSync),truncate:promisify(fs.truncateSync),unlink:promisify(fs.unlinkSync),utimes:promisify(fs.utimesSync),lutimes:promisify(fs.lutimesSync),rm:promisify(fs.rmSync),rmdir:promisify(fs.rmdirSync),writev:(fd,buffers,position)=>{return new Promise((resolve,reject)=>{try{var bytesWritten=fs.writevSync(fd,buffers,position)}catch(err){reject(err);return}resolve({bytesWritten,buffers})})},readv:(fd,buffers,position)=>{return new Promise((resolve,reject)=>{try{var bytesRead=fs.readvSync(fd,buffers,position)}catch(err){reject(err);return}resolve({bytesRead,buffers})})},constants,watch},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";var $;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),{isTypedArray}=@requireNativeModule(\"node:util/types\"),{Duplex,Readable,Writable}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),headerCharRegex=/[^\\t\\x20-\\x7e\\x80-\\xff]/;function checkInvalidHeaderChar(val){return RegExpPrototypeExec.call(headerCharRegex,val)!==null}const validateHeaderName=(name,label)=>{if(typeof name!==\"string\"||!name||!checkIsHttpToken(name))throw new Error(\"ERR_INVALID_HTTP_TOKEN\")},validateHeaderValue=(name,value)=>{if(value===void 0)throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");if(checkInvalidHeaderChar(value))throw new Error(\"ERR_INVALID_CHAR\")};function isIPv6(input){return new RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input)}const{URL}=globalThis,globalReportError=globalThis.reportError,setTimeout=globalThis.setTimeout,fetch=Bun.fetch,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.\";var _defaultHTTPSAgent,kInternalRequest=Symbol(\"kInternalRequest\"),kInternalSocketData=Symbol.for(\"::bunternal::\");const kEmptyBuffer=Buffer.alloc(0);function isValidTLSArray(obj){if(typeof obj===\"string\"||isTypedArray(obj)||obj instanceof ArrayBuffer||obj instanceof Blob)return!0;if(Array.isArray(obj)){for(var i=0;i{this.close()}),host=port\?.host,port=port\?.port,typeof port\?.callback===\"function\")onListen=port\?.callback}if(typeof backlog===\"function\")onListen=backlog;const ResponseClass=this.#options.ServerResponse||ServerResponse,RequestClass=this.#options.IncomingMessage||IncomingMessage;try{const tls=this.#tls;if(tls)this.serverName=tls.serverName||host||\"localhost\";this.#server=Bun.serve({tls,port,hostname:host,websocket:{open(ws){ws.data.open(ws)},message(ws,message){ws.data.message(ws,message)},close(ws,code,reason){ws.data.close(ws,code,reason)},drain(ws){ws.data.drain(ws)}},fetch(req,_server){var pendingResponse,pendingError,rejectFunction,resolveFunction,reject=(err)=>{if(pendingError)return;if(pendingError=err,rejectFunction)rejectFunction(err)},reply=function(resp){if(pendingResponse)return;if(pendingResponse=resp,resolveFunction)resolveFunction(resp)};const http_req=new RequestClass(req),http_res=new ResponseClass({reply,req:http_req});if(http_req.once(\"error\",(err)=>reject(err)),http_res.once(\"error\",(err)=>reject(err)),req.headers.get(\"upgrade\")){const socket=new FakeSocket;socket[kInternalSocketData]=[_server,http_res,req],server.emit(\"upgrade\",http_req,socket,kEmptyBuffer)}else server.emit(\"request\",http_req,http_res);if(pendingError)throw pendingError;if(pendingResponse)return pendingResponse;return new Promise((resolve,reject2)=>{resolveFunction=resolve,rejectFunction=reject2})}}),setTimeout(emitListeningNextTick,1,this,onListen,null,this.#server.hostname,this.#server.port)}catch(err){setTimeout(emitListeningNextTick,1,this,onListen,err)}return this}setTimeout(msecs,callback){}}function assignHeaders(object,req){var headers=req.headers.toJSON();const rawHeaders=@newArrayWithSize(req.headers.count*2);var i=0;for(let key in headers)rawHeaders[i++]=key,rawHeaders[i++]=headers[key];object.headers=headers,object.rawHeaders=rawHeaders}function destroyBodyStreamNT(bodyStream){bodyStream.destroy()}var defaultIncomingOpts={type:\"request\"};function getDefaultHTTPSAgent(){return _defaultHTTPSAgent\?\?=new Agent({defaultPort:443,protocol:\"https:\"})}class IncomingMessage extends Readable{method;complete;constructor(req,defaultIncomingOpts2){const method=req.method;super();const url=new URL(req.url);var{type=\"request\",[kInternalRequest]:nodeReq}=defaultIncomingOpts2||{};this.#noBody=type===\"request\"\?method===\"GET\"||method===\"HEAD\"||method===\"TRACE\"||method===\"CONNECT\"||method===\"OPTIONS\"||(parseInt(req.headers.get(\"Content-Length\")||\"\")||0)===0:!1,this.#req=req,this.method=method,this.#type=type,this.complete=!!this.#noBody,this.#bodyStream=void 0;const socket=new FakeSocket;socket.remoteAddress=url.hostname,socket.remotePort=url.port,this.#fakeSocket=socket,this.url=url.pathname+url.search,this.#nodeReq=nodeReq,assignHeaders(this,req)}headers;rawHeaders;_consuming=!1;_dumped=!1;#bodyStream;#fakeSocket;#noBody=!1;#aborted=!1;#req;url;#type;#nodeReq;get req(){return this.#nodeReq}_construct(callback){if(this.#type===\"response\"||this.#noBody){callback();return}const contentLength=this.#req.headers.get(\"content-length\");if((contentLength\?parseInt(contentLength,10):0)===0){this.#noBody=!0,callback();return}callback()}async#consumeStream(reader){while(!0){var{done,value}=await reader.readMany();if(this.#aborted)return;if(done){this.push(null),this.destroy();break}for(var v of value)this.push(v)}}_read(size){if(this.#noBody)this.push(null),this.complete=!0;else if(this.#bodyStream==null){const reader=this.#req.body\?.getReader();if(!reader){this.push(null);return}this.#bodyStream=reader,this.#consumeStream(reader)}}get aborted(){return this.#aborted}#abort(){if(this.#aborted)return;this.#aborted=!0;var bodyStream=this.#bodyStream;if(!bodyStream)return;bodyStream.cancel(),this.complete=!0,this.#bodyStream=void 0,this.push(null)}get connection(){return this.#fakeSocket}get statusCode(){return this.#req.status}get statusMessage(){return STATUS_CODES[this.#req.status]}get httpVersion(){return\"1.1\"}get rawTrailers(){return[]}get httpVersionMajor(){return 1}get httpVersionMinor(){return 1}get trailers(){return kEmptyObject}get socket(){return this.#fakeSocket\?\?=new FakeSocket}set socket(val){this.#fakeSocket=val}setTimeout(msecs,callback){throw new Error(\"not implemented\")}}function emitErrorNt(msg,err,callback){if(callback(err),typeof msg.emit===\"function\"&&!msg._closed)msg.emit(\"error\",err)}function onError(self,err,cb){process.nextTick(()=>emitErrorNt(self,err,cb))}function write_(msg,chunk,encoding,callback,fromEnd){if(typeof callback!==\"function\")callback=nop;let len;if(chunk===null)throw new Error(\"ERR_STREAM_NULL_VALUES\");else if(typeof chunk===\"string\")len=Buffer.byteLength(chunk,encoding);else throw new Error(\"Invalid arg type for chunk\");let err;if(msg.finished)err=new Error(\"ERR_STREAM_WRITE_AFTER_END\");else if(msg.destroyed)err=new Error(\"ERR_STREAM_DESTROYED\");if(err){if(!msg.destroyed)onError(msg,err,callback);else process.nextTick(callback,err);return!1}if(!msg._header){if(fromEnd)msg._contentLength=len}if(!msg._hasBody)return process.nextTick(callback),!0;return!0}class OutgoingMessage extends Writable{constructor(){super(...arguments)}#headers;headersSent=!1;sendDate=!0;req;timeout;#finished=!1;[kEndCalled]=!1;#fakeSocket;#timeoutTimer;[kAbortController]=null;_implicitHeader(){}get headers(){if(!this.#headers)return kEmptyObject;return this.#headers.toJSON()}get shouldKeepAlive(){return!0}get chunkedEncoding(){return!1}set chunkedEncoding(value){}set shouldKeepAlive(value){}get useChunkedEncodingByDefault(){return!0}set useChunkedEncodingByDefault(value){}get socket(){return this.#fakeSocket\?\?=new FakeSocket}set socket(val){this.#fakeSocket=val}get connection(){return this.socket}get finished(){return this.#finished}appendHeader(name,value){var headers=this.#headers\?\?=new Headers;headers.append(name,value)}flushHeaders(){}getHeader(name){return getHeader(this.#headers,name)}getHeaders(){if(!this.#headers)return kEmptyObject;return this.#headers.toJSON()}getHeaderNames(){var headers=this.#headers;if(!headers)return[];return Array.from(headers.keys())}removeHeader(name){if(!this.#headers)return;this.#headers.delete(name)}setHeader(name,value){var headers=this.#headers\?\?=new Headers;return headers.set(name,value),this}hasHeader(name){if(!this.#headers)return!1;return this.#headers.has(name)}addTrailers(headers){throw new Error(\"not implemented\")}[kClearTimeout](){if(this.#timeoutTimer)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.destroyed)return 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}}let OriginalWriteHeadFn,OriginalImplicitHeadFn;class ServerResponse extends Writable{constructor({req,reply}){super();if(this.req=req,this._reply=reply,this.sendDate=!0,this.statusCode=200,this.headersSent=!1,this.statusMessage=void 0,this.#controller=void 0,this.#firstWrite=void 0,this._writableState.decodeStrings=!1,this.#deferred=void 0,req.method===\"HEAD\")this._hasBody=!1}req;_reply;sendDate;statusCode;#headers;headersSent=!1;statusMessage;#controller;#firstWrite;_sent100=!1;_defaultKeepAlive=!1;_removedConnection=!1;_removedContLen=!1;_hasBody=!0;#deferred=void 0;#finished=!1;_implicitHeader(){this.writeHead(this.statusCode)}_write(chunk,encoding,callback){if(!this.#firstWrite&&!this.headersSent){this.#firstWrite=chunk,callback();return}this.#ensureReadableStreamController((controller)=>{controller.write(chunk),callback()})}_writev(chunks,callback){if(chunks.length===1&&!this.headersSent&&!this.#firstWrite){this.#firstWrite=chunks[0].chunk,callback();return}this.#ensureReadableStreamController((controller)=>{for(let chunk of chunks)controller.write(chunk.chunk);callback()})}#ensureReadableStreamController(run){var thisController=this.#controller;if(thisController)return run(thisController);this.headersSent=!0;var firstWrite=this.#firstWrite;this.#firstWrite=void 0,this._reply(new Response(new ReadableStream({type:\"direct\",pull:(controller)=>{if(this.#controller=controller,firstWrite)controller.write(firstWrite);if(firstWrite=void 0,run(controller),!this.#finished)return new Promise((resolve)=>{this.#deferred=resolve})}}),{headers:this.#headers,status:this.statusCode,statusText:this.statusMessage\?\?STATUS_CODES[this.statusCode]}))}#drainHeadersIfObservable(){if(this._implicitHeader===OriginalImplicitHeadFn&&this.writeHead===OriginalWriteHeadFn)return;this._implicitHeader()}_final(callback){if(!this.headersSent){var data=this.#firstWrite||\"\";this.#firstWrite=void 0,this.#finished=!0,this.#drainHeadersIfObservable(),this._reply(new Response(data,{headers:this.#headers,status:this.statusCode,statusText:this.statusMessage\?\?STATUS_CODES[this.statusCode]})),callback&&callback();return}this.#finished=!0,this.#ensureReadableStreamController((controller)=>{controller.end(),callback();var deferred=this.#deferred;if(deferred)this.#deferred=void 0,deferred()})}writeProcessing(){throw new Error(\"not implemented\")}addTrailers(headers){throw new Error(\"not implemented\")}assignSocket(socket){throw new Error(\"not implemented\")}detachSocket(socket){throw new Error(\"not implemented\")}writeContinue(callback){throw new Error(\"not implemented\")}setTimeout(msecs,callback){throw new Error(\"not implemented\")}get shouldKeepAlive(){return!0}get chunkedEncoding(){return!1}set chunkedEncoding(value){}set shouldKeepAlive(value){}get useChunkedEncodingByDefault(){return!0}set useChunkedEncodingByDefault(value){}appendHeader(name,value){var headers=this.#headers\?\?=new Headers;headers.append(name,value)}flushHeaders(){}getHeader(name){return getHeader(this.#headers,name)}getHeaders(){var headers=this.#headers;if(!headers)return kEmptyObject;return headers.toJSON()}getHeaderNames(){var headers=this.#headers;if(!headers)return[];return Array.from(headers.keys())}removeHeader(name){if(!this.#headers)return;this.#headers.delete(name)}setHeader(name,value){var headers=this.#headers\?\?=new Headers;return headers.set(name,value),this}hasHeader(name){if(!this.#headers)return!1;return this.#headers.has(name)}writeHead(statusCode,statusMessage,headers){return _writeHead(statusCode,statusMessage,headers,this),this}}OriginalWriteHeadFn=ServerResponse.prototype.writeHead,OriginalImplicitHeadFn=ServerResponse.prototype._implicitHeader;class ClientRequest extends OutgoingMessage{#timeout;#res=null;#upgradeOrConnect=!1;#parser=null;#maxHeadersCount=null;#reusedSocket=!1;#host;#protocol;#method;#port;#useDefaultPort;#joinDuplicateHeaders;#maxHeaderSize;#agent=globalAgent;#path;#socketPath;#bodyChunks=null;#fetchRequest;#signal=null;[kAbortController]=null;#timeoutTimer=void 0;#options;#finished;get path(){return this.#path}get port(){return this.#port}get method(){return this.#method}get host(){return this.#host}get protocol(){return this.#protocol}_write(chunk,encoding,callback){if(!this.#bodyChunks){this.#bodyChunks=[chunk],callback();return}this.#bodyChunks.push(chunk),callback()}_writev(chunks,callback){if(!this.#bodyChunks){this.#bodyChunks=chunks,callback();return}this.#bodyChunks.push(...chunks),callback()}_final(callback){if(this.#finished=!0,this[kAbortController]=new AbortController,this[kAbortController].signal.addEventListener(\"abort\",()=>{this[kClearTimeout]()}),this.#signal\?.aborted)this[kAbortController].abort();var method=this.#method,body=this.#bodyChunks\?.length===1\?this.#bodyChunks[0]:Buffer.concat(this.#bodyChunks||[]);try{this.#fetchRequest=fetch(`${this.#protocol}//${this.#host}${this.#useDefaultPort\?\"\":\":\"+this.#port}${this.#path}`,{method,headers:this.getHeaders(),body:body&&method!==\"GET\"&&method!==\"HEAD\"&&method!==\"OPTIONS\"\?body:void 0,redirect:\"manual\",verbose:!1,signal:this[kAbortController].signal,timeout:!1}).then((response)=>{var res=this.#res=new IncomingMessage(response,{type:\"response\",[kInternalRequest]:this});this.emit(\"response\",res)}).catch((err)=>{this.emit(\"error\",err)}).finally(()=>{this.#fetchRequest=null,this[kClearTimeout]()})}catch(err){this.emit(\"error\",err)}finally{callback()}}get aborted(){return this.#signal\?.aborted||!!this[kAbortController]\?.signal.aborted}abort(){if(this.aborted)return;this[kAbortController].abort()}constructor(input,options,cb){super();if(typeof input===\"string\"){const urlStr=input;try{var urlObject=new URL(urlStr)}catch(e){@throwTypeError(`Invalid URL: ${urlStr}`)}input=urlToHttpOptions(urlObject)}else if(input&&typeof input===\"object\"&&input instanceof URL)input=urlToHttpOptions(input);else cb=options,options=input,input=null;if(typeof options===\"function\")cb=options,options=input||kEmptyObject;else options=ObjectAssign(input||{},options);var defaultAgent=options._defaultAgent||Agent.globalAgent;let protocol=options.protocol;if(!protocol)if(options.port===443)protocol=\"https:\";else protocol=defaultAgent.protocol||\"http:\";switch(this.#protocol=protocol,this.#agent\?.protocol){case void 0:break;case\"http:\":if(protocol===\"https:\"){defaultAgent=this.#agent=getDefaultHTTPSAgent();break}case\"https:\":if(protocol===\"https\"){defaultAgent=this.#agent=Agent.globalAgent;break}default:break}if(options.path){const path=String(options.path);if(RegExpPrototypeExec.call(INVALID_PATH_REGEX,path)!==null)throw new Error(\"Path contains unescaped characters\")}if(protocol!==\"http:\"&&protocol!==\"https:\"&&protocol){const expectedProtocol=defaultAgent\?.protocol\?\?\"http:\";throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`)}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\";this.#socketPath=options.socketPath;const signal=options.signal;if(signal)signal.addEventListener(\"abort\",()=>{this[kAbortController]\?.abort()}),this.#signal=signal;let method=options.method;const methodIsString=typeof method===\"string\";if(method!==null&&method!==void 0&&!methodIsString)throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");if(methodIsString&&method){if(!checkIsHttpToken(method))throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");method=this.#method=StringPrototypeToUpperCase.call(method)}else method=this.#method=\"GET\";const _maxHeaderSize=options.maxHeaderSize;this.#maxHeaderSize=_maxHeaderSize;var _joinDuplicateHeaders=options.joinDuplicateHeaders;if(this.#joinDuplicateHeaders=_joinDuplicateHeaders,this.#path=options.path||\"/\",cb)this.once(\"response\",cb);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)this.setHeader(key,headers[key]);var auth=options.auth;if(auth&&!this.getHeader(\"Authorization\"))this.setHeader(\"Authorization\",\"Basic \"+Buffer.from(auth).toString(\"base64\"))}var{signal:_signal,...optsWithoutSignal}=options;this.#options=optsWithoutSignal}setSocketKeepAlive(enable=!0,initialDelay=0){}setNoDelay(noDelay=!0){}[kClearTimeout](){if(this.#timeoutTimer)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.destroyed)return 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}}function urlToHttpOptions(url){var{protocol,hostname,hash,search,pathname,href,port,username,password}=url;return{protocol,hostname:typeof hostname===\"string\"&&StringPrototypeStartsWith.call(hostname,\"[\")\?StringPrototypeSlice.call(hostname,1,-1):hostname,hash,search,pathname,path:`${pathname||\"\"}${search||\"\"}`,href,port:port\?Number(port):protocol===\"https:\"\?443:protocol===\"http:\"\?80:void 0,auth:username||password\?`${decodeURIComponent(username)}:${decodeURIComponent(password)}`:void 0}}function validateHost(host,name){if(host!==null&&host!==void 0&&typeof host!==\"string\")throw new Error(\"Invalid arg type in options\");return host}const tokenRegExp=/^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/;function checkIsHttpToken(val){return RegExpPrototypeExec.call(tokenRegExp,val)!==null}const METHODS=[\"ACL\",\"BIND\",\"CHECKOUT\",\"CONNECT\",\"COPY\",\"DELETE\",\"GET\",\"HEAD\",\"LINK\",\"LOCK\",\"M-SEARCH\",\"MERGE\",\"MKACTIVITY\",\"MKCALENDAR\",\"MKCOL\",\"MOVE\",\"NOTIFY\",\"OPTIONS\",\"PATCH\",\"POST\",\"PROPFIND\",\"PROPPATCH\",\"PURGE\",\"PUT\",\"REBIND\",\"REPORT\",\"SEARCH\",\"SOURCE\",\"SUBSCRIBE\",\"TRACE\",\"UNBIND\",\"UNLINK\",\"UNLOCK\",\"UNSUBSCRIBE\"],STATUS_CODES={100:\"Continue\",101:\"Switching Protocols\",102:\"Processing\",103:\"Early Hints\",200:\"OK\",201:\"Created\",202:\"Accepted\",203:\"Non-Authoritative Information\",204:\"No Content\",205:\"Reset Content\",206:\"Partial Content\",207:\"Multi-Status\",208:\"Already Reported\",226:\"IM Used\",300:\"Multiple Choices\",301:\"Moved Permanently\",302:\"Found\",303:\"See Other\",304:\"Not Modified\",305:\"Use Proxy\",307:\"Temporary Redirect\",308:\"Permanent Redirect\",400:\"Bad Request\",401:\"Unauthorized\",402:\"Payment Required\",403:\"Forbidden\",404:\"Not Found\",405:\"Method Not Allowed\",406:\"Not Acceptable\",407:\"Proxy Authentication Required\",408:\"Request Timeout\",409:\"Conflict\",410:\"Gone\",411:\"Length Required\",412:\"Precondition Failed\",413:\"Payload Too Large\",414:\"URI Too Long\",415:\"Unsupported Media Type\",416:\"Range Not Satisfiable\",417:\"Expectation Failed\",418:\"I'm a Teapot\",421:\"Misdirected Request\",422:\"Unprocessable Entity\",423:\"Locked\",424:\"Failed Dependency\",425:\"Too Early\",426:\"Upgrade Required\",428:\"Precondition Required\",429:\"Too Many Requests\",431:\"Request Header Fields Too Large\",451:\"Unavailable For Legal Reasons\",500:\"Internal Server Error\",501:\"Not Implemented\",502:\"Bad Gateway\",503:\"Service Unavailable\",504:\"Gateway Timeout\",505:\"HTTP Version Not Supported\",506:\"Variant Also Negotiates\",507:\"Insufficient Storage\",508:\"Loop Detected\",509:\"Bandwidth Limit Exceeded\",510:\"Not Extended\",511:\"Network Authentication Required\"};function _normalizeArgs(args){let arr;if(args.length===0)return arr=[{},null],arr;const arg0=args[0];let options={};if(typeof arg0===\"object\"&&arg0!==null)options=arg0;else if(options.port=arg0,args.length>1&&typeof args[1]===\"string\")options.host=args[1];const cb=args[args.length-1];if(typeof cb!==\"function\")arr=[options,null];else arr=[options,cb];return arr}function _writeHead(statusCode,reason,obj,response){if(statusCode|=0,statusCode<100||statusCode>999)throw new Error(\"status code must be between 100 and 999\");if(typeof reason===\"string\")response.statusMessage=reason;else{if(!response.statusMessage)response.statusMessage=STATUS_CODES[statusCode]||\"unknown\";obj=reason}response.statusCode=statusCode;{let k;if(Array.isArray(obj)){if(obj.length%2!==0)throw new Error(\"raw headers must have an even number of elements\");for(let n=0;n=100&&statusCode<=199)response._hasBody=!1}function request(url,options,cb){return new ClientRequest(url,options,cb)}function get(url,options,cb){const req=request(url,options,cb);return req.end(),req}var globalAgent=new Agent;return $={Agent,Server,METHODS,STATUS_CODES,createServer,ServerResponse,IncomingMessage,request,get,maxHeaderSize:16384,validateHeaderName,validateHeaderValue,setMaxIdleHTTPParsers(max){},globalAgent,ClientRequest,OutgoingMessage},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttp2Code = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function connect(){throwNotImplemented(\"node:http2 connect\",887)}const constants={NGHTTP2_ERR_FRAME_SIZE_ERROR:-522,NGHTTP2_SESSION_SERVER:0,NGHTTP2_SESSION_CLIENT:1,NGHTTP2_STREAM_STATE_IDLE:1,NGHTTP2_STREAM_STATE_OPEN:2,NGHTTP2_STREAM_STATE_RESERVED_LOCAL:3,NGHTTP2_STREAM_STATE_RESERVED_REMOTE:4,NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL:5,NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE:6,NGHTTP2_STREAM_STATE_CLOSED:7,NGHTTP2_FLAG_NONE:0,NGHTTP2_FLAG_END_STREAM:1,NGHTTP2_FLAG_END_HEADERS:4,NGHTTP2_FLAG_ACK:1,NGHTTP2_FLAG_PADDED:8,NGHTTP2_FLAG_PRIORITY:32,DEFAULT_SETTINGS_HEADER_TABLE_SIZE:4096,DEFAULT_SETTINGS_ENABLE_PUSH:1,DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS:4294967295,DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE:65535,DEFAULT_SETTINGS_MAX_FRAME_SIZE:16384,DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE:65535,DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL:0,MAX_MAX_FRAME_SIZE:16777215,MIN_MAX_FRAME_SIZE:16384,MAX_INITIAL_WINDOW_SIZE:2147483647,NGHTTP2_SETTINGS_HEADER_TABLE_SIZE:1,NGHTTP2_SETTINGS_ENABLE_PUSH:2,NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS:3,NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE:4,NGHTTP2_SETTINGS_MAX_FRAME_SIZE:5,NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE:6,NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL:8,PADDING_STRATEGY_NONE:0,PADDING_STRATEGY_ALIGNED:1,PADDING_STRATEGY_MAX:2,PADDING_STRATEGY_CALLBACK:1,NGHTTP2_NO_ERROR:0,NGHTTP2_PROTOCOL_ERROR:1,NGHTTP2_INTERNAL_ERROR:2,NGHTTP2_FLOW_CONTROL_ERROR:3,NGHTTP2_SETTINGS_TIMEOUT:4,NGHTTP2_STREAM_CLOSED:5,NGHTTP2_FRAME_SIZE_ERROR:6,NGHTTP2_REFUSED_STREAM:7,NGHTTP2_CANCEL:8,NGHTTP2_COMPRESSION_ERROR:9,NGHTTP2_CONNECT_ERROR:10,NGHTTP2_ENHANCE_YOUR_CALM:11,NGHTTP2_INADEQUATE_SECURITY:12,NGHTTP2_HTTP_1_1_REQUIRED:13,NGHTTP2_DEFAULT_WEIGHT:16,HTTP2_HEADER_STATUS:\":status\",HTTP2_HEADER_METHOD:\":method\",HTTP2_HEADER_AUTHORITY:\":authority\",HTTP2_HEADER_SCHEME:\":scheme\",HTTP2_HEADER_PATH:\":path\",HTTP2_HEADER_PROTOCOL:\":protocol\",HTTP2_HEADER_ACCEPT_ENCODING:\"accept-encoding\",HTTP2_HEADER_ACCEPT_LANGUAGE:\"accept-language\",HTTP2_HEADER_ACCEPT_RANGES:\"accept-ranges\",HTTP2_HEADER_ACCEPT:\"accept\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS:\"access-control-allow-credentials\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS:\"access-control-allow-headers\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS:\"access-control-allow-methods\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN:\"access-control-allow-origin\",HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS:\"access-control-expose-headers\",HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS:\"access-control-request-headers\",HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD:\"access-control-request-method\",HTTP2_HEADER_AGE:\"age\",HTTP2_HEADER_AUTHORIZATION:\"authorization\",HTTP2_HEADER_CACHE_CONTROL:\"cache-control\",HTTP2_HEADER_CONNECTION:\"connection\",HTTP2_HEADER_CONTENT_DISPOSITION:\"content-disposition\",HTTP2_HEADER_CONTENT_ENCODING:\"content-encoding\",HTTP2_HEADER_CONTENT_LENGTH:\"content-length\",HTTP2_HEADER_CONTENT_TYPE:\"content-type\",HTTP2_HEADER_COOKIE:\"cookie\",HTTP2_HEADER_DATE:\"date\",HTTP2_HEADER_ETAG:\"etag\",HTTP2_HEADER_FORWARDED:\"forwarded\",HTTP2_HEADER_HOST:\"host\",HTTP2_HEADER_IF_MODIFIED_SINCE:\"if-modified-since\",HTTP2_HEADER_IF_NONE_MATCH:\"if-none-match\",HTTP2_HEADER_IF_RANGE:\"if-range\",HTTP2_HEADER_LAST_MODIFIED:\"last-modified\",HTTP2_HEADER_LINK:\"link\",HTTP2_HEADER_LOCATION:\"location\",HTTP2_HEADER_RANGE:\"range\",HTTP2_HEADER_REFERER:\"referer\",HTTP2_HEADER_SERVER:\"server\",HTTP2_HEADER_SET_COOKIE:\"set-cookie\",HTTP2_HEADER_STRICT_TRANSPORT_SECURITY:\"strict-transport-security\",HTTP2_HEADER_TRANSFER_ENCODING:\"transfer-encoding\",HTTP2_HEADER_TE:\"te\",HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS:\"upgrade-insecure-requests\",HTTP2_HEADER_UPGRADE:\"upgrade\",HTTP2_HEADER_USER_AGENT:\"user-agent\",HTTP2_HEADER_VARY:\"vary\",HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS:\"x-content-type-options\",HTTP2_HEADER_X_FRAME_OPTIONS:\"x-frame-options\",HTTP2_HEADER_KEEP_ALIVE:\"keep-alive\",HTTP2_HEADER_PROXY_CONNECTION:\"proxy-connection\",HTTP2_HEADER_X_XSS_PROTECTION:\"x-xss-protection\",HTTP2_HEADER_ALT_SVC:\"alt-svc\",HTTP2_HEADER_CONTENT_SECURITY_POLICY:\"content-security-policy\",HTTP2_HEADER_EARLY_DATA:\"early-data\",HTTP2_HEADER_EXPECT_CT:\"expect-ct\",HTTP2_HEADER_ORIGIN:\"origin\",HTTP2_HEADER_PURPOSE:\"purpose\",HTTP2_HEADER_TIMING_ALLOW_ORIGIN:\"timing-allow-origin\",HTTP2_HEADER_X_FORWARDED_FOR:\"x-forwarded-for\",HTTP2_HEADER_PRIORITY:\"priority\",HTTP2_HEADER_ACCEPT_CHARSET:\"accept-charset\",HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE:\"access-control-max-age\",HTTP2_HEADER_ALLOW:\"allow\",HTTP2_HEADER_CONTENT_LANGUAGE:\"content-language\",HTTP2_HEADER_CONTENT_LOCATION:\"content-location\",HTTP2_HEADER_CONTENT_MD5:\"content-md5\",HTTP2_HEADER_CONTENT_RANGE:\"content-range\",HTTP2_HEADER_DNT:\"dnt\",HTTP2_HEADER_EXPECT:\"expect\",HTTP2_HEADER_EXPIRES:\"expires\",HTTP2_HEADER_FROM:\"from\",HTTP2_HEADER_IF_MATCH:\"if-match\",HTTP2_HEADER_IF_UNMODIFIED_SINCE:\"if-unmodified-since\",HTTP2_HEADER_MAX_FORWARDS:\"max-forwards\",HTTP2_HEADER_PREFER:\"prefer\",HTTP2_HEADER_PROXY_AUTHENTICATE:\"proxy-authenticate\",HTTP2_HEADER_PROXY_AUTHORIZATION:\"proxy-authorization\",HTTP2_HEADER_REFRESH:\"refresh\",HTTP2_HEADER_RETRY_AFTER:\"retry-after\",HTTP2_HEADER_TRAILER:\"trailer\",HTTP2_HEADER_TK:\"tk\",HTTP2_HEADER_VIA:\"via\",HTTP2_HEADER_WARNING:\"warning\",HTTP2_HEADER_WWW_AUTHENTICATE:\"www-authenticate\",HTTP2_HEADER_HTTP2_SETTINGS:\"http2-settings\",HTTP2_METHOD_ACL:\"ACL\",HTTP2_METHOD_BASELINE_CONTROL:\"BASELINE-CONTROL\",HTTP2_METHOD_BIND:\"BIND\",HTTP2_METHOD_CHECKIN:\"CHECKIN\",HTTP2_METHOD_CHECKOUT:\"CHECKOUT\",HTTP2_METHOD_CONNECT:\"CONNECT\",HTTP2_METHOD_COPY:\"COPY\",HTTP2_METHOD_DELETE:\"DELETE\",HTTP2_METHOD_GET:\"GET\",HTTP2_METHOD_HEAD:\"HEAD\",HTTP2_METHOD_LABEL:\"LABEL\",HTTP2_METHOD_LINK:\"LINK\",HTTP2_METHOD_LOCK:\"LOCK\",HTTP2_METHOD_MERGE:\"MERGE\",HTTP2_METHOD_MKACTIVITY:\"MKACTIVITY\",HTTP2_METHOD_MKCALENDAR:\"MKCALENDAR\",HTTP2_METHOD_MKCOL:\"MKCOL\",HTTP2_METHOD_MKREDIRECTREF:\"MKREDIRECTREF\",HTTP2_METHOD_MKWORKSPACE:\"MKWORKSPACE\",HTTP2_METHOD_MOVE:\"MOVE\",HTTP2_METHOD_OPTIONS:\"OPTIONS\",HTTP2_METHOD_ORDERPATCH:\"ORDERPATCH\",HTTP2_METHOD_PATCH:\"PATCH\",HTTP2_METHOD_POST:\"POST\",HTTP2_METHOD_PRI:\"PRI\",HTTP2_METHOD_PROPFIND:\"PROPFIND\",HTTP2_METHOD_PROPPATCH:\"PROPPATCH\",HTTP2_METHOD_PUT:\"PUT\",HTTP2_METHOD_REBIND:\"REBIND\",HTTP2_METHOD_REPORT:\"REPORT\",HTTP2_METHOD_SEARCH:\"SEARCH\",HTTP2_METHOD_TRACE:\"TRACE\",HTTP2_METHOD_UNBIND:\"UNBIND\",HTTP2_METHOD_UNCHECKOUT:\"UNCHECKOUT\",HTTP2_METHOD_UNLINK:\"UNLINK\",HTTP2_METHOD_UNLOCK:\"UNLOCK\",HTTP2_METHOD_UPDATE:\"UPDATE\",HTTP2_METHOD_UPDATEREDIRECTREF:\"UPDATEREDIRECTREF\",HTTP2_METHOD_VERSION_CONTROL:\"VERSION-CONTROL\",HTTP_STATUS_CONTINUE:100,HTTP_STATUS_SWITCHING_PROTOCOLS:101,HTTP_STATUS_PROCESSING:102,HTTP_STATUS_EARLY_HINTS:103,HTTP_STATUS_OK:200,HTTP_STATUS_CREATED:201,HTTP_STATUS_ACCEPTED:202,HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:203,HTTP_STATUS_NO_CONTENT:204,HTTP_STATUS_RESET_CONTENT:205,HTTP_STATUS_PARTIAL_CONTENT:206,HTTP_STATUS_MULTI_STATUS:207,HTTP_STATUS_ALREADY_REPORTED:208,HTTP_STATUS_IM_USED:226,HTTP_STATUS_MULTIPLE_CHOICES:300,HTTP_STATUS_MOVED_PERMANENTLY:301,HTTP_STATUS_FOUND:302,HTTP_STATUS_SEE_OTHER:303,HTTP_STATUS_NOT_MODIFIED:304,HTTP_STATUS_USE_PROXY:305,HTTP_STATUS_TEMPORARY_REDIRECT:307,HTTP_STATUS_PERMANENT_REDIRECT:308,HTTP_STATUS_BAD_REQUEST:400,HTTP_STATUS_UNAUTHORIZED:401,HTTP_STATUS_PAYMENT_REQUIRED:402,HTTP_STATUS_FORBIDDEN:403,HTTP_STATUS_NOT_FOUND:404,HTTP_STATUS_METHOD_NOT_ALLOWED:405,HTTP_STATUS_NOT_ACCEPTABLE:406,HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:407,HTTP_STATUS_REQUEST_TIMEOUT:408,HTTP_STATUS_CONFLICT:409,HTTP_STATUS_GONE:410,HTTP_STATUS_LENGTH_REQUIRED:411,HTTP_STATUS_PRECONDITION_FAILED:412,HTTP_STATUS_PAYLOAD_TOO_LARGE:413,HTTP_STATUS_URI_TOO_LONG:414,HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:415,HTTP_STATUS_RANGE_NOT_SATISFIABLE:416,HTTP_STATUS_EXPECTATION_FAILED:417,HTTP_STATUS_TEAPOT:418,HTTP_STATUS_MISDIRECTED_REQUEST:421,HTTP_STATUS_UNPROCESSABLE_ENTITY:422,HTTP_STATUS_LOCKED:423,HTTP_STATUS_FAILED_DEPENDENCY:424,HTTP_STATUS_TOO_EARLY:425,HTTP_STATUS_UPGRADE_REQUIRED:426,HTTP_STATUS_PRECONDITION_REQUIRED:428,HTTP_STATUS_TOO_MANY_REQUESTS:429,HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:431,HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:451,HTTP_STATUS_INTERNAL_SERVER_ERROR:500,HTTP_STATUS_NOT_IMPLEMENTED:501,HTTP_STATUS_BAD_GATEWAY:502,HTTP_STATUS_SERVICE_UNAVAILABLE:503,HTTP_STATUS_GATEWAY_TIMEOUT:504,HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:505,HTTP_STATUS_VARIANT_ALSO_NEGOTIATES:506,HTTP_STATUS_INSUFFICIENT_STORAGE:507,HTTP_STATUS_LOOP_DETECTED:508,HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED:509,HTTP_STATUS_NOT_EXTENDED:510,HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:511};function createServer(){throwNotImplemented(\"node:http2 createServer\",887)}function createSecureServer(){throwNotImplemented(\"node:http2 createSecureServer\",887)}function getDefaultSettings(){return{headerTableSize:4096,enablePush:!0,initialWindowSize:65535,maxFrameSize:16384,maxConcurrentStreams:4294967295,maxHeaderSize:65535,maxHeaderListSize:65535,enableConnectProtocol:!1}}function getPackedSettings(){return Buffer.alloc(0)}function getUnpackedSettings(){return Buffer.alloc(0)}const sensitiveHeaders=Symbol.for(\"nodejs.http2.sensitiveHeaders\");function Http2ServerRequest(){throwNotImplemented(\"node:http2 Http2ServerRequest\",887)}function Http2ServerResponse(){throwNotImplemented(\"node:http2 Http2ServerResponse\",887)}return $={constants,createServer,createSecureServer,getDefaultSettings,getPackedSettings,getUnpackedSettings,sensitiveHeaders,Http2ServerRequest,Http2ServerResponse,connect},hideFromStack([Http2ServerRequest,Http2ServerResponse,connect,createServer,createSecureServer,getDefaultSettings,getPackedSettings,getUnpackedSettings]),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttpsCode = "(function (){\"use strict\";const http=@getInternalField(@internalModuleRegistry,18)||@createInternalModuleById(18);function request(input,options,cb){if(input&&typeof input===\"object\"&&!(input instanceof URL))input.protocol\?\?=\"https:\";else if(typeof options===\"object\")options.protocol\?\?=\"https:\";return http.request(input,options,cb)}function get(input,options,cb){const req=request(input,options,cb);return req.end(),req}return{...http,get,request}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeInspectorCode = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15);function open(){throwNotImplemented(\"node:inspector open\",2445)}function close(){throwNotImplemented(\"node:inspector close\",2445)}function url(){throwNotImplemented(\"node:inspector url\",2445)}function waitForDebugger(){throwNotImplemented(\"node:inspector waitForDebugger\",2445)}class Session extends EventEmitter{constructor(){super();throwNotImplemented(\"node:inspector Session\",2445)}}return $={console:{...globalThis.console,context:{console:globalThis.console}},open,close,url,waitForDebugger,Session},hideFromStack(open,close,url,waitForDebugger,Session.prototype.constructor),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeNetCode = "(function (){\"use strict\";const{Duplex}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),IPv4Reg=new RegExp(\"^((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$\"),IPv6Reg=new RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\");function isIPv4(s){return IPv4Reg.test(s)}function isIPv6(s){return IPv6Reg.test(s)}function isIP(s){if(isIPv4(s))return 4;if(isIPv6(s))return 6;return 0}const{connect:bunConnect}=Bun;var{setTimeout}=globalThis;const bunTlsSymbol=Symbol.for(\"::buntls::\"),bunSocketServerHandlers=Symbol.for(\"::bunsocket_serverhandlers::\"),bunSocketServerConnections=Symbol.for(\"::bunnetserverconnections::\"),bunSocketServerOptions=Symbol.for(\"::bunnetserveroptions::\"),bunSocketInternal=Symbol.for(\"::bunnetsocketinternal::\"),bunTLSConnectOptions=Symbol.for(\"::buntlsconnectoptions::\");var SocketClass;const Socket=function(InternalSocket){return SocketClass=InternalSocket,Object.defineProperty(SocketClass.prototype,Symbol.toStringTag,{value:\"Socket\",enumerable:!1}),Object.defineProperty(function Socket(options){return new InternalSocket(options)},Symbol.hasInstance,{value(instance){return instance instanceof InternalSocket}})}(class Socket2 extends Duplex{static#Handlers={close:Socket2.#Close,connectError(socket,error){socket.data.emit(\"error\",error)},data({data:self},buffer){self.bytesRead+=buffer.length;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(buffer))return}queue.push(buffer)},drain:Socket2.#Drain,end:Socket2.#Close,error(socket,error){const self=socket.data,callback=self.#writeCallback;if(callback)self.#writeCallback=null,callback(error);self.emit(\"error\",error)},open(socket){const self=socket.data;socket.timeout(self.timeout),socket.ref(),self[bunSocketInternal]=socket,self.connecting=!1;const options=self[bunTLSConnectOptions];if(options){const{session}=options;if(session)self.setSession(session)}if(!self.#upgraded)self.emit(\"connect\",self);Socket2.#Drain(socket)},handshake(socket,success,verifyError){const{data:self}=socket;self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self.emit(\"secure\",self);const{checkServerIdentity}=self[bunTLSConnectOptions];if(!verifyError&&typeof checkServerIdentity===\"function\"&&self.servername){const cert=self.getPeerCertificate(!0);verifyError=checkServerIdentity(self.servername,cert)}if(self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit(\"secureConnect\",verifyError)},timeout(socket){const self=socket.data;self.emit(\"timeout\",self)},binaryType:\"buffer\"};static#Close(socket){const self=socket.data;if(self.#closed)return;self.#closed=!0,self[bunSocketInternal]=null;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(null))return}queue.push(null)}static#Drain(socket){const self=socket.data,callback=self.#writeCallback;if(callback){const chunk=self.#writeChunk,written=socket.write(chunk);if(self.bytesWritten+=written,written=self.maxConnections){const data={localAddress:_socket.localAddress,localPort:_socket.localPort,localFamily:_socket.localFamily,remoteAddress:_socket.remoteAddress,remotePort:_socket.remotePort,remoteFamily:_socket.remoteFamily||\"IPv4\"};socket.end(),self.emit(\"drop\",data);return}if(!pauseOnConnect)_socket.resume();if(self[bunSocketServerConnections]++,typeof connectionListener==\"function\")if(InternalSocketClass.name===\"TLSSocket\")self.once(\"secureConnection\",()=>connectionListener(_socket));else connectionListener(_socket);self.emit(\"connection\",_socket)},handshake(socket,success,verifyError){const{data:self}=socket;if(self.emit(\"secure\",self),self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit(\"secureConnection\",verifyError)},error(socket,error){Socket2.#Handlers.error(socket,error),this.data.emit(\"error\",error)},timeout:Socket2.#Handlers.timeout,connectError:Socket2.#Handlers.connectError,drain:Socket2.#Handlers.drain,binaryType:\"buffer\"};bytesRead=0;bytesWritten=0;#closed=!1;connecting=!1;localAddress=\"127.0.0.1\";#readQueue=@createFIFO();remotePort;[bunSocketInternal]=null;[bunTLSConnectOptions]=null;timeout=0;#writeCallback;#writeChunk;#pendingRead;isServer=!1;_handle;_parent;_parentWrap;#socket;#upgraded;constructor(options){const{socket,signal,write,read,allowHalfOpen=!1,...opts}=options||{};super({...opts,allowHalfOpen,readable:!0,writable:!0});if(this._handle=this,this._parent=this,this._parentWrap=this,this.#pendingRead=void 0,this.#upgraded=!1,socket instanceof Socket2)this.#socket=socket;signal\?.once(\"abort\",()=>this.destroy()),this.once(\"connect\",()=>this.emit(\"ready\"))}address(){return{address:this.localAddress,family:this.localFamily,port:this.localPort}}get bufferSize(){return this.writableLength}#attach(port,socket){if(this.remotePort=port,socket.data=this,socket.timeout(this.timeout),socket.ref(),this[bunSocketInternal]=socket,this.connecting=!1,!this.#upgraded)this.emit(\"connect\",this);Socket2.#Drain(socket)}connect(port,host,connectListener){var path,connection=this.#socket,_checkServerIdentity=void 0;if(typeof port===\"string\"){if(path=port,port=void 0,typeof host===\"function\")connectListener=host,host=void 0}else if(typeof host==\"function\"){if(typeof port===\"string\")path=port,port=void 0;connectListener=host,host=void 0}if(typeof port==\"object\"){var{port,host,path,socket,localAddress,localPort,family,hints,lookup,noDelay,keepAlive,keepAliveInitialDelay,requestCert,rejectUnauthorized,pauseOnConnect,servername,checkServerIdentity,session}=port;if(_checkServerIdentity=checkServerIdentity,this.servername=servername,socket)connection=socket}if(!pauseOnConnect)this.resume();this.connecting=!0,this.remotePort=port;const bunTLS=this[bunTlsSymbol];var tls=void 0;if(typeof bunTLS===\"function\"){if(tls=bunTLS.call(this,port,host,!0),this._requestCert=!0,this._rejectUnauthorized=rejectUnauthorized,tls){if(tls.rejectUnauthorized=rejectUnauthorized,tls.requestCert=!0,tls.session=session||tls.session,this.servername=tls.servername,tls.checkServerIdentity=_checkServerIdentity||tls.checkServerIdentity,this[bunTLSConnectOptions]=tls,!connection&&tls.socket)connection=tls.socket}if(connection){if(typeof connection!==\"object\"||!(connection instanceof Socket2)||typeof connection[bunTlsSymbol]===\"function\")@throwTypeError(\"socket must be an instance of net.Socket\")}if(this.authorized=!1,this.secureConnecting=!0,this._secureEstablished=!1,this._securePending=!0,connectListener)this.on(\"secureConnect\",connectListener)}else if(connectListener)this.on(\"connect\",connectListener);if(connection){const socket2=connection[bunSocketInternal];if(socket2){this.connecting=!0,this.#upgraded=!0;const result=socket2.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error(\"Invalid socket\")}else connection.once(\"connect\",()=>{const socket3=connection[bunSocketInternal];if(!socket3)return;this.connecting=!0,this.#upgraded=!0;const result=socket3.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error(\"Invalid socket\")})}else if(path)bunConnect({data:this,unix:path,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit(\"error\",error)});else bunConnect({data:this,hostname:host||\"localhost\",port,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit(\"error\",error)});return this}_destroy(err,callback){this[bunSocketInternal]\?.end(),callback(err)}_final(callback){this[bunSocketInternal]\?.end(),callback()}get localAddress(){return\"127.0.0.1\"}get localFamily(){return\"IPv4\"}get localPort(){return this[bunSocketInternal]\?.localPort}get pending(){return this.connecting}_read(size){const queue=this.#readQueue;let chunk;while(chunk=queue.peek()){if(!this.push(chunk))return;queue.shift()}}get readyState(){if(this.connecting)return\"opening\";if(this.readable)return this.writable\?\"open\":\"readOnly\";else return this.writable\?\"writeOnly\":\"closed\"}ref(){this[bunSocketInternal]\?.ref()}get remoteAddress(){return this[bunSocketInternal]\?.remoteAddress}get remoteFamily(){return\"IPv4\"}resetAndDestroy(){this[bunSocketInternal]\?.end()}setKeepAlive(enable=!1,initialDelay=0){return this}setNoDelay(noDelay=!0){return this}setTimeout(timeout,callback){if(this[bunSocketInternal]\?.timeout(timeout),this.timeout=timeout,callback)this.once(\"timeout\",callback);return this}unref(){this[bunSocketInternal]\?.unref()}_write(chunk,encoding,callback){if(typeof chunk==\"string\"&&encoding!==\"ascii\")chunk=Buffer.from(chunk,encoding);var written=this[bunSocketInternal]\?.write(chunk);if(written==chunk.length)callback();else if(this.#writeCallback)callback(new Error(\"overlapping _write()\"));else{if(written>0)if(typeof chunk==\"string\")chunk=chunk.slice(written);else chunk=chunk.subarray(written);this.#writeCallback=callback,this.#writeChunk=chunk}}});function createConnection(port,host,connectListener){if(typeof port===\"object\")return new Socket(port).connect(port,host,connectListener);return new Socket().connect(port,host,connectListener)}const connect=createConnection;class Server extends EventEmitter{#server;#listening=!1;[bunSocketServerConnections]=0;[bunSocketServerOptions];maxConnections=0;constructor(options,connectionListener){super();if(typeof options===\"function\")connectionListener=options,options={};else if(options==null||typeof options===\"object\")options={...options};else throw new Error(\"bun-net-polyfill: invalid arguments\");const{maxConnections}=options;this.maxConnections=Number.isSafeInteger(maxConnections)&&maxConnections>0\?maxConnections:0,options.connectionListener=connectionListener,this[bunSocketServerOptions]=options}ref(){return this.#server\?.ref(),this}unref(){return this.#server\?.unref(),this}close(callback){if(this.#server){if(this.#server.stop(!0),this.#server=null,this.#listening=!1,this[bunSocketServerConnections]=0,this.emit(\"close\"),typeof callback===\"function\")callback();return this}if(typeof callback===\"function\"){const error=new Error(\"Server is not running\");error.code=\"ERR_SERVER_NOT_RUNNING\",callback(error)}return this}address(){const server=this.#server;if(server){const unix=server.unix;if(unix)return unix;let address=server.hostname;const type=isIP(address),port=server.port;if(typeof port===\"number\")return{port,address,family:type\?`IPv${type}`:void 0};if(type)return{address,family:type\?`IPv${type}`:void 0};return address}return null}getConnections(callback){if(typeof callback===\"function\")callback(null,this.#server\?this[bunSocketServerConnections]:0);return this}listen(port,hostname,onListen){let backlog,path,exclusive=!1;if(typeof port===\"string\"){if(Number.isSafeInteger(hostname)){if(hostname>0)backlog=hostname}else if(typeof hostname===\"function\")onListen=hostname;path=port,hostname=void 0,port=void 0}else{if(typeof hostname===\"function\")onListen=hostname,hostname=void 0;if(typeof port===\"function\")onListen=port,port=0;else if(typeof port===\"object\"){const options=port;options.signal\?.addEventListener(\"abort\",()=>this.close()),hostname=options.host,exclusive=options.exclusive===!0;const path2=options.path;if(port=options.port,!Number.isSafeInteger(port)||port<0)if(path2)hostname=path2,port=void 0;else{let message='The argument \\'options\\' must have the property \"port\" or \"path\"';try{message=`${message}. Received ${JSON.stringify(options)}`}catch{}const error=@makeTypeError(message);throw error.code=\"ERR_INVALID_ARG_VALUE\",error}else if(!Number.isSafeInteger(port)||port<0)port=0;if(typeof port.callback===\"function\")onListen=port\?.callback}else if(!Number.isSafeInteger(port)||port<0)port=0;hostname=hostname||\"::\"}try{var tls=void 0,TLSSocketClass=void 0;const bunTLS=this[bunTlsSymbol],options=this[bunSocketServerOptions];if(typeof bunTLS===\"function\")[tls,TLSSocketClass]=bunTLS.call(this,port,hostname,!1),options.servername=tls.serverName,options.InternalSocketClass=TLSSocketClass;else options.InternalSocketClass=SocketClass;this.#server=Bun.listen(path\?{exclusive,unix:path,tls,socket:SocketClass[bunSocketServerHandlers]}:{exclusive,port,hostname,tls,socket:SocketClass[bunSocketServerHandlers]}),this.#server.data=this,this.#listening=!0,setTimeout(emitListeningNextTick,1,this,onListen)}catch(err){this.#listening=!1,setTimeout(emitErrorNextTick,1,this,err)}return this}}function emitErrorNextTick(self,error){self.emit(\"error\",error)}function emitListeningNextTick(self,onListen){if(typeof onListen===\"function\")try{onListen()}catch(err){self.emit(\"error\",err)}self.emit(\"listening\")}function createServer(options,connectionListener){return new Server(options,connectionListener)}return{createServer,Server,createConnection,connect,isIP,isIPv4,isIPv6,Socket,[Symbol.for(\"::bunternal::\")]:SocketClass}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeOSCode = "(function (){\"use strict\";var tmpdir=function(){var env=Bun.env;return tmpdir=function(){var path=env.TMPDIR||env.TMP||env.TEMP||\"/tmp\";const length=path.length;if(length>1&&path[length-1]===\"/\")path=path.slice(0,-1);return path},tmpdir()};function lazyCpus({cpus}){return()=>{const array=new Array(navigator.hardwareConcurrency);function populate(){const results=cpus(),length=results.length;array.length=length;for(let i=0;i= 0x80 (not a basic code point)\",\"invalid-input\":\"Invalid input\"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;function error(type){@throwRangeError(errors[type])}function map(array,callback){const result=[];let length=array.length;while(length--)result[length]=callback(array[length]);return result}function mapDomain(domain,callback){const parts=domain.split(\"@\");let result=\"\";if(parts.length>1)result=parts[0]+\"@\",domain=parts[1];domain=domain.replace(regexSeparators,\".\");const labels=domain.split(\".\"),encoded=map(labels,callback).join(\".\");return result+encoded}function ucs2decode(string){const output=[];let counter=0;const length=string.length;while(counter=55296&&value<=56319&&counterString.fromCodePoint(...codePoints),basicToDigit=function(codePoint){if(codePoint>=48&&codePoint<58)return 26+(codePoint-48);if(codePoint>=65&&codePoint<91)return codePoint-65;if(codePoint>=97&&codePoint<123)return codePoint-97;return base},digitToBasic=function(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)},adapt=function(delta,numPoints,firstTime){let k=0;delta=firstTime\?floor(delta/damp):delta>>1,delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base)delta=floor(delta/baseMinusTMin);return floor(k+(baseMinusTMin+1)*delta/(delta+skew))},decode=function(input){const output=[],inputLength=input.length;let i=0,n=initialN,bias=initialBias,basic=input.lastIndexOf(delimiter);if(basic<0)basic=0;for(let j=0;j=128)error(\"not-basic\");output.push(input.charCodeAt(j))}for(let index=basic>0\?basic+1:0;index=inputLength)error(\"invalid-input\");const digit=basicToDigit(input.charCodeAt(index++));if(digit>=base)error(\"invalid-input\");if(digit>floor((maxInt-i)/w))error(\"overflow\");i+=digit*w;const t=k<=bias\?tMin:k>=bias+tMax\?tMax:k-bias;if(digitfloor(maxInt/baseMinusT))error(\"overflow\");w*=baseMinusT}const out=output.length+1;if(bias=adapt(i-oldi,out,oldi==0),floor(i/out)>maxInt-n)error(\"overflow\");n+=floor(i/out),i%=out,output.splice(i++,0,n)}return String.fromCodePoint(...output)},encode=function(input){const output=[];input=ucs2decode(input);const inputLength=input.length;let n=initialN,delta=0,bias=initialBias;for(let currentValue of input)if(currentValue<128)output.push(stringFromCharCode(currentValue));const basicLength=output.length;let handledCPCount=basicLength;if(basicLength)output.push(delimiter);while(handledCPCount=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne))error(\"overflow\");delta+=(m-n)*handledCPCountPlusOne,n=m;for(let currentValue of input){if(currentValuemaxInt)error(\"overflow\");if(currentValue===n){let q=delta;for(let k=base;;k+=base){const t=k<=bias\?tMin:k>=bias+tMax\?tMax:k-bias;if(q()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),Buffer=@requireNativeModule(\"node:buffer\").Buffer,require_object_keys=__commonJS((exports,module)=>{var objectKeys=Object.keys||function(){var hasOwnProperty=Object.prototype.hasOwnProperty,hasDontEnumBug=!{toString:null}.propertyIsEnumerable(\"toString\"),dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;return function(obj){if(typeof obj!==\"function\"&&(typeof obj!==\"object\"||obj===null))@throwTypeError(\"Object.keys called on non-object\");var result=[],prop,i;for(prop in obj)if(hasOwnProperty.call(obj,prop))result.push(prop);if(hasDontEnumBug){for(i=0;i{var ParsedQueryString=function(){},unescapeBuffer=function(s,decodeSpaces){var out=Buffer.allocUnsafe(s.length),state=0,n,m,hexchar,c;for(var inIndex=0,outIndex=0;;inIndex++){if(inIndex0){if(out[outIndex++]=37,state===2)out[outIndex++]=hexchar}break}switch(state){case 0:switch(c){case 37:n=0,m=0,state=1;break;case 43:if(decodeSpaces)c=32;default:out[outIndex++]=c;break}break;case 1:if(hexchar=c,n=unhexTable[c],!(n>=0)){out[outIndex++]=37,out[outIndex++]=c,state=0;break}state=2;break;case 2:if(state=0,m=unhexTable[c],!(m>=0)){out[outIndex++]=37,out[outIndex++]=hexchar,out[outIndex++]=c;break}out[outIndex++]=16*n+m;break}}return out.slice(0,outIndex)},qsUnescape=function(s,decodeSpaces){try{return decodeURIComponent(s)}catch(e){return QueryString.unescapeBuffer(s,decodeSpaces).toString()}},qsEscape=function(str){if(typeof str!==\"string\")if(typeof str===\"object\")str=String(str);else str+=\"\";var out=\"\",lastPos=0;for(var i2=0;i2>6]+hexTable[128|c&63];continue}if(c<55296||c>=57344){lastPos=i2+1,out+=hexTable[224|c>>12]+hexTable[128|c>>6&63]+hexTable[128|c&63];continue}++i2;var c2;if(i2>18]+hexTable[128|c>>12&63]+hexTable[128|c>>6&63]+hexTable[128|c&63]}if(lastPos===0)return str;if(lastPos0\?options.maxKeys:-1;var decode=QueryString.unescape;if(options&&typeof options.decodeURIComponent===\"function\")decode=options.decodeURIComponent;const customDecode=decode!==qsUnescape,keys=[];var posIdx=0,lastPos=0,sepIdx=0,eqIdx=0,key=\"\",value=\"\",keyEncoded=customDecode,valEncoded=customDecode,encodeCheck=0;for(var i2=0;i2sepLen||i2===0)if(indexOf(keys,key)===-1)obj[key]=value,keys[keys.length]=key;else{const curValue=obj[key]||\"\";if(curValue.pop)curValue[curValue.length]=value;else if(curValue)obj[key]=[curValue,value]}else if(i2===1)delete obj[key];if(--pairs===0)break;keyEncoded=valEncoded=customDecode,encodeCheck=0,key=value=\"\",posIdx=lastPos,lastPos=i2+1,sepIdx=eqIdx=0}continue}else if(sepIdx=0,!valEncoded)if(code===37)encodeCheck=1;else if(encodeCheck>0&&(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){if(++encodeCheck===3)valEncoded=!0}else encodeCheck=0;if(eqIdx0&&(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){if(++encodeCheck===3)keyEncoded=!0}else encodeCheck=0}if(code===43){if(eqIdx0)){if(lastPosObject.prototype.toString.call(arg)===\"[object Array]\",indexOf=(arr,searchElement,fromIndex)=>{var k;if(arr==null)@throwTypeError('\"arr\" is null or not defined');var o=Object(arr),len=o.length>>>0;if(len===0)return-1;var n=fromIndex|0;if(n>=len)return-1;k=Math.max(n>=0\?n:len-Math.abs(n),0);while(k{},SymbolAsyncIterator=Symbol.asyncIterator,SymbolIterator=Symbol.iterator,SymbolFor=Symbol.for,SymbolReplace=Symbol.replace,ArrayFrom=Array.from,ArrayIsArray=Array.isArray,ArrayPrototypeFilter=Array.prototype.filter,ArrayPrototypeSort=Array.prototype.sort,ArrayPrototypeIndexOf=Array.prototype.indexOf,ArrayPrototypeJoin=Array.prototype.join,ArrayPrototypeMap=Array.prototype.map,ArrayPrototypePop=Array.prototype.pop,ArrayPrototypePush=Array.prototype.push,ArrayPrototypeSlice=Array.prototype.slice,ArrayPrototypeSplice=Array.prototype.splice,ArrayPrototypeReverse=Array.prototype.reverse,ArrayPrototypeShift=Array.prototype.shift,ArrayPrototypeUnshift=Array.prototype.unshift,RegExpPrototypeExec=RegExp.prototype.exec,RegExpPrototypeSymbolReplace=RegExp.prototype[SymbolReplace],StringFromCharCode=String.fromCharCode,StringPrototypeCharCodeAt=String.prototype.charCodeAt,StringPrototypeCodePointAt=String.prototype.codePointAt,StringPrototypeSlice=String.prototype.slice,StringPrototypeToLowerCase=String.prototype.toLowerCase,StringPrototypeEndsWith=String.prototype.endsWith,StringPrototypeRepeat=String.prototype.repeat,StringPrototypeStartsWith=String.prototype.startsWith,StringPrototypeTrim=String.prototype.trim,StringPrototypeNormalize=String.prototype.normalize,NumberIsNaN=Number.isNaN,NumberIsFinite=Number.isFinite,NumberIsInteger=Number.isInteger,NumberMAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER=Number.MIN_SAFE_INTEGER,MathCeil=Math.ceil,MathFloor=Math.floor,MathMax=Math.max,MathMaxApply=Math.max.apply,DateNow=Date.now,FunctionPrototype=Function.prototype,StringPrototype=String.prototype,StringPrototypeSymbolIterator=StringPrototype[SymbolIterator],StringIteratorPrototypeNext=StringPrototypeSymbolIterator.call(\"\").next,ObjectSetPrototypeOf=Object.setPrototypeOf,ObjectDefineProperty=Object.defineProperty,ObjectDefineProperties=Object.defineProperties,ObjectFreeze=Object.freeze,ObjectAssign=Object.assign,ObjectCreate=Object.create,ObjectKeys=Object.keys,ObjectSeal=Object.seal,createSafeIterator=(factory,next)=>{class SafeIterator{#iterator;constructor(iterable){this.#iterator=factory.call(iterable)}next(){return next.call(this.#iterator)}[SymbolIterator](){return this}}return ObjectSetPrototypeOf(SafeIterator.prototype,null),ObjectFreeze(SafeIterator.prototype),ObjectFreeze(SafeIterator),SafeIterator},SafeStringIterator=createSafeIterator(StringPrototypeSymbolIterator,StringIteratorPrototypeNext),isFullWidthCodePoint=(code)=>{return code>=4352&&(code<=4447||code===9001||code===9002||code>=11904&&code<=12871&&code!==12351||code>=12880&&code<=19903||code>=19968&&code<=42182||code>=43360&&code<=43388||code>=44032&&code<=55203||code>=63744&&code<=64255||code>=65040&&code<=65049||code>=65072&&code<=65131||code>=65281&&code<=65376||code>=65504&&code<=65510||code>=110592&&code<=110593||code>=127488&&code<=127569||code>=127744&&code<=128591||code>=131072&&code<=262141)},isZeroWidthCodePoint=(code)=>{return code<=31||code>=127&&code<=159||code>=768&&code<=879||code>=8203&&code<=8207||code>=8400&&code<=8447||code>=65024&&code<=65039||code>=65056&&code<=65071||code>=917760&&code<=917999},getStringWidth=function getStringWidth(str,removeControlChars=!0){var width=0;if(removeControlChars)str=stripVTControlCharacters(str);str=StringPrototypeNormalize.call(str,\"NFC\");for(var char of new SafeStringIterator(str)){var code=StringPrototypeCodePointAt.call(char,0);if(isFullWidthCodePoint(code))width+=2;else if(!isZeroWidthCodePoint(code))width++}return width},ansiPattern=\"[\\\\u001B\\\\u009B][[\\\\]()#;\?]*(\?:(\?:(\?:(\?:;[-a-zA-Z\\\\d\\\\/#&.:=\?%@~_]+)*|[a-zA-Z\\\\d]+(\?:;[-a-zA-Z\\\\d\\\\/#&.:=\?%@~_]*)*)\?\\\\u0007)|(\?:(\?:\\\\d{1,4}(\?:;\\\\d{0,4})*)\?[\\\\dA-PR-TZcf-ntqry=><~]))\",ansi=new RegExp(ansiPattern,\"g\");function stripVTControlCharacters(str){return validateString(str,\"str\"),RegExpPrototypeSymbolReplace.call(ansi,str,\"\")}var kCustomPromisifiedSymbol=SymbolFor(\"nodejs.util.promisify.custom\"),kCustomPromisifyArgsSymbol=Symbol(\"customPromisifyArgs\");function promisify(original){if(validateFunction(original,\"original\"),original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];return validateFunction(fn,\"util.promisify.custom\"),ObjectDefineProperty(fn,kCustomPromisifiedSymbol,{__proto__:null,value:fn,enumerable:!1,writable:!1,configurable:!0})}var argumentNames=original[kCustomPromisifyArgsSymbol];function fn(...args){return new Promise((resolve,reject)=>{ArrayPrototypePush.call(args,(err,...values)=>{if(err)return reject(err);if(argumentNames!==void 0&&values.length>1){var obj={};for(var i2=0;i2max)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}function validateUint32(value,name,positive=!1){if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE(name,\"number\",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);var min=positive\?1:0,max=4294967295;if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}function CSI(strings,...args){var ret=`${kEscape}[`;for(var n=0;n1&&StringPrototypeCodePointAt.call(str,i-2)>=kUTF16SurrogateThreshold||StringPrototypeCodePointAt.call(str,i-1)>=kUTF16SurrogateThreshold)return 2;return 1}function charLengthAt(str,i){if(str.length<=i)return 1;return StringPrototypeCodePointAt.call(str,i)>=kUTF16SurrogateThreshold\?2:1}function*emitKeys(stream){while(!0){var ch=yield,s=ch,escaped=!1,keySeq=null,keyName,keyCtrl2=!1,keyMeta=!1,keyShift=!1;if(ch===kEscape){if(escaped=!0,s+=ch=yield,ch===kEscape)s+=ch=yield}if(escaped&&(ch===\"O\"||ch===\"[\")){var code=ch,modifier=0;if(ch===\"O\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")modifier=(ch>>0)-1,s+=ch=yield;code+=ch}else if(ch===\"[\"){if(s+=ch=yield,ch===\"[\")code+=ch,s+=ch=yield;var cmdStart=s.length-1;if(ch>=\"0\"&&ch<=\"9\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")s+=ch=yield}if(ch===\";\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")s+=yield}var cmd=StringPrototypeSlice.call(s,cmdStart),match;if(match=RegExpPrototypeExec.call(/^(\\d\\d\?)(;(\\d))\?([~^$])$/,cmd))code+=match[1]+match[4],modifier=(match[3]||1)-1;else if(match=RegExpPrototypeExec.call(/^((\\d;)\?(\\d))\?([A-Za-z])$/,cmd))code+=match[4],modifier=(match[3]||1)-1;else code+=cmd}switch(keyCtrl2=!!(modifier&4),keyMeta=!!(modifier&10),keyShift=!!(modifier&1),code){case\"[P\":keyName=\"f1\";break;case\"[Q\":keyName=\"f2\";break;case\"[R\":keyName=\"f3\";break;case\"[S\":keyName=\"f4\";break;case\"OP\":keyName=\"f1\";break;case\"OQ\":keyName=\"f2\";break;case\"OR\":keyName=\"f3\";break;case\"OS\":keyName=\"f4\";break;case\"[11~\":keyName=\"f1\";break;case\"[12~\":keyName=\"f2\";break;case\"[13~\":keyName=\"f3\";break;case\"[14~\":keyName=\"f4\";break;case\"[[A\":keyName=\"f1\";break;case\"[[B\":keyName=\"f2\";break;case\"[[C\":keyName=\"f3\";break;case\"[[D\":keyName=\"f4\";break;case\"[[E\":keyName=\"f5\";break;case\"[15~\":keyName=\"f5\";break;case\"[17~\":keyName=\"f6\";break;case\"[18~\":keyName=\"f7\";break;case\"[19~\":keyName=\"f8\";break;case\"[20~\":keyName=\"f9\";break;case\"[21~\":keyName=\"f10\";break;case\"[23~\":keyName=\"f11\";break;case\"[24~\":keyName=\"f12\";break;case\"[A\":keyName=\"up\";break;case\"[B\":keyName=\"down\";break;case\"[C\":keyName=\"right\";break;case\"[D\":keyName=\"left\";break;case\"[E\":keyName=\"clear\";break;case\"[F\":keyName=\"end\";break;case\"[H\":keyName=\"home\";break;case\"OA\":keyName=\"up\";break;case\"OB\":keyName=\"down\";break;case\"OC\":keyName=\"right\";break;case\"OD\":keyName=\"left\";break;case\"OE\":keyName=\"clear\";break;case\"OF\":keyName=\"end\";break;case\"OH\":keyName=\"home\";break;case\"[1~\":keyName=\"home\";break;case\"[2~\":keyName=\"insert\";break;case\"[3~\":keyName=\"delete\";break;case\"[4~\":keyName=\"end\";break;case\"[5~\":keyName=\"pageup\";break;case\"[6~\":keyName=\"pagedown\";break;case\"[[5~\":keyName=\"pageup\";break;case\"[[6~\":keyName=\"pagedown\";break;case\"[7~\":keyName=\"home\";break;case\"[8~\":keyName=\"end\";break;case\"[a\":keyName=\"up\",keyShift=!0;break;case\"[b\":keyName=\"down\",keyShift=!0;break;case\"[c\":keyName=\"right\",keyShift=!0;break;case\"[d\":keyName=\"left\",keyShift=!0;break;case\"[e\":keyName=\"clear\",keyShift=!0;break;case\"[2$\":keyName=\"insert\",keyShift=!0;break;case\"[3$\":keyName=\"delete\",keyShift=!0;break;case\"[5$\":keyName=\"pageup\",keyShift=!0;break;case\"[6$\":keyName=\"pagedown\",keyShift=!0;break;case\"[7$\":keyName=\"home\",keyShift=!0;break;case\"[8$\":keyName=\"end\",keyShift=!0;break;case\"Oa\":keyName=\"up\",keyCtrl2=!0;break;case\"Ob\":keyName=\"down\",keyCtrl2=!0;break;case\"Oc\":keyName=\"right\",keyCtrl2=!0;break;case\"Od\":keyName=\"left\",keyCtrl2=!0;break;case\"Oe\":keyName=\"clear\",keyCtrl2=!0;break;case\"[2^\":keyName=\"insert\",keyCtrl2=!0;break;case\"[3^\":keyName=\"delete\",keyCtrl2=!0;break;case\"[5^\":keyName=\"pageup\",keyCtrl2=!0;break;case\"[6^\":keyName=\"pagedown\",keyCtrl2=!0;break;case\"[7^\":keyName=\"home\",keyCtrl2=!0;break;case\"[8^\":keyName=\"end\",keyCtrl2=!0;break;case\"[Z\":keyName=\"tab\",keyShift=!0;break;default:keyName=\"undefined\";break}}else if(ch===\"\\r\")keyName=\"return\",keyMeta=escaped;else if(ch===\"\\n\")keyName=\"enter\",keyMeta=escaped;else if(ch===\"\\t\")keyName=\"tab\",keyMeta=escaped;else if(ch===\"\\b\"||ch===\"\\x7F\")keyName=\"backspace\",keyMeta=escaped;else if(ch===kEscape)keyName=\"escape\",keyMeta=escaped;else if(ch===\" \")keyName=\"space\",keyMeta=escaped;else if(!escaped&&ch<=\"\\x1A\")keyName=StringFromCharCode(StringPrototypeCharCodeAt.call(ch)+StringPrototypeCharCodeAt.call(\"a\")-1),keyCtrl2=!0;else if(RegExpPrototypeExec.call(/^[0-9A-Za-z]$/,ch)!==null)keyName=StringPrototypeToLowerCase.call(ch),keyShift=RegExpPrototypeExec.call(/^[A-Z]$/,ch)!==null,keyMeta=escaped;else if(escaped)keyName=ch.length\?void 0:\"escape\",keyMeta=!0;if(keySeq=s,s.length!==0&&(keyName!==void 0||escaped))stream.emit(\"keypress\",escaped\?void 0:s,{sequence:keySeq,name:keyName,ctrl:keyCtrl2,meta:keyMeta,shift:keyShift});else if(charLengthAt(s,0)===s.length)stream.emit(\"keypress\",s,{sequence:keySeq,name:keyName,ctrl:keyCtrl2,meta:keyMeta,shift:keyShift})}}function commonPrefix(strings){if(strings.length===0)return\"\";if(strings.length===1)return strings[0];var sorted=ArrayPrototypeSort.call(ArrayPrototypeSlice.call(strings)),min=sorted[0],max=sorted[sorted.length-1];for(var i=0;i0)data+=CSI`${dx}C`;if(dy<0)data+=CSI`${-dy}A`;else if(dy>0)data+=CSI`${dy}B`;return stream.write(data,callback)}function clearLine(stream,dir,callback){if(callback!==void 0)validateFunction(callback,\"callback\");if(stream===null||stream===void 0){if(typeof callback===\"function\")process.nextTick(callback,null);return!0}var type=dir<0\?kClearToLineBeginning:dir>0\?kClearToLineEnd:kClearLine;return stream.write(type,callback)}function clearScreenDown(stream,callback){if(callback!==void 0)validateFunction(callback,\"callback\");if(stream===null||stream===void 0){if(typeof callback===\"function\")process.nextTick(callback,null);return!0}return stream.write(kClearScreenDown,callback)}var KEYPRESS_DECODER=Symbol(\"keypress-decoder\"),ESCAPE_DECODER=Symbol(\"escape-decoder\"),ESCAPE_CODE_TIMEOUT=500;function emitKeypressEvents(stream,iface={}){if(stream[KEYPRESS_DECODER])return;stream[KEYPRESS_DECODER]=new StringDecoder(\"utf8\"),stream[ESCAPE_DECODER]=emitKeys(stream),stream[ESCAPE_DECODER].next();var triggerEscape=()=>stream[ESCAPE_DECODER].next(\"\"),{escapeCodeTimeout=ESCAPE_CODE_TIMEOUT}=iface,timeoutId;function onData2(input){if(stream.listenerCount(\"keypress\")>0){var string=stream[KEYPRESS_DECODER].write(input);if(string){clearTimeout(timeoutId),iface[kSawKeyPress]=charLengthAt(string,0)===string.length,iface.isCompletionEnabled=!1;var length=0;for(var character of new SafeStringIterator(string)){if(length+=character.length,length===string.length)iface.isCompletionEnabled=!0;try{if(stream[ESCAPE_DECODER].next(character),length===string.length&&character===kEscape)timeoutId=setTimeout(triggerEscape,escapeCodeTimeout)}catch(err){throw stream[ESCAPE_DECODER]=emitKeys(stream),stream[ESCAPE_DECODER].next(),err}}}}else stream.removeListener(\"data\",onData2),stream.on(\"newListener\",onNewListener)}function onNewListener(event){if(event===\"keypress\")stream.on(\"data\",onData2),stream.removeListener(\"newListener\",onNewListener)}if(stream.listenerCount(\"keypress\")>0)stream.on(\"data\",onData2);else stream.on(\"newListener\",onNewListener)}var kEmptyObject=ObjectFreeze(ObjectCreate(null)),kHistorySize=30,kMaxUndoRedoStackSize=2048,kMincrlfDelay=100,lineEnding=/\\r\?\\n|\\r(\?!\\n)/g,kMaxLengthOfKillRing=32,kLineObjectStream=Symbol(\"line object stream\"),kQuestionCancel=Symbol(\"kQuestionCancel\"),kQuestion=Symbol(\"kQuestion\"),kAddHistory=Symbol(\"_addHistory\"),kBeforeEdit=Symbol(\"_beforeEdit\"),kDecoder=Symbol(\"_decoder\"),kDeleteLeft=Symbol(\"_deleteLeft\"),kDeleteLineLeft=Symbol(\"_deleteLineLeft\"),kDeleteLineRight=Symbol(\"_deleteLineRight\"),kDeleteRight=Symbol(\"_deleteRight\"),kDeleteWordLeft=Symbol(\"_deleteWordLeft\"),kDeleteWordRight=Symbol(\"_deleteWordRight\"),kGetDisplayPos=Symbol(\"_getDisplayPos\"),kHistoryNext=Symbol(\"_historyNext\"),kHistoryPrev=Symbol(\"_historyPrev\"),kInsertString=Symbol(\"_insertString\"),kLine=Symbol(\"_line\"),kLine_buffer=Symbol(\"_line_buffer\"),kKillRing=Symbol(\"_killRing\"),kKillRingCursor=Symbol(\"_killRingCursor\"),kMoveCursor=Symbol(\"_moveCursor\"),kNormalWrite=Symbol(\"_normalWrite\"),kOldPrompt=Symbol(\"_oldPrompt\"),kOnLine=Symbol(\"_onLine\"),kPreviousKey=Symbol(\"_previousKey\"),kPrompt=Symbol(\"_prompt\"),kPushToKillRing=Symbol(\"_pushToKillRing\"),kPushToUndoStack=Symbol(\"_pushToUndoStack\"),kQuestionCallback=Symbol(\"_questionCallback\"),kRedo=Symbol(\"_redo\"),kRedoStack=Symbol(\"_redoStack\"),kRefreshLine=Symbol(\"_refreshLine\"),kSawKeyPress=Symbol(\"_sawKeyPress\"),kSawReturnAt=Symbol(\"_sawReturnAt\"),kSetRawMode=Symbol(\"_setRawMode\"),kTabComplete=Symbol(\"_tabComplete\"),kTabCompleter=Symbol(\"_tabCompleter\"),kTtyWrite=Symbol(\"_ttyWrite\"),kUndo=Symbol(\"_undo\"),kUndoStack=Symbol(\"_undoStack\"),kWordLeft=Symbol(\"_wordLeft\"),kWordRight=Symbol(\"_wordRight\"),kWriteToOutput=Symbol(\"_writeToOutput\"),kYank=Symbol(\"_yank\"),kYanking=Symbol(\"_yanking\"),kYankPop=Symbol(\"_yankPop\"),kFirstEventParam=Symbol(\"nodejs.kFirstEventParam\"),kOnSelfCloseWithTerminal=Symbol(\"_onSelfCloseWithTerminal\"),kOnSelfCloseWithoutTerminal=Symbol(\"_onSelfCloseWithoutTerminal\"),kOnKeyPress=Symbol(\"_onKeyPress\"),kOnError=Symbol(\"_onError\"),kOnData=Symbol(\"_onData\"),kOnEnd=Symbol(\"_onEnd\"),kOnTermEnd=Symbol(\"_onTermEnd\"),kOnResize=Symbol(\"_onResize\");function onSelfCloseWithTerminal(){var input=this.input,output=this.output;if(!input)throw new Error(\"Input not set, invalid state for readline!\");if(input.removeListener(\"keypress\",this[kOnKeyPress]),input.removeListener(\"error\",this[kOnError]),input.removeListener(\"end\",this[kOnTermEnd]),output!==null&&output!==void 0)output.removeListener(\"resize\",this[kOnResize])}function onSelfCloseWithoutTerminal(){var input=this.input;if(!input)throw new Error(\"Input not set, invalid state for readline!\");input.removeListener(\"data\",this[kOnData]),input.removeListener(\"error\",this[kOnError]),input.removeListener(\"end\",this[kOnEnd])}function onError(err){this.emit(\"error\",err)}function onData(data){debug(\"onData\"),this[kNormalWrite](data)}function onEnd(){if(debug(\"onEnd\"),typeof this[kLine_buffer]===\"string\"&&this[kLine_buffer].length>0)this.emit(\"line\",this[kLine_buffer]);this.close()}function onTermEnd(){if(debug(\"onTermEnd\"),typeof this.line===\"string\"&&this.line.length>0)this.emit(\"line\",this.line);this.close()}function onKeyPress(s,key){if(this[kTtyWrite](s,key),key&&key.sequence){var ch=StringPrototypeCodePointAt.call(key.sequence,0);if(ch>=55296&&ch<=57343)this[kRefreshLine]()}}function onResize(){this[kRefreshLine]()}function InterfaceConstructor(input,output,completer,terminal){if(!(this instanceof InterfaceConstructor))return new InterfaceConstructor(input,output,completer,terminal);EventEmitter.call(this),this[kOnSelfCloseWithoutTerminal]=onSelfCloseWithoutTerminal.bind(this),this[kOnSelfCloseWithTerminal]=onSelfCloseWithTerminal.bind(this),this[kOnError]=onError.bind(this),this[kOnData]=onData.bind(this),this[kOnEnd]=onEnd.bind(this),this[kOnTermEnd]=onTermEnd.bind(this),this[kOnKeyPress]=onKeyPress.bind(this),this[kOnResize]=onResize.bind(this),this[kSawReturnAt]=0,this.isCompletionEnabled=!0,this[kSawKeyPress]=!1,this[kPreviousKey]=null,this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT,this.tabSize=8;var history,historySize,removeHistoryDuplicates=!1,crlfDelay,prompt=\"> \",signal;if(input\?.input){output=input.output,completer=input.completer,terminal=input.terminal,history=input.history,historySize=input.historySize,signal=input.signal;var tabSize=input.tabSize;if(tabSize!==void 0)validateUint32(tabSize,\"tabSize\",!0),this.tabSize=tabSize;removeHistoryDuplicates=input.removeHistoryDuplicates;var inputPrompt=input.prompt;if(inputPrompt!==void 0)prompt=inputPrompt;var inputEscapeCodeTimeout=input.escapeCodeTimeout;if(inputEscapeCodeTimeout!==void 0)if(NumberIsFinite(inputEscapeCodeTimeout))this.escapeCodeTimeout=inputEscapeCodeTimeout;else throw new ERR_INVALID_ARG_VALUE(\"input.escapeCodeTimeout\",this.escapeCodeTimeout);if(signal)validateAbortSignal(signal,\"options.signal\");crlfDelay=input.crlfDelay,input=input.input}if(completer!==void 0&&typeof completer!==\"function\")throw new ERR_INVALID_ARG_VALUE(\"completer\",completer);if(history===void 0)history=[];else validateArray(history,\"history\");if(historySize===void 0)historySize=kHistorySize;if(typeof historySize!==\"number\"||NumberIsNaN(historySize)||historySize<0)throw new ERR_INVALID_ARG_VALUE(\"historySize\",historySize);if(terminal===void 0&&!(output===null||output===void 0))terminal=!!output.isTTY;if(this.line=\"\",this[kSubstringSearch]=null,this.output=output,this.input=input,this[kUndoStack]=[],this[kRedoStack]=[],this.history=history,this.historySize=historySize,this[kKillRing]=[],this[kKillRingCursor]=0,this.removeHistoryDuplicates=!!removeHistoryDuplicates,this.crlfDelay=crlfDelay\?MathMax(kMincrlfDelay,crlfDelay):kMincrlfDelay,this.completer=completer,this.setPrompt(prompt),this.terminal=!!terminal,this[kLineObjectStream]=void 0,input.on(\"error\",this[kOnError]),!this.terminal)input.on(\"data\",this[kOnData]),input.on(\"end\",this[kOnEnd]),this.once(\"close\",this[kOnSelfCloseWithoutTerminal]),this[kDecoder]=new StringDecoder(\"utf8\");else{if(emitKeypressEvents(input,this),input.on(\"keypress\",this[kOnKeyPress]),input.on(\"end\",this[kOnTermEnd]),this[kSetRawMode](!0),this.terminal=!0,this.cursor=0,this.historyIndex=-1,output!==null&&output!==void 0)output.on(\"resize\",this[kOnResize]);this.once(\"close\",this[kOnSelfCloseWithTerminal])}if(signal){var onAborted=(()=>this.close()).bind(this);if(signal.aborted)process.nextTick(onAborted);else signal.addEventListener(\"abort\",onAborted,{once:!0}),this.once(\"close\",()=>signal.removeEventListener(\"abort\",onAborted))}this.line=\"\",input.resume()}InterfaceConstructor.prototype={},ObjectSetPrototypeOf(InterfaceConstructor.prototype,EventEmitter.prototype);var _Interface=class Interface2 extends InterfaceConstructor{constructor(input,output,completer,terminal){super(input,output,completer,terminal)}get columns(){var output=this.output;if(output&&output.columns)return output.columns;return Infinity}setPrompt(prompt){this[kPrompt]=prompt}getPrompt(){return this[kPrompt]}[kSetRawMode](mode){var input=this.input,{setRawMode,wasInRawMode}=input;return debug(\"setRawMode\",mode,\"set!\"),wasInRawMode}prompt(preserveCursor){if(this.paused)this.resume();if(this.terminal&&process.env.TERM!==\"dumb\"){if(!preserveCursor)this.cursor=0;this[kRefreshLine]()}else this[kWriteToOutput](this[kPrompt])}[kQuestion](query,cb){if(this.closed)throw new ERR_USE_AFTER_CLOSE(\"readline\");if(this[kQuestionCallback])this.prompt();else this[kOldPrompt]=this[kPrompt],this.setPrompt(query),this[kQuestionCallback]=cb,this.prompt()}[kOnLine](line){if(this[kQuestionCallback]){var cb=this[kQuestionCallback];this[kQuestionCallback]=null,this.setPrompt(this[kOldPrompt]),cb(line)}else this.emit(\"line\",line)}[kBeforeEdit](oldText,oldCursor){this[kPushToUndoStack](oldText,oldCursor)}[kQuestionCancel](){if(this[kQuestionCallback])this[kQuestionCallback]=null,this.setPrompt(this[kOldPrompt]),this.clearLine()}[kWriteToOutput](stringToWrite){if(validateString(stringToWrite,\"stringToWrite\"),this.output!==null&&this.output!==void 0)this.output.write(stringToWrite)}[kAddHistory](){if(this.line.length===0)return\"\";if(this.historySize===0)return this.line;if(StringPrototypeTrim.call(this.line).length===0)return this.line;if(this.history.length===0||this.history[0]!==this.line){if(this.removeHistoryDuplicates){var dupIndex=ArrayPrototypeIndexOf.call(this.history,this.line);if(dupIndex!==-1)ArrayPrototypeSplice.call(this.history,dupIndex,1)}if(ArrayPrototypeUnshift.call(this.history,this.line),this.history.length>this.historySize)ArrayPrototypePop.call(this.history)}this.historyIndex=-1;var line=this.history[0];return this.emit(\"history\",this.history),line}[kRefreshLine](){var line=this[kPrompt]+this.line,dispPos=this[kGetDisplayPos](line),lineCols=dispPos.cols,lineRows=dispPos.rows,cursorPos=this.getCursorPos(),prevRows=this.prevRows||0;if(prevRows>0)moveCursor(this.output,0,-prevRows);if(cursorTo(this.output,0),clearScreenDown(this.output),this[kWriteToOutput](line),lineCols===0)this[kWriteToOutput](\" \");cursorTo(this.output,cursorPos.cols);var diff=lineRows-cursorPos.rows;if(diff>0)moveCursor(this.output,0,-diff);this.prevRows=cursorPos.rows}close(){if(this.closed)return;if(this.pause(),this.terminal)this[kSetRawMode](!1);this.closed=!0,this.emit(\"close\")}pause(){if(this.paused)return;return this.input.pause(),this.paused=!0,this.emit(\"pause\"),this}resume(){if(!this.paused)return;return this.input.resume(),this.paused=!1,this.emit(\"resume\"),this}write(d,key){if(this.paused)this.resume();if(this.terminal)this[kTtyWrite](d,key);else this[kNormalWrite](d)}[kNormalWrite](b){if(b===void 0)return;var string=this[kDecoder].write(b);if(this[kSawReturnAt]&&DateNow()-this[kSawReturnAt]<=this.crlfDelay){if(StringPrototypeCodePointAt.call(string)===10)string=StringPrototypeSlice.call(string,1);this[kSawReturnAt]=0}var newPartContainsEnding=RegExpPrototypeExec.call(lineEnding,string);if(newPartContainsEnding!==null){if(this[kLine_buffer])string=this[kLine_buffer]+string,this[kLine_buffer]=null,newPartContainsEnding=RegExpPrototypeExec.call(lineEnding,string);this[kSawReturnAt]=StringPrototypeEndsWith.call(string,\"\\r\")\?DateNow():0;var indexes=[0,newPartContainsEnding.index,lineEnding.lastIndex],nextMatch;while((nextMatch=RegExpPrototypeExec.call(lineEnding,string))!==null)ArrayPrototypePush.call(indexes,nextMatch.index,lineEnding.lastIndex);var lastIndex=indexes.length-1;this[kLine_buffer]=StringPrototypeSlice.call(string,indexes[lastIndex]);for(var i=1;ie!==\"\"));if(StringPrototypeStartsWith.call(prefix,completeOn)&&prefix.length>completeOn.length){this[kInsertString](StringPrototypeSlice.call(prefix,completeOn.length));return}else if(!StringPrototypeStartsWith.call(completeOn,prefix)){this.line=StringPrototypeSlice.call(this.line,0,this.cursor-completeOn.length)+prefix+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor=this.cursor-completeOn.length+prefix.length,this._refreshLine();return}if(!lastKeypressWasTab)return;this[kBeforeEdit](this.line,this.cursor);var completionsWidth=ArrayPrototypeMap.call(completions,(e)=>getStringWidth(e)),width=MathMaxApply(completionsWidth)+2,maxColumns=MathFloor(this.columns/width)||1;if(maxColumns===Infinity)maxColumns=1;var output=\"\\r\\n\",lineIndex=0,whitespace=0;for(var i=0;i0){var leading=StringPrototypeSlice.call(this.line,0,this.cursor),reversed=ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)),\"\"),match=RegExpPrototypeExec.call(/^\\s*(\?:[^\\w\\s]+|\\w+)\?/,reversed);this[kMoveCursor](-match[0].length)}}[kWordRight](){if(this.cursor0&&this.line.length>0){this[kBeforeEdit](this.line,this.cursor);var charSize=charLengthLeft(this.line,this.cursor);this.line=StringPrototypeSlice.call(this.line,0,this.cursor-charSize)+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor-=charSize,this[kRefreshLine]()}}[kDeleteRight](){if(this.cursor0){this[kBeforeEdit](this.line,this.cursor);var leading=StringPrototypeSlice.call(this.line,0,this.cursor),reversed=ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)),\"\"),match=RegExpPrototypeExec.call(/^\\s*(\?:[^\\w\\s]+|\\w+)\?/,reversed);leading=StringPrototypeSlice.call(leading,0,leading.length-match[0].length),this.line=leading+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor=leading.length,this[kRefreshLine]()}}[kDeleteWordRight](){if(this.cursorkMaxLengthOfKillRing)ArrayPrototypePop.call(this[kKillRing])}[kYank](){if(this[kKillRing].length>0)this[kYanking]=!0,this[kInsertString](this[kKillRing][this[kKillRingCursor]])}[kYankPop](){if(!this[kYanking])return;if(this[kKillRing].length>1){var lastYank=this[kKillRing][this[kKillRingCursor]];if(this[kKillRingCursor]++,this[kKillRingCursor]>=this[kKillRing].length)this[kKillRingCursor]=0;var currentYank=this[kKillRing][this[kKillRingCursor]],head=StringPrototypeSlice.call(this.line,0,this.cursor-lastYank.length),tail=StringPrototypeSlice.call(this.line,this.cursor);this.line=head+currentYank+tail,this.cursor=head.length+currentYank.length,this[kRefreshLine]()}}clearLine(){this[kMoveCursor](Infinity),this[kWriteToOutput](\"\\r\\n\"),this.line=\"\",this.cursor=0,this.prevRows=0}[kLine](){var line=this[kAddHistory]();this[kUndoStack]=[],this[kRedoStack]=[],this.clearLine(),this[kOnLine](line)}[kPushToUndoStack](text,cursor){if(ArrayPrototypePush.call(this[kUndoStack],{text,cursor})>kMaxUndoRedoStackSize)ArrayPrototypeShift.call(this[kUndoStack])}[kUndo](){if(this[kUndoStack].length<=0)return;ArrayPrototypePush.call(this[kRedoStack],{text:this.line,cursor:this.cursor});var entry=ArrayPrototypePop.call(this[kUndoStack]);this.line=entry.text,this.cursor=entry.cursor,this[kRefreshLine]()}[kRedo](){if(this[kRedoStack].length<=0)return;ArrayPrototypePush.call(this[kUndoStack],{text:this.line,cursor:this.cursor});var entry=ArrayPrototypePop.call(this[kRedoStack]);this.line=entry.text,this.cursor=entry.cursor,this[kRefreshLine]()}[kHistoryNext](){if(this.historyIndex>=0){this[kBeforeEdit](this.line,this.cursor);var search=this[kSubstringSearch]||\"\",index=this.historyIndex-1;while(index>=0&&(!StringPrototypeStartsWith.call(this.history[index],search)||this.line===this.history[index]))index--;if(index===-1)this.line=search;else this.line=this.history[index];this.historyIndex=index,this.cursor=this.line.length,this[kRefreshLine]()}}[kHistoryPrev](){if(this.historyIndexthis.line.length)this.cursor=this.line.length;var newPos=this.getCursorPos();if(oldPos.rows===newPos.rows){var diffWidth=newPos.cols-oldPos.cols;moveCursor(this.output,diffWidth,0)}else this[kRefreshLine]()}[kTtyWrite](s,key){var previousKey=this[kPreviousKey];key=key||kEmptyObject,this[kPreviousKey]=key;var{name:keyName,meta:keyMeta,ctrl:keyCtrl2,shift:keyShift,sequence:keySeq}=key;if(!keyMeta||keyName!==\"y\")this[kYanking]=!1;if((keyName===\"up\"||keyName===\"down\")&&!keyCtrl2&&!keyMeta&&!keyShift){if(this[kSubstringSearch]===null)this[kSubstringSearch]=StringPrototypeSlice.call(this.line,0,this.cursor)}else if(this[kSubstringSearch]!==null){if(this[kSubstringSearch]=null,this.history.length===this.historyIndex)this.historyIndex=-1}if(typeof keySeq===\"string\")switch(StringPrototypeCodePointAt.call(keySeq,0)){case 31:this[kUndo]();return;case 30:this[kRedo]();return;default:break}if(keyName===\"escape\")return;if(keyCtrl2&&keyShift)switch(keyName){case\"backspace\":this[kDeleteLineLeft]();break;case\"delete\":this[kDeleteLineRight]();break}else if(keyCtrl2)switch(keyName){case\"c\":if(this.listenerCount(\"SIGINT\")>0)this.emit(\"SIGINT\");else this.close();break;case\"h\":this[kDeleteLeft]();break;case\"d\":if(this.cursor===0&&this.line.length===0)this.close();else if(this.cursor0)this.emit(\"SIGTSTP\");else process.once(\"SIGCONT\",()=>{if(!this.paused)this.pause(),this.emit(\"SIGCONT\");this[kSetRawMode](!0),this[kRefreshLine]()}),this[kSetRawMode](!1),process.kill(process.pid,\"SIGTSTP\");break;case\"w\":case\"backspace\":this[kDeleteWordLeft]();break;case\"delete\":this[kDeleteWordRight]();break;case\"left\":this[kWordLeft]();break;case\"right\":this[kWordRight]();break}else if(keyMeta)switch(keyName){case\"b\":this[kWordLeft]();break;case\"f\":this[kWordRight]();break;case\"d\":case\"delete\":this[kDeleteWordRight]();break;case\"backspace\":this[kDeleteWordLeft]();break;case\"y\":this[kYankPop]();break}else{if(this[kSawReturnAt]&&keyName!==\"enter\")this[kSawReturnAt]=0;switch(keyName){case\"return\":this[kSawReturnAt]=DateNow(),this[kLine]();break;case\"enter\":if(this[kSawReturnAt]===0||DateNow()-this[kSawReturnAt]>this.crlfDelay)this[kLine]();this[kSawReturnAt]=0;break;case\"backspace\":this[kDeleteLeft]();break;case\"delete\":this[kDeleteRight]();break;case\"left\":this[kMoveCursor](-charLengthLeft(this.line,this.cursor));break;case\"right\":this[kMoveCursor](+charLengthAt(this.line,this.cursor));break;case\"home\":this[kMoveCursor]((-Infinity));break;case\"end\":this[kMoveCursor](Infinity);break;case\"up\":this[kHistoryPrev]();break;case\"down\":this[kHistoryNext]();break;case\"tab\":if(typeof this.completer===\"function\"&&this.isCompletionEnabled){var lastKeypressWasTab=previousKey&&previousKey.name===\"tab\";this[kTabComplete](lastKeypressWasTab);break}default:if(typeof s===\"string\"&&s){var nextMatch=RegExpPrototypeExec.call(lineEnding,s);if(nextMatch!==null){this[kInsertString](StringPrototypeSlice.call(s,0,nextMatch.index));var{lastIndex}=lineEnding;while((nextMatch=RegExpPrototypeExec.call(lineEnding,s))!==null)this[kLine](),this[kInsertString](StringPrototypeSlice.call(s,lastIndex,nextMatch.index)),{lastIndex}=lineEnding;if(lastIndex===s.length)this[kLine]()}else this[kInsertString](s)}}}}[SymbolAsyncIterator](){if(this[kLineObjectStream]===void 0)this[kLineObjectStream]=EventEmitter.on(this,\"line\",{close:[\"close\"],highWatermark:1024,[kFirstEventParam]:!0});return this[kLineObjectStream]}};function Interface(input,output,completer,terminal){if(!(this instanceof Interface))return new Interface(input,output,completer,terminal);if(input\?.input&&typeof input.completer===\"function\"&&input.completer.length!==2){var{completer}=input;input.completer=(v,cb)=>cb(null,completer(v))}else if(typeof completer===\"function\"&&completer.length!==2){var realCompleter=completer;completer=(v,cb)=>cb(null,realCompleter(v))}if(InterfaceConstructor.call(this,input,output,completer,terminal),process.env.TERM===\"dumb\")this._ttyWrite=_ttyWriteDumb.bind(this)}Interface.prototype={},ObjectSetPrototypeOf(Interface.prototype,_Interface.prototype),ObjectSetPrototypeOf(Interface,_Interface),Interface.prototype.question=function question(query,options,cb){if(cb=typeof options===\"function\"\?options:cb,options===null||typeof options!==\"object\")options=kEmptyObject;var signal=options\?.signal;if(signal){if(validateAbortSignal(signal,\"options.signal\"),signal.aborted)return;var onAbort=()=>{this[kQuestionCancel]()};signal.addEventListener(\"abort\",onAbort,{once:!0});var cleanup=()=>{signal.removeEventListener(\"abort\",onAbort)},originalCb=cb;cb=typeof cb===\"function\"\?(answer)=>{return cleanup(),originalCb(answer)}:cleanup}if(typeof cb===\"function\")this[kQuestion](query,cb)},Interface.prototype.question[promisify.custom]=function question(query,options){if(options===null||typeof options!==\"object\")options=kEmptyObject;var signal=options\?.signal;if(signal&&signal.aborted)return PromiseReject(new AbortError(void 0,{cause:signal.reason}));return new Promise((resolve,reject)=>{var cb=resolve;if(signal){var onAbort=()=>{reject(new AbortError(void 0,{cause:signal.reason}))};signal.addEventListener(\"abort\",onAbort,{once:!0}),cb=(answer)=>{signal.removeEventListener(\"abort\",onAbort),resolve(answer)}}this.question(query,options,cb)})};function createInterface(input,output,completer,terminal){return new Interface(input,output,completer,terminal)}ObjectDefineProperties(Interface.prototype,{[kSetRawMode]:{__proto__:null,get(){return this._setRawMode}},[kOnLine]:{__proto__:null,get(){return this._onLine}},[kWriteToOutput]:{__proto__:null,get(){return this._writeToOutput}},[kAddHistory]:{__proto__:null,get(){return this._addHistory}},[kRefreshLine]:{__proto__:null,get(){return this._refreshLine}},[kNormalWrite]:{__proto__:null,get(){return this._normalWrite}},[kInsertString]:{__proto__:null,get(){return this._insertString}},[kTabComplete]:{__proto__:null,get(){return this._tabComplete}},[kWordLeft]:{__proto__:null,get(){return this._wordLeft}},[kWordRight]:{__proto__:null,get(){return this._wordRight}},[kDeleteLeft]:{__proto__:null,get(){return this._deleteLeft}},[kDeleteRight]:{__proto__:null,get(){return this._deleteRight}},[kDeleteWordLeft]:{__proto__:null,get(){return this._deleteWordLeft}},[kDeleteWordRight]:{__proto__:null,get(){return this._deleteWordRight}},[kDeleteLineLeft]:{__proto__:null,get(){return this._deleteLineLeft}},[kDeleteLineRight]:{__proto__:null,get(){return this._deleteLineRight}},[kLine]:{__proto__:null,get(){return this._line}},[kHistoryNext]:{__proto__:null,get(){return this._historyNext}},[kHistoryPrev]:{__proto__:null,get(){return this._historyPrev}},[kGetDisplayPos]:{__proto__:null,get(){return this._getDisplayPos}},[kMoveCursor]:{__proto__:null,get(){return this._moveCursor}},[kTtyWrite]:{__proto__:null,get(){return this._ttyWrite}},_decoder:{__proto__:null,get(){return this[kDecoder]},set(value){this[kDecoder]=value}},_line_buffer:{__proto__:null,get(){return this[kLine_buffer]},set(value){this[kLine_buffer]=value}},_oldPrompt:{__proto__:null,get(){return this[kOldPrompt]},set(value){this[kOldPrompt]=value}},_previousKey:{__proto__:null,get(){return this[kPreviousKey]},set(value){this[kPreviousKey]=value}},_prompt:{__proto__:null,get(){return this[kPrompt]},set(value){this[kPrompt]=value}},_questionCallback:{__proto__:null,get(){return this[kQuestionCallback]},set(value){this[kQuestionCallback]=value}},_sawKeyPress:{__proto__:null,get(){return this[kSawKeyPress]},set(value){this[kSawKeyPress]=value}},_sawReturnAt:{__proto__:null,get(){return this[kSawReturnAt]},set(value){this[kSawReturnAt]=value}}}),Interface.prototype._setRawMode=_Interface.prototype[kSetRawMode],Interface.prototype._onLine=_Interface.prototype[kOnLine],Interface.prototype._writeToOutput=_Interface.prototype[kWriteToOutput],Interface.prototype._addHistory=_Interface.prototype[kAddHistory],Interface.prototype._refreshLine=_Interface.prototype[kRefreshLine],Interface.prototype._normalWrite=_Interface.prototype[kNormalWrite],Interface.prototype._insertString=_Interface.prototype[kInsertString],Interface.prototype._tabComplete=function(lastKeypressWasTab){this.pause();var string=StringPrototypeSlice.call(this.line,0,this.cursor);this.completer(string,(err,value)=>{if(this.resume(),err){this._writeToOutput(`Tab completion error: ${inspect(err)}`);return}this[kTabCompleter](lastKeypressWasTab,value)})},Interface.prototype._wordLeft=_Interface.prototype[kWordLeft],Interface.prototype._wordRight=_Interface.prototype[kWordRight],Interface.prototype._deleteLeft=_Interface.prototype[kDeleteLeft],Interface.prototype._deleteRight=_Interface.prototype[kDeleteRight],Interface.prototype._deleteWordLeft=_Interface.prototype[kDeleteWordLeft],Interface.prototype._deleteWordRight=_Interface.prototype[kDeleteWordRight],Interface.prototype._deleteLineLeft=_Interface.prototype[kDeleteLineLeft],Interface.prototype._deleteLineRight=_Interface.prototype[kDeleteLineRight],Interface.prototype._line=_Interface.prototype[kLine],Interface.prototype._historyNext=_Interface.prototype[kHistoryNext],Interface.prototype._historyPrev=_Interface.prototype[kHistoryPrev],Interface.prototype._getDisplayPos=_Interface.prototype[kGetDisplayPos],Interface.prototype._getCursorPos=_Interface.prototype.getCursorPos,Interface.prototype._moveCursor=_Interface.prototype[kMoveCursor],Interface.prototype._ttyWrite=_Interface.prototype[kTtyWrite];function _ttyWriteDumb(s,key){if(key=key||kEmptyObject,key.name===\"escape\")return;if(this[kSawReturnAt]&&key.name!==\"enter\")this[kSawReturnAt]=0;if(keyCtrl){if(key.name===\"c\"){if(this.listenerCount(\"SIGINT\")>0)this.emit(\"SIGINT\");else this.close();return}else if(key.name===\"d\"){this.close();return}}switch(key.name){case\"return\":this[kSawReturnAt]=DateNow(),this._line();break;case\"enter\":if(this[kSawReturnAt]===0||DateNow()-this[kSawReturnAt]>this.crlfDelay)this._line();this[kSawReturnAt]=0;break;default:if(typeof s===\"string\"&&s)this.line+=s,this.cursor+=s.length,this._writeToOutput(s)}}class Readline{#autoCommit=!1;#stream;#todo=[];constructor(stream,options=void 0){if(isWritable\?\?=(@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34)).isWritable,!isWritable(stream))throw new ERR_INVALID_ARG_TYPE(\"stream\",\"Writable\",stream);if(this.#stream=stream,options\?.autoCommit!=null)validateBoolean(options.autoCommit,\"options.autoCommit\"),this.#autoCommit=options.autoCommit}cursorTo(x,y=void 0){if(validateInteger(x,\"x\"),y!=null)validateInteger(y,\"y\");var data=y==null\?CSI`${x+1}G`:CSI`${y+1};${x+1}H`;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data);return this}moveCursor(dx,dy){if(dx||dy){validateInteger(dx,\"dx\"),validateInteger(dy,\"dy\");var data=\"\";if(dx<0)data+=CSI`${-dx}D`;else if(dx>0)data+=CSI`${dx}C`;if(dy<0)data+=CSI`${-dy}A`;else if(dy>0)data+=CSI`${dy}B`;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data)}return this}clearLine(dir){validateInteger(dir,\"dir\",-1,1);var data=dir<0\?kClearToLineBeginning:dir>0\?kClearToLineEnd:kClearLine;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data);return this}clearScreenDown(){if(this.#autoCommit)process.nextTick(()=>this.#stream.write(kClearScreenDown));else ArrayPrototypePush.call(this.#todo,kClearScreenDown);return this}commit(){return new Promise((resolve)=>{this.#stream.write(ArrayPrototypeJoin.call(this.#todo,\"\"),resolve),this.#todo=[]})}rollback(){return this.#todo=[],this}}var PromisesInterface=class Interface2 extends _Interface{constructor(input,output,completer,terminal){super(input,output,completer,terminal)}question(query,options=kEmptyObject){var signal=options\?.signal;if(signal){if(validateAbortSignal(signal,\"options.signal\"),signal.aborted)return PromiseReject(new AbortError(void 0,{cause:signal.reason}))}return new Promise((resolve,reject)=>{var cb=resolve;if(options\?.signal){var onAbort=()=>{this[kQuestionCancel](),reject(new AbortError(void 0,{cause:signal.reason}))};signal.addEventListener(\"abort\",onAbort,{once:!0}),cb=(answer)=>{signal.removeEventListener(\"abort\",onAbort),resolve(answer)}}this[kQuestion](query,cb)})}};return $={Interface,clearLine,clearScreenDown,createInterface,cursorTo,emitKeypressEvents,moveCursor,promises:{Readline,Interface:PromisesInterface,createInterface(input,output,completer,terminal){return new PromisesInterface(input,output,completer,terminal)}},[SymbolFor(\"__BUN_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED__\")]:{CSI,utils:{getStringWidth,stripVTControlCharacters}}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeReadlinePromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,30)||@createInternalModuleById(30)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeReplCode = "(function (){\"use strict\";var $;const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function REPLServer(){throwNotImplemented(\"node:repl REPLServer\")}function Recoverable(){throwNotImplemented(\"node:repl Recoverable\")}var REPL_MODE_SLOPPY=0,REPL_MODE_STRICT=1;function start(){throwNotImplemented(\"node:repl\")}return $={lines:[],context:globalThis,historyIndex:-1,cursor:0,historySize:1000,removeHistoryDuplicates:!1,crlfDelay:100,completer:()=>{throwNotImplemented(\"node:repl\")},history:[],_initialPrompt:\"> \",terminal:!0,input:new Proxy({},{get(){throwNotImplemented(\"node:repl\")},has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{return},set(){throwNotImplemented(\"node:repl\")}}),line:\"\",eval:()=>{throwNotImplemented(\"node:repl\")},isCompletionEnabled:!0,escapeCodeTimeout:500,tabSize:8,breakEvalOnSigint:!0,useGlobal:!0,underscoreAssigned:!1,last:void 0,_domain:void 0,allowBlockingCompletions:!1,useColors:!0,output:new Proxy({},{get(){throwNotImplemented(\"node:repl\")},has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{return},set(){throwNotImplemented(\"node:repl\")}})},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamConsumersCode = "(function (){\"use strict\";const{readableStreamToArrayBuffer:arrayBuffer,readableStreamToText:text}=Bun,json=(stream)=>Bun.readableStreamToText(stream).then(JSON.parse),buffer=async(readableStream)=>{return new Buffer(await arrayBuffer(readableStream))},blob=Bun.readableStreamToBlob;return{arrayBuffer,text,json,buffer,blob}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamCode = "(function (){\"use strict\";const EE=globalThis[globalThis.Symbol.for('Bun.lazy')](\"events\"),StringDecoder=@requireNativeModule(\"node:string_decoder\").StringDecoder;var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},runOnNextTick=process.nextTick;function isReadableStream(value){return typeof value===\"object\"&&value!==null&&value instanceof ReadableStream}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}const validateObject=(value,name,options=null)=>{const allowArray=options\?.allowArray\?\?!1,allowFunction=options\?.allowFunction\?\?!1;if(!(options\?.nullable\?\?!1)&&value===null||!allowArray&&ArrayIsArray(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE(name,\"Object\",value)};function validateString(value,name){if(typeof value!==\"string\")throw new ERR_INVALID_ARG_TYPE(name,\"string\",value)}var ArrayIsArray=Array.isArray;function ERR_INVALID_ARG_TYPE(name,type,value){return new Error(`The argument '${name}' is invalid. Received '${value}' for type '${type}'`)}function ERR_INVALID_ARG_VALUE(name,value,reason){return new Error(`The value '${value}' is invalid for argument '${name}'. Reason: ${reason}`)}var require_primordials=__commonJS({\"node_modules/readable-stream/lib/ours/primordials.js\"(exports2,module){module.exports={ArrayIsArray(self){return Array.isArray(self)},ArrayPrototypeIncludes(self,el){return self.includes(el)},ArrayPrototypeIndexOf(self,el){return self.indexOf(el)},ArrayPrototypeJoin(self,sep){return self.join(sep)},ArrayPrototypeMap(self,fn){return self.map(fn)},ArrayPrototypePop(self,el){return self.pop(el)},ArrayPrototypePush(self,el){return self.push(el)},ArrayPrototypeSlice(self,start,end){return self.slice(start,end)},Error,FunctionPrototypeCall(fn,thisArgs,...args){return fn.call(thisArgs,...args)},FunctionPrototypeSymbolHasInstance(self,instance){return Function.prototype[Symbol.hasInstance].call(self,instance)},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(self,props){return Object.defineProperties(self,props)},ObjectDefineProperty(self,name,prop){return Object.defineProperty(self,name,prop)},ObjectGetOwnPropertyDescriptor(self,name){return Object.getOwnPropertyDescriptor(self,name)},ObjectKeys(obj){return Object.keys(obj)},ObjectSetPrototypeOf(target,proto){return Object.setPrototypeOf(target,proto)},Promise,PromisePrototypeCatch(self,fn){return self.catch(fn)},PromisePrototypeThen(self,thenFn,catchFn){return self.then(thenFn,catchFn)},PromiseReject(err){return Promise.reject(err)},ReflectApply:Reflect.apply,RegExpPrototypeTest(self,value){return self.test(value)},SafeSet:Set,String,StringPrototypeSlice(self,start,end){return self.slice(start,end)},StringPrototypeToLowerCase(self){return self.toLowerCase()},StringPrototypeToUpperCase(self){return self.toUpperCase()},StringPrototypeTrim(self){return self.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(self,buf,len){return self.set(buf,len)},Uint8Array}}}),require_util=__commonJS({\"node_modules/readable-stream/lib/ours/util.js\"(exports2,module){var AsyncFunction=Object.getPrototypeOf(async function(){}).constructor,isBlob=typeof Blob!==\"undefined\"\?function isBlob2(b){return b instanceof Blob}:function isBlob2(b){return!1},AggregateError=class extends Error{constructor(errors){if(!Array.isArray(errors))@throwTypeError(`Expected input to be an Array, got ${typeof errors}`);let message=\"\";for(let i=0;i{resolve=res,reject=rej}),resolve,reject}},promisify(fn){return new Promise((resolve,reject)=>{fn((err,...args)=>{if(err)return reject(err);return resolve(...args)})})},debuglog(){return function(){}},format(format,...args){return format.replace(/%([sdifj])/g,function(...[_unused,type]){const replacement=args.shift();if(type===\"f\")return replacement.toFixed(6);else if(type===\"j\")return JSON.stringify(replacement);else if(type===\"s\"&&typeof replacement===\"object\")return`${replacement.constructor!==Object\?replacement.constructor.name:\"\"} {}`.trim();else return replacement.toString()})},inspect(value){switch(typeof value){case\"string\":if(value.includes(\"'\")){if(!value.includes('\"'))return`\"${value}\"`;else if(!value.includes(\"`\")&&!value.includes(\"${\"))return`\\`${value}\\``}return`'${value}'`;case\"number\":if(isNaN(value))return\"NaN\";else if(Object.is(value,-0))return String(value);return value;case\"bigint\":return`${String(value)}n`;case\"boolean\":case\"undefined\":return String(value);case\"object\":return\"{}\"}},types:{isAsyncFunction(fn){return fn instanceof AsyncFunction},isArrayBufferView(arr){return ArrayBuffer.isView(arr)}},isBlob},module.exports.promisify.custom=Symbol.for(\"nodejs.util.promisify.custom\")}}),require_errors=__commonJS({\"node_modules/readable-stream/lib/ours/errors.js\"(exports2,module){var{format,inspect,AggregateError:CustomAggregateError}=require_util(),AggregateError=globalThis.AggregateError||CustomAggregateError,kIsNodeError=Symbol(\"kIsNodeError\"),kTypes=[\"string\",\"function\",\"number\",\"object\",\"Function\",\"Object\",\"boolean\",\"bigint\",\"symbol\"],classRegExp=/^([A-Z][a-z0-9]*)+$/,nodeInternalPrefix=\"__node_internal_\",codes={};function assert(value,message){if(!value)throw new codes.ERR_INTERNAL_ASSERTION(message)}function addNumericalSeparator(val){let res=\"\",i=val.length;const start=val[0]===\"-\"\?1:0;for(;i>=start+4;i-=3)res=`_${val.slice(i-3,i)}${res}`;return`${val.slice(0,i)}${res}`}function getMessage(key,msg,args){if(typeof msg===\"function\")return assert(msg.length<=args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`),msg(...args);const expectedLength=(msg.match(/%[dfijoOs]/g)||[]).length;if(assert(expectedLength===args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`),args.length===0)return msg;return format(msg,...args)}function E(code,message,Base){if(!Base)Base=Error;class NodeError extends Base{constructor(...args){super(getMessage(code,message,args))}toString(){return`${this.name} [${code}]: ${this.message}`}}Object.defineProperties(NodeError.prototype,{name:{value:Base.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${code}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),NodeError.prototype.code=code,NodeError.prototype[kIsNodeError]=!0,codes[code]=NodeError}function hideStackFrames(fn){const hidden=nodeInternalPrefix+fn.name;return Object.defineProperty(fn,\"name\",{value:hidden}),fn}function aggregateTwoErrors(innerError,outerError){if(innerError&&outerError&&innerError!==outerError){if(Array.isArray(outerError.errors))return outerError.errors.push(innerError),outerError;const err=new AggregateError([outerError,innerError],outerError.message);return err.code=outerError.code,err}return innerError||outerError}var AbortError2=class extends Error{constructor(message=\"The operation was aborted\",options=void 0){if(options!==void 0&&typeof options!==\"object\")throw new codes.ERR_INVALID_ARG_TYPE(\"options\",\"Object\",options);super(message,options);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};E(\"ERR_ASSERTION\",\"%s\",Error),E(\"ERR_INVALID_ARG_TYPE\",(name,expected,actual)=>{if(assert(typeof name===\"string\",\"'name' must be a string\"),!Array.isArray(expected))expected=[expected];let msg=\"The \";if(name.endsWith(\" argument\"))msg+=`${name} `;else msg+=`\"${name}\" ${name.includes(\".\")\?\"property\":\"argument\"} `;msg+=\"must be \";const types=[],instances=[],other=[];for(let value of expected)if(assert(typeof value===\"string\",\"All expected entries have to be of type string\"),kTypes.includes(value))types.push(value.toLowerCase());else if(classRegExp.test(value))instances.push(value);else assert(value!==\"object\",'The value \"object\" should be written as \"Object\"'),other.push(value);if(instances.length>0){const pos=types.indexOf(\"object\");if(pos!==-1)types.splice(types,pos,1),instances.push(\"Object\")}if(types.length>0){switch(types.length){case 1:msg+=`of type ${types[0]}`;break;case 2:msg+=`one of type ${types[0]} or ${types[1]}`;break;default:{const last=types.pop();msg+=`one of type ${types.join(\", \")}, or ${last}`}}if(instances.length>0||other.length>0)msg+=\" or \"}if(instances.length>0){switch(instances.length){case 1:msg+=`an instance of ${instances[0]}`;break;case 2:msg+=`an instance of ${instances[0]} or ${instances[1]}`;break;default:{const last=instances.pop();msg+=`an instance of ${instances.join(\", \")}, or ${last}`}}if(other.length>0)msg+=\" or \"}switch(other.length){case 0:break;case 1:if(other[0].toLowerCase()!==other[0])msg+=\"an \";msg+=`${other[0]}`;break;case 2:msg+=`one of ${other[0]} or ${other[1]}`;break;default:{const last=other.pop();msg+=`one of ${other.join(\", \")}, or ${last}`}}if(actual==null)msg+=`. Received ${actual}`;else if(typeof actual===\"function\"&&actual.name)msg+=`. Received function ${actual.name}`;else if(typeof actual===\"object\"){var _actual$constructor;if((_actual$constructor=actual.constructor)!==null&&_actual$constructor!==void 0&&_actual$constructor.name)msg+=`. Received an instance of ${actual.constructor.name}`;else{const inspected=inspect(actual,{depth:-1});msg+=`. Received ${inspected}`}}else{let inspected=inspect(actual,{colors:!1});if(inspected.length>25)inspected=`${inspected.slice(0,25)}...`;msg+=`. Received type ${typeof actual} (${inspected})`}return msg},TypeError),E(\"ERR_INVALID_ARG_VALUE\",(name,value,reason=\"is invalid\")=>{let inspected=inspect(value);if(inspected.length>128)inspected=inspected.slice(0,128)+\"...\";return`The ${name.includes(\".\")\?\"property\":\"argument\"} '${name}' ${reason}. Received ${inspected}`},TypeError),E(\"ERR_INVALID_RETURN_VALUE\",(input,name,value)=>{var _value$constructor;const type=value!==null&&value!==void 0&&(_value$constructor=value.constructor)!==null&&_value$constructor!==void 0&&_value$constructor.name\?`instance of ${value.constructor.name}`:`type ${typeof value}`;return`Expected ${input} to be returned from the \"${name}\" function but got ${type}.`},TypeError),E(\"ERR_MISSING_ARGS\",(...args)=>{assert(args.length>0,\"At least one arg needs to be specified\");let msg;const len=args.length;switch(args=(Array.isArray(args)\?args:[args]).map((a)=>`\"${a}\"`).join(\" or \"),len){case 1:msg+=`The ${args[0]} argument`;break;case 2:msg+=`The ${args[0]} and ${args[1]} arguments`;break;default:{const last=args.pop();msg+=`The ${args.join(\", \")}, and ${last} arguments`}break}return`${msg} must be specified`},TypeError),E(\"ERR_OUT_OF_RANGE\",(str,range,input)=>{assert(range,'Missing \"range\" argument');let received;if(Number.isInteger(input)&&Math.abs(input)>4294967296)received=addNumericalSeparator(String(input));else if(typeof input===\"bigint\"){if(received=String(input),input>2n**32n||input<-(2n**32n))received=addNumericalSeparator(received);received+=\"n\"}else received=inspect(input);return`The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`},RangeError),E(\"ERR_MULTIPLE_CALLBACK\",\"Callback called multiple times\",Error),E(\"ERR_METHOD_NOT_IMPLEMENTED\",\"The %s method is not implemented\",Error),E(\"ERR_STREAM_ALREADY_FINISHED\",\"Cannot call %s after a stream was finished\",Error),E(\"ERR_STREAM_CANNOT_PIPE\",\"Cannot pipe, not readable\",Error),E(\"ERR_STREAM_DESTROYED\",\"Cannot call %s after a stream was destroyed\",Error),E(\"ERR_STREAM_NULL_VALUES\",\"May not write null values to stream\",TypeError),E(\"ERR_STREAM_PREMATURE_CLOSE\",\"Premature close\",Error),E(\"ERR_STREAM_PUSH_AFTER_EOF\",\"stream.push() after EOF\",Error),E(\"ERR_STREAM_UNSHIFT_AFTER_END_EVENT\",\"stream.unshift() after end event\",Error),E(\"ERR_STREAM_WRITE_AFTER_END\",\"write after end\",Error),E(\"ERR_UNKNOWN_ENCODING\",\"Unknown encoding: %s\",TypeError),module.exports={AbortError:AbortError2,aggregateTwoErrors:hideStackFrames(aggregateTwoErrors),hideStackFrames,codes}}}),require_validators=__commonJS({\"node_modules/readable-stream/lib/internal/validators.js\"(exports2,module){var{ArrayIsArray:ArrayIsArray2,ArrayPrototypeIncludes,ArrayPrototypeJoin,ArrayPrototypeMap,NumberIsInteger,NumberMAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER,NumberParseInt,RegExpPrototypeTest,String:String2,StringPrototypeToUpperCase,StringPrototypeTrim}=require_primordials(),{hideStackFrames,codes:{ERR_SOCKET_BAD_PORT,ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2,ERR_OUT_OF_RANGE,ERR_UNKNOWN_SIGNAL}}=require_errors(),{normalizeEncoding}=require_util(),{isAsyncFunction,isArrayBufferView}=require_util().types,signals={};function isInt32(value){return value===(value|0)}function isUint32(value){return value===value>>>0}var octalReg=/^[0-7]+$/,modeDesc=\"must be a 32-bit unsigned integer or an octal string\";function parseFileMode(value,name,def){if(typeof value===\"undefined\")value=def;if(typeof value===\"string\"){if(!RegExpPrototypeTest(octalReg,value))throw new ERR_INVALID_ARG_VALUE2(name,value,modeDesc);value=NumberParseInt(value,8)}return validateInt32(value,name,0,4294967295),value}var validateInteger=hideStackFrames((value,name,min=NumberMIN_SAFE_INTEGER,max=NumberMAX_SAFE_INTEGER)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}),validateInt32=hideStackFrames((value,name,min=-2147483648,max=2147483647)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!isInt32(value)){if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}),validateUint32=hideStackFrames((value,name,positive)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!isUint32(value)){if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);throw new ERR_OUT_OF_RANGE(name,`>= ${positive\?1:0} && < 4294967296`,value)}if(positive&&value===0)throw new ERR_OUT_OF_RANGE(name,\">= 1 && < 4294967296\",value)});function validateString2(value,name){if(typeof value!==\"string\")throw new ERR_INVALID_ARG_TYPE2(name,\"string\",value)}function validateNumber(value,name){if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value)}var validateOneOf=hideStackFrames((value,name,oneOf)=>{if(!ArrayPrototypeIncludes(oneOf,value)){const reason=\"must be one of: \"+ArrayPrototypeJoin(ArrayPrototypeMap(oneOf,(v)=>typeof v===\"string\"\?`'${v}'`:String2(v)),\", \");throw new ERR_INVALID_ARG_VALUE2(name,value,reason)}});function validateBoolean2(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE2(name,\"boolean\",value)}var validateObject2=hideStackFrames((value,name,options)=>{const useDefaultOptions=options==null,allowArray=useDefaultOptions\?!1:options.allowArray,allowFunction=useDefaultOptions\?!1:options.allowFunction;if(!(useDefaultOptions\?!1:options.nullable)&&value===null||!allowArray&&ArrayIsArray2(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE2(name,\"Object\",value)}),validateArray=hideStackFrames((value,name,minLength=0)=>{if(!ArrayIsArray2(value))throw new ERR_INVALID_ARG_TYPE2(name,\"Array\",value);if(value.length{if(!isArrayBufferView(buffer))throw new ERR_INVALID_ARG_TYPE2(name,[\"Buffer\",\"TypedArray\",\"DataView\"],buffer)});function validateEncoding(data,encoding){const normalizedEncoding=normalizeEncoding(encoding),length=data.length;if(normalizedEncoding===\"hex\"&&length%2!==0)throw new ERR_INVALID_ARG_VALUE2(\"encoding\",encoding,`is invalid for data of length ${length}`)}function validatePort(port,name=\"Port\",allowZero=!0){if(typeof port!==\"number\"&&typeof port!==\"string\"||typeof port===\"string\"&&StringPrototypeTrim(port).length===0||+port!==+port>>>0||port>65535||port===0&&!allowZero)throw new ERR_SOCKET_BAD_PORT(name,port,allowZero);return port|0}var validateAbortSignal=hideStackFrames((signal,name)=>{if(signal!==void 0&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE2(name,\"AbortSignal\",signal)}),validateFunction=hideStackFrames((value,name)=>{if(typeof value!==\"function\")throw new ERR_INVALID_ARG_TYPE2(name,\"Function\",value)}),validatePlainFunction=hideStackFrames((value,name)=>{if(typeof value!==\"function\"||isAsyncFunction(value))throw new ERR_INVALID_ARG_TYPE2(name,\"Function\",value)}),validateUndefined=hideStackFrames((value,name)=>{if(value!==void 0)throw new ERR_INVALID_ARG_TYPE2(name,\"undefined\",value)});module.exports={isInt32,isUint32,parseFileMode,validateArray,validateBoolean:validateBoolean2,validateBuffer,validateEncoding,validateFunction,validateInt32,validateInteger,validateNumber,validateObject:validateObject2,validateOneOf,validatePlainFunction,validatePort,validateSignalName,validateString:validateString2,validateUint32,validateUndefined,validateAbortSignal}}}),require_utils=__commonJS({\"node_modules/readable-stream/lib/internal/streams/utils.js\"(exports2,module){var{Symbol:Symbol2,SymbolAsyncIterator,SymbolIterator}=require_primordials(),kDestroyed=Symbol2(\"kDestroyed\"),kIsErrored=Symbol2(\"kIsErrored\"),kIsReadable=Symbol2(\"kIsReadable\"),kIsDisturbed=Symbol2(\"kIsDisturbed\");function isReadableNodeStream(obj,strict=!1){var _obj$_readableState;return!!(obj&&typeof obj.pipe===\"function\"&&typeof obj.on===\"function\"&&(!strict||typeof obj.pause===\"function\"&&typeof obj.resume===\"function\")&&(!obj._writableState||((_obj$_readableState=obj._readableState)===null||_obj$_readableState===void 0\?void 0:_obj$_readableState.readable)!==!1)&&(!obj._writableState||obj._readableState))}function isWritableNodeStream(obj){var _obj$_writableState;return!!(obj&&typeof obj.write===\"function\"&&typeof obj.on===\"function\"&&(!obj._readableState||((_obj$_writableState=obj._writableState)===null||_obj$_writableState===void 0\?void 0:_obj$_writableState.writable)!==!1))}function isDuplexNodeStream(obj){return!!(obj&&typeof obj.pipe===\"function\"&&obj._readableState&&typeof obj.on===\"function\"&&typeof obj.write===\"function\")}function isNodeStream(obj){return obj&&(obj._readableState||obj._writableState||typeof obj.write===\"function\"&&typeof obj.on===\"function\"||typeof obj.pipe===\"function\"&&typeof obj.on===\"function\")}function isIterable(obj,isAsync){if(obj==null)return!1;if(isAsync===!0)return typeof obj[SymbolAsyncIterator]===\"function\";if(isAsync===!1)return typeof obj[SymbolIterator]===\"function\";return typeof obj[SymbolAsyncIterator]===\"function\"||typeof obj[SymbolIterator]===\"function\"}function isDestroyed(stream){if(!isNodeStream(stream))return null;const{_writableState:wState,_readableState:rState}=stream,state=wState||rState;return!!(stream.destroyed||stream[kDestroyed]||state!==null&&state!==void 0&&state.destroyed)}function isWritableEnded(stream){if(!isWritableNodeStream(stream))return null;if(stream.writableEnded===!0)return!0;const wState=stream._writableState;if(wState!==null&&wState!==void 0&&wState.errored)return!1;if(typeof(wState===null||wState===void 0\?void 0:wState.ended)!==\"boolean\")return null;return wState.ended}function isWritableFinished(stream,strict){if(!isWritableNodeStream(stream))return null;if(stream.writableFinished===!0)return!0;const wState=stream._writableState;if(wState!==null&&wState!==void 0&&wState.errored)return!1;if(typeof(wState===null||wState===void 0\?void 0:wState.finished)!==\"boolean\")return null;return!!(wState.finished||strict===!1&&wState.ended===!0&&wState.length===0)}function isReadableEnded(stream){if(!isReadableNodeStream(stream))return null;if(stream.readableEnded===!0)return!0;const rState=stream._readableState;if(!rState||rState.errored)return!1;if(typeof(rState===null||rState===void 0\?void 0:rState.ended)!==\"boolean\")return null;return rState.ended}function isReadableFinished(stream,strict){if(!isReadableNodeStream(stream))return null;const rState=stream._readableState;if(rState!==null&&rState!==void 0&&rState.errored)return!1;if(typeof(rState===null||rState===void 0\?void 0:rState.endEmitted)!==\"boolean\")return null;return!!(rState.endEmitted||strict===!1&&rState.ended===!0&&rState.length===0)}function isReadable(stream){if(stream&&stream[kIsReadable]!=null)return stream[kIsReadable];if(typeof(stream===null||stream===void 0\?void 0:stream.readable)!==\"boolean\")return null;if(isDestroyed(stream))return!1;return isReadableNodeStream(stream)&&stream.readable&&!isReadableFinished(stream)}function isWritable(stream){if(typeof(stream===null||stream===void 0\?void 0:stream.writable)!==\"boolean\")return null;if(isDestroyed(stream))return!1;return isWritableNodeStream(stream)&&stream.writable&&!isWritableEnded(stream)}function isFinished(stream,opts){if(!isNodeStream(stream))return null;if(isDestroyed(stream))return!0;if((opts===null||opts===void 0\?void 0:opts.readable)!==!1&&isReadable(stream))return!1;if((opts===null||opts===void 0\?void 0:opts.writable)!==!1&&isWritable(stream))return!1;return!0}function isWritableErrored(stream){var _stream$_writableStat,_stream$_writableStat2;if(!isNodeStream(stream))return null;if(stream.writableErrored)return stream.writableErrored;return(_stream$_writableStat=(_stream$_writableStat2=stream._writableState)===null||_stream$_writableStat2===void 0\?void 0:_stream$_writableStat2.errored)!==null&&_stream$_writableStat!==void 0\?_stream$_writableStat:null}function isReadableErrored(stream){var _stream$_readableStat,_stream$_readableStat2;if(!isNodeStream(stream))return null;if(stream.readableErrored)return stream.readableErrored;return(_stream$_readableStat=(_stream$_readableStat2=stream._readableState)===null||_stream$_readableStat2===void 0\?void 0:_stream$_readableStat2.errored)!==null&&_stream$_readableStat!==void 0\?_stream$_readableStat:null}function isClosed(stream){if(!isNodeStream(stream))return null;if(typeof stream.closed===\"boolean\")return stream.closed;const{_writableState:wState,_readableState:rState}=stream;if(typeof(wState===null||wState===void 0\?void 0:wState.closed)===\"boolean\"||typeof(rState===null||rState===void 0\?void 0:rState.closed)===\"boolean\")return(wState===null||wState===void 0\?void 0:wState.closed)||(rState===null||rState===void 0\?void 0:rState.closed);if(typeof stream._closed===\"boolean\"&&isOutgoingMessage(stream))return stream._closed;return null}function isOutgoingMessage(stream){return typeof stream._closed===\"boolean\"&&typeof stream._defaultKeepAlive===\"boolean\"&&typeof stream._removedConnection===\"boolean\"&&typeof stream._removedContLen===\"boolean\"}function isServerResponse(stream){return typeof stream._sent100===\"boolean\"&&isOutgoingMessage(stream)}function isServerRequest(stream){var _stream$req;return typeof stream._consuming===\"boolean\"&&typeof stream._dumped===\"boolean\"&&((_stream$req=stream.req)===null||_stream$req===void 0\?void 0:_stream$req.upgradeOrConnect)===void 0}function willEmitClose(stream){if(!isNodeStream(stream))return null;const{_writableState:wState,_readableState:rState}=stream,state=wState||rState;return!state&&isServerResponse(stream)||!!(state&&state.autoDestroy&&state.emitClose&&state.closed===!1)}function isDisturbed(stream){var _stream$kIsDisturbed;return!!(stream&&((_stream$kIsDisturbed=stream[kIsDisturbed])!==null&&_stream$kIsDisturbed!==void 0\?_stream$kIsDisturbed:stream.readableDidRead||stream.readableAborted))}function isErrored(stream){var _ref,_ref2,_ref3,_ref4,_ref5,_stream$kIsErrored,_stream$_readableStat3,_stream$_writableStat3,_stream$_readableStat4,_stream$_writableStat4;return!!(stream&&((_ref=(_ref2=(_ref3=(_ref4=(_ref5=(_stream$kIsErrored=stream[kIsErrored])!==null&&_stream$kIsErrored!==void 0\?_stream$kIsErrored:stream.readableErrored)!==null&&_ref5!==void 0\?_ref5:stream.writableErrored)!==null&&_ref4!==void 0\?_ref4:(_stream$_readableStat3=stream._readableState)===null||_stream$_readableStat3===void 0\?void 0:_stream$_readableStat3.errorEmitted)!==null&&_ref3!==void 0\?_ref3:(_stream$_writableStat3=stream._writableState)===null||_stream$_writableStat3===void 0\?void 0:_stream$_writableStat3.errorEmitted)!==null&&_ref2!==void 0\?_ref2:(_stream$_readableStat4=stream._readableState)===null||_stream$_readableStat4===void 0\?void 0:_stream$_readableStat4.errored)!==null&&_ref!==void 0\?_ref:(_stream$_writableStat4=stream._writableState)===null||_stream$_writableStat4===void 0\?void 0:_stream$_writableStat4.errored))}module.exports={kDestroyed,isDisturbed,kIsDisturbed,isErrored,kIsErrored,isReadable,kIsReadable,isClosed,isDestroyed,isDuplexNodeStream,isFinished,isIterable,isReadableNodeStream,isReadableEnded,isReadableFinished,isReadableErrored,isNodeStream,isWritable,isWritableNodeStream,isWritableEnded,isWritableFinished,isWritableErrored,isServerRequest,isServerResponse,willEmitClose}}}),require_end_of_stream=__commonJS({\"node_modules/readable-stream/lib/internal/streams/end-of-stream.js\"(exports2,module){var{AbortError:AbortError2,codes}=require_errors(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_STREAM_PREMATURE_CLOSE}=codes,{once}=require_util(),{validateAbortSignal,validateFunction,validateObject:validateObject2}=require_validators(),{Promise:Promise2}=require_primordials(),{isClosed,isReadable,isReadableNodeStream,isReadableFinished,isReadableErrored,isWritable,isWritableNodeStream,isWritableFinished,isWritableErrored,isNodeStream,willEmitClose:_willEmitClose}=require_utils();function isRequest(stream){return stream.setHeader&&typeof stream.abort===\"function\"}var nop=()=>{};function eos(stream,options,callback){var _options$readable,_options$writable;if(arguments.length===2)callback=options,options={};else if(options==null)options={};else validateObject2(options,\"options\");validateFunction(callback,\"callback\"),validateAbortSignal(options.signal,\"options.signal\"),callback=once(callback);const readable=(_options$readable=options.readable)!==null&&_options$readable!==void 0\?_options$readable:isReadableNodeStream(stream),writable=(_options$writable=options.writable)!==null&&_options$writable!==void 0\?_options$writable:isWritableNodeStream(stream);if(!isNodeStream(stream))throw new ERR_INVALID_ARG_TYPE2(\"stream\",\"Stream\",stream);const{_writableState:wState,_readableState:rState}=stream,onlegacyfinish=()=>{if(!stream.writable)onfinish()};let willEmitClose=_willEmitClose(stream)&&isReadableNodeStream(stream)===readable&&isWritableNodeStream(stream)===writable,writableFinished=isWritableFinished(stream,!1);const onfinish=()=>{if(writableFinished=!0,stream.destroyed)willEmitClose=!1;if(willEmitClose&&(!stream.readable||readable))return;if(!readable||readableFinished)callback.call(stream)};let readableFinished=isReadableFinished(stream,!1);const onend=()=>{if(readableFinished=!0,stream.destroyed)willEmitClose=!1;if(willEmitClose&&(!stream.writable||writable))return;if(!writable||writableFinished)callback.call(stream)},onerror=(err)=>{callback.call(stream,err)};let closed=isClosed(stream);const onclose=()=>{closed=!0;const errored=isWritableErrored(stream)||isReadableErrored(stream);if(errored&&typeof errored!==\"boolean\")return callback.call(stream,errored);if(readable&&!readableFinished&&isReadableNodeStream(stream,!0)){if(!isReadableFinished(stream,!1))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}if(writable&&!writableFinished){if(!isWritableFinished(stream,!1))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}callback.call(stream)},onrequest=()=>{stream.req.on(\"finish\",onfinish)};if(isRequest(stream)){if(stream.on(\"complete\",onfinish),!willEmitClose)stream.on(\"abort\",onclose);if(stream.req)onrequest();else stream.on(\"request\",onrequest)}else if(writable&&!wState)stream.on(\"end\",onlegacyfinish),stream.on(\"close\",onlegacyfinish);if(!willEmitClose&&typeof stream.aborted===\"boolean\")stream.on(\"aborted\",onclose);if(stream.on(\"end\",onend),stream.on(\"finish\",onfinish),options.error!==!1)stream.on(\"error\",onerror);if(stream.on(\"close\",onclose),closed)runOnNextTick(onclose);else if(wState!==null&&wState!==void 0&&wState.errorEmitted||rState!==null&&rState!==void 0&&rState.errorEmitted){if(!willEmitClose)runOnNextTick(onclose)}else if(!readable&&(!willEmitClose||isReadable(stream))&&(writableFinished||isWritable(stream)===!1))runOnNextTick(onclose);else if(!writable&&(!willEmitClose||isWritable(stream))&&(readableFinished||isReadable(stream)===!1))runOnNextTick(onclose);else if(rState&&stream.req&&stream.aborted)runOnNextTick(onclose);const cleanup=()=>{if(callback=nop,stream.removeListener(\"aborted\",onclose),stream.removeListener(\"complete\",onfinish),stream.removeListener(\"abort\",onclose),stream.removeListener(\"request\",onrequest),stream.req)stream.req.removeListener(\"finish\",onfinish);stream.removeListener(\"end\",onlegacyfinish),stream.removeListener(\"close\",onlegacyfinish),stream.removeListener(\"finish\",onfinish),stream.removeListener(\"end\",onend),stream.removeListener(\"error\",onerror),stream.removeListener(\"close\",onclose)};if(options.signal&&!closed){const abort=()=>{const endCallback=callback;cleanup(),endCallback.call(stream,new AbortError2(void 0,{cause:options.signal.reason}))};if(options.signal.aborted)runOnNextTick(abort);else{const originalCallback=callback;callback=once((...args)=>{options.signal.removeEventListener(\"abort\",abort),originalCallback.apply(stream,args)}),options.signal.addEventListener(\"abort\",abort)}}return cleanup}function finished2(stream,opts){return new Promise2((resolve,reject)=>{eos(stream,opts,(err)=>{if(err)reject(err);else resolve()})})}module.exports=eos,module.exports.finished=finished2}}),require_operators=__commonJS({\"node_modules/readable-stream/lib/internal/streams/operators.js\"(exports2,module){var{codes:{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_MISSING_ARGS,ERR_OUT_OF_RANGE},AbortError:AbortError2}=require_errors(),{validateAbortSignal,validateInteger,validateObject:validateObject2}=require_validators(),kWeakHandler=require_primordials().Symbol(\"kWeak\"),{finished:finished2}=require_end_of_stream(),{ArrayPrototypePush,MathFloor,Number:Number2,NumberIsNaN,Promise:Promise2,PromiseReject,PromisePrototypeCatch,Symbol:Symbol2}=require_primordials(),kEmpty=Symbol2(\"kEmpty\"),kEof=Symbol2(\"kEof\");function map(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");let concurrency=1;if((options===null||options===void 0\?void 0:options.concurrency)!=null)concurrency=MathFloor(options.concurrency);return validateInteger(concurrency,\"concurrency\",1),async function*map2(){var _options$signal,_options$signal2;const ac=new AbortController,stream=this,queue=[],signal=ac.signal,signalOpt={signal},abort=()=>ac.abort();if(options!==null&&options!==void 0&&(_options$signal=options.signal)!==null&&_options$signal!==void 0&&_options$signal.aborted)abort();options===null||options===void 0||(_options$signal2=options.signal)===null||_options$signal2===void 0||_options$signal2.addEventListener(\"abort\",abort);let next,resume,done=!1;function onDone(){done=!0}async function pump(){try{for await(let val of stream){var _val;if(done)return;if(signal.aborted)throw new AbortError2;try{val=fn(val,signalOpt)}catch(err){val=PromiseReject(err)}if(val===kEmpty)continue;if(typeof((_val=val)===null||_val===void 0\?void 0:_val.catch)===\"function\")val.catch(onDone);if(queue.push(val),next)next(),next=null;if(!done&&queue.length&&queue.length>=concurrency)await new Promise2((resolve)=>{resume=resolve})}queue.push(kEof)}catch(err){const val=PromiseReject(err);PromisePrototypeCatch(val,onDone),queue.push(val)}finally{var _options$signal3;if(done=!0,next)next(),next=null;options===null||options===void 0||(_options$signal3=options.signal)===null||_options$signal3===void 0||_options$signal3.removeEventListener(\"abort\",abort)}}pump();try{while(!0){while(queue.length>0){const val=await queue[0];if(val===kEof)return;if(signal.aborted)throw new AbortError2;if(val!==kEmpty)yield val;if(queue.shift(),resume)resume(),resume=null}await new Promise2((resolve)=>{next=resolve})}}finally{if(ac.abort(),done=!0,resume)resume(),resume=null}}.call(this)}function asIndexedPairs(options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return async function*asIndexedPairs2(){let index=0;for await(let val of this){var _options$signal4;if(options!==null&&options!==void 0&&(_options$signal4=options.signal)!==null&&_options$signal4!==void 0&&_options$signal4.aborted)throw new AbortError2({cause:options.signal.reason});yield[index++,val]}}.call(this)}async function some(fn,options=void 0){for await(let unused of filter.call(this,fn,options))return!0;return!1}async function every(fn,options=void 0){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);return!await some.call(this,async(...args)=>{return!await fn(...args)},options)}async function find(fn,options){for await(let result of filter.call(this,fn,options))return result;return}async function forEach(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);async function forEachFn(value,options2){return await fn(value,options2),kEmpty}for await(let unused of map.call(this,forEachFn,options));}function filter(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);async function filterFn(value,options2){if(await fn(value,options2))return value;return kEmpty}return map.call(this,filterFn,options)}var ReduceAwareErrMissingArgs=class extends ERR_MISSING_ARGS{constructor(){super(\"reduce\");this.message=\"Reduce of an empty stream requires an initial value\"}};async function reduce(reducer,initialValue,options){var _options$signal5;if(typeof reducer!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"reducer\",[\"Function\",\"AsyncFunction\"],reducer);if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");let hasInitialValue=arguments.length>1;if(options!==null&&options!==void 0&&(_options$signal5=options.signal)!==null&&_options$signal5!==void 0&&_options$signal5.aborted){const err=new AbortError2(void 0,{cause:options.signal.reason});throw this.once(\"error\",()=>{}),await finished2(this.destroy(err)),err}const ac=new AbortController,signal=ac.signal;if(options!==null&&options!==void 0&&options.signal){const opts={once:!0,[kWeakHandler]:this};options.signal.addEventListener(\"abort\",()=>ac.abort(),opts)}let gotAnyItemFromStream=!1;try{for await(let value of this){var _options$signal6;if(gotAnyItemFromStream=!0,options!==null&&options!==void 0&&(_options$signal6=options.signal)!==null&&_options$signal6!==void 0&&_options$signal6.aborted)throw new AbortError2;if(!hasInitialValue)initialValue=value,hasInitialValue=!0;else initialValue=await reducer(initialValue,value,{signal})}if(!gotAnyItemFromStream&&!hasInitialValue)throw new ReduceAwareErrMissingArgs}finally{ac.abort()}return initialValue}async function toArray(options){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");const result=[];for await(let val of this){var _options$signal7;if(options!==null&&options!==void 0&&(_options$signal7=options.signal)!==null&&_options$signal7!==void 0&&_options$signal7.aborted)throw new AbortError2(void 0,{cause:options.signal.reason});ArrayPrototypePush(result,val)}return result}function flatMap(fn,options){const values=map.call(this,fn,options);return async function*flatMap2(){for await(let val of values)yield*val}.call(this)}function toIntegerOrInfinity(number){if(number=Number2(number),NumberIsNaN(number))return 0;if(number<0)throw new ERR_OUT_OF_RANGE(\"number\",\">= 0\",number);return number}function drop(number,options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return number=toIntegerOrInfinity(number),async function*drop2(){var _options$signal8;if(options!==null&&options!==void 0&&(_options$signal8=options.signal)!==null&&_options$signal8!==void 0&&_options$signal8.aborted)throw new AbortError2;for await(let val of this){var _options$signal9;if(options!==null&&options!==void 0&&(_options$signal9=options.signal)!==null&&_options$signal9!==void 0&&_options$signal9.aborted)throw new AbortError2;if(number--<=0)yield val}}.call(this)}function take(number,options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return number=toIntegerOrInfinity(number),async function*take2(){var _options$signal10;if(options!==null&&options!==void 0&&(_options$signal10=options.signal)!==null&&_options$signal10!==void 0&&_options$signal10.aborted)throw new AbortError2;for await(let val of this){var _options$signal11;if(options!==null&&options!==void 0&&(_options$signal11=options.signal)!==null&&_options$signal11!==void 0&&_options$signal11.aborted)throw new AbortError2;if(number-- >0)yield val;else return}}.call(this)}module.exports.streamReturningOperators={asIndexedPairs,drop,filter,flatMap,map,take},module.exports.promiseReturningOperators={every,forEach,reduce,toArray,some,find}}}),require_destroy=__commonJS({\"node_modules/readable-stream/lib/internal/streams/destroy.js\"(exports2,module){var{aggregateTwoErrors,codes:{ERR_MULTIPLE_CALLBACK},AbortError:AbortError2}=require_errors(),{Symbol:Symbol2}=require_primordials(),{kDestroyed,isDestroyed,isFinished,isServerRequest}=require_utils(),kDestroy=\"#kDestroy\",kConstruct=\"#kConstruct\";function checkError(err,w,r){if(err){if(err.stack,w&&!w.errored)w.errored=err;if(r&&!r.errored)r.errored=err}}function destroy2(err,cb){const r=this._readableState,w=this._writableState,s=w||r;if(w&&w.destroyed||r&&r.destroyed){if(typeof cb===\"function\")cb();return this}if(checkError(err,w,r),w)w.destroyed=!0;if(r)r.destroyed=!0;if(!s.constructed)this.once(kDestroy,(er)=>{_destroy(this,aggregateTwoErrors(er,err),cb)});else _destroy(this,err,cb);return this}function _destroy(self,err,cb){let called=!1;function onDestroy(err2){if(called)return;called=!0;const{_readableState:r,_writableState:w}=self;if(checkError(err2,w,r),w)w.closed=!0;if(r)r.closed=!0;if(typeof cb===\"function\")cb(err2);if(err2)runOnNextTick(emitErrorCloseNT,self,err2);else runOnNextTick(emitCloseNT,self)}try{self._destroy(err||null,onDestroy)}catch(err2){onDestroy(err2)}}function emitErrorCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){const{_readableState:r,_writableState:w}=self;if(w)w.closeEmitted=!0;if(r)r.closeEmitted=!0;if(w&&w.emitClose||r&&r.emitClose)self.emit(\"close\")}function emitErrorNT(self,err){const r=self\?._readableState,w=self\?._writableState;if(w\?.errorEmitted||r\?.errorEmitted)return;if(w)w.errorEmitted=!0;if(r)r.errorEmitted=!0;self\?.emit\?.(\"error\",err)}function undestroy(){const r=this._readableState,w=this._writableState;if(r)r.constructed=!0,r.closed=!1,r.closeEmitted=!1,r.destroyed=!1,r.errored=null,r.errorEmitted=!1,r.reading=!1,r.ended=r.readable===!1,r.endEmitted=r.readable===!1;if(w)w.constructed=!0,w.destroyed=!1,w.closed=!1,w.closeEmitted=!1,w.errored=null,w.errorEmitted=!1,w.finalCalled=!1,w.prefinished=!1,w.ended=w.writable===!1,w.ending=w.writable===!1,w.finished=w.writable===!1}function errorOrDestroy2(stream,err,sync){const r=stream\?._readableState,w=stream\?._writableState;if(w&&w.destroyed||r&&r.destroyed)return this;if(r&&r.autoDestroy||w&&w.autoDestroy)stream.destroy(err);else if(err){if(Error.captureStackTrace(err),w&&!w.errored)w.errored=err;if(r&&!r.errored)r.errored=err;if(sync)runOnNextTick(emitErrorNT,stream,err);else emitErrorNT(stream,err)}}function construct(stream,cb){if(typeof stream._construct!==\"function\")return;const{_readableState:r,_writableState:w}=stream;if(r)r.constructed=!1;if(w)w.constructed=!1;if(stream.once(kConstruct,cb),stream.listenerCount(kConstruct)>1)return;runOnNextTick(constructNT,stream)}function constructNT(stream){let called=!1;function onConstruct(err){if(called){errorOrDestroy2(stream,err!==null&&err!==void 0\?err:new ERR_MULTIPLE_CALLBACK);return}called=!0;const{_readableState:r,_writableState:w}=stream,s=w||r;if(r)r.constructed=!0;if(w)w.constructed=!0;if(s.destroyed)stream.emit(kDestroy,err);else if(err)errorOrDestroy2(stream,err,!0);else runOnNextTick(emitConstructNT,stream)}try{stream._construct(onConstruct)}catch(err){onConstruct(err)}}function emitConstructNT(stream){stream.emit(kConstruct)}function isRequest(stream){return stream&&stream.setHeader&&typeof stream.abort===\"function\"}function emitCloseLegacy(stream){stream.emit(\"close\")}function emitErrorCloseLegacy(stream,err){stream.emit(\"error\",err),runOnNextTick(emitCloseLegacy,stream)}function destroyer(stream,err){if(!stream||isDestroyed(stream))return;if(!err&&!isFinished(stream))err=new AbortError2;if(isServerRequest(stream))stream.socket=null,stream.destroy(err);else if(isRequest(stream))stream.abort();else if(isRequest(stream.req))stream.req.abort();else if(typeof stream.destroy===\"function\")stream.destroy(err);else if(typeof stream.close===\"function\")stream.close();else if(err)runOnNextTick(emitErrorCloseLegacy,stream);else runOnNextTick(emitCloseLegacy,stream);if(!stream.destroyed)stream[kDestroyed]=!0}module.exports={construct,destroyer,destroy:destroy2,undestroy,errorOrDestroy:errorOrDestroy2}}}),require_legacy=__commonJS({\"node_modules/readable-stream/lib/internal/streams/legacy.js\"(exports2,module){var{ArrayIsArray:ArrayIsArray2,ObjectSetPrototypeOf}=require_primordials();function Stream(options){if(!(this instanceof Stream))return new Stream(options);EE.call(this,options)}Stream.prototype={},ObjectSetPrototypeOf(Stream.prototype,EE.prototype),ObjectSetPrototypeOf(Stream,EE),Stream.prototype.pipe=function(dest,options){const source=this;function ondata(chunk){if(dest.writable&&dest.write(chunk)===!1&&source.pause)source.pause()}source.on(\"data\",ondata);function ondrain(){if(source.readable&&source.resume)source.resume()}if(dest.on(\"drain\",ondrain),!dest._isStdio&&(!options||options.end!==!1))source.on(\"end\",onend),source.on(\"close\",onclose);let didOnEnd=!1;function onend(){if(didOnEnd)return;didOnEnd=!0,dest.end()}function onclose(){if(didOnEnd)return;if(didOnEnd=!0,typeof dest.destroy===\"function\")dest.destroy()}function onerror(er){if(cleanup(),EE.listenerCount(this,\"error\")===0)this.emit(\"error\",er)}prependListener(source,\"error\",onerror),prependListener(dest,\"error\",onerror);function cleanup(){source.removeListener(\"data\",ondata),dest.removeListener(\"drain\",ondrain),source.removeListener(\"end\",onend),source.removeListener(\"close\",onclose),source.removeListener(\"error\",onerror),dest.removeListener(\"error\",onerror),source.removeListener(\"end\",cleanup),source.removeListener(\"close\",cleanup),dest.removeListener(\"close\",cleanup)}return source.on(\"end\",cleanup),source.on(\"close\",cleanup),dest.on(\"close\",cleanup),dest.emit(\"pipe\",source),dest};function prependListener(emitter,event,fn){if(typeof emitter.prependListener===\"function\")return emitter.prependListener(event,fn);if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(ArrayIsArray2(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}module.exports={Stream,prependListener}}}),require_add_abort_signal=__commonJS({\"node_modules/readable-stream/lib/internal/streams/add-abort-signal.js\"(exports2,module){var{AbortError:AbortError2,codes}=require_errors(),eos=require_end_of_stream(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2}=codes,validateAbortSignal=(signal,name)=>{if(typeof signal!==\"object\"||!(\"aborted\"in signal))throw new ERR_INVALID_ARG_TYPE2(name,\"AbortSignal\",signal)};function isNodeStream(obj){return!!(obj&&typeof obj.pipe===\"function\")}module.exports.addAbortSignal=function addAbortSignal(signal,stream){if(validateAbortSignal(signal,\"signal\"),!isNodeStream(stream))throw new ERR_INVALID_ARG_TYPE2(\"stream\",\"stream.Stream\",stream);return module.exports.addAbortSignalNoValidate(signal,stream)},module.exports.addAbortSignalNoValidate=function(signal,stream){if(typeof signal!==\"object\"||!(\"aborted\"in signal))return stream;const onAbort=()=>{stream.destroy(new AbortError2(void 0,{cause:signal.reason}))};if(signal.aborted)onAbort();else signal.addEventListener(\"abort\",onAbort),eos(stream,()=>signal.removeEventListener(\"abort\",onAbort));return stream}}}),require_state=__commonJS({\"node_modules/readable-stream/lib/internal/streams/state.js\"(exports2,module){var{MathFloor,NumberIsInteger}=require_primordials(),{ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2}=require_errors().codes;function highWaterMarkFrom(options,isDuplex,duplexKey){return options.highWaterMark!=null\?options.highWaterMark:isDuplex\?options[duplexKey]:null}function getDefaultHighWaterMark(objectMode){return objectMode\?16:16384}function getHighWaterMark(state,options,duplexKey,isDuplex){const hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(hwm!=null){if(!NumberIsInteger(hwm)||hwm<0){const name=isDuplex\?`options.${duplexKey}`:\"options.highWaterMark\";throw new ERR_INVALID_ARG_VALUE2(name,hwm)}return MathFloor(hwm)}return getDefaultHighWaterMark(state.objectMode)}module.exports={getHighWaterMark,getDefaultHighWaterMark}}}),require_from=__commonJS({\"node_modules/readable-stream/lib/internal/streams/from.js\"(exports2,module){var{PromisePrototypeThen,SymbolAsyncIterator,SymbolIterator}=require_primordials(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_STREAM_NULL_VALUES}=require_errors().codes;function from(Readable,iterable,opts){let iterator;if(typeof iterable===\"string\"||iterable instanceof Buffer)return new Readable({objectMode:!0,...opts,read(){this.push(iterable),this.push(null)}});let isAsync;if(iterable&&iterable[SymbolAsyncIterator])isAsync=!0,iterator=iterable[SymbolAsyncIterator]();else if(iterable&&iterable[SymbolIterator])isAsync=!1,iterator=iterable[SymbolIterator]();else throw new ERR_INVALID_ARG_TYPE2(\"iterable\",[\"Iterable\"],iterable);const readable=new Readable({objectMode:!0,highWaterMark:1,...opts});let reading=!1;readable._read=function(){if(!reading)reading=!0,next()},readable._destroy=function(error,cb){PromisePrototypeThen(close(error),()=>runOnNextTick(cb,error),(e)=>runOnNextTick(cb,e||error))};async function close(error){const hadError=error!==void 0&&error!==null,hasThrow=typeof iterator.throw===\"function\";if(hadError&&hasThrow){const{value,done}=await iterator.throw(error);if(await value,done)return}if(typeof iterator.return===\"function\"){const{value}=await iterator.return();await value}}async function next(){for(;;){try{const{value,done}=isAsync\?await iterator.next():iterator.next();if(done)readable.push(null);else{const res=value&&typeof value.then===\"function\"\?await value:value;if(res===null)throw reading=!1,new ERR_STREAM_NULL_VALUES;else if(readable.push(res))continue;else reading=!1}}catch(err){readable.destroy(err)}break}}return readable}module.exports=from}}),_ReadableFromWeb,_ReadableFromWebForUndici,require_readable=__commonJS({\"node_modules/readable-stream/lib/internal/streams/readable.js\"(exports2,module){var{ArrayPrototypeIndexOf,NumberIsInteger,NumberIsNaN,NumberParseInt,ObjectDefineProperties,ObjectKeys,ObjectSetPrototypeOf,Promise:Promise2,SafeSet,SymbolAsyncIterator,Symbol:Symbol2}=require_primordials(),ReadableState=globalThis[globalThis.Symbol.for('Bun.lazy')](\"bun:stream\").ReadableState,{Stream,prependListener}=require_legacy();function Readable(options){if(!(this instanceof Readable))return new Readable(options);const isDuplex=this instanceof require_duplex();if(this._readableState=new ReadableState(options,this,isDuplex),options){const{read,destroy:destroy2,construct,signal}=options;if(typeof read===\"function\")this._read=read;if(typeof destroy2===\"function\")this._destroy=destroy2;if(typeof construct===\"function\")this._construct=construct;if(signal&&!isDuplex)addAbortSignal(signal,this)}Stream.call(this,options),destroyImpl.construct(this,()=>{if(this._readableState.needReadable)maybeReadMore(this,this._readableState)})}Readable.prototype={},ObjectSetPrototypeOf(Readable.prototype,Stream.prototype),ObjectSetPrototypeOf(Readable,Stream),Readable.prototype.on=function(ev,fn){const res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;if(ev===\"data\"){if(state.readableListening=this.listenerCount(\"readable\")>0,state.flowing!==!1)this.resume()}else if(ev===\"readable\"){if(!state.endEmitted&&!state.readableListening){if(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,state.length)emitReadable(this,state);else if(!state.reading)runOnNextTick(nReadingNextTick,this)}else if(state.endEmitted);}return res};class ReadableFromWeb extends Readable{#reader;#closed;#pendingChunks;#stream;constructor(options,stream){const{objectMode,highWaterMark,encoding,signal}=options;super({objectMode,highWaterMark,encoding,signal});this.#pendingChunks=[],this.#reader=void 0,this.#stream=stream,this.#closed=!1}#drainPending(){var pendingChunks=this.#pendingChunks,pendingChunksI=0,pendingChunksCount=pendingChunks.length;for(;pendingChunksI0)this.#pendingChunks=[];return!1}#handleDone(reader){reader.releaseLock(),this.#reader=void 0,this.#closed=!0,this.push(null);return}async _read(){var stream=this.#stream,reader=this.#reader;if(stream)reader=this.#reader=stream.getReader(),this.#stream=void 0;else if(this.#drainPending())return;var deferredError;try{do{var done=!1,value;const firstResult=reader.readMany();if(@isPromise(firstResult)){if({done,value}=await firstResult,this.#closed){this.#pendingChunks.push(...value);return}}else({done,value}=firstResult);if(done){this.#handleDone(reader);return}if(!this.push(value[0])){this.#pendingChunks=value.slice(1);return}for(let i=1,count=value.length;i{this.#closed=!0,callback(error)});return}try{callback(error)}catch(error2){globalThis.reportError(error2)}}}_ReadableFromWebForUndici=ReadableFromWeb;function newStreamReadableFromReadableStream(readableStream,options={}){if(!isReadableStream(readableStream))throw new ERR_INVALID_ARG_TYPE2(\"readableStream\",\"ReadableStream\",readableStream);validateObject2(options,\"options\");const{highWaterMark,encoding,objectMode=!1,signal}=options;if(encoding!==void 0&&!Buffer.isEncoding(encoding))throw new ERR_INVALID_ARG_VALUE(encoding,\"options.encoding\");return validateBoolean(objectMode,\"options.objectMode\"),getNativeReadableStream(Readable,readableStream,options)||new ReadableFromWeb({highWaterMark,encoding,objectMode,signal},readableStream)}module.exports=Readable,_ReadableFromWeb=newStreamReadableFromReadableStream;var{addAbortSignal}=require_add_abort_signal(),eos=require_end_of_stream();const{maybeReadMore:_maybeReadMore,resume,emitReadable:_emitReadable,onEofChunk}=globalThis[globalThis.Symbol.for('Bun.lazy')](\"bun:stream\");function maybeReadMore(stream,state){process.nextTick(_maybeReadMore,stream,state)}function emitReadable(stream,state){_emitReadable(stream,state)}var destroyImpl=require_destroy(),{aggregateTwoErrors,codes:{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_METHOD_NOT_IMPLEMENTED,ERR_OUT_OF_RANGE,ERR_STREAM_PUSH_AFTER_EOF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT}}=require_errors(),{validateObject:validateObject2}=require_validators(),from=require_from(),nop=()=>{},{errorOrDestroy:errorOrDestroy2}=destroyImpl;Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype[EE.captureRejectionSymbol]=function(err){this.destroy(err)},Readable.prototype.push=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,!0)};function readableAddChunk(stream,chunk,encoding,addToFront){const state=stream._readableState;let err;if(!state.objectMode){if(typeof chunk===\"string\"){if(encoding=encoding||state.defaultEncoding,state.encoding!==encoding)if(addToFront&&state.encoding)chunk=Buffer.from(chunk,encoding).toString(state.encoding);else chunk=Buffer.from(chunk,encoding),encoding=\"\"}else if(chunk instanceof Buffer)encoding=\"\";else if(Stream._isUint8Array(chunk)){if(addToFront||!state.decoder)chunk=Stream._uint8ArrayToBuffer(chunk);encoding=\"\"}else if(chunk!=null)err=new ERR_INVALID_ARG_TYPE2(\"chunk\",[\"string\",\"Buffer\",\"Uint8Array\"],chunk)}if(err)errorOrDestroy2(stream,err);else if(chunk===null)state.reading=!1,onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(addToFront)if(state.endEmitted)errorOrDestroy2(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);else if(state.destroyed||state.errored)return!1;else addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy2(stream,new ERR_STREAM_PUSH_AFTER_EOF);else if(state.destroyed||state.errored)return!1;else if(state.reading=!1,state.decoder&&!encoding)if(chunk=state.decoder.write(chunk),state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,!1);else maybeReadMore(stream,state);else addChunk(stream,state,chunk,!1);else if(!addToFront)state.reading=!1,maybeReadMore(stream,state);return!state.ended&&(state.length0){if(state.multiAwaitDrain)state.awaitDrainWriters.clear();else state.awaitDrainWriters=null;state.dataEmitted=!0,stream.emit(\"data\",chunk)}else{if(state.length+=state.objectMode\?1:chunk.length,addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream,state)}maybeReadMore(stream,state)}Readable.prototype.isPaused=function(){const state=this._readableState;return state.paused===!0||state.flowing===!1},Readable.prototype.setEncoding=function(enc){const decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;const buffer=this._readableState.buffer;let content=\"\";for(let i=buffer.length;i>0;i--)content+=decoder.write(buffer.shift());if(content!==\"\")buffer.push(content);return this._readableState.length=content.length,this};var MAX_HWM=1073741824;function computeNewHighWaterMark(n){if(n>MAX_HWM)throw new ERR_OUT_OF_RANGE(\"size\",\"<= 1GiB\",n);else n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++;return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(NumberIsNaN(n)){if(state.flowing&&state.length)return state.buffer.first().length;return state.length}if(n<=state.length)return n;return state.ended\?state.length:0}Readable.prototype.read=function(n){if(!NumberIsInteger(n))n=NumberParseInt(n,10);const state=this._readableState,nOrig=n;if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n!==0)state.emittedReadable=!1;if(n===0&&state.needReadable&&((state.highWaterMark!==0\?state.length>=state.highWaterMark:state.length>0)||state.ended)){if(state.length===0&&state.ended)endReadable(this);else emitReadable(this,state);return null}if(n=howMuchToRead(n,state),n===0&&state.ended){if(state.length===0)endReadable(this);return null}let doRead=state.needReadable;if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null)state.needReadable=state.length<=state.highWaterMark,n=0;else if(state.length-=n,state.multiAwaitDrain)state.awaitDrainWriters.clear();else state.awaitDrainWriters=null;if(state.length===0){if(!state.ended)state.needReadable=!0;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null&&!state.errorEmitted&&!state.closeEmitted)state.dataEmitted=!0,this.emit(\"data\",ret);return ret},Readable.prototype._read=function(n){throw new ERR_METHOD_NOT_IMPLEMENTED(\"_read()\")},Readable.prototype.pipe=function(dest,pipeOpts){const src=this,state=this._readableState;if(state.pipes.length===1){if(!state.multiAwaitDrain)state.multiAwaitDrain=!0,state.awaitDrainWriters=new SafeSet(state.awaitDrainWriters\?[state.awaitDrainWriters]:[])}state.pipes.push(dest);const endFn=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr\?onend:unpipe;if(state.endEmitted)runOnNextTick(endFn);else src.once(\"end\",endFn);dest.on(\"unpipe\",onunpipe);function onunpipe(readable,unpipeInfo){if(readable===src){if(unpipeInfo&&unpipeInfo.hasUnpiped===!1)unpipeInfo.hasUnpiped=!0,cleanup()}}function onend(){dest.end()}let ondrain,cleanedUp=!1;function cleanup(){if(dest.removeListener(\"close\",onclose),dest.removeListener(\"finish\",onfinish),ondrain)dest.removeListener(\"drain\",ondrain);if(dest.removeListener(\"error\",onerror),dest.removeListener(\"unpipe\",onunpipe),src.removeListener(\"end\",onend),src.removeListener(\"end\",unpipe),src.removeListener(\"data\",ondata),cleanedUp=!0,ondrain&&state.awaitDrainWriters&&(!dest._writableState||dest._writableState.needDrain))ondrain()}function pause(){if(!cleanedUp){if(state.pipes.length===1&&state.pipes[0]===dest)state.awaitDrainWriters=dest,state.multiAwaitDrain=!1;else if(state.pipes.length>1&&state.pipes.includes(dest))state.awaitDrainWriters.add(dest);src.pause()}if(!ondrain)ondrain=pipeOnDrain(src,dest),dest.on(\"drain\",ondrain)}src.on(\"data\",ondata);function ondata(chunk){if(dest.write(chunk)===!1)pause()}function onerror(er){if(unpipe(),dest.removeListener(\"error\",onerror),dest.listenerCount(\"error\")===0){const s=dest._writableState||dest._readableState;if(s&&!s.errorEmitted)errorOrDestroy2(dest,er);else dest.emit(\"error\",er)}}prependListener(dest,\"error\",onerror);function onclose(){dest.removeListener(\"finish\",onfinish),unpipe()}dest.once(\"close\",onclose);function onfinish(){dest.removeListener(\"close\",onclose),unpipe()}dest.once(\"finish\",onfinish);function unpipe(){src.unpipe(dest)}if(dest.emit(\"pipe\",src),dest.writableNeedDrain===!0){if(state.flowing)pause()}else if(!state.flowing)src.resume();return dest};function pipeOnDrain(src,dest){return function pipeOnDrainFunctionResult(){const state=src._readableState;if(state.awaitDrainWriters===dest)state.awaitDrainWriters=null;else if(state.multiAwaitDrain)state.awaitDrainWriters.delete(dest);if((!state.awaitDrainWriters||state.awaitDrainWriters.size===0)&&src.listenerCount(\"data\"))src.resume()}}Readable.prototype.unpipe=function(dest){const state=this._readableState,unpipeInfo={hasUnpiped:!1};if(state.pipes.length===0)return this;if(!dest){const dests=state.pipes;state.pipes=[],this.pause();for(let i=0;i0,state.resumeScheduled&&state.paused===!1)state.flowing=!0;else if(self.listenerCount(\"data\")>0)self.resume();else if(!state.readableListening)state.flowing=null}function nReadingNextTick(self){self.read(0)}Readable.prototype.resume=function(){const state=this._readableState;if(!state.flowing)state.flowing=!state.readableListening,resume(this,state);return state.paused=!1,this},Readable.prototype.pause=function(){if(this._readableState.flowing!==!1)this._readableState.flowing=!1,this.emit(\"pause\");return this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){let paused=!1;stream.on(\"data\",(chunk)=>{if(!this.push(chunk)&&stream.pause)paused=!0,stream.pause()}),stream.on(\"end\",()=>{this.push(null)}),stream.on(\"error\",(err)=>{errorOrDestroy2(this,err)}),stream.on(\"close\",()=>{this.destroy()}),stream.on(\"destroy\",()=>{this.destroy()}),this._read=()=>{if(paused&&stream.resume)paused=!1,stream.resume()};const streamKeys=ObjectKeys(stream);for(let j=1;j{error=err\?aggregateTwoErrors(error,err):null,callback(),callback=nop});try{while(!0){const chunk=stream.destroyed\?null:stream.read();if(chunk!==null)yield chunk;else if(error)throw error;else if(error===null)return;else await new Promise2(next)}}catch(err){throw error=aggregateTwoErrors(error,err),error}finally{if((error||(options===null||options===void 0\?void 0:options.destroyOnReturn)!==!1)&&(error===void 0||stream._readableState.autoDestroy))destroyImpl.destroyer(stream,null);else stream.off(\"readable\",next),cleanup()}}ObjectDefineProperties(Readable.prototype,{readable:{get(){const r=this._readableState;return!!r&&r.readable!==!1&&!r.destroyed&&!r.errorEmitted&&!r.endEmitted},set(val){if(this._readableState)this._readableState.readable=!!val}},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(state){if(this._readableState)this._readableState.flowing=state}},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(value){if(!this._readableState)return;this._readableState.destroyed=value}},readableEnded:{enumerable:!1,get(){return this._readableState\?this._readableState.endEmitted:!1}}}),Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;let ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){if(state.decoder)ret=state.buffer.join(\"\");else if(state.buffer.length===1)ret=state.buffer.first();else ret=state.buffer.concat(state.length);state.buffer.clear()}else ret=state.buffer.consume(n,state.decoder);return ret}function endReadable(stream){const state=stream._readableState;if(!state.endEmitted)state.ended=!0,runOnNextTick(endReadableNT,state,stream)}function endReadableNT(state,stream){if(!state.errored&&!state.closeEmitted&&!state.endEmitted&&state.length===0){if(state.endEmitted=!0,stream.emit(\"end\"),stream.writable&&stream.allowHalfOpen===!1)runOnNextTick(endWritableNT,stream);else if(state.autoDestroy){const wState=stream._writableState;if(!wState||wState.autoDestroy&&(wState.finished||wState.writable===!1))stream.destroy()}}}function endWritableNT(stream){if(stream.writable&&!stream.writableEnded&&!stream.destroyed)stream.end()}Readable.from=function(iterable,opts){return from(Readable,iterable,opts)};var webStreamsAdapters={newStreamReadableFromReadableStream,newReadableStreamFromStreamReadable(streamReadable,options={}){if(typeof streamReadable\?._readableState!==\"object\")throw new ERR_INVALID_ARG_TYPE2(\"streamReadable\",\"stream.Readable\",streamReadable);var{isDestroyed,isReadable}=require_utils();if(isDestroyed(streamReadable)||!isReadable(streamReadable)){const readable=new ReadableStream;return readable.cancel(),readable}const{readableObjectMode:objectMode,readableHighWaterMark:highWaterMark}=streamReadable,strategy=((strategy2)=>{if(strategy2)return strategy2;if(objectMode)return new CountQueuingStrategy({highWaterMark});return{highWaterMark}})(options\?.strategy);let controller;function onData(chunk){if(controller.enqueue(chunk),controller.desiredSize<=0)streamReadable.pause()}streamReadable.pause();const cleanup=finished(streamReadable,(error)=>{if(error\?.code===\"ERR_STREAM_PREMATURE_CLOSE\")error=new AbortError(void 0,{cause:error});if(cleanup(),streamReadable.on(\"error\",()=>{}),error)return controller.error(error);controller.close()});return streamReadable.on(\"data\",onData),new ReadableStream({start(c){controller=c},pull(){streamReadable.resume()},cancel(reason){destroy(streamReadable,reason)}},strategy)}};Readable.fromWeb=function(readableStream,options){return webStreamsAdapters.newStreamReadableFromReadableStream(readableStream,options)},Readable.toWeb=function(streamReadable,options){return webStreamsAdapters.newReadableStreamFromStreamReadable(streamReadable,options)},Readable.wrap=function(src,options){var _ref,_src$readableObjectMo;return new Readable({objectMode:(_ref=(_src$readableObjectMo=src.readableObjectMode)!==null&&_src$readableObjectMo!==void 0\?_src$readableObjectMo:src.objectMode)!==null&&_ref!==void 0\?_ref:!0,...options,destroy(err,callback){destroyImpl.destroyer(src,err),callback(err)}}).wrap(src)}}}),require_writable=__commonJS({\"node_modules/readable-stream/lib/internal/streams/writable.js\"(exports2,module){var{ArrayPrototypeSlice,Error:Error2,FunctionPrototypeSymbolHasInstance,ObjectDefineProperty,ObjectDefineProperties,ObjectSetPrototypeOf,StringPrototypeToLowerCase,Symbol:Symbol2,SymbolHasInstance}=require_primordials(),Stream=require_legacy().Stream,destroyImpl=require_destroy(),{addAbortSignal}=require_add_abort_signal(),{getHighWaterMark,getDefaultHighWaterMark}=require_state(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED,ERR_STREAM_ALREADY_FINISHED,ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING}=require_errors().codes,{errorOrDestroy:errorOrDestroy2}=destroyImpl;function Writable2(options={}){const isDuplex=this instanceof require_duplex();if(!isDuplex&&!FunctionPrototypeSymbolHasInstance(Writable2,this))return new Writable2(options);if(this._writableState=new WritableState(options,this,isDuplex),options){if(typeof options.write===\"function\")this._write=options.write;if(typeof options.writev===\"function\")this._writev=options.writev;if(typeof options.destroy===\"function\")this._destroy=options.destroy;if(typeof options.final===\"function\")this._final=options.final;if(typeof options.construct===\"function\")this._construct=options.construct;if(options.signal)addAbortSignal(options.signal,this)}Stream.call(this,options),destroyImpl.construct(this,()=>{const state=this._writableState;if(!state.writing)clearBuffer(this,state);finishMaybe(this,state)})}Writable2.prototype={},ObjectSetPrototypeOf(Writable2.prototype,Stream.prototype),ObjectSetPrototypeOf(Writable2,Stream),module.exports=Writable2;function nop(){}var kOnFinished=Symbol2(\"kOnFinished\");function WritableState(options,stream,isDuplex){if(typeof isDuplex!==\"boolean\")isDuplex=stream instanceof require_duplex();if(this.objectMode=!!(options&&options.objectMode),isDuplex)this.objectMode=this.objectMode||!!(options&&options.writableObjectMode);this.highWaterMark=options\?getHighWaterMark(this,options,\"writableHighWaterMark\",isDuplex):getDefaultHighWaterMark(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const noDecode=!!(options&&options.decodeStrings===!1);this.decodeStrings=!noDecode,this.defaultEncoding=options&&options.defaultEncoding||\"utf8\",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=onwrite.bind(void 0,stream),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,resetBuffer(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!options||options.emitClose!==!1,this.autoDestroy=!options||options.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[kOnFinished]=[]}WritableState.prototype={};function resetBuffer(state){state.buffered=[],state.bufferedIndex=0,state.allBuffers=!0,state.allNoop=!0}WritableState.prototype.getBuffer=function getBuffer(){return ArrayPrototypeSlice(this.buffered,this.bufferedIndex)},ObjectDefineProperty(WritableState.prototype,\"bufferedRequestCount\",{get(){return this.buffered.length-this.bufferedIndex}}),ObjectDefineProperty(Writable2,SymbolHasInstance,{value:function(object){if(FunctionPrototypeSymbolHasInstance(this,object))return!0;if(this!==Writable2)return!1;return object&&object._writableState instanceof WritableState}}),Writable2.prototype.pipe=function(){errorOrDestroy2(this,new ERR_STREAM_CANNOT_PIPE)};function _write(stream,chunk,encoding,cb){const state=stream._writableState;if(typeof encoding===\"function\")cb=encoding,encoding=state.defaultEncoding;else{if(!encoding)encoding=state.defaultEncoding;else if(encoding!==\"buffer\"&&!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);if(typeof cb!==\"function\")cb=nop}if(chunk===null)throw new ERR_STREAM_NULL_VALUES;else if(!state.objectMode)if(typeof chunk===\"string\"){if(state.decodeStrings!==!1)chunk=Buffer.from(chunk,encoding),encoding=\"buffer\"}else if(chunk instanceof Buffer)encoding=\"buffer\";else if(Stream._isUint8Array(chunk))chunk=Stream._uint8ArrayToBuffer(chunk),encoding=\"buffer\";else throw new ERR_INVALID_ARG_TYPE2(\"chunk\",[\"string\",\"Buffer\",\"Uint8Array\"],chunk);let err;if(state.ending)err=new ERR_STREAM_WRITE_AFTER_END;else if(state.destroyed)err=new ERR_STREAM_DESTROYED(\"write\");if(err)return runOnNextTick(cb,err),errorOrDestroy2(stream,err,!0),err;return state.pendingcb++,writeOrBuffer(stream,state,chunk,encoding,cb)}Writable2.prototype.write=function(chunk,encoding,cb){return _write(this,chunk,encoding,cb)===!0},Writable2.prototype.cork=function(){this._writableState.corked++},Writable2.prototype.uncork=function(){const state=this._writableState;if(state.corked){if(state.corked--,!state.writing)clearBuffer(this,state)}},Writable2.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding===\"string\")encoding=StringPrototypeToLowerCase(encoding);if(!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this};function writeOrBuffer(stream,state,chunk,encoding,callback){const len=state.objectMode\?1:chunk.length;state.length+=len;const ret=state.lengthstate.bufferedIndex)clearBuffer(stream,state);if(sync)if(state.afterWriteTickInfo!==null&&state.afterWriteTickInfo.cb===cb)state.afterWriteTickInfo.count++;else state.afterWriteTickInfo={count:1,cb,stream,state},runOnNextTick(afterWriteTick,state.afterWriteTickInfo);else afterWrite(stream,state,1,cb)}}function afterWriteTick({stream,state,count,cb}){return state.afterWriteTickInfo=null,afterWrite(stream,state,count,cb)}function afterWrite(stream,state,count,cb){if(!state.ending&&!stream.destroyed&&state.length===0&&state.needDrain)state.needDrain=!1,stream.emit(\"drain\");while(count-- >0)state.pendingcb--,cb();if(state.destroyed)errorBuffer(state);finishMaybe(stream,state)}function errorBuffer(state){if(state.writing)return;for(let n=state.bufferedIndex;n1&&stream._writev){state.pendingcb-=bufferedLength-1;const callback=state.allNoop\?nop:(err)=>{for(let n=i;n256)buffered.splice(0,i),state.bufferedIndex=0;else state.bufferedIndex=i}state.bufferProcessing=!1}Writable2.prototype._write=function(chunk,encoding,cb){if(this._writev)this._writev([{chunk,encoding}],cb);else throw new ERR_METHOD_NOT_IMPLEMENTED(\"_write()\")},Writable2.prototype._writev=null,Writable2.prototype.end=function(chunk,encoding,cb,native=!1){const state=this._writableState;if(typeof chunk===\"function\")cb=chunk,chunk=null,encoding=null;else if(typeof encoding===\"function\")cb=encoding,encoding=null;let err;if(chunk!==null&&chunk!==void 0){let ret;if(!native)ret=_write(this,chunk,encoding);else ret=this.write(chunk,encoding);if(ret instanceof Error2)err=ret}if(state.corked)state.corked=1,this.uncork();if(err)this.emit(\"error\",err);else if(!state.errored&&!state.ending)state.ending=!0,finishMaybe(this,state,!0),state.ended=!0;else if(state.finished)err=new ERR_STREAM_ALREADY_FINISHED(\"end\");else if(state.destroyed)err=new ERR_STREAM_DESTROYED(\"end\");if(typeof cb===\"function\")if(err||state.finished)runOnNextTick(cb,err);else state[kOnFinished].push(cb);return this};function needFinish(state,tag){var needFinish2=state.ending&&!state.destroyed&&state.constructed&&state.length===0&&!state.errored&&state.buffered.length===0&&!state.finished&&!state.writing&&!state.errorEmitted&&!state.closeEmitted;return needFinish2}function callFinal(stream,state){let called=!1;function onFinish(err){if(called){errorOrDestroy2(stream,err!==null&&err!==void 0\?err:ERR_MULTIPLE_CALLBACK());return}if(called=!0,state.pendingcb--,err){const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i{if(needFinish(state2))finish(stream2,state2);else state2.pendingcb--},stream,state);else if(needFinish(state))state.pendingcb++,finish(stream,state)}}function finish(stream,state){state.pendingcb--,state.finished=!0;const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i{if(val!=null)throw new ERR_INVALID_RETURN_VALUE(\"nully\",\"body\",val)},(err)=>{destroyer(d,err)});return d=new Duplexify({objectMode:!0,readable:!1,write,final(cb){final(async()=>{try{await promise,runOnNextTick(cb,null)}catch(err){runOnNextTick(cb,err)}})},destroy:destroy2})}throw new ERR_INVALID_RETURN_VALUE(\"Iterable, AsyncIterable or AsyncFunction\",name,value)}if(isBlob(body))return duplexify(body.arrayBuffer());if(isIterable(body))return from(Duplexify,body,{objectMode:!0,writable:!1});if(typeof(body===null||body===void 0\?void 0:body.writable)===\"object\"||typeof(body===null||body===void 0\?void 0:body.readable)===\"object\"){const readable=body!==null&&body!==void 0&&body.readable\?isReadableNodeStream(body===null||body===void 0\?void 0:body.readable)\?body===null||body===void 0\?void 0:body.readable:duplexify(body.readable):void 0,writable=body!==null&&body!==void 0&&body.writable\?isWritableNodeStream(body===null||body===void 0\?void 0:body.writable)\?body===null||body===void 0\?void 0:body.writable:duplexify(body.writable):void 0;return _duplexify({readable,writable})}const then=body===null||body===void 0\?void 0:body.then;if(typeof then===\"function\"){let d;return FunctionPrototypeCall(then,body,(val)=>{if(val!=null)d.push(val);d.push(null)},(err)=>{destroyer(d,err)}),d=new Duplexify({objectMode:!0,writable:!1,read(){}})}throw new ERR_INVALID_ARG_TYPE2(name,[\"Blob\",\"ReadableStream\",\"WritableStream\",\"Stream\",\"Iterable\",\"AsyncIterable\",\"Function\",\"{ readable, writable } pair\",\"Promise\"],body)};function fromAsyncGen(fn){let{promise,resolve}=createDeferredPromise();const ac=new AbortController,signal=ac.signal;return{value:fn(async function*(){while(!0){const _promise=promise;promise=null;const{chunk,done,cb}=await _promise;if(runOnNextTick(cb),done)return;if(signal.aborted)throw new AbortError2(void 0,{cause:signal.reason});({promise,resolve}=createDeferredPromise()),yield chunk}}(),{signal}),write(chunk,encoding,cb){const _resolve=resolve;resolve=null,_resolve({chunk,done:!1,cb})},final(cb){const _resolve=resolve;resolve=null,_resolve({done:!0,cb})},destroy(err,cb){ac.abort(),cb(err)}}}function _duplexify(pair){const r=pair.readable&&typeof pair.readable.read!==\"function\"\?Readable.wrap(pair.readable):pair.readable,w=pair.writable;let readable=!!isReadable(r),writable=!!isWritable(w),ondrain,onfinish,onreadable,onclose,d;function onfinished(err){const cb=onclose;if(onclose=null,cb)cb(err);else if(err)d.destroy(err);else if(!readable&&!writable)d.destroy()}if(d=new Duplexify({readableObjectMode:!!(r!==null&&r!==void 0&&r.readableObjectMode),writableObjectMode:!!(w!==null&&w!==void 0&&w.writableObjectMode),readable,writable}),writable)eos(w,(err)=>{if(writable=!1,err)destroyer(r,err);onfinished(err)}),d._write=function(chunk,encoding,callback){if(w.write(chunk,encoding))callback();else ondrain=callback},d._final=function(callback){w.end(),onfinish=callback},w.on(\"drain\",function(){if(ondrain){const cb=ondrain;ondrain=null,cb()}}),w.on(\"finish\",function(){if(onfinish){const cb=onfinish;onfinish=null,cb()}});if(readable)eos(r,(err)=>{if(readable=!1,err)destroyer(r,err);onfinished(err)}),r.on(\"readable\",function(){if(onreadable){const cb=onreadable;onreadable=null,cb()}}),r.on(\"end\",function(){d.push(null)}),d._read=function(){while(!0){const buf=r.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf))return}};return d._destroy=function(err,callback){if(!err&&onclose!==null)err=new AbortError2;if(onreadable=null,ondrain=null,onfinish=null,onclose===null)callback(err);else onclose=callback,destroyer(w,err),destroyer(r,err)},d}}}),require_duplex=__commonJS({\"node_modules/readable-stream/lib/internal/streams/duplex.js\"(exports2,module){var{ObjectDefineProperties,ObjectGetOwnPropertyDescriptor,ObjectKeys,ObjectSetPrototypeOf}=require_primordials(),Readable=require_readable();function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);if(Readable.call(this,options),Writable.call(this,options),options){if(this.allowHalfOpen=options.allowHalfOpen!==!1,options.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(options.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}Duplex.prototype={},module.exports=Duplex,ObjectSetPrototypeOf(Duplex.prototype,Readable.prototype),ObjectSetPrototypeOf(Duplex,Readable);for(var method in Writable.prototype)if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method];ObjectDefineProperties(Duplex.prototype,{writable:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writable\"),writableHighWaterMark:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableHighWaterMark\"),writableObjectMode:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableObjectMode\"),writableBuffer:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableBuffer\"),writableLength:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableLength\"),writableFinished:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableFinished\"),writableCorked:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableCorked\"),writableEnded:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableEnded\"),writableNeedDrain:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableNeedDrain\"),destroyed:{get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(value){if(this._readableState&&this._writableState)this._readableState.destroyed=value,this._writableState.destroyed=value}}});var webStreamsAdapters;function lazyWebStreams(){if(webStreamsAdapters===void 0)webStreamsAdapters={};return webStreamsAdapters}Duplex.fromWeb=function(pair,options){return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair,options)},Duplex.toWeb=function(duplex){return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)};var duplexify;Duplex.from=function(body){if(!duplexify)duplexify=require_duplexify();return duplexify(body,\"body\")}}}),require_transform=__commonJS({\"node_modules/readable-stream/lib/internal/streams/transform.js\"(exports2,module){var{ObjectSetPrototypeOf,Symbol:Symbol2}=require_primordials(),{ERR_METHOD_NOT_IMPLEMENTED}=require_errors().codes,Duplex=require_duplex();function Transform(options){if(!(this instanceof Transform))return new Transform(options);if(Duplex.call(this,options),this._readableState.sync=!1,this[kCallback]=null,options){if(typeof options.transform===\"function\")this._transform=options.transform;if(typeof options.flush===\"function\")this._flush=options.flush}this.on(\"prefinish\",prefinish.bind(this))}Transform.prototype={},ObjectSetPrototypeOf(Transform.prototype,Duplex.prototype),ObjectSetPrototypeOf(Transform,Duplex),module.exports=Transform;var kCallback=Symbol2(\"kCallback\");function final(cb){if(typeof this._flush===\"function\"&&!this.destroyed)this._flush((er,data)=>{if(er){if(cb)cb(er);else this.destroy(er);return}if(data!=null)this.push(data);if(this.push(null),cb)cb()});else if(this.push(null),cb)cb()}function prefinish(){if(this._final!==final)final.call(this)}Transform.prototype._final=final,Transform.prototype._transform=function(chunk,encoding,callback){throw new ERR_METHOD_NOT_IMPLEMENTED(\"_transform()\")},Transform.prototype._write=function(chunk,encoding,callback){const rState=this._readableState,wState=this._writableState,length=rState.length;this._transform(chunk,encoding,(err,val)=>{if(err){callback(err);return}if(val!=null)this.push(val);if(wState.ended||length===rState.length||rState.length{finished2=!0});const cleanup=eos(stream,{readable:reading,writable:writing},(err)=>{finished2=!err});return{destroy:(err)=>{if(finished2)return;finished2=!0,destroyImpl.destroyer(stream,err||new ERR_STREAM_DESTROYED(\"pipe\"))},cleanup}}function popCallback(streams){return validateFunction(streams[streams.length-1],\"streams[stream.length - 1]\"),streams.pop()}function makeAsyncIterable(val){if(isIterable(val))return val;else if(isReadableNodeStream(val))return fromReadable(val);throw new ERR_INVALID_ARG_TYPE2(\"val\",[\"Readable\",\"Iterable\",\"AsyncIterable\"],val)}async function*fromReadable(val){if(!Readable)Readable=require_readable();yield*Readable.prototype[SymbolAsyncIterator].call(val)}async function pump(iterable,writable,finish,{end}){let error,onresolve=null;const resume=(err)=>{if(err)error=err;if(onresolve){const callback=onresolve;onresolve=null,callback()}},wait=()=>new Promise2((resolve,reject)=>{if(error)reject(error);else onresolve=()=>{if(error)reject(error);else resolve()}});writable.on(\"drain\",resume);const cleanup=eos(writable,{readable:!1},resume);try{if(writable.writableNeedDrain)await wait();for await(let chunk of iterable)if(!writable.write(chunk))await wait();if(end)writable.end();await wait(),finish()}catch(err){finish(error!==err\?aggregateTwoErrors(error,err):err)}finally{cleanup(),writable.off(\"drain\",resume)}}function pipeline(...streams){return pipelineImpl(streams,once(popCallback(streams)))}function pipelineImpl(streams,callback,opts){if(streams.length===1&&ArrayIsArray2(streams[0]))streams=streams[0];if(streams.length<2)throw new ERR_MISSING_ARGS(\"streams\");const ac=new AbortController,signal=ac.signal,outerSignal=opts===null||opts===void 0\?void 0:opts.signal,lastStreamCleanup=[];validateAbortSignal(outerSignal,\"options.signal\");function abort(){finishImpl(new AbortError2)}outerSignal===null||outerSignal===void 0||outerSignal.addEventListener(\"abort\",abort);let error,value;const destroys=[];let finishCount=0;function finish(err){finishImpl(err,--finishCount===0)}function finishImpl(err,final){if(err&&(!error||error.code===\"ERR_STREAM_PREMATURE_CLOSE\"))error=err;if(!error&&!final)return;while(destroys.length)destroys.shift()(error);if(outerSignal===null||outerSignal===void 0||outerSignal.removeEventListener(\"abort\",abort),ac.abort(),final){if(!error)lastStreamCleanup.forEach((fn)=>fn());runOnNextTick(callback,error,value)}}let ret;for(let i=0;i0,end=reading||(opts===null||opts===void 0\?void 0:opts.end)!==!1,isLastStream=i===streams.length-1;if(isNodeStream(stream)){let onError=function(err){if(err&&err.name!==\"AbortError\"&&err.code!==\"ERR_STREAM_PREMATURE_CLOSE\")finish(err)};if(end){const{destroy:destroy2,cleanup}=destroyer(stream,reading,writing);if(destroys.push(destroy2),isReadable(stream)&&isLastStream)lastStreamCleanup.push(cleanup)}if(stream.on(\"error\",onError),isReadable(stream)&&isLastStream)lastStreamCleanup.push(()=>{stream.removeListener(\"error\",onError)})}if(i===0)if(typeof stream===\"function\"){if(ret=stream({signal}),!isIterable(ret))throw new ERR_INVALID_RETURN_VALUE(\"Iterable, AsyncIterable or Stream\",\"source\",ret)}else if(isIterable(stream)||isReadableNodeStream(stream))ret=stream;else ret=Duplex.from(stream);else if(typeof stream===\"function\")if(ret=makeAsyncIterable(ret),ret=stream(ret,{signal}),reading){if(!isIterable(ret,!0))throw new ERR_INVALID_RETURN_VALUE(\"AsyncIterable\",`transform[${i-1}]`,ret)}else{var _ret;if(!PassThrough)PassThrough=require_passthrough();const pt=new PassThrough({objectMode:!0}),then=(_ret=ret)===null||_ret===void 0\?void 0:_ret.then;if(typeof then===\"function\")finishCount++,then.call(ret,(val)=>{if(value=val,val!=null)pt.write(val);if(end)pt.end();runOnNextTick(finish)},(err)=>{pt.destroy(err),runOnNextTick(finish,err)});else if(isIterable(ret,!0))finishCount++,pump(ret,pt,finish,{end});else throw new ERR_INVALID_RETURN_VALUE(\"AsyncIterable or Promise\",\"destination\",ret);ret=pt;const{destroy:destroy2,cleanup}=destroyer(ret,!1,!0);if(destroys.push(destroy2),isLastStream)lastStreamCleanup.push(cleanup)}else if(isNodeStream(stream)){if(isReadableNodeStream(ret)){finishCount+=2;const cleanup=pipe(ret,stream,finish,{end});if(isReadable(stream)&&isLastStream)lastStreamCleanup.push(cleanup)}else if(isIterable(ret))finishCount++,pump(ret,stream,finish,{end});else throw new ERR_INVALID_ARG_TYPE2(\"val\",[\"Readable\",\"Iterable\",\"AsyncIterable\"],ret);ret=stream}else ret=Duplex.from(stream)}if(signal!==null&&signal!==void 0&&signal.aborted||outerSignal!==null&&outerSignal!==void 0&&outerSignal.aborted)runOnNextTick(abort);return ret}function pipe(src,dst,finish,{end}){if(src.pipe(dst,{end}),end)src.once(\"end\",()=>dst.end());else finish();return eos(src,{readable:!0,writable:!1},(err)=>{const rState=src._readableState;if(err&&err.code===\"ERR_STREAM_PREMATURE_CLOSE\"&&rState&&rState.ended&&!rState.errored&&!rState.errorEmitted)src.once(\"end\",finish).once(\"error\",finish);else finish(err)}),eos(dst,{readable:!1,writable:!0},finish)}module.exports={pipelineImpl,pipeline}}}),require_compose=__commonJS({\"node_modules/readable-stream/lib/internal/streams/compose.js\"(exports2,module){var{pipeline}=require_pipeline(),Duplex=require_duplex(),{destroyer}=require_destroy(),{isNodeStream,isReadable,isWritable}=require_utils(),{AbortError:AbortError2,codes:{ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2,ERR_MISSING_ARGS}}=require_errors();module.exports=function compose(...streams){if(streams.length===0)throw new ERR_MISSING_ARGS(\"streams\");if(streams.length===1)return Duplex.from(streams[0]);const orgStreams=[...streams];if(typeof streams[0]===\"function\")streams[0]=Duplex.from(streams[0]);if(typeof streams[streams.length-1]===\"function\"){const idx=streams.length-1;streams[idx]=Duplex.from(streams[idx])}for(let n=0;n0&&!isWritable(streams[n]))throw new ERR_INVALID_ARG_VALUE2(`streams[${n}]`,orgStreams[n],\"must be writable\")}let ondrain,onfinish,onreadable,onclose,d;function onfinished(err){const cb=onclose;if(onclose=null,cb)cb(err);else if(err)d.destroy(err);else if(!readable&&!writable)d.destroy()}const head=streams[0],tail=pipeline(streams,onfinished),writable=!!isWritable(head),readable=!!isReadable(tail);if(d=new Duplex({writableObjectMode:!!(head!==null&&head!==void 0&&head.writableObjectMode),readableObjectMode:!!(tail!==null&&tail!==void 0&&tail.writableObjectMode),writable,readable}),writable)d._write=function(chunk,encoding,callback){if(head.write(chunk,encoding))callback();else ondrain=callback},d._final=function(callback){head.end(),onfinish=callback},head.on(\"drain\",function(){if(ondrain){const cb=ondrain;ondrain=null,cb()}}),tail.on(\"finish\",function(){if(onfinish){const cb=onfinish;onfinish=null,cb()}});if(readable)tail.on(\"readable\",function(){if(onreadable){const cb=onreadable;onreadable=null,cb()}}),tail.on(\"end\",function(){d.push(null)}),d._read=function(){while(!0){const buf=tail.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf))return}};return d._destroy=function(err,callback){if(!err&&onclose!==null)err=new AbortError2;if(onreadable=null,ondrain=null,onfinish=null,onclose===null)callback(err);else onclose=callback,destroyer(tail,err)},d}}}),require_promises=__commonJS({\"node_modules/readable-stream/lib/stream/promises.js\"(exports2,module){var{ArrayPrototypePop,Promise:Promise2}=require_primordials(),{isIterable,isNodeStream}=require_utils(),{pipelineImpl:pl}=require_pipeline(),{finished:finished2}=require_end_of_stream();function pipeline(...streams){return new Promise2((resolve,reject)=>{let signal,end;const lastArg=streams[streams.length-1];if(lastArg&&typeof lastArg===\"object\"&&!isNodeStream(lastArg)&&!isIterable(lastArg)){const options=ArrayPrototypePop(streams);signal=options.signal,end=options.end}pl(streams,(err,value)=>{if(err)reject(err);else resolve(value)},{signal,end})})}module.exports={finished:finished2,pipeline}}}),require_stream=__commonJS({\"node_modules/readable-stream/lib/stream.js\"(exports2,module){var{ObjectDefineProperty,ObjectKeys,ReflectApply}=require_primordials(),{promisify:{custom:customPromisify}}=require_util(),{streamReturningOperators,promiseReturningOperators}=require_operators(),{codes:{ERR_ILLEGAL_CONSTRUCTOR}}=require_errors(),compose=require_compose(),{pipeline}=require_pipeline(),{destroyer}=require_destroy(),eos=require_end_of_stream(),promises2=require_promises(),utils=require_utils(),Stream=module.exports=require_legacy().Stream;Stream.isDisturbed=utils.isDisturbed,Stream.isErrored=utils.isErrored,Stream.isWritable=utils.isWritable,Stream.isReadable=utils.isReadable,Stream.Readable=require_readable();for(let key of ObjectKeys(streamReturningOperators)){let fn=function(...args){if(new.target)throw ERR_ILLEGAL_CONSTRUCTOR();return Stream.Readable.from(ReflectApply(op,this,args))};const op=streamReturningOperators[key];ObjectDefineProperty(fn,\"name\",{value:op.name}),ObjectDefineProperty(fn,\"length\",{value:op.length}),ObjectDefineProperty(Stream.Readable.prototype,key,{value:fn,enumerable:!1,configurable:!0,writable:!0})}for(let key of ObjectKeys(promiseReturningOperators)){let fn=function(...args){if(new.target)throw ERR_ILLEGAL_CONSTRUCTOR();return ReflectApply(op,this,args)};const op=promiseReturningOperators[key];ObjectDefineProperty(fn,\"name\",{value:op.name}),ObjectDefineProperty(fn,\"length\",{value:op.length}),ObjectDefineProperty(Stream.Readable.prototype,key,{value:fn,enumerable:!1,configurable:!0,writable:!0})}Stream.Writable=require_writable(),Stream.Duplex=require_duplex(),Stream.Transform=require_transform(),Stream.PassThrough=require_passthrough(),Stream.pipeline=pipeline;var{addAbortSignal}=require_add_abort_signal();Stream.addAbortSignal=addAbortSignal,Stream.finished=eos,Stream.destroy=destroyer,Stream.compose=compose,ObjectDefineProperty(Stream,\"promises\",{configurable:!0,enumerable:!0,get(){return promises2}}),ObjectDefineProperty(pipeline,customPromisify,{enumerable:!0,get(){return promises2.pipeline}}),ObjectDefineProperty(eos,customPromisify,{enumerable:!0,get(){return promises2.finished}}),Stream.Stream=Stream,Stream._isUint8Array=function isUint8Array(value){return value instanceof Uint8Array},Stream._uint8ArrayToBuffer=function _uint8ArrayToBuffer(chunk){return new Buffer(chunk.buffer,chunk.byteOffset,chunk.byteLength)}}});function createNativeStreamReadable(nativeType,Readable){var[pull,start,cancel,setClose,deinit,updateRef,drainFn]=globalThis[globalThis.Symbol.for('Bun.lazy')](nativeType),closer=[!1],handleNumberResult=function(nativeReadable,result,view,isClosed){if(result>0){const slice=view.subarray(0,result),remainder=view.subarray(result);if(slice.byteLength>0)nativeReadable.push(slice);if(isClosed)nativeReadable.push(null);return remainder.byteLength>0\?remainder:void 0}if(isClosed)nativeReadable.push(null);return view},handleArrayBufferViewResult=function(nativeReadable,result,view,isClosed){if(result.byteLength>0)nativeReadable.push(result);if(isClosed)nativeReadable.push(null);return view},DYNAMICALLY_ADJUST_CHUNK_SIZE=process.env.BUN_DISABLE_DYNAMIC_CHUNK_SIZE!==\"1\";const finalizer=new FinalizationRegistry((ptr)=>ptr&&deinit(ptr)),MIN_BUFFER_SIZE=512;var NativeReadable=class NativeReadable2 extends Readable{#bunNativePtr;#refCount=1;#constructed=!1;#remainingChunk=void 0;#highWaterMark;#pendingRead=!1;#hasResized=!DYNAMICALLY_ADJUST_CHUNK_SIZE;#unregisterToken;constructor(ptr,options={}){super(options);if(typeof options.highWaterMark===\"number\")this.#highWaterMark=options.highWaterMark;else this.#highWaterMark=262144;this.#bunNativePtr=ptr,this.#constructed=!1,this.#remainingChunk=void 0,this.#pendingRead=!1,this.#unregisterToken={},finalizer.register(this,this.#bunNativePtr,this.#unregisterToken)}_read(maxToRead){if(this.#pendingRead)return;var ptr=this.#bunNativePtr;if(ptr===0){this.push(null);return}if(!this.#constructed)this.#internalConstruct(ptr);return this.#internalRead(this.#getRemainingChunk(maxToRead),ptr)}#internalConstruct(ptr){this.#constructed=!0;const result=start(ptr,this.#highWaterMark);if(typeof result===\"number\"&&result>1)this.#hasResized=!0,this.#highWaterMark=Math.min(this.#highWaterMark,result);if(drainFn){const drainResult=drainFn(ptr);if((drainResult\?.byteLength\?\?0)>0)this.push(drainResult)}}#getRemainingChunk(maxToRead=this.#highWaterMark){var chunk=this.#remainingChunk;if(chunk\?.byteLength\?\?0MIN_BUFFER_SIZE\?maxToRead:MIN_BUFFER_SIZE;this.#remainingChunk=chunk=new Buffer(size)}return chunk}#handleResult(result,view,isClosed){if(typeof result===\"number\"){if(result>=this.#highWaterMark&&!this.#hasResized&&!isClosed)this.#highWaterMark*=2,this.#hasResized=!0;return handleNumberResult(this,result,view,isClosed)}else if(typeof result===\"boolean\")return process.nextTick(()=>{this.push(null)}),view\?.byteLength\?\?0>0\?view:void 0;else if(ArrayBuffer.isView(result)){if(result.byteLength>=this.#highWaterMark&&!this.#hasResized&&!isClosed)this.#highWaterMark*=2,this.#hasResized=!0;return handleArrayBufferViewResult(this,result,view,isClosed)}else throw new Error(\"Invalid result from pull\")}#internalRead(view,ptr){closer[0]=!1;var result=pull(ptr,view,closer);if(@isPromise(result))return this.#pendingRead=!0,result.then((result2)=>{this.#pendingRead=!1,this.#remainingChunk=this.#handleResult(result2,view,closer[0])},(reason)=>{errorOrDestroy(this,reason)});else this.#remainingChunk=this.#handleResult(result,view,closer[0])}_destroy(error,callback){var ptr=this.#bunNativePtr;if(ptr===0){callback(error);return}if(finalizer.unregister(this.#unregisterToken),this.#bunNativePtr=0,updateRef)updateRef(ptr,!1);cancel(ptr,error),callback(error)}ref(){var ptr=this.#bunNativePtr;if(ptr===0)return;if(this.#refCount++===0)updateRef(ptr,!0)}unref(){var ptr=this.#bunNativePtr;if(ptr===0)return;if(this.#refCount--===1)updateRef(ptr,!1)}};if(!updateRef)NativeReadable.prototype.ref=void 0,NativeReadable.prototype.unref=void 0;return NativeReadable}var nativeReadableStreamPrototypes={0:void 0,1:void 0,2:void 0,3:void 0,4:void 0,5:void 0};function getNativeReadableStreamPrototype(nativeType,Readable){return nativeReadableStreamPrototypes[nativeType]||=createNativeStreamReadable(nativeType,Readable)}function getNativeReadableStream(Readable,stream,options){if(!(stream&&typeof stream===\"object\"&&stream instanceof ReadableStream))return;const native=@direct(stream);if(!native)return;const{stream:ptr,data:type}=native;return new(getNativeReadableStreamPrototype(type,Readable))(ptr,options)}var Writable=require_writable(),NativeWritable=class NativeWritable2 extends Writable{#pathOrFdOrSink;#fileSink;#native=!0;_construct;_destroy;_final;constructor(pathOrFdOrSink,options={}){super(options);this._construct=this.#internalConstruct,this._destroy=this.#internalDestroy,this._final=this.#internalFinal,this.#pathOrFdOrSink=pathOrFdOrSink}#internalConstruct(cb){this._writableState.constructed=!0,this.constructed=!0,cb()}#lazyConstruct(){if(typeof this.#pathOrFdOrSink===\"object\")if(typeof this.#pathOrFdOrSink.write===\"function\")this.#fileSink=this.#pathOrFdOrSink;else throw new Error(\"Invalid FileSink\");else this.#fileSink=Bun.file(this.#pathOrFdOrSink).writer()}write(chunk,encoding,cb,native=this.#native){if(!native)return this.#native=!1,super.write(chunk,encoding,cb);if(!this.#fileSink)this.#lazyConstruct();var fileSink=this.#fileSink,result=fileSink.write(chunk);if(@isPromise(result))return result.then(()=>{this.emit(\"drain\"),fileSink.flush(!0)}),!1;if(fileSink.flush(!0),cb)cb(null,chunk.byteLength);return!0}end(chunk,encoding,cb,native=this.#native){return super.end(chunk,encoding,cb,native)}#internalDestroy(error,cb){if(this._writableState.destroyed=!0,cb)cb(error)}#internalFinal(cb){if(this.#fileSink)this.#fileSink.end();if(cb)cb()}ref(){if(!this.#fileSink)this.#lazyConstruct();this.#fileSink.ref()}unref(){if(!this.#fileSink)return;this.#fileSink.unref()}};const exports=require_stream(),promises=require_promises();return exports._getNativeReadableStreamPrototype=getNativeReadableStreamPrototype,exports.NativeWritable=NativeWritable,Object.defineProperty(exports,\"promises\",{configurable:!0,enumerable:!0,get(){return promises}}),exports[Symbol.for(\"::bunternal::\")]={_ReadableFromWeb,_ReadableFromWebForUndici},exports.eos=require_end_of_stream(),exports})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamPromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamWebCode = "(function (){\"use strict\";return{ReadableStream,ReadableStreamDefaultReader,ReadableStreamBYOBReader,ReadableStreamBYOBRequest,ReadableByteStreamController,ReadableStreamDefaultController,TransformStream,TransformStreamDefaultController,WritableStream,WritableStreamDefaultWriter,WritableStreamDefaultController,ByteLengthQueuingStrategy,CountQueuingStrategy}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTimersCode = "(function (){\"use strict\";return{setTimeout,clearTimeout,setInterval,setImmediate,clearInterval,clearImmediate}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTimersPromisesCode = "(function (){\"use strict\";var $;const symbolAsyncIterator=Symbol.asyncIterator;class ERR_INVALID_ARG_TYPE extends Error{constructor(name,expected,actual){super(`${name} must be ${expected}, ${typeof actual} given`);this.code=\"ERR_INVALID_ARG_TYPE\"}}class AbortError extends Error{constructor(){super(\"The operation was aborted\");this.code=\"ABORT_ERR\"}}function validateObject(object,name){if(object===null||typeof object!==\"object\")throw new ERR_INVALID_ARG_TYPE(name,\"Object\",object)}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}function validateAbortSignal(signal,name){if(typeof signal!==\"undefined\"&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE(name,\"AbortSignal\",signal)}function asyncIterator({next:nextFunction,return:returnFunction}){const result={};if(typeof nextFunction===\"function\")result.next=nextFunction;if(typeof returnFunction===\"function\")result.return=returnFunction;return result[symbolAsyncIterator]=function(){return this},result}function setTimeoutPromise(after=1,value,options={}){const arguments_=[].concat(value\?\?[]);try{validateObject(options,\"options\")}catch(error){return Promise.reject(error)}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return Promise.reject(error)}try{validateBoolean(reference,\"options.ref\")}catch(error){return Promise.reject(error)}if(signal\?.aborted)return Promise.reject(new AbortError);let onCancel;const returnValue=new Promise((resolve,reject)=>{const timeout=setTimeout(()=>resolve(value),after,...arguments_);if(!reference)timeout\?.unref\?.();if(signal)onCancel=()=>{clearTimeout(timeout),reject(new AbortError)},signal.addEventListener(\"abort\",onCancel)});if(typeof onCancel!==\"undefined\")returnValue.finally(()=>signal.removeEventListener(\"abort\",onCancel));return returnValue}function setImmediatePromise(value,options={}){try{validateObject(options,\"options\")}catch(error){return Promise.reject(error)}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return Promise.reject(error)}try{validateBoolean(reference,\"options.ref\")}catch(error){return Promise.reject(error)}if(signal\?.aborted)return Promise.reject(new AbortError);let onCancel;const returnValue=new Promise((resolve,reject)=>{const immediate=setImmediate(()=>resolve(value));if(!reference)immediate\?.unref\?.();if(signal)onCancel=()=>{clearImmediate(immediate),reject(new AbortError)},signal.addEventListener(\"abort\",onCancel)});if(typeof onCancel!==\"undefined\")returnValue.finally(()=>signal.removeEventListener(\"abort\",onCancel));return returnValue}function setIntervalPromise(after=1,value,options={}){try{validateObject(options,\"options\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}try{validateBoolean(reference,\"options.ref\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}if(signal\?.aborted)return asyncIterator({next:function(){return Promise.reject(new AbortError)}});let onCancel,interval;try{let notYielded=0,callback;if(interval=setInterval(()=>{if(notYielded++,callback)callback(),callback=void 0},after),!reference)interval\?.unref\?.();if(signal)onCancel=()=>{if(clearInterval(interval),callback)callback(),callback=void 0},signal.addEventListener(\"abort\",onCancel);return asyncIterator({next:function(){return new Promise((resolve,reject)=>{if(!signal\?.aborted)if(notYielded===0)callback=resolve;else resolve();else if(notYielded===0)reject(new AbortError);else resolve()}).then(()=>{if(notYielded>0)return notYielded=notYielded-1,{done:!1,value};return{done:!0}})},return:function(){return clearInterval(interval),signal\?.removeEventListener(\"abort\",onCancel),Promise.resolve({})}})}catch(error){return asyncIterator({next:function(){clearInterval(interval),signal\?.removeEventListener(\"abort\",onCancel)}})}}return $={setTimeout:setTimeoutPromise,setImmediate:setImmediatePromise,setInterval:setIntervalPromise,scheduler:{wait:(delay,options)=>setTimeoutPromise(delay,void 0,options),yield:setImmediatePromise}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTLSCode = "(function (){\"use strict\";const{isArrayBufferView,isTypedArray}=@requireNativeModule(\"node:util/types\"),net=@getInternalField(@internalModuleRegistry,22)||@createInternalModuleById(22),{Server:NetServer,[Symbol.for(\"::bunternal::\")]:InternalTCPSocket}=net,bunSocketInternal=Symbol.for(\"::bunnetsocketinternal::\"),{rootCertificates,canonicalizeIP}=globalThis[globalThis.Symbol.for('Bun.lazy')](\"internal/tls\"),SymbolReplace=Symbol.replace,RegExpPrototypeSymbolReplace=RegExp.prototype[SymbolReplace],RegExpPrototypeExec=RegExp.prototype.exec,StringPrototypeStartsWith=String.prototype.startsWith,StringPrototypeSlice=String.prototype.slice,StringPrototypeIncludes=String.prototype.includes,StringPrototypeSplit=String.prototype.split,StringPrototypeIndexOf=String.prototype.indexOf,StringPrototypeSubstring=String.prototype.substring,StringPrototypeEndsWith=String.prototype.endsWith,StringFromCharCode=String.fromCharCode,StringPrototypeCharCodeAt=String.prototype.charCodeAt,ArrayPrototypeIncludes=Array.prototype.includes,ArrayPrototypeJoin=Array.prototype.join,ArrayPrototypeForEach=Array.prototype.forEach,ArrayPrototypePush=Array.prototype.push,ArrayPrototypeSome=Array.prototype.some,ArrayPrototypeReduce=Array.prototype.reduce;function parseCertString(){throwNotImplemented(\"Not implemented\")}function isValidTLSArray(obj){if(typeof obj===\"string\"||isTypedArray(obj)||obj instanceof ArrayBuffer||obj instanceof Blob)return!0;if(Array.isArray(obj)){for(var i=0;iRegExpPrototypeExec.call(/[^\\u0021-\\u007F]/u,s)!==null;if(ArrayPrototypeSome.call(patternParts,isBad))return!1;for(let i=hostParts.length-1;i>0;i-=1)if(hostParts[i]!==patternParts[i])return!1;const hostSubdomain=hostParts[0],patternSubdomain=patternParts[0],patternSubdomainParts=StringPrototypeSplit.call(patternSubdomain,\"*\");if(patternSubdomainParts.length===1||StringPrototypeIncludes.call(patternSubdomain,\"xn--\"))return hostSubdomain===patternSubdomain;if(!wildcards)return!1;if(patternSubdomainParts.length>2)return!1;if(patternParts.length<=2)return!1;const{0:prefix,1:suffix}=patternSubdomainParts;if(prefix.length+suffix.length>hostSubdomain.length)return!1;if(!StringPrototypeStartsWith.call(hostSubdomain,prefix))return!1;if(!StringPrototypeEndsWith.call(hostSubdomain,suffix))return!1;return!0}const jsonStringPattern=/^\"(\?:[^\"\\\\\\u0000-\\u001f]|\\\\(\?:[\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"/;function splitEscapedAltNames(altNames){const result=[];let currentToken=\"\",offset=0;while(offset!==altNames.length){const nextSep=StringPrototypeIndexOf.call(altNames,\", \",offset),nextQuote=StringPrototypeIndexOf.call(altNames,'\"',offset);if(nextQuote!==-1&&(nextSep===-1||nextQuote{if(StringPrototypeStartsWith.call(name,\"DNS:\"))ArrayPrototypePush.call(dnsNames,StringPrototypeSlice.call(name,4));else if(StringPrototypeStartsWith.call(name,\"IP Address:\"))ArrayPrototypePush.call(ips,canonicalizeIP(StringPrototypeSlice.call(name,11)))})}let valid=!1,reason=\"Unknown reason\";if(hostname=unfqdn(hostname),net.isIP(hostname)){if(valid=ArrayPrototypeIncludes.call(ips,canonicalizeIP(hostname)),!valid)reason=`IP: ${hostname} is not in the cert's list: `+ArrayPrototypeJoin.call(ips,\", \")}else if(dnsNames.length>0||subject\?.CN){const hostParts=splitHost(hostname),wildcard=(pattern)=>check(hostParts,pattern,!0);if(dnsNames.length>0){if(valid=ArrayPrototypeSome.call(dnsNames,wildcard),!valid)reason=`Host: ${hostname}. is not in the cert's altnames: ${altNames}`}else{const cn=subject.CN;if(Array.isArray(cn))valid=ArrayPrototypeSome.call(cn,wildcard);else if(cn)valid=wildcard(cn);if(!valid)reason=`Host: ${hostname}. is not cert's CN: ${cn}`}}else reason=\"Cert does not contain a DNS name\";if(!valid){let error=new Error(`ERR_TLS_CERT_ALTNAME_INVALID: Hostname/IP does not match certificate's altnames: ${reason}`);return error.name=\"ERR_TLS_CERT_ALTNAME_INVALID\",error.reason=reason,error.host=host,error.cert=cert,error}}var InternalSecureContext=class SecureContext2{context;constructor(options){const context={};if(options){let key=options.key;if(key){if(!isValidTLSArray(key))@throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.key=key}let cert=options.cert;if(cert){if(!isValidTLSArray(cert))@throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.cert=cert}let ca=options.ca;if(ca){if(!isValidTLSArray(ca))@throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.ca=ca}let passphrase=options.passphrase;if(passphrase&&typeof passphrase!==\"string\")@throwTypeError(\"passphrase argument must be an string\");this.passphrase=passphrase;let servername=options.servername;if(servername&&typeof servername!==\"string\")@throwTypeError(\"servername argument must be an string\");this.servername=servername;let secureOptions=options.secureOptions||0;if(secureOptions&&typeof secureOptions!==\"number\")@throwTypeError(\"secureOptions argument must be an number\");this.secureOptions=secureOptions}this.context=context}};function SecureContext(options){return new InternalSecureContext(options)}function createSecureContext(options){return new SecureContext(options)}function translatePeerCertificate(c){if(!c)return null;if(c.issuerCertificate!=null&&c.issuerCertificate!==c)c.issuerCertificate=translatePeerCertificate(c.issuerCertificate);if(c.infoAccess!=null){const info=c.infoAccess;c.infoAccess={__proto__:null},RegExpPrototypeSymbolReplace.call(/([^\\n:]*):([^\\n]*)(\?:\\n|$)/g,info,(all,key,val)=>{if(val.charCodeAt(0)===34)val=JSONParse(val);if(key in c.infoAccess)ArrayPrototypePush.call(c.infoAccess[key],val);else c.infoAccess[key]=[val]})}return c}const buntls=Symbol.for(\"::buntls::\");var SocketClass;const TLSSocket=function(InternalTLSSocket){return SocketClass=InternalTLSSocket,Object.defineProperty(SocketClass.prototype,Symbol.toStringTag,{value:\"TLSSocket\",enumerable:!1}),Object.defineProperty(function Socket(options){return new InternalTLSSocket(options)},Symbol.hasInstance,{value(instance){return instance instanceof InternalTLSSocket}})}(class TLSSocket2 extends InternalTCPSocket{#secureContext;ALPNProtocols;#socket;#checkServerIdentity;#session;constructor(socket,options){super(socket instanceof InternalTCPSocket\?options:options||socket);if(options=options||socket||{},typeof options===\"object\"){const{ALPNProtocols}=options;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,this);if(socket instanceof InternalTCPSocket)this.#socket=socket}this.#secureContext=options.secureContext||createSecureContext(options),this.authorized=!1,this.secureConnecting=!0,this._secureEstablished=!1,this._securePending=!0,this.#checkServerIdentity=options.checkServerIdentity||checkServerIdentity,this.#session=options.session||null}_secureEstablished=!1;_securePending=!0;_newSessionPending;_controlReleased;secureConnecting=!1;_SNICallback;servername;authorized=!1;authorizationError;#renegotiationDisabled=!1;encrypted=!0;_start(){this.connect()}getSession(){return this[bunSocketInternal]\?.getSession()}getEphemeralKeyInfo(){return this[bunSocketInternal]\?.getEphemeralKeyInfo()}getCipher(){return this[bunSocketInternal]\?.getCipher()}getSharedSigalgs(){return this[bunSocketInternal]\?.getSharedSigalgs()}getProtocol(){return this[bunSocketInternal]\?.getTLSVersion()}getFinished(){return this[bunSocketInternal]\?.getTLSFinishedMessage()||void 0}getPeerFinished(){return this[bunSocketInternal]\?.getTLSPeerFinishedMessage()||void 0}isSessionReused(){return!!this.#session}renegotiate(){if(this.#renegotiationDisabled){const error=new Error(\"ERR_TLS_RENEGOTIATION_DISABLED: TLS session renegotiation disabled for this socket\");throw error.name=\"ERR_TLS_RENEGOTIATION_DISABLED\",error}throw Error(\"Not implented in Bun yet\")}disableRenegotiation(){this.#renegotiationDisabled=!0}getTLSTicket(){return this[bunSocketInternal]\?.getTLSTicket()}exportKeyingMaterial(length,label,context){if(context)return this[bunSocketInternal]\?.exportKeyingMaterial(length,label,context);return this[bunSocketInternal]\?.exportKeyingMaterial(length,label)}setMaxSendFragment(size){return this[bunSocketInternal]\?.setMaxSendFragment(size)||!1}enableTrace(){}setServername(name){if(this.isServer){let error=new Error(\"ERR_TLS_SNI_FROM_SERVER: Cannot issue SNI from a TLS server-side socket\");throw error.name=\"ERR_TLS_SNI_FROM_SERVER\",error}this.servername=name,this[bunSocketInternal]\?.setServername(name)}setSession(session){if(this.#session=session,typeof session===\"string\")session=Buffer.from(session,\"latin1\");return this[bunSocketInternal]\?.setSession(session)}getPeerCertificate(abbreviated){const cert=arguments.length<1\?this[bunSocketInternal]\?.getPeerCertificate():this[bunSocketInternal]\?.getPeerCertificate(abbreviated);if(cert)return translatePeerCertificate(cert)}getCertificate(){const cert=this[bunSocketInternal]\?.getCertificate();if(cert)return translatePeerCertificate(cert)}getPeerX509Certificate(){throw Error(\"Not implented in Bun yet\")}getX509Certificate(){throw Error(\"Not implented in Bun yet\")}get alpnProtocol(){return this[bunSocketInternal]\?.alpnProtocol}[buntls](port,host2){return{socket:this.#socket,ALPNProtocols:this.ALPNProtocols,serverName:this.servername||host2||\"localhost\",checkServerIdentity:this.#checkServerIdentity,session:this.#session,...this.#secureContext}}});class Server extends NetServer{key;cert;ca;passphrase;secureOptions;_rejectUnauthorized;_requestCert;servername;ALPNProtocols;constructor(options,secureConnectionListener){super(options,secureConnectionListener);this.setSecureContext(options)}setSecureContext(options){if(options instanceof InternalSecureContext)options=options.context;if(options){const{ALPNProtocols}=options;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,this);let key=options.key;if(key){if(!isValidTLSArray(key))@throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.key=key}let cert=options.cert;if(cert){if(!isValidTLSArray(cert))@throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.cert=cert}let ca=options.ca;if(ca){if(!isValidTLSArray(ca))@throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.ca=ca}let passphrase=options.passphrase;if(passphrase&&typeof passphrase!==\"string\")@throwTypeError(\"passphrase argument must be an string\");this.passphrase=passphrase;let servername=options.servername;if(servername&&typeof servername!==\"string\")@throwTypeError(\"servername argument must be an string\");this.servername=servername;let secureOptions=options.secureOptions||0;if(secureOptions&&typeof secureOptions!==\"number\")@throwTypeError(\"secureOptions argument must be an number\");this.secureOptions=secureOptions;const requestCert=options.requestCert||!1;if(requestCert)this._requestCert=requestCert;else this._requestCert=void 0;const rejectUnauthorized=options.rejectUnauthorized||!1;if(rejectUnauthorized)this._rejectUnauthorized=rejectUnauthorized;else this._rejectUnauthorized=void 0}}getTicketKeys(){throw Error(\"Not implented in Bun yet\")}setTicketKeys(){throw Error(\"Not implented in Bun yet\")}[buntls](port,host2,isClient){return[{serverName:this.servername||host2||\"localhost\",key:this.key,cert:this.cert,ca:this.ca,passphrase:this.passphrase,secureOptions:this.secureOptions,rejectUnauthorized:isClient\?!1:this._rejectUnauthorized,requestCert:isClient\?!1:this._requestCert,ALPNProtocols:this.ALPNProtocols},SocketClass]}}function createServer(options,connectionListener){return new Server(options,connectionListener)}const CLIENT_RENEG_LIMIT=3,CLIENT_RENEG_WINDOW=600,DEFAULT_ECDH_CURVE=\"auto\",DEFAULT_CIPHERS=\"DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256\",DEFAULT_MIN_VERSION=\"TLSv1.2\",DEFAULT_MAX_VERSION=\"TLSv1.3\",createConnection=(port,host2,connectListener)=>{if(typeof port===\"object\"){port.checkServerIdentity;const{ALPNProtocols}=port;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,port);return new TLSSocket(port).connect(port,host2,connectListener)}return new TLSSocket().connect(port,host2,connectListener)},connect=createConnection;function getCiphers(){return DEFAULT_CIPHERS.split(\":\")}function convertProtocols(protocols){const lens=new Array(protocols.length),buff=Buffer.allocUnsafe(ArrayPrototypeReduce.call(protocols,(p,c,i)=>{const len=Buffer.byteLength(c);if(len>255)@throwRangeError(\"The byte length of the protocol at index \"+`${i} exceeds the maximum length.`,\"<= 255\",len,!0);return lens[i]=len,p+1+len},0));let offset=0;for(let i=0,c=protocols.length;i\",'\"',\"`\",\" \",\"\\r\",\"\\n\",\"\\t\"],unwise=[\"{\",\"}\",\"|\",\"\\\\\",\"^\",\"`\"].concat(delims),autoEscape=[\"'\"].concat(unwise),nonHostChars=[\"%\",\"/\",\"\?\",\";\",\"#\"].concat(autoEscape),hostEndingChars=[\"/\",\"\?\",\"#\"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,\"javascript:\":!0},hostlessProtocol={javascript:!0,\"javascript:\":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,\"http:\":!0,\"https:\":!0,\"ftp:\":!0,\"gopher:\":!0,\"file:\":!0};function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&typeof url===\"object\"&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(typeof url!==\"string\")@throwTypeError(\"Parameter 'url' must be a string, not \"+typeof url);var queryIndex=url.indexOf(\"\?\"),splitter=queryIndex!==-1&&queryIndex127)newpart+=\"x\";else newpart+=part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);if(bit)validParts.push(bit[1]),notHost.unshift(bit[2]);if(notHost.length)rest=\"/\"+notHost.join(\".\")+rest;this.hostname=validParts.join(\".\");break}}}}if(this.hostname.length>hostnameMaxLen)this.hostname=\"\";else this.hostname=this.hostname.toLowerCase();if(!ipv6Hostname)this.hostname=new URL(\"http://\"+this.hostname).hostname;var p=this.port\?\":\"+this.port:\"\",h=this.hostname||\"\";if(this.host=h+p,this.href+=this.host,ipv6Hostname){if(this.hostname=this.hostname.substr(1,this.hostname.length-2),rest[0]!==\"/\")rest=\"/\"+rest}}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length;i0\?result.host.split(\"@\"):!1;if(authInHost)result.auth=authInHost.shift(),result.hostname=authInHost.shift(),result.host=result.hostname}if(result.search=relative.search,result.query=relative.query,result.pathname!==null||result.search!==null)result.path=(result.pathname\?result.pathname:\"\")+(result.search\?result.search:\"\");return result.href=result.format(),result}if(!srcPath.length){if(result.pathname=null,result.search)result.path=\"/\"+result.search;else result.path=null;return result.href=result.format(),result}var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last===\".\"||last===\"..\")||last===\"\",up=0;for(var i=srcPath.length;i>=0;i--)if(last=srcPath[i],last===\".\")srcPath.splice(i,1);else if(last===\"..\")srcPath.splice(i,1),up++;else if(up)srcPath.splice(i,1),up--;if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift(\"..\");if(mustEndAbs&&srcPath[0]!==\"\"&&(!srcPath[0]||srcPath[0].charAt(0)!==\"/\"))srcPath.unshift(\"\");if(hasTrailingSlash&&srcPath.join(\"/\").substr(-1)!==\"/\")srcPath.push(\"\");var isAbsolute=srcPath[0]===\"\"||srcPath[0]&&srcPath[0].charAt(0)===\"/\";if(psychotic){result.hostname=isAbsolute\?\"\":srcPath.length\?srcPath.shift():\"\",result.host=result.hostname;var authInHost=result.host&&result.host.indexOf(\"@\")>0\?result.host.split(\"@\"):!1;if(authInHost)result.auth=authInHost.shift(),result.hostname=authInHost.shift(),result.host=result.hostname}if(mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute)srcPath.unshift(\"\");if(srcPath.length>0)result.pathname=srcPath.join(\"/\");else result.pathname=null,result.path=null;if(result.pathname!==null||result.search!==null)result.path=(result.pathname\?result.pathname:\"\")+(result.search\?result.search:\"\");return result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);if(port){if(port=port[0],port!==\":\")this.port=port.substr(1);host=host.substr(0,host.length-port.length)}if(host)this.hostname=host};function urlToHttpOptions(url){const options={protocol:url.protocol,hostname:typeof url.hostname===\"string\"&&url.hostname.startsWith(\"[\")\?url.hostname.slice(1,-1):url.hostname,hash:url.hash,search:url.search,pathname:url.pathname,path:`${url.pathname||\"\"}${url.search||\"\"}`,href:url.href};if(url.port!==\"\")options.port=Number(url.port);if(url.username||url.password)options.auth=`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;return options}const pathToFileURL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"pathToFileURL\"),fileURLToPath=globalThis[globalThis.Symbol.for('Bun.lazy')](\"fileURLToPath\");return{parse:urlParse,resolve:urlResolve,resolveObject:urlResolveObject,format:urlFormat,Url,URLSearchParams,URL,pathToFileURL,fileURLToPath,urlToHttpOptions}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeUtilCode = "(function (){\"use strict\";const types=@requireNativeModule(\"node:util/types\");var cjs_exports={};function isBufferInterface({copy,fill,readUint8}){return typeof copy===\"function\"&&typeof fill===\"function\"&&typeof readUint8===\"function\"}function isBuffer(value){return Buffer.isBuffer(value)||typeof value===\"object\"&&isBufferInterface(value||{})}function isFunction(value){return typeof value===\"function\"}const deepEquals=Bun.deepEquals,isDeepStrictEqual=(a,b)=>deepEquals(a,b,!0);var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors,formatRegExp=/%[sdj%]/g;function format(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x2;switch(x2){case\"%s\":return String(args[i++]);case\"%d\":return Number(args[i++]);case\"%j\":try{return JSON.stringify(args[i++])}catch(_){return\"[Circular]\"}default:return x2}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts))ctx.showHidden=opts;else if(opts)_extend(ctx,opts);if(isUndefined(ctx.showHidden))ctx.showHidden=!1;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=!1;if(isUndefined(ctx.customInspect))ctx.customInspect=!0;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:\"cyan\",number:\"yellow\",boolean:\"yellow\",undefined:\"grey\",null:\"bold\",string:\"green\",date:\"magenta\",regexp:\"red\"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style)return\"\\x1B[\"+inspect.colors[style][0]+\"m\"+str+\"\\x1B[\"+inspect.colors[style][1]+\"m\";else return str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret))ret=formatValue(ctx,ret,recurseTimes);return ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden)keys=Object.getOwnPropertyNames(value);if(isError(value)&&(keys.indexOf(\"message\")>=0||keys.indexOf(\"description\")>=0))return formatError(value);if(keys.length===0){if(isFunction(value)){var name=value.name\?\": \"+value.name:\"\";return ctx.stylize(\"[Function\"+name+\"]\",\"special\")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),\"regexp\");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),\"date\");if(isError(value))return formatError(value)}var base=\"\",array=!1,braces=[\"{\",\"}\"];if(@isArray(value))array=!0,braces=[\"[\",\"]\"];if(isFunction(value)){var n=value.name\?\": \"+value.name:\"\";base=\" [Function\"+n+\"]\"}if(isRegExp(value))base=\" \"+RegExp.prototype.toString.call(value);if(isDate(value))base=\" \"+Date.prototype.toUTCString.call(value);if(isError(value))base=\" \"+formatError(value);if(keys.length===0&&(!array||value.length==0))return braces[0]+base+braces[1];if(recurseTimes<0)if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),\"regexp\");else return ctx.stylize(\"[Object]\",\"special\");ctx.seen.push(value);var output;if(array)output=formatArray(ctx,value,recurseTimes,visibleKeys,keys);else output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)});return ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize(\"undefined\",\"undefined\");if(isString(value)){var simple=\"'\"+JSON.stringify(value).replace(/^\"|\"$/g,\"\").replace(/'/g,\"\\\\'\").replace(/\\\\\"/g,'\"')+\"'\";return ctx.stylize(simple,\"string\")}if(isNumber(value))return ctx.stylize(\"\"+value,\"number\");if(isBoolean(value))return ctx.stylize(\"\"+value,\"boolean\");if(isNull(value))return ctx.stylize(\"null\",\"null\")}function formatError(value){return\"[\"+Error.prototype.toString.call(value)+\"]\"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1)if(array)str=str.split(\"\\n\").map(function(line){return\" \"+line}).join(\"\\n\").substr(2);else str=\"\\n\"+str.split(\"\\n\").map(function(line){return\" \"+line}).join(\"\\n\")}else str=ctx.stylize(\"[Circular]\",\"special\");if(isUndefined(name)){if(array&&key.match(/^\\d+$/))return str;if(name=JSON.stringify(\"\"+key),name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/))name=name.substr(1,name.length-2),name=ctx.stylize(name,\"name\");else name=name.replace(/'/g,\"\\\\'\").replace(/\\\\\"/g,'\"').replace(/(^\"|\"$)/g,\"'\"),name=ctx.stylize(name,\"string\")}return name+\": \"+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){if(numLinesEst++,cur.indexOf(\"\\n\")>=0)numLinesEst++;return prev+cur.replace(/\\u001b\\[\\d\\d\?m/g,\"\").length+1},0);if(length>60)return braces[0]+(base===\"\"\?\"\":base+\"\\n \")+\" \"+output.join(\",\\n \")+\" \"+braces[1];return braces[0]+base+\" \"+output.join(\", \")+\" \"+braces[1]}function isBoolean(arg){return typeof arg===\"boolean\"}function isNull(arg){return arg===null}function isNullOrUndefined(arg){return arg==null}function isNumber(arg){return typeof arg===\"number\"}function isString(arg){return typeof arg===\"string\"}function isSymbol(arg){return typeof arg===\"symbol\"}function isUndefined(arg){return arg===void 0}var isRegExp=types.isRegExp;function isObject(arg){return typeof arg===\"object\"&&arg!==null}var{isDate,isNativeError:isError}=types;function isPrimitive(arg){return arg===null||typeof arg===\"boolean\"||typeof arg===\"number\"||typeof arg===\"string\"||typeof arg===\"symbol\"||typeof arg===\"undefined\"}function pad(n){return n<10\?\"0\"+n.toString(10):n.toString(10)}var months=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"];function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(\":\");return[d.getDate(),months[d.getMonth()],time].join(\" \")}var log=function log(){console.log(\"%s - %s\",timestamp(),format.apply(cjs_exports,arguments))},inherits=function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},_extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add),i=keys.length;while(i--)origin[keys[i]]=add[keys[i]];return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var kCustomPromisifiedSymbol=Symbol.for(\"util.promisify.custom\"),promisify=function promisify(original){if(typeof original!==\"function\")@throwTypeError('The \"original\" argument must be of type Function');if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if(typeof fn!==\"function\")@throwTypeError('The \"util.promisify.custom\" argument must be of type Function');return Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),fn}function fn(){var promiseResolve,promiseReject,promise=new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject}),args=[];for(var i=0;i{return(input+\"\").toWellFormed()};return Object.assign(cjs_exports,{format,deprecate,debuglog,_extend,inspect,types,isArray:@isArray,isBoolean,isNull,isNullOrUndefined,isNumber,isString,isSymbol,isUndefined,isRegExp,isObject,isDate,isFunction,isError,isPrimitive,isBuffer,log,inherits,toUSVString,promisify,callbackify,isDeepStrictEqual,TextDecoder,TextEncoder})})\n"_s; +// + +// +static constexpr ASCIILiteral NodeV8Code = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),jsc=@requireNativeModule(\"bun:jsc\");function notimpl(message){throwNotImplemented(\"node:v8 \"+message)}class Deserializer{constructor(){notimpl(\"Deserializer\")}}class Serializer{constructor(){notimpl(\"Serializer\")}}class DefaultDeserializer extends Deserializer{constructor(){super(...arguments)}}class DefaultSerializer extends Serializer{constructor(){super(...arguments)}}class GCProfiler{constructor(){notimpl(\"GCProfiler\")}}function cachedDataVersionTag(){notimpl(\"cachedDataVersionTag\")}function getHeapSnapshot(){notimpl(\"getHeapSnapshot\")}function getHeapStatistics(){notimpl(\"getHeapStatistics\")}function getHeapSpaceStatistics(){notimpl(\"getHeapSpaceStatistics\")}function getHeapCodeStatistics(){notimpl(\"getHeapCodeStatistics\")}function setFlagsFromString(){notimpl(\"setFlagsFromString\")}function deserialize(value){return jsc.deserialize(value)}function takeCoverage(){notimpl(\"takeCoverage\")}function stopCoverage(){notimpl(\"stopCoverage\")}function serialize(arg1){return jsc.serialize(arg1,{binaryType:\"nodebuffer\"})}function writeHeapSnapshot(){notimpl(\"writeHeapSnapshot\")}function setHeapSnapshotNearHeapLimit(){notimpl(\"setHeapSnapshotNearHeapLimit\")}return $={cachedDataVersionTag,getHeapSnapshot,getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,deserialize,takeCoverage,stopCoverage,serialize,writeHeapSnapshot,setHeapSnapshotNearHeapLimit,promiseHooks:{createHook:()=>{notimpl(\"createHook\")},onInit:()=>{notimpl(\"onInit\")},onBefore:()=>{notimpl(\"onBefore\")},onAfter:()=>{notimpl(\"onAfter\")},onSettled:()=>{notimpl(\"onSettled\")}},startupSnapshot:{addDeserializeCallback:()=>notimpl(\"addDeserializeCallback\"),addSerializeCallback:()=>notimpl(\"addSerializeCallback\"),setDeserializeMainFunction:()=>notimpl(\"setDeserializeMainFunction\"),isBuildingSnapshot:()=>notimpl(\"isBuildingSnapshot\")},Deserializer,Serializer},hideFromStack(notimpl,cachedDataVersionTag,getHeapSnapshot,getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,deserialize,takeCoverage,stopCoverage,serialize,writeHeapSnapshot,setHeapSnapshotNearHeapLimit,Deserializer,Serializer,DefaultDeserializer,DefaultSerializer,GCProfiler),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeVMCode = "(function (){\"use strict\";const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),vm=globalThis[globalThis.Symbol.for('Bun.lazy')](\"vm\"),{createContext,isContext,Script,runInNewContext,runInThisContext}=vm;function runInContext(code,context,options){return new Script(code,options).runInContext(context)}function compileFunction(){throwNotImplemented(\"node:vm compileFunction\")}function measureMemory(){throwNotImplemented(\"node:vm measureMemory\")}class Module{constructor(){throwNotImplemented(\"node:vm Module\")}}class SourceTextModule{constructor(){throwNotImplemented(\"node:vm Module\")}}class SyntheticModule{constructor(){throwNotImplemented(\"node:vm Module\")}}return{createContext,runInContext,runInNewContext,runInThisContext,isContext,compileFunction,measureMemory,Script,Module,SourceTextModule,SyntheticModule}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeWasiCode = "(function (){\"use strict\";const nodeFsConstants=@processBindingConstants.fs;var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_types=__commonJS({\"node_modules/wasi-js/dist/types.js\"(exports){Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.WASIKillError=exports.WASIExitError=exports.WASIError=void 0;var WASIError=class extends Error{constructor(errno){super();this.errno=errno,Object.setPrototypeOf(this,WASIError.prototype)}};exports.WASIError=WASIError;var WASIExitError=class extends Error{constructor(code){super(`WASI Exit error: ${code}`);this.code=code,Object.setPrototypeOf(this,WASIExitError.prototype)}};exports.WASIExitError=WASIExitError;var WASIKillError=class extends Error{constructor(signal){super(`WASI Kill signal: ${signal}`);this.signal=signal,Object.setPrototypeOf(this,WASIKillError.prototype)}};exports.WASIKillError=WASIKillError}}),require_constants=__commonJS({\"node_modules/wasi-js/dist/constants.js\"(exports){Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.WASI_ENOMSG=exports.WASI_ENOMEM=exports.WASI_ENOLINK=exports.WASI_ENOLCK=exports.WASI_ENOEXEC=exports.WASI_ENOENT=exports.WASI_ENODEV=exports.WASI_ENOBUFS=exports.WASI_ENFILE=exports.WASI_ENETUNREACH=exports.WASI_ENETRESET=exports.WASI_ENETDOWN=exports.WASI_ENAMETOOLONG=exports.WASI_EMULTIHOP=exports.WASI_EMSGSIZE=exports.WASI_EMLINK=exports.WASI_EMFILE=exports.WASI_ELOOP=exports.WASI_EISDIR=exports.WASI_EISCONN=exports.WASI_EIO=exports.WASI_EINVAL=exports.WASI_EINTR=exports.WASI_EINPROGRESS=exports.WASI_EILSEQ=exports.WASI_EIDRM=exports.WASI_EHOSTUNREACH=exports.WASI_EFBIG=exports.WASI_EFAULT=exports.WASI_EEXIST=exports.WASI_EDQUOT=exports.WASI_EDOM=exports.WASI_EDESTADDRREQ=exports.WASI_EDEADLK=exports.WASI_ECONNRESET=exports.WASI_ECONNREFUSED=exports.WASI_ECONNABORTED=exports.WASI_ECHILD=exports.WASI_ECANCELED=exports.WASI_EBUSY=exports.WASI_EBADMSG=exports.WASI_EBADF=exports.WASI_EALREADY=exports.WASI_EAGAIN=exports.WASI_EAFNOSUPPORT=exports.WASI_EADDRNOTAVAIL=exports.WASI_EADDRINUSE=exports.WASI_EACCES=exports.WASI_E2BIG=exports.WASI_ESUCCESS=void 0,exports.WASI_SIGVTALRM=exports.WASI_SIGUSR2=exports.WASI_SIGUSR1=exports.WASI_SIGURG=exports.WASI_SIGTTOU=exports.WASI_SIGTTIN=exports.WASI_SIGTSTP=exports.WASI_SIGTRAP=exports.WASI_SIGTERM=exports.WASI_SIGSTOP=exports.WASI_SIGSEGV=exports.WASI_SIGQUIT=exports.WASI_SIGPIPE=exports.WASI_SIGKILL=exports.WASI_SIGINT=exports.WASI_SIGILL=exports.WASI_SIGHUP=exports.WASI_SIGFPE=exports.WASI_SIGCONT=exports.WASI_SIGCHLD=exports.WASI_SIGBUS=exports.WASI_SIGALRM=exports.WASI_SIGABRT=exports.WASI_ENOTCAPABLE=exports.WASI_EXDEV=exports.WASI_ETXTBSY=exports.WASI_ETIMEDOUT=exports.WASI_ESTALE=exports.WASI_ESRCH=exports.WASI_ESPIPE=exports.WASI_EROFS=exports.WASI_ERANGE=exports.WASI_EPROTOTYPE=exports.WASI_EPROTONOSUPPORT=exports.WASI_EPROTO=exports.WASI_EPIPE=exports.WASI_EPERM=exports.WASI_EOWNERDEAD=exports.WASI_EOVERFLOW=exports.WASI_ENXIO=exports.WASI_ENOTTY=exports.WASI_ENOTSUP=exports.WASI_ENOTSOCK=exports.WASI_ENOTRECOVERABLE=exports.WASI_ENOTEMPTY=exports.WASI_ENOTDIR=exports.WASI_ENOTCONN=exports.WASI_ENOSYS=exports.WASI_ENOSPC=exports.WASI_ENOPROTOOPT=void 0,exports.RIGHTS_REGULAR_FILE_BASE=exports.RIGHTS_CHARACTER_DEVICE_INHERITING=exports.RIGHTS_CHARACTER_DEVICE_BASE=exports.RIGHTS_BLOCK_DEVICE_INHERITING=exports.RIGHTS_BLOCK_DEVICE_BASE=exports.RIGHTS_ALL=exports.WASI_RIGHT_SOCK_SHUTDOWN=exports.WASI_RIGHT_POLL_FD_READWRITE=exports.WASI_RIGHT_PATH_UNLINK_FILE=exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY=exports.WASI_RIGHT_PATH_SYMLINK=exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES=exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE=exports.WASI_RIGHT_FD_FILESTAT_GET=exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES=exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE=exports.WASI_RIGHT_PATH_FILESTAT_GET=exports.WASI_RIGHT_PATH_RENAME_TARGET=exports.WASI_RIGHT_PATH_RENAME_SOURCE=exports.WASI_RIGHT_PATH_READLINK=exports.WASI_RIGHT_FD_READDIR=exports.WASI_RIGHT_PATH_OPEN=exports.WASI_RIGHT_PATH_LINK_TARGET=exports.WASI_RIGHT_PATH_LINK_SOURCE=exports.WASI_RIGHT_PATH_CREATE_FILE=exports.WASI_RIGHT_PATH_CREATE_DIRECTORY=exports.WASI_RIGHT_FD_ALLOCATE=exports.WASI_RIGHT_FD_ADVISE=exports.WASI_RIGHT_FD_WRITE=exports.WASI_RIGHT_FD_TELL=exports.WASI_RIGHT_FD_SYNC=exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS=exports.WASI_RIGHT_FD_SEEK=exports.WASI_RIGHT_FD_READ=exports.WASI_RIGHT_FD_DATASYNC=exports.WASI_FDFLAG_SYNC=exports.WASI_FDFLAG_RSYNC=exports.WASI_FDFLAG_NONBLOCK=exports.WASI_FDFLAG_DSYNC=exports.WASI_FDFLAG_APPEND=exports.WASI_FILETYPE_SYMBOLIC_LINK=exports.WASI_FILETYPE_SOCKET_STREAM=exports.WASI_FILETYPE_SOCKET_DGRAM=exports.WASI_FILETYPE_REGULAR_FILE=exports.WASI_FILETYPE_DIRECTORY=exports.WASI_FILETYPE_CHARACTER_DEVICE=exports.WASI_FILETYPE_BLOCK_DEVICE=exports.WASI_FILETYPE_UNKNOWN=exports.WASI_SIGXFSZ=exports.WASI_SIGXCPU=void 0,exports.SIGNAL_MAP=exports.ERROR_MAP=exports.WASI_WHENCE_END=exports.WASI_WHENCE_CUR=exports.WASI_WHENCE_SET=exports.WASI_STDERR_FILENO=exports.WASI_STDOUT_FILENO=exports.WASI_STDIN_FILENO=exports.WASI_DIRCOOKIE_START=exports.WASI_PREOPENTYPE_DIR=exports.WASI_O_TRUNC=exports.WASI_O_EXCL=exports.WASI_O_DIRECTORY=exports.WASI_O_CREAT=exports.WASI_FILESTAT_SET_MTIM_NOW=exports.WASI_FILESTAT_SET_MTIM=exports.WASI_FILESTAT_SET_ATIM_NOW=exports.WASI_FILESTAT_SET_ATIM=exports.WASI_EVENTTYPE_FD_WRITE=exports.WASI_EVENTTYPE_FD_READ=exports.WASI_EVENTTYPE_CLOCK=exports.WASI_CLOCK_THREAD_CPUTIME_ID=exports.WASI_CLOCK_PROCESS_CPUTIME_ID=exports.WASI_CLOCK_MONOTONIC=exports.WASI_CLOCK_REALTIME=exports.RIGHTS_TTY_INHERITING=exports.RIGHTS_TTY_BASE=exports.RIGHTS_SOCKET_INHERITING=exports.RIGHTS_SOCKET_BASE=exports.RIGHTS_DIRECTORY_INHERITING=exports.RIGHTS_DIRECTORY_BASE=exports.RIGHTS_REGULAR_FILE_INHERITING=void 0,exports.WASI_ESUCCESS=0,exports.WASI_E2BIG=1,exports.WASI_EACCES=2,exports.WASI_EADDRINUSE=3,exports.WASI_EADDRNOTAVAIL=4,exports.WASI_EAFNOSUPPORT=5,exports.WASI_EAGAIN=6,exports.WASI_EALREADY=7,exports.WASI_EBADF=8,exports.WASI_EBADMSG=9,exports.WASI_EBUSY=10,exports.WASI_ECANCELED=11,exports.WASI_ECHILD=12,exports.WASI_ECONNABORTED=13,exports.WASI_ECONNREFUSED=14,exports.WASI_ECONNRESET=15,exports.WASI_EDEADLK=16,exports.WASI_EDESTADDRREQ=17,exports.WASI_EDOM=18,exports.WASI_EDQUOT=19,exports.WASI_EEXIST=20,exports.WASI_EFAULT=21,exports.WASI_EFBIG=22,exports.WASI_EHOSTUNREACH=23,exports.WASI_EIDRM=24,exports.WASI_EILSEQ=25,exports.WASI_EINPROGRESS=26,exports.WASI_EINTR=27,exports.WASI_EINVAL=28,exports.WASI_EIO=29,exports.WASI_EISCONN=30,exports.WASI_EISDIR=31,exports.WASI_ELOOP=32,exports.WASI_EMFILE=33,exports.WASI_EMLINK=34,exports.WASI_EMSGSIZE=35,exports.WASI_EMULTIHOP=36,exports.WASI_ENAMETOOLONG=37,exports.WASI_ENETDOWN=38,exports.WASI_ENETRESET=39,exports.WASI_ENETUNREACH=40,exports.WASI_ENFILE=41,exports.WASI_ENOBUFS=42,exports.WASI_ENODEV=43,exports.WASI_ENOENT=44,exports.WASI_ENOEXEC=45,exports.WASI_ENOLCK=46,exports.WASI_ENOLINK=47,exports.WASI_ENOMEM=48,exports.WASI_ENOMSG=49,exports.WASI_ENOPROTOOPT=50,exports.WASI_ENOSPC=51,exports.WASI_ENOSYS=52,exports.WASI_ENOTCONN=53,exports.WASI_ENOTDIR=54,exports.WASI_ENOTEMPTY=55,exports.WASI_ENOTRECOVERABLE=56,exports.WASI_ENOTSOCK=57,exports.WASI_ENOTSUP=58,exports.WASI_ENOTTY=59,exports.WASI_ENXIO=60,exports.WASI_EOVERFLOW=61,exports.WASI_EOWNERDEAD=62,exports.WASI_EPERM=63,exports.WASI_EPIPE=64,exports.WASI_EPROTO=65,exports.WASI_EPROTONOSUPPORT=66,exports.WASI_EPROTOTYPE=67,exports.WASI_ERANGE=68,exports.WASI_EROFS=69,exports.WASI_ESPIPE=70,exports.WASI_ESRCH=71,exports.WASI_ESTALE=72,exports.WASI_ETIMEDOUT=73,exports.WASI_ETXTBSY=74,exports.WASI_EXDEV=75,exports.WASI_ENOTCAPABLE=76,exports.WASI_SIGABRT=0,exports.WASI_SIGALRM=1,exports.WASI_SIGBUS=2,exports.WASI_SIGCHLD=3,exports.WASI_SIGCONT=4,exports.WASI_SIGFPE=5,exports.WASI_SIGHUP=6,exports.WASI_SIGILL=7,exports.WASI_SIGINT=8,exports.WASI_SIGKILL=9,exports.WASI_SIGPIPE=10,exports.WASI_SIGQUIT=11,exports.WASI_SIGSEGV=12,exports.WASI_SIGSTOP=13,exports.WASI_SIGTERM=14,exports.WASI_SIGTRAP=15,exports.WASI_SIGTSTP=16,exports.WASI_SIGTTIN=17,exports.WASI_SIGTTOU=18,exports.WASI_SIGURG=19,exports.WASI_SIGUSR1=20,exports.WASI_SIGUSR2=21,exports.WASI_SIGVTALRM=22,exports.WASI_SIGXCPU=23,exports.WASI_SIGXFSZ=24,exports.WASI_FILETYPE_UNKNOWN=0,exports.WASI_FILETYPE_BLOCK_DEVICE=1,exports.WASI_FILETYPE_CHARACTER_DEVICE=2,exports.WASI_FILETYPE_DIRECTORY=3,exports.WASI_FILETYPE_REGULAR_FILE=4,exports.WASI_FILETYPE_SOCKET_DGRAM=5,exports.WASI_FILETYPE_SOCKET_STREAM=6,exports.WASI_FILETYPE_SYMBOLIC_LINK=7,exports.WASI_FDFLAG_APPEND=1,exports.WASI_FDFLAG_DSYNC=2,exports.WASI_FDFLAG_NONBLOCK=4,exports.WASI_FDFLAG_RSYNC=8,exports.WASI_FDFLAG_SYNC=16,exports.WASI_RIGHT_FD_DATASYNC=BigInt(1),exports.WASI_RIGHT_FD_READ=BigInt(2),exports.WASI_RIGHT_FD_SEEK=BigInt(4),exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS=BigInt(8),exports.WASI_RIGHT_FD_SYNC=BigInt(16),exports.WASI_RIGHT_FD_TELL=BigInt(32),exports.WASI_RIGHT_FD_WRITE=BigInt(64),exports.WASI_RIGHT_FD_ADVISE=BigInt(128),exports.WASI_RIGHT_FD_ALLOCATE=BigInt(256),exports.WASI_RIGHT_PATH_CREATE_DIRECTORY=BigInt(512),exports.WASI_RIGHT_PATH_CREATE_FILE=BigInt(1024),exports.WASI_RIGHT_PATH_LINK_SOURCE=BigInt(2048),exports.WASI_RIGHT_PATH_LINK_TARGET=BigInt(4096),exports.WASI_RIGHT_PATH_OPEN=BigInt(8192),exports.WASI_RIGHT_FD_READDIR=BigInt(16384),exports.WASI_RIGHT_PATH_READLINK=BigInt(32768),exports.WASI_RIGHT_PATH_RENAME_SOURCE=BigInt(65536),exports.WASI_RIGHT_PATH_RENAME_TARGET=BigInt(131072),exports.WASI_RIGHT_PATH_FILESTAT_GET=BigInt(262144),exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE=BigInt(524288),exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES=BigInt(1048576),exports.WASI_RIGHT_FD_FILESTAT_GET=BigInt(2097152),exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE=BigInt(4194304),exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES=BigInt(8388608),exports.WASI_RIGHT_PATH_SYMLINK=BigInt(16777216),exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY=BigInt(33554432),exports.WASI_RIGHT_PATH_UNLINK_FILE=BigInt(67108864),exports.WASI_RIGHT_POLL_FD_READWRITE=BigInt(134217728),exports.WASI_RIGHT_SOCK_SHUTDOWN=BigInt(268435456),exports.RIGHTS_ALL=exports.WASI_RIGHT_FD_DATASYNC|exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_SEEK|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_TELL|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_FD_ALLOCATE|exports.WASI_RIGHT_PATH_CREATE_DIRECTORY|exports.WASI_RIGHT_PATH_CREATE_FILE|exports.WASI_RIGHT_PATH_LINK_SOURCE|exports.WASI_RIGHT_PATH_LINK_TARGET|exports.WASI_RIGHT_PATH_OPEN|exports.WASI_RIGHT_FD_READDIR|exports.WASI_RIGHT_PATH_READLINK|exports.WASI_RIGHT_PATH_RENAME_SOURCE|exports.WASI_RIGHT_PATH_RENAME_TARGET|exports.WASI_RIGHT_PATH_FILESTAT_GET|exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_SYMLINK|exports.WASI_RIGHT_PATH_UNLINK_FILE|exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY|exports.WASI_RIGHT_POLL_FD_READWRITE|exports.WASI_RIGHT_SOCK_SHUTDOWN,exports.RIGHTS_BLOCK_DEVICE_BASE=exports.RIGHTS_ALL,exports.RIGHTS_BLOCK_DEVICE_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_CHARACTER_DEVICE_BASE=exports.RIGHTS_ALL,exports.RIGHTS_CHARACTER_DEVICE_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_REGULAR_FILE_BASE=exports.WASI_RIGHT_FD_DATASYNC|exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_SEEK|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_TELL|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_FD_ALLOCATE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_REGULAR_FILE_INHERITING=BigInt(0),exports.RIGHTS_DIRECTORY_BASE=exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_PATH_CREATE_DIRECTORY|exports.WASI_RIGHT_PATH_CREATE_FILE|exports.WASI_RIGHT_PATH_LINK_SOURCE|exports.WASI_RIGHT_PATH_LINK_TARGET|exports.WASI_RIGHT_PATH_OPEN|exports.WASI_RIGHT_FD_READDIR|exports.WASI_RIGHT_PATH_READLINK|exports.WASI_RIGHT_PATH_RENAME_SOURCE|exports.WASI_RIGHT_PATH_RENAME_TARGET|exports.WASI_RIGHT_PATH_FILESTAT_GET|exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_PATH_SYMLINK|exports.WASI_RIGHT_PATH_UNLINK_FILE|exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_DIRECTORY_INHERITING=exports.RIGHTS_DIRECTORY_BASE|exports.RIGHTS_REGULAR_FILE_BASE,exports.RIGHTS_SOCKET_BASE=exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_POLL_FD_READWRITE|exports.WASI_RIGHT_SOCK_SHUTDOWN,exports.RIGHTS_SOCKET_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_TTY_BASE=exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_TTY_INHERITING=BigInt(0),exports.WASI_CLOCK_REALTIME=0,exports.WASI_CLOCK_MONOTONIC=1,exports.WASI_CLOCK_PROCESS_CPUTIME_ID=2,exports.WASI_CLOCK_THREAD_CPUTIME_ID=3,exports.WASI_EVENTTYPE_CLOCK=0,exports.WASI_EVENTTYPE_FD_READ=1,exports.WASI_EVENTTYPE_FD_WRITE=2,exports.WASI_FILESTAT_SET_ATIM=1<<0,exports.WASI_FILESTAT_SET_ATIM_NOW=1<<1,exports.WASI_FILESTAT_SET_MTIM=1<<2,exports.WASI_FILESTAT_SET_MTIM_NOW=1<<3,exports.WASI_O_CREAT=1<<0,exports.WASI_O_DIRECTORY=1<<1,exports.WASI_O_EXCL=1<<2,exports.WASI_O_TRUNC=1<<3,exports.WASI_PREOPENTYPE_DIR=0,exports.WASI_DIRCOOKIE_START=0,exports.WASI_STDIN_FILENO=0,exports.WASI_STDOUT_FILENO=1,exports.WASI_STDERR_FILENO=2,exports.WASI_WHENCE_SET=0,exports.WASI_WHENCE_CUR=1,exports.WASI_WHENCE_END=2,exports.ERROR_MAP={E2BIG:exports.WASI_E2BIG,EACCES:exports.WASI_EACCES,EADDRINUSE:exports.WASI_EADDRINUSE,EADDRNOTAVAIL:exports.WASI_EADDRNOTAVAIL,EAFNOSUPPORT:exports.WASI_EAFNOSUPPORT,EALREADY:exports.WASI_EALREADY,EAGAIN:exports.WASI_EAGAIN,EBADF:exports.WASI_EBADF,EBADMSG:exports.WASI_EBADMSG,EBUSY:exports.WASI_EBUSY,ECANCELED:exports.WASI_ECANCELED,ECHILD:exports.WASI_ECHILD,ECONNABORTED:exports.WASI_ECONNABORTED,ECONNREFUSED:exports.WASI_ECONNREFUSED,ECONNRESET:exports.WASI_ECONNRESET,EDEADLOCK:exports.WASI_EDEADLK,EDESTADDRREQ:exports.WASI_EDESTADDRREQ,EDOM:exports.WASI_EDOM,EDQUOT:exports.WASI_EDQUOT,EEXIST:exports.WASI_EEXIST,EFAULT:exports.WASI_EFAULT,EFBIG:exports.WASI_EFBIG,EHOSTDOWN:exports.WASI_EHOSTUNREACH,EHOSTUNREACH:exports.WASI_EHOSTUNREACH,EIDRM:exports.WASI_EIDRM,EILSEQ:exports.WASI_EILSEQ,EINPROGRESS:exports.WASI_EINPROGRESS,EINTR:exports.WASI_EINTR,EINVAL:exports.WASI_EINVAL,EIO:exports.WASI_EIO,EISCONN:exports.WASI_EISCONN,EISDIR:exports.WASI_EISDIR,ELOOP:exports.WASI_ELOOP,EMFILE:exports.WASI_EMFILE,EMLINK:exports.WASI_EMLINK,EMSGSIZE:exports.WASI_EMSGSIZE,EMULTIHOP:exports.WASI_EMULTIHOP,ENAMETOOLONG:exports.WASI_ENAMETOOLONG,ENETDOWN:exports.WASI_ENETDOWN,ENETRESET:exports.WASI_ENETRESET,ENETUNREACH:exports.WASI_ENETUNREACH,ENFILE:exports.WASI_ENFILE,ENOBUFS:exports.WASI_ENOBUFS,ENODEV:exports.WASI_ENODEV,ENOENT:exports.WASI_ENOENT,ENOEXEC:exports.WASI_ENOEXEC,ENOLCK:exports.WASI_ENOLCK,ENOLINK:exports.WASI_ENOLINK,ENOMEM:exports.WASI_ENOMEM,ENOMSG:exports.WASI_ENOMSG,ENOPROTOOPT:exports.WASI_ENOPROTOOPT,ENOSPC:exports.WASI_ENOSPC,ENOSYS:exports.WASI_ENOSYS,ENOTCONN:exports.WASI_ENOTCONN,ENOTDIR:exports.WASI_ENOTDIR,ENOTEMPTY:exports.WASI_ENOTEMPTY,ENOTRECOVERABLE:exports.WASI_ENOTRECOVERABLE,ENOTSOCK:exports.WASI_ENOTSOCK,ENOTTY:exports.WASI_ENOTTY,ENXIO:exports.WASI_ENXIO,EOVERFLOW:exports.WASI_EOVERFLOW,EOWNERDEAD:exports.WASI_EOWNERDEAD,EPERM:exports.WASI_EPERM,EPIPE:exports.WASI_EPIPE,EPROTO:exports.WASI_EPROTO,EPROTONOSUPPORT:exports.WASI_EPROTONOSUPPORT,EPROTOTYPE:exports.WASI_EPROTOTYPE,ERANGE:exports.WASI_ERANGE,EROFS:exports.WASI_EROFS,ESPIPE:exports.WASI_ESPIPE,ESRCH:exports.WASI_ESRCH,ESTALE:exports.WASI_ESTALE,ETIMEDOUT:exports.WASI_ETIMEDOUT,ETXTBSY:exports.WASI_ETXTBSY,EXDEV:exports.WASI_EXDEV},exports.SIGNAL_MAP={[exports.WASI_SIGHUP]:\"SIGHUP\",[exports.WASI_SIGINT]:\"SIGINT\",[exports.WASI_SIGQUIT]:\"SIGQUIT\",[exports.WASI_SIGILL]:\"SIGILL\",[exports.WASI_SIGTRAP]:\"SIGTRAP\",[exports.WASI_SIGABRT]:\"SIGABRT\",[exports.WASI_SIGBUS]:\"SIGBUS\",[exports.WASI_SIGFPE]:\"SIGFPE\",[exports.WASI_SIGKILL]:\"SIGKILL\",[exports.WASI_SIGUSR1]:\"SIGUSR1\",[exports.WASI_SIGSEGV]:\"SIGSEGV\",[exports.WASI_SIGUSR2]:\"SIGUSR2\",[exports.WASI_SIGPIPE]:\"SIGPIPE\",[exports.WASI_SIGALRM]:\"SIGALRM\",[exports.WASI_SIGTERM]:\"SIGTERM\",[exports.WASI_SIGCHLD]:\"SIGCHLD\",[exports.WASI_SIGCONT]:\"SIGCONT\",[exports.WASI_SIGSTOP]:\"SIGSTOP\",[exports.WASI_SIGTSTP]:\"SIGTSTP\",[exports.WASI_SIGTTIN]:\"SIGTTIN\",[exports.WASI_SIGTTOU]:\"SIGTTOU\",[exports.WASI_SIGURG]:\"SIGURG\",[exports.WASI_SIGXCPU]:\"SIGXCPU\",[exports.WASI_SIGXFSZ]:\"SIGXFSZ\",[exports.WASI_SIGVTALRM]:\"SIGVTALRM\"}}}),require_wasi=__commonJS({\"node_modules/wasi-js/dist/wasi.js\"(exports){var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule\?mod:{default:mod}};let fs;Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.SOCKET_DEFAULT_RIGHTS=void 0;var log=()=>{},logOpen=()=>{},SC_OPEN_MAX=32768,types_1=require_types(),constants_1=require_constants(),STDIN_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_SYNC|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE,STDOUT_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_SYNC|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE,STDERR_DEFAULT_RIGHTS=STDOUT_DEFAULT_RIGHTS;exports.SOCKET_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE|constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS;var msToNs=(ms)=>{const msInt=Math.trunc(ms),decimal=BigInt(Math.round((ms-msInt)*1e6));return BigInt(msInt)*BigInt(1e6)+decimal},nsToMs=(ns)=>{if(typeof ns===\"number\")ns=Math.trunc(ns);const nsInt=BigInt(ns);return Number(nsInt/BigInt(1e6))},wrap=(f)=>(...args)=>{try{return f(...args)}catch(err){let e=err;while(e.prev!=null)e=e.prev;if(e\?.code&&typeof e\?.code===\"string\")return constants_1.ERROR_MAP[e.code]||constants_1.WASI_EINVAL;if(e instanceof types_1.WASIError)return e.errno;throw e}},stat=(wasi,fd)=>{const entry=wasi.FD_MAP.get(fd);if(!entry)throw new types_1.WASIError(constants_1.WASI_EBADF);if(entry.filetype===void 0){const stats=wasi.fstatSync(entry.real),{filetype,rightsBase,rightsInheriting}=translateFileAttributes(wasi,fd,stats);if(entry.filetype=filetype,!entry.rights)entry.rights={base:rightsBase,inheriting:rightsInheriting}}return entry},translateFileAttributes=(wasi,fd,stats)=>{switch(!0){case stats.isBlockDevice():return{filetype:constants_1.WASI_FILETYPE_BLOCK_DEVICE,rightsBase:constants_1.RIGHTS_BLOCK_DEVICE_BASE,rightsInheriting:constants_1.RIGHTS_BLOCK_DEVICE_INHERITING};case stats.isCharacterDevice():{const filetype=constants_1.WASI_FILETYPE_CHARACTER_DEVICE;if(fd!==void 0&&wasi.bindings.isTTY(fd))return{filetype,rightsBase:constants_1.RIGHTS_TTY_BASE,rightsInheriting:constants_1.RIGHTS_TTY_INHERITING};return{filetype,rightsBase:constants_1.RIGHTS_CHARACTER_DEVICE_BASE,rightsInheriting:constants_1.RIGHTS_CHARACTER_DEVICE_INHERITING}}case stats.isDirectory():return{filetype:constants_1.WASI_FILETYPE_DIRECTORY,rightsBase:constants_1.RIGHTS_DIRECTORY_BASE,rightsInheriting:constants_1.RIGHTS_DIRECTORY_INHERITING};case stats.isFIFO():return{filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rightsBase:constants_1.RIGHTS_SOCKET_BASE,rightsInheriting:constants_1.RIGHTS_SOCKET_INHERITING};case stats.isFile():return{filetype:constants_1.WASI_FILETYPE_REGULAR_FILE,rightsBase:constants_1.RIGHTS_REGULAR_FILE_BASE,rightsInheriting:constants_1.RIGHTS_REGULAR_FILE_INHERITING};case stats.isSocket():return{filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rightsBase:constants_1.RIGHTS_SOCKET_BASE,rightsInheriting:constants_1.RIGHTS_SOCKET_INHERITING};case stats.isSymbolicLink():return{filetype:constants_1.WASI_FILETYPE_SYMBOLIC_LINK,rightsBase:BigInt(0),rightsInheriting:BigInt(0)};default:return{filetype:constants_1.WASI_FILETYPE_UNKNOWN,rightsBase:BigInt(0),rightsInheriting:BigInt(0)}}},warnedAboutSleep=!1,defaultConfig;function getDefaults(){if(defaultConfig)return defaultConfig;const defaultBindings={hrtime:()=>process.hrtime.bigint(),exit:(code)=>{process.exit(code)},kill:(signal)=>{process.kill(process.pid,signal)},randomFillSync:(array)=>crypto.getRandomValues(array),isTTY:(fd)=>@requireNativeModule(\"node:tty\").isatty(fd),fs:Bun.fs(),path:@getInternalField(@internalModuleRegistry,25)||@createInternalModuleById(25)};return defaultConfig={args:[],env:{},preopens:{},bindings:defaultBindings,sleep:(ms)=>{Bun.sleepSync(ms)}}}var WASI=class WASI2{constructor(wasiConfig={}){const defaultConfig2=getDefaults();this.lastStdin=0,this.sleep=wasiConfig.sleep||defaultConfig2.sleep,this.getStdin=wasiConfig.getStdin,this.sendStdout=wasiConfig.sendStdout,this.sendStderr=wasiConfig.sendStderr;let preopens=wasiConfig.preopens\?\?defaultConfig2.preopens;this.env=wasiConfig.env\?\?defaultConfig2.env;const args=wasiConfig.args\?\?defaultConfig2.args;this.memory=void 0,this.view=void 0,this.bindings=wasiConfig.bindings||defaultConfig2.bindings;const bindings2=this.bindings;fs=bindings2.fs,this.FD_MAP=new Map([[constants_1.WASI_STDIN_FILENO,{real:0,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDIN_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stdin\"}],[constants_1.WASI_STDOUT_FILENO,{real:1,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDOUT_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stdout\"}],[constants_1.WASI_STDERR_FILENO,{real:2,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDERR_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stderr\"}]]);const path=bindings2.path;for(let[k,v]of Object.entries(preopens)){const real=fs.openSync(v,nodeFsConstants.O_RDONLY),newfd=this.getUnusedFileDescriptor();this.FD_MAP.set(newfd,{real,filetype:constants_1.WASI_FILETYPE_DIRECTORY,rights:{base:constants_1.RIGHTS_DIRECTORY_BASE,inheriting:constants_1.RIGHTS_DIRECTORY_INHERITING},fakePath:k,path:v})}const getiovs=(iovs,iovsLen)=>{this.refreshMemory();const{view,memory}=this,{buffer}=memory,{byteLength}=buffer;if(iovsLen===1){const ptr=iovs,buf=view.getUint32(ptr,!0);let bufLen=view.getUint32(ptr+4,!0);if(bufLen>byteLength-buf)console.log({buf,bufLen,total_memory:byteLength}),log(\"getiovs: warning -- truncating buffer to fit in memory\"),bufLen=Math.min(bufLen,Math.max(0,byteLength-buf));try{return[new Uint8Array(buffer,buf,bufLen)]}catch(err){throw console.warn(\"WASI.getiovs -- invalid buffer\",err),new types_1.WASIError(constants_1.WASI_EINVAL)}}const buffers=[];buffers.length=iovsLen;for(let i=0,ptr=iovs;ibyteLength-buf)console.log({buf,bufLen,total_memory:byteLength}),log(\"getiovs: warning -- truncating buffer to fit in memory\"),bufLen=Math.min(bufLen,Math.max(0,byteLength-buf));try{buffers[i]=new Uint8Array(buffer,buf,bufLen)}catch(err){throw console.warn(\"WASI.getiovs -- invalid buffer\",err),new types_1.WASIError(constants_1.WASI_EINVAL)}}return buffers},CHECK_FD=(fd,rights)=>{const stats=stat(this,fd);if(rights!==BigInt(0)&&(stats.rights.base&rights)===BigInt(0))throw new types_1.WASIError(constants_1.WASI_EPERM);return stats},CPUTIME_START=Bun.nanoseconds(),timeOrigin=Math.trunc(performance.timeOrigin*1e6),now=(clockId)=>{switch(clockId){case constants_1.WASI_CLOCK_MONOTONIC:return Bun.nanoseconds();case constants_1.WASI_CLOCK_REALTIME:return Bun.nanoseconds()+timeOrigin;case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID:case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID:return Bun.nanoseconds()-CPUTIME_START;default:return null}};if(this.wasiImport={args_get:(argv,argvBuf)=>{this.refreshMemory();let coffset=argv,offset=argvBuf;return args.forEach((a)=>{this.view.setUint32(coffset,offset,!0),coffset+=4,offset+=Buffer.from(this.memory.buffer).write(`${a}\\0`,offset)}),constants_1.WASI_ESUCCESS},args_sizes_get:(argc,argvBufSize)=>{this.refreshMemory(),this.view.setUint32(argc,args.length,!0);const size=args.reduce((acc,a)=>acc+Buffer.byteLength(a)+1,0);return this.view.setUint32(argvBufSize,size,!0),constants_1.WASI_ESUCCESS},environ_get:(environ,environBuf)=>{this.refreshMemory();let coffset=environ,offset=environBuf;return Object.entries(this.env).forEach(([key,value])=>{this.view.setUint32(coffset,offset,!0),coffset+=4,offset+=Buffer.from(this.memory.buffer).write(`${key}=${value}\\0`,offset)}),constants_1.WASI_ESUCCESS},environ_sizes_get:(environCount,environBufSize)=>{this.refreshMemory();const envProcessed=Object.entries(this.env).map(([key,value])=>`${key}=${value}\\0`),size=envProcessed.reduce((acc,e)=>acc+Buffer.byteLength(e),0);return this.view.setUint32(environCount,envProcessed.length,!0),this.view.setUint32(environBufSize,size,!0),constants_1.WASI_ESUCCESS},clock_res_get:(clockId,resolution)=>{let res;switch(clockId){case constants_1.WASI_CLOCK_MONOTONIC:case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID:case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID:{res=BigInt(1);break}case constants_1.WASI_CLOCK_REALTIME:{res=BigInt(1000);break}}if(!res)throw Error(\"invalid clockId\");return this.view.setBigUint64(resolution,res),constants_1.WASI_ESUCCESS},clock_time_get:(clockId,_precision,time)=>{this.refreshMemory();const n=now(clockId);if(n===null)return constants_1.WASI_EINVAL;return this.view.setBigUint64(time,BigInt(n),!0),constants_1.WASI_ESUCCESS},fd_advise:wrap((fd,_offset,_len,_advice)=>{return CHECK_FD(fd,constants_1.WASI_RIGHT_FD_ADVISE),constants_1.WASI_ENOSYS}),fd_allocate:wrap((fd,_offset,_len)=>{return CHECK_FD(fd,constants_1.WASI_RIGHT_FD_ALLOCATE),constants_1.WASI_ENOSYS}),fd_close:wrap((fd)=>{const stats=CHECK_FD(fd,BigInt(0));return fs.closeSync(stats.real),this.FD_MAP.delete(fd),constants_1.WASI_ESUCCESS}),fd_datasync:wrap((fd)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_DATASYNC);return fs.fdatasyncSync(stats.real),constants_1.WASI_ESUCCESS}),fd_fdstat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,BigInt(0));if(this.refreshMemory(),stats.filetype==null)throw Error(\"stats.filetype must be set\");return this.view.setUint8(bufPtr,stats.filetype),this.view.setUint16(bufPtr+2,0,!0),this.view.setUint16(bufPtr+4,0,!0),this.view.setBigUint64(bufPtr+8,BigInt(stats.rights.base),!0),this.view.setBigUint64(bufPtr+8+8,BigInt(stats.rights.inheriting),!0),constants_1.WASI_ESUCCESS}),fd_fdstat_set_flags:wrap((fd,flags)=>{if(CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS),this.wasiImport.sock_fcntlSetFlags(fd,flags)==0)return constants_1.WASI_ESUCCESS;return constants_1.WASI_ENOSYS}),fd_fdstat_set_rights:wrap((fd,fsRightsBase,fsRightsInheriting)=>{const stats=CHECK_FD(fd,BigInt(0));if((stats.rights.base|fsRightsBase)>stats.rights.base)return constants_1.WASI_EPERM;if((stats.rights.inheriting|fsRightsInheriting)>stats.rights.inheriting)return constants_1.WASI_EPERM;return stats.rights.base=fsRightsBase,stats.rights.inheriting=fsRightsInheriting,constants_1.WASI_ESUCCESS}),fd_filestat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_GET),rstats=this.fstatSync(stats.real);if(this.refreshMemory(),this.view.setBigUint64(bufPtr,BigInt(rstats.dev),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,stats.filetype==null)throw Error(\"stats.filetype must be set\");return this.view.setUint8(bufPtr,stats.filetype),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.nlink),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.size),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.atimeMs),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.mtimeMs),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.ctimeMs),!0),constants_1.WASI_ESUCCESS}),fd_filestat_set_size:wrap((fd,stSize)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE);return fs.ftruncateSync(stats.real,Number(stSize)),constants_1.WASI_ESUCCESS}),fd_filestat_set_times:wrap((fd,stAtim,stMtim,fstflags)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_SET_TIMES),rstats=this.fstatSync(stats.real);let{atime:atim,mtime:mtim}=rstats;const n=nsToMs(now(constants_1.WASI_CLOCK_REALTIME)),atimflags=constants_1.WASI_FILESTAT_SET_ATIM|constants_1.WASI_FILESTAT_SET_ATIM_NOW;if((fstflags&atimflags)===atimflags)return constants_1.WASI_EINVAL;const mtimflags=constants_1.WASI_FILESTAT_SET_MTIM|constants_1.WASI_FILESTAT_SET_MTIM_NOW;if((fstflags&mtimflags)===mtimflags)return constants_1.WASI_EINVAL;if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM)===constants_1.WASI_FILESTAT_SET_ATIM)atim=nsToMs(stAtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM_NOW)===constants_1.WASI_FILESTAT_SET_ATIM_NOW)atim=n;if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM)===constants_1.WASI_FILESTAT_SET_MTIM)mtim=nsToMs(stMtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM_NOW)===constants_1.WASI_FILESTAT_SET_MTIM_NOW)mtim=n;return fs.futimesSync(stats.real,new Date(atim),new Date(mtim)),constants_1.WASI_ESUCCESS}),fd_prestat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,BigInt(0));return this.refreshMemory(),this.view.setUint8(bufPtr,constants_1.WASI_PREOPENTYPE_DIR),this.view.setUint32(bufPtr+4,Buffer.byteLength(stats.fakePath\?\?stats.path\?\?\"\"),!0),constants_1.WASI_ESUCCESS}),fd_prestat_dir_name:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,BigInt(0));return this.refreshMemory(),Buffer.from(this.memory.buffer).write(stats.fakePath\?\?stats.path\?\?\"\",pathPtr,pathLen,\"utf8\"),constants_1.WASI_ESUCCESS}),fd_pwrite:wrap((fd,iovs,iovsLen,offset,nwritten)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_SEEK);let written=0;return getiovs(iovs,iovsLen).forEach((iov)=>{let w=0;while(w{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_WRITE),IS_STDOUT=fd==constants_1.WASI_STDOUT_FILENO,IS_STDERR=fd==constants_1.WASI_STDERR_FILENO;let written=0;return getiovs(iovs,iovsLen).forEach((iov)=>{if(iov.byteLength==0)return;if(IS_STDOUT&&this.sendStdout!=null)this.sendStdout(iov),written+=iov.byteLength;else if(IS_STDERR&&this.sendStderr!=null)this.sendStderr(iov),written+=iov.byteLength;else{let w=0;while(w{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_SEEK);let read=0;outer:for(let iov of getiovs(iovs,iovsLen)){let r=0;while(r{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READ),IS_STDIN=fd==constants_1.WASI_STDIN_FILENO;let read=0;outer:for(let iov of getiovs(iovs,iovsLen)){let r=0;while(r0)this.lastStdin=(new Date()).valueOf()}}else{if(this.sleep==null&&!warnedAboutSleep)warnedAboutSleep=!0,console.log(\"(cpu waiting for stdin: please define a way to sleep!) \");try{rr=fs.readSync(stats.real,iov,r,length,position)}catch(_err){}if(rr==0)this.shortPause();else this.lastStdin=(new Date()).valueOf()}else rr=fs.readSync(stats.real,iov,r,length,position);if(stats.filetype==constants_1.WASI_FILETYPE_REGULAR_FILE)stats.offset=(stats.offset\?stats.offset:BigInt(0))+BigInt(rr);if(r+=rr,read+=rr,rr===0||rr{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READDIR);this.refreshMemory();const entries=fs.readdirSync(stats.path,{withFileTypes:!0}),startPtr=bufPtr;for(let i=Number(cookie);ibufLen)break;if(this.view.setBigUint64(bufPtr,BigInt(i+1),!0),bufPtr+=8,bufPtr-startPtr>bufLen)break;const rstats=fs.lstatSync(path.resolve(stats.path,entry.name));if(this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,bufPtr-startPtr>bufLen)break;if(this.view.setUint32(bufPtr,nameLength,!0),bufPtr+=4,bufPtr-startPtr>bufLen)break;let filetype;switch(!0){case rstats.isBlockDevice():filetype=constants_1.WASI_FILETYPE_BLOCK_DEVICE;break;case rstats.isCharacterDevice():filetype=constants_1.WASI_FILETYPE_CHARACTER_DEVICE;break;case rstats.isDirectory():filetype=constants_1.WASI_FILETYPE_DIRECTORY;break;case rstats.isFIFO():filetype=constants_1.WASI_FILETYPE_SOCKET_STREAM;break;case rstats.isFile():filetype=constants_1.WASI_FILETYPE_REGULAR_FILE;break;case rstats.isSocket():filetype=constants_1.WASI_FILETYPE_SOCKET_STREAM;break;case rstats.isSymbolicLink():filetype=constants_1.WASI_FILETYPE_SYMBOLIC_LINK;break;default:filetype=constants_1.WASI_FILETYPE_UNKNOWN;break}if(this.view.setUint8(bufPtr,filetype),bufPtr+=1,bufPtr+=3,bufPtr+nameLength>=startPtr+bufLen)break;Buffer.from(this.memory.buffer).write(entry.name,bufPtr),bufPtr+=nameLength}const bufused=bufPtr-startPtr;return this.view.setUint32(bufusedPtr,Math.min(bufused,bufLen),!0),constants_1.WASI_ESUCCESS}),fd_renumber:wrap((from,to)=>{return CHECK_FD(from,BigInt(0)),CHECK_FD(to,BigInt(0)),fs.closeSync(this.FD_MAP.get(from).real),this.FD_MAP.set(from,this.FD_MAP.get(to)),this.FD_MAP.delete(to),constants_1.WASI_ESUCCESS}),fd_seek:wrap((fd,offset,whence,newOffsetPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_SEEK);switch(this.refreshMemory(),whence){case constants_1.WASI_WHENCE_CUR:stats.offset=(stats.offset\?stats.offset:BigInt(0))+BigInt(offset);break;case constants_1.WASI_WHENCE_END:const{size}=this.fstatSync(stats.real);stats.offset=BigInt(size)+BigInt(offset);break;case constants_1.WASI_WHENCE_SET:stats.offset=BigInt(offset);break}if(stats.offset==null)throw Error(\"stats.offset must be defined\");return this.view.setBigUint64(newOffsetPtr,stats.offset,!0),constants_1.WASI_ESUCCESS}),fd_tell:wrap((fd,offsetPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_TELL);if(this.refreshMemory(),!stats.offset)stats.offset=BigInt(0);return this.view.setBigUint64(offsetPtr,stats.offset,!0),constants_1.WASI_ESUCCESS}),fd_sync:wrap((fd)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_SYNC);return fs.fsyncSync(stats.real),constants_1.WASI_ESUCCESS}),path_create_directory:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_CREATE_DIRECTORY);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.mkdirSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),path_filestat_get:wrap((fd,flags,pathPtr,pathLen,bufPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_FILESTAT_GET);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();let rstats;if(flags)rstats=fs.statSync(path.resolve(stats.path,p));else rstats=fs.lstatSync(path.resolve(stats.path,p));return this.view.setBigUint64(bufPtr,BigInt(rstats.dev),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,this.view.setUint8(bufPtr,translateFileAttributes(this,void 0,rstats).filetype),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.nlink),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.size),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.atime.getTime()*1e6),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.mtime.getTime()*1e6),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ctime.getTime()*1e6),!0),constants_1.WASI_ESUCCESS}),path_filestat_set_times:wrap((fd,_dirflags,pathPtr,pathLen,stAtim,stMtim,fstflags)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_FILESTAT_SET_TIMES);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const rstats=this.fstatSync(stats.real);let{atime:atim,mtime:mtim}=rstats;const n=nsToMs(now(constants_1.WASI_CLOCK_REALTIME)),atimflags=constants_1.WASI_FILESTAT_SET_ATIM|constants_1.WASI_FILESTAT_SET_ATIM_NOW;if((fstflags&atimflags)===atimflags)return constants_1.WASI_EINVAL;const mtimflags=constants_1.WASI_FILESTAT_SET_MTIM|constants_1.WASI_FILESTAT_SET_MTIM_NOW;if((fstflags&mtimflags)===mtimflags)return constants_1.WASI_EINVAL;if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM)===constants_1.WASI_FILESTAT_SET_ATIM)atim=nsToMs(stAtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM_NOW)===constants_1.WASI_FILESTAT_SET_ATIM_NOW)atim=n;if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM)===constants_1.WASI_FILESTAT_SET_MTIM)mtim=nsToMs(stMtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM_NOW)===constants_1.WASI_FILESTAT_SET_MTIM_NOW)mtim=n;const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.utimesSync(path.resolve(stats.path,p),new Date(atim),new Date(mtim)),constants_1.WASI_ESUCCESS}),path_link:wrap((oldFd,_oldFlags,oldPath,oldPathLen,newFd,newPath,newPathLen)=>{const ostats=CHECK_FD(oldFd,constants_1.WASI_RIGHT_PATH_LINK_SOURCE),nstats=CHECK_FD(newFd,constants_1.WASI_RIGHT_PATH_LINK_TARGET);if(!ostats.path||!nstats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.linkSync(path.resolve(ostats.path,op),path.resolve(nstats.path,np)),constants_1.WASI_ESUCCESS}),path_open:wrap((dirfd,_dirflags,pathPtr,pathLen,oflags,fsRightsBase,fsRightsInheriting,fsFlags,fdPtr)=>{try{const stats=CHECK_FD(dirfd,constants_1.WASI_RIGHT_PATH_OPEN);fsRightsBase=BigInt(fsRightsBase),fsRightsInheriting=BigInt(fsRightsInheriting);const read=(fsRightsBase&(constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_READDIR))!==BigInt(0),write=(fsRightsBase&(constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_ALLOCATE|constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE))!==BigInt(0);let noflags;if(write&&read)noflags=nodeFsConstants.O_RDWR;else if(read)noflags=nodeFsConstants.O_RDONLY;else if(write)noflags=nodeFsConstants.O_WRONLY;let neededBase=fsRightsBase|constants_1.WASI_RIGHT_PATH_OPEN,neededInheriting=fsRightsBase|fsRightsInheriting;if((oflags&constants_1.WASI_O_CREAT)!==0)noflags|=nodeFsConstants.O_CREAT,neededBase|=constants_1.WASI_RIGHT_PATH_CREATE_FILE;if((oflags&constants_1.WASI_O_DIRECTORY)!==0)noflags|=nodeFsConstants.O_DIRECTORY;if((oflags&constants_1.WASI_O_EXCL)!==0)noflags|=nodeFsConstants.O_EXCL;if((oflags&constants_1.WASI_O_TRUNC)!==0)noflags|=nodeFsConstants.O_TRUNC,neededBase|=constants_1.WASI_RIGHT_PATH_FILESTAT_SET_SIZE;if((fsFlags&constants_1.WASI_FDFLAG_APPEND)!==0)noflags|=nodeFsConstants.O_APPEND;if((fsFlags&constants_1.WASI_FDFLAG_DSYNC)!==0){if(nodeFsConstants.O_DSYNC)noflags|=nodeFsConstants.O_DSYNC;else noflags|=nodeFsConstants.O_SYNC;neededInheriting|=constants_1.WASI_RIGHT_FD_DATASYNC}if((fsFlags&constants_1.WASI_FDFLAG_NONBLOCK)!==0)noflags|=nodeFsConstants.O_NONBLOCK;if((fsFlags&constants_1.WASI_FDFLAG_RSYNC)!==0){if(nodeFsConstants.O_RSYNC)noflags|=nodeFsConstants.O_RSYNC;else noflags|=nodeFsConstants.O_SYNC;neededInheriting|=constants_1.WASI_RIGHT_FD_SYNC}if((fsFlags&constants_1.WASI_FDFLAG_SYNC)!==0)noflags|=nodeFsConstants.O_SYNC,neededInheriting|=constants_1.WASI_RIGHT_FD_SYNC;if(write&&(noflags&(nodeFsConstants.O_APPEND|nodeFsConstants.O_TRUNC))===0)neededInheriting|=constants_1.WASI_RIGHT_FD_SEEK;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();if(p==\"dev/tty\")return this.view.setUint32(fdPtr,constants_1.WASI_STDIN_FILENO,!0),constants_1.WASI_ESUCCESS;if(logOpen(\"path_open\",p),p.startsWith(\"proc/\"))throw new types_1.WASIError(constants_1.WASI_EBADF);const fullUnresolved=path.resolve(p);let full;try{full=fs.realpathSync(fullUnresolved)}catch(e){if(e\?.code===\"ENOENT\")full=fullUnresolved;else throw e}let isDirectory;if(write)try{isDirectory=fs.statSync(full).isDirectory()}catch(_err){}let realfd;if(!write&&isDirectory)realfd=fs.openSync(full,nodeFsConstants.O_RDONLY);else realfd=fs.openSync(full,noflags);const newfd=this.getUnusedFileDescriptor();this.FD_MAP.set(newfd,{real:realfd,filetype:void 0,rights:{base:neededBase,inheriting:neededInheriting},path:full}),stat(this,newfd),this.view.setUint32(fdPtr,newfd,!0)}catch(e){console.error(e)}return constants_1.WASI_ESUCCESS}),path_readlink:wrap((fd,pathPtr,pathLen,buf,bufLen,bufused)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_READLINK);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString(),full=path.resolve(stats.path,p),r=fs.readlinkSync(full),used=Buffer.from(this.memory.buffer).write(r,buf,bufLen);return this.view.setUint32(bufused,used,!0),constants_1.WASI_ESUCCESS}),path_remove_directory:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_REMOVE_DIRECTORY);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.rmdirSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),path_rename:wrap((oldFd,oldPath,oldPathLen,newFd,newPath,newPathLen)=>{const ostats=CHECK_FD(oldFd,constants_1.WASI_RIGHT_PATH_RENAME_SOURCE),nstats=CHECK_FD(newFd,constants_1.WASI_RIGHT_PATH_RENAME_TARGET);if(!ostats.path||!nstats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.renameSync(path.resolve(ostats.path,op),path.resolve(nstats.path,np)),constants_1.WASI_ESUCCESS}),path_symlink:wrap((oldPath,oldPathLen,fd,newPath,newPathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_SYMLINK);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.symlinkSync(op,path.resolve(stats.path,np)),constants_1.WASI_ESUCCESS}),path_unlink_file:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_UNLINK_FILE);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.unlinkSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),poll_oneoff:(sin,sout,nsubscriptions,neventsPtr)=>{let nevents=0,name=\"\",waitTimeNs=BigInt(0),fd=-1,fd_type=\"read\",fd_timeout_ms=0;const startNs=BigInt(bindings2.hrtime());this.refreshMemory();let last_sin=sin;for(let i=0;iwaitTimeNs)waitTimeNs=waitNs}this.view.setBigUint64(sout,userdata,!0),sout+=8,this.view.setUint16(sout,e,!0),sout+=2,this.view.setUint8(sout,constants_1.WASI_EVENTTYPE_CLOCK),sout+=1,sout+=5,nevents+=1;break}case constants_1.WASI_EVENTTYPE_FD_READ:case constants_1.WASI_EVENTTYPE_FD_WRITE:{if(fd=this.view.getUint32(sin,!0),fd_type=type==constants_1.WASI_EVENTTYPE_FD_READ\?\"read\":\"write\",sin+=4,log(name,\"fd =\",fd),sin+=28,this.view.setBigUint64(sout,userdata,!0),sout+=8,this.view.setUint16(sout,constants_1.WASI_ENOSYS,!0),sout+=2,this.view.setUint8(sout,type),sout+=1,sout+=5,nevents+=1,fd==constants_1.WASI_STDIN_FILENO&&constants_1.WASI_EVENTTYPE_FD_READ==type)this.shortPause();break}default:return constants_1.WASI_EINVAL}if(sin-last_sin!=48)console.warn(\"*** BUG in wasi-js in poll_oneoff \",{i,sin,last_sin,diff:sin-last_sin});last_sin=sin}if(this.view.setUint32(neventsPtr,nevents,!0),nevents==2&&fd>=0){const r=this.wasiImport.sock_pollSocket(fd,fd_type,fd_timeout_ms);if(r!=constants_1.WASI_ENOSYS)return r}if(waitTimeNs>0){if(waitTimeNs-=Bun.nanoseconds()-timeOrigin,waitTimeNs>=1e6){if(this.sleep==null&&!warnedAboutSleep)warnedAboutSleep=!0,console.log(\"(100% cpu burning waiting for stdin: please define a way to sleep!) \");if(this.sleep!=null){const ms=nsToMs(waitTimeNs);this.sleep(ms)}else{const end=BigInt(bindings2.hrtime())+waitTimeNs;while(BigInt(bindings2.hrtime()){return bindings2.exit(rval),constants_1.WASI_ESUCCESS},proc_raise:(sig)=>{if(!(sig in constants_1.SIGNAL_MAP))return constants_1.WASI_EINVAL;return bindings2.kill(constants_1.SIGNAL_MAP[sig]),constants_1.WASI_ESUCCESS},random_get:(bufPtr,bufLen)=>{return this.refreshMemory(),crypto.getRandomValues(this.memory.buffer,bufPtr,bufLen),bufLen},sched_yield(){return constants_1.WASI_ESUCCESS},sock_recv(){return constants_1.WASI_ENOSYS},sock_send(){return constants_1.WASI_ENOSYS},sock_shutdown(){return constants_1.WASI_ENOSYS},sock_fcntlSetFlags(_fd,_flags){return constants_1.WASI_ENOSYS},sock_pollSocket(_fd,_eventtype,_timeout_ms){return constants_1.WASI_ENOSYS}},log.enabled)Object.keys(this.wasiImport).forEach((key)=>{const prevImport=this.wasiImport[key];this.wasiImport[key]=function(...args2){log(key,args2);try{let result=prevImport(...args2);return log(\"result\",result),result}catch(e){throw log(\"error: \",e),e}}})}getState(){return{env:this.env,FD_MAP:this.FD_MAP,bindings}}setState(state){this.env=state.env,this.FD_MAP=state.FD_MAP,bindings=state.bindings}fstatSync(real_fd){if(real_fd<=2)try{return fs.fstatSync(real_fd)}catch(_){const now=new Date;return{dev:0,mode:8592,nlink:1,uid:0,gid:0,rdev:0,blksize:65536,ino:0,size:0,blocks:0,atimeMs:now.valueOf(),mtimeMs:now.valueOf(),ctimeMs:now.valueOf(),birthtimeMs:0,atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date(0)}}return fs.fstatSync(real_fd)}shortPause(){if(this.sleep==null)return;if((new Date()).valueOf()-this.lastStdin>2000)this.sleep(50)}getUnusedFileDescriptor(start=3){let fd=start;while(this.FD_MAP.has(fd))fd+=1;if(fd>SC_OPEN_MAX)throw Error(\"no available file descriptors\");return fd}refreshMemory(){if(!this.view||this.view.buffer.byteLength===0)this.view=new DataView(this.memory.buffer)}setMemory(memory){this.memory=memory}start(instance,memory){const exports2=instance.exports;if(exports2===null||typeof exports2!==\"object\")throw new Error(`instance.exports must be an Object. Received ${exports2}.`);if(memory==null){if(memory=exports2.memory,!(memory instanceof WebAssembly.Memory))throw new Error(`instance.exports.memory must be a WebAssembly.Memory. Recceived ${memory}.`)}if(this.setMemory(memory),exports2._start)exports2._start()}getImports(module2){let namespace=null;const imports=WebAssembly.Module.imports(module2);for(let imp of imports){if(imp.kind!==\"function\")continue;if(!imp.module.startsWith(\"wasi_\"))continue;namespace=imp.module;break}switch(namespace){case\"wasi_unstable\":return{wasi_unstable:this.wasiImport};case\"wasi_snapshot_preview1\":return{wasi_snapshot_preview1:this.wasiImport};default:throw new Error(\"No WASI namespace found. Only wasi_unstable and wasi_snapshot_preview1 are supported.\\n\\nList of imports:\\n\\n\"+imports.map(({name,kind,module})=>`${module}:${name} (${kind})`).join(\"\\n\")+\"\\n\")}}initWasiFdInfo(){if(this.env.WASI_FD_INFO!=null){const fdInfo=JSON.parse(this.env.WASI_FD_INFO);for(let wasi_fd in fdInfo){console.log(wasi_fd);const fd=parseInt(wasi_fd);if(this.FD_MAP.has(fd))continue;const real=fdInfo[wasi_fd];try{this.fstatSync(real)}catch(_err){console.log(\"discarding \",{wasi_fd,real});continue}const file={real,filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rights:{base:STDIN_DEFAULT_RIGHTS,inheriting:BigInt(0)}};this.FD_MAP.set(fd,file)}console.log(\"after initWasiFdInfo: \",this.FD_MAP),console.log(\"fdInfo = \",fdInfo)}else console.log(\"no WASI_FD_INFO\")}};exports.default=WASI}});return{WASI:require_wasi().default}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeWorkerThreadsCode = "(function (){\"use strict\";var $;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),{MessageChannel,BroadcastChannel,Worker:WebWorker}=globalThis,SHARE_ENV=Symbol(\"nodejs.worker_threads.SHARE_ENV\"),isMainThread=Bun.isMainThread;let[_workerData,_threadId,_receiveMessageOnPort]=globalThis[globalThis.Symbol.for('Bun.lazy')](\"worker_threads\");const emittedWarnings=new Set;function emitWarning(type,message){if(emittedWarnings.has(type))return;emittedWarnings.add(type),console.warn(\"[bun] Warning:\",message)}function injectFakeEmitter(Class){function messageEventHandler(event){return event.data}function errorEventHandler(event){return event.error}const wrappedListener=Symbol(\"wrappedListener\");function wrapped(run,listener){const callback=function(event){return listener(run(event))};return listener[wrappedListener]=callback,callback}function functionForEventType(event,listener){switch(event){case\"error\":case\"messageerror\":return wrapped(errorEventHandler,listener);default:return wrapped(messageEventHandler,listener)}}Class.prototype.on=function(event,listener){return this.addEventListener(event,functionForEventType(event,listener)),this},Class.prototype.off=function(event,listener){if(listener)this.removeEventListener(event,listener[wrappedListener]||listener);else this.removeEventListener(event);return this},Class.prototype.once=function(event,listener){return this.addEventListener(event,functionForEventType(event,listener),{once:!0}),this};function EventClass(eventName){if(eventName===\"error\"||eventName===\"messageerror\")return ErrorEvent;return MessageEvent}Class.prototype.emit=function(event,...args){return this.dispatchEvent(new(EventClass(event))(event,...args)),this},Class.prototype.prependListener=Class.prototype.on,Class.prototype.prependOnceListener=Class.prototype.once}const _MessagePort=globalThis.MessagePort;injectFakeEmitter(_MessagePort);const MessagePort=_MessagePort;let resourceLimits={},workerData=_workerData,threadId=_threadId;function receiveMessageOnPort(port){let res=_receiveMessageOnPort(port);if(!res)return;return{message:res}}function fakeParentPort(){const fake=Object.create(MessagePort.prototype);return Object.defineProperty(fake,\"onmessage\",{get(){return self.onmessage},set(value){self.onmessage=value}}),Object.defineProperty(fake,\"onmessageerror\",{get(){return self.onmessageerror},set(value){}}),Object.defineProperty(fake,\"postMessage\",{value(...args){return self.postMessage(...args)}}),Object.defineProperty(fake,\"close\",{value(){return process.exit(0)}}),Object.defineProperty(fake,\"start\",{value(){}}),Object.defineProperty(fake,\"unref\",{value(){}}),Object.defineProperty(fake,\"ref\",{value(){}}),Object.defineProperty(fake,\"hasRef\",{value(){return!1}}),Object.defineProperty(fake,\"setEncoding\",{value(){}}),Object.defineProperty(fake,\"addEventListener\",{value:self.addEventListener.bind(self)}),Object.defineProperty(fake,\"removeEventListener\",{value:self.removeEventListener.bind(self)}),fake}let parentPort=isMainThread\?null:fakeParentPort();function getEnvironmentData(){return process.env}function setEnvironmentData(env){process.env=env}function markAsUntransferable(){throwNotImplemented(\"worker_threads.markAsUntransferable\")}function moveMessagePortToContext(){throwNotImplemented(\"worker_threads.moveMessagePortToContext\")}const unsupportedOptions=[\"eval\",\"argv\",\"execArgv\",\"stdin\",\"stdout\",\"stderr\",\"trackedUnmanagedFds\",\"resourceLimits\"];class Worker extends EventEmitter{#worker;#performance;#onExitPromise=void 0;constructor(filename,options={}){super();for(let key of unsupportedOptions)if(key in options)emitWarning(\"option.\"+key,`worker_threads.Worker option \"${key}\" is not implemented.`);this.#worker=new WebWorker(filename,options),this.#worker.addEventListener(\"close\",this.#onClose.bind(this)),this.#worker.addEventListener(\"error\",this.#onError.bind(this)),this.#worker.addEventListener(\"message\",this.#onMessage.bind(this)),this.#worker.addEventListener(\"messageerror\",this.#onMessageError.bind(this)),this.#worker.addEventListener(\"open\",this.#onOpen.bind(this))}ref(){this.#worker.ref()}unref(){this.#worker.unref()}get stdin(){return null}get stdout(){return null}get stderr(){return null}get performance(){return this.#performance\?\?={eventLoopUtilization(){return emitWarning(\"performance\",\"worker_threads.Worker.performance is not implemented.\"),{idle:0,active:0,utilization:0}}}}terminate(){if(this.#onExitPromise)return this.#onExitPromise;const{resolve,promise}=Promise.withResolvers();return this.once(\"exit\",(code)=>{resolve(code)}),this.#worker.terminate(),this.#onExitPromise=promise}postMessage(...args){return this.#worker.postMessage(...args)}#onClose(e){console.log(\"worker closed\",e),this.#onExitPromise=e.code,this.emit(\"exit\",e.code)}#onError(event){this.emit(\"error\",event.error)}#onMessage(event){this.emit(\"message\",event.data)}#onMessageError(event){this.emit(\"messageerror\",event.error\?\?event.data\?\?event)}#onOpen(){this.emit(\"online\")}async getHeapSnapshot(){throwNotImplemented(\"worker_threads.Worker.getHeapSnapshot\")}}return $={Worker,workerData,parentPort,resourceLimits,isMainThread,MessageChannel,BroadcastChannel,MessagePort,getEnvironmentData,setEnvironmentData,getHeapSnapshot(){return{}},markAsUntransferable,moveMessagePortToContext,receiveMessageOnPort,SHARE_ENV,threadId},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeZlibCode = "(function (){\"use strict\";const assert=@getInternalField(@internalModuleRegistry,3)||@createInternalModuleById(3),BufferModule=@requireNativeModule(\"node:buffer\"),StreamModule=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),Util=@getInternalField(@internalModuleRegistry,42)||@createInternalModuleById(42);var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_zstream=__commonJS({\"node_modules/pako/lib/zlib/zstream.js\"(exports,module2){function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0}module2.exports=ZStream}}),require_common=__commonJS({\"node_modules/pako/lib/utils/common.js\"(exports){var TYPED_OK=typeof Uint8Array!==\"undefined\"&&typeof Uint16Array!==\"undefined\"&&typeof Int32Array!==\"undefined\";function _has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}exports.assign=function(obj){var sources=Array.prototype.slice.call(arguments,1);while(sources.length){var source=sources.shift();if(!source)continue;if(typeof source!==\"object\")@throwTypeError(source+\"must be non-object\");for(var p in source)if(_has(source,p))obj[p]=source[p]}return obj},exports.shrinkBuf=function(buf,size){if(buf.length===size)return buf;if(buf.subarray)return buf.subarray(0,size);return buf.length=size,buf};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i=0)buf[len]=0}var STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH=3,MAX_MATCH=258,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],DIST_CODE_LEN=512,static_ltree=new Array((L_CODES+2)*2);zero(static_ltree);var static_dtree=new Array(D_CODES*2);zero(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero(_dist_code);var _length_code=new Array(MAX_MATCH-MIN_MATCH+1);zero(_length_code);var base_length=new Array(LENGTH_CODES);zero(base_length);var base_dist=new Array(D_CODES);zero(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}var static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}function d_code(dist){return dist<256\?_dist_code[dist]:_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=w&255,s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){if(s.bi_valid>Buf_size-length)s.bi_buf|=value<>Buf_size-s.bi_valid,s.bi_valid+=length-Buf_size;else s.bi_buf|=value<>>=1,res<<=1;while(--len>0);return res>>>1}function bi_flush(s){if(s.bi_valid===16)put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0;else if(s.bi_valid>=8)s.pending_buf[s.pending++]=s.bi_buf&255,s.bi_buf>>=8,s.bi_valid-=8}function gen_bitlen(s,desc){var{dyn_tree:tree,max_code}=desc,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length,h,n,m,bits,xbits,f,overflow=0;for(bits=0;bits<=MAX_BITS;bits++)s.bl_count[bits]=0;tree[s.heap[s.heap_max]*2+1]=0;for(h=s.heap_max+1;hmax_length)bits=max_length,overflow++;if(tree[n*2+1]=bits,n>max_code)continue;if(s.bl_count[bits]++,xbits=0,n>=base)xbits=extra[n-base];if(f=tree[n*2],s.opt_len+=f*(bits+xbits),has_stree)s.static_len+=f*(stree[n*2+1]+xbits)}if(overflow===0)return;do{bits=max_length-1;while(s.bl_count[bits]===0)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){if(m=s.heap[--h],m>max_code)continue;if(tree[m*2+1]!==bits)s.opt_len+=(bits-tree[m*2+1])*tree[m*2],tree[m*2+1]=bits;n--}}}function gen_codes(tree,max_code,bl_count){var next_code=new Array(MAX_BITS+1),code=0,bits,n;for(bits=1;bits<=MAX_BITS;bits++)next_code[bits]=code=code+bl_count[bits-1]<<1;for(n=0;n<=max_code;n++){var len=tree[n*2+1];if(len===0)continue;tree[n*2]=bi_reverse(next_code[len]++,len)}}function tr_static_init(){var n,bits,length,code,dist,bl_count=new Array(MAX_BITS+1);length=0;for(code=0;code>=7;for(;code8)put_short(s,s.bi_buf);else if(s.bi_valid>0)s.pending_buf[s.pending++]=s.bi_buf;s.bi_buf=0,s.bi_valid=0}function copy_block(s,buf,len,header){if(bi_windup(s),header)put_short(s,len),put_short(s,~len);utils.arraySet(s.pending_buf,s.window,buf,len,s.pending),s.pending+=len}function smaller(tree,n,m,depth){var _n2=n*2,_m2=m*2;return tree[_n2]>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[node*2]=tree[n*2]+tree[m*2],s.depth[node]=(s.depth[n]>=s.depth[m]\?s.depth[n]:s.depth[m])+1,tree[n*2+1]=tree[m*2+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],gen_bitlen(s,desc),gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n,prevlen=-1,curlen,nextlen=tree[1],count=0,max_count=7,min_count=4;if(nextlen===0)max_count=138,min_count=3;tree[(max_code+1)*2+1]=65535;for(n=0;n<=max_code;n++){if(curlen=nextlen,nextlen=tree[(n+1)*2+1],++count=3;max_blindex--)if(s.bl_tree[bl_order[max_blindex]*2+1]!==0)break;return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4);for(rank=0;rank>>=1)if(black_mask&1&&s.dyn_ltree[n*2]!==0)return Z_BINARY;if(s.dyn_ltree[18]!==0||s.dyn_ltree[20]!==0||s.dyn_ltree[26]!==0)return Z_TEXT;for(n=32;n0){if(s.strm.data_type===Z_UNKNOWN)s.strm.data_type=detect_data_type(s);if(build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=build_bl_tree(s),opt_lenb=s.opt_len+3+7>>>3,static_lenb=s.static_len+3+7>>>3,static_lenb<=opt_lenb)opt_lenb=static_lenb}else opt_lenb=static_lenb=stored_len+5;if(stored_len+4<=opt_lenb&&buf!==-1)_tr_stored_block(s,buf,stored_len,last);else if(s.strategy===Z_FIXED||static_lenb===opt_lenb)send_bits(s,(STATIC_TREES<<1)+(last\?1:0),3),compress_block(s,static_ltree,static_dtree);else send_bits(s,(DYN_TREES<<1)+(last\?1:0),3),send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree);if(init_block(s),last)bi_windup(s)}function _tr_tally(s,dist,lc){if(s.pending_buf[s.d_buf+s.last_lit*2]=dist>>>8&255,s.pending_buf[s.d_buf+s.last_lit*2+1]=dist&255,s.pending_buf[s.l_buf+s.last_lit]=lc&255,s.last_lit++,dist===0)s.dyn_ltree[lc*2]++;else s.matches++,dist--,s.dyn_ltree[(_length_code[lc]+LITERALS+1)*2]++,s.dyn_dtree[d_code(dist)*2]++;return s.last_lit===s.lit_bufsize-1}exports._tr_init=_tr_init,exports._tr_stored_block=_tr_stored_block,exports._tr_flush_block=_tr_flush_block,exports._tr_tally=_tr_tally,exports._tr_align=_tr_align}}),require_adler32=__commonJS({\"node_modules/pako/lib/zlib/adler32.js\"(exports,module2){function adler32(adler,buf,len,pos){var s1=adler&65535|0,s2=adler>>>16&65535|0,n=0;while(len!==0){n=len>2000\?2000:len,len-=n;do s1=s1+buf[pos++]|0,s2=s2+s1|0;while(--n);s1%=65521,s2%=65521}return s1|s2<<16|0}module2.exports=adler32}}),require_crc32=__commonJS({\"node_modules/pako/lib/zlib/crc32.js\"(exports,module2){function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=c&1\?3988292384^c>>>1:c>>>1;table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255];return crc^-1}module2.exports=crc32}}),require_messages=__commonJS({\"node_modules/pako/lib/zlib/messages.js\"(exports,module2){module2.exports={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"}}}),require_deflate=__commonJS({\"node_modules/pako/lib/zlib/deflate.js\"(exports){var utils=require_common(),trees=require_trees(),adler32=require_adler32(),crc32=require_crc32(),msg=require_messages(),Z_NO_FLUSH=0,Z_PARTIAL_FLUSH=1,Z_FULL_FLUSH=3,Z_FINISH=4,Z_BLOCK=5,Z_OK=0,Z_STREAM_END=1,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_BUF_ERROR=-5,Z_DEFAULT_COMPRESSION=-1,Z_FILTERED=1,Z_HUFFMAN_ONLY=2,Z_RLE=3,Z_FIXED=4,Z_DEFAULT_STRATEGY=0,Z_UNKNOWN=2,Z_DEFLATED=8,MAX_MEM_LEVEL=9,MAX_WBITS=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3;function err(strm,errorCode){return strm.msg=msg[errorCode],errorCode}function rank(f){return(f<<1)-(f>4\?9:0)}function zero(buf){var len=buf.length;while(--len>=0)buf[len]=0}function flush_pending(strm){var s=strm.state,len=s.pending;if(len>strm.avail_out)len=strm.avail_out;if(len===0)return;if(utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,s.pending===0)s.pending_out=0}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0\?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=b&255}function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size)len=size;if(len===0)return 0;if(strm.avail_in-=len,utils.arraySet(buf,strm.input,strm.next_in,len,start),strm.state.wrap===1)strm.adler=adler32(strm.adler,buf,len,start);else if(strm.state.wrap===2)strm.adler=crc32(strm.adler,buf,len,start);return strm.next_in+=len,strm.total_in+=len,len}function longest_match(s,cur_match){var{max_chain_length:chain_length,strstart:scan}=s,match,len,best_len=s.prev_length,nice_match=s.nice_match,limit=s.strstart>s.w_size-MIN_LOOKAHEAD\?s.strstart-(s.w_size-MIN_LOOKAHEAD):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+MAX_MATCH,scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match)chain_length>>=2;if(nice_match>s.lookahead)nice_match=s.lookahead;do{if(match=cur_match,_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1])continue;scan+=2,match++;do;while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scanbest_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead)return best_len;return s.lookahead}function fill_window(s){var _w_size=s.w_size,p,n,m,more,str;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){utils.arraySet(s.window,s.window,_w_size,_w_size,0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,n=s.hash_size,p=n;do m=s.head[--p],s.head[p]=m>=_w_size\?m-_w_size:0;while(--n);n=_w_size,p=n;do m=s.prev[--p],s.prev[p]=m>=_w_size\?m-_w_size:0;while(--n);more+=_w_size}if(s.strm.avail_in===0)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=(s.ins_h<s.pending_buf_size-5)max_block_size=s.pending_buf_size-5;for(;;){if(s.lookahead<=1){if(fill_window(s),s.lookahead===0&&flush===Z_NO_FLUSH)return BS_NEED_MORE;if(s.lookahead===0)break}s.strstart+=s.lookahead,s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){if(s.lookahead=s.strstart-max_start,s.strstart=max_start,flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.strstart>s.block_start){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_NEED_MORE}function deflate_fast(s,flush){var hash_head,bflush;for(;;){if(s.lookahead=MIN_MATCH)s.ins_h=(s.ins_h<=MIN_MATCH)if(bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=MIN_MATCH)s.ins_h=(s.ins_h<4096))s.match_length=MIN_MATCH-1}if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH,bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH),s.lookahead-=s.prev_length-1,s.prev_length-=2;do if(++s.strstart<=max_insert)s.ins_h=(s.ins_h<=MIN_MATCH&&s.strstart>0){if(scan=s.strstart-1,prev=_win[scan],prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do;while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scans.lookahead)s.match_length=s.lookahead}}if(s.match_length>=MIN_MATCH)bflush=trees._tr_tally(s,1,s.match_length-MIN_MATCH),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0;else bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.last_lit){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_BLOCK_DONE}function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){if(fill_window(s),s.lookahead===0){if(flush===Z_NO_FLUSH)return BS_NEED_MORE;break}}if(s.match_length=0,bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.last_lit){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_BLOCK_DONE}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}var configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function lm_init(s){s.window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=MIN_MATCH-1,s.match_available=0,s.ins_h=0}function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new utils.Buf16(HEAP_SIZE*2),this.dyn_dtree=new utils.Buf16((2*D_CODES+1)*2),this.bl_tree=new utils.Buf16((2*BL_CODES+1)*2),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new utils.Buf16(MAX_BITS+1),this.heap=new utils.Buf16(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new utils.Buf16(2*L_CODES+1),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(strm){var s;if(!strm||!strm.state)return err(strm,Z_STREAM_ERROR);if(strm.total_in=strm.total_out=0,strm.data_type=Z_UNKNOWN,s=strm.state,s.pending=0,s.pending_out=0,s.wrap<0)s.wrap=-s.wrap;return s.status=s.wrap\?INIT_STATE:BUSY_STATE,strm.adler=s.wrap===2\?0:1,s.last_flush=Z_NO_FLUSH,trees._tr_init(s),Z_OK}function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK)lm_init(strm.state);return ret}function deflateSetHeader(strm,head){if(!strm||!strm.state)return Z_STREAM_ERROR;if(strm.state.wrap!==2)return Z_STREAM_ERROR;return strm.state.gzhead=head,Z_OK}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm)return Z_STREAM_ERROR;var wrap=1;if(level===Z_DEFAULT_COMPRESSION)level=6;if(windowBits<0)wrap=0,windowBits=-windowBits;else if(windowBits>15)wrap=2,windowBits-=16;if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED)return err(strm,Z_STREAM_ERROR);if(windowBits===8)windowBits=9;var s=new DeflateState;return strm.state=s,s.strm=strm,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<Z_BLOCK||flush<0)return strm\?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR;if(s=strm.state,!strm.output||!strm.input&&strm.avail_in!==0||s.status===FINISH_STATE&&flush!==Z_FINISH)return err(strm,strm.avail_out===0\?Z_BUF_ERROR:Z_STREAM_ERROR);if(s.strm=strm,old_flush=s.last_flush,s.last_flush=flush,s.status===INIT_STATE)if(s.wrap===2)if(strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),!s.gzhead)put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,s.level===9\?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2\?4:0),put_byte(s,OS_CODE),s.status=BUSY_STATE;else{if(put_byte(s,(s.gzhead.text\?1:0)+(s.gzhead.hcrc\?2:0)+(!s.gzhead.extra\?0:4)+(!s.gzhead.name\?0:8)+(!s.gzhead.comment\?0:16)),put_byte(s,s.gzhead.time&255),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,s.level===9\?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2\?4:0),put_byte(s,s.gzhead.os&255),s.gzhead.extra&&s.gzhead.extra.length)put_byte(s,s.gzhead.extra.length&255),put_byte(s,s.gzhead.extra.length>>8&255);if(s.gzhead.hcrc)strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0);s.gzindex=0,s.status=EXTRA_STATE}else{var header=Z_DEFLATED+(s.w_bits-8<<4)<<8,level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2)level_flags=0;else if(s.level<6)level_flags=1;else if(s.level===6)level_flags=2;else level_flags=3;if(header|=level_flags<<6,s.strstart!==0)header|=PRESET_DICT;if(header+=31-header%31,s.status=BUSY_STATE,putShortMSB(s,header),s.strstart!==0)putShortMSB(s,strm.adler>>>16),putShortMSB(s,strm.adler&65535);strm.adler=1}if(s.status===EXTRA_STATE)if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&65535)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size)break}put_byte(s,s.gzhead.extra[s.gzindex]&255),s.gzindex++}if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(s.gzindex===s.gzhead.extra.length)s.gzindex=0,s.status=NAME_STATE}else s.status=NAME_STATE;if(s.status===NAME_STATE)if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size){val=1;break}}if(s.gzindexbeg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(val===0)s.gzindex=0,s.status=COMMENT_STATE}else s.status=COMMENT_STATE;if(s.status===COMMENT_STATE)if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size){val=1;break}}if(s.gzindexbeg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(val===0)s.status=HCRC_STATE}else s.status=HCRC_STATE;if(s.status===HCRC_STATE)if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size)flush_pending(strm);if(s.pending+2<=s.pending_buf_size)put_byte(s,strm.adler&255),put_byte(s,strm.adler>>8&255),strm.adler=0,s.status=BUSY_STATE}else s.status=BUSY_STATE;if(s.pending!==0){if(flush_pending(strm),strm.avail_out===0)return s.last_flush=-1,Z_OK}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH)return err(strm,Z_BUF_ERROR);if(s.status===FINISH_STATE&&strm.avail_in!==0)return err(strm,Z_BUF_ERROR);if(strm.avail_in!==0||s.lookahead!==0||flush!==Z_NO_FLUSH&&s.status!==FINISH_STATE){var bstate=s.strategy===Z_HUFFMAN_ONLY\?deflate_huff(s,flush):s.strategy===Z_RLE\?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE)s.status=FINISH_STATE;if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0)s.last_flush=-1;return Z_OK}if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH)trees._tr_align(s);else if(flush!==Z_BLOCK){if(trees._tr_stored_block(s,0,0,!1),flush===Z_FULL_FLUSH){if(zero(s.head),s.lookahead===0)s.strstart=0,s.block_start=0,s.insert=0}}if(flush_pending(strm),strm.avail_out===0)return s.last_flush=-1,Z_OK}}if(flush!==Z_FINISH)return Z_OK;if(s.wrap<=0)return Z_STREAM_END;if(s.wrap===2)put_byte(s,strm.adler&255),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,strm.total_in&255),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255);else putShortMSB(s,strm.adler>>>16),putShortMSB(s,strm.adler&65535);if(flush_pending(strm),s.wrap>0)s.wrap=-s.wrap;return s.pending!==0\?Z_OK:Z_STREAM_END}function deflateEnd(strm){var status;if(!strm||!strm.state)return Z_STREAM_ERROR;if(status=strm.state.status,status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE)return err(strm,Z_STREAM_ERROR);return strm.state=null,status===BUSY_STATE\?err(strm,Z_DATA_ERROR):Z_OK}function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length,s,str,n,wrap,avail,next,input,tmpDict;if(!strm||!strm.state)return Z_STREAM_ERROR;if(s=strm.state,wrap=s.wrap,wrap===2||wrap===1&&s.status!==INIT_STATE||s.lookahead)return Z_STREAM_ERROR;if(wrap===1)strm.adler=adler32(strm.adler,dictionary,dictLength,0);if(s.wrap=0,dictLength>=s.w_size){if(wrap===0)zero(s.head),s.strstart=0,s.block_start=0,s.insert=0;tmpDict=new utils.Buf8(s.w_size),utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0),dictionary=tmpDict,dictLength=s.w_size}avail=strm.avail_in,next=strm.next_in,input=strm.input,strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);while(s.lookahead>=MIN_MATCH){str=s.strstart,n=s.lookahead-(MIN_MATCH-1);do s.ins_h=(s.ins_h<>>24,hold>>>=op,bits-=op,op=here>>>16&255,op===0)output[_out++]=here&65535;else if(op&16){if(len=here&65535,op&=15,op){if(bits>>=op,bits-=op}if(bits<15)hold+=input[_in++]<>>24,hold>>>=op,bits-=op,op=here>>>16&255,op&16){if(dist=here&65535,op&=15,bitsdmax){strm.msg=\"invalid distance too far back\",state.mode=BAD;break top}if(hold>>>=op,bits-=op,op=_out-beg,dist>op){if(op=dist-op,op>whave){if(state.sane){strm.msg=\"invalid distance too far back\",state.mode=BAD;break top}}if(from=0,from_source=s_window,wnext===0){if(from+=wsize-op,op2)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;if(len){if(output[_out++]=from_source[from++],len>1)output[_out++]=from_source[from++]}}else{from=_out-dist;do output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3;while(len>2);if(len){if(output[_out++]=output[from++],len>1)output[_out++]=output[from++]}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3,_in-=len,bits-=len<<3,hold&=(1<=1;max--)if(count[max]!==0)break;if(root>max)root=max;if(max===0)return table[table_index++]=1<<24|64<<16|0,table[table_index++]=1<<24|64<<16|0,opts.bits=1,0;for(min=1;min0&&(type===CODES||max!==1))return-1;offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS)return 1;for(;;){if(here_bits=len-drop,work[sym]end)here_op=extra[extra_index+work[sym]],here_val=base[base_index+work[sym]];else here_op=96,here_val=0;incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0;while(fill!==0);incr=1<>=1;if(incr!==0)huff&=incr-1,huff+=incr;else huff=0;if(sym++,--count[len]===0){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0)drop=root;next+=min,curr=len-drop,left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS)return 1;low=huff&mask,table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0)table[next+huff]=len-drop<<24|64<<16|0;return opts.bits=root,0}}}),require_inflate=__commonJS({\"node_modules/pako/lib/zlib/inflate.js\"(exports){var utils=require_common(),adler32=require_adler32(),crc32=require_crc32(),inflate_fast=require_inffast(),inflate_table=require_inftrees(),CODES=0,LENS=1,DISTS=2,Z_FINISH=4,Z_BLOCK=5,Z_TREES=6,Z_OK=0,Z_STREAM_END=1,Z_NEED_DICT=2,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_MEM_ERROR=-4,Z_BUF_ERROR=-5,Z_DEFLATED=8,HEAD=1,FLAGS=2,TIME=3,OS=4,EXLEN=5,EXTRA=6,NAME=7,COMMENT=8,HCRC=9,DICTID=10,DICT=11,TYPE=12,TYPEDO=13,STORED=14,COPY_=15,COPY=16,TABLE=17,LENLENS=18,CODELENS=19,LEN_=20,LEN=21,LENEXT=22,DIST=23,DISTEXT=24,MATCH=25,LIT=26,CHECK=27,LENGTH=28,DONE=29,BAD=30,MEM=31,SYNC=32,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new utils.Buf16(320),this.work=new utils.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state)return Z_STREAM_ERROR;if(state=strm.state,strm.total_in=strm.total_out=state.total=0,strm.msg=\"\",state.wrap)strm.adler=state.wrap&1;return state.mode=HEAD,state.last=0,state.havedict=0,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS),state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS),state.sane=1,state.back=-1,Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state)return Z_STREAM_ERROR;return state=strm.state,state.wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap,state;if(!strm||!strm.state)return Z_STREAM_ERROR;if(state=strm.state,windowBits<0)wrap=0,windowBits=-windowBits;else if(wrap=(windowBits>>4)+1,windowBits<48)windowBits&=15;if(windowBits&&(windowBits<8||windowBits>15))return Z_STREAM_ERROR;if(state.window!==null&&state.wbits!==windowBits)state.window=null;return state.wrap=wrap,state.wbits=windowBits,inflateReset(strm)}function inflateInit2(strm,windowBits){var ret,state;if(!strm)return Z_STREAM_ERROR;if(state=new InflateState,strm.state=state,state.window=null,ret=inflateReset2(strm,windowBits),ret!==Z_OK)strm.state=null;return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=!0,lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512),distfix=new utils.Buf32(32),sym=0;while(sym<144)state.lens[sym++]=8;while(sym<256)state.lens[sym++]=9;while(sym<280)state.lens[sym++]=7;while(sym<288)state.lens[sym++]=8;inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;while(sym<32)state.lens[sym++]=5;inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5}function updatewindow(strm,src,end,copy){var dist,state=strm.state;if(state.window===null)state.wsize=1<=state.wsize)utils.arraySet(state.window,src,end-state.wsize,state.wsize,0),state.wnext=0,state.whave=state.wsize;else{if(dist=state.wsize-state.wnext,dist>copy)dist=copy;if(utils.arraySet(state.window,src,end-copy,dist,state.wnext),copy-=dist,copy)utils.arraySet(state.window,src,end-copy,copy,0),state.wnext=copy,state.whave=state.wsize;else{if(state.wnext+=dist,state.wnext===state.wsize)state.wnext=0;if(state.whave>>8&255,state.check=crc32(state.check,hbuf,2,0),hold=0,bits=0,state.mode=FLAGS;break}if(state.flags=0,state.head)state.head.done=!1;if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg=\"incorrect header check\",state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg=\"unknown compression method\",state.mode=BAD;break}if(hold>>>=4,bits-=4,len=(hold&15)+8,state.wbits===0)state.wbits=len;else if(len>state.wbits){strm.msg=\"invalid window size\",state.mode=BAD;break}state.dmax=1<>8&1;if(state.flags&512)hbuf[0]=hold&255,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0,state.mode=TIME;case TIME:while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32(state.check,hbuf,4,0);hold=0,bits=0,state.mode=OS;case OS:while(bits<16){if(have===0)break inf_leave;have--,hold+=input[next++]<>8;if(state.flags&512)hbuf[0]=hold&255,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0,state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0)break inf_leave;have--,hold+=input[next++]<>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0}else if(state.head)state.head.extra=null;state.mode=EXTRA;case EXTRA:if(state.flags&1024){if(copy=state.length,copy>have)copy=have;if(copy){if(state.head){if(len=state.head.extra_len-state.length,!state.head.extra)state.head.extra=new Array(state.head.extra_len);utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512)state.check=crc32(state.check,input,copy,next);have-=copy,next+=copy,state.length-=copy}if(state.length)break inf_leave}state.length=0,state.mode=NAME;case NAME:if(state.flags&2048){if(have===0)break inf_leave;copy=0;do if(len=input[next+copy++],state.head&&len&&state.length<65536)state.head.name+=String.fromCharCode(len);while(len&©>9&1,state.head.done=!0;strm.adler=state.check=0,state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=bits&7,bits-=bits&7,state.mode=CHECK;break}while(bits<3){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=1,bits-=1,hold&3){case 0:state.mode=STORED;break;case 1:if(fixedtables(state),state.mode=LEN_,flush===Z_TREES){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg=\"invalid block type\",state.mode=BAD}hold>>>=2,bits-=2;break;case STORED:hold>>>=bits&7,bits-=bits&7;while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>16^65535)){strm.msg=\"invalid stored block lengths\",state.mode=BAD;break}if(state.length=hold&65535,hold=0,bits=0,state.mode=COPY_,flush===Z_TREES)break inf_leave;case COPY_:state.mode=COPY;case COPY:if(copy=state.length,copy){if(copy>have)copy=have;if(copy>left)copy=left;if(copy===0)break inf_leave;utils.arraySet(output,input,next,copy,put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=5,bits-=5,state.ndist=(hold&31)+1,hold>>>=5,bits-=5,state.ncode=(hold&15)+4,hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg=\"too many length or distance symbols\",state.mode=BAD;break}state.have=0,state.mode=LENLENS;case LENLENS:while(state.have>>=3,bits-=3}while(state.have<19)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg=\"invalid code lengths set\",state.mode=BAD;break}state.have=0,state.mode=CODELENS;case CODELENS:while(state.have>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits,bits-=here_bits,state.have===0){strm.msg=\"invalid bit length repeat\",state.mode=BAD;break}len=state.lens[state.have-1],copy=3+(hold&3),hold>>>=2,bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits,bits-=here_bits,len=0,copy=3+(hold&7),hold>>>=3,bits-=3}else{n=here_bits+7;while(bits>>=here_bits,bits-=here_bits,len=0,copy=11+(hold&127),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg=\"invalid bit length repeat\",state.mode=BAD;break}while(copy--)state.lens[state.have++]=len}}if(state.mode===BAD)break;if(state.lens[256]===0){strm.msg=\"invalid code -- missing end-of-block\",state.mode=BAD;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg=\"invalid literal/lengths set\",state.mode=BAD;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg=\"invalid distances set\",state.mode=BAD;break}if(state.mode=LEN_,flush===Z_TREES)break inf_leave;case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){if(strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inflate_fast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,state.mode===TYPE)state.back=-1;break}state.back=0;for(;;){if(here=state.lencode[hold&(1<>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=here&65535,last_bits+here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1,state.mode=TYPE;break}if(here_op&64){strm.msg=\"invalid literal/length code\",state.mode=BAD;break}state.extra=here_op&15,state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=DIST;case DIST:for(;;){if(here=state.distcode[hold&(1<>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=here&65535,last_bits+here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,here_op&64){strm.msg=\"invalid distance code\",state.mode=BAD;break}state.offset=here_val,state.extra=here_op&15,state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg=\"invalid distance too far back\",state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0)break inf_leave;if(copy=_out-left,state.offset>copy){if(copy=state.offset-copy,copy>state.whave){if(state.sane){strm.msg=\"invalid distance too far back\",state.mode=BAD;break}}if(copy>state.wnext)copy-=state.wnext,from=state.wsize-copy;else from=state.wnext-copy;if(copy>state.length)copy=state.length;from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;if(copy>left)copy=left;left-=copy,state.length-=copy;do output[put++]=from_source[from++];while(--copy);if(state.length===0)state.mode=LEN;break;case LIT:if(left===0)break inf_leave;output[put++]=state.length,left--,state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0)break inf_leave;have--,hold|=input[next++]<exports.UNZIP)@throwTypeError(\"Bad argument\");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=mode,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}Zlib.prototype={},Zlib.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}if(this.pending_close=!1,assert(this.init_done,\"close before init\"),assert(this.mode<=exports.UNZIP),this.mode===exports.DEFLATE||this.mode===exports.GZIP||this.mode===exports.DEFLATERAW)zlib_deflate.deflateEnd(this.strm);else if(this.mode===exports.INFLATE||this.mode===exports.GUNZIP||this.mode===exports.INFLATERAW||this.mode===exports.UNZIP)zlib_inflate.inflateEnd(this.strm);this.mode=exports.NONE,this.dictionary=null},Zlib.prototype.write=function(flush,input,in_off,in_len,out,out_off,out_len){return this._write(!0,flush,input,in_off,in_len,out,out_off,out_len)},Zlib.prototype.writeSync=function(flush,input,in_off,in_len,out,out_off,out_len){return this._write(!1,flush,input,in_off,in_len,out,out_off,out_len)},Zlib.prototype._write=function(async,flush,input,in_off,in_len,out,out_off,out_len){if(assert.equal(arguments.length,8),assert(this.init_done,\"write before init\"),assert(this.mode!==exports.NONE,\"already finalized\"),assert.equal(!1,this.write_in_progress,\"write already in progress\"),assert.equal(!1,this.pending_close,\"close is pending\"),this.write_in_progress=!0,assert.equal(!1,flush===void 0,\"must provide flush value\"),this.write_in_progress=!0,flush!==exports.Z_NO_FLUSH&&flush!==exports.Z_PARTIAL_FLUSH&&flush!==exports.Z_SYNC_FLUSH&&flush!==exports.Z_FULL_FLUSH&&flush!==exports.Z_FINISH&&flush!==exports.Z_BLOCK)throw new Error(\"Invalid flush value\");if(input==null)input=Buffer.alloc(0),in_len=0,in_off=0;if(this.strm.avail_in=in_len,this.strm.input=input,this.strm.next_in=in_off,this.strm.avail_out=out_len,this.strm.output=out,this.strm.next_out=out_off,this.flush=flush,!async){if(this._process(),this._checkError())return this._afterSync();return}var self=this;return process.nextTick(function(){self._process(),self._after()}),this},Zlib.prototype._afterSync=function(){var avail_out=this.strm.avail_out,avail_in=this.strm.avail_in;return this.write_in_progress=!1,[avail_in,avail_out]},Zlib.prototype._process=function(){var next_expected_header_byte=null;switch(this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:this.err=zlib_deflate.deflate(this.strm,this.flush);break;case exports.UNZIP:if(this.strm.avail_in>0)next_expected_header_byte=this.strm.next_in;switch(this.gzip_id_bytes_read){case 0:if(next_expected_header_byte===null)break;if(this.strm.input[next_expected_header_byte]===GZIP_HEADER_ID1){if(this.gzip_id_bytes_read=1,next_expected_header_byte++,this.strm.avail_in===1)break}else{this.mode=exports.INFLATE;break}case 1:if(next_expected_header_byte===null)break;if(this.strm.input[next_expected_header_byte]===GZIP_HEADER_ID2)this.gzip_id_bytes_read=2,this.mode=exports.GUNZIP;else this.mode=exports.INFLATE;break;default:throw new Error(\"invalid number of gzip magic number bytes read\")}case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:if(this.err=zlib_inflate.inflate(this.strm,this.flush),this.err===exports.Z_NEED_DICT&&this.dictionary){if(this.err=zlib_inflate.inflateSetDictionary(this.strm,this.dictionary),this.err===exports.Z_OK)this.err=zlib_inflate.inflate(this.strm,this.flush);else if(this.err===exports.Z_DATA_ERROR)this.err=exports.Z_NEED_DICT}while(this.strm.avail_in>0&&this.mode===exports.GUNZIP&&this.err===exports.Z_STREAM_END&&this.strm.next_in[0]!==0)this.reset(),this.err=zlib_inflate.inflate(this.strm,this.flush);break;default:throw new Error(\"Unknown mode \"+this.mode)}},Zlib.prototype._checkError=function(){switch(this.err){case exports.Z_OK:case exports.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===exports.Z_FINISH)return this._error(\"unexpected end of file\"),!1;break;case exports.Z_STREAM_END:break;case exports.Z_NEED_DICT:if(this.dictionary==null)this._error(\"Missing dictionary\");else this._error(\"Bad dictionary\");return!1;default:return this._error(\"Zlib error\"),!1}return!0},Zlib.prototype._after=function(){if(!this._checkError())return;var avail_out=this.strm.avail_out,avail_in=this.strm.avail_in;if(this.write_in_progress=!1,this.callback(avail_in,avail_out),this.pending_close)this.close()},Zlib.prototype._error=function(message){if(this.strm.msg)message=this.strm.msg;if(this.onerror(message,this.err),this.write_in_progress=!1,this.pending_close)this.close()},Zlib.prototype.init=function(windowBits,level,memLevel,strategy,dictionary){assert(arguments.length===4||arguments.length===5,\"init(windowBits, level, memLevel, strategy, [dictionary])\"),assert(windowBits>=8&&windowBits<=15,\"invalid windowBits\"),assert(level>=-1&&level<=9,\"invalid compression level\"),assert(memLevel>=1&&memLevel<=9,\"invalid memlevel\"),assert(strategy===exports.Z_FILTERED||strategy===exports.Z_HUFFMAN_ONLY||strategy===exports.Z_RLE||strategy===exports.Z_FIXED||strategy===exports.Z_DEFAULT_STRATEGY,\"invalid strategy\"),this._init(level,windowBits,memLevel,strategy,dictionary),this._setDictionary()},Zlib.prototype.params=function(){throw new Error(\"deflateParams Not supported\")},Zlib.prototype.reset=function(){this._reset(),this._setDictionary()},Zlib.prototype._init=function(level,windowBits,memLevel,strategy,dictionary){if(this.level=level,this.windowBits=windowBits,this.memLevel=memLevel,this.strategy=strategy,this.flush=exports.Z_NO_FLUSH,this.err=exports.Z_OK,this.mode===exports.GZIP||this.mode===exports.GUNZIP)this.windowBits+=16;if(this.mode===exports.UNZIP)this.windowBits+=32;if(this.mode===exports.DEFLATERAW||this.mode===exports.INFLATERAW)this.windowBits=-1*this.windowBits;switch(this.strm=new Zstream,this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:this.err=zlib_deflate.deflateInit2(this.strm,this.level,exports.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:case exports.UNZIP:this.err=zlib_inflate.inflateInit2(this.strm,this.windowBits);break;default:throw new Error(\"Unknown mode \"+this.mode)}if(this.err!==exports.Z_OK)this._error(\"Init error\");this.dictionary=dictionary,this.write_in_progress=!1,this.init_done=!0},Zlib.prototype._setDictionary=function(){if(this.dictionary==null)return;switch(this.err=exports.Z_OK,this.mode){case exports.DEFLATE:case exports.DEFLATERAW:this.err=zlib_deflate.deflateSetDictionary(this.strm,this.dictionary);break;default:break}if(this.err!==exports.Z_OK)this._error(\"Failed to set dictionary\")},Zlib.prototype._reset=function(){switch(this.err=exports.Z_OK,this.mode){case exports.DEFLATE:case exports.DEFLATERAW:case exports.GZIP:this.err=zlib_deflate.deflateReset(this.strm);break;case exports.INFLATE:case exports.INFLATERAW:case exports.GUNZIP:this.err=zlib_inflate.inflateReset(this.strm);break;default:break}if(this.err!==exports.Z_OK)this._error(\"Failed to reset stream\")},exports.Zlib=Zlib}}),require_lib=__commonJS({\"node_modules/browserify-zlib/lib/index.js\"(exports){var Buffer2=BufferModule.Buffer,Transform=StreamModule.Transform,binding=require_binding(),util=Util,kMaxLength=BufferModule.kMaxLength,kRangeErrorMessage=\"Cannot create final Buffer. It would be larger than 0x\"+kMaxLength.toString(16)+\" bytes\";binding.Z_MIN_WINDOWBITS=8,binding.Z_MAX_WINDOWBITS=15,binding.Z_DEFAULT_WINDOWBITS=15,binding.Z_MIN_CHUNK=64,binding.Z_MAX_CHUNK=Infinity,binding.Z_DEFAULT_CHUNK=16384,binding.Z_MIN_MEMLEVEL=1,binding.Z_MAX_MEMLEVEL=9,binding.Z_DEFAULT_MEMLEVEL=8,binding.Z_MIN_LEVEL=-1,binding.Z_MAX_LEVEL=9,binding.Z_DEFAULT_LEVEL=binding.Z_DEFAULT_COMPRESSION;var bkeys=Object.keys(binding);for(bk=0;bk=kMaxLength)err=new RangeError(kRangeErrorMessage);else buf=Buffer2.concat(buffers,nread);buffers=[],engine.close(),callback(err,buf)}}function zlibBufferSync(engine,buffer){if(typeof buffer===\"string\")buffer=Buffer2.from(buffer);if(!Buffer2.isBuffer(buffer))@throwTypeError(\"Not a string or buffer\");var flushFlag=engine._finishFlushFlag;return engine._processChunk(buffer,flushFlag)}function Deflate(opts){if(!(this instanceof Deflate))return new Deflate(opts);Zlib.call(this,opts,binding.DEFLATE)}function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);Zlib.call(this,opts,binding.INFLATE)}function Gzip(opts){if(!(this instanceof Gzip))return new Gzip(opts);Zlib.call(this,opts,binding.GZIP)}function Gunzip(opts){if(!(this instanceof Gunzip))return new Gunzip(opts);Zlib.call(this,opts,binding.GUNZIP)}function DeflateRaw(opts){if(!(this instanceof DeflateRaw))return new DeflateRaw(opts);Zlib.call(this,opts,binding.DEFLATERAW)}function InflateRaw(opts){if(!(this instanceof InflateRaw))return new InflateRaw(opts);Zlib.call(this,opts,binding.INFLATERAW)}function Unzip(opts){if(!(this instanceof Unzip))return new Unzip(opts);Zlib.call(this,opts,binding.UNZIP)}function isValidFlushFlag(flag){return flag===binding.Z_NO_FLUSH||flag===binding.Z_PARTIAL_FLUSH||flag===binding.Z_SYNC_FLUSH||flag===binding.Z_FULL_FLUSH||flag===binding.Z_FINISH||flag===binding.Z_BLOCK}function Zlib(opts,mode){var _this=this;if(this._opts=opts=opts||{},this._chunkSize=opts.chunkSize||exports.Z_DEFAULT_CHUNK,Transform.call(this,opts),opts.flush&&!isValidFlushFlag(opts.flush))throw new Error(\"Invalid flush flag: \"+opts.flush);if(opts.finishFlush&&!isValidFlushFlag(opts.finishFlush))throw new Error(\"Invalid flush flag: \"+opts.finishFlush);if(this._flushFlag=opts.flush||binding.Z_NO_FLUSH,this._finishFlushFlag=typeof opts.finishFlush!==\"undefined\"\?opts.finishFlush:binding.Z_FINISH,opts.chunkSize){if(opts.chunkSizeexports.Z_MAX_CHUNK)throw new Error(\"Invalid chunk size: \"+opts.chunkSize)}if(opts.windowBits){if(opts.windowBitsexports.Z_MAX_WINDOWBITS)throw new Error(\"Invalid windowBits: \"+opts.windowBits)}if(opts.level){if(opts.levelexports.Z_MAX_LEVEL)throw new Error(\"Invalid compression level: \"+opts.level)}if(opts.memLevel){if(opts.memLevelexports.Z_MAX_MEMLEVEL)throw new Error(\"Invalid memLevel: \"+opts.memLevel)}if(opts.strategy){if(opts.strategy!=exports.Z_FILTERED&&opts.strategy!=exports.Z_HUFFMAN_ONLY&&opts.strategy!=exports.Z_RLE&&opts.strategy!=exports.Z_FIXED&&opts.strategy!=exports.Z_DEFAULT_STRATEGY)throw new Error(\"Invalid strategy: \"+opts.strategy)}if(opts.dictionary){if(!Buffer2.isBuffer(opts.dictionary))throw new Error(\"Invalid dictionary: it should be a Buffer instance\")}this._handle=new binding.Zlib(mode);var self=this;this._hadError=!1,this._handle.onerror=function(message,errno){_close(self),self._hadError=!0;var error=new Error(message);error.errno=errno,error.code=exports.codes[errno],self.emit(\"error\",error)};var level=exports.Z_DEFAULT_COMPRESSION;if(typeof opts.level===\"number\")level=opts.level;var strategy=exports.Z_DEFAULT_STRATEGY;if(typeof opts.strategy===\"number\")strategy=opts.strategy;this._handle.init(opts.windowBits||exports.Z_DEFAULT_WINDOWBITS,level,opts.memLevel||exports.Z_DEFAULT_MEMLEVEL,strategy,opts.dictionary),this._buffer=Buffer2.allocUnsafe(this._chunkSize),this._offset=0,this._level=level,this._strategy=strategy,this.once(\"end\",this.close),Object.defineProperty(this,\"_closed\",{get:function(){return!_this._handle},configurable:!0,enumerable:!0})}util.inherits(Zlib,Transform),Zlib.prototype.params=function(level,strategy,callback){if(levelexports.Z_MAX_LEVEL)@throwRangeError(\"Invalid compression level: \"+level);if(strategy!=exports.Z_FILTERED&&strategy!=exports.Z_HUFFMAN_ONLY&&strategy!=exports.Z_RLE&&strategy!=exports.Z_FIXED&&strategy!=exports.Z_DEFAULT_STRATEGY)@throwTypeError(\"Invalid strategy: \"+strategy);if(this._level!==level||this._strategy!==strategy){var self=this;this.flush(binding.Z_SYNC_FLUSH,function(){if(assert(self._handle,\"zlib binding closed\"),self._handle.params(level,strategy),!self._hadError){if(self._level=level,self._strategy=strategy,callback)callback()}})}else process.nextTick(callback)},Zlib.prototype.reset=function(){return assert(this._handle,\"zlib binding closed\"),this._handle.reset()},Zlib.prototype._flush=function(callback){this._transform(Buffer2.alloc(0),\"\",callback)},Zlib.prototype.flush=function(kind,callback){var _this2=this,ws=this._writableState;if(typeof kind===\"function\"||kind===void 0&&!callback)callback=kind,kind=binding.Z_FULL_FLUSH;if(ws.ended){if(callback)process.nextTick(callback)}else if(ws.ending){if(callback)this.once(\"end\",callback)}else if(ws.needDrain){if(callback)this.once(\"drain\",function(){return _this2.flush(kind,callback)})}else this._flushFlag=kind,this.write(Buffer2.alloc(0),\"\",callback)},Zlib.prototype.close=function(callback){_close(this,callback),process.nextTick(emitCloseNT,this)};function _close(engine,callback){if(callback)process.nextTick(callback);if(!engine._handle)return;engine._handle.close(),engine._handle=null}function emitCloseNT(self){self.emit(\"close\")}Zlib.prototype._transform=function(chunk,encoding,cb){var flushFlag,ws=this._writableState,ending=ws.ending||ws.ended,last=ending&&(!chunk||ws.length===chunk.length);if(chunk!==null&&!Buffer2.isBuffer(chunk))return cb(new Error(\"invalid input\"));if(!this._handle)return cb(new Error(\"zlib binding closed\"));if(last)flushFlag=this._finishFlushFlag;else if(flushFlag=this._flushFlag,chunk.length>=ws.length)this._flushFlag=this._opts.flush||binding.Z_NO_FLUSH;this._processChunk(chunk,flushFlag,cb)},Zlib.prototype._processChunk=function(chunk,flushFlag,cb){var availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,inOff=0,self=this,async=typeof cb===\"function\";if(!async){var buffers=[],nread=0,error;this.on(\"error\",function(er){error=er}),assert(this._handle,\"zlib binding closed\");do var res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);while(!this._hadError&&callback(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)_close(this),@throwRangeError(kRangeErrorMessage);var buf=Buffer2.concat(buffers,nread);return _close(this),buf}assert(this._handle,\"zlib binding closed\");var req=this._handle.write(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);req.buffer=chunk,req.callback=callback;function callback(availInAfter,availOutAfter){if(this)this.buffer=null,this.callback=null;if(self._hadError)return;var have=availOutBefore-availOutAfter;if(assert(have>=0,\"have should not go down\"),have>0){var out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,async)self.push(out);else buffers.push(out),nread+=out.length}if(availOutAfter===0||self._offset>=self._chunkSize)availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer2.allocUnsafe(self._chunkSize);if(availOutAfter===0){if(inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!async)return!0;var newReq=self._handle.write(flushFlag,chunk,inOff,availInBefore,self._buffer,self._offset,self._chunkSize);newReq.callback=callback,newReq.buffer=chunk;return}if(!async)return!1;cb()}},util.inherits(Deflate,Zlib),util.inherits(Inflate,Zlib),util.inherits(Gzip,Zlib),util.inherits(Gunzip,Zlib),util.inherits(DeflateRaw,Zlib),util.inherits(InflateRaw,Zlib),util.inherits(Unzip,Zlib)}});return require_lib()})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDepdCode = "(function (){\"use strict\";var $=function depd(namespace){if(!namespace)@throwTypeError(\"argument namespace is required\");function deprecate(message){}return deprecate._file=void 0,deprecate._ignored=!0,deprecate._namespace=namespace,deprecate._traced=!1,deprecate._warned=Object.create(null),deprecate.function=wrapfunction,deprecate.property=wrapproperty,deprecate};function wrapfunction(fn,message){if(typeof fn!==\"function\")@throwTypeError(\"argument fn must be a function\");return fn}function wrapproperty(obj,prop,message){if(!obj||typeof obj!==\"object\"&&typeof obj!==\"function\")@throwTypeError(\"argument obj must be object\");var descriptor=Object.getOwnPropertyDescriptor(obj,prop);if(!descriptor)@throwTypeError(\"must call property on owner object\");if(!descriptor.configurable)@throwTypeError(\"property must be configurable\")}return $})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDetectLibcCode = "(function (){\"use strict\";function family(){return Promise.resolve(familySync())}function familySync(){return null}const GLIBC=\"glibc\",MUSL=\"musl\";function versionAsync(){return Promise.resolve(version())}function version(){return null}function isNonGlibcLinuxSync(){return!1}function isNonGlibcLinux(){return Promise.resolve(isNonGlibcLinuxSync())}return{GLIBC,MUSL,family,familySync,isNonGlibcLinux,isNonGlibcLinuxSync,version,versionAsync}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDetectLibcLinuxCode = "(function (){\"use strict\";function family(){return Promise.resolve(familySync())}function familySync(){return GLIBC}const GLIBC=\"glibc\",MUSL=\"musl\";function versionAsync(){return Promise.resolve(version())}function version(){return\"2.29\"}function isNonGlibcLinuxSync(){return!1}function isNonGlibcLinux(){return Promise.resolve(isNonGlibcLinuxSync())}return{GLIBC,MUSL,family,familySync,isNonGlibcLinux,isNonGlibcLinuxSync,version,versionAsync}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyIsomorphicFetchCode = "(function (){\"use strict\";const bunFetch=Bun.fetch,fetch=(...args)=>bunFetch(...args);return fetch.default=fetch,fetch.fetch=fetch,fetch})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyNodeFetchCode = "(function (){\"use strict\";const{Headers,Request,Response,Blob,File=Blob,FormData}=globalThis,realFetch=Bun.fetch;function fetch(...args){return realFetch(...args)}class AbortError extends DOMException{constructor(message){super(message,\"AbortError\")}}class FetchBaseError extends Error{constructor(message,type){super(message);this.type=type}}class FetchError extends FetchBaseError{constructor(message,type,systemError){super(message,type);this.code=systemError\?.code}}function blobFrom(path,options){return Promise.resolve(Bun.file(data))}function blobFromSync(path,options){return Bun.file(data)}var fileFrom=blobFrom,fileFromSync=blobFromSync;function isRedirect(code){return code===301||code===302||code===303||code===307||code===308}return Object.assign(fetch,{AbortError,Blob,FetchBaseError,FetchError,File,FormData,Headers,Request,Response,blobFrom,blobFromSync,fileFrom,fileFromSync,isRedirect,fetch,default:fetch})})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyUndiciCode = "(function (){\"use strict\";const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),StreamModule=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),{Readable}=StreamModule,{_ReadableFromWebForUndici:ReadableFromWeb}=StreamModule[Symbol.for(\"::bunternal::\")],ObjectCreate=Object.create,kEmptyObject=ObjectCreate(null);var fetch=Bun.fetch,Response=globalThis.Response,Headers=globalThis.Headers,Request=globalThis.Request,URLSearchParams=globalThis.URLSearchParams,URL=globalThis.URL;class File extends Blob{constructor(){super(...arguments)}}class FileReader extends EventTarget{constructor(){throw new Error(\"Not implemented yet!\")}}var FormData=globalThis.FormData;function notImplemented(){throw new Error(\"Not implemented in bun\")}class BodyReadable extends ReadableFromWeb{#response;#bodyUsed;constructor(response,options={}){var{body}=response;if(!body)throw new Error(\"Response body is null\");super(options,body);this.#response=response,this.#bodyUsed=response.bodyUsed}get bodyUsed(){return this.#bodyUsed}#consume(){if(this.#bodyUsed)@throwTypeError(\"unusable\");this.#bodyUsed=!0}async arrayBuffer(){return this.#consume(),await this.#response.arrayBuffer()}async blob(){return this.#consume(),await this.#response.blob()}async formData(){return this.#consume(),await this.#response.formData()}async json(){return this.#consume(),await this.#response.json()}async text(){return this.#consume(),await this.#response.text()}}async function request(url,options={method:\"GET\",signal:null,headers:null,query:null,reset:!1,throwOnError:!1,body:null}){let{method=\"GET\",headers:inputHeaders,query,signal,reset=!1,throwOnError=!1,body:inputBody,maxRedirections}=options;if(typeof url===\"string\"){if(query)url=new URL(url)}else if(typeof url===\"object\"&&url!==null){if(!(url instanceof URL))throw new Error(\"not implemented\")}else @throwTypeError(\"url must be a string, URL, or UrlObject\");if(typeof url===\"string\"&&query)url=new URL(url);if(typeof url===\"object\"&&url!==null&&query){if(query)url.search=new URLSearchParams(query).toString()}if(method=method&&typeof method===\"string\"\?method.toUpperCase():null,inputBody&&(method===\"GET\"||method===\"HEAD\"))throw new Error(\"Body not allowed for GET or HEAD requests\");if(inputBody&&inputBody.read&&inputBody instanceof Readable){let data=\"\";inputBody.setEncoding(\"utf8\");for await(let chunk of stream)data+=chunk;inputBody=(new TextEncoder()).encode(data)}if(maxRedirections!==void 0&&Number.isNaN(maxRedirections))throw new Error(\"maxRedirections must be a number if defined\");if(signal&&!(signal instanceof AbortSignal))throw new Error(\"signal must be an instance of AbortSignal\");let resp;const{status:statusCode,headers,trailers}=resp=await fetch(url,{signal,mode:\"cors\",method,headers:inputHeaders||kEmptyObject,body:inputBody,redirect:maxRedirections===\"undefined\"||maxRedirections>0\?\"follow\":\"manual\",keepalive:!reset});if(throwOnError&&statusCode>=400&&statusCode<600)throw new Error(`Request failed with status code ${statusCode}`);const body=resp.body\?new BodyReadable(resp):null;return{statusCode,headers:headers.toJSON(),body,trailers,opaque:kEmptyObject,context:kEmptyObject}}function stream(){throw new Error(\"Not implemented in bun\")}function pipeline(){throw new Error(\"Not implemented in bun\")}function connect(){throw new Error(\"Not implemented in bun\")}function upgrade(){throw new Error(\"Not implemented in bun\")}class MockClient{constructor(){throw new Error(\"Not implemented in bun\")}}class MockPool{constructor(){throw new Error(\"Not implemented in bun\")}}class MockAgent{constructor(){throw new Error(\"Not implemented in bun\")}}function mockErrors(){throw new Error(\"Not implemented in bun\")}function Undici(){throw new Error(\"Not implemented in bun\")}class Dispatcher extends EventEmitter{constructor(){super(...arguments)}}class Agent extends Dispatcher{constructor(){super(...arguments)}}class Pool extends Dispatcher{constructor(){super(...arguments)}request(){throw new Error(\"Not implemented in bun\")}}class BalancedPool extends Dispatcher{constructor(){super(...arguments)}}class Client extends Dispatcher{constructor(){super(...arguments)}request(){throw new Error(\"Not implemented in bun\")}}return Undici.Dispatcher=Dispatcher,Undici.Pool=Pool,Undici.BalancedPool=BalancedPool,Undici.Client=Client,Undici.Agent=Agent,Undici.buildConnector=Undici.errors=Undici.setGlobalDispatcher=Undici.getGlobalDispatcher=Undici.request=Undici.stream=Undici.pipeline=Undici.connect=Undici.upgrade=Undici.MockClient=Undici.MockPool=Undici.MockAgent=Undici.mockErrors=notImplemented,Undici.fetch=fetch,{fetch,Response,Headers,Request,URLSearchParams,URL,File,FileReader,FormData,request,stream,pipeline,connect,upgrade,MockClient,MockPool,MockAgent,mockErrors,Dispatcher,Pool,BalancedPool,Client,Agent,Undici}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyVercelFetchCode = "(function (){\"use strict\";var $=(wrapper=Bun.fetch)=>{async function vercelFetch(url,opts={}){if(opts.body&&typeof opts.body===\"object\"&&(!(\"buffer\"in opts.body)||typeof opts.body.buffer!==\"object\"||!(opts.body.buffer instanceof ArrayBuffer))){if(opts.body=JSON.stringify(opts.body),!opts.headers)opts.headers=new Headers;opts.headers.set(\"Content-Type\",\"application/json\")}try{return await wrapper(url,opts)}catch(err){if(typeof err===\"string\")err=new Error(err);throw err.url=url,err.opts=opts,err}}return vercelFetch.default=vercelFetch,vercelFetch};return $})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyWSCode = "(function (){\"use strict\";const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),http=@getInternalField(@internalModuleRegistry,18)||@createInternalModuleById(18),kBunInternals=Symbol.for(\"::bunternal::\"),readyStates=[\"CONNECTING\",\"OPEN\",\"CLOSING\",\"CLOSED\"],encoder=new TextEncoder,eventIds={open:1,close:2,message:3,error:4,ping:5,pong:6},emittedWarnings=new Set;function emitWarning(type,message){if(emittedWarnings.has(type))return;emittedWarnings.add(type),console.warn(\"[bun] Warning:\",message)}class BunWebSocket extends EventEmitter{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;#ws;#paused=!1;#fragments=!1;#binaryType=\"nodebuffer\";#eventId=0;constructor(url,protocols,options){super();let ws=this.#ws=new WebSocket(url,protocols);ws.binaryType=\"nodebuffer\"}on(event,listener){if(event===\"unexpected-response\"||event===\"upgrade\"||event===\"redirect\")emitWarning(event,\"ws.WebSocket '\"+event+\"' event is not implemented in bun\");const mask=1<{this.emit(\"open\")});else if(event===\"close\")this.#ws.addEventListener(\"close\",({code,reason,wasClean})=>{this.emit(\"close\",code,reason,wasClean)});else if(event===\"message\")this.#ws.addEventListener(\"message\",({data})=>{const isBinary=typeof data!==\"string\";if(isBinary)this.emit(\"message\",this.#fragments\?[data]:data,isBinary);else{let encoded=encoder.encode(data);if(this.#binaryType!==\"arraybuffer\")encoded=Buffer.from(encoded.buffer,encoded.byteOffset,encoded.byteLength);this.emit(\"message\",this.#fragments\?[encoded]:encoded,isBinary)}});else if(event===\"error\")this.#ws.addEventListener(\"error\",(err)=>{this.emit(\"error\",err)});else if(event===\"ping\")this.#ws.addEventListener(\"ping\",({data})=>{this.emit(\"ping\",data)});else if(event===\"pong\")this.#ws.addEventListener(\"pong\",({data})=>{this.emit(\"pong\",data)})}return super.on(event,listener)}send(data,opts,cb){try{this.#ws.send(data,opts\?.compress)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}close(code,reason){this.#ws.close(code,reason)}terminate(){this.#ws.terminate()}get url(){return this.#ws.url}get readyState(){return this.#ws.readyState}get binaryType(){return this.#binaryType}set binaryType(value){if(value===\"nodebuffer\"||value===\"arraybuffer\")this.#ws.binaryType=this.#binaryType=value,this.#fragments=!1;else if(value===\"fragments\")this.#ws.binaryType=\"nodebuffer\",this.#binaryType=\"fragments\",this.#fragments=!0;else throw new Error(`Invalid binaryType: ${value}`)}get protocol(){return this.#ws.protocol}get extensions(){return this.#ws.extensions}addEventListener(type,listener,options){this.#ws.addEventListener(type,listener,options)}removeEventListener(type,listener){this.#ws.removeEventListener(type,listener)}get onopen(){return this.#ws.onopen}set onopen(value){this.#ws.onopen=value}get onerror(){return this.#ws.onerror}set onerror(value){this.#ws.onerror=value}get onclose(){return this.#ws.onclose}set onclose(value){this.#ws.onclose=value}get onmessage(){return this.#ws.onmessage}set onmessage(value){this.#ws.onmessage=value}get bufferedAmount(){return this.#ws.bufferedAmount}get isPaused(){return this.#paused}ping(data,mask,cb){if(typeof data===\"function\")cb=data,data=mask=void 0;else if(typeof mask===\"function\")cb=mask,mask=void 0;if(typeof data===\"number\")data=data.toString();try{this.#ws.ping(data)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}pong(data,mask,cb){if(typeof data===\"function\")cb=data,data=mask=void 0;else if(typeof mask===\"function\")cb=mask,mask=void 0;if(typeof data===\"number\")data=data.toString();try{this.#ws.pong(data)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}pause(){switch(this.readyState){case WebSocket.CONNECTING:case WebSocket.CLOSED:return}this.#paused=!0,emitWarning(\"pause()\",\"ws.WebSocket.pause() is not implemented in bun\")}resume(){switch(this.readyState){case WebSocket.CONNECTING:case WebSocket.CLOSED:return}this.#paused=!1,emitWarning(\"resume()\",\"ws.WebSocket.resume() is not implemented in bun\")}}Object.defineProperty(BunWebSocket,\"name\",{value:\"WebSocket\"});const wsKeyRegex=/^[+/0-9A-Za-z]{22}==$/,wsTokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,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,0,0,0,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,0,1,0,1,0];function subprotocolParse(header){const protocols=new Set;let start=-1,end=-1,i=0;for(i;i{const body=http.STATUS_CODES[426];res.writeHead(426,{\"Content-Length\":body.length,\"Content-Type\":\"text/plain\"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback);else if(options.server)this._server=options.server;if(this._server){const emitConnection=this.emit.bind(this,\"connection\"),emitListening=this.emit.bind(this,\"listening\"),emitError=this.emit.bind(this,\"error\"),doUpgrade=(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)};this._server.on(\"listening\",emitListening),this._server.on(\"error\",emitError),this._server.on(\"upgrade\",doUpgrade),this._removeListeners=()=>{this._server.removeListener(\"upgrade\",doUpgrade),this._server.removeListener(\"listening\",emitListening),this._server.removeListener(\"error\",emitError)}}if(options.perMessageDeflate===!0)options.perMessageDeflate={};if(options.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=options,this._state=RUNNING}address(){if(this.options.noServer)throw new Error('The server is operating in \"noServer\" mode');if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb)this.once(\"close\",()=>{cb(new Error(\"The server is not running\"))});process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this);return}if(cb)this.once(\"close\",cb);if(this._state===CLOSING)return;if(this._state=CLOSING,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this);else this._shouldEmitClose=!0;else process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this)}else{const server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{this._state=CLOSED,this.emit(\"close\")})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf(\"\?\");if((index!==-1\?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}completeUpgrade(extensions,key,protocols,request,socket,head,cb){const[server,response,req]=socket[kBunInternals];if(this._state>RUNNING)return abortHandshake(response,503);let protocol=\"\";if(protocols.size)protocol=this.options.handleProtocols\?this.options.handleProtocols(protocols,request):protocols.values().next().value;const ws=new BunWebSocketMocked(request.url,protocol,extensions,\"nodebuffer\"),headers=[\"HTTP/1.1 101 Switching Protocols\",\"Upgrade: websocket\",\"Connection: Upgrade\"];if(this.emit(\"headers\",headers,request),server.upgrade(req,{data:ws[kBunInternals]})){if(response._reply(void 0),this.clients)this.clients.add(ws),ws.on(\"close\",()=>{if(this.clients.delete(ws),this._shouldEmitClose&&!this.clients.size)process.nextTick(wsEmitClose,this)});cb(ws,request)}else abortHandshake(response,500)}handleUpgrade(req,socket,head,cb){const[_,response]=socket[kBunInternals],key=req.headers[\"sec-websocket-key\"],version=+req.headers[\"sec-websocket-version\"];if(req.method!==\"GET\"){abortHandshakeOrEmitwsClientError(this,req,response,socket,405,\"Invalid HTTP method\");return}if(req.headers.upgrade.toLowerCase()!==\"websocket\"){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Invalid Upgrade header\");return}if(!key||!wsKeyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Missing or invalid Sec-WebSocket-Key header\");return}if(version!==8&&version!==13){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Missing or invalid Sec-WebSocket-Version header\");return}if(!this.shouldHandle(req)){abortHandshake(response,400);return}const secWebSocketProtocol=req.headers[\"sec-websocket-protocol\"];let protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocolParse(secWebSocketProtocol)}catch(err){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Invalid Sec-WebSocket-Protocol header\");return}const extensions={};if(this.options.verifyClient){const info={origin:req.headers[`${version===8\?\"sec-websocket-origin\":\"origin\"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(response,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(response,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}}Object.defineProperty(BunWebSocket,\"CONNECTING\",{enumerable:!0,value:readyStates.indexOf(\"CONNECTING\")}),Object.defineProperty(BunWebSocket.prototype,\"CONNECTING\",{enumerable:!0,value:readyStates.indexOf(\"CONNECTING\")}),Object.defineProperty(BunWebSocket,\"OPEN\",{enumerable:!0,value:readyStates.indexOf(\"OPEN\")}),Object.defineProperty(BunWebSocket.prototype,\"OPEN\",{enumerable:!0,value:readyStates.indexOf(\"OPEN\")}),Object.defineProperty(BunWebSocket,\"CLOSING\",{enumerable:!0,value:readyStates.indexOf(\"CLOSING\")}),Object.defineProperty(BunWebSocket.prototype,\"CLOSING\",{enumerable:!0,value:readyStates.indexOf(\"CLOSING\")}),Object.defineProperty(BunWebSocket,\"CLOSED\",{enumerable:!0,value:readyStates.indexOf(\"CLOSED\")}),Object.defineProperty(BunWebSocket.prototype,\"CLOSED\",{enumerable:!0,value:readyStates.indexOf(\"CLOSED\")});class Sender{constructor(){throw new Error(\"Not supported yet in Bun\")}}class Receiver{constructor(){throw new Error(\"Not supported yet in Bun\")}}var createWebSocketStream=(ws)=>{throw new Error(\"Not supported yet in Bun\")};return Object.assign(BunWebSocket,{createWebSocketStream,Receiver,Sender,WebSocket:BunWebSocket,Server:WebSocketServer,WebSocketServer})})\n"_s; +// + + #elif _WIN32 + // +static constexpr ASCIILiteral BunFFICode = "(function (){\"use strict\";const FFIType={\"0\":0,\"1\":1,\"2\":2,\"3\":3,\"4\":4,\"5\":5,\"6\":6,\"7\":7,\"8\":8,\"9\":9,\"10\":10,\"11\":11,\"12\":12,\"13\":13,\"14\":14,\"15\":15,\"16\":16,\"17\":17,bool:11,c_int:5,c_uint:6,char:0,\"char*\":12,double:9,f32:10,f64:9,float:10,i16:3,i32:5,i64:7,i8:1,int:5,int16_t:3,int32_t:5,int64_t:7,int8_t:1,isize:7,u16:4,u32:6,u64:8,u8:2,uint16_t:4,uint32_t:6,uint64_t:8,uint8_t:2,usize:8,\"void*\":12,ptr:12,pointer:12,void:13,cstring:14,i64_fast:15,u64_fast:16,function:17,callback:17,fn:17};var ffi=globalThis.Bun.FFI;const ptr=(arg1,arg2)=>typeof arg2===\"undefined\"\?ffi.ptr(arg1):ffi.ptr(arg1,arg2),toBuffer=ffi.toBuffer,toArrayBuffer=ffi.toArrayBuffer,viewSource=ffi.viewSource,BunCString=ffi.CString,nativeLinkSymbols=ffi.linkSymbols,nativeDLOpen=ffi.dlopen,nativeCallback=ffi.callback,closeCallback=ffi.closeCallback;delete ffi.callback,delete ffi.closeCallback;class JSCallback{constructor(cb,options){const{ctx,ptr:ptr2}=nativeCallback(options,cb);this.#ctx=ctx,this.ptr=ptr2,this.#threadsafe=!!options\?.threadsafe}ptr;#ctx;#threadsafe;get threadsafe(){return this.#threadsafe}[Symbol.toPrimitive](){const{ptr:ptr2}=this;return typeof ptr2===\"number\"\?ptr2:0}close(){const ctx=this.#ctx;if(this.ptr=null,this.#ctx=null,ctx)closeCallback(ctx)}}class CString extends String{constructor(ptr2,byteOffset,byteLength){super(ptr2\?typeof byteLength===\"number\"&&Number.isSafeInteger(byteLength)\?new BunCString(ptr2,byteOffset||0,byteLength):new BunCString(ptr2):\"\");if(this.ptr=typeof ptr2===\"number\"\?ptr2:0,typeof byteOffset!==\"undefined\")this.byteOffset=byteOffset;if(typeof byteLength!==\"undefined\")this.byteLength=byteLength}ptr;byteOffset;byteLength;#cachedArrayBuffer;get arrayBuffer(){if(this.#cachedArrayBuffer)return this.#cachedArrayBuffer;if(!this.ptr)return this.#cachedArrayBuffer=new ArrayBuffer(0);return this.#cachedArrayBuffer=toArrayBuffer(this.ptr,this.byteOffset,this.byteLength)}}Object.defineProperty(globalThis,\"__GlobalBunCString\",{value:CString,enumerable:!1,configurable:!1});const ffiWrappers=new Array(18);var char=\"val|0\";ffiWrappers.fill(char),ffiWrappers[FFIType.uint8_t]=\"val<0\?0:val>=255\?255:val|0\",ffiWrappers[FFIType.int16_t]=\"val<=-32768\?-32768:val>=32768\?32768:val|0\",ffiWrappers[FFIType.uint16_t]=\"val<=0\?0:val>=65536\?65536:val|0\",ffiWrappers[FFIType.int32_t]=\"val|0\",ffiWrappers[FFIType.uint32_t]=\"val<=0\?0:val>=0xffffffff\?0xffffffff:+val||0\",ffiWrappers[FFIType.i64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.i64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.u64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= 0) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.int64_t]=`{\n if (typeof val === \"bigint\") {\n return val;\n }\n\n if (typeof val === \"number\") {\n return BigInt(val || 0);\n }\n\n return BigInt(+val || 0);\n}`,ffiWrappers[FFIType.uint64_t]=`{\n if (typeof val === \"bigint\") {\n return val;\n }\n\n if (typeof val === \"number\") {\n return val <= 0 \? BigInt(0) : BigInt(val || 0);\n }\n\n return BigInt(+val || 0);\n}`,ffiWrappers[FFIType.u64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(0)) return Number(val);\n return val;\n }\n\n return typeof val === \"number\" \? (val <= 0 \? 0 : +val || 0) : +val || 0;\n}`,ffiWrappers[FFIType.uint16_t]=`{\n const ret = (typeof val === \"bigint\" \? Number(val) : val) | 0;\n return ret <= 0 \? 0 : ret > 0xffff \? 0xffff : ret;\n}`,ffiWrappers[FFIType.double]=`{\n if (typeof val === \"bigint\") {\n if (val.valueOf() < BigInt(Number.MAX_VALUE)) {\n return Math.abs(Number(val).valueOf()) + 0.00000000000001 - 0.00000000000001;\n }\n }\n\n if (!val) {\n return 0 + 0.00000000000001 - 0.00000000000001;\n }\n\n return val + 0.00000000000001 - 0.00000000000001;\n}`,ffiWrappers[FFIType.float]=ffiWrappers[10]=`{\n return Math.fround(val);\n}`,ffiWrappers[FFIType.bool]=`{\n return !!val;\n}`,Object.defineProperty(globalThis,\"__GlobalBunFFIPtrFunctionForWrapper\",{value:ptr,enumerable:!1,configurable:!0}),ffiWrappers[FFIType.cstring]=ffiWrappers[FFIType.pointer]=`{\n if (typeof val === \"number\") return val;\n if (!val) {\n return null;\n }\n\n if (ArrayBuffer.isView(val) || val instanceof ArrayBuffer) {\n return __GlobalBunFFIPtrFunctionForWrapper(val);\n }\n\n if (typeof val === \"string\") {\n throw new TypeError(\"To convert a string to a pointer, encode it as a buffer\");\n }\n\n throw new TypeError(\\`Unable to convert \\${ val } to a pointer\\`);\n}`,ffiWrappers[FFIType.function]=`{\n if (typeof val === \"number\") {\n return val;\n }\n\n if (typeof val === \"bigint\") {\n return Number(val);\n }\n\n var ptr = val && val.ptr;\n\n if (!ptr) {\n throw new TypeError(\"Expected function to be a JSCallback or a number\");\n }\n\n return ptr;\n}`;function FFIBuilder(params,returnType,functionToCall,name){const hasReturnType=typeof FFIType[returnType]===\"number\"&&FFIType[returnType]!==FFIType.void;var paramNames=new Array(params.length),args=new Array(params.length);for(let i=0;i${wrapper})(p${i})`;else @throwTypeError(`Unsupported type ${params[i]}. Must be one of: ${Object.keys(FFIType).sort().join(\", \")}`)}var code=`functionToCall(${args.join(\", \")})`;if(hasReturnType)if(FFIType[returnType]===FFIType.cstring)code=`return new __GlobalBunCString(${code})`;else code=`return ${code}`;var func=new Function(\"functionToCall\",...paramNames,code);Object.defineProperty(func,\"name\",{value:name});var wrap;switch(paramNames.length){case 0:wrap=()=>func(functionToCall);break;case 1:wrap=(arg1)=>func(functionToCall,arg1);break;case 2:wrap=(arg1,arg2)=>func(functionToCall,arg1,arg2);break;case 3:wrap=(arg1,arg2,arg3)=>func(functionToCall,arg1,arg2,arg3);break;case 4:wrap=(arg1,arg2,arg3,arg4)=>func(functionToCall,arg1,arg2,arg3,arg4);break;case 5:wrap=(arg1,arg2,arg3,arg4,arg5)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5);break;case 6:wrap=(arg1,arg2,arg3,arg4,arg5,arg6)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6);break;case 7:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7);break;case 8:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);break;case 9:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);break;default:{wrap=(...args2)=>func(functionToCall,...args2);break}}return wrap.native=functionToCall,wrap.ptr=functionToCall.ptr,wrap}const native={dlopen:nativeDLOpen,callback:()=>{throw new Error(\"Deprecated. Use new JSCallback(options, fn) instead\")}};function dlopen(path,options){const result=nativeDLOpen(path,options);for(let key in result.symbols){var symbol=result.symbols[key];if(options[key]\?.args\?.length||FFIType[options[key]\?.returns]===FFIType.cstring)result.symbols[key]=FFIBuilder(options[key].args\?\?[],options[key].returns\?\?FFIType.void,symbol,path.includes(\"/\")\?`${key} (${path.split(\"/\").pop()})`:`${key} (${path})`);else result.symbols[key].native=result.symbols[key]}return result}function linkSymbols(options){const result=nativeLinkSymbols(options);for(let key in result.symbols){var symbol=result.symbols[key];if(options[key]\?.args\?.length||FFIType[options[key]\?.returns]===FFIType.cstring)result.symbols[key]=FFIBuilder(options[key].args\?\?[],options[key].returns\?\?FFIType.void,symbol,key);else result.symbols[key].native=result.symbols[key]}return result}var cFunctionI=0,cFunctionRegistry;function onCloseCFunction(close){close()}function CFunction(options){const identifier=`CFunction${cFunctionI++}`;var result=linkSymbols({[identifier]:options}),hasClosed=!1,close=result.close;return result.symbols[identifier].close=()=>{if(hasClosed||!close)return;hasClosed=!0,close(),close=void 0},cFunctionRegistry||=new FinalizationRegistry(onCloseCFunction),cFunctionRegistry.register(result.symbols[identifier],result.symbols[identifier].close),result.symbols[identifier]}const read=ffi.read;return{CFunction,CString,FFIType,JSCallback,dlopen,linkSymbols,native,ptr,read,suffix:\"dll\",toArrayBuffer,toBuffer,viewSource}})\n"_s; +// + +// +static constexpr ASCIILiteral BunSqliteCode = "(function (){\"use strict\";var defineProperties=Object.defineProperties,toStringTag=Symbol.toStringTag,isArray=Array.isArray,isTypedArray=ArrayBuffer.isView;const constants={SQLITE_OPEN_READONLY:1,SQLITE_OPEN_READWRITE:2,SQLITE_OPEN_CREATE:4,SQLITE_OPEN_DELETEONCLOSE:8,SQLITE_OPEN_EXCLUSIVE:16,SQLITE_OPEN_AUTOPROXY:32,SQLITE_OPEN_URI:64,SQLITE_OPEN_MEMORY:128,SQLITE_OPEN_MAIN_DB:256,SQLITE_OPEN_TEMP_DB:512,SQLITE_OPEN_TRANSIENT_DB:1024,SQLITE_OPEN_MAIN_JOURNAL:2048,SQLITE_OPEN_TEMP_JOURNAL:4096,SQLITE_OPEN_SUBJOURNAL:8192,SQLITE_OPEN_SUPER_JOURNAL:16384,SQLITE_OPEN_NOMUTEX:32768,SQLITE_OPEN_FULLMUTEX:65536,SQLITE_OPEN_SHAREDCACHE:131072,SQLITE_OPEN_PRIVATECACHE:262144,SQLITE_OPEN_WAL:524288,SQLITE_OPEN_NOFOLLOW:16777216,SQLITE_OPEN_EXRESCODE:33554432,SQLITE_PREPARE_PERSISTENT:1,SQLITE_PREPARE_NORMALIZE:2,SQLITE_PREPARE_NO_VTAB:4};var SQL,controllers;class Statement{constructor(raw){switch(this.#raw=raw,raw.paramsCount){case 0:{this.get=this.#getNoArgs,this.all=this.#allNoArgs,this.values=this.#valuesNoArgs,this.run=this.#runNoArgs;break}default:{this.get=this.#get,this.all=this.#all,this.values=this.#values,this.run=this.#run;break}}}#raw;get;all;values;run;isFinalized=!1;toJSON(){return{sql:this.native.toString(),isFinalized:this.isFinalized,paramsCount:this.paramsCount,columnNames:this.columnNames}}get[toStringTag](){return`\"${this.native.toString()}\"`}toString(){return this.native.toString()}get native(){return this.#raw}#getNoArgs(){return this.#raw.get()}#allNoArgs(){return this.#raw.all()}#valuesNoArgs(){return this.#raw.values()}#runNoArgs(){this.#raw.run()}#get(...args){if(args.length===0)return this.#getNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.get(args):this.#raw.get(...args)}#all(...args){if(args.length===0)return this.#allNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.all(args):this.#raw.all(...args)}#values(...args){if(args.length===0)return this.#valuesNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.values(args):this.#raw.values(...args)}#run(...args){if(args.length===0)return this.#runNoArgs();var arg0=args[0];!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.run(args):this.#raw.run(...args)}get columnNames(){return this.#raw.columns}get paramsCount(){return this.#raw.paramsCount}finalize(...args){return this.isFinalized=!0,this.#raw.finalize(...args)}}var cachedCount=Symbol.for(\"Bun.Database.cache.count\");class Database{constructor(filenameGiven,options){if(typeof filenameGiven===\"undefined\");else if(typeof filenameGiven!==\"string\"){if(isTypedArray(filenameGiven)){this.#handle=Database.deserialize(filenameGiven,typeof options===\"object\"&&options\?!!options.readonly:((options|0)&constants.SQLITE_OPEN_READONLY)!=0),this.filename=\":memory:\";return}@throwTypeError(`Expected 'filename' to be a string, got '${typeof filenameGiven}'`)}var filename=typeof filenameGiven===\"string\"\?filenameGiven.trim():\":memory:\",flags=constants.SQLITE_OPEN_READWRITE|constants.SQLITE_OPEN_CREATE;if(typeof options===\"object\"&&options){if(flags=0,options.readonly)flags=constants.SQLITE_OPEN_READONLY;if(\"readOnly\"in options)@throwTypeError('Misspelled option \"readOnly\" should be \"readonly\"');if(options.create)flags=constants.SQLITE_OPEN_READWRITE|constants.SQLITE_OPEN_CREATE;if(options.readwrite)flags|=constants.SQLITE_OPEN_READWRITE}else if(typeof options===\"number\")flags=options;const anonymous=filename===\"\"||filename===\":memory:\";if(anonymous&&(flags&constants.SQLITE_OPEN_READONLY)!==0)throw new Error(\"Cannot open an anonymous database in read-only mode.\");if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");this.#handle=SQL.open(anonymous\?\":memory:\":filename,flags),this.filename=filename}#handle;#cachedQueriesKeys=[];#cachedQueriesLengths=[];#cachedQueriesValues=[];filename;get handle(){return this.#handle}get inTransaction(){return SQL.isInTransaction(this.#handle)}static open(filename,options){return new Database(filename,options)}loadExtension(name,entryPoint){return SQL.loadExtension(this.#handle,name,entryPoint)}serialize(optionalName){return SQL.serialize(this.#handle,optionalName||\"main\")}static deserialize(serialized,isReadOnly=!1){if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");return SQL.deserialize(serialized,isReadOnly)}static setCustomSQLite(path){if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");return SQL.setCustomSQLite(path)}close(){return this.clearQueryCache(),SQL.close(this.#handle)}clearQueryCache(){for(let item of this.#cachedQueriesValues)item.finalize();this.#cachedQueriesKeys.length=0,this.#cachedQueriesValues.length=0,this.#cachedQueriesLengths.length=0}run(query,...params){if(params.length===0){SQL.run(this.#handle,query);return}var arg0=params[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?SQL.run(this.#handle,query,params):SQL.run(this.#handle,query,...params)}prepare(query,params,flags){return new Statement(SQL.prepare(this.#handle,query,params,flags||0))}static MAX_QUERY_CACHE_SIZE=20;get[cachedCount](){return this.#cachedQueriesKeys.length}query(query){if(typeof query!==\"string\")@throwTypeError(`Expected 'query' to be a string, got '${typeof query}'`);if(query.length===0)throw new Error(\"SQL query cannot be empty.\");var index=this.#cachedQueriesLengths.indexOf(query.length);while(index!==-1){if(this.#cachedQueriesKeys[index]!==query){index=this.#cachedQueriesLengths.indexOf(query.length,index+1);continue}var stmt=this.#cachedQueriesValues[index];if(stmt.isFinalized)return this.#cachedQueriesValues[index]=this.prepare(query,void 0,willCache\?constants.SQLITE_PREPARE_PERSISTENT:0);return stmt}const willCache=this.#cachedQueriesKeys.length{let controller=(controllers||=new WeakMap).get(db);if(!controller){const shared={commit:db.prepare(\"COMMIT\",void 0,0),rollback:db.prepare(\"ROLLBACK\",void 0,0),savepoint:db.prepare(\"SAVEPOINT `\\t_bs3.\\t`\",void 0,0),release:db.prepare(\"RELEASE `\\t_bs3.\\t`\",void 0,0),rollbackTo:db.prepare(\"ROLLBACK TO `\\t_bs3.\\t`\",void 0,0)};controllers.set(db,controller={default:Object.assign({begin:db.prepare(\"BEGIN\",void 0,0)},shared),deferred:Object.assign({begin:db.prepare(\"BEGIN DEFERRED\",void 0,0)},shared),immediate:Object.assign({begin:db.prepare(\"BEGIN IMMEDIATE\",void 0,0)},shared),exclusive:Object.assign({begin:db.prepare(\"BEGIN EXCLUSIVE\",void 0,0)},shared)})}return controller},wrapTransaction=(fn,db,{begin,commit,rollback,savepoint,release,rollbackTo})=>function transaction(...args){let before,after,undo;if(db.inTransaction)before=savepoint,after=release,undo=rollbackTo;else before=begin,after=commit,undo=rollback;try{before.run();const result=fn.apply(this,args);return after.run(),result}catch(ex){if(db.inTransaction){if(undo.run(),undo!==rollback)after.run()}throw ex}};return{__esModule:!0,Database,Statement,constants,default:Database}})\n"_s; +// + +// +static constexpr ASCIILiteral InternalSharedCode = "(function (){\"use strict\";class NotImplementedError extends Error{code;constructor(feature,issue){super(feature+\" is not yet implemented in Bun.\"+(issue\?\" Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/\"+issue:\"\"));this.name=\"NotImplementedError\",this.code=\"ERR_NOT_IMPLEMENTED\",hideFromStack(NotImplementedError)}}function throwNotImplemented(feature,issue){throw hideFromStack(throwNotImplemented),new NotImplementedError(feature,issue)}function hideFromStack(...fns){for(let fn of fns)Object.defineProperty(fn,\"name\",{value:\"::bunternal::\"})}return{NotImplementedError,throwNotImplemented,hideFromStack}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeAssertCode = "(function (){\"use strict\";const util=@getInternalField(@internalModuleRegistry,42)||@createInternalModuleById(42);var isDeepEqual=Bun.deepEquals,__commonJS=(cb,mod)=>function(){return mod||(0,cb[Object.keys(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_errors=__commonJS({\"assert/build/internal/errors.js\"(exports,module2){function _typeof(obj){return typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"\?_typeof=function(obj2){return typeof obj2}:_typeof=function(obj2){return obj2&&typeof Symbol==\"function\"&&obj2.constructor===Symbol&&obj2!==Symbol.prototype\?\"symbol\":typeof obj2},_typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))@throwTypeError(\"Cannot call a class as a function\")}function _possibleConstructorReturn(self,call){return call&&(_typeof(call)===\"object\"||typeof call==\"function\")\?call:_assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return self}function _getPrototypeOf(o){return _getPrototypeOf=Object.setPrototypeOf\?Object.getPrototypeOf:function(o2){return o2.__proto__||Object.getPrototypeOf(o2)},_getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=\"function\"&&superClass!==null)@throwTypeError(\"Super expression must either be null or a function\");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),superClass&&_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){return _setPrototypeOf=Object.setPrototypeOf||function(o2,p2){return o2.__proto__=p2,o2},_setPrototypeOf(o,p)}var codes={},assert,util2;function createErrorType(code,message,Base){Base||(Base=Error);function getMessage(arg1,arg2,arg3){return typeof message==\"string\"\?message:message(arg1,arg2,arg3)}var NodeError=function(_Base){_inherits(NodeError2,_Base);function NodeError2(arg1,arg2,arg3){var _this;return _classCallCheck(this,NodeError2),_this=_possibleConstructorReturn(this,_getPrototypeOf(NodeError2).call(this,getMessage(arg1,arg2,arg3))),_this.code=code,_this}return NodeError2}(Base);codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return String(i)}),len>2\?\"one of \".concat(thing,\" \").concat(expected.slice(0,len-1).join(\", \"),\", or \")+expected[len-1]:len===2\?\"one of \".concat(thing,\" \").concat(expected[0],\" or \").concat(expected[1]):\"of \".concat(thing,\" \").concat(expected[0])}else return\"of \".concat(thing,\" \").concat(String(expected))}function startsWith(str,search,pos){return str.substr(!pos||pos<0\?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(this_len===void 0||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return typeof start!=\"number\"&&(start=0),start+search.length>str.length\?!1:str.indexOf(search,start)!==-1}createErrorType(\"ERR_AMBIGUOUS_ARGUMENT\",'The \"%s\" argument is ambiguous. %s',TypeError),createErrorType(\"ERR_INVALID_ARG_TYPE\",function(name,expected,actual){assert===void 0&&(assert=require_assert()),assert(typeof name==\"string\",\"'name' must be a string\");var determiner;typeof expected==\"string\"&&startsWith(expected,\"not \")\?(determiner=\"must not be\",expected=expected.replace(/^not /,\"\")):determiner=\"must be\";var msg;if(endsWith(name,\" argument\"))msg=\"The \".concat(name,\" \").concat(determiner,\" \").concat(oneOf(expected,\"type\"));else{var type=includes(name,\".\")\?\"property\":\"argument\";msg='The \"'.concat(name,'\" ').concat(type,\" \").concat(determiner,\" \").concat(oneOf(expected,\"type\"))}return msg+=\". Received type \".concat(_typeof(actual)),msg},TypeError),createErrorType(\"ERR_INVALID_ARG_VALUE\",function(name,value){var reason=arguments.length>2&&arguments[2]!==void 0\?arguments[2]:\"is invalid\",inspected=util2.inspect(value);return inspected.length>128&&(inspected=\"\".concat(inspected.slice(0,128),\"...\")),\"The argument '\".concat(name,\"' \").concat(reason,\". Received \").concat(inspected)},TypeError,RangeError),createErrorType(\"ERR_INVALID_RETURN_VALUE\",function(input,name,value){var type;return value&&value.constructor&&value.constructor.name\?type=\"instance of \".concat(value.constructor.name):type=\"type \".concat(_typeof(value)),\"Expected \".concat(input,' to be returned from the \"').concat(name,'\"')+\" function but got \".concat(type,\".\")},TypeError),createErrorType(\"ERR_MISSING_ARGS\",function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];assert===void 0&&(assert=require_assert()),assert(args.length>0,\"At least one arg needs to be specified\");var msg=\"The \",len=args.length;switch(args=args.map(function(a){return'\"'.concat(a,'\"')}),len){case 1:msg+=\"\".concat(args[0],\" argument\");break;case 2:msg+=\"\".concat(args[0],\" and \").concat(args[1],\" arguments\");break;default:msg+=args.slice(0,len-1).join(\", \"),msg+=\", and \".concat(args[len-1],\" arguments\");break}return\"\".concat(msg,\" must be specified\")},TypeError),module2.exports.codes=codes}}),require_assertion_error=__commonJS({\"assert/build/internal/assert/assertion_error.js\"(exports,module2){function _objectSpread(target){for(var i=1;istr.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function repeat(str,count){if(count=Math.floor(count),str.length==0||count==0)return\"\";var maxCount=str.length*count;for(count=Math.floor(Math.log(count)/Math.log(2));count;)str+=str,count--;return str+=str.substring(0,maxCount-str.length),str}var blue=\"\",green=\"\",red=\"\",white=\"\",kReadableOperator={deepStrictEqual:\"Expected values to be strictly deep-equal:\",strictEqual:\"Expected values to be strictly equal:\",strictEqualObject:'Expected \"actual\" to be reference-equal to \"expected\":',deepEqual:\"Expected values to be loosely deep-equal:\",equal:\"Expected values to be loosely equal:\",notDeepStrictEqual:'Expected \"actual\" not to be strictly deep-equal to:',notStrictEqual:'Expected \"actual\" to be strictly unequal to:',notStrictEqualObject:'Expected \"actual\" not to be reference-equal to \"expected\":',notDeepEqual:'Expected \"actual\" not to be loosely deep-equal to:',notEqual:'Expected \"actual\" to be loosely unequal to:',notIdentical:\"Values identical but not reference-equal:\"},kMaxShortLength=10;function copyError(source){var keys=Object.keys(source),target=Object.create(Object.getPrototypeOf(source));return keys.forEach(function(key){target[key]=source[key]}),Object.defineProperty(target,\"message\",{value:source.message}),target}function inspectValue(val){return inspect(val,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:Infinity,showHidden:!1,breakLength:Infinity,showProxy:!1,sorted:!0,getters:!0})}function createErrDiff(actual,expected,operator){var other=\"\",res=\"\",lastPos=0,end=\"\",skipped=!1,actualInspected=inspectValue(actual),actualLines=actualInspected.split(`\n`),expectedLines=inspectValue(expected).split(`\n`),i=0,indicator=\"\";if(operator===\"strictEqual\"&&_typeof(actual)===\"object\"&&_typeof(expected)===\"object\"&&actual!==null&&expected!==null&&(operator=\"strictEqualObject\"),actualLines.length===1&&expectedLines.length===1&&actualLines[0]!==expectedLines[0]){var inputLength=actualLines[0].length+expectedLines[0].length;if(inputLength<=kMaxShortLength){if((_typeof(actual)!==\"object\"||actual===null)&&(_typeof(expected)!==\"object\"||expected===null)&&(actual!==0||expected!==0))return\"\".concat(kReadableOperator[operator],`\n\n`)+\"\".concat(actualLines[0],\" !== \").concat(expectedLines[0],`\n`)}else if(operator!==\"strictEqualObject\"){var maxLength=process.stderr&&process.stderr.isTTY\?process.stderr.columns:80;if(inputLength2&&(indicator=`\n `.concat(repeat(\" \",i),\"^\"),i=0)}}}for(var a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];a===b&&(i++<2\?end=`\n `.concat(a).concat(end):other=a,actualLines.pop(),expectedLines.pop(),!(actualLines.length===0||expectedLines.length===0));)a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];var maxLines=Math.max(actualLines.length,expectedLines.length);if(maxLines===0){var _actualLines=actualInspected.split(`\n`);if(_actualLines.length>30)for(_actualLines[26]=\"\".concat(blue,\"...\").concat(white);_actualLines.length>27;)_actualLines.pop();return\"\".concat(kReadableOperator.notIdentical,`\n\n`).concat(_actualLines.join(`\n`),`\n`)}i>3&&(end=`\n`.concat(blue,\"...\").concat(white).concat(end),skipped=!0),other!==\"\"&&(end=`\n `.concat(other).concat(end),other=\"\");var printedLines=0,msg=kReadableOperator[operator]+`\n`.concat(green,\"+ actual\").concat(white,\" \").concat(red,\"- expected\").concat(white),skippedMsg=\" \".concat(blue,\"...\").concat(white,\" Lines skipped\");for(i=0;i1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(expectedLines[i-2]),printedLines++),res+=`\n `.concat(expectedLines[i-1]),printedLines++),lastPos=i,other+=`\n`.concat(red,\"-\").concat(white,\" \").concat(expectedLines[i]),printedLines++;else if(expectedLines.length1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(actualLines[i-2]),printedLines++),res+=`\n `.concat(actualLines[i-1]),printedLines++),lastPos=i,res+=`\n`.concat(green,\"+\").concat(white,\" \").concat(actualLines[i]),printedLines++;else{var expectedLine=expectedLines[i],actualLine=actualLines[i],divergingLines=actualLine!==expectedLine&&(!endsWith(actualLine,\",\")||actualLine.slice(0,-1)!==expectedLine);divergingLines&&endsWith(expectedLine,\",\")&&expectedLine.slice(0,-1)===actualLine&&(divergingLines=!1,actualLine+=\",\"),divergingLines\?(cur>1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(actualLines[i-2]),printedLines++),res+=`\n `.concat(actualLines[i-1]),printedLines++),lastPos=i,res+=`\n`.concat(green,\"+\").concat(white,\" \").concat(actualLine),other+=`\n`.concat(red,\"-\").concat(white,\" \").concat(expectedLine),printedLines+=2):(res+=other,other=\"\",(cur===1||i===0)&&(res+=`\n `.concat(actualLine),printedLines++))}if(printedLines>20&&i30)for(res[26]=\"\".concat(blue,\"...\").concat(white);res.length>27;)res.pop();res.length===1\?_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(base,\" \").concat(res[0]))):_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(base,`\n\n`).concat(res.join(`\n`),`\n`)))}else{var _res=inspectValue(actual),other=\"\",knownOperators=kReadableOperator[operator];operator===\"notDeepEqual\"||operator===\"notEqual\"\?(_res=\"\".concat(kReadableOperator[operator],`\n\n`).concat(_res),_res.length>1024&&(_res=\"\".concat(_res.slice(0,1021),\"...\"))):(other=\"\".concat(inspectValue(expected)),_res.length>512&&(_res=\"\".concat(_res.slice(0,509),\"...\")),other.length>512&&(other=\"\".concat(other.slice(0,509),\"...\")),operator===\"deepEqual\"||operator===\"equal\"\?_res=\"\".concat(knownOperators,`\n\n`).concat(_res,`\n\nshould equal\n\n`):other=\" \".concat(operator,\" \").concat(other)),_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(_res).concat(other)))}return Error.stackTraceLimit=limit,_this.generatedMessage=!message,Object.defineProperty(_assertThisInitialized(_this),\"name\",{value:\"AssertionError [ERR_ASSERTION]\",enumerable:!1,writable:!0,configurable:!0}),_this.code=\"ERR_ASSERTION\",_this.actual=actual,_this.expected=expected,_this.operator=operator,Error.captureStackTrace&&Error.captureStackTrace(_assertThisInitialized(_this),stackStartFn),_this.stack,_this.name=\"AssertionError\",_possibleConstructorReturn(_this)}return AssertionError2.prototype={},_inherits(AssertionError2,_Error),_createClass(AssertionError2,[{key:\"toString\",value:function(){return\"\".concat(this.name,\" [\").concat(this.code,\"]: \").concat(this.message)}},{key:inspect.custom,value:function(recurseTimes,ctx){return inspect(this,_objectSpread({},ctx,{customInspect:!1,depth:0}))}}]),AssertionError2}(_wrapNativeSuper(Error));module2.exports=AssertionError}}),require_assert=__commonJS({\"assert/build/assert.js\"(exports,module2){function _typeof(obj){return typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"\?_typeof=function(obj2){return typeof obj2}:_typeof=function(obj2){return obj2&&typeof Symbol==\"function\"&&obj2.constructor===Symbol&&obj2!==Symbol.prototype\?\"symbol\":typeof obj2},_typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))@throwTypeError(\"Cannot call a class as a function\")}var _require=require_errors(),_require$codes=_require.codes,ERR_AMBIGUOUS_ARGUMENT=_require$codes.ERR_AMBIGUOUS_ARGUMENT,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_INVALID_ARG_VALUE=_require$codes.ERR_INVALID_ARG_VALUE,ERR_INVALID_RETURN_VALUE=_require$codes.ERR_INVALID_RETURN_VALUE,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,AssertionError=require_assertion_error(),_require2=util,inspect=_require2.inspect,_require$types=util.types,isPromise=_require$types.isPromise,isRegExp=_require$types.isRegExp,objectAssign=Object.assign,objectIs=Object.is,errorCache=new Map,warned=!1,assert=module2.exports=ok,NO_EXCEPTION_SENTINEL={};function innerFail(obj){throw obj.message instanceof Error\?obj.message:new AssertionError(obj)}function fail(actual,expected,message,operator,stackStartFn){var argsLen=arguments.length,internalMessage;if(argsLen===0)internalMessage=\"Failed\";else if(argsLen===1)message=actual,actual=void 0;else{if(warned===!1){warned=!0;var warn=process.emitWarning\?process.emitWarning:console.warn.bind(console);warn(\"assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.\",\"DeprecationWarning\",\"DEP0094\")}argsLen===2&&(operator=\"!=\")}if(message instanceof Error)throw message;var errArgs={actual,expected,operator:operator===void 0\?\"fail\":operator,stackStartFn:stackStartFn||fail};message!==void 0&&(errArgs.message=message);var err=new AssertionError(errArgs);throw internalMessage&&(err.message=internalMessage,err.generatedMessage=!0),err}assert.fail=fail,assert.AssertionError=AssertionError;function innerOk(fn,argLen,value,message){if(!value){var generatedMessage=!1;if(argLen===0)generatedMessage=!0,message=\"No value argument passed to `assert.ok()`\";else if(message instanceof Error)throw message;var err=new AssertionError({actual:value,expected:!0,message,operator:\"==\",stackStartFn:fn});throw err.generatedMessage=generatedMessage,err}}function ok(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];innerOk.apply(void 0,[ok,args.length].concat(args))}assert.ok=ok,assert.equal=function equal(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");actual!=expected&&innerFail({actual,expected,message,operator:\"==\",stackStartFn:equal})},assert.notEqual=function notEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");actual==expected&&innerFail({actual,expected,message,operator:\"!=\",stackStartFn:notEqual})},assert.deepEqual=function deepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!1)||innerFail({actual,expected,message,operator:\"deepEqual\",stackStartFn:deepEqual})},assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!1)&&innerFail({actual,expected,message,operator:\"notDeepEqual\",stackStartFn:notDeepEqual})},assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!0)||innerFail({actual,expected,message,operator:\"deepStrictEqual\",stackStartFn:deepStrictEqual})},assert.notDeepStrictEqual=notDeepStrictEqual;function notDeepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!0)&&innerFail({actual,expected,message,operator:\"notDeepStrictEqual\",stackStartFn:notDeepStrictEqual})}assert.strictEqual=function strictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");objectIs(actual,expected)||innerFail({actual,expected,message,operator:\"strictEqual\",stackStartFn:strictEqual})},assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");objectIs(actual,expected)&&innerFail({actual,expected,message,operator:\"notStrictEqual\",stackStartFn:notStrictEqual})},assert.match=function match(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");if(!isRegExp(expected))throw new ERR_INVALID_ARG_TYPE(\"expected\",\"RegExp\",expected);expected.test(actual)||innerFail({actual,expected,message,operator:\"match\",stackStartFn:match})};var Comparison=function Comparison2(obj,keys,actual){var _this=this;_classCallCheck(this,Comparison2),keys.forEach(function(key){(key in obj)&&(actual!==void 0&&typeof actual[key]==\"string\"&&isRegExp(obj[key])&&obj[key].test(actual[key])\?_this[key]=actual[key]:_this[key]=obj[key])})};function compareExceptionKey(actual,expected,key,message,keys,fn){if(!(key in actual)||!isDeepEqual(actual[key],expected[key],!0)){if(!message){var a=new Comparison(actual,keys),b=new Comparison(expected,keys,actual),err=new AssertionError({actual:a,expected:b,operator:\"deepStrictEqual\",stackStartFn:fn});throw err.actual=actual,err.expected=expected,err.operator=fn.name,err}innerFail({actual,expected,message,operator:fn.name,stackStartFn:fn})}}function expectedException(actual,expected,msg,fn){if(typeof expected!=\"function\"){if(isRegExp(expected))return expected.test(actual);if(arguments.length===2)throw new ERR_INVALID_ARG_TYPE(\"expected\",[\"Function\",\"RegExp\"],expected);if(_typeof(actual)!==\"object\"||actual===null){var err=new AssertionError({actual,expected,message:msg,operator:\"deepStrictEqual\",stackStartFn:fn});throw err.operator=fn.name,err}var keys=Object.keys(expected);if(expected instanceof Error)keys.push(\"name\",\"message\");else if(keys.length===0)throw new ERR_INVALID_ARG_VALUE(\"error\",expected,\"may not be an empty object\");return keys.forEach(function(key){return typeof actual[key]==\"string\"&&isRegExp(expected[key])&&expected[key].test(actual[key])||compareExceptionKey(actual,expected,key,msg,keys,fn)}),!0}return expected.prototype!==void 0&&actual instanceof expected\?!0:Error.isPrototypeOf(expected)\?!1:expected.call({},actual)===!0}function getActual(fn){if(typeof fn!=\"function\")throw new ERR_INVALID_ARG_TYPE(\"fn\",\"Function\",fn);try{fn()}catch(e){return e}return NO_EXCEPTION_SENTINEL}function checkIsPromise(obj){return isPromise(obj)||obj!==null&&_typeof(obj)===\"object\"&&typeof obj.then==\"function\"&&typeof obj.catch==\"function\"}function waitForActual(promiseFn){return Promise.resolve().then(function(){var resultPromise;if(typeof promiseFn==\"function\"){if(resultPromise=promiseFn(),!checkIsPromise(resultPromise))throw new ERR_INVALID_RETURN_VALUE(\"instance of Promise\",\"promiseFn\",resultPromise)}else if(checkIsPromise(promiseFn))resultPromise=promiseFn;else throw new ERR_INVALID_ARG_TYPE(\"promiseFn\",[\"Function\",\"Promise\"],promiseFn);return Promise.resolve().then(function(){return resultPromise}).then(function(){return NO_EXCEPTION_SENTINEL}).catch(function(e){return e})})}function expectsError(stackStartFn,actual,error,message){if(typeof error==\"string\"){if(arguments.length===4)throw new ERR_INVALID_ARG_TYPE(\"error\",[\"Object\",\"Error\",\"Function\",\"RegExp\"],error);if(_typeof(actual)===\"object\"&&actual!==null){if(actual.message===error)throw new ERR_AMBIGUOUS_ARGUMENT(\"error/message\",'The error message \"'.concat(actual.message,'\" is identical to the message.'))}else if(actual===error)throw new ERR_AMBIGUOUS_ARGUMENT(\"error/message\",'The error \"'.concat(actual,'\" is identical to the message.'));message=error,error=void 0}else if(error!=null&&_typeof(error)!==\"object\"&&typeof error!=\"function\")throw new ERR_INVALID_ARG_TYPE(\"error\",[\"Object\",\"Error\",\"Function\",\"RegExp\"],error);if(actual===NO_EXCEPTION_SENTINEL){var details=\"\";error&&error.name&&(details+=\" (\".concat(error.name,\")\")),details+=message\?\": \".concat(message):\".\";var fnType=stackStartFn.name===\"rejects\"\?\"rejection\":\"exception\";innerFail({actual:void 0,expected:error,operator:stackStartFn.name,message:\"Missing expected \".concat(fnType).concat(details),stackStartFn})}if(error&&!expectedException(actual,error,message,stackStartFn))throw actual}function expectsNoError(stackStartFn,actual,error,message){if(actual!==NO_EXCEPTION_SENTINEL){if(typeof error==\"string\"&&(message=error,error=void 0),!error||expectedException(actual,error)){var details=message\?\": \".concat(message):\".\",fnType=stackStartFn.name===\"doesNotReject\"\?\"rejection\":\"exception\";innerFail({actual,expected:error,operator:stackStartFn.name,message:\"Got unwanted \".concat(fnType).concat(details,`\n`)+'Actual message: \"'.concat(actual&&actual.message,'\"'),stackStartFn})}throw actual}}assert.throws=function throws(promiseFn){for(var _len2=arguments.length,args=new Array(_len2>1\?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];expectsError.apply(void 0,[throws,getActual(promiseFn)].concat(args))},assert.rejects=function rejects(promiseFn){for(var _len3=arguments.length,args=new Array(_len3>1\?_len3-1:0),_key3=1;_key3<_len3;_key3++)args[_key3-1]=arguments[_key3];return waitForActual(promiseFn).then(function(result){return expectsError.apply(void 0,[rejects,result].concat(args))})},assert.doesNotThrow=function doesNotThrow(fn){for(var _len4=arguments.length,args=new Array(_len4>1\?_len4-1:0),_key4=1;_key4<_len4;_key4++)args[_key4-1]=arguments[_key4];expectsNoError.apply(void 0,[doesNotThrow,getActual(fn)].concat(args))},assert.doesNotReject=function doesNotReject(fn){for(var _len5=arguments.length,args=new Array(_len5>1\?_len5-1:0),_key5=1;_key5<_len5;_key5++)args[_key5-1]=arguments[_key5];return waitForActual(fn).then(function(result){return expectsNoError.apply(void 0,[doesNotReject,result].concat(args))})},assert.ifError=function ifError(err){if(err!=null){var message=\"ifError got unwanted exception: \";_typeof(err)===\"object\"&&typeof err.message==\"string\"\?err.message.length===0&&err.constructor\?message+=err.constructor.name:message+=err.message:message+=inspect(err);var newErr=new AssertionError({actual:err,expected:null,operator:\"ifError\",message,stackStartFn:ifError}),origStack=err.stack;if(typeof origStack==\"string\"){var tmp2=origStack.split(`\n`);tmp2.shift();for(var tmp1=newErr.stack.split(`\n`),i=0;i{var prev=get();set(context);try{return fn(...args)}catch(error){throw error}finally{set(prev)}}}enterWith(store){cleanupLater();var context=get();if(!context){set([this,store]);return}var{length}=context;for(var i=0;i-1)hasPrevious=!0,previous=context[i+1],context[i+1]=store;else context.push(this,store);set(context)}try{return callback(...args)}catch(e){throw e}finally{if(!this.#disableCalled){var context2=get();if(context2===context&&contextWasInit)set(void 0);else if(context2=context2.slice(),hasPrevious)context2[i+1]=previous,set(context2);else context2.splice(i,2),set(context2.length\?context2:void 0)}}}disable(){if(!this.#disableCalled){var context=get();if(context){var{length}=context;for(var i=0;i-1){try{child.kill(killSignal)}catch(err){child.emit(\"error\",err)}timeoutHolder.timeoutId=-1}}function spawn(file,args,options){options=normalizeSpawnArguments(file,args,options),validateTimeout(options.timeout),validateAbortSignal(options.signal,\"options.signal\");const killSignal2=sanitizeKillSignal(options.killSignal),child=new ChildProcess;if(child.spawn(options),options.timeout>0){let timeoutId=setTimeout(()=>{if(timeoutId){try{child.kill(killSignal2)}catch(err){child.emit(\"error\",err)}timeoutId=null}});child.once(\"exit\",()=>{if(timeoutId)clearTimeout(timeoutId),timeoutId=null})}if(options.signal){let onAbortListener2=function(){abortChildProcess(child,killSignal2,options.signal.reason)};var onAbortListener=onAbortListener2;const signal=options.signal;if(signal.aborted)process.nextTick(onAbortListener2);else signal.addEventListener(\"abort\",onAbortListener2,{once:!0}),child.once(\"exit\",()=>signal.removeEventListener(\"abort\",onAbortListener2))}return child}function execFile(file,args,options,callback){({file,args,options,callback}=normalizeExecFileArgs(file,args,options,callback)),options={encoding:\"utf8\",timeout:0,maxBuffer:MAX_BUFFER,killSignal:\"SIGTERM\",cwd:null,env:null,shell:!1,...options};const maxBuffer=options.maxBuffer;validateTimeout(options.timeout),validateMaxBuffer(maxBuffer),options.killSignal=sanitizeKillSignal(options.killSignal);const child=spawn(file,args,{cwd:options.cwd,env:options.env,shell:options.shell,signal:options.signal});let encoding;const _stdout=[],_stderr=[];if(options.encoding!==\"buffer\"&&BufferIsEncoding(options.encoding))encoding=options.encoding;else encoding=null;let stdoutLen=0,stderrLen=0,killed=!1,exited=!1,timeoutId,encodedStdoutLen,encodedStderrLen,ex=null,cmd=file;function exitHandler(code,signal){if(exited)return;if(exited=!0,timeoutId)clearTimeout(timeoutId),timeoutId=null;if(!callback)return;const readableEncoding=child\?.stdout\?.readableEncoding;let stdout,stderr;if(encoding||child.stdout&&readableEncoding)stdout=ArrayPrototypeJoin.call(_stdout,\"\");else stdout=BufferConcat(_stdout);if(encoding||child.stderr&&readableEncoding)stderr=ArrayPrototypeJoin.call(_stderr,\"\");else stderr=BufferConcat(_stderr);if(!ex&&code===0&&signal===null){callback(null,stdout,stderr);return}if(args\?.length)cmd+=` ${ArrayPrototypeJoin.call(args,\" \")}`;if(!ex){let message=`Command failed: ${cmd}`;if(stderr)message+=`\\n${stderr}`;ex=genericNodeError(message,{code,killed:child.killed||killed,signal})}ex.cmd=cmd,callback(ex,stdout,stderr)}function errorHandler(e){if(ex=e,child.stdout)child.stdout.destroy();if(child.stderr)child.stderr.destroy();exitHandler()}function kill(){if(child.stdout)child.stdout.destroy();if(child.stderr)child.stderr.destroy();killed=!0;try{child.kill(options.killSignal)}catch(e){ex=e,exitHandler()}}if(options.timeout>0)timeoutId=setTimeout(function delayedKill(){kill(),timeoutId=null},options.timeout);if(child.stdout){if(encoding)child.stdout.setEncoding(encoding);child.stdout.on(\"data\",maxBuffer===Infinity\?function onUnlimitedSizeBufferedData(chunk){ArrayPrototypePush.call(_stdout,chunk)}:encoding\?function onChildStdoutEncoded(chunk){if(stdoutLen+=chunk.length,stdoutLen*4>maxBuffer){const encoding2=child.stdout.readableEncoding,actualLen=Buffer.byteLength(chunk,encoding2);if(encodedStdoutLen===void 0)for(let i=0;i<_stdout.length;i++)encodedStdoutLen+=Buffer.byteLength(_stdout[i],encoding2);else encodedStdoutLen+=actualLen;const truncatedLen=maxBuffer-(encodedStdoutLen-actualLen);ArrayPrototypePush.call(_stdout,StringPrototypeSlice.apply(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stdout\"),kill()}else ArrayPrototypePush.call(_stdout,chunk)}:function onChildStdoutRaw(chunk){if(stdoutLen+=chunk.length,stdoutLen>maxBuffer){const truncatedLen=maxBuffer-(stdoutLen-chunk.length);ArrayPrototypePush.call(_stdout,chunk.slice(0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stdout\"),kill()}else ArrayPrototypePush.call(_stdout,chunk)})}if(child.stderr){if(encoding)child.stderr.setEncoding(encoding);child.stderr.on(\"data\",maxBuffer===Infinity\?function onUnlimitedSizeBufferedData(chunk){ArrayPrototypePush.call(_stderr,chunk)}:encoding\?function onChildStderrEncoded(chunk){if(stderrLen+=chunk.length,stderrLen*4>maxBuffer){const encoding2=child.stderr.readableEncoding,actualLen=Buffer.byteLength(chunk,encoding2);if(encodedStderrLen===void 0)for(let i=0;i<_stderr.length;i++)encodedStderrLen+=Buffer.byteLength(_stderr[i],encoding2);else encodedStderrLen+=actualLen;const truncatedLen=maxBuffer-(encodedStderrLen-actualLen);ArrayPrototypePush.call(_stderr,StringPrototypeSlice.call(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stderr\"),kill()}else ArrayPrototypePush.call(_stderr,chunk)}:function onChildStderrRaw(chunk){if(stderrLen+=chunk.length,stderrLen>maxBuffer){const truncatedLen=maxBuffer-(stderrLen-chunk.length);ArrayPrototypePush.call(_stderr,StringPrototypeSlice.call(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stderr\"),kill()}else ArrayPrototypePush.call(_stderr,chunk)})}return child.addListener(\"close\",exitHandler),child.addListener(\"error\",errorHandler),child}function exec(command,options,callback){const opts=normalizeExecArgs(command,options,callback);return execFile(opts.file,opts.options,opts.callback)}const customPromiseExecFunction=(orig)=>{return(...args)=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res,reject=rej});return promise.child=orig(...args,(err,stdout,stderr)=>{if(err!==null)err.stdout=stdout,err.stderr=stderr,reject(err);else resolve({stdout,stderr})}),promise}};ObjectDefineProperty(exec,promisify.custom,{__proto__:null,enumerable:!1,value:customPromiseExecFunction(exec)});function spawnSync(file,args,options){options={maxBuffer:MAX_BUFFER,...normalizeSpawnArguments(file,args,options)};const{maxBuffer,encoding}=options;validateTimeout(options.timeout),validateMaxBuffer(maxBuffer),options.killSignal=sanitizeKillSignal(options.killSignal);const stdio=options.stdio||\"pipe\",bunStdio=getBunStdioFromOptions(stdio);var{input}=options;if(input)if(ArrayBufferIsView(input))bunStdio[0]=input;else if(typeof input===\"string\")bunStdio[0]=Buffer.from(input,encoding||\"utf8\");else throw new ERR_INVALID_ARG_TYPE(\"options.stdio[0]\",[\"Buffer\",\"TypedArray\",\"DataView\",\"string\"],input);const{stdout,stderr,success,exitCode}=Bun.spawnSync({cmd:options.args,env:options.env||void 0,cwd:options.cwd||void 0,stdin:bunStdio[0],stdout:bunStdio[1],stderr:bunStdio[2]}),result={signal:null,status:exitCode,output:[null,stdout,stderr]};if(stdout&&encoding&&encoding!==\"buffer\")result.output[1]=result.output[1]\?.toString(encoding);if(stderr&&encoding&&encoding!==\"buffer\")result.output[2]=result.output[2]\?.toString(encoding);if(result.stdout=result.output[1],result.stderr=result.output[2],!success)result.error=new SystemError(result.output[2],options.file,\"spawnSync\",-1,result.status),result.error.spawnargs=ArrayPrototypeSlice.call(options.args,1);return result}function execFileSync(file,args,options){({file,args,options}=normalizeExecFileArgs(file,args,options));const ret=spawnSync(file,args,options),errArgs=[options.argv0||file];ArrayPrototypePush.apply(errArgs,args);const err=checkExecSyncError(ret,errArgs);if(err)throw err;return ret.stdout}function execSync(command,options){const opts=normalizeExecArgs(command,options,null),ret=spawnSync(opts.file,opts.options),err=checkExecSyncError(ret,void 0,command);if(err)throw err;return ret.stdout}function stdioStringToArray(stdio,channel){const options=[];switch(stdio){case\"ignore\":case\"overlapped\":case\"pipe\":ArrayPrototypePush.call(options,stdio,stdio,stdio);break;case\"inherit\":ArrayPrototypePush.call(options,0,1,2);break;default:throw new ERR_INVALID_ARG_VALUE(\"stdio\",stdio)}if(channel)ArrayPrototypePush.call(options,channel);return options}function fork(modulePath,args=[],options){modulePath=getValidatedPath(modulePath,\"modulePath\");let execArgv;if(args==null)args=[];else if(typeof args===\"object\"&&!ArrayIsArray(args))options=args,args=[];else validateArray(args,\"args\");if(options!=null)validateObject(options,\"options\");if(options={__proto__:null,...options,shell:!1},options.execPath=options.execPath||process.execPath,validateArgumentNullCheck(options.execPath,\"options.execPath\"),execArgv=options.execArgv||process.execArgv,validateArgumentsNullCheck(execArgv,\"options.execArgv\"),execArgv===process.execArgv&&process._eval!=null){const index=ArrayPrototypeLastIndexOf.call(execArgv,process._eval);if(index>0)execArgv=ArrayPrototypeSlice.call(execArgv),ArrayPrototypeSplice.call(execArgv,index-1,2)}if(args=[...execArgv,modulePath,...args],typeof options.stdio===\"string\")options.stdio=stdioStringToArray(options.stdio,\"ipc\");else if(!ArrayIsArray(options.stdio))options.stdio=stdioStringToArray(options.silent\?\"pipe\":\"inherit\",\"ipc\");else if(!ArrayPrototypeIncludes.call(options.stdio,\"ipc\"))throw new ERR_CHILD_PROCESS_IPC_REQUIRED(\"options.stdio\");return spawn(options.execPath,args,options)}function convertToValidSignal(signal){if(typeof signal===\"number\"&&getSignalsToNamesMapping()[signal])return signal;if(typeof signal===\"string\"){const signalName=signals[StringPrototypeToUpperCase.call(signal)];if(signalName)return signalName}throw new ERR_UNKNOWN_SIGNAL(signal)}function sanitizeKillSignal(killSignal2){if(typeof killSignal2===\"string\"||typeof killSignal2===\"number\")return convertToValidSignal(killSignal2);else if(killSignal2!=null)throw new ERR_INVALID_ARG_TYPE(\"options.killSignal\",[\"string\",\"number\"],killSignal2)}let signalsToNamesMapping;function getSignalsToNamesMapping(){if(signalsToNamesMapping!==void 0)return signalsToNamesMapping;signalsToNamesMapping=ObjectCreate(null);for(let key in signals)signalsToNamesMapping[signals[key]]=key;return signalsToNamesMapping}function normalizeExecFileArgs(file,args,options,callback){if(ArrayIsArray(args))args=ArrayPrototypeSlice.call(args);else if(args!=null&&typeof args===\"object\")callback=options,options=args,args=null;else if(typeof args===\"function\")callback=args,options=null,args=null;if(args==null)args=[];if(typeof options===\"function\")callback=options;else if(options!=null)validateObject(options,\"options\");if(options==null)options=kEmptyObject;if(callback!=null)validateFunction(callback,\"callback\");if(options.argv0!=null)validateString(options.argv0,\"options.argv0\"),validateArgumentNullCheck(options.argv0,\"options.argv0\");return{file,args,options,callback}}function normalizeExecArgs(command,options,callback){if(validateString(command,\"command\"),validateArgumentNullCheck(command,\"command\"),typeof options===\"function\")callback=options,options=void 0;return options={...options},options.shell=typeof options.shell===\"string\"\?options.shell:!0,{file:command,options,callback}}function normalizeSpawnArguments(file,args,options){if(validateString(file,\"file\"),validateArgumentNullCheck(file,\"file\"),file.length===0)throw new ERR_INVALID_ARG_VALUE(\"file\",file,\"cannot be empty\");if(ArrayIsArray(args))args=ArrayPrototypeSlice.call(args);else if(args==null)args=[];else if(typeof args!==\"object\")throw new ERR_INVALID_ARG_TYPE(\"args\",\"object\",args);else options=args,args=[];if(validateArgumentsNullCheck(args,\"args\"),options===void 0)options={};else validateObject(options,\"options\");let cwd=options.cwd;if(cwd!=null)cwd=getValidatedPath(cwd,\"options.cwd\");if(options.shell!=null&&typeof options.shell!==\"boolean\"&&typeof options.shell!==\"string\")throw new ERR_INVALID_ARG_TYPE(\"options.shell\",[\"boolean\",\"string\"],options.shell);if(options.argv0!=null)validateString(options.argv0,\"options.argv0\"),validateArgumentNullCheck(options.argv0,\"options.argv0\");if(options.shell){validateArgumentNullCheck(options.shell,\"options.shell\");const command=ArrayPrototypeJoin.call([file,...args],\" \");if(typeof options.shell===\"string\")file=options.shell;else file=\"sh\";args=[\"-c\",command]}if(typeof options.argv0===\"string\")ArrayPrototypeUnshift.call(args,options.argv0);else ArrayPrototypeUnshift.call(args,file);const envPairs=options.env||process.env;return{...options,file,args,cwd,envPairs}}function checkExecSyncError(ret,args,cmd){let err;if(ret.error)err=ret.error,ObjectAssign(err,ret);else if(ret.status!==0){let msg=\"Command failed: \";if(msg+=cmd||ArrayPrototypeJoin.call(args,\" \"),ret.stderr&&ret.stderr.length>0)msg+=`\\n${ret.stderr.toString()}`;err=genericNodeError(msg,ret)}return err}class ChildProcess extends EventEmitter{constructor(){super(...arguments)}#handle;#exited=!1;#closesNeeded=1;#closesGot=0;connected=!1;signalCode=null;exitCode=null;spawnfile;spawnargs;pid;channel;get killed(){if(this.#handle==null)return!1}#handleOnExit(exitCode,signalCode,err){if(this.#exited)return;if(signalCode)this.signalCode=signalCode;else this.exitCode=exitCode;if(this.#stdin)this.#stdin.destroy();if(this.#handle)this.#handle=null;if(exitCode<0){const err2=new SystemError(`Spawned process exited with error code: ${exitCode}`,void 0,\"spawn\",\"EUNKNOWN\",\"ERR_CHILD_PROCESS_UNKNOWN_ERROR\");if(this.spawnfile)err2.path=this.spawnfile;err2.spawnargs=ArrayPrototypeSlice.call(this.spawnargs,1),this.emit(\"error\",err2)}else this.emit(\"exit\",this.exitCode,this.signalCode);process.nextTick(flushStdio,this),this.#maybeClose(),this.#exited=!0,this.#stdioOptions=[\"destroyed\",\"destroyed\",\"destroyed\"]}#getBunSpawnIo(i,encoding){NativeWritable||=StreamModule.NativeWritable,ReadableFromWeb||=StreamModule.Readable.fromWeb;const io=this.#stdioOptions[i];switch(i){case 0:switch(io){case\"pipe\":return new NativeWritable(this.#handle.stdin);case\"inherit\":return process.stdin||null;case\"destroyed\":return new ShimmedStdin;default:return null}case 2:case 1:switch(io){case\"pipe\":return ReadableFromWeb(this.#handle[fdToStdioName(i)],{encoding});case\"inherit\":return process[fdToStdioName(i)]||null;case\"destroyed\":return new ShimmedStdioOutStream;default:return null}}}#stdin;#stdout;#stderr;#stdioObject;#encoding;#stdioOptions;#createStdioObject(){return Object.create(null,{0:{get:()=>this.stdin},1:{get:()=>this.stdout},2:{get:()=>this.stderr}})}get stdin(){return this.#stdin\?\?=this.#getBunSpawnIo(0,this.#encoding)}get stdout(){return this.#stdout\?\?=this.#getBunSpawnIo(1,this.#encoding)}get stderr(){return this.#stderr\?\?=this.#getBunSpawnIo(2,this.#encoding)}get stdio(){return this.#stdioObject\?\?=this.#createStdioObject()}spawn(options){validateObject(options,\"options\"),validateString(options.file,\"options.file\");var file=this.spawnfile=options.file,spawnargs;if(options.args==null)spawnargs=this.spawnargs=[];else validateArray(options.args,\"options.args\"),spawnargs=this.spawnargs=options.args;const stdio=options.stdio||[\"pipe\",\"pipe\",\"pipe\"],bunStdio=getBunStdioFromOptions(stdio);var env=options.envPairs||void 0;this.#encoding=options.encoding||void 0,this.#stdioOptions=bunStdio,this.#handle=Bun.spawn({cmd:spawnargs,stdin:bunStdio[0],stdout:bunStdio[1],stderr:bunStdio[2],cwd:options.cwd||void 0,env:env||process.env,onExit:(handle,exitCode,signalCode,err)=>{this.#handle=handle,this.pid=this.#handle.pid,process.nextTick((exitCode2,signalCode2,err2)=>this.#handleOnExit(exitCode2,signalCode2,err2),exitCode,signalCode,err)},lazy:!0}),this.pid=this.#handle.pid,onSpawnNT(this)}send(){console.log(\"ChildProcess.prototype.send() - Sorry! Not implemented yet\")}disconnect(){console.log(\"ChildProcess.prototype.disconnect() - Sorry! Not implemented yet\")}kill(sig){const signal=sig===0\?sig:convertToValidSignal(sig===void 0\?\"SIGTERM\":sig);if(this.#handle)this.#handle.kill(signal);return this.#maybeClose(),!0}#maybeClose(){if(this.#closesGot++,this.#closesGot===this.#closesNeeded)this.emit(\"close\",this.exitCode,this.signalCode)}ref(){if(this.#handle)this.#handle.ref()}unref(){if(this.#handle)this.#handle.unref()}}const nodeToBunLookup={ignore:null,pipe:\"pipe\",overlapped:\"pipe\",inherit:\"inherit\"};function nodeToBun(item){if(typeof item===\"number\")return item;else{const result=nodeToBunLookup[item];if(result===void 0)throw new Error(\"Invalid stdio option\");return result}}function fdToStdioName(fd){switch(fd){case 0:return\"stdin\";case 1:return\"stdout\";case 2:return\"stderr\";default:return null}}function getBunStdioFromOptions(stdio){return normalizeStdio(stdio).map((item)=>nodeToBun(item))}function normalizeStdio(stdio){if(typeof stdio===\"string\")switch(stdio){case\"ignore\":return[\"ignore\",\"ignore\",\"ignore\"];case\"pipe\":return[\"pipe\",\"pipe\",\"pipe\"];case\"inherit\":return[\"inherit\",\"inherit\",\"inherit\"];default:throw new ERR_INVALID_OPT_VALUE(\"stdio\",stdio)}else if(ArrayIsArray(stdio)){let processedStdio;if(stdio.length===0)processedStdio=[\"pipe\",\"pipe\",\"pipe\"];else if(stdio.length===1)processedStdio=[stdio[0],\"pipe\",\"pipe\"];else if(stdio.length===2)processedStdio=[stdio[0],stdio[1],\"pipe\"];else if(stdio.length>=3)processedStdio=[stdio[0],stdio[1],stdio[2]];return processedStdio.map((item)=>!item\?\"pipe\":item)}else throw new ERR_INVALID_OPT_VALUE(\"stdio\",stdio)}function flushStdio(subprocess){const stdio=subprocess.stdio;if(stdio==null)return;for(let i=0;i=0))throw new ERR_OUT_OF_RANGE(\"options.maxBuffer\",\"a positive number\",maxBuffer)}function validateArgumentNullCheck(arg,propName){if(typeof arg===\"string\"&&StringPrototypeIncludes.call(arg,\"\\0\"))throw new ERR_INVALID_ARG_VALUE(propName,arg,\"must be a string without null bytes\")}function validateArgumentsNullCheck(args,propName){for(let i=0;i=0))throw new ERR_OUT_OF_RANGE(\"timeout\",\"an unsigned integer\",timeout)}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}function validateFunction(value,name){if(typeof value!==\"function\")throw new ERR_INVALID_ARG_TYPE(name,\"Function\",value)}const validateAbortSignal=(signal,name)=>{if(signal!==void 0&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE(name,\"AbortSignal\",signal)},validateOneOf=(value,name,oneOf)=>{if(!ArrayPrototypeIncludes.call(oneOf,value)){const reason=\"must be one of: \"+ArrayPrototypeJoin.call(ArrayPrototypeMap.call(oneOf,(v)=>typeof v===\"string\"\?`'${v}'`:String(v)),\", \");throw new ERR_INVALID_ARG_VALUE(name,value,reason)}},validateObject=(value,name,options=null)=>{const allowArray=options\?.allowArray\?\?!1,allowFunction=options\?.allowFunction\?\?!1;if(!(options\?.nullable\?\?!1)&&value===null||!allowArray&&ArrayIsArray.call(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE(name,\"object\",value)},validateArray=(value,name,minLength=0)=>{if(!ArrayIsArray(value))throw new ERR_INVALID_ARG_TYPE(name,\"Array\",value);if(value.lengthfunction(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},require_safe_buffer=__commonJS({\"node_modules/safe-buffer/index.js\"(exports,module){var buffer=BufferModule,Buffer2=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}Buffer2.from&&Buffer2.alloc&&Buffer2.allocUnsafe&&Buffer2.allocUnsafeSlow\?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer);function SafeBuffer(arg,encodingOrOffset,length){return Buffer2(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer2.prototype),copyProps(Buffer2,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==\"number\")@throwTypeError(\"Argument must not be a number\");return Buffer2(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");var buf=Buffer2(size);return fill!==void 0\?typeof encoding==\"string\"\?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");return Buffer2(size)},SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");return buffer.SlowBuffer(size)}}}),require_browser=__commonJS({\"node_modules/randombytes/browser.js\"(exports,module){var MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser(){throw new Error(`Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11`)}var Buffer2=require_safe_buffer().Buffer,crypto2=globalCrypto;crypto2&&crypto2.getRandomValues\?module.exports=randomBytes:module.exports=oldBrowser;function randomBytes(size,cb){if(size>MAX_UINT32)@throwRangeError(\"requested too many random bytes\");var bytes=Buffer2.allocUnsafe(size);if(size>0)if(size>MAX_BYTES)for(var generated=0;generated=this._blockSize;){for(var i=this._blockOffset;i0;++j)this._length[j]+=carry,carry=this._length[j]/4294967296|0,carry>0&&(this._length[j]-=4294967296*carry);return this},HashBase.prototype._update=function(){throw new Error(\"_update is not implemented\")},HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error(\"Digest already called\");this._finalized=!0;var digest=this._digest();encoding!==void 0&&(digest=digest.toString(encoding)),this._block.fill(0),this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return digest},HashBase.prototype._digest=function(){throw new Error(\"_digest is not implemented\")},module.exports=HashBase}}),require_md5=__commonJS({\"node_modules/md5.js/index.js\"(exports,module){var inherits=require_inherits_browser(),HashBase=require_hash_base(),Buffer2=require_safe_buffer().Buffer,ARRAY16=new Array(16);function MD5(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}inherits(MD5,HashBase),MD5.prototype._update=function(){for(var M=ARRAY16,i=0;i<16;++i)M[i]=this._block.readInt32LE(i*4);var a=this._a,b=this._b,c=this._c,d=this._d;a=fnF(a,b,c,d,M[0],3614090360,7),d=fnF(d,a,b,c,M[1],3905402710,12),c=fnF(c,d,a,b,M[2],606105819,17),b=fnF(b,c,d,a,M[3],3250441966,22),a=fnF(a,b,c,d,M[4],4118548399,7),d=fnF(d,a,b,c,M[5],1200080426,12),c=fnF(c,d,a,b,M[6],2821735955,17),b=fnF(b,c,d,a,M[7],4249261313,22),a=fnF(a,b,c,d,M[8],1770035416,7),d=fnF(d,a,b,c,M[9],2336552879,12),c=fnF(c,d,a,b,M[10],4294925233,17),b=fnF(b,c,d,a,M[11],2304563134,22),a=fnF(a,b,c,d,M[12],1804603682,7),d=fnF(d,a,b,c,M[13],4254626195,12),c=fnF(c,d,a,b,M[14],2792965006,17),b=fnF(b,c,d,a,M[15],1236535329,22),a=fnG(a,b,c,d,M[1],4129170786,5),d=fnG(d,a,b,c,M[6],3225465664,9),c=fnG(c,d,a,b,M[11],643717713,14),b=fnG(b,c,d,a,M[0],3921069994,20),a=fnG(a,b,c,d,M[5],3593408605,5),d=fnG(d,a,b,c,M[10],38016083,9),c=fnG(c,d,a,b,M[15],3634488961,14),b=fnG(b,c,d,a,M[4],3889429448,20),a=fnG(a,b,c,d,M[9],568446438,5),d=fnG(d,a,b,c,M[14],3275163606,9),c=fnG(c,d,a,b,M[3],4107603335,14),b=fnG(b,c,d,a,M[8],1163531501,20),a=fnG(a,b,c,d,M[13],2850285829,5),d=fnG(d,a,b,c,M[2],4243563512,9),c=fnG(c,d,a,b,M[7],1735328473,14),b=fnG(b,c,d,a,M[12],2368359562,20),a=fnH(a,b,c,d,M[5],4294588738,4),d=fnH(d,a,b,c,M[8],2272392833,11),c=fnH(c,d,a,b,M[11],1839030562,16),b=fnH(b,c,d,a,M[14],4259657740,23),a=fnH(a,b,c,d,M[1],2763975236,4),d=fnH(d,a,b,c,M[4],1272893353,11),c=fnH(c,d,a,b,M[7],4139469664,16),b=fnH(b,c,d,a,M[10],3200236656,23),a=fnH(a,b,c,d,M[13],681279174,4),d=fnH(d,a,b,c,M[0],3936430074,11),c=fnH(c,d,a,b,M[3],3572445317,16),b=fnH(b,c,d,a,M[6],76029189,23),a=fnH(a,b,c,d,M[9],3654602809,4),d=fnH(d,a,b,c,M[12],3873151461,11),c=fnH(c,d,a,b,M[15],530742520,16),b=fnH(b,c,d,a,M[2],3299628645,23),a=fnI(a,b,c,d,M[0],4096336452,6),d=fnI(d,a,b,c,M[7],1126891415,10),c=fnI(c,d,a,b,M[14],2878612391,15),b=fnI(b,c,d,a,M[5],4237533241,21),a=fnI(a,b,c,d,M[12],1700485571,6),d=fnI(d,a,b,c,M[3],2399980690,10),c=fnI(c,d,a,b,M[10],4293915773,15),b=fnI(b,c,d,a,M[1],2240044497,21),a=fnI(a,b,c,d,M[8],1873313359,6),d=fnI(d,a,b,c,M[15],4264355552,10),c=fnI(c,d,a,b,M[6],2734768916,15),b=fnI(b,c,d,a,M[13],1309151649,21),a=fnI(a,b,c,d,M[4],4149444226,6),d=fnI(d,a,b,c,M[11],3174756917,10),c=fnI(c,d,a,b,M[2],718787259,15),b=fnI(b,c,d,a,M[9],3951481745,21),this._a=this._a+a|0,this._b=this._b+b|0,this._c=this._c+c|0,this._d=this._d+d|0},MD5.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer2.allocUnsafe(16);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer};function rotl(x,n){return x<>>32-n}function fnF(a,b,c,d,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+b|0}function fnG(a,b,c,d,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+b|0}function fnH(a,b,c,d,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+b|0}function fnI(a,b,c,d,m,k,s){return rotl(a+(c^(b|~d))+m+k|0,s)+b|0}module.exports=MD5}}),require_ripemd160=__commonJS({\"node_modules/ripemd160/index.js\"(exports,module){var Buffer2=Buffer,inherits=require_inherits_browser(),HashBase=require_hash_base(),ARRAY16=new Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;j<16;++j)words[j]=this._block.readInt32LE(j*4);for(var al=this._a|0,bl=this._b|0,cl=this._c|0,dl=this._d|0,el=this._e|0,ar=this._a|0,br=this._b|0,cr=this._c|0,dr=this._d|0,er=this._e|0,i=0;i<80;i+=1){var tl,tr;i<16\?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):i<32\?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):i<48\?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):i<64\?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=this._b+cl+dr|0;this._b=this._c+dl+er|0,this._c=this._d+el+ar|0,this._d=this._e+al+br|0,this._e=this._a+bl+cr|0,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer2.alloc\?Buffer2.alloc(20):new Buffer2(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer};function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+e|0}function fn2(a,b,c,d,e,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+e|0}function fn3(a,b,c,d,e,m,k,s){return rotl(a+((b|~c)^d)+m+k|0,s)+e|0}function fn4(a,b,c,d,e,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+e|0}function fn5(a,b,c,d,e,m,k,s){return rotl(a+(b^(c|~d))+m+k|0,s)+e|0}module.exports=RIPEMD160}}),require_hash=__commonJS({\"node_modules/sha.js/hash.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer;function Hash(blockSize,finalSize){this._block=Buffer2.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}Hash.prototype={},Hash.prototype.update=function(data,enc){typeof data==\"string\"&&(enc=enc||\"utf8\",data=Buffer2.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=this._len*8;if(bits<=4294967295)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(bits&4294967295)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc\?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error(\"_update must be implemented by subclass\")},module.exports=Hash}}),require_sha=__commonJS({\"node_modules/sha.js/sha.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return s===0\?b&c|~b&d:s===2\?b&c|b&d|c&d:b^c^d}Sha.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<80;++i)W2[i]=W2[i-3]^W2[i-8]^W2[i-14]^W2[i-16];for(var j=0;j<80;++j){var s=~~(j/20),t=rotl5(a)+ft(s,b,c,d)+e+W2[j]+K[s]|0;e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha.prototype._hash=function(){var H=Buffer2.allocUnsafe(20);return H.writeInt32BE(this._a|0,0),H.writeInt32BE(this._b|0,4),H.writeInt32BE(this._c|0,8),H.writeInt32BE(this._d|0,12),H.writeInt32BE(this._e|0,16),H},module.exports=Sha}}),require_sha1=__commonJS({\"node_modules/sha.js/sha1.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return s===0\?b&c|~b&d:s===2\?b&c|b&d|c&d:b^c^d}Sha1.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<80;++i)W2[i]=rotl1(W2[i-3]^W2[i-8]^W2[i-14]^W2[i-16]);for(var j=0;j<80;++j){var s=~~(j/20),t=rotl5(a)+ft(s,b,c,d)+e+W2[j]+K[s]|0;e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha1.prototype._hash=function(){var H=Buffer2.allocUnsafe(20);return H.writeInt32BE(this._a|0,0),H.writeInt32BE(this._b|0,4),H.writeInt32BE(this._c|0,8),H.writeInt32BE(this._d|0,12),H.writeInt32BE(this._e|0,16),H},module.exports=Sha1}}),require_sha256=__commonJS({\"node_modules/sha.js/sha256.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=new Array(64);function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,f=this._f|0,g=this._g|0,h=this._h|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<64;++i)W2[i]=gamma1(W2[i-2])+W2[i-7]+gamma0(W2[i-15])+W2[i-16]|0;for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W2[j]|0,T2=sigma0(a)+maj(a,b,c)|0;h=g,g=f,f=e,e=d+T1|0,d=c,c=b,b=a,a=T1+T2|0}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0,this._f=f+this._f|0,this._g=g+this._g|0,this._h=h+this._h|0},Sha256.prototype._hash=function(){var H=Buffer2.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256}}),require_sha224=__commonJS({\"node_modules/sha.js/sha224.js\"(exports,module){var inherits=require_inherits_browser(),Sha256=require_sha256(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,W=new Array(64);function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer2.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224}}),require_sha512=__commonJS({\"node_modules/sha.js/sha512.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=new Array(160);function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0\?1:0}Sha512.prototype._update=function(M){for(var W2=this._w,ah=this._ah|0,bh=this._bh|0,ch=this._ch|0,dh=this._dh|0,eh=this._eh|0,fh=this._fh|0,gh=this._gh|0,hh=this._hh|0,al=this._al|0,bl=this._bl|0,cl=this._cl|0,dl=this._dl|0,el=this._el|0,fl=this._fl|0,gl=this._gl|0,hl=this._hl|0,i=0;i<32;i+=2)W2[i]=M.readInt32BE(i*4),W2[i+1]=M.readInt32BE(i*4+4);for(;i<160;i+=2){var xh=W2[i-30],xl=W2[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh);xh=W2[i-4],xl=W2[i-4+1];var gamma1=Gamma1(xh,xl),gamma1l=Gamma1l(xl,xh),Wi7h=W2[i-14],Wi7l=W2[i-14+1],Wi16h=W2[i-32],Wi16l=W2[i-32+1],Wil=gamma0l+Wi7l|0,Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wil=Wil+gamma1l|0,Wih=Wih+gamma1+getCarry(Wil,gamma1l)|0,Wil=Wil+Wi16l|0,Wih=Wih+Wi16h+getCarry(Wil,Wi16l)|0,W2[i]=Wih,W2[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W2[j],Wil=W2[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=hl+sigma1l|0,t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1l=t1l+chl|0,t1h=t1h+chh+getCarry(t1l,chl)|0,t1l=t1l+Kil|0,t1h=t1h+Kih+getCarry(t1l,Kil)|0,t1l=t1l+Wil|0,t1h=t1h+Wih+getCarry(t1l,Wil)|0;var t2l=sigma0l+majl|0,t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,el=dl+t1l|0,eh=dh+t1h+getCarry(el,dl)|0,dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,al=t1l+t2l|0,ah=t1h+t2h+getCarry(al,t1l)|0}this._al=this._al+al|0,this._bl=this._bl+bl|0,this._cl=this._cl+cl|0,this._dl=this._dl+dl|0,this._el=this._el+el|0,this._fl=this._fl+fl|0,this._gl=this._gl+gl|0,this._hl=this._hl+hl|0,this._ah=this._ah+ah+getCarry(this._al,al)|0,this._bh=this._bh+bh+getCarry(this._bl,bl)|0,this._ch=this._ch+ch+getCarry(this._cl,cl)|0,this._dh=this._dh+dh+getCarry(this._dl,dl)|0,this._eh=this._eh+eh+getCarry(this._el,el)|0,this._fh=this._fh+fh+getCarry(this._fl,fl)|0,this._gh=this._gh+gh+getCarry(this._gl,gl)|0,this._hh=this._hh+hh+getCarry(this._hl,hl)|0},Sha512.prototype._hash=function(){var H=Buffer2.allocUnsafe(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512}}),require_sha384=__commonJS({\"node_modules/sha.js/sha384.js\"(exports,module){var inherits=require_inherits_browser(),SHA512=require_sha512(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,W=new Array(160);function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){var H=Buffer2.allocUnsafe(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384}}),require_sha2=__commonJS({\"node_modules/sha.js/index.js\"(exports,module){var exports=module.exports=function(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+\" is not supported (we accept pull requests)\");return new Algorithm};exports.sha=require_sha(),exports.sha1=require_sha1(),exports.sha224=require_sha224(),exports.sha256=require_sha256(),exports.sha384=require_sha384(),exports.sha512=require_sha512()}}),require_cipher_base=__commonJS({\"node_modules/cipher-base/index.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,inherits=require_inherits_browser();function CipherBase(hashMode){StreamModule.Transform.call(this),this.hashMode=typeof hashMode==\"string\",this.hashMode\?this[hashMode]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}inherits(CipherBase,StreamModule.Transform),CipherBase.prototype.update=function(data,inputEnc,outputEnc){typeof data==\"string\"&&(data=Buffer2.from(data,inputEnc));var outData=this._update(data);return this.hashMode\?this:(outputEnc&&(outData=this._toString(outData,outputEnc)),outData)},CipherBase.prototype.setAutoPadding=function(){},CipherBase.prototype.getAuthTag=function(){throw new Error(\"trying to get auth tag in unsupported state\")},CipherBase.prototype.setAuthTag=function(){throw new Error(\"trying to set auth tag in unsupported state\")},CipherBase.prototype.setAAD=function(){throw new Error(\"trying to set aad in unsupported state\")},CipherBase.prototype._transform=function(data,_,next){var err;try{this.hashMode\?this._update(data):this.push(this._update(data))}catch(e){err=e}finally{next(err)}},CipherBase.prototype._flush=function(done){var err;try{this.push(this.__final())}catch(e){err=e}done(err)},CipherBase.prototype._finalOrDigest=function(outputEnc){var outData=this.__final()||Buffer2.alloc(0);return outputEnc&&(outData=this._toString(outData,outputEnc,!0)),outData},CipherBase.prototype._toString=function(value,enc,fin){if(this._decoder||(this._decoder=new StringDecoder(enc),this._encoding=enc),this._encoding!==enc)throw new Error(\"can't switch encodings\");var out=this._decoder.write(value);return fin&&(out+=this._decoder.end()),out},module.exports=CipherBase}}),require_browser2=__commonJS({\"node_modules/create-hash/browser.js\"(exports,module){const LazyHash=function Hash(algorithm,options){this._options=options,this._hasher=new CryptoHasher(algorithm,options),this._finalized=!1};LazyHash.prototype=Object.create(StreamModule.Transform.prototype),LazyHash.prototype.update=function update(data,encoding){return this._checkFinalized(),this._hasher.update(data,encoding),this},LazyHash.prototype.digest=function update(data,encoding){return this._checkFinalized(),this._finalized=!0,this._hasher.digest(data,encoding)},LazyHash.prototype._checkFinalized=function _checkFinalized(){if(this._finalized){var err=new Error(\"Digest already called\");throw err.code=\"ERR_CRYPTO_HASH_FINALIZED\",err}},LazyHash.prototype.copy=function copy(){const copy=Object.create(LazyHash.prototype);return copy._options=this._options,copy._hasher=this._hasher.copy(),copy._finalized=this._finalized,copy};const lazyHashFullInitProto={__proto__:StreamModule.Transform.prototype,...LazyHash.prototype,_transform(data,encoding,callback){this.update(data,encoding),callback&&callback()},_flush(callback){this.push(this.digest()),callback()}},triggerMethods=[\"_events\",\"_eventsCount\",\"_final\",\"_maxListeners\",\"_maxListeners\",\"_read\",\"_undestroy\",\"_writableState\",\"_write\",\"_writev\",\"addListener\",\"asIndexedPairs\",\"closed\",\"compose\",\"constructor\",\"cork\",\"destroy\",\"destroyed\",\"drop\",\"emit\",\"end\",\"errored\",\"eventNames\",\"every\",\"filter\",\"find\",\"flatMap\",\"forEach\",\"getMaxListeners\",\"hasOwnProperty\",\"isPaused\",\"isPrototypeOf\",\"iterator\",\"listenerCount\",\"listeners\",\"map\",\"off\",\"on\",\"once\",\"pause\",\"pipe\",\"prependListener\",\"prependOnceListener\",\"propertyIsEnumerable\",\"push\",\"rawListeners\",\"read\",\"readable\",\"readableAborted\",\"readableBuffer\",\"readableDidRead\",\"readableEncoding\",\"readableEnded\",\"readableFlowing\",\"readableHighWaterMark\",\"readableLength\",\"readableObjectMode\",\"reduce\",\"removeAllListeners\",\"removeListener\",\"resume\",\"setDefaultEncoding\",\"setEncoding\",\"setMaxListeners\",\"some\",\"take\",\"toArray\",\"toLocaleString\",\"toString\",\"uncork\",\"unpipe\",\"unshift\",\"valueOf\",\"wrap\",\"writable\",\"writableBuffer\",\"writableCorked\",\"writableEnded\",\"writableFinished\",\"writableHighWaterMark\",\"writableLength\",\"writableNeedDrain\",\"writableObjectMode\",\"write\"];for(let method of triggerMethods)Object.defineProperty(LazyHash.prototype,method,{get(){return Object.setPrototypeOf(this,lazyHashFullInitProto),StreamModule.Transform.call(this,this._options),this[method]},enumerable:!1,configurable:!0});module.exports=function createHash(algorithm){return new LazyHash(algorithm)},module.exports.createHash=module.exports,module.exports.Hash=LazyHash}}),require_legacy=__commonJS({\"node_modules/create-hmac/legacy.js\"(exports,module){var inherits=require_inherits_browser(),Buffer2=require_safe_buffer().Buffer,Base=require_cipher_base(),ZEROS=Buffer2.alloc(128),blocksize=64;function Hmac(alg,key){Base.call(this,\"digest\"),typeof key==\"string\"&&(key=Buffer2.from(key)),this._alg=alg,this._key=key,key.length>blocksize\?key=alg(key):key.lengthblocksize){var hash=alg===\"rmd160\"\?new RIPEMD160:sha(alg);key=hash.update(key).digest()}else key.lengthMAX_ALLOC||keylen!==keylen)@throwTypeError(\"Bad key length\")}}}),require_default_encoding=__commonJS({\"node_modules/pbkdf2/lib/default-encoding.js\"(exports,module){var defaultEncoding;global.process&&global.process.browser\?defaultEncoding=\"utf-8\":global.process&&global.process.version\?(pVersionMajor=parseInt(process.version.split(\".\")[0].slice(1),10),defaultEncoding=pVersionMajor>=6\?\"utf-8\":\"binary\"):defaultEncoding=\"utf-8\";var pVersionMajor;module.exports=defaultEncoding}}),require_to_buffer=__commonJS({\"node_modules/pbkdf2/lib/to-buffer.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer;module.exports=function(thing,encoding,name){if(Buffer2.isBuffer(thing))return thing;if(typeof thing==\"string\")return Buffer2.from(thing,encoding);if(ArrayBuffer.isView(thing))return Buffer2.from(thing.buffer);@throwTypeError(name+\" must be a string, a Buffer, a typed array or a DataView\")}}}),require_sync_browser=__commonJS({\"node_modules/pbkdf2/lib/sync-browser.js\"(exports,module){var md5=require_md52(),RIPEMD160=require_ripemd160(),sha=require_sha2(),Buffer2=require_safe_buffer().Buffer,checkParameters=require_precondition(),defaultEncoding=require_default_encoding(),toBuffer=require_to_buffer(),ZEROS=Buffer2.alloc(128),sizes={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function Hmac(alg,key,saltLen){var hash=getDigest(alg),blocksize=alg===\"sha512\"||alg===\"sha384\"\?128:64;key.length>blocksize\?key=hash(key):key.length>>0},exports.writeUInt32BE=function(bytes,value,off){bytes[0+off]=value>>>24,bytes[1+off]=value>>>16&255,bytes[2+off]=value>>>8&255,bytes[3+off]=value&255},exports.ip=function(inL,inR,out,off){for(var outL=0,outR=0,i=6;i>=0;i-=2){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>>j+i&1;for(var j=0;j<=24;j+=8)outL<<=1,outL|=inL>>>j+i&1}for(var i=6;i>=0;i-=2){for(var j=1;j<=25;j+=8)outR<<=1,outR|=inR>>>j+i&1;for(var j=1;j<=25;j+=8)outR<<=1,outR|=inL>>>j+i&1}out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.rip=function(inL,inR,out,off){for(var outL=0,outR=0,i=0;i<4;i++)for(var j=24;j>=0;j-=8)outL<<=1,outL|=inR>>>j+i&1,outL<<=1,outL|=inL>>>j+i&1;for(var i=4;i<8;i++)for(var j=24;j>=0;j-=8)outR<<=1,outR|=inR>>>j+i&1,outR<<=1,outR|=inL>>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.pc1=function(inL,inR,out,off){for(var outL=0,outR=0,i=7;i>=5;i--){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(var j=0;j<=24;j+=8)outL<<=1,outL|=inL>>j+i&1}for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(var i=1;i<=3;i++){for(var j=0;j<=24;j+=8)outR<<=1,outR|=inR>>j+i&1;for(var j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1}for(var j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.r28shl=function(num,shift){return num<>>28-shift};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];exports.pc2=function(inL,inR,out,off){for(var outL=0,outR=0,len=pc2table.length>>>1,i=0;i>>pc2table[i]&1;for(var i=len;i>>pc2table[i]&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.expand=function(r,out,off){var outL=0,outR=0;outL=(r&1)<<5|r>>>27;for(var i=23;i>=15;i-=4)outL<<=6,outL|=r>>>i&63;for(var i=11;i>=3;i-=4)outR|=r>>>i&63,outR<<=6;outR|=(r&31)<<1|r>>>31,out[off+0]=outL>>>0,out[off+1]=outR>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];exports.substitute=function(inL,inR){for(var out=0,i=0;i<4;i++){var b=inL>>>18-i*6&63,sb=sTable[i*64+b];out<<=4,out|=sb}for(var i=0;i<4;i++){var b=inR>>>18-i*6&63,sb=sTable[256+i*64+b];out<<=4,out|=sb}return out>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];exports.permute=function(num){for(var out=0,i=0;i>>permuteTable[i]&1;return out>>>0},exports.padSplit=function(num,size,group){for(var str=num.toString(2);str.length0;count--)inputOff+=this._buffer(data,inputOff),outputOff+=this._flushBuffer(out,outputOff);return inputOff+=this._buffer(data,inputOff),out},Cipher.prototype.final=function(buffer){var first;buffer&&(first=this.update(buffer));var last;return this.type===\"encrypt\"\?last=this._finalEncrypt():last=this._finalDecrypt(),first\?first.concat(last):last},Cipher.prototype._pad=function(buffer,off){if(off===0)return!1;for(;off>>1];kL=utils.r28shl(kL,shift),kR=utils.r28shl(kR,shift),utils.pc2(kL,kR,state.keys,i)}},DES.prototype._update=function(inp,inOff,out,outOff){var state=this._desState,l=utils.readUInt32BE(inp,inOff),r=utils.readUInt32BE(inp,inOff+4);utils.ip(l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],this.type===\"encrypt\"\?this._encrypt(state,l,r,state.tmp,0):this._decrypt(state,l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],utils.writeUInt32BE(out,l,outOff),utils.writeUInt32BE(out,r,outOff+4)},DES.prototype._pad=function(buffer,off){for(var value=buffer.length-off,i=off;i>>0,l=t}utils.rip(r,l,out,off)},DES.prototype._decrypt=function(state,lStart,rStart,out,off){for(var l=rStart,r=lStart,i=state.keys.length-2;i>=0;i-=2){var keyL=state.keys[i],keyR=state.keys[i+1];utils.expand(l,state.tmp,0),keyL^=state.tmp[0],keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR),f=utils.permute(s),t=l;l=(r^f)>>>0,r=t}utils.rip(l,r,out,off)}}}),require_cbc=__commonJS({\"node_modules/des.js/lib/des/cbc.js\"(exports){var assert=require_minimalistic_assert(),inherits=require_inherits_browser(),proto={};function CBCState(iv){assert.equal(iv.length,8,\"Invalid IV length\"),this.iv=new Array(8);for(var i=0;i>i%8,self2._prev=shiftIn(self2._prev,decrypt\?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer2.allocUnsafe(buffer.length);for(buffer=Buffer2.concat([buffer,Buffer2.from([value])]);++i>7;return out}exports.encrypt=function(self2,chunk,decrypt){for(var len=chunk.length,out=Buffer2.allocUnsafe(len),i=-1;++i>>24]^SUB_MIX1[s1>>>16&255]^SUB_MIX2[s2>>>8&255]^SUB_MIX3[s3&255]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[s2>>>16&255]^SUB_MIX2[s3>>>8&255]^SUB_MIX3[s0&255]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[s3>>>16&255]^SUB_MIX2[s0>>>8&255]^SUB_MIX3[s1&255]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[s0>>>16&255]^SUB_MIX2[s1>>>8&255]^SUB_MIX3[s2&255]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[s3&255])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[s0&255])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[s1&255])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[s2&255])^keySchedule[ksRow++],t0=t0>>>0,t1=t1>>>0,t2=t2>>>0,t3=t3>>>0,[t0,t1,t2,t3]}var RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=new Array(256),j=0;j<256;j++)j<128\?d[j]=j<<1:d[j]=j<<1^283;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0;i<256;++i){var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^sx&255^99,SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=d[sx]*257^sx*16843008;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=x8*16843009^x4*65537^x2*257^x*16843008,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,x===0\?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX,INV_SBOX,SUB_MIX,INV_SUB_MIX}}();function AES(key){this._key=asUInt32Array(key),this._reset()}AES.prototype={},AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=(nRounds+1)*4,keySchedule=[],k=0;k>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255],t^=RCON[k/keySize|0]<<24):keySize>6&&k%keySize===4&&(t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik>>24]]^G.INV_SUB_MIX[1][G.SBOX[tt>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[tt>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[tt&255]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return M=asUInt32Array(M),cryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=asUInt32Array(M);var m1=M[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES}}),require_ghash=__commonJS({\"node_modules/browserify-aes/ghash.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,ZEROES=Buffer2.alloc(16,0);function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){var buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer2.alloc(16,0),this.cache=Buffer2.allocUnsafe(0)}GHASH.prototype={},GHASH.prototype.ghash=function(block){for(var i=-1;++i0;j--)Vi[j]=Vi[j]>>>1|(Vi[j-1]&1)<<31;Vi[0]=Vi[0]>>>1,lsbVi&&(Vi[0]=Vi[0]^225<<24)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer2.concat([this.cache,buf]);for(var chunk;this.cache.length>=16;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer2.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH}}),require_authCipher=__commonJS({\"node_modules/browserify-aes/authCipher.js\"(exports,module){var aes=require_aes(),Buffer2=require_safe_buffer().Buffer,Transform=require_cipher_base(),inherits=require_inherits_browser(),GHASH=require_ghash(),xor=require_buffer_xor(),incr32=require_incr32();function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=Math.min(a.length,b.length),i=0;i0||ivLen>0;){var hash=new MD5;hash.update(tmp),hash.update(password),salt&&hash.update(salt),tmp=hash.digest();var used=0;if(keyLen>0){var keyStart=key.length-keyLen;used=Math.min(keyLen,tmp.length),tmp.copy(key,keyStart,0,used),keyLen-=used}if(used0){var ivStart=iv.length-ivLen,length=Math.min(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length),ivLen-=length}}return tmp.fill(0),{key,iv}}module.exports=EVP_BytesToKey}}),require_encrypter=__commonJS({\"node_modules/browserify-aes/encrypter.js\"(exports){var MODES=require_modes(),AuthCipher=require_authCipher(),Buffer2=require_safe_buffer().Buffer,StreamCipher=require_streamCipher(),Transform=require_cipher_base(),aes=require_aes(),ebtk=require_evp_bytestokey(),inherits=require_inherits_browser();function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer2.from(iv),this._mode=mode,this._autopadding=!0}inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var chunk,thing,out=[];chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer2.concat(out)};var PADDING=Buffer2.alloc(16,16);Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error(\"data not multiple of block length\")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this};function Splitter(){this.cache=Buffer2.allocUnsafe(0)}Splitter.prototype={},Splitter.prototype.add=function(data){this.cache=Buffer2.concat([this.cache,data])},Splitter.prototype.get=function(){if(this.cache.length>15){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer2.allocUnsafe(len),i=-1;++i16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out}else if(this.cache.length>=16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache};function unpad(last){var padded=last[15];if(padded<1||padded>16)throw new Error(\"unable to decrypt data\");for(var i=-1;++i0\?left:right},BN.min=function(left,right){return left.cmp(right)<0\?left:right},BN.prototype._init=function(number,base,endian){if(typeof number==\"number\")return this._initNumber(number,base,endian);if(typeof number==\"object\")return this._initArray(number,base,endian);base===\"hex\"&&(base=16),assert(base===(base|0)&&base>=2&&base<=36),number=number.toString().replace(/\\s+/g,\"\");var start=0;number[0]===\"-\"&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);else if(endian===\"le\")for(i=0,j=0;i>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);return this.strip()};function parseHex4Bits(string,index){var c=string.charCodeAt(index);return c>=65&&c<=70\?c-55:c>=97&&c<=102\?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}BN.prototype._parseHex=function(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18\?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=parseLength%2===0\?start+1:start;i=18\?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this.strip()};function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49\?r+=c-49+10:c>=17\?r+=c-17+10:r+=c}return r}BN.prototype._parseBase=function(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},BN.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},BN.prototype.inspect=function(){return(this.red\?\"\"};var zeros=[\"\",\"0\",\"00\",\"000\",\"0000\",\"00000\",\"000000\",\"0000000\",\"00000000\",\"000000000\",\"0000000000\",\"00000000000\",\"000000000000\",\"0000000000000\",\"00000000000000\",\"000000000000000\",\"0000000000000000\",\"00000000000000000\",\"000000000000000000\",\"0000000000000000000\",\"00000000000000000000\",\"000000000000000000000\",\"0000000000000000000000\",\"00000000000000000000000\",\"000000000000000000000000\",\"0000000000000000000000000\"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function(base,padding){base=base||10,padding=padding|0||1;var out;if(base===16||base===\"hex\"){out=\"\";for(var off=0,carry=0,i=0;i>>24-off&16777215,carry!==0||i!==this.length-1\?out=zeros[6-word.length]+word+out:out=word+out,off+=2,off>=26&&(off-=26,i--)}for(carry!==0&&(out=carry.toString(16)+out);out.length%padding!==0;)out=\"0\"+out;return this.negative!==0&&(out=\"-\"+out),out}if(base===(base|0)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out=\"\";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),c.isZero()\?out=r+out:out=zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out=\"0\"+out);out.length%padding!==0;)out=\"0\"+out;return this.negative!==0&&(out=\"-\"+out),out}assert(!1,\"Base should be between 2 and 36\")},BN.prototype.toNumber=function(){var ret=this.words[0];return this.length===2\?ret+=this.words[1]*67108864:this.length===3&&this.words[2]===1\?ret+=4503599627370496+this.words[1]*67108864:this.length>2&&assert(!1,\"Number can only safely store up to 53 bits\"),this.negative!==0\?-ret:ret},BN.prototype.toJSON=function(){return this.toString(16)},BN.prototype.toBuffer=function(endian,length){return assert(typeof Buffer2<\"u\"),this.toArrayLike(Buffer2,endian,length)},BN.prototype.toArray=function(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,\"byte array longer than desired length\"),assert(reqLength>0,\"Requested array length <= 0\"),this.strip();var littleEndian=endian===\"le\",res=new ArrayType(reqLength),b,i,q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(w===0)return 26;var t=w,r=0;return(t&8191)===0&&(r+=13,t>>>=13),(t&127)===0&&(r+=7,t>>>=7),(t&15)===0&&(r+=4,t>>>=4),(t&3)===0&&(r+=2,t>>>=2),(t&1)===0&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return(this.length-1)*26+hi};function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0;inum.length\?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length\?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b;this.length>num.length\?b=num:b=this;for(var i=0;inum.length\?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length\?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length\?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length\?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length\?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert(typeof width==\"number\"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0,bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert(typeof bit==\"number\"&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),val\?this.words[off]=this.words[off]|1<num.length\?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;carry!==0&&i>>26;if(this.length=a.length,carry!==0)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length\?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(cmp===0)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;cmp>0\?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=r&67108863;for(;carry!==0&&i>26,this.words[i]=r&67108863;if(carry===0&&i>>26,rword=carry&67108863,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self2.length+1);j<=maxJ;j++){var i=k-j|0;a=self2.words[i]|0,b=num.words[j]|0,r=a*b+rword,ncarry+=r/67108864|0,rword=r&67108863}out.words[k]=rword|0,carry=ncarry|0}return carry!==0\?out.words[k]=carry|0:out.length--,out.strip()}var comb10MulTo=function(self2,num,out){var a=self2.words,b=num.words,o=out.words,c=0,lo,mid,hi,a0=a[0]|0,al0=a0&8191,ah0=a0>>>13,a1=a[1]|0,al1=a1&8191,ah1=a1>>>13,a2=a[2]|0,al2=a2&8191,ah2=a2>>>13,a3=a[3]|0,al3=a3&8191,ah3=a3>>>13,a4=a[4]|0,al4=a4&8191,ah4=a4>>>13,a5=a[5]|0,al5=a5&8191,ah5=a5>>>13,a6=a[6]|0,al6=a6&8191,ah6=a6>>>13,a7=a[7]|0,al7=a7&8191,ah7=a7>>>13,a8=a[8]|0,al8=a8&8191,ah8=a8>>>13,a9=a[9]|0,al9=a9&8191,ah9=a9>>>13,b0=b[0]|0,bl0=b0&8191,bh0=b0>>>13,b1=b[1]|0,bl1=b1&8191,bh1=b1>>>13,b2=b[2]|0,bl2=b2&8191,bh2=b2>>>13,b3=b[3]|0,bl3=b3&8191,bh3=b3>>>13,b4=b[4]|0,bl4=b4&8191,bh4=b4>>>13,b5=b[5]|0,bl5=b5&8191,bh5=b5>>>13,b6=b[6]|0,bl6=b6&8191,bh6=b6>>>13,b7=b[7]|0,bl7=b7&8191,bh7=b7>>>13,b8=b[8]|0,bl8=b8&8191,bh8=b8>>>13,b9=b[9]|0,bl9=b9&8191,bh9=b9>>>13;out.negative=self2.negative^num.negative,out.length=19,lo=Math.imul(al0,bl0),mid=Math.imul(al0,bh0),mid=mid+Math.imul(ah0,bl0)|0,hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=Math.imul(al1,bh0),mid=mid+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0),lo=lo+Math.imul(al0,bl1)|0,mid=mid+Math.imul(al0,bh1)|0,mid=mid+Math.imul(ah0,bl1)|0,hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=Math.imul(al2,bh0),mid=mid+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=mid+Math.imul(al1,bh1)|0,mid=mid+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0,lo=lo+Math.imul(al0,bl2)|0,mid=mid+Math.imul(al0,bh2)|0,mid=mid+Math.imul(ah0,bl2)|0,hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=Math.imul(al3,bh0),mid=mid+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=mid+Math.imul(al2,bh1)|0,mid=mid+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=mid+Math.imul(al1,bh2)|0,mid=mid+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0,lo=lo+Math.imul(al0,bl3)|0,mid=mid+Math.imul(al0,bh3)|0,mid=mid+Math.imul(ah0,bl3)|0,hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=Math.imul(al4,bh0),mid=mid+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=mid+Math.imul(al3,bh1)|0,mid=mid+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=mid+Math.imul(al2,bh2)|0,mid=mid+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=mid+Math.imul(al1,bh3)|0,mid=mid+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0,lo=lo+Math.imul(al0,bl4)|0,mid=mid+Math.imul(al0,bh4)|0,mid=mid+Math.imul(ah0,bl4)|0,hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=Math.imul(al5,bh0),mid=mid+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=mid+Math.imul(al4,bh1)|0,mid=mid+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=mid+Math.imul(al3,bh2)|0,mid=mid+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=mid+Math.imul(al2,bh3)|0,mid=mid+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=mid+Math.imul(al1,bh4)|0,mid=mid+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0,lo=lo+Math.imul(al0,bl5)|0,mid=mid+Math.imul(al0,bh5)|0,mid=mid+Math.imul(ah0,bl5)|0,hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=Math.imul(al6,bh0),mid=mid+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=mid+Math.imul(al5,bh1)|0,mid=mid+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=mid+Math.imul(al4,bh2)|0,mid=mid+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=mid+Math.imul(al3,bh3)|0,mid=mid+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=mid+Math.imul(al2,bh4)|0,mid=mid+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=mid+Math.imul(al1,bh5)|0,mid=mid+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0,lo=lo+Math.imul(al0,bl6)|0,mid=mid+Math.imul(al0,bh6)|0,mid=mid+Math.imul(ah0,bl6)|0,hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=Math.imul(al7,bh0),mid=mid+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=mid+Math.imul(al6,bh1)|0,mid=mid+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=mid+Math.imul(al5,bh2)|0,mid=mid+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=mid+Math.imul(al4,bh3)|0,mid=mid+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=mid+Math.imul(al3,bh4)|0,mid=mid+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=mid+Math.imul(al2,bh5)|0,mid=mid+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=mid+Math.imul(al1,bh6)|0,mid=mid+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0,lo=lo+Math.imul(al0,bl7)|0,mid=mid+Math.imul(al0,bh7)|0,mid=mid+Math.imul(ah0,bl7)|0,hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=Math.imul(al8,bh0),mid=mid+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=mid+Math.imul(al7,bh1)|0,mid=mid+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=mid+Math.imul(al6,bh2)|0,mid=mid+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=mid+Math.imul(al5,bh3)|0,mid=mid+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=mid+Math.imul(al4,bh4)|0,mid=mid+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=mid+Math.imul(al3,bh5)|0,mid=mid+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=mid+Math.imul(al2,bh6)|0,mid=mid+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=mid+Math.imul(al1,bh7)|0,mid=mid+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0,lo=lo+Math.imul(al0,bl8)|0,mid=mid+Math.imul(al0,bh8)|0,mid=mid+Math.imul(ah0,bl8)|0,hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=Math.imul(al9,bh0),mid=mid+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=mid+Math.imul(al8,bh1)|0,mid=mid+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=mid+Math.imul(al7,bh2)|0,mid=mid+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=mid+Math.imul(al6,bh3)|0,mid=mid+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=mid+Math.imul(al5,bh4)|0,mid=mid+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=mid+Math.imul(al4,bh5)|0,mid=mid+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=mid+Math.imul(al3,bh6)|0,mid=mid+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=mid+Math.imul(al2,bh7)|0,mid=mid+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=mid+Math.imul(al1,bh8)|0,mid=mid+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0,lo=lo+Math.imul(al0,bl9)|0,mid=mid+Math.imul(al0,bh9)|0,mid=mid+Math.imul(ah0,bl9)|0,hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=Math.imul(al9,bh1),mid=mid+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=mid+Math.imul(al8,bh2)|0,mid=mid+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=mid+Math.imul(al7,bh3)|0,mid=mid+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=mid+Math.imul(al6,bh4)|0,mid=mid+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=mid+Math.imul(al5,bh5)|0,mid=mid+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=mid+Math.imul(al4,bh6)|0,mid=mid+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=mid+Math.imul(al3,bh7)|0,mid=mid+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=mid+Math.imul(al2,bh8)|0,mid=mid+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0,lo=lo+Math.imul(al1,bl9)|0,mid=mid+Math.imul(al1,bh9)|0,mid=mid+Math.imul(ah1,bl9)|0,hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=Math.imul(al9,bh2),mid=mid+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=mid+Math.imul(al8,bh3)|0,mid=mid+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=mid+Math.imul(al7,bh4)|0,mid=mid+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=mid+Math.imul(al6,bh5)|0,mid=mid+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=mid+Math.imul(al5,bh6)|0,mid=mid+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=mid+Math.imul(al4,bh7)|0,mid=mid+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=mid+Math.imul(al3,bh8)|0,mid=mid+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0,lo=lo+Math.imul(al2,bl9)|0,mid=mid+Math.imul(al2,bh9)|0,mid=mid+Math.imul(ah2,bl9)|0,hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=Math.imul(al9,bh3),mid=mid+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=mid+Math.imul(al8,bh4)|0,mid=mid+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=mid+Math.imul(al7,bh5)|0,mid=mid+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=mid+Math.imul(al6,bh6)|0,mid=mid+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=mid+Math.imul(al5,bh7)|0,mid=mid+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=mid+Math.imul(al4,bh8)|0,mid=mid+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0,lo=lo+Math.imul(al3,bl9)|0,mid=mid+Math.imul(al3,bh9)|0,mid=mid+Math.imul(ah3,bl9)|0,hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=Math.imul(al9,bh4),mid=mid+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=mid+Math.imul(al8,bh5)|0,mid=mid+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=mid+Math.imul(al7,bh6)|0,mid=mid+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=mid+Math.imul(al6,bh7)|0,mid=mid+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=mid+Math.imul(al5,bh8)|0,mid=mid+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0,lo=lo+Math.imul(al4,bl9)|0,mid=mid+Math.imul(al4,bh9)|0,mid=mid+Math.imul(ah4,bl9)|0,hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=Math.imul(al9,bh5),mid=mid+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=mid+Math.imul(al8,bh6)|0,mid=mid+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=mid+Math.imul(al7,bh7)|0,mid=mid+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=mid+Math.imul(al6,bh8)|0,mid=mid+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0,lo=lo+Math.imul(al5,bl9)|0,mid=mid+Math.imul(al5,bh9)|0,mid=mid+Math.imul(ah5,bl9)|0,hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=Math.imul(al9,bh6),mid=mid+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=mid+Math.imul(al8,bh7)|0,mid=mid+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=mid+Math.imul(al7,bh8)|0,mid=mid+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0,lo=lo+Math.imul(al6,bl9)|0,mid=mid+Math.imul(al6,bh9)|0,mid=mid+Math.imul(ah6,bl9)|0,hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=Math.imul(al9,bh7),mid=mid+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=mid+Math.imul(al8,bh8)|0,mid=mid+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0,lo=lo+Math.imul(al7,bl9)|0,mid=mid+Math.imul(al7,bh9)|0,mid=mid+Math.imul(ah7,bl9)|0,hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=Math.imul(al9,bh8),mid=mid+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8),lo=lo+Math.imul(al8,bl9)|0,mid=mid+Math.imul(al8,bh9)|0,mid=mid+Math.imul(ah8,bl9)|0,hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863,lo=Math.imul(al9,bl9),mid=Math.imul(al9,bh9),mid=mid+Math.imul(ah9,bl9)|0,hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&8191)<<13)|0;return c=(hi+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,c!==0&&(o[19]=c,out.length++),out};Math.imul||(comb10MulTo=smallMulTo);function bigMulTo(self2,num,out){out.negative=num.negative^self2.negative,out.length=self2.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0,hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return carry!==0\?out.words[k]=carry:out.length--,out.strip()}function jumboMulTo(self2,num,out){var fftm=new FFTM;return fftm.mulp(self2,num,out)}BN.prototype.mulTo=function(num,out){var res,len=this.length+num.length;return this.length===10&&num.length===10\?res=comb10MulTo(this,num,out):len<63\?res=smallMulTo(this,num,out):len<1024\?res=bigMulTo(this,num,out):res=jumboMulTo(this,num,out),res};function FFTM(x,y){this.x=x,this.y=y}FFTM.prototype={},FFTM.prototype.makeRBT=function(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1)i++;return 1<>>13,rws[2*i+1]=carry&8191,carry=carry>>>13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=lo&67108863}return carry!==0&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(w.length===0)return new BN(1);for(var res=this,i=0;i=0);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(r!==0){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(s!==0){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0);var h;hint\?h=(hint-hint%26)/26:h=0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&carry!==0&&(maskedWords.words[maskedWords.length++]=carry),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function(bits,hint,extended){return assert(this.negative===0),this.iushrn(bits,hint,extended)},BN.prototype.shln=function(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function(bit){assert(typeof bit==\"number\"&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(this.negative===0,\"imaskn works only with positive numbers\"),this.length<=s)return this;if(r!==0&&s++,this.length=Math.min(s,this.length),r!==0){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1\?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function(num){if(assert(typeof num==\"number\"),assert(num<67108864),num<0)return this.iaddn(-num);if(this.negative!==0)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=w&67108863}for(;i>26,this.words[i+shift]=w&67108863;if(carry===0)return this.strip();for(assert(carry===-1),carry=0,i=0;i>26,this.words[i]=w&67108863;return this.negative=1,this.strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=b.words[b.length-1]|0,bhiBits=this._countBits(bhi);shift=26-bhiBits,shift!==0&&(b=b.ushln(shift),a.iushln(shift),bhi=b.words[b.length-1]|0);var m=a.length-b.length,q;if(mode!==\"mod\"){q=new BN(null),q.length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);a.negative!==0;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),mode!==\"div\"&&shift!==0&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return this.negative!==0&&num.negative===0\?(res=this.neg().divmod(num,mode),mode!==\"mod\"&&(div=res.div.neg()),mode!==\"div\"&&(mod=res.mod.neg(),positive&&mod.negative!==0&&mod.iadd(num)),{div,mod}):this.negative===0&&num.negative!==0\?(res=this.divmod(num.neg(),mode),mode!==\"mod\"&&(div=res.div.neg()),{div,mod:res.mod}):(this.negative&num.negative)!==0\?(res=this.neg().divmod(num.neg(),mode),mode!==\"div\"&&(mod=res.mod.neg(),positive&&mod.negative!==0&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0\?{div:new BN(0),mod:this}:num.length===1\?mode===\"div\"\?{div:this.divn(num.words[0]),mod:null}:mode===\"mod\"\?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode)},BN.prototype.div=function(num){return this.divmod(num,\"div\",!1).div},BN.prototype.mod=function(num){return this.divmod(num,\"mod\",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,\"mod\",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0\?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||r2===1&&cmp===0\?dm.div:dm.div.negative!==0\?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(this.words[i]|0))%num;return acc},BN.prototype.idivn=function(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(p.negative===0),assert(!p.isZero());var x=this,y=p.clone();x.negative!==0\?x=x.umod(p):x=x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0\?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function(p){assert(p.negative===0),assert(!p.isZero());var a=this,b=p.clone();a.negative!==0\?a=a.umod(p):a=a.clone();for(var x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0\?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return a.cmpn(1)===0\?res=x1:res=x2,res.cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(r===0||b.cmpn(1)===0)break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return(this.words[0]&1)===0},BN.prototype.isOdd=function(){return(this.words[0]&1)===1},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert(typeof bit==\"number\");var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return carry!==0&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return this.length===1&&this.words[0]===0},BN.prototype.cmpn=function(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this.strip();var res;if(this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,\"Number is too big\");var w=this.words[0]|0;res=w===num\?0:wnum.length)return 1;if(this.length=0;i--){var a=this.words[i]|0,b=num.words[i]|0;if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function(num){return this.cmpn(num)===1},BN.prototype.gt=function(num){return this.cmp(num)===1},BN.prototype.gten=function(num){return this.cmpn(num)>=0},BN.prototype.gte=function(num){return this.cmp(num)>=0},BN.prototype.ltn=function(num){return this.cmpn(num)===-1},BN.prototype.lt=function(num){return this.cmp(num)===-1},BN.prototype.lten=function(num){return this.cmpn(num)<=0},BN.prototype.lte=function(num){return this.cmp(num)<=0},BN.prototype.eqn=function(num){return this.cmpn(num)===0},BN.prototype.eq=function(num){return this.cmp(num)===0},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,\"Already a number in reduction context\"),assert(this.negative===0,\"red works only with positives\"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,\"fromRed works only with numbers in reduction context\"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,\"Already a number in reduction context\"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,\"redAdd works only with red numbers\"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,\"redIAdd works only with red numbers\"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,\"redSub works only with red numbers\"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,\"redISub works only with red numbers\"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,\"redShl works only with red numbers\"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,\"redMul works only with red numbers\"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,\"redMul works only with red numbers\"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,\"redSqr works only with red numbers\"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,\"redISqr works only with red numbers\"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,\"redSqrt works only with red numbers\"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,\"redInvm works only with red numbers\"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,\"redNeg works only with red numbers\"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,\"redPow(normalNum)\"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}MPrime.prototype={},MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen0\?r.isub(this.p):r.strip!==void 0\?r.strip():r._strip(),r},MPrime.prototype.split=function(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function(num){return num.imul(this.k)};function K256(){MPrime.call(this,\"k256\",\"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f\")}inherits(K256,MPrime),K256.prototype.split=function(input,output){for(var mask=4194303,outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,prev===0&&input.length>10\?input.length-=10:input.length-=9},K256.prototype.imulK=function(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return carry!==0&&(num.words[num.length++]=carry),num},BN._prime=function(name){if(primes[name])return primes[name];var prime2;if(name===\"k256\")prime2=new K256;else if(name===\"p224\")prime2=new P224;else if(name===\"p192\")prime2=new P192;else if(name===\"p25519\")prime2=new P25519;else throw new Error(\"Unknown prime \"+name);return primes[name]=prime2,prime2};function Red(m){if(typeof m==\"string\"){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),\"modulus must be greater than 1\"),this.m=m,this.prime=null}Red.prototype={},Red.prototype._verify1=function(a){assert(a.negative===0,\"red works only with positives\"),assert(a.red,\"red works only with red numbers\")},Red.prototype._verify2=function(a,b){assert((a.negative|b.negative)===0,\"red works only with positives\"),assert(a.red&&a.red===b.red,\"red works only with red numbers\")},Red.prototype.imod=function(a){return this.prime\?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function(a){return a.isZero()\?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2===1),mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&q.andln(1)===0;)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);this.pow(z,lpow).cmp(nOne)!==0;)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;t.cmp(one)!==0;){for(var tmp=t,i=0;tmp.cmp(one)!==0;i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]&&(res=this.sqr(res)),bit===0&¤t===0){currentLen=0;continue}current<<=1,current|=bit,currentLen++,!(currentLen!==windowSize&&(i!==0||j!==0))&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num\?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)};function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0\?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0\?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(typeof module>\"u\"||module,exports)}}),require_bn2=require_bn,require_brorand=__commonJS({\"node_modules/brorand/index.js\"(exports,module){var r;module.exports=function(len){return r||(r=new Rand(null)),r.generate(len)};function Rand(rand){this.rand=rand}Rand.prototype={},module.exports.Rand=Rand,Rand.prototype.generate=function(len){return this._rand(len)},Rand.prototype._rand=function(n){var out=new Buffer(n);return crypto.getRandomValues(out),out}}}),require_mr=__commonJS({\"node_modules/miller-rabin/lib/mr.js\"(exports,module){var bn=require_bn2(),brorand=require_brorand();function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin,MillerRabin.create=function(rand){return new MillerRabin(rand)},MillerRabin.prototype={},MillerRabin.prototype._randbelow=function(n){var len=n.bitLength(),min_bytes=Math.ceil(len/8);do var a=new bn(this.rand.generate(min_bytes));while(a.cmp(n)>=0);return a},MillerRabin.prototype._randrange=function(start,stop){var size=stop.sub(start);return start.add(this._randbelow(size))},MillerRabin.prototype.test=function(n,k,cb){var len=n.bitLength(),red=bn.mont(n),rone=new bn(1).toRed(red);k||(k=Math.max(1,len/48|0));for(var n1=n.subn(1),s=0;!n1.testn(s);s++);for(var d=n.shrn(s),rn1=n1.toRed(red),prime=!0;k>0;k--){var a=this._randrange(new bn(2),n1);cb&&cb(a);var x=a.toRed(red).redPow(d);if(!(x.cmp(rone)===0||x.cmp(rn1)===0)){for(var i=1;i0;k--){var a=this._randrange(new bn(2),n1),g=n.gcd(a);if(g.cmpn(1)!==0)return g;var x=a.toRed(red).redPow(d);if(!(x.cmp(rone)===0||x.cmp(rn1)===0)){for(var i=1;ibits;)num.ishrn(1);if(num.isEven()&&num.iadd(ONE),num.testn(1)||num.iadd(TWO),gen.cmp(TWO)){if(!gen.cmp(FIVE))for(;num.mod(TEN).cmp(THREE);)num.iadd(FOUR)}else for(;num.mod(TWENTYFOUR).cmp(ELEVEN);)num.iadd(FOUR);if(n2=num.shrn(1),simpleSieve(n2)&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num))return num}}}}),require_primes=__commonJS({\"node_modules/diffie-hellman/lib/primes.json\"(exports,module){module.exports={modp1:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff\"},modp2:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff\"},modp5:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff\"},modp14:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff\"},modp15:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff\"},modp16:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff\"},modp17:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff\"},modp18:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff\"}}}}),require_dh=__commonJS({\"node_modules/diffie-hellman/lib/dh.js\"(exports,module){var BN=require_bn(),MillerRabin=require_mr(),millerRabin=new MillerRabin,TWENTYFOUR=new BN(24),ELEVEN=new BN(11),TEN=new BN(10),THREE=new BN(3),SEVEN=new BN(7),primes=require_generatePrime(),randomBytes=require_browser();module.exports=DH;function setPublicKey(pub,enc){return enc=enc||\"utf8\",Buffer.isBuffer(pub)||(pub=new Buffer(pub,enc)),this._pub=new BN(pub),this}function setPrivateKey(priv,enc){return enc=enc||\"utf8\",Buffer.isBuffer(priv)||(priv=new Buffer(priv,enc)),this._priv=new BN(priv),this}var primeCache={};function checkPrime(prime,generator){var gen=generator.toString(\"hex\"),hex=[gen,prime.toString(16)].join(\"_\");if(hex in primeCache)return primeCache[hex];var error=0;if(prime.isEven()||!primes.simpleSieve||!primes.fermatTest(prime)||!millerRabin.test(prime))return error+=1,gen===\"02\"||gen===\"05\"\?error+=8:error+=4,primeCache[hex]=error,error;millerRabin.test(prime.shrn(1))||(error+=2);var rem;switch(gen){case\"02\":prime.mod(TWENTYFOUR).cmp(ELEVEN)&&(error+=8);break;case\"05\":rem=prime.mod(TEN),rem.cmp(THREE)&&rem.cmp(SEVEN)&&(error+=8);break;default:error+=4}return primeCache[hex]=error,error}function DH(prime,generator,malleable){this.setGenerator(generator),this.__prime=new BN(prime),this._prime=BN.mont(this.__prime),this._primeLen=prime.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,malleable\?(this.setPublicKey=setPublicKey,this.setPrivateKey=setPrivateKey):this._primeCode=8}DH.prototype={},Object.defineProperty(DH.prototype,\"verifyError\",{enumerable:!0,get:function(){return typeof this._primeCode!=\"number\"&&(this._primeCode=checkPrime(this.__prime,this.__gen)),this._primeCode}}),DH.prototype.generateKeys=function(){return this._priv||(this._priv=new BN(randomBytes(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},DH.prototype.computeSecret=function(other){other=new BN(other),other=other.toRed(this._prime);var secret=other.redPow(this._priv).fromRed(),out=new Buffer(secret.toArray()),prime=this.getPrime();if(out.length=0||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=blind(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,\"be\",len)}crt.getr=getr,module.exports=crt}}),require_package=__commonJS({\"node_modules/elliptic/package.json\"(exports,module){module.exports={name:\"elliptic\",version:\"6.5.4\",description:\"EC cryptography\",main:\"lib/elliptic.js\",files:[\"lib\"],scripts:{lint:\"eslint lib test\",\"lint:fix\":\"npm run lint -- --fix\",unit:\"istanbul test _mocha --reporter=spec test/index.js\",test:\"npm run lint && npm run unit\",version:\"grunt dist && git add dist/\"},repository:{type:\"git\",url:\"git@github.com:indutny/elliptic\"},keywords:[\"EC\",\"Elliptic\",\"curve\",\"Cryptography\"],author:\"Fedor Indutny \",license:\"MIT\",bugs:{url:\"https://github.com/indutny/elliptic/issues\"},homepage:\"https://github.com/indutny/elliptic\",devDependencies:{brfs:\"^2.0.2\",coveralls:\"^3.1.0\",eslint:\"^7.6.0\",grunt:\"^1.2.1\",\"grunt-browserify\":\"^5.3.0\",\"grunt-cli\":\"^1.3.2\",\"grunt-contrib-connect\":\"^3.0.0\",\"grunt-contrib-copy\":\"^1.0.0\",\"grunt-contrib-uglify\":\"^5.0.0\",\"grunt-mocha-istanbul\":\"^5.0.2\",\"grunt-saucelabs\":\"^9.0.1\",istanbul:\"^0.4.5\",mocha:\"^8.0.1\"},dependencies:{\"bn.js\":\"^4.11.9\",brorand:\"^1.1.0\",\"hash.js\":\"^1.0.0\",\"hmac-drbg\":\"^1.0.1\",inherits:\"^2.0.4\",\"minimalistic-assert\":\"^1.0.1\",\"minimalistic-crypto-utils\":\"^1.0.1\"}}}}),require_bn4=require_bn,require_utils2=__commonJS({\"node_modules/minimalistic-crypto-utils/lib/utils.js\"(exports){var utils=exports;function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg!=\"string\"){for(var i=0;i>8,lo=c&255;hi\?res.push(hi,lo):res.push(lo)}return res}utils.toArray=toArray;function zero2(word){return word.length===1\?\"0\"+word:word}utils.zero2=zero2;function toHex(msg){for(var res=\"\",i=0;i(ws>>1)-1\?z=(ws>>1)-mod:z=mod,k.isubn(z)):z=0,naf[i]=z,k.iushrn(1)}return naf}utils.getNAF=getNAF;function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone(),k2=k2.clone();for(var d1=0,d2=0,m8;k1.cmpn(-d1)>0||k2.cmpn(-d2)>0;){var m14=k1.andln(3)+d1&3,m24=k2.andln(3)+d2&3;m14===3&&(m14=-1),m24===3&&(m24=-1);var u1;(m14&1)===0\?u1=0:(m8=k1.andln(7)+d1&7,(m8===3||m8===5)&&m24===2\?u1=-m14:u1=m14),jsf[0].push(u1);var u2;(m24&1)===0\?u2=0:(m8=k2.andln(7)+d2&7,(m8===3||m8===5)&&m14===2\?u2=-m24:u2=m24),jsf[1].push(u2),2*d1===u1+1&&(d1=1-d1),2*d2===u2+1&&(d2=1-d2),k1.iushrn(1),k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key=\"_\"+name;obj.prototype[name]=function(){return this[key]!==void 0\?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==\"string\"\?utils.toArray(bytes,\"hex\"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,\"hex\",\"le\")}utils.intFromLE=intFromLE}}),require_base=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/base.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),getNAF=utils.getNAF,getJSF=utils.getJSF,assert=utils.assert;function BaseCurve(type,conf){this.type=type,this.p=new BN(conf.p,16),this.red=conf.prime\?BN.red(conf.prime):BN.mont(this.p),this.zero=new BN(0).toRed(this.red),this.one=new BN(1).toRed(this.red),this.two=new BN(2).toRed(this.red),this.n=conf.n&&new BN(conf.n,16),this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n\?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);!adjustCount||adjustCount.cmpn(100)>0\?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}module.exports=BaseCurve,BaseCurve.prototype={},BaseCurve.prototype.point=function(){throw new Error(\"Not implemented\")},BaseCurve.prototype.validate=function(){throw new Error(\"Not implemented\")},BaseCurve.prototype._fixedNafMul=function(p,k){assert(p.precomputed);var doubles=p._getDoubles(),naf=getNAF(k,1,this._bitLength),I=(1<=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}for(var a=this.jpoint(null,null,null),b=this.jpoint(null,null,null),i=I;i>0;i--){for(j=0;j=0;i--){for(var l=0;i>=0&&naf[i]===0;i--)l++;if(i>=0&&l++,acc=acc.dblp(l),i<0)break;var z=naf[i];assert(z!==0),p.type===\"affine\"\?z>0\?acc=acc.mixedAdd(wnd[z-1>>1]):acc=acc.mixedAdd(wnd[-z-1>>1].neg()):z>0\?acc=acc.add(wnd[z-1>>1]):acc=acc.add(wnd[-z-1>>1].neg())}return p.type===\"affine\"\?acc.toP():acc},BaseCurve.prototype._wnafMulAdd=function(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1,wnd=this._wnafT2,naf=this._wnafT3,max=0,i,j,p;for(i=0;i=1;i-=2){var a=i-1,b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a],this._bitLength),naf[b]=getNAF(coeffs[b],wndWidth[b],this._bitLength),max=Math.max(naf[a].length,max),max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];points[a].y.cmp(points[b].y)===0\?(comb[1]=points[a].add(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg())):points[a].y.cmp(points[b].y.redNeg())===0\?(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].add(points[b].neg())):(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg()));var index=[-3,-1,-5,-7,0,7,5,1,3],jsf=getJSF(coeffs[a],coeffs[b]);for(max=Math.max(jsf[0].length,max),naf[a]=new Array(max),naf[b]=new Array(max),j=0;j=0;i--){for(var k=0;i>=0;){var zero=!0;for(j=0;j=0&&k++,acc=acc.dblp(k),i<0)break;for(j=0;j0\?p=wnd[j][z-1>>1]:z<0&&(p=wnd[j][-z-1>>1].neg()),p.type===\"affine\"\?acc=acc.mixedAdd(p):acc=acc.add(p))}}for(i=0;i=Math.ceil((k.bitLength()+1)/doubles.step):!1},BasePoint.prototype._getDoubles=function(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var doubles=[this],acc=this,i=0;i=0&&(a2=a0,b2=b0),a1.negative&&(a1=a1.neg(),b1=b1.neg()),a2.negative&&(a2=a2.neg(),b2=b2.neg()),[{a:a1,b:b1},{a:a2,b:b2}]},ShortCurve.prototype._endoSplit=function(k){var basis=this.endo.basis,v1=basis[0],v2=basis[1],c1=v2.b.mul(k).divRound(this.n),c2=v1.b.neg().mul(k).divRound(this.n),p1=c1.mul(v1.a),p2=c2.mul(v2.a),q1=c1.mul(v1.b),q2=c2.mul(v2.b),k1=k.sub(p1).sub(p2),k2=q1.add(q2).neg();return{k1,k2}},ShortCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b),y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error(\"invalid point\");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},ShortCurve.prototype.validate=function(point){if(point.inf)return!0;var{x,y}=point,ax=this.a.redMul(x),rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0},ShortCurve.prototype._endoWnafMulAdd=function(points,coeffs,jacobianResult){for(var npoints=this._endoWnafT1,ncoeffs=this._endoWnafT2,i=0;i\":\"\"},Point.prototype.isInfinity=function(){return this.inf},Point.prototype.add=function(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);c.cmpn(0)!==0&&(c=c.redMul(this.x.redSub(p.x).redInvm()));var nx=c.redSqr().redISub(this.x).redISub(p.x),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.dbl=function(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a,x2=this.x.redSqr(),dyinv=ys1.redInvm(),c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv),nx=c.redSqr().redISub(this.x.redAdd(this.x)),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.getX=function(){return this.x.fromRed()},Point.prototype.getY=function(){return this.y.fromRed()},Point.prototype.mul=function(k){return k=new BN(k,16),this.isInfinity()\?this:this._hasDoubles(k)\?this.curve._fixedNafMul(this,k):this.curve.endo\?this.curve._endoWnafMulAdd([this],[k]):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo\?this.curve._endoWnafMulAdd(points,coeffs):this.curve._wnafMulAdd(1,points,coeffs,2)},Point.prototype.jmulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo\?this.curve._endoWnafMulAdd(points,coeffs,!0):this.curve._wnafMulAdd(1,points,coeffs,2,!0)},Point.prototype.eq=function(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)},Point.prototype.neg=function(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed,negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res},Point.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,\"jacobian\"),x===null&&y===null&&z===null\?(this.x=this.curve.one,this.y=this.curve.one,this.z=new BN(0)):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=new BN(z,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}inherits(JPoint,Base.BasePoint),ShortCurve.prototype.jpoint=function(x,y,z){return new JPoint(this,x,y,z)},JPoint.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm(),zinv2=zinv.redSqr(),ax=this.x.redMul(zinv2),ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)},JPoint.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},JPoint.prototype.add=function(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr(),z2=this.z.redSqr(),u1=this.x.redMul(pz2),u2=p.x.redMul(z2),s1=this.y.redMul(pz2.redMul(p.z)),s2=p.y.redMul(z2.redMul(this.z)),h=u1.redSub(u2),r=s1.redSub(s2);if(h.cmpn(0)===0)return r.cmpn(0)!==0\?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.mixedAdd=function(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr(),u1=this.x,u2=p.x.redMul(z2),s1=this.y,s2=p.y.redMul(z2).redMul(this.z),h=u1.redSub(u2),r=s1.redSub(s2);if(h.cmpn(0)===0)return r.cmpn(0)!==0\?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.dblp=function(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i=0)return!1;if(rx.redIAdd(t),this.x.cmp(rx)===0)return!0}},JPoint.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},JPoint.prototype.isInfinity=function(){return this.z.cmpn(0)===0}}}),require_mont=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/mont.js\"(exports,module){var BN=require_bn4(),inherits=require_inherits_browser(),Base=require_base(),utils=require_utils3();function MontCurve(conf){Base.call(this,\"mont\",conf),this.a=new BN(conf.a,16).toRed(this.red),this.b=new BN(conf.b,16).toRed(this.red),this.i4=new BN(4).toRed(this.red).redInvm(),this.two=new BN(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits(MontCurve,Base),module.exports=MontCurve,MontCurve.prototype.validate=function(point){var x=point.normalize().x,x2=x.redSqr(),rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x),y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point(curve,x,z){Base.BasePoint.call(this,curve,\"projective\"),x===null&&z===null\?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new BN(x,16),this.z=new BN(z,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}inherits(Point,Base.BasePoint),MontCurve.prototype.decodePoint=function(bytes,enc){return this.point(utils.toArray(bytes,enc),1)},MontCurve.prototype.point=function(x,z){return new Point(this,x,z)},MontCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},Point.prototype.precompute=function(){},Point.prototype._encode=function(){return this.getX().toArray(\"be\",this.curve.p.byteLength())},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)},Point.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},Point.prototype.isInfinity=function(){return this.z.cmpn(0)===0},Point.prototype.dbl=function(){var a=this.x.redAdd(this.z),aa=a.redSqr(),b=this.x.redSub(this.z),bb=b.redSqr(),c=aa.redSub(bb),nx=aa.redMul(bb),nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)},Point.prototype.add=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.diffAdd=function(p,diff){var a=this.x.redAdd(this.z),b=this.x.redSub(this.z),c=p.x.redAdd(p.z),d=p.x.redSub(p.z),da=d.redMul(a),cb=c.redMul(b),nx=diff.z.redMul(da.redAdd(cb).redSqr()),nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)},Point.prototype.mul=function(k){for(var t=k.clone(),a=this,b=this.curve.point(null,null),c=this,bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--)bits[i]===0\?(a=a.diffAdd(b,c),b=b.dbl()):(b=a.diffAdd(b,c),a=a.dbl());return b},Point.prototype.mulAdd=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.jumlAdd=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.eq=function(other){return this.getX().cmp(other.getX())===0},Point.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()}}}),require_edwards=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/edwards.js\"(exports,module){var utils=require_utils3(),BN=require_bn4(),inherits=require_inherits_browser(),Base=require_base(),assert=utils.assert;function EdwardsCurve(conf){this.twisted=(conf.a|0)!==1,this.mOneA=this.twisted&&(conf.a|0)===-1,this.extended=this.mOneA,Base.call(this,\"edwards\",conf),this.a=new BN(conf.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new BN(conf.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new BN(conf.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),assert(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(conf.c|0)===1}inherits(EdwardsCurve,Base),module.exports=EdwardsCurve,EdwardsCurve.prototype._mulA=function(num){return this.mOneA\?num.redNeg():this.a.redMul(num)},EdwardsCurve.prototype._mulC=function(num){return this.oneC\?num:this.c.redMul(num)},EdwardsCurve.prototype.jpoint=function(x,y,z,t){return this.point(x,y,z,t)},EdwardsCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var x2=x.redSqr(),rhs=this.c2.redSub(this.a.redMul(x2)),lhs=this.one.redSub(this.c2.redMul(this.d).redMul(x2)),y2=rhs.redMul(lhs.redInvm()),y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error(\"invalid point\");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},EdwardsCurve.prototype.pointFromY=function(y,odd){y=new BN(y,16),y.red||(y=y.toRed(this.red));var y2=y.redSqr(),lhs=y2.redSub(this.c2),rhs=y2.redMul(this.d).redMul(this.c2).redSub(this.a),x2=lhs.redMul(rhs.redInvm());if(x2.cmp(this.zero)===0){if(odd)throw new Error(\"invalid point\");return this.point(this.zero,y)}var x=x2.redSqrt();if(x.redSqr().redSub(x2).cmp(this.zero)!==0)throw new Error(\"invalid point\");return x.fromRed().isOdd()!==odd&&(x=x.redNeg()),this.point(x,y)},EdwardsCurve.prototype.validate=function(point){if(point.isInfinity())return!0;point.normalize();var x2=point.x.redSqr(),y2=point.y.redSqr(),lhs=x2.redMul(this.a).redAdd(y2),rhs=this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));return lhs.cmp(rhs)===0};function Point(curve,x,y,z,t){Base.BasePoint.call(this,curve,\"projective\"),x===null&&y===null&&z===null\?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=z\?new BN(z,16):this.curve.one,this.t=t&&new BN(t,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}inherits(Point,Base.BasePoint),EdwardsCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},EdwardsCurve.prototype.point=function(x,y,z,t){return new Point(this,x,y,z,t)},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1],obj[2])},Point.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},Point.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},Point.prototype._extDbl=function(){var a=this.x.redSqr(),b=this.y.redSqr(),c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a),e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b),g=d.redAdd(b),f=g.redSub(c),h=d.redSub(b),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projDbl=function(){var b=this.x.redAdd(this.y).redSqr(),c=this.x.redSqr(),d=this.y.redSqr(),nx,ny,nz,e,h,j;if(this.curve.twisted){e=this.curve._mulA(c);var f=e.redAdd(d);this.zOne\?(nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)),ny=f.redMul(e.redSub(d)),nz=f.redSqr().redSub(f).redSub(f)):(h=this.z.redSqr(),j=f.redSub(h).redISub(h),nx=b.redSub(c).redISub(d).redMul(j),ny=f.redMul(e.redSub(d)),nz=f.redMul(j))}else e=c.redAdd(d),h=this.curve._mulC(this.z).redSqr(),j=e.redSub(h).redSub(h),nx=this.curve._mulC(b.redISub(e)).redMul(j),ny=this.curve._mulC(e).redMul(c.redISub(d)),nz=e.redMul(j);return this.curve.point(nx,ny,nz)},Point.prototype.dbl=function(){return this.isInfinity()\?this:this.curve.extended\?this._extDbl():this._projDbl()},Point.prototype._extAdd=function(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x)),b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)),c=this.t.redMul(this.curve.dd).redMul(p.t),d=this.z.redMul(p.z.redAdd(p.z)),e=b.redSub(a),f=d.redSub(c),g=d.redAdd(c),h=b.redAdd(a),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projAdd=function(p){var a=this.z.redMul(p.z),b=a.redSqr(),c=this.x.redMul(p.x),d=this.y.redMul(p.y),e=this.curve.d.redMul(c).redMul(d),f=b.redSub(e),g=b.redAdd(e),tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d),nx=a.redMul(f).redMul(tmp),ny,nz;return this.curve.twisted\?(ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c))),nz=f.redMul(g)):(ny=a.redMul(g).redMul(d.redSub(c)),nz=this.curve._mulC(f).redMul(g)),this.curve.point(nx,ny,nz)},Point.prototype.add=function(p){return this.isInfinity()\?p:p.isInfinity()\?this:this.curve.extended\?this._extAdd(p):this._projAdd(p)},Point.prototype.mul=function(k){return this._hasDoubles(k)\?this.curve._fixedNafMul(this,k):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!1)},Point.prototype.jmulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!0)},Point.prototype.normalize=function(){if(this.zOne)return this;var zi=this.z.redInvm();return this.x=this.x.redMul(zi),this.y=this.y.redMul(zi),this.t&&(this.t=this.t.redMul(zi)),this.z=this.curve.one,this.zOne=!0,this},Point.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Point.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Point.prototype.eq=function(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0},Point.prototype.eqXToP=function(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return!0;for(var xc=x.clone(),t=this.curve.redN.redMul(this.z);;){if(xc.iadd(this.curve.n),xc.cmp(this.curve.p)>=0)return!1;if(rx.redIAdd(t),this.x.cmp(rx)===0)return!0}},Point.prototype.toP=Point.prototype.normalize,Point.prototype.mixedAdd=Point.prototype.add}}),require_curve=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/index.js\"(exports){var curve=exports;curve.base=require_base(),curve.short=require_short(),curve.mont=require_mont(),curve.edwards=require_edwards()}}),require_utils4=__commonJS({\"node_modules/hash.js/lib/hash/utils.js\"(exports){var assert=require_minimalistic_assert(),inherits=require_inherits_browser();exports.inherits=inherits;function isSurrogatePair(msg,i){return(msg.charCodeAt(i)&64512)!==55296||i<0||i+1>=msg.length\?!1:(msg.charCodeAt(i+1)&64512)===56320}function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg==\"string\")if(enc){if(enc===\"hex\")for(msg=msg.replace(/[^a-z0-9]+/gi,\"\"),msg.length%2!==0&&(msg=\"0\"+msg),i=0;i>6|192,res[p++]=c&63|128):isSurrogatePair(msg,i)\?(c=65536+((c&1023)<<10)+(msg.charCodeAt(++i)&1023),res[p++]=c>>18|240,res[p++]=c>>12&63|128,res[p++]=c>>6&63|128,res[p++]=c&63|128):(res[p++]=c>>12|224,res[p++]=c>>6&63|128,res[p++]=c&63|128)}else for(i=0;i>>24|w>>>8&65280|w<<8&16711680|(w&255)<<24;return res>>>0}exports.htonl=htonl;function toHex32(msg,endian){for(var res=\"\",i=0;i>>0}return res}exports.join32=join32;function split32(msg,endian){for(var res=new Array(msg.length*4),i=0,k=0;i>>24,res[k+1]=m>>>16&255,res[k+2]=m>>>8&255,res[k+3]=m&255):(res[k+3]=m>>>24,res[k+2]=m>>>16&255,res[k+1]=m>>>8&255,res[k]=m&255)}return res}exports.split32=split32;function rotr32(w,b){return w>>>b|w<<32-b}exports.rotr32=rotr32;function rotl32(w,b){return w<>>32-b}exports.rotl32=rotl32;function sum32(a,b){return a+b>>>0}exports.sum32=sum32;function sum32_3(a,b,c){return a+b+c>>>0}exports.sum32_3=sum32_3;function sum32_4(a,b,c,d){return a+b+c+d>>>0}exports.sum32_4=sum32_4;function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}exports.sum32_5=sum32_5;function sum64(buf,pos,ah,al){var bh=buf[pos],bl=buf[pos+1],lo=al+bl>>>0,hi=(lo>>0,buf[pos+1]=lo}exports.sum64=sum64;function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0,hi=(lo>>0}exports.sum64_hi=sum64_hi;function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}exports.sum64_lo=sum64_lo;function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}exports.sum64_4_hi=sum64_4_hi;function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}exports.sum64_4_lo=sum64_4_lo;function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}exports.sum64_5_hi=sum64_5_hi;function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}exports.sum64_5_lo=sum64_5_lo;function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}exports.rotr64_hi=rotr64_hi;function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.rotr64_lo=rotr64_lo;function shr64_hi(ah,al,num){return ah>>>num}exports.shr64_hi=shr64_hi;function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.shr64_lo=shr64_lo}}),require_common=__commonJS({\"node_modules/hash.js/lib/hash/common.js\"(exports){var utils=require_utils4(),assert=require_minimalistic_assert();function BlockHash(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian=\"big\",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}BlockHash.prototype={},exports.BlockHash=BlockHash,BlockHash.prototype.update=function(msg,enc){if(msg=utils.toArray(msg,enc),this.pending\?this.pending=this.pending.concat(msg):this.pending=msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),this.pending.length===0&&(this.pending=null),msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i>>24&255,res[i++]=len>>>16&255,res[i++]=len>>>8&255,res[i++]=len&255}else for(res[i++]=len&255,res[i++]=len>>>8&255,res[i++]=len>>>16&255,res[i++]=len>>>24&255,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,t=8;t>>3}exports.g0_256=g0_256;function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}exports.g1_256=g1_256}}),require__=__commonJS({\"node_modules/hash.js/lib/hash/sha/1.js\"(exports,module){var utils=require_utils4(),common=require_common(),shaCommon=require_common2(),rotl32=utils.rotl32,sum32=utils.sum32,sum32_5=utils.sum32_5,ft_1=shaCommon.ft_1,BlockHash=common.BlockHash,sha1_K=[1518500249,1859775393,2400959708,3395469782];function SHA1(){if(!(this instanceof SHA1))return new SHA1;BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}utils.inherits(SHA1,BlockHash),module.exports=SHA1,SHA1.blockSize=512,SHA1.outSize=160,SHA1.hmacStrength=80,SHA1.padLength=64,SHA1.prototype._update=function(msg,start){for(var W=this.W,i=0;i<16;i++)W[i]=msg[start+i];for(;ithis.blockSize&&(key=new this.Hash().update(key).digest()),assert(key.length<=this.blockSize);for(var i=key.length;i=this.minEntropy/8,\"Not enough entropy. Minimum is: \"+this.minEntropy+\" bits\"),this._init(entropy,nonce,pers)}HmacDRBG.prototype={},module.exports=HmacDRBG,HmacDRBG.prototype._init=function(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,\"Not enough entropy. Minimum is: \"+this.minEntropy+\" bits\"),this._update(entropy.concat(add||[])),this._reseed=1},HmacDRBG.prototype.generate=function(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error(\"Reseed is required\");typeof enc!=\"string\"&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc||\"hex\"),this._update(add));for(var temp=[];temp.length\"}}}),require_signature=__commonJS({\"node_modules/elliptic/lib/elliptic/ec/signature.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),assert=utils.assert;function Signature(options,enc){if(options instanceof Signature)return options;this._importDER(options,enc)||(assert(options.r&&options.s,\"Signature without r or s\"),this.r=new BN(options.r,16),this.s=new BN(options.s,16),options.recoveryParam===void 0\?this.recoveryParam=null:this.recoveryParam=options.recoveryParam)}Signature.prototype={},module.exports=Signature;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128))return initial;var octetLen=initial&15;if(octetLen===0||octetLen>4)return!1;for(var val=0,i=0,off=p.place;i>>=0;return val<=127\?!1:(p.place=off,val)}function rmPadding(buf){for(var i=0,len=buf.length-1;!buf[i]&&!(buf[i+1]&128)&&i>>3);for(arr.push(octets|128);--octets;)arr.push(len>>>(octets<<3)&255);arr.push(len)}Signature.prototype.toDER=function(enc){var r=this.r.toArray(),s=this.s.toArray();for(r[0]&128&&(r=[0].concat(r)),s[0]&128&&(s=[0].concat(s)),r=rmPadding(r),s=rmPadding(s);!s[0]&&!(s[1]&128);)s=s.slice(1);var arr=[2];constructLength(arr,r.length),arr=arr.concat(r),arr.push(2),constructLength(arr,s.length);var backHalf=arr.concat(s),res=[48];return constructLength(res,backHalf.length),res=res.concat(backHalf),utils.encode(res,enc)}}}),require_ec=__commonJS({\"node_modules/elliptic/lib/elliptic/ec/index.js\"(exports,module){var BN=require_bn4(),HmacDRBG=require_hmac_drbg(),utils=require_utils3(),curves=require_curves(),rand=require_brorand(),assert=utils.assert,KeyPair=require_key(),Signature=require_signature();function EC(options){if(!(this instanceof EC))return new EC(options);typeof options==\"string\"&&(assert(Object.prototype.hasOwnProperty.call(curves,options),\"Unknown curve \"+options),options=curves[options]),options instanceof curves.PresetCurve&&(options={curve:options}),this.curve=options.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=options.curve.g,this.g.precompute(options.curve.n.bitLength()+1),this.hash=options.hash||options.curve.hash}EC.prototype={},module.exports=EC,EC.prototype.keyPair=function(options){return new KeyPair(this,options)},EC.prototype.keyFromPrivate=function(priv,enc){return KeyPair.fromPrivate(this,priv,enc)},EC.prototype.keyFromPublic=function(pub,enc){return KeyPair.fromPublic(this,pub,enc)},EC.prototype.genKeyPair=function(options){options||(options={});for(var drbg=new HmacDRBG({hash:this.hash,pers:options.pers,persEnc:options.persEnc||\"utf8\",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||\"utf8\",nonce:this.n.toArray()}),bytes=this.n.byteLength(),ns2=this.n.sub(new BN(2));;){var priv=new BN(drbg.generate(bytes));if(!(priv.cmp(ns2)>0))return priv.iaddn(1),this.keyFromPrivate(priv)}},EC.prototype._truncateToN=function(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();return delta>0&&(msg=msg.ushrn(delta)),!truncOnly&&msg.cmp(this.n)>=0\?msg.sub(this.n):msg},EC.prototype.sign=function(msg,key,enc,options){typeof enc==\"object\"&&(options=enc,enc=null),options||(options={}),key=this.keyFromPrivate(key,enc),msg=this._truncateToN(new BN(msg,16));for(var bytes=this.n.byteLength(),bkey=key.getPrivate().toArray(\"be\",bytes),nonce=msg.toArray(\"be\",bytes),drbg=new HmacDRBG({hash:this.hash,entropy:bkey,nonce,pers:options.pers,persEnc:options.persEnc||\"utf8\"}),ns1=this.n.sub(new BN(1)),iter=0;;iter++){var k=options.k\?options.k(iter):new BN(drbg.generate(this.n.byteLength()));if(k=this._truncateToN(k,!0),!(k.cmpn(1)<=0||k.cmp(ns1)>=0)){var kp=this.g.mul(k);if(!kp.isInfinity()){var kpX=kp.getX(),r=kpX.umod(this.n);if(r.cmpn(0)!==0){var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));if(s=s.umod(this.n),s.cmpn(0)!==0){var recoveryParam=(kp.getY().isOdd()\?1:0)|(kpX.cmp(r)!==0\?2:0);return options.canonical&&s.cmp(this.nh)>0&&(s=this.n.sub(s),recoveryParam^=1),new Signature({r,s,recoveryParam})}}}}}},EC.prototype.verify=function(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16)),key=this.keyFromPublic(key,enc),signature=new Signature(signature,\"hex\");var{r,s}=signature;if(r.cmpn(1)<0||r.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var sinv=s.invm(this.n),u1=sinv.mul(msg).umod(this.n),u2=sinv.mul(r).umod(this.n),p;return this.curve._maxwellTrick\?(p=this.g.jmulAdd(u1,key.getPublic(),u2),p.isInfinity()\?!1:p.eqXToP(r)):(p=this.g.mulAdd(u1,key.getPublic(),u2),p.isInfinity()\?!1:p.getX().umod(this.n).cmp(r)===0)},EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,\"The recovery param is more than two bits\"),signature=new Signature(signature,enc);var n=this.n,e=new BN(msg),r=signature.r,s=signature.s,isYOdd=j&1,isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error(\"Unable to find sencond key candinate\");isSecondKey\?r=this.curve.pointFromX(r.add(this.curve.n),isYOdd):r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n),s1=n.sub(e).mul(rInv).umod(n),s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)},EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){if(signature=new Signature(signature,enc),signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch{continue}if(Qprime.eq(Q))return i}throw new Error(\"Unable to find valid recovery factor\")}}}),require_key2=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/key.js\"(exports,module){var utils=require_utils3(),assert=utils.assert,parseBytes=utils.parseBytes,cachedProperty=utils.cachedProperty;function KeyPair(eddsa,params){this.eddsa=eddsa,this._secret=parseBytes(params.secret),eddsa.isPoint(params.pub)\?this._pub=params.pub:this._pubBytes=parseBytes(params.pub)}KeyPair.prototype={},KeyPair.fromPublic=function(eddsa,pub){return pub instanceof KeyPair\?pub:new KeyPair(eddsa,{pub})},KeyPair.fromSecret=function(eddsa,secret){return secret instanceof KeyPair\?secret:new KeyPair(eddsa,{secret})},KeyPair.prototype.secret=function(){return this._secret},cachedProperty(KeyPair,\"pubBytes\",function(){return this.eddsa.encodePoint(this.pub())}),cachedProperty(KeyPair,\"pub\",function(){return this._pubBytes\?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())}),cachedProperty(KeyPair,\"privBytes\",function(){var eddsa=this.eddsa,hash=this.hash(),lastIx=eddsa.encodingLength-1,a=hash.slice(0,eddsa.encodingLength);return a[0]&=248,a[lastIx]&=127,a[lastIx]|=64,a}),cachedProperty(KeyPair,\"priv\",function(){return this.eddsa.decodeInt(this.privBytes())}),cachedProperty(KeyPair,\"hash\",function(){return this.eddsa.hash().update(this.secret()).digest()}),cachedProperty(KeyPair,\"messagePrefix\",function(){return this.hash().slice(this.eddsa.encodingLength)}),KeyPair.prototype.sign=function(message){return assert(this._secret,\"KeyPair can only verify\"),this.eddsa.sign(message,this)},KeyPair.prototype.verify=function(message,sig){return this.eddsa.verify(message,sig,this)},KeyPair.prototype.getSecret=function(enc){return assert(this._secret,\"KeyPair is public only\"),utils.encode(this.secret(),enc)},KeyPair.prototype.getPublic=function(enc){return utils.encode(this.pubBytes(),enc)},module.exports=KeyPair}}),require_signature2=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/signature.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),assert=utils.assert,cachedProperty=utils.cachedProperty,parseBytes=utils.parseBytes;function Signature(eddsa,sig){this.eddsa=eddsa,typeof sig!=\"object\"&&(sig=parseBytes(sig)),Array.isArray(sig)&&(sig={R:sig.slice(0,eddsa.encodingLength),S:sig.slice(eddsa.encodingLength)}),assert(sig.R&&sig.S,\"Signature without R or S\"),eddsa.isPoint(sig.R)&&(this._R=sig.R),sig.S instanceof BN&&(this._S=sig.S),this._Rencoded=Array.isArray(sig.R)\?sig.R:sig.Rencoded,this._Sencoded=Array.isArray(sig.S)\?sig.S:sig.Sencoded}Signature.prototype={},cachedProperty(Signature,\"S\",function(){return this.eddsa.decodeInt(this.Sencoded())}),cachedProperty(Signature,\"R\",function(){return this.eddsa.decodePoint(this.Rencoded())}),cachedProperty(Signature,\"Rencoded\",function(){return this.eddsa.encodePoint(this.R())}),cachedProperty(Signature,\"Sencoded\",function(){return this.eddsa.encodeInt(this.S())}),Signature.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Signature.prototype.toHex=function(){return utils.encode(this.toBytes(),\"hex\").toUpperCase()},module.exports=Signature}}),require_eddsa=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/index.js\"(exports,module){var hash=require_hash2(),curves=require_curves(),utils=require_utils3(),assert=utils.assert,parseBytes=utils.parseBytes,KeyPair=require_key2(),Signature=require_signature2();function EDDSA(curve){if(assert(curve===\"ed25519\",\"only tested with ed25519 so far\"),!(this instanceof EDDSA))return new EDDSA(curve);curve=curves[curve].curve,this.curve=curve,this.g=curve.g,this.g.precompute(curve.n.bitLength()+1),this.pointClass=curve.point().constructor,this.encodingLength=Math.ceil(curve.n.bitLength()/8),this.hash=hash.sha512}EDDSA.prototype={},module.exports=EDDSA,EDDSA.prototype.sign=function(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret),r=this.hashInt(key.messagePrefix(),message),R=this.g.mul(r),Rencoded=this.encodePoint(R),s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv()),S=r.add(s_).umod(this.curve.n);return this.makeSignature({R,S,Rencoded})},EDDSA.prototype.verify=function(message,sig,pub){message=parseBytes(message),sig=this.makeSignature(sig);var key=this.keyFromPublic(pub),h=this.hashInt(sig.Rencoded(),key.pubBytes(),message),SG=this.g.mul(sig.S()),RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)},EDDSA.prototype.hashInt=function(){for(var hash2=this.hash(),i=0;i\"u\")@throwTypeError(\"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type \"+typeof value);return Buffer2(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if(typeof size!=\"number\")@throwTypeError('The \"size\" argument must be of type number. Received type '+typeof size);if(size<0||size>=2*(1<<30))@throwRangeError('The value \"'+size+'\" is invalid for option \"size\"');var buf=Buffer2(size);return!fill||fill.length===0\?buf.fill(0):typeof encoding==\"string\"\?buf.fill(fill,encoding):buf.fill(fill),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=MAX_STRING_LENGTH}catch{}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}}),require_reporter=__commonJS({\"node_modules/asn1.js/lib/asn1/base/reporter.js\"(exports){var inherits=require_inherits_browser();function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}Reporter.prototype={},exports.Reporter=Reporter,Reporter.prototype.isError=function(obj){return obj instanceof ReporterError},Reporter.prototype.save=function(){let state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function(data){let state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function(index){let state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function(index,key,value){let state=this._reporterState;this.exitKey(index),state.obj!==null&&(state.obj[key]=value)},Reporter.prototype.path=function(){return this._reporterState.path.join(\"/\")},Reporter.prototype.enterObject=function(){let state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function(prev){let state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function(msg){let err,state=this._reporterState,inherited=msg instanceof ReporterError;if(inherited\?err=msg:err=new ReporterError(state.path.map(function(elem){return\"[\"+JSON.stringify(elem)+\"]\"}).join(\"\"),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function(result){let state=this._reporterState;return state.options.partial\?{result:this.isError(result)\?null:result,errors:state.errors}:result};function ReporterError(path,msg){this.path=path,this.rethrow(msg)}inherits(ReporterError,Error),ReporterError.prototype.rethrow=function(msg){if(this.message=msg+\" at: \"+(this.path||\"(shallow)\"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}}}),require_buffer=__commonJS({\"node_modules/asn1.js/lib/asn1/base/buffer.js\"(exports){var inherits=require_inherits_browser(),Reporter=require_reporter().Reporter,Buffer2=require_safer().Buffer;function DecoderBuffer(base,options){if(Reporter.call(this,options),!Buffer2.isBuffer(base)){this.error(\"Input not Buffer\");return}this.base=base,this.offset=0,this.length=base.length}inherits(DecoderBuffer,Reporter),exports.DecoderBuffer=DecoderBuffer,DecoderBuffer.isDecoderBuffer=function(data){return data instanceof DecoderBuffer\?!0:typeof data==\"object\"&&Buffer2.isBuffer(data.base)&&data.constructor.name===\"DecoderBuffer\"&&typeof data.offset==\"number\"&&typeof data.length==\"number\"&&typeof data.save==\"function\"&&typeof data.restore==\"function\"&&typeof data.isEmpty==\"function\"&&typeof data.readUInt8==\"function\"&&typeof data.skip==\"function\"&&typeof data.raw==\"function\"},DecoderBuffer.prototype.save=function(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function(save){let res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function(fail){return this.offset+1<=this.length\?this.base.readUInt8(this.offset++,!0):this.error(fail||\"DecoderBuffer overrun\")},DecoderBuffer.prototype.skip=function(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||\"DecoderBuffer overrun\");let res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function(save){return this.base.slice(save\?save.offset:this.offset,this.length)};function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return EncoderBuffer.isEncoderBuffer(item)||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if(typeof value==\"number\"){if(!(0<=value&&value<=255))return reporter.error(\"non-byte EncoderBuffer value\");this.value=value,this.length=1}else if(typeof value==\"string\")this.value=value,this.length=Buffer2.byteLength(value);else if(Buffer2.isBuffer(value))this.value=value,this.length=value.length;else return reporter.error(\"Unsupported type: \"+typeof value)}EncoderBuffer.prototype={},exports.EncoderBuffer=EncoderBuffer,EncoderBuffer.isEncoderBuffer=function(data){return data instanceof EncoderBuffer\?!0:typeof data==\"object\"&&data.constructor.name===\"EncoderBuffer\"&&typeof data.length==\"number\"&&typeof data.join==\"function\"},EncoderBuffer.prototype.join=function(out,offset){return out||(out=Buffer2.alloc(this.length)),offset||(offset=0),this.length===0||(Array.isArray(this.value)\?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):(typeof this.value==\"number\"\?out[offset]=this.value:typeof this.value==\"string\"\?out.write(this.value,offset):Buffer2.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length)),out}}}),require_node=__commonJS({\"node_modules/asn1.js/lib/asn1/base/node.js\"(exports,module){var Reporter=require_reporter().Reporter,EncoderBuffer=require_buffer().EncoderBuffer,DecoderBuffer=require_buffer().DecoderBuffer,assert=require_minimalistic_assert(),tags=[\"seq\",\"seqof\",\"set\",\"setof\",\"objid\",\"bool\",\"gentime\",\"utctime\",\"null_\",\"enum\",\"int\",\"objDesc\",\"bitstr\",\"bmpstr\",\"charstr\",\"genstr\",\"graphstr\",\"ia5str\",\"iso646str\",\"numstr\",\"octstr\",\"printstr\",\"t61str\",\"unistr\",\"utf8str\",\"videostr\"],methods=[\"key\",\"obj\",\"use\",\"optional\",\"explicit\",\"implicit\",\"def\",\"choice\",\"any\",\"contains\"].concat(tags),overrided=[\"_peekTag\",\"_decodeTag\",\"_use\",\"_decodeStr\",\"_decodeObjid\",\"_decodeTime\",\"_decodeNull\",\"_decodeInt\",\"_decodeBool\",\"_decodeList\",\"_encodeComposite\",\"_encodeStr\",\"_encodeObjid\",\"_encodeTime\",\"_encodeNull\",\"_encodeInt\",\"_encodeBool\"];function Node(enc,parent,name){let state={};this._baseState=state,state.name=name,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state.default=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}Node.prototype={},module.exports=Node;var stateProps=[\"enc\",\"parent\",\"children\",\"tag\",\"args\",\"reverseArgs\",\"choice\",\"optional\",\"any\",\"obj\",\"use\",\"alteredUse\",\"key\",\"default\",\"explicit\",\"implicit\",\"contains\"];Node.prototype.clone=function(){let state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});let res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function(){let state=this._baseState;methods.forEach(function(method){this[method]=function(){let clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function(body){let state=this._baseState;assert(state.parent===null),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,\"Root node can have only one child\")},Node.prototype._useArgs=function(args){let state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),children.length!==0&&(assert(state.children===null),state.children=children,children.forEach(function(child){child._baseState.parent=this},this)),args.length!==0&&(assert(state.args===null),state.args=args,state.reverseArgs=args.map(function(arg){if(typeof arg!=\"object\"||arg.constructor!==Object)return arg;let res={};return Object.keys(arg).forEach(function(key){key==(key|0)&&(key|=0);let value=arg[key];res[value]=key}),res}))},overrided.forEach(function(method){Node.prototype[method]=function(){let state=this._baseState;throw new Error(method+\" not implemented for encoding: \"+state.enc)}}),tags.forEach(function(tag){Node.prototype[tag]=function(){let state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(state.tag===null),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function(item){assert(item);let state=this._baseState;return assert(state.use===null),state.use=item,this},Node.prototype.optional=function(){let state=this._baseState;return state.optional=!0,this},Node.prototype.def=function(val){let state=this._baseState;return assert(state.default===null),state.default=val,state.optional=!0,this},Node.prototype.explicit=function(num){let state=this._baseState;return assert(state.explicit===null&&state.implicit===null),state.explicit=num,this},Node.prototype.implicit=function(num){let state=this._baseState;return assert(state.explicit===null&&state.implicit===null),state.implicit=num,this},Node.prototype.obj=function(){let state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,args.length!==0&&this._useArgs(args),this},Node.prototype.key=function(newKey){let state=this._baseState;return assert(state.key===null),state.key=newKey,this},Node.prototype.any=function(){let state=this._baseState;return state.any=!0,this},Node.prototype.choice=function(obj){let state=this._baseState;return assert(state.choice===null),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function(item){let state=this._baseState;return assert(state.use===null),state.contains=item,this},Node.prototype._decode=function(input,options){let state=this._baseState;if(state.parent===null)return input.wrapResult(state.children[0]._decode(input,options));let result=state.default,present=!0,prevKey=null;if(state.key!==null&&(prevKey=input.enterKey(state.key)),state.optional){let tag=null;if(state.explicit!==null\?tag=state.explicit:state.implicit!==null\?tag=state.implicit:state.tag!==null&&(tag=state.tag),tag===null&&!state.any){let save=input.save();try{state.choice===null\?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch{present=!1}input.restore(save)}else if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}let prevObj;if(state.obj&&present&&(prevObj=input.enterObject()),present){if(state.explicit!==null){let explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}let start=input.offset;if(state.use===null&&state.choice===null){let save;state.any&&(save=input.save());let body=this._decodeTag(input,state.implicit!==null\?state.implicit:state.tag,state.any);if(input.isError(body))return body;state.any\?result=input.raw(save):input=body}if(options&&options.track&&state.tag!==null&&options.track(input.path(),start,input.length,\"tagged\"),options&&options.track&&state.tag!==null&&options.track(input.path(),input.offset,input.length,\"content\"),state.any||(state.choice===null\?result=this._decodeGeneric(state.tag,input,options):result=this._decodeChoice(input,options)),input.isError(result))return result;if(!state.any&&state.choice===null&&state.children!==null&&state.children.forEach(function(child){child._decode(input,options)}),state.contains&&(state.tag===\"octstr\"||state.tag===\"bitstr\")){let data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),state.key!==null&&(result!==null||present===!0)\?input.leaveKey(prevKey,state.key,result):prevKey!==null&&input.exitKey(prevKey),result},Node.prototype._decodeGeneric=function(tag,input,options){let state=this._baseState;return tag===\"seq\"||tag===\"set\"\?null:tag===\"seqof\"||tag===\"setof\"\?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)\?this._decodeStr(input,tag,options):tag===\"objid\"&&state.args\?this._decodeObjid(input,state.args[0],state.args[1],options):tag===\"objid\"\?this._decodeObjid(input,null,null,options):tag===\"gentime\"||tag===\"utctime\"\?this._decodeTime(input,tag,options):tag===\"null_\"\?this._decodeNull(input,options):tag===\"bool\"\?this._decodeBool(input,options):tag===\"objDesc\"\?this._decodeStr(input,tag,options):tag===\"int\"||tag===\"enum\"\?this._decodeInt(input,state.args&&state.args[0],options):state.use!==null\?this._getUse(state.use,input._reporterState.obj)._decode(input,options):input.error(\"unknown tag: \"+tag)},Node.prototype._getUse=function(entity,obj){let state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(state.useDecoder._baseState.parent===null),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function(input,options){let state=this._baseState,result=null,match=!1;return Object.keys(state.choice).some(function(key){let save=input.save(),node=state.choice[key];try{let value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value},match=!0}catch{return input.restore(save),!1}return!0},this),match\?result:input.error(\"Choice not matched\")},Node.prototype._createEncoderBuffer=function(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function(data,reporter,parent){let state=this._baseState;if(state.default!==null&&state.default===data)return;let result=this._encodeValue(data,reporter,parent);if(result!==void 0&&!this._skipDefault(result,reporter,parent))return result},Node.prototype._encodeValue=function(data,reporter,parent){let state=this._baseState;if(state.parent===null)return state.children[0]._encode(data,reporter||new Reporter);let result=null;if(this.reporter=reporter,state.optional&&data===void 0)if(state.default!==null)data=state.default;else return;let content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){if(child._baseState.tag===\"null_\")return child._encode(null,reporter,data);if(child._baseState.key===null)return reporter.error(\"Child should have a key\");let prevKey=reporter.enterKey(child._baseState.key);if(typeof data!=\"object\")return reporter.error(\"Child expected, but input is not object\");let res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if(state.tag===\"seqof\"||state.tag===\"setof\"){if(!(state.args&&state.args.length===1))return reporter.error(\"Too many args for : \"+state.tag);if(!Array.isArray(data))return reporter.error(\"seqof/setof, but data is not Array\");let child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){let state2=this._baseState;return this._getUse(state2.args[0],data)._encode(item,reporter)},child))}else state.use!==null\?result=this._getUse(state.use,parent)._encode(data,reporter):(content=this._encodePrimitive(state.tag,data),primitive=!0);if(!state.any&&state.choice===null){let tag=state.implicit!==null\?state.implicit:state.tag,cls=state.implicit===null\?\"universal\":\"context\";tag===null\?state.use===null&&reporter.error(\"Tag could be omitted only for .use()\"):state.use===null&&(result=this._encodeComposite(tag,primitive,cls,content))}return state.explicit!==null&&(result=this._encodeComposite(state.explicit,!1,\"context\",result)),result},Node.prototype._encodeChoice=function(data,reporter){let state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+\" not found in \"+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function(tag,data){let state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if(tag===\"objid\"&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if(tag===\"objid\")return this._encodeObjid(data,null,null);if(tag===\"gentime\"||tag===\"utctime\")return this._encodeTime(data,tag);if(tag===\"null_\")return this._encodeNull();if(tag===\"int\"||tag===\"enum\")return this._encodeInt(data,state.args&&state.reverseArgs[0]);if(tag===\"bool\")return this._encodeBool(data);if(tag===\"objDesc\")return this._encodeStr(data,tag);throw new Error(\"Unsupported tag: \"+tag)},Node.prototype._isNumstr=function(str){return/^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function(str){return/^[A-Za-z0-9 '()+,-./:=\?]*$/.test(str)}}}),require_der=__commonJS({\"node_modules/asn1.js/lib/asn1/constants/der.js\"(exports){function reverse(map){let res={};return Object.keys(map).forEach(function(key){(key|0)==key&&(key=key|0);let value=map[key];res[value]=key}),res}exports.tagClass={0:\"universal\",1:\"application\",2:\"context\",3:\"private\"},exports.tagClassByName=reverse(exports.tagClass),exports.tag={0:\"end\",1:\"bool\",2:\"int\",3:\"bitstr\",4:\"octstr\",5:\"null_\",6:\"objid\",7:\"objDesc\",8:\"external\",9:\"real\",10:\"enum\",11:\"embed\",12:\"utf8str\",13:\"relativeOid\",16:\"seq\",17:\"set\",18:\"numstr\",19:\"printstr\",20:\"t61str\",21:\"videostr\",22:\"ia5str\",23:\"utctime\",24:\"gentime\",25:\"graphstr\",26:\"iso646str\",27:\"genstr\",28:\"unistr\",29:\"charstr\",30:\"bmpstr\"},exports.tagByName=reverse(exports.tag)}}),require_der2=__commonJS({\"node_modules/asn1.js/lib/asn1/encoders/der.js\"(exports,module){var inherits=require_inherits_browser(),Buffer2=require_safer().Buffer,Node=require_node(),der=require_der();function DEREncoder(entity){this.enc=\"der\",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}DEREncoder.prototype={},module.exports=DEREncoder,DEREncoder.prototype.encode=function(data,reporter){return this.tree._encode(data,reporter).join()};function DERNode(parent){Node.call(this,\"der\",parent)}inherits(DERNode,Node),DERNode.prototype._encodeComposite=function(tag,primitive,cls,content){let encodedTag=encodeTag(tag,primitive,cls,this.reporter);if(content.length<128){let header2=Buffer2.alloc(2);return header2[0]=encodedTag,header2[1]=content.length,this._createEncoderBuffer([header2,content])}let lenOctets=1;for(let i=content.length;i>=256;i>>=8)lenOctets++;let header=Buffer2.alloc(2+lenOctets);header[0]=encodedTag,header[1]=128|lenOctets;for(let i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=j&255;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function(str,tag){if(tag===\"bitstr\")return this._createEncoderBuffer([str.unused|0,str.data]);if(tag===\"bmpstr\"){let buf=Buffer2.alloc(str.length*2);for(let i=0;i=40)return this.reporter.error(\"Second objid identifier OOB\");id.splice(0,2,id[0]*40+id[1])}let size=0;for(let i=0;i=128;ident>>=7)size++}let objid=Buffer2.alloc(size),offset=objid.length-1;for(let i=id.length-1;i>=0;i--){let ident=id[i];for(objid[offset--]=ident&127;(ident>>=7)>0;)objid[offset--]=128|ident&127}return this._createEncoderBuffer(objid)};function two(num){return num<10\?\"0\"+num:num}DERNode.prototype._encodeTime=function(time,tag){let str,date=new Date(time);return tag===\"gentime\"\?str=[two(date.getUTCFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),\"Z\"].join(\"\"):tag===\"utctime\"\?str=[two(date.getUTCFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),\"Z\"].join(\"\"):this.reporter.error(\"Encoding \"+tag+\" time is not supported yet\"),this._encodeStr(str,\"octstr\")},DERNode.prototype._encodeNull=function(){return this._createEncoderBuffer(\"\")},DERNode.prototype._encodeInt=function(num,values){if(typeof num==\"string\"){if(!values)return this.reporter.error(\"String int or enum given, but no values map\");if(!values.hasOwnProperty(num))return this.reporter.error(\"Values map doesn't contain: \"+JSON.stringify(num));num=values[num]}if(typeof num!=\"number\"&&!Buffer2.isBuffer(num)){let numArray=num.toArray();!num.sign&&numArray[0]&128&&numArray.unshift(0),num=Buffer2.from(numArray)}if(Buffer2.isBuffer(num)){let size2=num.length;num.length===0&&size2++;let out2=Buffer2.alloc(size2);return num.copy(out2),num.length===0&&(out2[0]=0),this._createEncoderBuffer(out2)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);let size=1;for(let i=num;i>=256;i>>=8)size++;let out=new Array(size);for(let i=out.length-1;i>=0;i--)out[i]=num&255,num>>=8;return out[0]&128&&out.unshift(0),this._createEncoderBuffer(Buffer2.from(out))},DERNode.prototype._encodeBool=function(value){return this._createEncoderBuffer(value\?255:0)},DERNode.prototype._use=function(entity,obj){return typeof entity==\"function\"&&(entity=entity(obj)),entity._getEncoder(\"der\").tree},DERNode.prototype._skipDefault=function(dataBuffer,reporter,parent){let state=this._baseState,i;if(state.default===null)return!1;let data=dataBuffer.join();if(state.defaultBuffer===void 0&&(state.defaultBuffer=this._encodeValue(state.default,reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i=31\?reporter.error(\"Multi-octet tag encoding unsupported\"):(primitive||(res|=32),res|=der.tagClassByName[cls||\"universal\"]<<6,res)}}}),require_pem=__commonJS({\"node_modules/asn1.js/lib/asn1/encoders/pem.js\"(exports,module){var inherits=require_inherits_browser(),DEREncoder=require_der2();function PEMEncoder(entity){DEREncoder.call(this,entity),this.enc=\"pem\"}inherits(PEMEncoder,DEREncoder),module.exports=PEMEncoder,PEMEncoder.prototype.encode=function(data,options){let p=DEREncoder.prototype.encode.call(this,data).toString(\"base64\"),out=[\"-----BEGIN \"+options.label+\"-----\"];for(let i=0;i>6],primitive=(tag&32)===0;if((tag&31)===31){let oct=tag;for(tag=0;(oct&128)===128;){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=oct&127}}else tag&=31;let tagStr=der.tag[tag];return{cls,primitive,tag,tagStr}}function derDecodeLen(buf,primitive,fail){let len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&len===128)return null;if((len&128)===0)return len;let num=len&127;if(num>4)return buf.error(\"length octect is too long\");len=0;for(let i=0;i0&&bits.ishrn(shift),bits}function bits2octets(bits,q){bits=bits2int(bits,q),bits=bits.mod(q);var out=Buffer2.from(bits.toArray());if(out.length=q)throw new Error(\"invalid sig\")}module.exports=verify}}),require_browser8=__commonJS({\"node_modules/browserify-sign/browser/index.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,createHash=require_browser2(),inherits=require_inherits_browser(),sign=require_sign(),verify=require_verify(),algorithms=require_algorithms();Object.keys(algorithms).forEach(function(key){algorithms[key].id=Buffer2.from(algorithms[key].id,\"hex\"),algorithms[key.toLowerCase()]=algorithms[key]});function Sign(algorithm){StreamModule.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error(\"Unknown message digest\");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}inherits(Sign,StreamModule.Writable),Sign.prototype._write=function(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function(data,enc){return typeof data==\"string\"&&(data=Buffer2.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc\?sig.toString(enc):sig};function Verify(algorithm){StreamModule.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error(\"Unknown message digest\");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}inherits(Verify,StreamModule.Writable),Verify.prototype._write=function(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function(data,enc){return typeof data==\"string\"&&(data=Buffer2.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function(key,sig,enc){typeof sig==\"string\"&&(sig=Buffer2.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)};function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}module.exports={Sign:createSign,Verify:createVerify,createSign,createVerify}}}),require_bn6=require_bn,require_browser9=__commonJS({\"node_modules/create-ecdh/browser.js\"(exports,module){var elliptic=require_elliptic(),BN=require_bn6();module.exports=function(curve){return new ECDH(curve)};var aliases={secp256k1:{name:\"secp256k1\",byteLength:32},secp224r1:{name:\"p224\",byteLength:28},prime256v1:{name:\"p256\",byteLength:32},prime192v1:{name:\"p192\",byteLength:24},ed25519:{name:\"ed25519\",byteLength:32},secp384r1:{name:\"p384\",byteLength:48},secp521r1:{name:\"p521\",byteLength:66}};aliases.p224=aliases.secp224r1,aliases.p256=aliases.secp256r1=aliases.prime256v1,aliases.p192=aliases.secp192r1=aliases.prime192v1,aliases.p384=aliases.secp384r1,aliases.p521=aliases.secp521r1;function ECDH(curve){this.curveType=aliases[curve],this.curveType||(this.curveType={name:curve}),this.curve=new elliptic.ec(this.curveType.name),this.keys=void 0}ECDH.prototype={},ECDH.prototype.generateKeys=function(enc,format){return this.keys=this.curve.genKeyPair(),this.getPublicKey(enc,format)},ECDH.prototype.computeSecret=function(other,inenc,enc){inenc=inenc||\"utf8\",Buffer.isBuffer(other)||(other=new Buffer(other,inenc));var otherPub=this.curve.keyFromPublic(other).getPublic(),out=otherPub.mul(this.keys.getPrivate()).getX();return formatReturnValue(out,enc,this.curveType.byteLength)},ECDH.prototype.getPublicKey=function(enc,format){var key=this.keys.getPublic(format===\"compressed\",!0);return format===\"hybrid\"&&(key[key.length-1]%2\?key[0]=7:key[0]=6),formatReturnValue(key,enc)},ECDH.prototype.getPrivateKey=function(enc){return formatReturnValue(this.keys.getPrivate(),enc)},ECDH.prototype.setPublicKey=function(pub,enc){return enc=enc||\"utf8\",Buffer.isBuffer(pub)||(pub=new Buffer(pub,enc)),this.keys._importPublic(pub),this},ECDH.prototype.setPrivateKey=function(priv,enc){enc=enc||\"utf8\",Buffer.isBuffer(priv)||(priv=new Buffer(priv,enc));var _priv=new BN(priv);return _priv=_priv.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(_priv),this};function formatReturnValue(bn,enc,len){Array.isArray(bn)||(bn=bn.toArray());var buf=new Buffer(bn);if(len&&buf.length=0)throw new Error(\"data too long for modulus\")}else throw new Error(\"unknown padding\");return reverse\?crt(paddedMsg,key):withPublic(paddedMsg,key)};function oaep(key,msg){var k=key.modulus.byteLength(),mLen=msg.length,iHash=createHash(\"sha1\").update(Buffer2.alloc(0)).digest(),hLen=iHash.length,hLen2=2*hLen;if(mLen>k-hLen2-2)throw new Error(\"message too long\");var ps=Buffer2.alloc(k-mLen-hLen2-2),dblen=k-hLen-1,seed=randomBytes(hLen),maskedDb=xor(Buffer2.concat([iHash,ps,Buffer2.alloc(1,1),msg],dblen),mgf(seed,dblen)),maskedSeed=xor(seed,mgf(maskedDb,hLen));return new BN(Buffer2.concat([Buffer2.alloc(1),maskedSeed,maskedDb],k))}function pkcs1(key,msg,reverse){var mLen=msg.length,k=key.modulus.byteLength();if(mLen>k-11)throw new Error(\"message too long\");var ps;return reverse\?ps=Buffer2.alloc(k-mLen-3,255):ps=nonZero(k-mLen-3),new BN(Buffer2.concat([Buffer2.from([0,reverse\?1:2]),ps,Buffer2.alloc(1),msg],k))}function nonZero(len){for(var out=Buffer2.allocUnsafe(len),i=0,cache=randomBytes(len*2),cur=0,num;ik||new BN(enc).cmp(key.modulus)>=0)throw new Error(\"decryption error\");var msg;reverse\?msg=withPublic(new BN(enc),key):msg=crt(enc,key);var zBuffer=Buffer2.alloc(k-msg.length);if(msg=Buffer2.concat([zBuffer,msg],k),padding===4)return oaep(key,msg);if(padding===1)return pkcs1(key,msg,reverse);if(padding===3)return msg;throw new Error(\"unknown padding\")};function oaep(key,msg){var k=key.modulus.byteLength(),iHash=createHash(\"sha1\").update(Buffer2.alloc(0)).digest(),hLen=iHash.length;if(msg[0]!==0)throw new Error(\"decryption error\");var maskedSeed=msg.slice(1,hLen+1),maskedDb=msg.slice(hLen+1),seed=xor(maskedSeed,mgf(maskedDb,hLen)),db=xor(maskedDb,mgf(seed,k-hLen-1));if(compare(iHash,db.slice(0,hLen)))throw new Error(\"decryption error\");for(var i=hLen;db[i]===0;)i++;if(db[i++]!==1)throw new Error(\"decryption error\");return db.slice(i)}function pkcs1(key,msg,reverse){for(var p1=msg.slice(0,2),i=2,status=0;msg[i++]!==0;)if(i>=msg.length){status++;break}var ps=msg.slice(2,i-1);if((p1.toString(\"hex\")!==\"0002\"&&!reverse||p1.toString(\"hex\")!==\"0001\"&&reverse)&&status++,ps.length<8&&status++,status)throw new Error(\"decryption error\");return msg.slice(i)}function compare(a,b){a=Buffer2.from(a),b=Buffer2.from(b);var dif=0,len=a.length;a.length!==b.length&&(dif++,len=Math.min(a.length,b.length));for(var i=-1;++ikMaxUint32||offset<0)@throwTypeError(\"offset must be a uint32\");if(offset>kBufferMaxLength||offset>length)@throwRangeError(\"offset out of range\")}function assertSize(size,offset,length){if(typeof size!=\"number\"||size!==size)@throwTypeError(\"size must be a number\");if(size>kMaxUint32||size<0)@throwTypeError(\"size must be a uint32\");if(size+offset>length||size>kBufferMaxLength)@throwRangeError(\"buffer too small\")}exports.randomFill=randomFill,exports.randomFillSync=randomFillSync;function randomFill(buf,offset,size,cb){if(!Buffer2.isBuffer(buf)&&!(buf instanceof global.Uint8Array))@throwTypeError('\"buf\" argument must be a Buffer or Uint8Array');if(typeof offset==\"function\")cb=offset,offset=0,size=buf.length;else if(typeof size==\"function\")cb=size,size=buf.length-offset;else if(typeof cb!=\"function\")@throwTypeError('\"cb\" argument must be a function');return assertOffset(offset,buf.length),assertSize(size,offset,buf.length),actualFill(buf,offset,size,cb)}function actualFill(buf,offset,size,cb){if(cb){randombytes(size,function(err,bytes2){if(err)return cb(err);bytes2.copy(buf,offset),cb(null,buf)});return}var bytes=randombytes(size);return bytes.copy(buf,offset),buf}function randomFillSync(buf,offset,size){if(typeof offset>\"u\"&&(offset=0),!Buffer2.isBuffer(buf)&&!(buf instanceof global.Uint8Array))@throwTypeError('\"buf\" argument must be a Buffer or Uint8Array');return assertOffset(offset,buf.length),size===void 0&&(size=buf.length-offset),assertSize(size,offset,buf.length),actualFill(buf,offset,size)}}}),require_crypto_browserify2=__commonJS({\"node_modules/crypto-browserify/index.js\"(exports){exports.randomBytes=exports.rng=exports.pseudoRandomBytes=exports.prng=require_browser(),exports.createHash=require_browser2(),exports.Hash=exports.createHash.Hash,exports.createHmac=exports.Hmac=require_browser3();var algos=require_algos(),algoKeys=Object.keys(algos),hashes=[\"sha1\",\"sha224\",\"sha256\",\"sha384\",\"sha512\",\"md5\",\"rmd160\"].concat(algoKeys);exports.getHashes=function(){return hashes};var p=require_browser4();exports.pbkdf2=p.pbkdf2,exports.pbkdf2Sync=p.pbkdf2Sync;var aes=require_browser6();exports.Cipher=aes.Cipher,exports.createCipher=aes.createCipher,exports.Cipheriv=aes.Cipheriv,exports.createCipheriv=aes.createCipheriv,exports.Decipher=aes.Decipher,exports.createDecipher=aes.createDecipher,exports.Decipheriv=aes.Decipheriv,exports.createDecipheriv=aes.createDecipheriv,exports.getCiphers=aes.getCiphers,exports.listCiphers=aes.listCiphers;var dh=require_browser7();exports.DiffieHellmanGroup=dh.DiffieHellmanGroup,exports.createDiffieHellmanGroup=dh.createDiffieHellmanGroup,exports.getDiffieHellman=dh.getDiffieHellman,exports.createDiffieHellman=dh.createDiffieHellman,exports.DiffieHellman=dh.DiffieHellman;var sign=require_browser8();exports.createSign=sign.createSign,exports.Sign=sign.Sign,exports.createVerify=sign.createVerify,exports.Verify=sign.Verify,exports.createECDH=require_browser9();var publicEncrypt=require_browser10();exports.publicEncrypt=publicEncrypt.publicEncrypt,exports.privateEncrypt=publicEncrypt.privateEncrypt,exports.publicDecrypt=publicEncrypt.publicDecrypt,exports.privateDecrypt=publicEncrypt.privateDecrypt,exports.getRandomValues=(values)=>crypto.getRandomValues(values);var rf=require_browser11();exports.randomFill=rf.randomFill,exports.randomFillSync=rf.randomFillSync,exports.createCredentials=function(){throw new Error([\"sorry, createCredentials is not implemented yet\",\"we accept pull requests\",\"https://github.com/crypto-browserify/crypto-browserify\"].join(`\n`))},exports.constants=@processBindingConstants.crypto}}),crypto_exports=require_crypto_browserify2(),DEFAULT_ENCODING=\"buffer\",getRandomValues=(array)=>crypto.getRandomValues(array),randomUUID=()=>crypto.randomUUID(),randomInt=(...args)=>crypto.randomInt(...args),timingSafeEqual=\"timingSafeEqual\"in crypto\?(a,b)=>{let{byteLength:byteLengthA}=a,{byteLength:byteLengthB}=b;if(typeof byteLengthA!=\"number\"||typeof byteLengthB!=\"number\")@throwTypeError(\"Input must be an array buffer view\");if(byteLengthA!==byteLengthB)@throwRangeError(\"Input buffers must have the same length\");return crypto.timingSafeEqual(a,b)}:void 0,scryptSync=\"scryptSync\"in crypto\?(password,salt,keylen,options)=>{let res=crypto.scryptSync(password,salt,keylen,options);return DEFAULT_ENCODING!==\"buffer\"\?new Buffer(res).toString(DEFAULT_ENCODING):new Buffer(res)}:void 0,scrypt=\"scryptSync\"in crypto\?function(password,salt,keylen,options,callback){if(typeof options==\"function\"&&(callback=options,options=void 0),typeof callback!=\"function\"){var err=@makeTypeError(\"callback must be a function\");throw err.code=\"ERR_INVALID_CALLBACK\",err}try{let result=crypto.scryptSync(password,salt,keylen,options);process.nextTick(callback,null,DEFAULT_ENCODING!==\"buffer\"\?new Buffer(result).toString(DEFAULT_ENCODING):new Buffer(result))}catch(err2){throw err2}}:void 0;timingSafeEqual&&(Object.defineProperty(timingSafeEqual,\"name\",{value:\"::bunternal::\"}),Object.defineProperty(scrypt,\"name\",{value:\"::bunternal::\"}),Object.defineProperty(scryptSync,\"name\",{value:\"::bunternal::\"}));const harcoded_curves=[\"p192\",\"p224\",\"p256\",\"p384\",\"p521\",\"curve25519\",\"ed25519\",\"secp256k1\",\"secp224r1\",\"prime256v1\",\"prime192v1\",\"ed25519\",\"secp384r1\",\"secp521r1\"];function getCurves(){return harcoded_curves}var webcrypto=crypto;__export(crypto_exports,{DEFAULT_ENCODING:()=>DEFAULT_ENCODING,getRandomValues:()=>getRandomValues,randomUUID:()=>randomUUID,randomInt:()=>randomInt,getCurves:()=>getCurves,scrypt:()=>scrypt,scryptSync:()=>scryptSync,timingSafeEqual:()=>timingSafeEqual,webcrypto:()=>webcrypto,subtle:()=>webcrypto.subtle}),$=crypto_exports;/*! safe-buffer. MIT License. Feross Aboukhadijeh */return $})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDgramCode = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function createSocket(){throwNotImplemented(\"node:dgram createSocket\",1630)}function Socket(){throwNotImplemented(\"node:dgram Socket\",1630)}function _createSocketHandle(){throwNotImplemented(\"node:dgram _createSocketHandle\",1630)}return $={createSocket,Socket,_createSocketHandle},hideFromStack(createSocket,Socket,_createSocketHandle),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDiagnosticsChannelCode = "(function (){\"use strict\";const SafeMap=Map,SafeFinalizationRegistry=FinalizationRegistry,ArrayPrototypeAt=(array,index)=>array[index],ArrayPrototypeIndexOf=(array,value)=>array.indexOf(value),ArrayPrototypePush=(array,value)=>array.push(value),ArrayPrototypeSplice=(array,start,deleteCount)=>array.splice(start,deleteCount),ObjectGetPrototypeOf=Object.getPrototypeOf,ObjectSetPrototypeOf=Object.setPrototypeOf,SymbolHasInstance=Symbol.hasInstance,ReflectApply=Reflect.apply,PromiseResolve=Promise.resolve,PromiseReject=Promise.reject,PromisePrototypeThen=(promise,onFulfilled,onRejected)=>promise.then(onFulfilled,onRejected);class WeakReference extends WeakRef{constructor(){super(...arguments)}#refs=0;get(){return this.deref()}incRef(){return++this.#refs}decRef(){return--this.#refs}}class WeakRefMap extends SafeMap{constructor(){super(...arguments)}#finalizers=new SafeFinalizationRegistry((key)=>{this.delete(key)});set(key,value){return this.#finalizers.register(value,key),super.set(key,new WeakReference(value))}get(key){return super.get(key)\?.get()}incRef(key){return super.get(key)\?.incRef()}decRef(key){return super.get(key)\?.decRef()}}function markActive(channel2){ObjectSetPrototypeOf(channel2,ActiveChannel.prototype),channel2._subscribers=[],channel2._stores=new SafeMap}function maybeMarkInactive(channel2){if(!channel2._subscribers.length&&!channel2._stores.size)ObjectSetPrototypeOf(channel2,Channel.prototype),channel2._subscribers=void 0,channel2._stores=void 0}function defaultTransform(data){return data}function wrapStoreRun(store,data,next,transform=defaultTransform){return()=>{let context;try{context=transform(data)}catch(err){return process.nextTick(()=>reportError(err)),next()}return store.run(context,next)}}class ActiveChannel{subscribe(subscription){validateFunction(subscription,\"subscription\"),ArrayPrototypePush(this._subscribers,subscription),channels.incRef(this.name)}unsubscribe(subscription){const index=ArrayPrototypeIndexOf(this._subscribers,subscription);if(index===-1)return!1;return ArrayPrototypeSplice(this._subscribers,index,1),channels.decRef(this.name),maybeMarkInactive(this),!0}bindStore(store,transform){if(!this._stores.has(store))channels.incRef(this.name);this._stores.set(store,transform)}unbindStore(store){if(!this._stores.has(store))return!1;return this._stores.delete(store),channels.decRef(this.name),maybeMarkInactive(this),!0}get hasSubscribers(){return!0}publish(data){for(let i=0;i<(this._subscribers\?.length||0);i++)try{const onMessage=this._subscribers[i];onMessage(data,this.name)}catch(err){process.nextTick(()=>reportError(err))}}runStores(data,fn,thisArg,...args){let run=()=>{return this.publish(data),ReflectApply(fn,thisArg,args)};for(let entry of this._stores.entries()){const store=entry[0],transform=entry[1];run=wrapStoreRun(store,data,run,transform)}return run()}}class Channel{constructor(name){this._subscribers=void 0,this._stores=void 0,this.name=name,channels.set(name,this)}static[SymbolHasInstance](instance){const prototype=ObjectGetPrototypeOf(instance);return prototype===Channel.prototype||prototype===ActiveChannel.prototype}subscribe(subscription){markActive(this),this.subscribe(subscription)}unsubscribe(){return!1}bindStore(store,transform){markActive(this),this.bindStore(store,transform)}unbindStore(){return!1}get hasSubscribers(){return!1}publish(){}runStores(data,fn,thisArg,...args){return ReflectApply(fn,thisArg,args)}}const channels=new WeakRefMap;function channel(name){const channel2=channels.get(name);if(channel2)return channel2;if(typeof name!==\"string\"&&typeof name!==\"symbol\")throw new ERR_INVALID_ARG_TYPE(\"channel\",[\"string\",\"symbol\"],name);return new Channel(name)}function subscribe(name,subscription){return channel(name).subscribe(subscription)}function unsubscribe(name,subscription){return channel(name).unsubscribe(subscription)}function hasSubscribers(name){const channel2=channels.get(name);if(!channel2)return!1;return channel2.hasSubscribers}const traceEvents=[\"start\",\"end\",\"asyncStart\",\"asyncEnd\",\"error\"];function assertChannel(value,name){if(!(value instanceof Channel))throw new ERR_INVALID_ARG_TYPE(name,[\"Channel\"],value)}class TracingChannel{constructor(nameOrChannels){if(typeof nameOrChannels===\"string\")this.start=channel(`tracing:${nameOrChannels}:start`),this.end=channel(`tracing:${nameOrChannels}:end`),this.asyncStart=channel(`tracing:${nameOrChannels}:asyncStart`),this.asyncEnd=channel(`tracing:${nameOrChannels}:asyncEnd`),this.error=channel(`tracing:${nameOrChannels}:error`);else if(typeof nameOrChannels===\"object\"){const{start,end,asyncStart,asyncEnd,error}=nameOrChannels;assertChannel(start,\"nameOrChannels.start\"),assertChannel(end,\"nameOrChannels.end\"),assertChannel(asyncStart,\"nameOrChannels.asyncStart\"),assertChannel(asyncEnd,\"nameOrChannels.asyncEnd\"),assertChannel(error,\"nameOrChannels.error\"),this.start=start,this.end=end,this.asyncStart=asyncStart,this.asyncEnd=asyncEnd,this.error=error}else throw new ERR_INVALID_ARG_TYPE(\"nameOrChannels\",[\"string\",\"object\",\"Channel\"],nameOrChannels)}subscribe(handlers){for(let name of traceEvents){if(!handlers[name])continue;this[name]\?.subscribe(handlers[name])}}unsubscribe(handlers){let done=!0;for(let name of traceEvents){if(!handlers[name])continue;if(!this[name]\?.unsubscribe(handlers[name]))done=!1}return done}traceSync(fn,context={},thisArg,...args){const{start,end,error}=this;return start.runStores(context,()=>{try{const result=ReflectApply(fn,thisArg,args);return context.result=result,result}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}tracePromise(fn,context={},thisArg,...args){const{start,end,asyncStart,asyncEnd,error}=this;function reject(err){return context.error=err,error.publish(context),asyncStart.publish(context),asyncEnd.publish(context),PromiseReject(err)}function resolve(result){return context.result=result,asyncStart.publish(context),asyncEnd.publish(context),result}return start.runStores(context,()=>{try{let promise=ReflectApply(fn,thisArg,args);if(!(promise instanceof Promise))promise=PromiseResolve(promise);return PromisePrototypeThen(promise,resolve,reject)}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}traceCallback(fn,position=-1,context={},thisArg,...args){const{start,end,asyncStart,asyncEnd,error}=this;function wrappedCallback(err,res){if(err)context.error=err,error.publish(context);else context.result=res;asyncStart.runStores(context,()=>{try{if(callback)return ReflectApply(callback,this,arguments)}finally{asyncEnd.publish(context)}})}const callback=ArrayPrototypeAt(args,position);if(typeof callback!==\"function\")throw new ERR_INVALID_ARG_TYPE(\"callback\",[\"function\"],callback);return ArrayPrototypeSplice(args,position,1,wrappedCallback),start.runStores(context,()=>{try{return ReflectApply(fn,thisArg,args)}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}}function tracingChannel(nameOrChannels){return new TracingChannel(nameOrChannels)}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 validateFunction(callable,field){if(typeof callable!==\"function\")throw new ERR_INVALID_ARG_TYPE(field,\"Function\",callable);return callable}return{channel,hasSubscribers,subscribe,tracingChannel,unsubscribe,Channel}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDNSCode = "(function (){\"use strict\";const dns=Bun.dns;function getServers(){return dns.getServers()}function lookup(domain,options,callback){if(typeof options==\"function\")callback=options;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");if(typeof options==\"number\")options={family:options};dns.lookup(domain,options).then((res)=>{if(res.sort((a,b)=>a.family-b.family),options\?.all)callback(null,res.map(mapLookupAll));else{const[{address,family}]=res;callback(null,address,family)}},(error)=>{callback(error)})}function resolveSrv(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSrv(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveTxt(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveTxt(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveSoa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSoa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveNaptr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNaptr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveMx(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveMx(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveCaa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCaa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveNs(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNs(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolvePtr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolvePtr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveCname(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCname(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function lookupService(address,port,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");callback(null,address,port)}var InternalResolver=class Resolver2{constructor(options){}cancel(){}getServers(){return[]}resolve(hostname,rrtype,callback){if(typeof rrtype==\"function\")callback=rrtype,rrtype=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolve(hostname).then((results)=>{switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":callback(null,hostname,results.map(mapResolveX));break;default:callback(null,results);break}},(error)=>{callback(error)})}resolve4(hostname,options,callback){if(typeof options==\"function\")callback=options,options=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.lookup(hostname,{family:4}).then((addresses)=>{callback(null,options\?.ttl\?addresses:addresses.map(mapResolveX))},(error)=>{callback(error)})}resolve6(hostname,options,callback){if(typeof options==\"function\")callback=options,options=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.lookup(hostname,{family:6}).then((addresses)=>{callback(null,options\?.ttl\?addresses:addresses.map(({address})=>address))},(error)=>{callback(error)})}resolveAny(hostname,callback){callback(null,[])}resolveCname(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCname(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveMx(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveMx(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveNaptr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNaptr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveNs(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNs(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolvePtr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolvePtr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveSrv(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSrv(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveCaa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCaa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveTxt(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveTxt(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveSoa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSoa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}reverse(ip,callback){callback(null,[])}setServers(servers){}};function resolve(hostname,rrtype,callback){if(typeof rrtype==\"function\")callback=rrtype;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolve(hostname).then((results)=>{switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":callback(null,hostname,results.map(({address})=>address));break;default:callback(null,results);break}},(error)=>{callback(error)})}function Resolver(options){return new InternalResolver(options)}Resolver.prototype={},Object.setPrototypeOf(Resolver.prototype,InternalResolver.prototype),Object.setPrototypeOf(Resolver,InternalResolver);var{resolve,resolve4,resolve6,resolveAny,resolveCname,resolveCaa,resolveMx,resolveNaptr,resolveNs,resolvePtr,resolveSoa,resolveSrv,reverse,resolveTxt}=InternalResolver.prototype;function setDefaultResultOrder(){}function setServers(){}const promisifyLookup=(res)=>{res.sort((a,b)=>a.family-b.family);const[{address,family}]=res;return{address,family}},mapLookupAll=(res)=>{const{address,family}=res;return{address,family}},promisifyLookupAll=(res)=>{return res.sort((a,b)=>a.family-b.family),res.map(mapLookupAll)},mapResolveX=(a)=>a.address,promisifyResolveX=(res)=>{return res\?.map(mapResolveX)},promises={lookup(domain,options){if(options\?.all)return dns.lookup(domain,options).then(promisifyLookupAll);return dns.lookup(domain,options).then(promisifyLookup)},lookupService(address,port){return Promise.resolve([])},resolve(hostname,rrtype){if(typeof rrtype!==\"string\")rrtype=null;switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":return dns.resolve(hostname,rrtype).then(promisifyLookup);default:return dns.resolve(hostname,rrtype)}},resolve4(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:4});return dns.lookup(hostname,{family:4}).then(promisifyResolveX)},resolve6(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:6});return dns.lookup(hostname,{family:6}).then(promisifyResolveX)},resolveSrv(hostname){return dns.resolveSrv(hostname)},resolveTxt(hostname){return dns.resolveTxt(hostname)},resolveSoa(hostname){return dns.resolveSoa(hostname)},resolveNaptr(hostname){return dns.resolveNaptr(hostname)},resolveMx(hostname){return dns.resolveMx(hostname)},resolveCaa(hostname){return dns.resolveCaa(hostname)},resolveNs(hostname){return dns.resolveNs(hostname)},resolvePtr(hostname){return dns.resolvePtr(hostname)},resolveCname(hostname){return dns.resolveCname(hostname)},Resolver:class Resolver2{constructor(options){}cancel(){}getServers(){return[]}resolve(hostname,rrtype){if(typeof rrtype!==\"string\")rrtype=null;switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":return dns.resolve(hostname,rrtype).then(promisifyLookup);default:return dns.resolve(hostname,rrtype)}}resolve4(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:4});return dns.lookup(hostname,{family:4}).then(promisifyResolveX)}resolve6(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:6});return dns.lookup(hostname,{family:6}).then(promisifyResolveX)}resolveAny(hostname){return Promise.resolve([])}resolveCname(hostname){return dns.resolveCname(hostname)}resolveMx(hostname){return dns.resolveMx(hostname)}resolveNaptr(hostname){return dns.resolveNaptr(hostname)}resolveNs(hostname){return dns.resolveNs(hostname)}resolvePtr(hostname){return dns.resolvePtr(hostname)}resolveSoa(hostname){return dns.resolveSoa(hostname)}resolveSrv(hostname){return dns.resolveSrv(hostname)}resolveCaa(hostname){return dns.resolveCaa(hostname)}resolveTxt(hostname){return dns.resolveTxt(hostname)}reverse(ip){return Promise.resolve([])}setServers(servers){}}};for(let key of[\"resolveAny\",\"reverse\"])promises[key]=()=>Promise.resolve(void 0);return{ADDRCONFIG:0,ALL:1,V4MAPPED:2,NODATA:\"DNS_ENODATA\",FORMERR:\"DNS_EFORMERR\",SERVFAIL:\"DNS_ESERVFAIL\",NOTFOUND:\"DNS_ENOTFOUND\",NOTIMP:\"DNS_ENOTIMP\",REFUSED:\"DNS_EREFUSED\",BADQUERY:\"DNS_EBADQUERY\",BADNAME:\"DNS_EBADNAME\",BADFAMILY:\"DNS_EBADFAMILY\",BADRESP:\"DNS_EBADRESP\",CONNREFUSED:\"DNS_ECONNREFUSED\",TIMEOUT:\"DNS_ETIMEOUT\",EOF:\"DNS_EEOF\",FILE:\"DNS_EFILE\",NOMEM:\"DNS_ENOMEM\",DESTRUCTION:\"DNS_EDESTRUCTION\",BADSTR:\"DNS_EBADSTR\",BADFLAGS:\"DNS_EBADFLAGS\",NONAME:\"DNS_ENONAME\",BADHINTS:\"DNS_EBADHINTS\",NOTINITIALIZED:\"DNS_ENOTINITIALIZED\",LOADIPHLPAPI:\"DNS_ELOADIPHLPAPI\",ADDRGETNETWORKPARAMS:\"DNS_EADDRGETNETWORKPARAMS\",CANCELLED:\"DNS_ECANCELLED\",lookup,lookupService,Resolver,setServers,setDefaultResultOrder,resolve,reverse,resolve4,resolve6,resolveAny,resolveCname,resolveCaa,resolveMx,resolveNs,resolvePtr,resolveSoa,resolveSrv,resolveTxt,resolveNaptr,promises,getServers}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDNSPromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,12)||@createInternalModuleById(12)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDomainCode = "(function (){\"use strict\";var EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),domain={};return domain.createDomain=domain.create=function(){var d=new EventEmitter;function emitError(e){d.emit(\"error\",e)}return d.add=function(emitter){emitter.on(\"error\",emitError)},d.remove=function(emitter){emitter.removeListener(\"error\",emitError)},d.bind=function(fn){return function(){var args=Array.prototype.slice.call(arguments);try{fn.apply(null,args)}catch(err){emitError(err)}}},d.intercept=function(fn){return function(err){if(err)emitError(err);else{var args=Array.prototype.slice.call(arguments,1);try{fn.apply(null,args)}catch(err2){emitError(err2)}}}},d.run=function(fn){try{fn()}catch(err){emitError(err)}return this},d.dispose=function(){return this.removeAllListeners(),this},d.enter=d.exit=function(){return this},d},domain})\n"_s; +// + +// +static constexpr ASCIILiteral NodeEventsCode = "(function (){\"use strict\";const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),SymbolFor=Symbol.for,kCapture=Symbol(\"kCapture\"),kErrorMonitor=SymbolFor(\"events.errorMonitor\"),kMaxEventTargetListeners=Symbol(\"events.maxEventTargetListeners\"),kMaxEventTargetListenersWarned=Symbol(\"events.maxEventTargetListenersWarned\"),kWatermarkData=SymbolFor(\"nodejs.watermarkData\"),kRejection=SymbolFor(\"nodejs.rejection\"),captureRejectionSymbol=SymbolFor(\"nodejs.rejection\"),ArrayPrototypeSlice=Array.prototype.slice;var defaultMaxListeners=10;const EventEmitter=function EventEmitter(opts){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners\?\?=void 0,this[kCapture]=opts\?.captureRejections\?Boolean(opts\?.captureRejections):EventEmitterPrototype[kCapture])this.emit=emitWithRejectionCapture},EventEmitterPrototype=EventEmitter.prototype={};EventEmitterPrototype._events=void 0,EventEmitterPrototype._eventsCount=0,EventEmitterPrototype._maxListeners=void 0,EventEmitterPrototype.setMaxListeners=function setMaxListeners(n){return validateNumber(n,\"setMaxListeners\",0),this._maxListeners=n,this},EventEmitterPrototype.getMaxListeners=function getMaxListeners(){return this._maxListeners\?\?defaultMaxListeners};function emitError(emitter,args){var{_events:events}=emitter;if(args[0]\?\?=new Error(\"Unhandled error.\"),!events)throw args[0];var errorMonitor=events[kErrorMonitor];if(errorMonitor)for(var handler of ArrayPrototypeSlice.call(errorMonitor))handler.apply(emitter,args);var handlers=events.error;if(!handlers)throw args[0];for(var handler of ArrayPrototypeSlice.call(handlers))handler.apply(emitter,args);return!0}function addCatch(emitter,promise,type,args){promise.then(void 0,function(err){process.nextTick(emitUnhandledRejectionOrErr,emitter,err,type,args)})}function emitUnhandledRejectionOrErr(emitter,err,type,args){if(typeof emitter[kRejection]===\"function\")emitter[kRejection](err,type,...args);else try{emitter[kCapture]=!1,emitter.emit(\"error\",err)}finally{emitter[kCapture]=!0}}const emitWithoutRejectionCapture=function emit(type,...args){if(type===\"error\")return emitError(this,args);var{_events:events}=this;if(events===void 0)return!1;var handlers=events[type];if(handlers===void 0)return!1;for(var handler of[...handlers])handler.apply(this,args);return!0},emitWithRejectionCapture=function emit(type,...args){if(type===\"error\")return emitError(this,args);var{_events:events}=this;if(events===void 0)return!1;var handlers=events[type];if(handlers===void 0)return!1;for(var handler of[...handlers]){var result=handler.apply(this,args);if(result!==void 0&&@isPromise(result))addCatch(this,result,type,args)}return!0};EventEmitterPrototype.emit=emitWithoutRejectionCapture,EventEmitterPrototype.addListener=function addListener(type,fn){checkListener(fn);var events=this._events;if(!events)events=this._events={__proto__:null},this._eventsCount=0;else if(events.newListener)this.emit(\"newListener\",type,fn.listener\?\?fn);var handlers=events[type];if(!handlers)events[type]=[fn],this._eventsCount++;else{handlers.push(fn);var m=this._maxListeners\?\?defaultMaxListeners;if(m>0&&handlers.length>m&&!handlers.warned)overflowWarning(this,type,handlers)}return this},EventEmitterPrototype.on=EventEmitterPrototype.addListener,EventEmitterPrototype.prependListener=function prependListener(type,fn){checkListener(fn);var events=this._events;if(!events)events=this._events={__proto__:null},this._eventsCount=0;else if(events.newListener)this.emit(\"newListener\",type,fn.listener\?\?fn);var handlers=events[type];if(!handlers)events[type]=[fn],this._eventsCount++;else{handlers.unshift(fn);var m=this._maxListeners\?\?defaultMaxListeners;if(m>0&&handlers.length>m&&!handlers.warned)overflowWarning(this,type,handlers)}return this};function overflowWarning(emitter,type,handlers){handlers.warned=!0;const warn=new Error(`Possible EventEmitter memory leak detected. ${handlers.length} ${String(type)} listeners `+`added to [${emitter.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);warn.name=\"MaxListenersExceededWarning\",warn.emitter=emitter,warn.type=type,warn.count=handlers.length,process.emitWarning(warn)}function onceWrapper(type,listener,...args){this.removeListener(type,listener),listener.apply(this,args)}EventEmitterPrototype.once=function once(type,fn){checkListener(fn);const bound=onceWrapper.bind(this,type,fn);return bound.listener=fn,this.addListener(type,bound),this},EventEmitterPrototype.prependOnceListener=function prependOnceListener(type,fn){checkListener(fn);const bound=onceWrapper.bind(this,type,fn);return bound.listener=fn,this.prependListener(type,bound),this},EventEmitterPrototype.removeListener=function removeListener(type,fn){checkListener(fn);var{_events:events}=this;if(!events)return this;var handlers=events[type];if(!handlers)return this;var length=handlers.length;let position=-1;for(let i=length-1;i>=0;i--)if(handlers[i]===fn||handlers[i].listener===fn){position=i;break}if(position<0)return this;if(position===0)handlers.shift();else handlers.splice(position,1);if(handlers.length===0)delete events[type],this._eventsCount--;return this},EventEmitterPrototype.off=EventEmitterPrototype.removeListener,EventEmitterPrototype.removeAllListeners=function removeAllListeners(type){var{_events:events}=this;if(type&&events){if(events[type])delete events[type],this._eventsCount--}else this._events={__proto__:null};return this},EventEmitterPrototype.listeners=function listeners(type){var{_events:events}=this;if(!events)return[];var handlers=events[type];if(!handlers)return[];return handlers.map((x)=>x.listener\?\?x)},EventEmitterPrototype.rawListeners=function rawListeners(type){var{_events}=this;if(!_events)return[];var handlers=_events[type];if(!handlers)return[];return handlers.slice()},EventEmitterPrototype.listenerCount=function listenerCount(type){var{_events:events}=this;if(!events)return 0;return events[type]\?.length\?\?0},EventEmitterPrototype.eventNames=function eventNames(){return this._eventsCount>0\?Reflect.ownKeys(this._events):[]},EventEmitterPrototype[kCapture]=!1;function once(emitter,type,options){var signal=options\?.signal;if(validateAbortSignal(signal,\"options.signal\"),signal\?.aborted)throw new AbortError(void 0,{cause:signal\?.reason});return new Promise((resolve,reject)=>{const errorListener=(err)=>{if(emitter.removeListener(type,resolver),signal!=null)eventTargetAgnosticRemoveListener(signal,\"abort\",abortListener);reject(err)},resolver=(...args)=>{if(typeof emitter.removeListener===\"function\")emitter.removeListener(\"error\",errorListener);if(signal!=null)eventTargetAgnosticRemoveListener(signal,\"abort\",abortListener);resolve(args)};if(eventTargetAgnosticAddListener(emitter,type,resolver,{once:!0}),type!==\"error\"&&typeof emitter.once===\"function\")emitter.once(\"error\",errorListener);function abortListener(){eventTargetAgnosticRemoveListener(emitter,type,resolver),eventTargetAgnosticRemoveListener(emitter,\"error\",errorListener),reject(new AbortError(void 0,{cause:signal\?.reason}))}if(signal!=null)eventTargetAgnosticAddListener(signal,\"abort\",abortListener,{once:!0})})}function on(emitter,type,options){var{signal,close,highWatermark=Number.MAX_SAFE_INTEGER,lowWatermark=1}=options||{};throwNotImplemented(\"events.on\",2679)}function getEventListeners(emitter,type){if(emitter instanceof EventTarget)throwNotImplemented(\"getEventListeners with an EventTarget\",2678);return emitter.listeners(type)}function setMaxListeners(n,...eventTargets){validateNumber(n,\"setMaxListeners\",0);var length;if(eventTargets&&(length=eventTargets.length))for(let i=0;imax||(min!=null||max!=null)&&Number.isNaN(value))throw new ERR_OUT_OF_RANGE(name,`${min!=null\?`>= ${min}`:\"\"}${min!=null&&max!=null\?\" && \":\"\"}${max!=null\?`<= ${max}`:\"\"}`,value)}function checkListener(listener){if(typeof listener!==\"function\")@throwTypeError(\"The listener must be a function\")}let AsyncResource=null;class EventEmitterAsyncResource extends EventEmitter{triggerAsyncId;asyncResource;constructor(options){if(!AsyncResource)AsyncResource=(@getInternalField(@internalModuleRegistry,5)||@createInternalModuleById(5)).AsyncResource;var{captureRejections=!1,triggerAsyncId,name=new.target.name,requireManualDestroy}=options||{};super({captureRejections});this.triggerAsyncId=triggerAsyncId\?\?0,this.asyncResource=new AsyncResource(name,{triggerAsyncId,requireManualDestroy})}emit(...args){this.asyncResource.runInAsyncScope(()=>super.emit(...args))}emitDestroy(){this.asyncResource.emitDestroy()}}return Object.defineProperties(EventEmitter,{captureRejections:{get(){return EventEmitterPrototype[kCapture]},set(value){validateBoolean(value,\"EventEmitter.captureRejections\"),EventEmitterPrototype[kCapture]=value},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return defaultMaxListeners},set:(arg)=>{validateNumber(arg,\"defaultMaxListeners\",0),defaultMaxListeners=arg}},kMaxEventTargetListeners:{value:kMaxEventTargetListeners,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:kMaxEventTargetListenersWarned,enumerable:!1,configurable:!1,writable:!1}}),Object.assign(EventEmitter,{once,on,getEventListeners,setMaxListeners,EventEmitter,usingDomains:!1,captureRejectionSymbol,EventEmitterAsyncResource,errorMonitor:kErrorMonitor,setMaxListeners,init:EventEmitter,listenerCount}),EventEmitter})\n"_s; +// + +// +static constexpr ASCIILiteral NodeFSCode = "(function (){\"use strict\";var $,ReadStream,WriteStream;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),promises=@getInternalField(@internalModuleRegistry,17)||@createInternalModuleById(17),Stream=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34);var fs=Bun.fs();class FSWatcher extends EventEmitter{#watcher;#listener;constructor(path,options,listener){super();if(typeof options===\"function\")listener=options,options={};else if(typeof options===\"string\")options={encoding:options};if(typeof listener!==\"function\")listener=()=>{};this.#listener=listener;try{this.#watcher=fs.watch(path,options||{},this.#onEvent.bind(this))}catch(e){if(!e.message\?.startsWith(\"FileNotFound\"))throw e;const notFound=new Error(`ENOENT: no such file or directory, watch '${path}'`);throw notFound.code=\"ENOENT\",notFound.errno=-2,notFound.path=path,notFound.syscall=\"watch\",notFound.filename=path,notFound}}#onEvent(eventType,filenameOrError){if(eventType===\"error\"||eventType===\"close\")this.emit(eventType,filenameOrError);else this.emit(\"change\",eventType,filenameOrError),this.#listener(eventType,filenameOrError)}close(){this.#watcher\?.close(),this.#watcher=null}ref(){this.#watcher\?.ref()}unref(){this.#watcher\?.unref()}}var access=function access(...args){callbackify(fs.accessSync,args)},appendFile=function appendFile(...args){callbackify(fs.appendFileSync,args)},close=function close(...args){callbackify(fs.closeSync,args)},rm=function rm(...args){callbackify(fs.rmSync,args)},rmdir=function rmdir(...args){callbackify(fs.rmdirSync,args)},copyFile=function copyFile(...args){callbackify(fs.copyFileSync,args)},exists=function exists(...args){callbackify(fs.existsSync,args)},chown=function chown(...args){callbackify(fs.chownSync,args)},chmod=function chmod(...args){callbackify(fs.chmodSync,args)},fchmod=function fchmod(...args){callbackify(fs.fchmodSync,args)},fchown=function fchown(...args){callbackify(fs.fchownSync,args)},fstat=function fstat(...args){callbackify(fs.fstatSync,args)},fsync=function fsync(...args){callbackify(fs.fsyncSync,args)},ftruncate=function ftruncate(...args){callbackify(fs.ftruncateSync,args)},futimes=function futimes(...args){callbackify(fs.futimesSync,args)},lchmod=function lchmod(...args){callbackify(fs.lchmodSync,args)},lchown=function lchown(...args){callbackify(fs.lchownSync,args)},link=function link(...args){callbackify(fs.linkSync,args)},mkdir=function mkdir(...args){callbackify(fs.mkdirSync,args)},mkdtemp=function mkdtemp(...args){callbackify(fs.mkdtempSync,args)},open=function open(...args){callbackify(fs.openSync,args)},read=function read(...args){callbackify(fs.readSync,args)},write=function write(...args){callbackify(fs.writeSync,args)},readdir=function readdir(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.readdir(...args).then((result)=>callback(null,result),callback)},readFile=function readFile(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.readFile(...args).then((result)=>callback(null,result),callback)},writeFile=function writeFile(...args){callbackify(fs.writeFileSync,args)},readlink=function readlink(...args){callbackify(fs.readlinkSync,args)},realpath=function realpath(...args){callbackify(fs.realpathSync,args)},rename=function rename(...args){callbackify(fs.renameSync,args)},lstat=function lstat(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.lstat(...args).then((result)=>callback(null,result),callback)},stat=function stat(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.stat(...args).then((result)=>callback(null,result),callback)},symlink=function symlink(...args){callbackify(fs.symlinkSync,args)},truncate=function truncate(...args){callbackify(fs.truncateSync,args)},unlink=function unlink(...args){callbackify(fs.unlinkSync,args)},utimes=function utimes(...args){callbackify(fs.utimesSync,args)},lutimes=function lutimes(...args){callbackify(fs.lutimesSync,args)},accessSync=fs.accessSync.bind(fs),appendFileSync=fs.appendFileSync.bind(fs),closeSync=fs.closeSync.bind(fs),copyFileSync=fs.copyFileSync.bind(fs),existsSync=fs.existsSync.bind(fs),chownSync=fs.chownSync.bind(fs),chmodSync=fs.chmodSync.bind(fs),fchmodSync=fs.fchmodSync.bind(fs),fchownSync=fs.fchownSync.bind(fs),fstatSync=fs.fstatSync.bind(fs),fsyncSync=fs.fsyncSync.bind(fs),ftruncateSync=fs.ftruncateSync.bind(fs),futimesSync=fs.futimesSync.bind(fs),lchmodSync=fs.lchmodSync.bind(fs),lchownSync=fs.lchownSync.bind(fs),linkSync=fs.linkSync.bind(fs),lstatSync=fs.lstatSync.bind(fs),mkdirSync=fs.mkdirSync.bind(fs),mkdtempSync=fs.mkdtempSync.bind(fs),openSync=fs.openSync.bind(fs),readSync=fs.readSync.bind(fs),writeSync=fs.writeSync.bind(fs),readdirSync=fs.readdirSync.bind(fs),readFileSync=fs.readFileSync.bind(fs),writeFileSync=fs.writeFileSync.bind(fs),readlinkSync=fs.readlinkSync.bind(fs),realpathSync=fs.realpathSync.bind(fs),renameSync=fs.renameSync.bind(fs),statSync=fs.statSync.bind(fs),symlinkSync=fs.symlinkSync.bind(fs),truncateSync=fs.truncateSync.bind(fs),unlinkSync=fs.unlinkSync.bind(fs),utimesSync=fs.utimesSync.bind(fs),lutimesSync=fs.lutimesSync.bind(fs),rmSync=fs.rmSync.bind(fs),rmdirSync=fs.rmdirSync.bind(fs),writev=(fd,buffers,position,callback)=>{if(typeof position===\"function\")callback=position,position=null;queueMicrotask(()=>{try{var written=fs.writevSync(fd,buffers,position)}catch(e){callback(e)}callback(null,written,buffers)})},writevSync=fs.writevSync.bind(fs),readv=(fd,buffers,position,callback)=>{if(typeof position===\"function\")callback=position,position=null;queueMicrotask(()=>{try{var written=fs.readvSync(fd,buffers,position)}catch(e){callback(e)}callback(null,written,buffers)})},readvSync=fs.readvSync.bind(fs),Dirent=fs.Dirent,Stats=fs.Stats,watch=function watch(path,options,listener){return new FSWatcher(path,options,listener)};function callbackify(fsFunction,args){try{const result=fsFunction.apply(fs,args.slice(0,args.length-1)),callback=args[args.length-1];if(typeof callback===\"function\")queueMicrotask(()=>callback(null,result))}catch(e){const callback=args[args.length-1];if(typeof callback===\"function\")queueMicrotask(()=>callback(e))}}var readStreamPathFastPathSymbol=Symbol.for(\"Bun.Node.readStreamPathFastPath\");const readStreamSymbol=Symbol.for(\"Bun.NodeReadStream\"),readStreamPathOrFdSymbol=Symbol.for(\"Bun.NodeReadStreamPathOrFd\"),writeStreamSymbol=Symbol.for(\"Bun.NodeWriteStream\");var writeStreamPathFastPathSymbol=Symbol.for(\"Bun.NodeWriteStreamFastPath\"),writeStreamPathFastPathCallSymbol=Symbol.for(\"Bun.NodeWriteStreamFastPathCall\"),kIoDone=Symbol.for(\"kIoDone\"),defaultReadStreamOptions={file:void 0,fd:void 0,flags:\"r\",encoding:void 0,mode:438,autoClose:!0,emitClose:!0,start:0,end:Infinity,highWaterMark:65536,fs:{read,open:(path,flags,mode,cb)=>{var fd;try{fd=openSync(path,flags,mode)}catch(e){cb(e);return}cb(null,fd)},openSync,close},autoDestroy:!0},ReadStreamClass;ReadStream=function(InternalReadStream){ReadStreamClass=InternalReadStream,Object.defineProperty(ReadStreamClass.prototype,Symbol.toStringTag,{value:\"ReadStream\",enumerable:!1});function ReadStream2(path,options){return new InternalReadStream(path,options)}return ReadStream2.prototype=InternalReadStream.prototype,Object.defineProperty(ReadStream2,Symbol.hasInstance,{value(instance){return instance instanceof InternalReadStream}})}(class ReadStream2 extends Stream._getNativeReadableStreamPrototype(2,Stream.Readable){constructor(pathOrFd,options=defaultReadStreamOptions){if(typeof options!==\"object\"||!options)@throwTypeError(\"Expected options to be an object\");var{flags=defaultReadStreamOptions.flags,encoding=defaultReadStreamOptions.encoding,mode=defaultReadStreamOptions.mode,autoClose=defaultReadStreamOptions.autoClose,emitClose=defaultReadStreamOptions.emitClose,start=defaultReadStreamOptions.start,end=defaultReadStreamOptions.end,autoDestroy=defaultReadStreamOptions.autoClose,fs:fs2=defaultReadStreamOptions.fs,highWaterMark=defaultReadStreamOptions.highWaterMark}=options;if(pathOrFd\?.constructor\?.name===\"URL\")pathOrFd=Bun.fileURLToPath(pathOrFd);var tempThis={};if(typeof pathOrFd===\"string\"){if(pathOrFd.startsWith(\"file://\"))pathOrFd=Bun.fileURLToPath(pathOrFd);if(pathOrFd.length===0)@throwTypeError(\"Expected path to be a non-empty string\");tempThis.path=tempThis.file=tempThis[readStreamPathOrFdSymbol]=pathOrFd}else if(typeof pathOrFd===\"number\"){if(pathOrFd|=0,pathOrFd<0)@throwTypeError(\"Expected fd to be a positive integer\");tempThis.fd=tempThis[readStreamPathOrFdSymbol]=pathOrFd,tempThis.autoClose=!1}else @throwTypeError(\"Expected a path or file descriptor\");if(!tempThis.fd)tempThis.fd=fs2.openSync(pathOrFd,flags,mode);var fileRef=Bun.file(tempThis.fd),stream=fileRef.stream(),native=@direct(stream);if(!native)throw new Error(\"no native readable stream\");var{stream:ptr}=native;super(ptr,{...options,encoding,autoDestroy,autoClose,emitClose,highWaterMark});if(Object.assign(this,tempThis),this.#fileRef=fileRef,this.end=end,this._read=this.#internalRead,this.start=start,this.flags=flags,this.mode=mode,this.emitClose=emitClose,this[readStreamPathFastPathSymbol]=start===0&&end===Infinity&&autoClose&&fs2===defaultReadStreamOptions.fs&&(encoding===\"buffer\"||encoding===\"binary\"||encoding==null||encoding===\"utf-8\"||encoding===\"utf8\"),this._readableState.autoClose=autoDestroy=autoClose,this._readableState.highWaterMark=highWaterMark,start!==void 0)this.pos=start}#fileRef;#fs;file;path;fd=null;flags;mode;start;end;pos;bytesRead=0;#fileSize=-1;_read;[readStreamSymbol]=!0;[readStreamPathOrFdSymbol];[readStreamPathFastPathSymbol];_construct(callback){if(super._construct)super._construct(callback);else callback();this.emit(\"open\",this.fd),this.emit(\"ready\")}_destroy(err,cb){super._destroy(err,cb);try{var fd=this.fd;if(this[readStreamPathFastPathSymbol]=!1,!fd)cb(err);else this.#fs.close(fd,(er)=>{cb(er||err)}),this.fd=null}catch(e){throw e}}close(cb){if(typeof cb===\"function\")eos_()(this,cb);this.destroy()}push(chunk){var bytesRead=chunk\?.length\?\?0;if(bytesRead>0){this.bytesRead+=bytesRead;var currPos=this.pos;if(currPos!==void 0){if(this.bytesReadthis.end)chunk=chunk.slice(0,this.end-this.start+1);return super.push(chunk,...rest)}var end=this.end;if(end!==void 0&&this.bytesRead>end){chunk=chunk.slice(0,end-currPos+1);var[_,...rest]=arguments;return this.pos=this.bytesRead,super.push(chunk,...rest)}this.pos=this.bytesRead}}return super.push(...arguments)}#internalRead(n){var{pos,end,bytesRead,fd,encoding}=this;if(n=pos!==void 0\?Math.min(end-pos+1,n):Math.min(end-bytesRead+1,n),n<=0){this.push(null);return}if(this.#fileSize===-1&&bytesRead===0&&pos===void 0){var stat2=fstatSync(fd);if(this.#fileSize=stat2.size,this.#fileSize>0&&n>this.#fileSize)n=this.#fileSize+1}this[kIoDone]=!1;var res=super._read(n);if(@isPromise(res)){var then=res\?.then;if(then&&@isCallable(then))then(()=>{if(this[kIoDone]=!0,this.destroyed)this.emit(kIoDone)},(er)=>{this[kIoDone]=!0,this.#errorOrDestroy(er)})}else if(this[kIoDone]=!0,this.destroyed)this.emit(kIoDone),this.#errorOrDestroy(new Error(\"ERR_STREAM_PREMATURE_CLOSE\"))}#errorOrDestroy(err,sync=null){var{_readableState:r={destroyed:!1,autoDestroy:!1},_writableState:w={destroyed:!1,autoDestroy:!1}}=this;if(w\?.destroyed||r\?.destroyed)return this;if(r\?.autoDestroy||w\?.autoDestroy)this.destroy(err);else if(err)this.emit(\"error\",err)}pause(){return this[readStreamPathFastPathSymbol]=!1,super.pause()}resume(){return this[readStreamPathFastPathSymbol]=!1,super.resume()}unshift(...args){return this[readStreamPathFastPathSymbol]=!1,super.unshift(...args)}pipe(dest,pipeOpts){if(this[readStreamPathFastPathSymbol]&&(pipeOpts\?.end\?\?!0)&&this._readableState\?.pipes\?.length===0){if((writeStreamPathFastPathSymbol in dest)&&dest[writeStreamPathFastPathSymbol]){if(dest[writeStreamPathFastPathCallSymbol](this,pipeOpts))return this}}return this[readStreamPathFastPathSymbol]=!1,super.pipe(dest,pipeOpts)}});function createReadStream(path,options){return new ReadStream(path,options)}var defaultWriteStreamOptions={fd:null,start:void 0,pos:void 0,encoding:void 0,flags:\"w\",mode:438,fs:{write,close,open,openSync}},WriteStreamClass;WriteStream=function(InternalWriteStream){WriteStreamClass=InternalWriteStream,Object.defineProperty(WriteStreamClass.prototype,Symbol.toStringTag,{value:\"WritesStream\",enumerable:!1});function WriteStream2(path,options){return new InternalWriteStream(path,options)}return WriteStream2.prototype=InternalWriteStream.prototype,Object.defineProperty(WriteStream2,Symbol.hasInstance,{value(instance){return instance instanceof InternalWriteStream}})}(class WriteStream2 extends Stream.NativeWritable{constructor(path,options=defaultWriteStreamOptions){if(!options)@throwTypeError(\"Expected options to be an object\");var{fs:fs2=defaultWriteStreamOptions.fs,start=defaultWriteStreamOptions.start,flags=defaultWriteStreamOptions.flags,mode=defaultWriteStreamOptions.mode,autoClose=!0,emitClose=!1,autoDestroy=autoClose,encoding=defaultWriteStreamOptions.encoding,fd=defaultWriteStreamOptions.fd,pos=defaultWriteStreamOptions.pos}=options,tempThis={};if(typeof path===\"string\"){if(path.length===0)@throwTypeError(\"Expected a non-empty path\");if(path.startsWith(\"file:\"))path=Bun.fileURLToPath(path);tempThis.path=path,tempThis.fd=null,tempThis[writeStreamPathFastPathSymbol]=autoClose&&(start===void 0||start===0)&&fs2.write===defaultWriteStreamOptions.fs.write&&fs2.close===defaultWriteStreamOptions.fs.close}else tempThis.fd=fd,tempThis[writeStreamPathFastPathSymbol]=!1;if(!tempThis.fd)tempThis.fd=fs2.openSync(path,flags,mode);super(tempThis.fd,{...options,decodeStrings:!1,autoDestroy,emitClose,fd:tempThis});if(Object.assign(this,tempThis),typeof fs2\?.write!==\"function\")@throwTypeError(\"Expected fs.write to be a function\");if(typeof fs2\?.close!==\"function\")@throwTypeError(\"Expected fs.close to be a function\");if(typeof fs2\?.open!==\"function\")@throwTypeError(\"Expected fs.open to be a function\");if(typeof path===\"object\"&&path){if(path instanceof URL)path=Bun.fileURLToPath(path)}if(typeof path!==\"string\"&&typeof fd!==\"number\")@throwTypeError(\"Expected a path or file descriptor\");if(this.start=start,this.#fs=fs2,this.flags=flags,this.mode=mode,this.start!==void 0)this.pos=this.start;if(encoding!==defaultWriteStreamOptions.encoding){if(this.setDefaultEncoding(encoding),encoding!==\"buffer\"&&encoding!==\"utf8\"&&encoding!==\"utf-8\"&&encoding!==\"binary\")this[writeStreamPathFastPathSymbol]=!1}}get autoClose(){return this._writableState.autoDestroy}set autoClose(val){this._writableState.autoDestroy=val}destroySoon=this.end;open(){}path;fd;flags;mode;#fs;bytesWritten=0;pos;[writeStreamPathFastPathSymbol];[writeStreamSymbol]=!0;start;[writeStreamPathFastPathCallSymbol](readStream,pipeOpts){if(!this[writeStreamPathFastPathSymbol])return!1;if(this.fd!==null)return this[writeStreamPathFastPathSymbol]=!1,!1;return this[kIoDone]=!1,readStream[kIoDone]=!1,Bun.write(this[writeStreamPathFastPathSymbol],readStream[readStreamPathOrFdSymbol]).then((bytesWritten)=>{readStream[kIoDone]=this[kIoDone]=!0,this.bytesWritten+=bytesWritten,readStream.bytesRead+=bytesWritten,this.end(),readStream.close()},(err)=>{readStream[kIoDone]=this[kIoDone]=!0,this.#errorOrDestroy(err),readStream.emit(\"error\",err)})}isBunFastPathEnabled(){return this[writeStreamPathFastPathSymbol]}disableBunFastPath(){this[writeStreamPathFastPathSymbol]=!1}#handleWrite(er,bytes){if(er)return this.#errorOrDestroy(er);this.bytesWritten+=bytes}#internalClose(err,cb){this[writeStreamPathFastPathSymbol]=!1;var fd=this.fd;this.#fs.close(fd,(er)=>{this.fd=null,cb(err||er)})}_construct(callback){if(typeof this.fd===\"number\"){callback();return}callback(),this.emit(\"open\",this.fd),this.emit(\"ready\")}_destroy(err,cb){if(this.fd===null)return cb(err);if(this[kIoDone]){this.once(kIoDone,()=>this.#internalClose(err,cb));return}this.#internalClose(err,cb)}[kIoDone]=!1;close(cb){if(cb){if(this.closed){process.nextTick(cb);return}this.on(\"close\",cb)}if(!this.autoClose)this.on(\"finish\",this.destroy);this.end()}write(chunk,encoding=this._writableState.defaultEncoding,cb){if(this[writeStreamPathFastPathSymbol]=!1,typeof chunk===\"string\")chunk=Buffer.from(chunk,encoding);var native=this.pos===void 0;return this[kIoDone]=!0,super.write(chunk,encoding,native\?(err,bytes)=>{if(this[kIoDone]=!1,this.#handleWrite(err,bytes),this.emit(kIoDone),cb)!err\?cb():cb(err)}:()=>{},native)}#internalWriteSlow(chunk,encoding,cb){this.#fs.write(this.fd,chunk,0,chunk.length,this.pos,(err,bytes)=>{this[kIoDone]=!1,this.#handleWrite(err,bytes),this.emit(kIoDone),!err\?cb():cb(err)})}end(chunk,encoding,cb){var native=this.pos===void 0;return super.end(chunk,encoding,cb,native)}_write=this.#internalWriteSlow;_writev=void 0;get pending(){return this.fd===null}_destroy(err,cb){this.close(err,cb)}#errorOrDestroy(err){var{_readableState:r={destroyed:!1,autoDestroy:!1},_writableState:w={destroyed:!1,autoDestroy:!1}}=this;if(w\?.destroyed||r\?.destroyed)return this;if(r\?.autoDestroy||w\?.autoDestroy)this.destroy(err);else if(err)this.emit(\"error\",err)}});function createWriteStream(path,options){return new WriteStream(path,options)}return Object.defineProperties(fs,{createReadStream:{value:createReadStream},createWriteStream:{value:createWriteStream},ReadStream:{value:ReadStream},WriteStream:{value:WriteStream}}),realpath.native=realpath,realpathSync.native=realpathSync,$={access,accessSync,appendFile,appendFileSync,chmod,chmodSync,chown,chownSync,close,closeSync,constants:promises.constants,copyFile,copyFileSync,createReadStream,createWriteStream,Dirent,exists,existsSync,fchmod,fchmodSync,fchown,fchownSync,fstat,fstatSync,fsync,fsyncSync,ftruncate,ftruncateSync,futimes,futimesSync,lchmod,lchmodSync,lchown,lchownSync,link,linkSync,lstat,lstatSync,lutimes,lutimesSync,mkdir,mkdirSync,mkdtemp,mkdtempSync,open,openSync,promises,read,readFile,readFileSync,readSync,readdir,readdirSync,readlink,readlinkSync,realpath,realpathSync,rename,renameSync,rm,rmSync,rmdir,rmdirSync,stat,statSync,Stats,symlink,symlinkSync,truncate,truncateSync,unlink,unlinkSync,utimes,utimesSync,write,writeFile,writeFileSync,writeSync,WriteStream,ReadStream,watch,FSWatcher,writev,writevSync,readv,readvSync,[Symbol.for(\"::bunternal::\")]:{ReadStreamClass,WriteStreamClass}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeFSPromisesCode = "(function (){\"use strict\";var $;const constants=@processBindingConstants.fs;var fs=Bun.fs();const notrace=\"::bunternal::\";var promisify={[notrace]:(fsFunction)=>{return async function(...args){return await 1,fsFunction.apply(fs,args)}}}[notrace];function watch(filename,options={}){if(filename instanceof URL)@throwTypeError(\"Watch URLs are not supported yet\");else if(Buffer.isBuffer(filename))filename=filename.toString();else if(typeof filename!==\"string\")@throwTypeError(\"Expected path to be a string or Buffer\");let nextEventResolve=null;if(typeof options===\"string\")options={encoding:options};const queue=@createFIFO(),watcher=fs.watch(filename,options||{},(eventType,filename2)=>{if(queue.push({eventType,filename:filename2}),nextEventResolve){const resolve=nextEventResolve;nextEventResolve=null,resolve()}});return{[Symbol.asyncIterator](){let closed=!1;return{async next(){while(!closed){let event;while(event=queue.shift()){if(event.eventType===\"close\")return closed=!0,{value:void 0,done:!0};if(event.eventType===\"error\")throw closed=!0,event.filename;return{value:event,done:!1}}const{promise,resolve}=Promise.withResolvers();nextEventResolve=resolve,await promise}return{value:void 0,done:!0}},return(){if(!closed){if(watcher.close(),closed=!0,nextEventResolve){const resolve=nextEventResolve;nextEventResolve=null,resolve()}}return{value:void 0,done:!0}}}}}}return $={access:promisify(fs.accessSync),appendFile:promisify(fs.appendFileSync),close:promisify(fs.closeSync),copyFile:promisify(fs.copyFileSync),exists:promisify(fs.existsSync),chown:promisify(fs.chownSync),chmod:promisify(fs.chmodSync),fchmod:promisify(fs.fchmodSync),fchown:promisify(fs.fchownSync),fstat:promisify(fs.fstatSync),fsync:promisify(fs.fsyncSync),ftruncate:promisify(fs.ftruncateSync),futimes:promisify(fs.futimesSync),lchmod:promisify(fs.lchmodSync),lchown:promisify(fs.lchownSync),link:promisify(fs.linkSync),lstat:fs.lstat.bind(fs),mkdir:promisify(fs.mkdirSync),mkdtemp:promisify(fs.mkdtempSync),open:promisify(fs.openSync),read:promisify(fs.readSync),write:promisify(fs.writeSync),readdir:fs.readdir.bind(fs),readFile:fs.readFile.bind(fs),writeFile:promisify(fs.writeFileSync),readlink:promisify(fs.readlinkSync),realpath:promisify(fs.realpathSync),rename:promisify(fs.renameSync),stat:fs.stat.bind(fs),symlink:promisify(fs.symlinkSync),truncate:promisify(fs.truncateSync),unlink:promisify(fs.unlinkSync),utimes:promisify(fs.utimesSync),lutimes:promisify(fs.lutimesSync),rm:promisify(fs.rmSync),rmdir:promisify(fs.rmdirSync),writev:(fd,buffers,position)=>{return new Promise((resolve,reject)=>{try{var bytesWritten=fs.writevSync(fd,buffers,position)}catch(err){reject(err);return}resolve({bytesWritten,buffers})})},readv:(fd,buffers,position)=>{return new Promise((resolve,reject)=>{try{var bytesRead=fs.readvSync(fd,buffers,position)}catch(err){reject(err);return}resolve({bytesRead,buffers})})},constants,watch},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";var $;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),{isTypedArray}=@requireNativeModule(\"node:util/types\"),{Duplex,Readable,Writable}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),headerCharRegex=/[^\\t\\x20-\\x7e\\x80-\\xff]/;function checkInvalidHeaderChar(val){return RegExpPrototypeExec.call(headerCharRegex,val)!==null}const validateHeaderName=(name,label)=>{if(typeof name!==\"string\"||!name||!checkIsHttpToken(name))throw new Error(\"ERR_INVALID_HTTP_TOKEN\")},validateHeaderValue=(name,value)=>{if(value===void 0)throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");if(checkInvalidHeaderChar(value))throw new Error(\"ERR_INVALID_CHAR\")};function isIPv6(input){return new RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input)}const{URL}=globalThis,globalReportError=globalThis.reportError,setTimeout=globalThis.setTimeout,fetch=Bun.fetch,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.\";var _defaultHTTPSAgent,kInternalRequest=Symbol(\"kInternalRequest\"),kInternalSocketData=Symbol.for(\"::bunternal::\");const kEmptyBuffer=Buffer.alloc(0);function isValidTLSArray(obj){if(typeof obj===\"string\"||isTypedArray(obj)||obj instanceof ArrayBuffer||obj instanceof Blob)return!0;if(Array.isArray(obj)){for(var i=0;i{this.close()}),host=port\?.host,port=port\?.port,typeof port\?.callback===\"function\")onListen=port\?.callback}if(typeof backlog===\"function\")onListen=backlog;const ResponseClass=this.#options.ServerResponse||ServerResponse,RequestClass=this.#options.IncomingMessage||IncomingMessage;try{const tls=this.#tls;if(tls)this.serverName=tls.serverName||host||\"localhost\";this.#server=Bun.serve({tls,port,hostname:host,websocket:{open(ws){ws.data.open(ws)},message(ws,message){ws.data.message(ws,message)},close(ws,code,reason){ws.data.close(ws,code,reason)},drain(ws){ws.data.drain(ws)}},fetch(req,_server){var pendingResponse,pendingError,rejectFunction,resolveFunction,reject=(err)=>{if(pendingError)return;if(pendingError=err,rejectFunction)rejectFunction(err)},reply=function(resp){if(pendingResponse)return;if(pendingResponse=resp,resolveFunction)resolveFunction(resp)};const http_req=new RequestClass(req),http_res=new ResponseClass({reply,req:http_req});if(http_req.once(\"error\",(err)=>reject(err)),http_res.once(\"error\",(err)=>reject(err)),req.headers.get(\"upgrade\")){const socket=new FakeSocket;socket[kInternalSocketData]=[_server,http_res,req],server.emit(\"upgrade\",http_req,socket,kEmptyBuffer)}else server.emit(\"request\",http_req,http_res);if(pendingError)throw pendingError;if(pendingResponse)return pendingResponse;return new Promise((resolve,reject2)=>{resolveFunction=resolve,rejectFunction=reject2})}}),setTimeout(emitListeningNextTick,1,this,onListen,null,this.#server.hostname,this.#server.port)}catch(err){setTimeout(emitListeningNextTick,1,this,onListen,err)}return this}setTimeout(msecs,callback){}}function assignHeaders(object,req){var headers=req.headers.toJSON();const rawHeaders=@newArrayWithSize(req.headers.count*2);var i=0;for(let key in headers)rawHeaders[i++]=key,rawHeaders[i++]=headers[key];object.headers=headers,object.rawHeaders=rawHeaders}function destroyBodyStreamNT(bodyStream){bodyStream.destroy()}var defaultIncomingOpts={type:\"request\"};function getDefaultHTTPSAgent(){return _defaultHTTPSAgent\?\?=new Agent({defaultPort:443,protocol:\"https:\"})}class IncomingMessage extends Readable{method;complete;constructor(req,defaultIncomingOpts2){const method=req.method;super();const url=new URL(req.url);var{type=\"request\",[kInternalRequest]:nodeReq}=defaultIncomingOpts2||{};this.#noBody=type===\"request\"\?method===\"GET\"||method===\"HEAD\"||method===\"TRACE\"||method===\"CONNECT\"||method===\"OPTIONS\"||(parseInt(req.headers.get(\"Content-Length\")||\"\")||0)===0:!1,this.#req=req,this.method=method,this.#type=type,this.complete=!!this.#noBody,this.#bodyStream=void 0;const socket=new FakeSocket;socket.remoteAddress=url.hostname,socket.remotePort=url.port,this.#fakeSocket=socket,this.url=url.pathname+url.search,this.#nodeReq=nodeReq,assignHeaders(this,req)}headers;rawHeaders;_consuming=!1;_dumped=!1;#bodyStream;#fakeSocket;#noBody=!1;#aborted=!1;#req;url;#type;#nodeReq;get req(){return this.#nodeReq}_construct(callback){if(this.#type===\"response\"||this.#noBody){callback();return}const contentLength=this.#req.headers.get(\"content-length\");if((contentLength\?parseInt(contentLength,10):0)===0){this.#noBody=!0,callback();return}callback()}async#consumeStream(reader){while(!0){var{done,value}=await reader.readMany();if(this.#aborted)return;if(done){this.push(null),this.destroy();break}for(var v of value)this.push(v)}}_read(size){if(this.#noBody)this.push(null),this.complete=!0;else if(this.#bodyStream==null){const reader=this.#req.body\?.getReader();if(!reader){this.push(null);return}this.#bodyStream=reader,this.#consumeStream(reader)}}get aborted(){return this.#aborted}#abort(){if(this.#aborted)return;this.#aborted=!0;var bodyStream=this.#bodyStream;if(!bodyStream)return;bodyStream.cancel(),this.complete=!0,this.#bodyStream=void 0,this.push(null)}get connection(){return this.#fakeSocket}get statusCode(){return this.#req.status}get statusMessage(){return STATUS_CODES[this.#req.status]}get httpVersion(){return\"1.1\"}get rawTrailers(){return[]}get httpVersionMajor(){return 1}get httpVersionMinor(){return 1}get trailers(){return kEmptyObject}get socket(){return this.#fakeSocket\?\?=new FakeSocket}set socket(val){this.#fakeSocket=val}setTimeout(msecs,callback){throw new Error(\"not implemented\")}}function emitErrorNt(msg,err,callback){if(callback(err),typeof msg.emit===\"function\"&&!msg._closed)msg.emit(\"error\",err)}function onError(self,err,cb){process.nextTick(()=>emitErrorNt(self,err,cb))}function write_(msg,chunk,encoding,callback,fromEnd){if(typeof callback!==\"function\")callback=nop;let len;if(chunk===null)throw new Error(\"ERR_STREAM_NULL_VALUES\");else if(typeof chunk===\"string\")len=Buffer.byteLength(chunk,encoding);else throw new Error(\"Invalid arg type for chunk\");let err;if(msg.finished)err=new Error(\"ERR_STREAM_WRITE_AFTER_END\");else if(msg.destroyed)err=new Error(\"ERR_STREAM_DESTROYED\");if(err){if(!msg.destroyed)onError(msg,err,callback);else process.nextTick(callback,err);return!1}if(!msg._header){if(fromEnd)msg._contentLength=len}if(!msg._hasBody)return process.nextTick(callback),!0;return!0}class OutgoingMessage extends Writable{constructor(){super(...arguments)}#headers;headersSent=!1;sendDate=!0;req;timeout;#finished=!1;[kEndCalled]=!1;#fakeSocket;#timeoutTimer;[kAbortController]=null;_implicitHeader(){}get headers(){if(!this.#headers)return kEmptyObject;return this.#headers.toJSON()}get shouldKeepAlive(){return!0}get chunkedEncoding(){return!1}set chunkedEncoding(value){}set shouldKeepAlive(value){}get useChunkedEncodingByDefault(){return!0}set useChunkedEncodingByDefault(value){}get socket(){return this.#fakeSocket\?\?=new FakeSocket}set socket(val){this.#fakeSocket=val}get connection(){return this.socket}get finished(){return this.#finished}appendHeader(name,value){var headers=this.#headers\?\?=new Headers;headers.append(name,value)}flushHeaders(){}getHeader(name){return getHeader(this.#headers,name)}getHeaders(){if(!this.#headers)return kEmptyObject;return this.#headers.toJSON()}getHeaderNames(){var headers=this.#headers;if(!headers)return[];return Array.from(headers.keys())}removeHeader(name){if(!this.#headers)return;this.#headers.delete(name)}setHeader(name,value){var headers=this.#headers\?\?=new Headers;return headers.set(name,value),this}hasHeader(name){if(!this.#headers)return!1;return this.#headers.has(name)}addTrailers(headers){throw new Error(\"not implemented\")}[kClearTimeout](){if(this.#timeoutTimer)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.destroyed)return 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}}let OriginalWriteHeadFn,OriginalImplicitHeadFn;class ServerResponse extends Writable{constructor({req,reply}){super();if(this.req=req,this._reply=reply,this.sendDate=!0,this.statusCode=200,this.headersSent=!1,this.statusMessage=void 0,this.#controller=void 0,this.#firstWrite=void 0,this._writableState.decodeStrings=!1,this.#deferred=void 0,req.method===\"HEAD\")this._hasBody=!1}req;_reply;sendDate;statusCode;#headers;headersSent=!1;statusMessage;#controller;#firstWrite;_sent100=!1;_defaultKeepAlive=!1;_removedConnection=!1;_removedContLen=!1;_hasBody=!0;#deferred=void 0;#finished=!1;_implicitHeader(){this.writeHead(this.statusCode)}_write(chunk,encoding,callback){if(!this.#firstWrite&&!this.headersSent){this.#firstWrite=chunk,callback();return}this.#ensureReadableStreamController((controller)=>{controller.write(chunk),callback()})}_writev(chunks,callback){if(chunks.length===1&&!this.headersSent&&!this.#firstWrite){this.#firstWrite=chunks[0].chunk,callback();return}this.#ensureReadableStreamController((controller)=>{for(let chunk of chunks)controller.write(chunk.chunk);callback()})}#ensureReadableStreamController(run){var thisController=this.#controller;if(thisController)return run(thisController);this.headersSent=!0;var firstWrite=this.#firstWrite;this.#firstWrite=void 0,this._reply(new Response(new ReadableStream({type:\"direct\",pull:(controller)=>{if(this.#controller=controller,firstWrite)controller.write(firstWrite);if(firstWrite=void 0,run(controller),!this.#finished)return new Promise((resolve)=>{this.#deferred=resolve})}}),{headers:this.#headers,status:this.statusCode,statusText:this.statusMessage\?\?STATUS_CODES[this.statusCode]}))}#drainHeadersIfObservable(){if(this._implicitHeader===OriginalImplicitHeadFn&&this.writeHead===OriginalWriteHeadFn)return;this._implicitHeader()}_final(callback){if(!this.headersSent){var data=this.#firstWrite||\"\";this.#firstWrite=void 0,this.#finished=!0,this.#drainHeadersIfObservable(),this._reply(new Response(data,{headers:this.#headers,status:this.statusCode,statusText:this.statusMessage\?\?STATUS_CODES[this.statusCode]})),callback&&callback();return}this.#finished=!0,this.#ensureReadableStreamController((controller)=>{controller.end(),callback();var deferred=this.#deferred;if(deferred)this.#deferred=void 0,deferred()})}writeProcessing(){throw new Error(\"not implemented\")}addTrailers(headers){throw new Error(\"not implemented\")}assignSocket(socket){throw new Error(\"not implemented\")}detachSocket(socket){throw new Error(\"not implemented\")}writeContinue(callback){throw new Error(\"not implemented\")}setTimeout(msecs,callback){throw new Error(\"not implemented\")}get shouldKeepAlive(){return!0}get chunkedEncoding(){return!1}set chunkedEncoding(value){}set shouldKeepAlive(value){}get useChunkedEncodingByDefault(){return!0}set useChunkedEncodingByDefault(value){}appendHeader(name,value){var headers=this.#headers\?\?=new Headers;headers.append(name,value)}flushHeaders(){}getHeader(name){return getHeader(this.#headers,name)}getHeaders(){var headers=this.#headers;if(!headers)return kEmptyObject;return headers.toJSON()}getHeaderNames(){var headers=this.#headers;if(!headers)return[];return Array.from(headers.keys())}removeHeader(name){if(!this.#headers)return;this.#headers.delete(name)}setHeader(name,value){var headers=this.#headers\?\?=new Headers;return headers.set(name,value),this}hasHeader(name){if(!this.#headers)return!1;return this.#headers.has(name)}writeHead(statusCode,statusMessage,headers){return _writeHead(statusCode,statusMessage,headers,this),this}}OriginalWriteHeadFn=ServerResponse.prototype.writeHead,OriginalImplicitHeadFn=ServerResponse.prototype._implicitHeader;class ClientRequest extends OutgoingMessage{#timeout;#res=null;#upgradeOrConnect=!1;#parser=null;#maxHeadersCount=null;#reusedSocket=!1;#host;#protocol;#method;#port;#useDefaultPort;#joinDuplicateHeaders;#maxHeaderSize;#agent=globalAgent;#path;#socketPath;#bodyChunks=null;#fetchRequest;#signal=null;[kAbortController]=null;#timeoutTimer=void 0;#options;#finished;get path(){return this.#path}get port(){return this.#port}get method(){return this.#method}get host(){return this.#host}get protocol(){return this.#protocol}_write(chunk,encoding,callback){if(!this.#bodyChunks){this.#bodyChunks=[chunk],callback();return}this.#bodyChunks.push(chunk),callback()}_writev(chunks,callback){if(!this.#bodyChunks){this.#bodyChunks=chunks,callback();return}this.#bodyChunks.push(...chunks),callback()}_final(callback){if(this.#finished=!0,this[kAbortController]=new AbortController,this[kAbortController].signal.addEventListener(\"abort\",()=>{this[kClearTimeout]()}),this.#signal\?.aborted)this[kAbortController].abort();var method=this.#method,body=this.#bodyChunks\?.length===1\?this.#bodyChunks[0]:Buffer.concat(this.#bodyChunks||[]);try{this.#fetchRequest=fetch(`${this.#protocol}//${this.#host}${this.#useDefaultPort\?\"\":\":\"+this.#port}${this.#path}`,{method,headers:this.getHeaders(),body:body&&method!==\"GET\"&&method!==\"HEAD\"&&method!==\"OPTIONS\"\?body:void 0,redirect:\"manual\",verbose:!1,signal:this[kAbortController].signal,timeout:!1}).then((response)=>{var res=this.#res=new IncomingMessage(response,{type:\"response\",[kInternalRequest]:this});this.emit(\"response\",res)}).catch((err)=>{this.emit(\"error\",err)}).finally(()=>{this.#fetchRequest=null,this[kClearTimeout]()})}catch(err){this.emit(\"error\",err)}finally{callback()}}get aborted(){return this.#signal\?.aborted||!!this[kAbortController]\?.signal.aborted}abort(){if(this.aborted)return;this[kAbortController].abort()}constructor(input,options,cb){super();if(typeof input===\"string\"){const urlStr=input;try{var urlObject=new URL(urlStr)}catch(e){@throwTypeError(`Invalid URL: ${urlStr}`)}input=urlToHttpOptions(urlObject)}else if(input&&typeof input===\"object\"&&input instanceof URL)input=urlToHttpOptions(input);else cb=options,options=input,input=null;if(typeof options===\"function\")cb=options,options=input||kEmptyObject;else options=ObjectAssign(input||{},options);var defaultAgent=options._defaultAgent||Agent.globalAgent;let protocol=options.protocol;if(!protocol)if(options.port===443)protocol=\"https:\";else protocol=defaultAgent.protocol||\"http:\";switch(this.#protocol=protocol,this.#agent\?.protocol){case void 0:break;case\"http:\":if(protocol===\"https:\"){defaultAgent=this.#agent=getDefaultHTTPSAgent();break}case\"https:\":if(protocol===\"https\"){defaultAgent=this.#agent=Agent.globalAgent;break}default:break}if(options.path){const path=String(options.path);if(RegExpPrototypeExec.call(INVALID_PATH_REGEX,path)!==null)throw new Error(\"Path contains unescaped characters\")}if(protocol!==\"http:\"&&protocol!==\"https:\"&&protocol){const expectedProtocol=defaultAgent\?.protocol\?\?\"http:\";throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`)}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\";this.#socketPath=options.socketPath;const signal=options.signal;if(signal)signal.addEventListener(\"abort\",()=>{this[kAbortController]\?.abort()}),this.#signal=signal;let method=options.method;const methodIsString=typeof method===\"string\";if(method!==null&&method!==void 0&&!methodIsString)throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");if(methodIsString&&method){if(!checkIsHttpToken(method))throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");method=this.#method=StringPrototypeToUpperCase.call(method)}else method=this.#method=\"GET\";const _maxHeaderSize=options.maxHeaderSize;this.#maxHeaderSize=_maxHeaderSize;var _joinDuplicateHeaders=options.joinDuplicateHeaders;if(this.#joinDuplicateHeaders=_joinDuplicateHeaders,this.#path=options.path||\"/\",cb)this.once(\"response\",cb);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)this.setHeader(key,headers[key]);var auth=options.auth;if(auth&&!this.getHeader(\"Authorization\"))this.setHeader(\"Authorization\",\"Basic \"+Buffer.from(auth).toString(\"base64\"))}var{signal:_signal,...optsWithoutSignal}=options;this.#options=optsWithoutSignal}setSocketKeepAlive(enable=!0,initialDelay=0){}setNoDelay(noDelay=!0){}[kClearTimeout](){if(this.#timeoutTimer)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.destroyed)return 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}}function urlToHttpOptions(url){var{protocol,hostname,hash,search,pathname,href,port,username,password}=url;return{protocol,hostname:typeof hostname===\"string\"&&StringPrototypeStartsWith.call(hostname,\"[\")\?StringPrototypeSlice.call(hostname,1,-1):hostname,hash,search,pathname,path:`${pathname||\"\"}${search||\"\"}`,href,port:port\?Number(port):protocol===\"https:\"\?443:protocol===\"http:\"\?80:void 0,auth:username||password\?`${decodeURIComponent(username)}:${decodeURIComponent(password)}`:void 0}}function validateHost(host,name){if(host!==null&&host!==void 0&&typeof host!==\"string\")throw new Error(\"Invalid arg type in options\");return host}const tokenRegExp=/^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/;function checkIsHttpToken(val){return RegExpPrototypeExec.call(tokenRegExp,val)!==null}const METHODS=[\"ACL\",\"BIND\",\"CHECKOUT\",\"CONNECT\",\"COPY\",\"DELETE\",\"GET\",\"HEAD\",\"LINK\",\"LOCK\",\"M-SEARCH\",\"MERGE\",\"MKACTIVITY\",\"MKCALENDAR\",\"MKCOL\",\"MOVE\",\"NOTIFY\",\"OPTIONS\",\"PATCH\",\"POST\",\"PROPFIND\",\"PROPPATCH\",\"PURGE\",\"PUT\",\"REBIND\",\"REPORT\",\"SEARCH\",\"SOURCE\",\"SUBSCRIBE\",\"TRACE\",\"UNBIND\",\"UNLINK\",\"UNLOCK\",\"UNSUBSCRIBE\"],STATUS_CODES={100:\"Continue\",101:\"Switching Protocols\",102:\"Processing\",103:\"Early Hints\",200:\"OK\",201:\"Created\",202:\"Accepted\",203:\"Non-Authoritative Information\",204:\"No Content\",205:\"Reset Content\",206:\"Partial Content\",207:\"Multi-Status\",208:\"Already Reported\",226:\"IM Used\",300:\"Multiple Choices\",301:\"Moved Permanently\",302:\"Found\",303:\"See Other\",304:\"Not Modified\",305:\"Use Proxy\",307:\"Temporary Redirect\",308:\"Permanent Redirect\",400:\"Bad Request\",401:\"Unauthorized\",402:\"Payment Required\",403:\"Forbidden\",404:\"Not Found\",405:\"Method Not Allowed\",406:\"Not Acceptable\",407:\"Proxy Authentication Required\",408:\"Request Timeout\",409:\"Conflict\",410:\"Gone\",411:\"Length Required\",412:\"Precondition Failed\",413:\"Payload Too Large\",414:\"URI Too Long\",415:\"Unsupported Media Type\",416:\"Range Not Satisfiable\",417:\"Expectation Failed\",418:\"I'm a Teapot\",421:\"Misdirected Request\",422:\"Unprocessable Entity\",423:\"Locked\",424:\"Failed Dependency\",425:\"Too Early\",426:\"Upgrade Required\",428:\"Precondition Required\",429:\"Too Many Requests\",431:\"Request Header Fields Too Large\",451:\"Unavailable For Legal Reasons\",500:\"Internal Server Error\",501:\"Not Implemented\",502:\"Bad Gateway\",503:\"Service Unavailable\",504:\"Gateway Timeout\",505:\"HTTP Version Not Supported\",506:\"Variant Also Negotiates\",507:\"Insufficient Storage\",508:\"Loop Detected\",509:\"Bandwidth Limit Exceeded\",510:\"Not Extended\",511:\"Network Authentication Required\"};function _normalizeArgs(args){let arr;if(args.length===0)return arr=[{},null],arr;const arg0=args[0];let options={};if(typeof arg0===\"object\"&&arg0!==null)options=arg0;else if(options.port=arg0,args.length>1&&typeof args[1]===\"string\")options.host=args[1];const cb=args[args.length-1];if(typeof cb!==\"function\")arr=[options,null];else arr=[options,cb];return arr}function _writeHead(statusCode,reason,obj,response){if(statusCode|=0,statusCode<100||statusCode>999)throw new Error(\"status code must be between 100 and 999\");if(typeof reason===\"string\")response.statusMessage=reason;else{if(!response.statusMessage)response.statusMessage=STATUS_CODES[statusCode]||\"unknown\";obj=reason}response.statusCode=statusCode;{let k;if(Array.isArray(obj)){if(obj.length%2!==0)throw new Error(\"raw headers must have an even number of elements\");for(let n=0;n=100&&statusCode<=199)response._hasBody=!1}function request(url,options,cb){return new ClientRequest(url,options,cb)}function get(url,options,cb){const req=request(url,options,cb);return req.end(),req}var globalAgent=new Agent;return $={Agent,Server,METHODS,STATUS_CODES,createServer,ServerResponse,IncomingMessage,request,get,maxHeaderSize:16384,validateHeaderName,validateHeaderValue,setMaxIdleHTTPParsers(max){},globalAgent,ClientRequest,OutgoingMessage},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttp2Code = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function connect(){throwNotImplemented(\"node:http2 connect\",887)}const constants={NGHTTP2_ERR_FRAME_SIZE_ERROR:-522,NGHTTP2_SESSION_SERVER:0,NGHTTP2_SESSION_CLIENT:1,NGHTTP2_STREAM_STATE_IDLE:1,NGHTTP2_STREAM_STATE_OPEN:2,NGHTTP2_STREAM_STATE_RESERVED_LOCAL:3,NGHTTP2_STREAM_STATE_RESERVED_REMOTE:4,NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL:5,NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE:6,NGHTTP2_STREAM_STATE_CLOSED:7,NGHTTP2_FLAG_NONE:0,NGHTTP2_FLAG_END_STREAM:1,NGHTTP2_FLAG_END_HEADERS:4,NGHTTP2_FLAG_ACK:1,NGHTTP2_FLAG_PADDED:8,NGHTTP2_FLAG_PRIORITY:32,DEFAULT_SETTINGS_HEADER_TABLE_SIZE:4096,DEFAULT_SETTINGS_ENABLE_PUSH:1,DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS:4294967295,DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE:65535,DEFAULT_SETTINGS_MAX_FRAME_SIZE:16384,DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE:65535,DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL:0,MAX_MAX_FRAME_SIZE:16777215,MIN_MAX_FRAME_SIZE:16384,MAX_INITIAL_WINDOW_SIZE:2147483647,NGHTTP2_SETTINGS_HEADER_TABLE_SIZE:1,NGHTTP2_SETTINGS_ENABLE_PUSH:2,NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS:3,NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE:4,NGHTTP2_SETTINGS_MAX_FRAME_SIZE:5,NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE:6,NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL:8,PADDING_STRATEGY_NONE:0,PADDING_STRATEGY_ALIGNED:1,PADDING_STRATEGY_MAX:2,PADDING_STRATEGY_CALLBACK:1,NGHTTP2_NO_ERROR:0,NGHTTP2_PROTOCOL_ERROR:1,NGHTTP2_INTERNAL_ERROR:2,NGHTTP2_FLOW_CONTROL_ERROR:3,NGHTTP2_SETTINGS_TIMEOUT:4,NGHTTP2_STREAM_CLOSED:5,NGHTTP2_FRAME_SIZE_ERROR:6,NGHTTP2_REFUSED_STREAM:7,NGHTTP2_CANCEL:8,NGHTTP2_COMPRESSION_ERROR:9,NGHTTP2_CONNECT_ERROR:10,NGHTTP2_ENHANCE_YOUR_CALM:11,NGHTTP2_INADEQUATE_SECURITY:12,NGHTTP2_HTTP_1_1_REQUIRED:13,NGHTTP2_DEFAULT_WEIGHT:16,HTTP2_HEADER_STATUS:\":status\",HTTP2_HEADER_METHOD:\":method\",HTTP2_HEADER_AUTHORITY:\":authority\",HTTP2_HEADER_SCHEME:\":scheme\",HTTP2_HEADER_PATH:\":path\",HTTP2_HEADER_PROTOCOL:\":protocol\",HTTP2_HEADER_ACCEPT_ENCODING:\"accept-encoding\",HTTP2_HEADER_ACCEPT_LANGUAGE:\"accept-language\",HTTP2_HEADER_ACCEPT_RANGES:\"accept-ranges\",HTTP2_HEADER_ACCEPT:\"accept\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS:\"access-control-allow-credentials\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS:\"access-control-allow-headers\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS:\"access-control-allow-methods\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN:\"access-control-allow-origin\",HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS:\"access-control-expose-headers\",HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS:\"access-control-request-headers\",HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD:\"access-control-request-method\",HTTP2_HEADER_AGE:\"age\",HTTP2_HEADER_AUTHORIZATION:\"authorization\",HTTP2_HEADER_CACHE_CONTROL:\"cache-control\",HTTP2_HEADER_CONNECTION:\"connection\",HTTP2_HEADER_CONTENT_DISPOSITION:\"content-disposition\",HTTP2_HEADER_CONTENT_ENCODING:\"content-encoding\",HTTP2_HEADER_CONTENT_LENGTH:\"content-length\",HTTP2_HEADER_CONTENT_TYPE:\"content-type\",HTTP2_HEADER_COOKIE:\"cookie\",HTTP2_HEADER_DATE:\"date\",HTTP2_HEADER_ETAG:\"etag\",HTTP2_HEADER_FORWARDED:\"forwarded\",HTTP2_HEADER_HOST:\"host\",HTTP2_HEADER_IF_MODIFIED_SINCE:\"if-modified-since\",HTTP2_HEADER_IF_NONE_MATCH:\"if-none-match\",HTTP2_HEADER_IF_RANGE:\"if-range\",HTTP2_HEADER_LAST_MODIFIED:\"last-modified\",HTTP2_HEADER_LINK:\"link\",HTTP2_HEADER_LOCATION:\"location\",HTTP2_HEADER_RANGE:\"range\",HTTP2_HEADER_REFERER:\"referer\",HTTP2_HEADER_SERVER:\"server\",HTTP2_HEADER_SET_COOKIE:\"set-cookie\",HTTP2_HEADER_STRICT_TRANSPORT_SECURITY:\"strict-transport-security\",HTTP2_HEADER_TRANSFER_ENCODING:\"transfer-encoding\",HTTP2_HEADER_TE:\"te\",HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS:\"upgrade-insecure-requests\",HTTP2_HEADER_UPGRADE:\"upgrade\",HTTP2_HEADER_USER_AGENT:\"user-agent\",HTTP2_HEADER_VARY:\"vary\",HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS:\"x-content-type-options\",HTTP2_HEADER_X_FRAME_OPTIONS:\"x-frame-options\",HTTP2_HEADER_KEEP_ALIVE:\"keep-alive\",HTTP2_HEADER_PROXY_CONNECTION:\"proxy-connection\",HTTP2_HEADER_X_XSS_PROTECTION:\"x-xss-protection\",HTTP2_HEADER_ALT_SVC:\"alt-svc\",HTTP2_HEADER_CONTENT_SECURITY_POLICY:\"content-security-policy\",HTTP2_HEADER_EARLY_DATA:\"early-data\",HTTP2_HEADER_EXPECT_CT:\"expect-ct\",HTTP2_HEADER_ORIGIN:\"origin\",HTTP2_HEADER_PURPOSE:\"purpose\",HTTP2_HEADER_TIMING_ALLOW_ORIGIN:\"timing-allow-origin\",HTTP2_HEADER_X_FORWARDED_FOR:\"x-forwarded-for\",HTTP2_HEADER_PRIORITY:\"priority\",HTTP2_HEADER_ACCEPT_CHARSET:\"accept-charset\",HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE:\"access-control-max-age\",HTTP2_HEADER_ALLOW:\"allow\",HTTP2_HEADER_CONTENT_LANGUAGE:\"content-language\",HTTP2_HEADER_CONTENT_LOCATION:\"content-location\",HTTP2_HEADER_CONTENT_MD5:\"content-md5\",HTTP2_HEADER_CONTENT_RANGE:\"content-range\",HTTP2_HEADER_DNT:\"dnt\",HTTP2_HEADER_EXPECT:\"expect\",HTTP2_HEADER_EXPIRES:\"expires\",HTTP2_HEADER_FROM:\"from\",HTTP2_HEADER_IF_MATCH:\"if-match\",HTTP2_HEADER_IF_UNMODIFIED_SINCE:\"if-unmodified-since\",HTTP2_HEADER_MAX_FORWARDS:\"max-forwards\",HTTP2_HEADER_PREFER:\"prefer\",HTTP2_HEADER_PROXY_AUTHENTICATE:\"proxy-authenticate\",HTTP2_HEADER_PROXY_AUTHORIZATION:\"proxy-authorization\",HTTP2_HEADER_REFRESH:\"refresh\",HTTP2_HEADER_RETRY_AFTER:\"retry-after\",HTTP2_HEADER_TRAILER:\"trailer\",HTTP2_HEADER_TK:\"tk\",HTTP2_HEADER_VIA:\"via\",HTTP2_HEADER_WARNING:\"warning\",HTTP2_HEADER_WWW_AUTHENTICATE:\"www-authenticate\",HTTP2_HEADER_HTTP2_SETTINGS:\"http2-settings\",HTTP2_METHOD_ACL:\"ACL\",HTTP2_METHOD_BASELINE_CONTROL:\"BASELINE-CONTROL\",HTTP2_METHOD_BIND:\"BIND\",HTTP2_METHOD_CHECKIN:\"CHECKIN\",HTTP2_METHOD_CHECKOUT:\"CHECKOUT\",HTTP2_METHOD_CONNECT:\"CONNECT\",HTTP2_METHOD_COPY:\"COPY\",HTTP2_METHOD_DELETE:\"DELETE\",HTTP2_METHOD_GET:\"GET\",HTTP2_METHOD_HEAD:\"HEAD\",HTTP2_METHOD_LABEL:\"LABEL\",HTTP2_METHOD_LINK:\"LINK\",HTTP2_METHOD_LOCK:\"LOCK\",HTTP2_METHOD_MERGE:\"MERGE\",HTTP2_METHOD_MKACTIVITY:\"MKACTIVITY\",HTTP2_METHOD_MKCALENDAR:\"MKCALENDAR\",HTTP2_METHOD_MKCOL:\"MKCOL\",HTTP2_METHOD_MKREDIRECTREF:\"MKREDIRECTREF\",HTTP2_METHOD_MKWORKSPACE:\"MKWORKSPACE\",HTTP2_METHOD_MOVE:\"MOVE\",HTTP2_METHOD_OPTIONS:\"OPTIONS\",HTTP2_METHOD_ORDERPATCH:\"ORDERPATCH\",HTTP2_METHOD_PATCH:\"PATCH\",HTTP2_METHOD_POST:\"POST\",HTTP2_METHOD_PRI:\"PRI\",HTTP2_METHOD_PROPFIND:\"PROPFIND\",HTTP2_METHOD_PROPPATCH:\"PROPPATCH\",HTTP2_METHOD_PUT:\"PUT\",HTTP2_METHOD_REBIND:\"REBIND\",HTTP2_METHOD_REPORT:\"REPORT\",HTTP2_METHOD_SEARCH:\"SEARCH\",HTTP2_METHOD_TRACE:\"TRACE\",HTTP2_METHOD_UNBIND:\"UNBIND\",HTTP2_METHOD_UNCHECKOUT:\"UNCHECKOUT\",HTTP2_METHOD_UNLINK:\"UNLINK\",HTTP2_METHOD_UNLOCK:\"UNLOCK\",HTTP2_METHOD_UPDATE:\"UPDATE\",HTTP2_METHOD_UPDATEREDIRECTREF:\"UPDATEREDIRECTREF\",HTTP2_METHOD_VERSION_CONTROL:\"VERSION-CONTROL\",HTTP_STATUS_CONTINUE:100,HTTP_STATUS_SWITCHING_PROTOCOLS:101,HTTP_STATUS_PROCESSING:102,HTTP_STATUS_EARLY_HINTS:103,HTTP_STATUS_OK:200,HTTP_STATUS_CREATED:201,HTTP_STATUS_ACCEPTED:202,HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:203,HTTP_STATUS_NO_CONTENT:204,HTTP_STATUS_RESET_CONTENT:205,HTTP_STATUS_PARTIAL_CONTENT:206,HTTP_STATUS_MULTI_STATUS:207,HTTP_STATUS_ALREADY_REPORTED:208,HTTP_STATUS_IM_USED:226,HTTP_STATUS_MULTIPLE_CHOICES:300,HTTP_STATUS_MOVED_PERMANENTLY:301,HTTP_STATUS_FOUND:302,HTTP_STATUS_SEE_OTHER:303,HTTP_STATUS_NOT_MODIFIED:304,HTTP_STATUS_USE_PROXY:305,HTTP_STATUS_TEMPORARY_REDIRECT:307,HTTP_STATUS_PERMANENT_REDIRECT:308,HTTP_STATUS_BAD_REQUEST:400,HTTP_STATUS_UNAUTHORIZED:401,HTTP_STATUS_PAYMENT_REQUIRED:402,HTTP_STATUS_FORBIDDEN:403,HTTP_STATUS_NOT_FOUND:404,HTTP_STATUS_METHOD_NOT_ALLOWED:405,HTTP_STATUS_NOT_ACCEPTABLE:406,HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:407,HTTP_STATUS_REQUEST_TIMEOUT:408,HTTP_STATUS_CONFLICT:409,HTTP_STATUS_GONE:410,HTTP_STATUS_LENGTH_REQUIRED:411,HTTP_STATUS_PRECONDITION_FAILED:412,HTTP_STATUS_PAYLOAD_TOO_LARGE:413,HTTP_STATUS_URI_TOO_LONG:414,HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:415,HTTP_STATUS_RANGE_NOT_SATISFIABLE:416,HTTP_STATUS_EXPECTATION_FAILED:417,HTTP_STATUS_TEAPOT:418,HTTP_STATUS_MISDIRECTED_REQUEST:421,HTTP_STATUS_UNPROCESSABLE_ENTITY:422,HTTP_STATUS_LOCKED:423,HTTP_STATUS_FAILED_DEPENDENCY:424,HTTP_STATUS_TOO_EARLY:425,HTTP_STATUS_UPGRADE_REQUIRED:426,HTTP_STATUS_PRECONDITION_REQUIRED:428,HTTP_STATUS_TOO_MANY_REQUESTS:429,HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:431,HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:451,HTTP_STATUS_INTERNAL_SERVER_ERROR:500,HTTP_STATUS_NOT_IMPLEMENTED:501,HTTP_STATUS_BAD_GATEWAY:502,HTTP_STATUS_SERVICE_UNAVAILABLE:503,HTTP_STATUS_GATEWAY_TIMEOUT:504,HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:505,HTTP_STATUS_VARIANT_ALSO_NEGOTIATES:506,HTTP_STATUS_INSUFFICIENT_STORAGE:507,HTTP_STATUS_LOOP_DETECTED:508,HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED:509,HTTP_STATUS_NOT_EXTENDED:510,HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:511};function createServer(){throwNotImplemented(\"node:http2 createServer\",887)}function createSecureServer(){throwNotImplemented(\"node:http2 createSecureServer\",887)}function getDefaultSettings(){return{headerTableSize:4096,enablePush:!0,initialWindowSize:65535,maxFrameSize:16384,maxConcurrentStreams:4294967295,maxHeaderSize:65535,maxHeaderListSize:65535,enableConnectProtocol:!1}}function getPackedSettings(){return Buffer.alloc(0)}function getUnpackedSettings(){return Buffer.alloc(0)}const sensitiveHeaders=Symbol.for(\"nodejs.http2.sensitiveHeaders\");function Http2ServerRequest(){throwNotImplemented(\"node:http2 Http2ServerRequest\",887)}function Http2ServerResponse(){throwNotImplemented(\"node:http2 Http2ServerResponse\",887)}return $={constants,createServer,createSecureServer,getDefaultSettings,getPackedSettings,getUnpackedSettings,sensitiveHeaders,Http2ServerRequest,Http2ServerResponse,connect},hideFromStack([Http2ServerRequest,Http2ServerResponse,connect,createServer,createSecureServer,getDefaultSettings,getPackedSettings,getUnpackedSettings]),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttpsCode = "(function (){\"use strict\";const http=@getInternalField(@internalModuleRegistry,18)||@createInternalModuleById(18);function request(input,options,cb){if(input&&typeof input===\"object\"&&!(input instanceof URL))input.protocol\?\?=\"https:\";else if(typeof options===\"object\")options.protocol\?\?=\"https:\";return http.request(input,options,cb)}function get(input,options,cb){const req=request(input,options,cb);return req.end(),req}return{...http,get,request}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeInspectorCode = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15);function open(){throwNotImplemented(\"node:inspector open\",2445)}function close(){throwNotImplemented(\"node:inspector close\",2445)}function url(){throwNotImplemented(\"node:inspector url\",2445)}function waitForDebugger(){throwNotImplemented(\"node:inspector waitForDebugger\",2445)}class Session extends EventEmitter{constructor(){super();throwNotImplemented(\"node:inspector Session\",2445)}}return $={console:{...globalThis.console,context:{console:globalThis.console}},open,close,url,waitForDebugger,Session},hideFromStack(open,close,url,waitForDebugger,Session.prototype.constructor),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeNetCode = "(function (){\"use strict\";const{Duplex}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),IPv4Reg=new RegExp(\"^((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$\"),IPv6Reg=new RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\");function isIPv4(s){return IPv4Reg.test(s)}function isIPv6(s){return IPv6Reg.test(s)}function isIP(s){if(isIPv4(s))return 4;if(isIPv6(s))return 6;return 0}const{connect:bunConnect}=Bun;var{setTimeout}=globalThis;const bunTlsSymbol=Symbol.for(\"::buntls::\"),bunSocketServerHandlers=Symbol.for(\"::bunsocket_serverhandlers::\"),bunSocketServerConnections=Symbol.for(\"::bunnetserverconnections::\"),bunSocketServerOptions=Symbol.for(\"::bunnetserveroptions::\"),bunSocketInternal=Symbol.for(\"::bunnetsocketinternal::\"),bunTLSConnectOptions=Symbol.for(\"::buntlsconnectoptions::\");var SocketClass;const Socket=function(InternalSocket){return SocketClass=InternalSocket,Object.defineProperty(SocketClass.prototype,Symbol.toStringTag,{value:\"Socket\",enumerable:!1}),Object.defineProperty(function Socket(options){return new InternalSocket(options)},Symbol.hasInstance,{value(instance){return instance instanceof InternalSocket}})}(class Socket2 extends Duplex{static#Handlers={close:Socket2.#Close,connectError(socket,error){socket.data.emit(\"error\",error)},data({data:self},buffer){self.bytesRead+=buffer.length;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(buffer))return}queue.push(buffer)},drain:Socket2.#Drain,end:Socket2.#Close,error(socket,error){const self=socket.data,callback=self.#writeCallback;if(callback)self.#writeCallback=null,callback(error);self.emit(\"error\",error)},open(socket){const self=socket.data;socket.timeout(self.timeout),socket.ref(),self[bunSocketInternal]=socket,self.connecting=!1;const options=self[bunTLSConnectOptions];if(options){const{session}=options;if(session)self.setSession(session)}if(!self.#upgraded)self.emit(\"connect\",self);Socket2.#Drain(socket)},handshake(socket,success,verifyError){const{data:self}=socket;self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self.emit(\"secure\",self);const{checkServerIdentity}=self[bunTLSConnectOptions];if(!verifyError&&typeof checkServerIdentity===\"function\"&&self.servername){const cert=self.getPeerCertificate(!0);verifyError=checkServerIdentity(self.servername,cert)}if(self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit(\"secureConnect\",verifyError)},timeout(socket){const self=socket.data;self.emit(\"timeout\",self)},binaryType:\"buffer\"};static#Close(socket){const self=socket.data;if(self.#closed)return;self.#closed=!0,self[bunSocketInternal]=null;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(null))return}queue.push(null)}static#Drain(socket){const self=socket.data,callback=self.#writeCallback;if(callback){const chunk=self.#writeChunk,written=socket.write(chunk);if(self.bytesWritten+=written,written=self.maxConnections){const data={localAddress:_socket.localAddress,localPort:_socket.localPort,localFamily:_socket.localFamily,remoteAddress:_socket.remoteAddress,remotePort:_socket.remotePort,remoteFamily:_socket.remoteFamily||\"IPv4\"};socket.end(),self.emit(\"drop\",data);return}if(!pauseOnConnect)_socket.resume();if(self[bunSocketServerConnections]++,typeof connectionListener==\"function\")if(InternalSocketClass.name===\"TLSSocket\")self.once(\"secureConnection\",()=>connectionListener(_socket));else connectionListener(_socket);self.emit(\"connection\",_socket)},handshake(socket,success,verifyError){const{data:self}=socket;if(self.emit(\"secure\",self),self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit(\"secureConnection\",verifyError)},error(socket,error){Socket2.#Handlers.error(socket,error),this.data.emit(\"error\",error)},timeout:Socket2.#Handlers.timeout,connectError:Socket2.#Handlers.connectError,drain:Socket2.#Handlers.drain,binaryType:\"buffer\"};bytesRead=0;bytesWritten=0;#closed=!1;connecting=!1;localAddress=\"127.0.0.1\";#readQueue=@createFIFO();remotePort;[bunSocketInternal]=null;[bunTLSConnectOptions]=null;timeout=0;#writeCallback;#writeChunk;#pendingRead;isServer=!1;_handle;_parent;_parentWrap;#socket;#upgraded;constructor(options){const{socket,signal,write,read,allowHalfOpen=!1,...opts}=options||{};super({...opts,allowHalfOpen,readable:!0,writable:!0});if(this._handle=this,this._parent=this,this._parentWrap=this,this.#pendingRead=void 0,this.#upgraded=!1,socket instanceof Socket2)this.#socket=socket;signal\?.once(\"abort\",()=>this.destroy()),this.once(\"connect\",()=>this.emit(\"ready\"))}address(){return{address:this.localAddress,family:this.localFamily,port:this.localPort}}get bufferSize(){return this.writableLength}#attach(port,socket){if(this.remotePort=port,socket.data=this,socket.timeout(this.timeout),socket.ref(),this[bunSocketInternal]=socket,this.connecting=!1,!this.#upgraded)this.emit(\"connect\",this);Socket2.#Drain(socket)}connect(port,host,connectListener){var path,connection=this.#socket,_checkServerIdentity=void 0;if(typeof port===\"string\"){if(path=port,port=void 0,typeof host===\"function\")connectListener=host,host=void 0}else if(typeof host==\"function\"){if(typeof port===\"string\")path=port,port=void 0;connectListener=host,host=void 0}if(typeof port==\"object\"){var{port,host,path,socket,localAddress,localPort,family,hints,lookup,noDelay,keepAlive,keepAliveInitialDelay,requestCert,rejectUnauthorized,pauseOnConnect,servername,checkServerIdentity,session}=port;if(_checkServerIdentity=checkServerIdentity,this.servername=servername,socket)connection=socket}if(!pauseOnConnect)this.resume();this.connecting=!0,this.remotePort=port;const bunTLS=this[bunTlsSymbol];var tls=void 0;if(typeof bunTLS===\"function\"){if(tls=bunTLS.call(this,port,host,!0),this._requestCert=!0,this._rejectUnauthorized=rejectUnauthorized,tls){if(tls.rejectUnauthorized=rejectUnauthorized,tls.requestCert=!0,tls.session=session||tls.session,this.servername=tls.servername,tls.checkServerIdentity=_checkServerIdentity||tls.checkServerIdentity,this[bunTLSConnectOptions]=tls,!connection&&tls.socket)connection=tls.socket}if(connection){if(typeof connection!==\"object\"||!(connection instanceof Socket2)||typeof connection[bunTlsSymbol]===\"function\")@throwTypeError(\"socket must be an instance of net.Socket\")}if(this.authorized=!1,this.secureConnecting=!0,this._secureEstablished=!1,this._securePending=!0,connectListener)this.on(\"secureConnect\",connectListener)}else if(connectListener)this.on(\"connect\",connectListener);if(connection){const socket2=connection[bunSocketInternal];if(socket2){this.connecting=!0,this.#upgraded=!0;const result=socket2.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error(\"Invalid socket\")}else connection.once(\"connect\",()=>{const socket3=connection[bunSocketInternal];if(!socket3)return;this.connecting=!0,this.#upgraded=!0;const result=socket3.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error(\"Invalid socket\")})}else if(path)bunConnect({data:this,unix:path,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit(\"error\",error)});else bunConnect({data:this,hostname:host||\"localhost\",port,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit(\"error\",error)});return this}_destroy(err,callback){this[bunSocketInternal]\?.end(),callback(err)}_final(callback){this[bunSocketInternal]\?.end(),callback()}get localAddress(){return\"127.0.0.1\"}get localFamily(){return\"IPv4\"}get localPort(){return this[bunSocketInternal]\?.localPort}get pending(){return this.connecting}_read(size){const queue=this.#readQueue;let chunk;while(chunk=queue.peek()){if(!this.push(chunk))return;queue.shift()}}get readyState(){if(this.connecting)return\"opening\";if(this.readable)return this.writable\?\"open\":\"readOnly\";else return this.writable\?\"writeOnly\":\"closed\"}ref(){this[bunSocketInternal]\?.ref()}get remoteAddress(){return this[bunSocketInternal]\?.remoteAddress}get remoteFamily(){return\"IPv4\"}resetAndDestroy(){this[bunSocketInternal]\?.end()}setKeepAlive(enable=!1,initialDelay=0){return this}setNoDelay(noDelay=!0){return this}setTimeout(timeout,callback){if(this[bunSocketInternal]\?.timeout(timeout),this.timeout=timeout,callback)this.once(\"timeout\",callback);return this}unref(){this[bunSocketInternal]\?.unref()}_write(chunk,encoding,callback){if(typeof chunk==\"string\"&&encoding!==\"ascii\")chunk=Buffer.from(chunk,encoding);var written=this[bunSocketInternal]\?.write(chunk);if(written==chunk.length)callback();else if(this.#writeCallback)callback(new Error(\"overlapping _write()\"));else{if(written>0)if(typeof chunk==\"string\")chunk=chunk.slice(written);else chunk=chunk.subarray(written);this.#writeCallback=callback,this.#writeChunk=chunk}}});function createConnection(port,host,connectListener){if(typeof port===\"object\")return new Socket(port).connect(port,host,connectListener);return new Socket().connect(port,host,connectListener)}const connect=createConnection;class Server extends EventEmitter{#server;#listening=!1;[bunSocketServerConnections]=0;[bunSocketServerOptions];maxConnections=0;constructor(options,connectionListener){super();if(typeof options===\"function\")connectionListener=options,options={};else if(options==null||typeof options===\"object\")options={...options};else throw new Error(\"bun-net-polyfill: invalid arguments\");const{maxConnections}=options;this.maxConnections=Number.isSafeInteger(maxConnections)&&maxConnections>0\?maxConnections:0,options.connectionListener=connectionListener,this[bunSocketServerOptions]=options}ref(){return this.#server\?.ref(),this}unref(){return this.#server\?.unref(),this}close(callback){if(this.#server){if(this.#server.stop(!0),this.#server=null,this.#listening=!1,this[bunSocketServerConnections]=0,this.emit(\"close\"),typeof callback===\"function\")callback();return this}if(typeof callback===\"function\"){const error=new Error(\"Server is not running\");error.code=\"ERR_SERVER_NOT_RUNNING\",callback(error)}return this}address(){const server=this.#server;if(server){const unix=server.unix;if(unix)return unix;let address=server.hostname;const type=isIP(address),port=server.port;if(typeof port===\"number\")return{port,address,family:type\?`IPv${type}`:void 0};if(type)return{address,family:type\?`IPv${type}`:void 0};return address}return null}getConnections(callback){if(typeof callback===\"function\")callback(null,this.#server\?this[bunSocketServerConnections]:0);return this}listen(port,hostname,onListen){let backlog,path,exclusive=!1;if(typeof port===\"string\"){if(Number.isSafeInteger(hostname)){if(hostname>0)backlog=hostname}else if(typeof hostname===\"function\")onListen=hostname;path=port,hostname=void 0,port=void 0}else{if(typeof hostname===\"function\")onListen=hostname,hostname=void 0;if(typeof port===\"function\")onListen=port,port=0;else if(typeof port===\"object\"){const options=port;options.signal\?.addEventListener(\"abort\",()=>this.close()),hostname=options.host,exclusive=options.exclusive===!0;const path2=options.path;if(port=options.port,!Number.isSafeInteger(port)||port<0)if(path2)hostname=path2,port=void 0;else{let message='The argument \\'options\\' must have the property \"port\" or \"path\"';try{message=`${message}. Received ${JSON.stringify(options)}`}catch{}const error=@makeTypeError(message);throw error.code=\"ERR_INVALID_ARG_VALUE\",error}else if(!Number.isSafeInteger(port)||port<0)port=0;if(typeof port.callback===\"function\")onListen=port\?.callback}else if(!Number.isSafeInteger(port)||port<0)port=0;hostname=hostname||\"::\"}try{var tls=void 0,TLSSocketClass=void 0;const bunTLS=this[bunTlsSymbol],options=this[bunSocketServerOptions];if(typeof bunTLS===\"function\")[tls,TLSSocketClass]=bunTLS.call(this,port,hostname,!1),options.servername=tls.serverName,options.InternalSocketClass=TLSSocketClass;else options.InternalSocketClass=SocketClass;this.#server=Bun.listen(path\?{exclusive,unix:path,tls,socket:SocketClass[bunSocketServerHandlers]}:{exclusive,port,hostname,tls,socket:SocketClass[bunSocketServerHandlers]}),this.#server.data=this,this.#listening=!0,setTimeout(emitListeningNextTick,1,this,onListen)}catch(err){this.#listening=!1,setTimeout(emitErrorNextTick,1,this,err)}return this}}function emitErrorNextTick(self,error){self.emit(\"error\",error)}function emitListeningNextTick(self,onListen){if(typeof onListen===\"function\")try{onListen()}catch(err){self.emit(\"error\",err)}self.emit(\"listening\")}function createServer(options,connectionListener){return new Server(options,connectionListener)}return{createServer,Server,createConnection,connect,isIP,isIPv4,isIPv6,Socket,[Symbol.for(\"::bunternal::\")]:SocketClass}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeOSCode = "(function (){\"use strict\";var tmpdir=function(){var env=Bun.env;return tmpdir=function(){var path=env.TMPDIR||env.TMP||env.TEMP||\"/tmp\";const length=path.length;if(length>1&&path[length-1]===\"/\")path=path.slice(0,-1);return path},tmpdir()};function lazyCpus({cpus}){return()=>{const array=new Array(navigator.hardwareConcurrency);function populate(){const results=cpus(),length=results.length;array.length=length;for(let i=0;i= 0x80 (not a basic code point)\",\"invalid-input\":\"Invalid input\"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;function error(type){@throwRangeError(errors[type])}function map(array,callback){const result=[];let length=array.length;while(length--)result[length]=callback(array[length]);return result}function mapDomain(domain,callback){const parts=domain.split(\"@\");let result=\"\";if(parts.length>1)result=parts[0]+\"@\",domain=parts[1];domain=domain.replace(regexSeparators,\".\");const labels=domain.split(\".\"),encoded=map(labels,callback).join(\".\");return result+encoded}function ucs2decode(string){const output=[];let counter=0;const length=string.length;while(counter=55296&&value<=56319&&counterString.fromCodePoint(...codePoints),basicToDigit=function(codePoint){if(codePoint>=48&&codePoint<58)return 26+(codePoint-48);if(codePoint>=65&&codePoint<91)return codePoint-65;if(codePoint>=97&&codePoint<123)return codePoint-97;return base},digitToBasic=function(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)},adapt=function(delta,numPoints,firstTime){let k=0;delta=firstTime\?floor(delta/damp):delta>>1,delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base)delta=floor(delta/baseMinusTMin);return floor(k+(baseMinusTMin+1)*delta/(delta+skew))},decode=function(input){const output=[],inputLength=input.length;let i=0,n=initialN,bias=initialBias,basic=input.lastIndexOf(delimiter);if(basic<0)basic=0;for(let j=0;j=128)error(\"not-basic\");output.push(input.charCodeAt(j))}for(let index=basic>0\?basic+1:0;index=inputLength)error(\"invalid-input\");const digit=basicToDigit(input.charCodeAt(index++));if(digit>=base)error(\"invalid-input\");if(digit>floor((maxInt-i)/w))error(\"overflow\");i+=digit*w;const t=k<=bias\?tMin:k>=bias+tMax\?tMax:k-bias;if(digitfloor(maxInt/baseMinusT))error(\"overflow\");w*=baseMinusT}const out=output.length+1;if(bias=adapt(i-oldi,out,oldi==0),floor(i/out)>maxInt-n)error(\"overflow\");n+=floor(i/out),i%=out,output.splice(i++,0,n)}return String.fromCodePoint(...output)},encode=function(input){const output=[];input=ucs2decode(input);const inputLength=input.length;let n=initialN,delta=0,bias=initialBias;for(let currentValue of input)if(currentValue<128)output.push(stringFromCharCode(currentValue));const basicLength=output.length;let handledCPCount=basicLength;if(basicLength)output.push(delimiter);while(handledCPCount=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne))error(\"overflow\");delta+=(m-n)*handledCPCountPlusOne,n=m;for(let currentValue of input){if(currentValuemaxInt)error(\"overflow\");if(currentValue===n){let q=delta;for(let k=base;;k+=base){const t=k<=bias\?tMin:k>=bias+tMax\?tMax:k-bias;if(q()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),Buffer=@requireNativeModule(\"node:buffer\").Buffer,require_object_keys=__commonJS((exports,module)=>{var objectKeys=Object.keys||function(){var hasOwnProperty=Object.prototype.hasOwnProperty,hasDontEnumBug=!{toString:null}.propertyIsEnumerable(\"toString\"),dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;return function(obj){if(typeof obj!==\"function\"&&(typeof obj!==\"object\"||obj===null))@throwTypeError(\"Object.keys called on non-object\");var result=[],prop,i;for(prop in obj)if(hasOwnProperty.call(obj,prop))result.push(prop);if(hasDontEnumBug){for(i=0;i{var ParsedQueryString=function(){},unescapeBuffer=function(s,decodeSpaces){var out=Buffer.allocUnsafe(s.length),state=0,n,m,hexchar,c;for(var inIndex=0,outIndex=0;;inIndex++){if(inIndex0){if(out[outIndex++]=37,state===2)out[outIndex++]=hexchar}break}switch(state){case 0:switch(c){case 37:n=0,m=0,state=1;break;case 43:if(decodeSpaces)c=32;default:out[outIndex++]=c;break}break;case 1:if(hexchar=c,n=unhexTable[c],!(n>=0)){out[outIndex++]=37,out[outIndex++]=c,state=0;break}state=2;break;case 2:if(state=0,m=unhexTable[c],!(m>=0)){out[outIndex++]=37,out[outIndex++]=hexchar,out[outIndex++]=c;break}out[outIndex++]=16*n+m;break}}return out.slice(0,outIndex)},qsUnescape=function(s,decodeSpaces){try{return decodeURIComponent(s)}catch(e){return QueryString.unescapeBuffer(s,decodeSpaces).toString()}},qsEscape=function(str){if(typeof str!==\"string\")if(typeof str===\"object\")str=String(str);else str+=\"\";var out=\"\",lastPos=0;for(var i2=0;i2>6]+hexTable[128|c&63];continue}if(c<55296||c>=57344){lastPos=i2+1,out+=hexTable[224|c>>12]+hexTable[128|c>>6&63]+hexTable[128|c&63];continue}++i2;var c2;if(i2>18]+hexTable[128|c>>12&63]+hexTable[128|c>>6&63]+hexTable[128|c&63]}if(lastPos===0)return str;if(lastPos0\?options.maxKeys:-1;var decode=QueryString.unescape;if(options&&typeof options.decodeURIComponent===\"function\")decode=options.decodeURIComponent;const customDecode=decode!==qsUnescape,keys=[];var posIdx=0,lastPos=0,sepIdx=0,eqIdx=0,key=\"\",value=\"\",keyEncoded=customDecode,valEncoded=customDecode,encodeCheck=0;for(var i2=0;i2sepLen||i2===0)if(indexOf(keys,key)===-1)obj[key]=value,keys[keys.length]=key;else{const curValue=obj[key]||\"\";if(curValue.pop)curValue[curValue.length]=value;else if(curValue)obj[key]=[curValue,value]}else if(i2===1)delete obj[key];if(--pairs===0)break;keyEncoded=valEncoded=customDecode,encodeCheck=0,key=value=\"\",posIdx=lastPos,lastPos=i2+1,sepIdx=eqIdx=0}continue}else if(sepIdx=0,!valEncoded)if(code===37)encodeCheck=1;else if(encodeCheck>0&&(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){if(++encodeCheck===3)valEncoded=!0}else encodeCheck=0;if(eqIdx0&&(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){if(++encodeCheck===3)keyEncoded=!0}else encodeCheck=0}if(code===43){if(eqIdx0)){if(lastPosObject.prototype.toString.call(arg)===\"[object Array]\",indexOf=(arr,searchElement,fromIndex)=>{var k;if(arr==null)@throwTypeError('\"arr\" is null or not defined');var o=Object(arr),len=o.length>>>0;if(len===0)return-1;var n=fromIndex|0;if(n>=len)return-1;k=Math.max(n>=0\?n:len-Math.abs(n),0);while(k{},SymbolAsyncIterator=Symbol.asyncIterator,SymbolIterator=Symbol.iterator,SymbolFor=Symbol.for,SymbolReplace=Symbol.replace,ArrayFrom=Array.from,ArrayIsArray=Array.isArray,ArrayPrototypeFilter=Array.prototype.filter,ArrayPrototypeSort=Array.prototype.sort,ArrayPrototypeIndexOf=Array.prototype.indexOf,ArrayPrototypeJoin=Array.prototype.join,ArrayPrototypeMap=Array.prototype.map,ArrayPrototypePop=Array.prototype.pop,ArrayPrototypePush=Array.prototype.push,ArrayPrototypeSlice=Array.prototype.slice,ArrayPrototypeSplice=Array.prototype.splice,ArrayPrototypeReverse=Array.prototype.reverse,ArrayPrototypeShift=Array.prototype.shift,ArrayPrototypeUnshift=Array.prototype.unshift,RegExpPrototypeExec=RegExp.prototype.exec,RegExpPrototypeSymbolReplace=RegExp.prototype[SymbolReplace],StringFromCharCode=String.fromCharCode,StringPrototypeCharCodeAt=String.prototype.charCodeAt,StringPrototypeCodePointAt=String.prototype.codePointAt,StringPrototypeSlice=String.prototype.slice,StringPrototypeToLowerCase=String.prototype.toLowerCase,StringPrototypeEndsWith=String.prototype.endsWith,StringPrototypeRepeat=String.prototype.repeat,StringPrototypeStartsWith=String.prototype.startsWith,StringPrototypeTrim=String.prototype.trim,StringPrototypeNormalize=String.prototype.normalize,NumberIsNaN=Number.isNaN,NumberIsFinite=Number.isFinite,NumberIsInteger=Number.isInteger,NumberMAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER=Number.MIN_SAFE_INTEGER,MathCeil=Math.ceil,MathFloor=Math.floor,MathMax=Math.max,MathMaxApply=Math.max.apply,DateNow=Date.now,FunctionPrototype=Function.prototype,StringPrototype=String.prototype,StringPrototypeSymbolIterator=StringPrototype[SymbolIterator],StringIteratorPrototypeNext=StringPrototypeSymbolIterator.call(\"\").next,ObjectSetPrototypeOf=Object.setPrototypeOf,ObjectDefineProperty=Object.defineProperty,ObjectDefineProperties=Object.defineProperties,ObjectFreeze=Object.freeze,ObjectAssign=Object.assign,ObjectCreate=Object.create,ObjectKeys=Object.keys,ObjectSeal=Object.seal,createSafeIterator=(factory,next)=>{class SafeIterator{#iterator;constructor(iterable){this.#iterator=factory.call(iterable)}next(){return next.call(this.#iterator)}[SymbolIterator](){return this}}return ObjectSetPrototypeOf(SafeIterator.prototype,null),ObjectFreeze(SafeIterator.prototype),ObjectFreeze(SafeIterator),SafeIterator},SafeStringIterator=createSafeIterator(StringPrototypeSymbolIterator,StringIteratorPrototypeNext),isFullWidthCodePoint=(code)=>{return code>=4352&&(code<=4447||code===9001||code===9002||code>=11904&&code<=12871&&code!==12351||code>=12880&&code<=19903||code>=19968&&code<=42182||code>=43360&&code<=43388||code>=44032&&code<=55203||code>=63744&&code<=64255||code>=65040&&code<=65049||code>=65072&&code<=65131||code>=65281&&code<=65376||code>=65504&&code<=65510||code>=110592&&code<=110593||code>=127488&&code<=127569||code>=127744&&code<=128591||code>=131072&&code<=262141)},isZeroWidthCodePoint=(code)=>{return code<=31||code>=127&&code<=159||code>=768&&code<=879||code>=8203&&code<=8207||code>=8400&&code<=8447||code>=65024&&code<=65039||code>=65056&&code<=65071||code>=917760&&code<=917999},getStringWidth=function getStringWidth(str,removeControlChars=!0){var width=0;if(removeControlChars)str=stripVTControlCharacters(str);str=StringPrototypeNormalize.call(str,\"NFC\");for(var char of new SafeStringIterator(str)){var code=StringPrototypeCodePointAt.call(char,0);if(isFullWidthCodePoint(code))width+=2;else if(!isZeroWidthCodePoint(code))width++}return width},ansiPattern=\"[\\\\u001B\\\\u009B][[\\\\]()#;\?]*(\?:(\?:(\?:(\?:;[-a-zA-Z\\\\d\\\\/#&.:=\?%@~_]+)*|[a-zA-Z\\\\d]+(\?:;[-a-zA-Z\\\\d\\\\/#&.:=\?%@~_]*)*)\?\\\\u0007)|(\?:(\?:\\\\d{1,4}(\?:;\\\\d{0,4})*)\?[\\\\dA-PR-TZcf-ntqry=><~]))\",ansi=new RegExp(ansiPattern,\"g\");function stripVTControlCharacters(str){return validateString(str,\"str\"),RegExpPrototypeSymbolReplace.call(ansi,str,\"\")}var kCustomPromisifiedSymbol=SymbolFor(\"nodejs.util.promisify.custom\"),kCustomPromisifyArgsSymbol=Symbol(\"customPromisifyArgs\");function promisify(original){if(validateFunction(original,\"original\"),original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];return validateFunction(fn,\"util.promisify.custom\"),ObjectDefineProperty(fn,kCustomPromisifiedSymbol,{__proto__:null,value:fn,enumerable:!1,writable:!1,configurable:!0})}var argumentNames=original[kCustomPromisifyArgsSymbol];function fn(...args){return new Promise((resolve,reject)=>{ArrayPrototypePush.call(args,(err,...values)=>{if(err)return reject(err);if(argumentNames!==void 0&&values.length>1){var obj={};for(var i2=0;i2max)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}function validateUint32(value,name,positive=!1){if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE(name,\"number\",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);var min=positive\?1:0,max=4294967295;if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}function CSI(strings,...args){var ret=`${kEscape}[`;for(var n=0;n1&&StringPrototypeCodePointAt.call(str,i-2)>=kUTF16SurrogateThreshold||StringPrototypeCodePointAt.call(str,i-1)>=kUTF16SurrogateThreshold)return 2;return 1}function charLengthAt(str,i){if(str.length<=i)return 1;return StringPrototypeCodePointAt.call(str,i)>=kUTF16SurrogateThreshold\?2:1}function*emitKeys(stream){while(!0){var ch=yield,s=ch,escaped=!1,keySeq=null,keyName,keyCtrl2=!1,keyMeta=!1,keyShift=!1;if(ch===kEscape){if(escaped=!0,s+=ch=yield,ch===kEscape)s+=ch=yield}if(escaped&&(ch===\"O\"||ch===\"[\")){var code=ch,modifier=0;if(ch===\"O\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")modifier=(ch>>0)-1,s+=ch=yield;code+=ch}else if(ch===\"[\"){if(s+=ch=yield,ch===\"[\")code+=ch,s+=ch=yield;var cmdStart=s.length-1;if(ch>=\"0\"&&ch<=\"9\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")s+=ch=yield}if(ch===\";\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")s+=yield}var cmd=StringPrototypeSlice.call(s,cmdStart),match;if(match=RegExpPrototypeExec.call(/^(\\d\\d\?)(;(\\d))\?([~^$])$/,cmd))code+=match[1]+match[4],modifier=(match[3]||1)-1;else if(match=RegExpPrototypeExec.call(/^((\\d;)\?(\\d))\?([A-Za-z])$/,cmd))code+=match[4],modifier=(match[3]||1)-1;else code+=cmd}switch(keyCtrl2=!!(modifier&4),keyMeta=!!(modifier&10),keyShift=!!(modifier&1),code){case\"[P\":keyName=\"f1\";break;case\"[Q\":keyName=\"f2\";break;case\"[R\":keyName=\"f3\";break;case\"[S\":keyName=\"f4\";break;case\"OP\":keyName=\"f1\";break;case\"OQ\":keyName=\"f2\";break;case\"OR\":keyName=\"f3\";break;case\"OS\":keyName=\"f4\";break;case\"[11~\":keyName=\"f1\";break;case\"[12~\":keyName=\"f2\";break;case\"[13~\":keyName=\"f3\";break;case\"[14~\":keyName=\"f4\";break;case\"[[A\":keyName=\"f1\";break;case\"[[B\":keyName=\"f2\";break;case\"[[C\":keyName=\"f3\";break;case\"[[D\":keyName=\"f4\";break;case\"[[E\":keyName=\"f5\";break;case\"[15~\":keyName=\"f5\";break;case\"[17~\":keyName=\"f6\";break;case\"[18~\":keyName=\"f7\";break;case\"[19~\":keyName=\"f8\";break;case\"[20~\":keyName=\"f9\";break;case\"[21~\":keyName=\"f10\";break;case\"[23~\":keyName=\"f11\";break;case\"[24~\":keyName=\"f12\";break;case\"[A\":keyName=\"up\";break;case\"[B\":keyName=\"down\";break;case\"[C\":keyName=\"right\";break;case\"[D\":keyName=\"left\";break;case\"[E\":keyName=\"clear\";break;case\"[F\":keyName=\"end\";break;case\"[H\":keyName=\"home\";break;case\"OA\":keyName=\"up\";break;case\"OB\":keyName=\"down\";break;case\"OC\":keyName=\"right\";break;case\"OD\":keyName=\"left\";break;case\"OE\":keyName=\"clear\";break;case\"OF\":keyName=\"end\";break;case\"OH\":keyName=\"home\";break;case\"[1~\":keyName=\"home\";break;case\"[2~\":keyName=\"insert\";break;case\"[3~\":keyName=\"delete\";break;case\"[4~\":keyName=\"end\";break;case\"[5~\":keyName=\"pageup\";break;case\"[6~\":keyName=\"pagedown\";break;case\"[[5~\":keyName=\"pageup\";break;case\"[[6~\":keyName=\"pagedown\";break;case\"[7~\":keyName=\"home\";break;case\"[8~\":keyName=\"end\";break;case\"[a\":keyName=\"up\",keyShift=!0;break;case\"[b\":keyName=\"down\",keyShift=!0;break;case\"[c\":keyName=\"right\",keyShift=!0;break;case\"[d\":keyName=\"left\",keyShift=!0;break;case\"[e\":keyName=\"clear\",keyShift=!0;break;case\"[2$\":keyName=\"insert\",keyShift=!0;break;case\"[3$\":keyName=\"delete\",keyShift=!0;break;case\"[5$\":keyName=\"pageup\",keyShift=!0;break;case\"[6$\":keyName=\"pagedown\",keyShift=!0;break;case\"[7$\":keyName=\"home\",keyShift=!0;break;case\"[8$\":keyName=\"end\",keyShift=!0;break;case\"Oa\":keyName=\"up\",keyCtrl2=!0;break;case\"Ob\":keyName=\"down\",keyCtrl2=!0;break;case\"Oc\":keyName=\"right\",keyCtrl2=!0;break;case\"Od\":keyName=\"left\",keyCtrl2=!0;break;case\"Oe\":keyName=\"clear\",keyCtrl2=!0;break;case\"[2^\":keyName=\"insert\",keyCtrl2=!0;break;case\"[3^\":keyName=\"delete\",keyCtrl2=!0;break;case\"[5^\":keyName=\"pageup\",keyCtrl2=!0;break;case\"[6^\":keyName=\"pagedown\",keyCtrl2=!0;break;case\"[7^\":keyName=\"home\",keyCtrl2=!0;break;case\"[8^\":keyName=\"end\",keyCtrl2=!0;break;case\"[Z\":keyName=\"tab\",keyShift=!0;break;default:keyName=\"undefined\";break}}else if(ch===\"\\r\")keyName=\"return\",keyMeta=escaped;else if(ch===\"\\n\")keyName=\"enter\",keyMeta=escaped;else if(ch===\"\\t\")keyName=\"tab\",keyMeta=escaped;else if(ch===\"\\b\"||ch===\"\\x7F\")keyName=\"backspace\",keyMeta=escaped;else if(ch===kEscape)keyName=\"escape\",keyMeta=escaped;else if(ch===\" \")keyName=\"space\",keyMeta=escaped;else if(!escaped&&ch<=\"\\x1A\")keyName=StringFromCharCode(StringPrototypeCharCodeAt.call(ch)+StringPrototypeCharCodeAt.call(\"a\")-1),keyCtrl2=!0;else if(RegExpPrototypeExec.call(/^[0-9A-Za-z]$/,ch)!==null)keyName=StringPrototypeToLowerCase.call(ch),keyShift=RegExpPrototypeExec.call(/^[A-Z]$/,ch)!==null,keyMeta=escaped;else if(escaped)keyName=ch.length\?void 0:\"escape\",keyMeta=!0;if(keySeq=s,s.length!==0&&(keyName!==void 0||escaped))stream.emit(\"keypress\",escaped\?void 0:s,{sequence:keySeq,name:keyName,ctrl:keyCtrl2,meta:keyMeta,shift:keyShift});else if(charLengthAt(s,0)===s.length)stream.emit(\"keypress\",s,{sequence:keySeq,name:keyName,ctrl:keyCtrl2,meta:keyMeta,shift:keyShift})}}function commonPrefix(strings){if(strings.length===0)return\"\";if(strings.length===1)return strings[0];var sorted=ArrayPrototypeSort.call(ArrayPrototypeSlice.call(strings)),min=sorted[0],max=sorted[sorted.length-1];for(var i=0;i0)data+=CSI`${dx}C`;if(dy<0)data+=CSI`${-dy}A`;else if(dy>0)data+=CSI`${dy}B`;return stream.write(data,callback)}function clearLine(stream,dir,callback){if(callback!==void 0)validateFunction(callback,\"callback\");if(stream===null||stream===void 0){if(typeof callback===\"function\")process.nextTick(callback,null);return!0}var type=dir<0\?kClearToLineBeginning:dir>0\?kClearToLineEnd:kClearLine;return stream.write(type,callback)}function clearScreenDown(stream,callback){if(callback!==void 0)validateFunction(callback,\"callback\");if(stream===null||stream===void 0){if(typeof callback===\"function\")process.nextTick(callback,null);return!0}return stream.write(kClearScreenDown,callback)}var KEYPRESS_DECODER=Symbol(\"keypress-decoder\"),ESCAPE_DECODER=Symbol(\"escape-decoder\"),ESCAPE_CODE_TIMEOUT=500;function emitKeypressEvents(stream,iface={}){if(stream[KEYPRESS_DECODER])return;stream[KEYPRESS_DECODER]=new StringDecoder(\"utf8\"),stream[ESCAPE_DECODER]=emitKeys(stream),stream[ESCAPE_DECODER].next();var triggerEscape=()=>stream[ESCAPE_DECODER].next(\"\"),{escapeCodeTimeout=ESCAPE_CODE_TIMEOUT}=iface,timeoutId;function onData2(input){if(stream.listenerCount(\"keypress\")>0){var string=stream[KEYPRESS_DECODER].write(input);if(string){clearTimeout(timeoutId),iface[kSawKeyPress]=charLengthAt(string,0)===string.length,iface.isCompletionEnabled=!1;var length=0;for(var character of new SafeStringIterator(string)){if(length+=character.length,length===string.length)iface.isCompletionEnabled=!0;try{if(stream[ESCAPE_DECODER].next(character),length===string.length&&character===kEscape)timeoutId=setTimeout(triggerEscape,escapeCodeTimeout)}catch(err){throw stream[ESCAPE_DECODER]=emitKeys(stream),stream[ESCAPE_DECODER].next(),err}}}}else stream.removeListener(\"data\",onData2),stream.on(\"newListener\",onNewListener)}function onNewListener(event){if(event===\"keypress\")stream.on(\"data\",onData2),stream.removeListener(\"newListener\",onNewListener)}if(stream.listenerCount(\"keypress\")>0)stream.on(\"data\",onData2);else stream.on(\"newListener\",onNewListener)}var kEmptyObject=ObjectFreeze(ObjectCreate(null)),kHistorySize=30,kMaxUndoRedoStackSize=2048,kMincrlfDelay=100,lineEnding=/\\r\?\\n|\\r(\?!\\n)/g,kMaxLengthOfKillRing=32,kLineObjectStream=Symbol(\"line object stream\"),kQuestionCancel=Symbol(\"kQuestionCancel\"),kQuestion=Symbol(\"kQuestion\"),kAddHistory=Symbol(\"_addHistory\"),kBeforeEdit=Symbol(\"_beforeEdit\"),kDecoder=Symbol(\"_decoder\"),kDeleteLeft=Symbol(\"_deleteLeft\"),kDeleteLineLeft=Symbol(\"_deleteLineLeft\"),kDeleteLineRight=Symbol(\"_deleteLineRight\"),kDeleteRight=Symbol(\"_deleteRight\"),kDeleteWordLeft=Symbol(\"_deleteWordLeft\"),kDeleteWordRight=Symbol(\"_deleteWordRight\"),kGetDisplayPos=Symbol(\"_getDisplayPos\"),kHistoryNext=Symbol(\"_historyNext\"),kHistoryPrev=Symbol(\"_historyPrev\"),kInsertString=Symbol(\"_insertString\"),kLine=Symbol(\"_line\"),kLine_buffer=Symbol(\"_line_buffer\"),kKillRing=Symbol(\"_killRing\"),kKillRingCursor=Symbol(\"_killRingCursor\"),kMoveCursor=Symbol(\"_moveCursor\"),kNormalWrite=Symbol(\"_normalWrite\"),kOldPrompt=Symbol(\"_oldPrompt\"),kOnLine=Symbol(\"_onLine\"),kPreviousKey=Symbol(\"_previousKey\"),kPrompt=Symbol(\"_prompt\"),kPushToKillRing=Symbol(\"_pushToKillRing\"),kPushToUndoStack=Symbol(\"_pushToUndoStack\"),kQuestionCallback=Symbol(\"_questionCallback\"),kRedo=Symbol(\"_redo\"),kRedoStack=Symbol(\"_redoStack\"),kRefreshLine=Symbol(\"_refreshLine\"),kSawKeyPress=Symbol(\"_sawKeyPress\"),kSawReturnAt=Symbol(\"_sawReturnAt\"),kSetRawMode=Symbol(\"_setRawMode\"),kTabComplete=Symbol(\"_tabComplete\"),kTabCompleter=Symbol(\"_tabCompleter\"),kTtyWrite=Symbol(\"_ttyWrite\"),kUndo=Symbol(\"_undo\"),kUndoStack=Symbol(\"_undoStack\"),kWordLeft=Symbol(\"_wordLeft\"),kWordRight=Symbol(\"_wordRight\"),kWriteToOutput=Symbol(\"_writeToOutput\"),kYank=Symbol(\"_yank\"),kYanking=Symbol(\"_yanking\"),kYankPop=Symbol(\"_yankPop\"),kFirstEventParam=Symbol(\"nodejs.kFirstEventParam\"),kOnSelfCloseWithTerminal=Symbol(\"_onSelfCloseWithTerminal\"),kOnSelfCloseWithoutTerminal=Symbol(\"_onSelfCloseWithoutTerminal\"),kOnKeyPress=Symbol(\"_onKeyPress\"),kOnError=Symbol(\"_onError\"),kOnData=Symbol(\"_onData\"),kOnEnd=Symbol(\"_onEnd\"),kOnTermEnd=Symbol(\"_onTermEnd\"),kOnResize=Symbol(\"_onResize\");function onSelfCloseWithTerminal(){var input=this.input,output=this.output;if(!input)throw new Error(\"Input not set, invalid state for readline!\");if(input.removeListener(\"keypress\",this[kOnKeyPress]),input.removeListener(\"error\",this[kOnError]),input.removeListener(\"end\",this[kOnTermEnd]),output!==null&&output!==void 0)output.removeListener(\"resize\",this[kOnResize])}function onSelfCloseWithoutTerminal(){var input=this.input;if(!input)throw new Error(\"Input not set, invalid state for readline!\");input.removeListener(\"data\",this[kOnData]),input.removeListener(\"error\",this[kOnError]),input.removeListener(\"end\",this[kOnEnd])}function onError(err){this.emit(\"error\",err)}function onData(data){debug(\"onData\"),this[kNormalWrite](data)}function onEnd(){if(debug(\"onEnd\"),typeof this[kLine_buffer]===\"string\"&&this[kLine_buffer].length>0)this.emit(\"line\",this[kLine_buffer]);this.close()}function onTermEnd(){if(debug(\"onTermEnd\"),typeof this.line===\"string\"&&this.line.length>0)this.emit(\"line\",this.line);this.close()}function onKeyPress(s,key){if(this[kTtyWrite](s,key),key&&key.sequence){var ch=StringPrototypeCodePointAt.call(key.sequence,0);if(ch>=55296&&ch<=57343)this[kRefreshLine]()}}function onResize(){this[kRefreshLine]()}function InterfaceConstructor(input,output,completer,terminal){if(!(this instanceof InterfaceConstructor))return new InterfaceConstructor(input,output,completer,terminal);EventEmitter.call(this),this[kOnSelfCloseWithoutTerminal]=onSelfCloseWithoutTerminal.bind(this),this[kOnSelfCloseWithTerminal]=onSelfCloseWithTerminal.bind(this),this[kOnError]=onError.bind(this),this[kOnData]=onData.bind(this),this[kOnEnd]=onEnd.bind(this),this[kOnTermEnd]=onTermEnd.bind(this),this[kOnKeyPress]=onKeyPress.bind(this),this[kOnResize]=onResize.bind(this),this[kSawReturnAt]=0,this.isCompletionEnabled=!0,this[kSawKeyPress]=!1,this[kPreviousKey]=null,this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT,this.tabSize=8;var history,historySize,removeHistoryDuplicates=!1,crlfDelay,prompt=\"> \",signal;if(input\?.input){output=input.output,completer=input.completer,terminal=input.terminal,history=input.history,historySize=input.historySize,signal=input.signal;var tabSize=input.tabSize;if(tabSize!==void 0)validateUint32(tabSize,\"tabSize\",!0),this.tabSize=tabSize;removeHistoryDuplicates=input.removeHistoryDuplicates;var inputPrompt=input.prompt;if(inputPrompt!==void 0)prompt=inputPrompt;var inputEscapeCodeTimeout=input.escapeCodeTimeout;if(inputEscapeCodeTimeout!==void 0)if(NumberIsFinite(inputEscapeCodeTimeout))this.escapeCodeTimeout=inputEscapeCodeTimeout;else throw new ERR_INVALID_ARG_VALUE(\"input.escapeCodeTimeout\",this.escapeCodeTimeout);if(signal)validateAbortSignal(signal,\"options.signal\");crlfDelay=input.crlfDelay,input=input.input}if(completer!==void 0&&typeof completer!==\"function\")throw new ERR_INVALID_ARG_VALUE(\"completer\",completer);if(history===void 0)history=[];else validateArray(history,\"history\");if(historySize===void 0)historySize=kHistorySize;if(typeof historySize!==\"number\"||NumberIsNaN(historySize)||historySize<0)throw new ERR_INVALID_ARG_VALUE(\"historySize\",historySize);if(terminal===void 0&&!(output===null||output===void 0))terminal=!!output.isTTY;if(this.line=\"\",this[kSubstringSearch]=null,this.output=output,this.input=input,this[kUndoStack]=[],this[kRedoStack]=[],this.history=history,this.historySize=historySize,this[kKillRing]=[],this[kKillRingCursor]=0,this.removeHistoryDuplicates=!!removeHistoryDuplicates,this.crlfDelay=crlfDelay\?MathMax(kMincrlfDelay,crlfDelay):kMincrlfDelay,this.completer=completer,this.setPrompt(prompt),this.terminal=!!terminal,this[kLineObjectStream]=void 0,input.on(\"error\",this[kOnError]),!this.terminal)input.on(\"data\",this[kOnData]),input.on(\"end\",this[kOnEnd]),this.once(\"close\",this[kOnSelfCloseWithoutTerminal]),this[kDecoder]=new StringDecoder(\"utf8\");else{if(emitKeypressEvents(input,this),input.on(\"keypress\",this[kOnKeyPress]),input.on(\"end\",this[kOnTermEnd]),this[kSetRawMode](!0),this.terminal=!0,this.cursor=0,this.historyIndex=-1,output!==null&&output!==void 0)output.on(\"resize\",this[kOnResize]);this.once(\"close\",this[kOnSelfCloseWithTerminal])}if(signal){var onAborted=(()=>this.close()).bind(this);if(signal.aborted)process.nextTick(onAborted);else signal.addEventListener(\"abort\",onAborted,{once:!0}),this.once(\"close\",()=>signal.removeEventListener(\"abort\",onAborted))}this.line=\"\",input.resume()}InterfaceConstructor.prototype={},ObjectSetPrototypeOf(InterfaceConstructor.prototype,EventEmitter.prototype);var _Interface=class Interface2 extends InterfaceConstructor{constructor(input,output,completer,terminal){super(input,output,completer,terminal)}get columns(){var output=this.output;if(output&&output.columns)return output.columns;return Infinity}setPrompt(prompt){this[kPrompt]=prompt}getPrompt(){return this[kPrompt]}[kSetRawMode](mode){var input=this.input,{setRawMode,wasInRawMode}=input;return debug(\"setRawMode\",mode,\"set!\"),wasInRawMode}prompt(preserveCursor){if(this.paused)this.resume();if(this.terminal&&process.env.TERM!==\"dumb\"){if(!preserveCursor)this.cursor=0;this[kRefreshLine]()}else this[kWriteToOutput](this[kPrompt])}[kQuestion](query,cb){if(this.closed)throw new ERR_USE_AFTER_CLOSE(\"readline\");if(this[kQuestionCallback])this.prompt();else this[kOldPrompt]=this[kPrompt],this.setPrompt(query),this[kQuestionCallback]=cb,this.prompt()}[kOnLine](line){if(this[kQuestionCallback]){var cb=this[kQuestionCallback];this[kQuestionCallback]=null,this.setPrompt(this[kOldPrompt]),cb(line)}else this.emit(\"line\",line)}[kBeforeEdit](oldText,oldCursor){this[kPushToUndoStack](oldText,oldCursor)}[kQuestionCancel](){if(this[kQuestionCallback])this[kQuestionCallback]=null,this.setPrompt(this[kOldPrompt]),this.clearLine()}[kWriteToOutput](stringToWrite){if(validateString(stringToWrite,\"stringToWrite\"),this.output!==null&&this.output!==void 0)this.output.write(stringToWrite)}[kAddHistory](){if(this.line.length===0)return\"\";if(this.historySize===0)return this.line;if(StringPrototypeTrim.call(this.line).length===0)return this.line;if(this.history.length===0||this.history[0]!==this.line){if(this.removeHistoryDuplicates){var dupIndex=ArrayPrototypeIndexOf.call(this.history,this.line);if(dupIndex!==-1)ArrayPrototypeSplice.call(this.history,dupIndex,1)}if(ArrayPrototypeUnshift.call(this.history,this.line),this.history.length>this.historySize)ArrayPrototypePop.call(this.history)}this.historyIndex=-1;var line=this.history[0];return this.emit(\"history\",this.history),line}[kRefreshLine](){var line=this[kPrompt]+this.line,dispPos=this[kGetDisplayPos](line),lineCols=dispPos.cols,lineRows=dispPos.rows,cursorPos=this.getCursorPos(),prevRows=this.prevRows||0;if(prevRows>0)moveCursor(this.output,0,-prevRows);if(cursorTo(this.output,0),clearScreenDown(this.output),this[kWriteToOutput](line),lineCols===0)this[kWriteToOutput](\" \");cursorTo(this.output,cursorPos.cols);var diff=lineRows-cursorPos.rows;if(diff>0)moveCursor(this.output,0,-diff);this.prevRows=cursorPos.rows}close(){if(this.closed)return;if(this.pause(),this.terminal)this[kSetRawMode](!1);this.closed=!0,this.emit(\"close\")}pause(){if(this.paused)return;return this.input.pause(),this.paused=!0,this.emit(\"pause\"),this}resume(){if(!this.paused)return;return this.input.resume(),this.paused=!1,this.emit(\"resume\"),this}write(d,key){if(this.paused)this.resume();if(this.terminal)this[kTtyWrite](d,key);else this[kNormalWrite](d)}[kNormalWrite](b){if(b===void 0)return;var string=this[kDecoder].write(b);if(this[kSawReturnAt]&&DateNow()-this[kSawReturnAt]<=this.crlfDelay){if(StringPrototypeCodePointAt.call(string)===10)string=StringPrototypeSlice.call(string,1);this[kSawReturnAt]=0}var newPartContainsEnding=RegExpPrototypeExec.call(lineEnding,string);if(newPartContainsEnding!==null){if(this[kLine_buffer])string=this[kLine_buffer]+string,this[kLine_buffer]=null,newPartContainsEnding=RegExpPrototypeExec.call(lineEnding,string);this[kSawReturnAt]=StringPrototypeEndsWith.call(string,\"\\r\")\?DateNow():0;var indexes=[0,newPartContainsEnding.index,lineEnding.lastIndex],nextMatch;while((nextMatch=RegExpPrototypeExec.call(lineEnding,string))!==null)ArrayPrototypePush.call(indexes,nextMatch.index,lineEnding.lastIndex);var lastIndex=indexes.length-1;this[kLine_buffer]=StringPrototypeSlice.call(string,indexes[lastIndex]);for(var i=1;ie!==\"\"));if(StringPrototypeStartsWith.call(prefix,completeOn)&&prefix.length>completeOn.length){this[kInsertString](StringPrototypeSlice.call(prefix,completeOn.length));return}else if(!StringPrototypeStartsWith.call(completeOn,prefix)){this.line=StringPrototypeSlice.call(this.line,0,this.cursor-completeOn.length)+prefix+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor=this.cursor-completeOn.length+prefix.length,this._refreshLine();return}if(!lastKeypressWasTab)return;this[kBeforeEdit](this.line,this.cursor);var completionsWidth=ArrayPrototypeMap.call(completions,(e)=>getStringWidth(e)),width=MathMaxApply(completionsWidth)+2,maxColumns=MathFloor(this.columns/width)||1;if(maxColumns===Infinity)maxColumns=1;var output=\"\\r\\n\",lineIndex=0,whitespace=0;for(var i=0;i0){var leading=StringPrototypeSlice.call(this.line,0,this.cursor),reversed=ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)),\"\"),match=RegExpPrototypeExec.call(/^\\s*(\?:[^\\w\\s]+|\\w+)\?/,reversed);this[kMoveCursor](-match[0].length)}}[kWordRight](){if(this.cursor0&&this.line.length>0){this[kBeforeEdit](this.line,this.cursor);var charSize=charLengthLeft(this.line,this.cursor);this.line=StringPrototypeSlice.call(this.line,0,this.cursor-charSize)+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor-=charSize,this[kRefreshLine]()}}[kDeleteRight](){if(this.cursor0){this[kBeforeEdit](this.line,this.cursor);var leading=StringPrototypeSlice.call(this.line,0,this.cursor),reversed=ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)),\"\"),match=RegExpPrototypeExec.call(/^\\s*(\?:[^\\w\\s]+|\\w+)\?/,reversed);leading=StringPrototypeSlice.call(leading,0,leading.length-match[0].length),this.line=leading+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor=leading.length,this[kRefreshLine]()}}[kDeleteWordRight](){if(this.cursorkMaxLengthOfKillRing)ArrayPrototypePop.call(this[kKillRing])}[kYank](){if(this[kKillRing].length>0)this[kYanking]=!0,this[kInsertString](this[kKillRing][this[kKillRingCursor]])}[kYankPop](){if(!this[kYanking])return;if(this[kKillRing].length>1){var lastYank=this[kKillRing][this[kKillRingCursor]];if(this[kKillRingCursor]++,this[kKillRingCursor]>=this[kKillRing].length)this[kKillRingCursor]=0;var currentYank=this[kKillRing][this[kKillRingCursor]],head=StringPrototypeSlice.call(this.line,0,this.cursor-lastYank.length),tail=StringPrototypeSlice.call(this.line,this.cursor);this.line=head+currentYank+tail,this.cursor=head.length+currentYank.length,this[kRefreshLine]()}}clearLine(){this[kMoveCursor](Infinity),this[kWriteToOutput](\"\\r\\n\"),this.line=\"\",this.cursor=0,this.prevRows=0}[kLine](){var line=this[kAddHistory]();this[kUndoStack]=[],this[kRedoStack]=[],this.clearLine(),this[kOnLine](line)}[kPushToUndoStack](text,cursor){if(ArrayPrototypePush.call(this[kUndoStack],{text,cursor})>kMaxUndoRedoStackSize)ArrayPrototypeShift.call(this[kUndoStack])}[kUndo](){if(this[kUndoStack].length<=0)return;ArrayPrototypePush.call(this[kRedoStack],{text:this.line,cursor:this.cursor});var entry=ArrayPrototypePop.call(this[kUndoStack]);this.line=entry.text,this.cursor=entry.cursor,this[kRefreshLine]()}[kRedo](){if(this[kRedoStack].length<=0)return;ArrayPrototypePush.call(this[kUndoStack],{text:this.line,cursor:this.cursor});var entry=ArrayPrototypePop.call(this[kRedoStack]);this.line=entry.text,this.cursor=entry.cursor,this[kRefreshLine]()}[kHistoryNext](){if(this.historyIndex>=0){this[kBeforeEdit](this.line,this.cursor);var search=this[kSubstringSearch]||\"\",index=this.historyIndex-1;while(index>=0&&(!StringPrototypeStartsWith.call(this.history[index],search)||this.line===this.history[index]))index--;if(index===-1)this.line=search;else this.line=this.history[index];this.historyIndex=index,this.cursor=this.line.length,this[kRefreshLine]()}}[kHistoryPrev](){if(this.historyIndexthis.line.length)this.cursor=this.line.length;var newPos=this.getCursorPos();if(oldPos.rows===newPos.rows){var diffWidth=newPos.cols-oldPos.cols;moveCursor(this.output,diffWidth,0)}else this[kRefreshLine]()}[kTtyWrite](s,key){var previousKey=this[kPreviousKey];key=key||kEmptyObject,this[kPreviousKey]=key;var{name:keyName,meta:keyMeta,ctrl:keyCtrl2,shift:keyShift,sequence:keySeq}=key;if(!keyMeta||keyName!==\"y\")this[kYanking]=!1;if((keyName===\"up\"||keyName===\"down\")&&!keyCtrl2&&!keyMeta&&!keyShift){if(this[kSubstringSearch]===null)this[kSubstringSearch]=StringPrototypeSlice.call(this.line,0,this.cursor)}else if(this[kSubstringSearch]!==null){if(this[kSubstringSearch]=null,this.history.length===this.historyIndex)this.historyIndex=-1}if(typeof keySeq===\"string\")switch(StringPrototypeCodePointAt.call(keySeq,0)){case 31:this[kUndo]();return;case 30:this[kRedo]();return;default:break}if(keyName===\"escape\")return;if(keyCtrl2&&keyShift)switch(keyName){case\"backspace\":this[kDeleteLineLeft]();break;case\"delete\":this[kDeleteLineRight]();break}else if(keyCtrl2)switch(keyName){case\"c\":if(this.listenerCount(\"SIGINT\")>0)this.emit(\"SIGINT\");else this.close();break;case\"h\":this[kDeleteLeft]();break;case\"d\":if(this.cursor===0&&this.line.length===0)this.close();else if(this.cursorthis.crlfDelay)this[kLine]();this[kSawReturnAt]=0;break;case\"backspace\":this[kDeleteLeft]();break;case\"delete\":this[kDeleteRight]();break;case\"left\":this[kMoveCursor](-charLengthLeft(this.line,this.cursor));break;case\"right\":this[kMoveCursor](+charLengthAt(this.line,this.cursor));break;case\"home\":this[kMoveCursor]((-Infinity));break;case\"end\":this[kMoveCursor](Infinity);break;case\"up\":this[kHistoryPrev]();break;case\"down\":this[kHistoryNext]();break;case\"tab\":if(typeof this.completer===\"function\"&&this.isCompletionEnabled){var lastKeypressWasTab=previousKey&&previousKey.name===\"tab\";this[kTabComplete](lastKeypressWasTab);break}default:if(typeof s===\"string\"&&s){var nextMatch=RegExpPrototypeExec.call(lineEnding,s);if(nextMatch!==null){this[kInsertString](StringPrototypeSlice.call(s,0,nextMatch.index));var{lastIndex}=lineEnding;while((nextMatch=RegExpPrototypeExec.call(lineEnding,s))!==null)this[kLine](),this[kInsertString](StringPrototypeSlice.call(s,lastIndex,nextMatch.index)),{lastIndex}=lineEnding;if(lastIndex===s.length)this[kLine]()}else this[kInsertString](s)}}}}[SymbolAsyncIterator](){if(this[kLineObjectStream]===void 0)this[kLineObjectStream]=EventEmitter.on(this,\"line\",{close:[\"close\"],highWatermark:1024,[kFirstEventParam]:!0});return this[kLineObjectStream]}};function Interface(input,output,completer,terminal){if(!(this instanceof Interface))return new Interface(input,output,completer,terminal);if(input\?.input&&typeof input.completer===\"function\"&&input.completer.length!==2){var{completer}=input;input.completer=(v,cb)=>cb(null,completer(v))}else if(typeof completer===\"function\"&&completer.length!==2){var realCompleter=completer;completer=(v,cb)=>cb(null,realCompleter(v))}if(InterfaceConstructor.call(this,input,output,completer,terminal),process.env.TERM===\"dumb\")this._ttyWrite=_ttyWriteDumb.bind(this)}Interface.prototype={},ObjectSetPrototypeOf(Interface.prototype,_Interface.prototype),ObjectSetPrototypeOf(Interface,_Interface),Interface.prototype.question=function question(query,options,cb){if(cb=typeof options===\"function\"\?options:cb,options===null||typeof options!==\"object\")options=kEmptyObject;var signal=options\?.signal;if(signal){if(validateAbortSignal(signal,\"options.signal\"),signal.aborted)return;var onAbort=()=>{this[kQuestionCancel]()};signal.addEventListener(\"abort\",onAbort,{once:!0});var cleanup=()=>{signal.removeEventListener(\"abort\",onAbort)},originalCb=cb;cb=typeof cb===\"function\"\?(answer)=>{return cleanup(),originalCb(answer)}:cleanup}if(typeof cb===\"function\")this[kQuestion](query,cb)},Interface.prototype.question[promisify.custom]=function question(query,options){if(options===null||typeof options!==\"object\")options=kEmptyObject;var signal=options\?.signal;if(signal&&signal.aborted)return PromiseReject(new AbortError(void 0,{cause:signal.reason}));return new Promise((resolve,reject)=>{var cb=resolve;if(signal){var onAbort=()=>{reject(new AbortError(void 0,{cause:signal.reason}))};signal.addEventListener(\"abort\",onAbort,{once:!0}),cb=(answer)=>{signal.removeEventListener(\"abort\",onAbort),resolve(answer)}}this.question(query,options,cb)})};function createInterface(input,output,completer,terminal){return new Interface(input,output,completer,terminal)}ObjectDefineProperties(Interface.prototype,{[kSetRawMode]:{__proto__:null,get(){return this._setRawMode}},[kOnLine]:{__proto__:null,get(){return this._onLine}},[kWriteToOutput]:{__proto__:null,get(){return this._writeToOutput}},[kAddHistory]:{__proto__:null,get(){return this._addHistory}},[kRefreshLine]:{__proto__:null,get(){return this._refreshLine}},[kNormalWrite]:{__proto__:null,get(){return this._normalWrite}},[kInsertString]:{__proto__:null,get(){return this._insertString}},[kTabComplete]:{__proto__:null,get(){return this._tabComplete}},[kWordLeft]:{__proto__:null,get(){return this._wordLeft}},[kWordRight]:{__proto__:null,get(){return this._wordRight}},[kDeleteLeft]:{__proto__:null,get(){return this._deleteLeft}},[kDeleteRight]:{__proto__:null,get(){return this._deleteRight}},[kDeleteWordLeft]:{__proto__:null,get(){return this._deleteWordLeft}},[kDeleteWordRight]:{__proto__:null,get(){return this._deleteWordRight}},[kDeleteLineLeft]:{__proto__:null,get(){return this._deleteLineLeft}},[kDeleteLineRight]:{__proto__:null,get(){return this._deleteLineRight}},[kLine]:{__proto__:null,get(){return this._line}},[kHistoryNext]:{__proto__:null,get(){return this._historyNext}},[kHistoryPrev]:{__proto__:null,get(){return this._historyPrev}},[kGetDisplayPos]:{__proto__:null,get(){return this._getDisplayPos}},[kMoveCursor]:{__proto__:null,get(){return this._moveCursor}},[kTtyWrite]:{__proto__:null,get(){return this._ttyWrite}},_decoder:{__proto__:null,get(){return this[kDecoder]},set(value){this[kDecoder]=value}},_line_buffer:{__proto__:null,get(){return this[kLine_buffer]},set(value){this[kLine_buffer]=value}},_oldPrompt:{__proto__:null,get(){return this[kOldPrompt]},set(value){this[kOldPrompt]=value}},_previousKey:{__proto__:null,get(){return this[kPreviousKey]},set(value){this[kPreviousKey]=value}},_prompt:{__proto__:null,get(){return this[kPrompt]},set(value){this[kPrompt]=value}},_questionCallback:{__proto__:null,get(){return this[kQuestionCallback]},set(value){this[kQuestionCallback]=value}},_sawKeyPress:{__proto__:null,get(){return this[kSawKeyPress]},set(value){this[kSawKeyPress]=value}},_sawReturnAt:{__proto__:null,get(){return this[kSawReturnAt]},set(value){this[kSawReturnAt]=value}}}),Interface.prototype._setRawMode=_Interface.prototype[kSetRawMode],Interface.prototype._onLine=_Interface.prototype[kOnLine],Interface.prototype._writeToOutput=_Interface.prototype[kWriteToOutput],Interface.prototype._addHistory=_Interface.prototype[kAddHistory],Interface.prototype._refreshLine=_Interface.prototype[kRefreshLine],Interface.prototype._normalWrite=_Interface.prototype[kNormalWrite],Interface.prototype._insertString=_Interface.prototype[kInsertString],Interface.prototype._tabComplete=function(lastKeypressWasTab){this.pause();var string=StringPrototypeSlice.call(this.line,0,this.cursor);this.completer(string,(err,value)=>{if(this.resume(),err){this._writeToOutput(`Tab completion error: ${inspect(err)}`);return}this[kTabCompleter](lastKeypressWasTab,value)})},Interface.prototype._wordLeft=_Interface.prototype[kWordLeft],Interface.prototype._wordRight=_Interface.prototype[kWordRight],Interface.prototype._deleteLeft=_Interface.prototype[kDeleteLeft],Interface.prototype._deleteRight=_Interface.prototype[kDeleteRight],Interface.prototype._deleteWordLeft=_Interface.prototype[kDeleteWordLeft],Interface.prototype._deleteWordRight=_Interface.prototype[kDeleteWordRight],Interface.prototype._deleteLineLeft=_Interface.prototype[kDeleteLineLeft],Interface.prototype._deleteLineRight=_Interface.prototype[kDeleteLineRight],Interface.prototype._line=_Interface.prototype[kLine],Interface.prototype._historyNext=_Interface.prototype[kHistoryNext],Interface.prototype._historyPrev=_Interface.prototype[kHistoryPrev],Interface.prototype._getDisplayPos=_Interface.prototype[kGetDisplayPos],Interface.prototype._getCursorPos=_Interface.prototype.getCursorPos,Interface.prototype._moveCursor=_Interface.prototype[kMoveCursor],Interface.prototype._ttyWrite=_Interface.prototype[kTtyWrite];function _ttyWriteDumb(s,key){if(key=key||kEmptyObject,key.name===\"escape\")return;if(this[kSawReturnAt]&&key.name!==\"enter\")this[kSawReturnAt]=0;if(keyCtrl){if(key.name===\"c\"){if(this.listenerCount(\"SIGINT\")>0)this.emit(\"SIGINT\");else this.close();return}else if(key.name===\"d\"){this.close();return}}switch(key.name){case\"return\":this[kSawReturnAt]=DateNow(),this._line();break;case\"enter\":if(this[kSawReturnAt]===0||DateNow()-this[kSawReturnAt]>this.crlfDelay)this._line();this[kSawReturnAt]=0;break;default:if(typeof s===\"string\"&&s)this.line+=s,this.cursor+=s.length,this._writeToOutput(s)}}class Readline{#autoCommit=!1;#stream;#todo=[];constructor(stream,options=void 0){if(isWritable\?\?=(@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34)).isWritable,!isWritable(stream))throw new ERR_INVALID_ARG_TYPE(\"stream\",\"Writable\",stream);if(this.#stream=stream,options\?.autoCommit!=null)validateBoolean(options.autoCommit,\"options.autoCommit\"),this.#autoCommit=options.autoCommit}cursorTo(x,y=void 0){if(validateInteger(x,\"x\"),y!=null)validateInteger(y,\"y\");var data=y==null\?CSI`${x+1}G`:CSI`${y+1};${x+1}H`;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data);return this}moveCursor(dx,dy){if(dx||dy){validateInteger(dx,\"dx\"),validateInteger(dy,\"dy\");var data=\"\";if(dx<0)data+=CSI`${-dx}D`;else if(dx>0)data+=CSI`${dx}C`;if(dy<0)data+=CSI`${-dy}A`;else if(dy>0)data+=CSI`${dy}B`;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data)}return this}clearLine(dir){validateInteger(dir,\"dir\",-1,1);var data=dir<0\?kClearToLineBeginning:dir>0\?kClearToLineEnd:kClearLine;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data);return this}clearScreenDown(){if(this.#autoCommit)process.nextTick(()=>this.#stream.write(kClearScreenDown));else ArrayPrototypePush.call(this.#todo,kClearScreenDown);return this}commit(){return new Promise((resolve)=>{this.#stream.write(ArrayPrototypeJoin.call(this.#todo,\"\"),resolve),this.#todo=[]})}rollback(){return this.#todo=[],this}}var PromisesInterface=class Interface2 extends _Interface{constructor(input,output,completer,terminal){super(input,output,completer,terminal)}question(query,options=kEmptyObject){var signal=options\?.signal;if(signal){if(validateAbortSignal(signal,\"options.signal\"),signal.aborted)return PromiseReject(new AbortError(void 0,{cause:signal.reason}))}return new Promise((resolve,reject)=>{var cb=resolve;if(options\?.signal){var onAbort=()=>{this[kQuestionCancel](),reject(new AbortError(void 0,{cause:signal.reason}))};signal.addEventListener(\"abort\",onAbort,{once:!0}),cb=(answer)=>{signal.removeEventListener(\"abort\",onAbort),resolve(answer)}}this[kQuestion](query,cb)})}};return $={Interface,clearLine,clearScreenDown,createInterface,cursorTo,emitKeypressEvents,moveCursor,promises:{Readline,Interface:PromisesInterface,createInterface(input,output,completer,terminal){return new PromisesInterface(input,output,completer,terminal)}},[SymbolFor(\"__BUN_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED__\")]:{CSI,utils:{getStringWidth,stripVTControlCharacters}}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeReadlinePromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,30)||@createInternalModuleById(30)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeReplCode = "(function (){\"use strict\";var $;const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function REPLServer(){throwNotImplemented(\"node:repl REPLServer\")}function Recoverable(){throwNotImplemented(\"node:repl Recoverable\")}var REPL_MODE_SLOPPY=0,REPL_MODE_STRICT=1;function start(){throwNotImplemented(\"node:repl\")}return $={lines:[],context:globalThis,historyIndex:-1,cursor:0,historySize:1000,removeHistoryDuplicates:!1,crlfDelay:100,completer:()=>{throwNotImplemented(\"node:repl\")},history:[],_initialPrompt:\"> \",terminal:!0,input:new Proxy({},{get(){throwNotImplemented(\"node:repl\")},has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{return},set(){throwNotImplemented(\"node:repl\")}}),line:\"\",eval:()=>{throwNotImplemented(\"node:repl\")},isCompletionEnabled:!0,escapeCodeTimeout:500,tabSize:8,breakEvalOnSigint:!0,useGlobal:!0,underscoreAssigned:!1,last:void 0,_domain:void 0,allowBlockingCompletions:!1,useColors:!0,output:new Proxy({},{get(){throwNotImplemented(\"node:repl\")},has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{return},set(){throwNotImplemented(\"node:repl\")}})},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamConsumersCode = "(function (){\"use strict\";const{readableStreamToArrayBuffer:arrayBuffer,readableStreamToText:text}=Bun,json=(stream)=>Bun.readableStreamToText(stream).then(JSON.parse),buffer=async(readableStream)=>{return new Buffer(await arrayBuffer(readableStream))},blob=Bun.readableStreamToBlob;return{arrayBuffer,text,json,buffer,blob}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamCode = "(function (){\"use strict\";const EE=globalThis[globalThis.Symbol.for('Bun.lazy')](\"events\"),StringDecoder=@requireNativeModule(\"node:string_decoder\").StringDecoder;var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},runOnNextTick=process.nextTick;function isReadableStream(value){return typeof value===\"object\"&&value!==null&&value instanceof ReadableStream}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}const validateObject=(value,name,options=null)=>{const allowArray=options\?.allowArray\?\?!1,allowFunction=options\?.allowFunction\?\?!1;if(!(options\?.nullable\?\?!1)&&value===null||!allowArray&&ArrayIsArray(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE(name,\"Object\",value)};function validateString(value,name){if(typeof value!==\"string\")throw new ERR_INVALID_ARG_TYPE(name,\"string\",value)}var ArrayIsArray=Array.isArray;function ERR_INVALID_ARG_TYPE(name,type,value){return new Error(`The argument '${name}' is invalid. Received '${value}' for type '${type}'`)}function ERR_INVALID_ARG_VALUE(name,value,reason){return new Error(`The value '${value}' is invalid for argument '${name}'. Reason: ${reason}`)}var require_primordials=__commonJS({\"node_modules/readable-stream/lib/ours/primordials.js\"(exports2,module){module.exports={ArrayIsArray(self){return Array.isArray(self)},ArrayPrototypeIncludes(self,el){return self.includes(el)},ArrayPrototypeIndexOf(self,el){return self.indexOf(el)},ArrayPrototypeJoin(self,sep){return self.join(sep)},ArrayPrototypeMap(self,fn){return self.map(fn)},ArrayPrototypePop(self,el){return self.pop(el)},ArrayPrototypePush(self,el){return self.push(el)},ArrayPrototypeSlice(self,start,end){return self.slice(start,end)},Error,FunctionPrototypeCall(fn,thisArgs,...args){return fn.call(thisArgs,...args)},FunctionPrototypeSymbolHasInstance(self,instance){return Function.prototype[Symbol.hasInstance].call(self,instance)},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(self,props){return Object.defineProperties(self,props)},ObjectDefineProperty(self,name,prop){return Object.defineProperty(self,name,prop)},ObjectGetOwnPropertyDescriptor(self,name){return Object.getOwnPropertyDescriptor(self,name)},ObjectKeys(obj){return Object.keys(obj)},ObjectSetPrototypeOf(target,proto){return Object.setPrototypeOf(target,proto)},Promise,PromisePrototypeCatch(self,fn){return self.catch(fn)},PromisePrototypeThen(self,thenFn,catchFn){return self.then(thenFn,catchFn)},PromiseReject(err){return Promise.reject(err)},ReflectApply:Reflect.apply,RegExpPrototypeTest(self,value){return self.test(value)},SafeSet:Set,String,StringPrototypeSlice(self,start,end){return self.slice(start,end)},StringPrototypeToLowerCase(self){return self.toLowerCase()},StringPrototypeToUpperCase(self){return self.toUpperCase()},StringPrototypeTrim(self){return self.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(self,buf,len){return self.set(buf,len)},Uint8Array}}}),require_util=__commonJS({\"node_modules/readable-stream/lib/ours/util.js\"(exports2,module){var AsyncFunction=Object.getPrototypeOf(async function(){}).constructor,isBlob=typeof Blob!==\"undefined\"\?function isBlob2(b){return b instanceof Blob}:function isBlob2(b){return!1},AggregateError=class extends Error{constructor(errors){if(!Array.isArray(errors))@throwTypeError(`Expected input to be an Array, got ${typeof errors}`);let message=\"\";for(let i=0;i{resolve=res,reject=rej}),resolve,reject}},promisify(fn){return new Promise((resolve,reject)=>{fn((err,...args)=>{if(err)return reject(err);return resolve(...args)})})},debuglog(){return function(){}},format(format,...args){return format.replace(/%([sdifj])/g,function(...[_unused,type]){const replacement=args.shift();if(type===\"f\")return replacement.toFixed(6);else if(type===\"j\")return JSON.stringify(replacement);else if(type===\"s\"&&typeof replacement===\"object\")return`${replacement.constructor!==Object\?replacement.constructor.name:\"\"} {}`.trim();else return replacement.toString()})},inspect(value){switch(typeof value){case\"string\":if(value.includes(\"'\")){if(!value.includes('\"'))return`\"${value}\"`;else if(!value.includes(\"`\")&&!value.includes(\"${\"))return`\\`${value}\\``}return`'${value}'`;case\"number\":if(isNaN(value))return\"NaN\";else if(Object.is(value,-0))return String(value);return value;case\"bigint\":return`${String(value)}n`;case\"boolean\":case\"undefined\":return String(value);case\"object\":return\"{}\"}},types:{isAsyncFunction(fn){return fn instanceof AsyncFunction},isArrayBufferView(arr){return ArrayBuffer.isView(arr)}},isBlob},module.exports.promisify.custom=Symbol.for(\"nodejs.util.promisify.custom\")}}),require_errors=__commonJS({\"node_modules/readable-stream/lib/ours/errors.js\"(exports2,module){var{format,inspect,AggregateError:CustomAggregateError}=require_util(),AggregateError=globalThis.AggregateError||CustomAggregateError,kIsNodeError=Symbol(\"kIsNodeError\"),kTypes=[\"string\",\"function\",\"number\",\"object\",\"Function\",\"Object\",\"boolean\",\"bigint\",\"symbol\"],classRegExp=/^([A-Z][a-z0-9]*)+$/,nodeInternalPrefix=\"__node_internal_\",codes={};function assert(value,message){if(!value)throw new codes.ERR_INTERNAL_ASSERTION(message)}function addNumericalSeparator(val){let res=\"\",i=val.length;const start=val[0]===\"-\"\?1:0;for(;i>=start+4;i-=3)res=`_${val.slice(i-3,i)}${res}`;return`${val.slice(0,i)}${res}`}function getMessage(key,msg,args){if(typeof msg===\"function\")return assert(msg.length<=args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`),msg(...args);const expectedLength=(msg.match(/%[dfijoOs]/g)||[]).length;if(assert(expectedLength===args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`),args.length===0)return msg;return format(msg,...args)}function E(code,message,Base){if(!Base)Base=Error;class NodeError extends Base{constructor(...args){super(getMessage(code,message,args))}toString(){return`${this.name} [${code}]: ${this.message}`}}Object.defineProperties(NodeError.prototype,{name:{value:Base.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${code}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),NodeError.prototype.code=code,NodeError.prototype[kIsNodeError]=!0,codes[code]=NodeError}function hideStackFrames(fn){const hidden=nodeInternalPrefix+fn.name;return Object.defineProperty(fn,\"name\",{value:hidden}),fn}function aggregateTwoErrors(innerError,outerError){if(innerError&&outerError&&innerError!==outerError){if(Array.isArray(outerError.errors))return outerError.errors.push(innerError),outerError;const err=new AggregateError([outerError,innerError],outerError.message);return err.code=outerError.code,err}return innerError||outerError}var AbortError2=class extends Error{constructor(message=\"The operation was aborted\",options=void 0){if(options!==void 0&&typeof options!==\"object\")throw new codes.ERR_INVALID_ARG_TYPE(\"options\",\"Object\",options);super(message,options);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};E(\"ERR_ASSERTION\",\"%s\",Error),E(\"ERR_INVALID_ARG_TYPE\",(name,expected,actual)=>{if(assert(typeof name===\"string\",\"'name' must be a string\"),!Array.isArray(expected))expected=[expected];let msg=\"The \";if(name.endsWith(\" argument\"))msg+=`${name} `;else msg+=`\"${name}\" ${name.includes(\".\")\?\"property\":\"argument\"} `;msg+=\"must be \";const types=[],instances=[],other=[];for(let value of expected)if(assert(typeof value===\"string\",\"All expected entries have to be of type string\"),kTypes.includes(value))types.push(value.toLowerCase());else if(classRegExp.test(value))instances.push(value);else assert(value!==\"object\",'The value \"object\" should be written as \"Object\"'),other.push(value);if(instances.length>0){const pos=types.indexOf(\"object\");if(pos!==-1)types.splice(types,pos,1),instances.push(\"Object\")}if(types.length>0){switch(types.length){case 1:msg+=`of type ${types[0]}`;break;case 2:msg+=`one of type ${types[0]} or ${types[1]}`;break;default:{const last=types.pop();msg+=`one of type ${types.join(\", \")}, or ${last}`}}if(instances.length>0||other.length>0)msg+=\" or \"}if(instances.length>0){switch(instances.length){case 1:msg+=`an instance of ${instances[0]}`;break;case 2:msg+=`an instance of ${instances[0]} or ${instances[1]}`;break;default:{const last=instances.pop();msg+=`an instance of ${instances.join(\", \")}, or ${last}`}}if(other.length>0)msg+=\" or \"}switch(other.length){case 0:break;case 1:if(other[0].toLowerCase()!==other[0])msg+=\"an \";msg+=`${other[0]}`;break;case 2:msg+=`one of ${other[0]} or ${other[1]}`;break;default:{const last=other.pop();msg+=`one of ${other.join(\", \")}, or ${last}`}}if(actual==null)msg+=`. Received ${actual}`;else if(typeof actual===\"function\"&&actual.name)msg+=`. Received function ${actual.name}`;else if(typeof actual===\"object\"){var _actual$constructor;if((_actual$constructor=actual.constructor)!==null&&_actual$constructor!==void 0&&_actual$constructor.name)msg+=`. Received an instance of ${actual.constructor.name}`;else{const inspected=inspect(actual,{depth:-1});msg+=`. Received ${inspected}`}}else{let inspected=inspect(actual,{colors:!1});if(inspected.length>25)inspected=`${inspected.slice(0,25)}...`;msg+=`. Received type ${typeof actual} (${inspected})`}return msg},TypeError),E(\"ERR_INVALID_ARG_VALUE\",(name,value,reason=\"is invalid\")=>{let inspected=inspect(value);if(inspected.length>128)inspected=inspected.slice(0,128)+\"...\";return`The ${name.includes(\".\")\?\"property\":\"argument\"} '${name}' ${reason}. Received ${inspected}`},TypeError),E(\"ERR_INVALID_RETURN_VALUE\",(input,name,value)=>{var _value$constructor;const type=value!==null&&value!==void 0&&(_value$constructor=value.constructor)!==null&&_value$constructor!==void 0&&_value$constructor.name\?`instance of ${value.constructor.name}`:`type ${typeof value}`;return`Expected ${input} to be returned from the \"${name}\" function but got ${type}.`},TypeError),E(\"ERR_MISSING_ARGS\",(...args)=>{assert(args.length>0,\"At least one arg needs to be specified\");let msg;const len=args.length;switch(args=(Array.isArray(args)\?args:[args]).map((a)=>`\"${a}\"`).join(\" or \"),len){case 1:msg+=`The ${args[0]} argument`;break;case 2:msg+=`The ${args[0]} and ${args[1]} arguments`;break;default:{const last=args.pop();msg+=`The ${args.join(\", \")}, and ${last} arguments`}break}return`${msg} must be specified`},TypeError),E(\"ERR_OUT_OF_RANGE\",(str,range,input)=>{assert(range,'Missing \"range\" argument');let received;if(Number.isInteger(input)&&Math.abs(input)>4294967296)received=addNumericalSeparator(String(input));else if(typeof input===\"bigint\"){if(received=String(input),input>2n**32n||input<-(2n**32n))received=addNumericalSeparator(received);received+=\"n\"}else received=inspect(input);return`The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`},RangeError),E(\"ERR_MULTIPLE_CALLBACK\",\"Callback called multiple times\",Error),E(\"ERR_METHOD_NOT_IMPLEMENTED\",\"The %s method is not implemented\",Error),E(\"ERR_STREAM_ALREADY_FINISHED\",\"Cannot call %s after a stream was finished\",Error),E(\"ERR_STREAM_CANNOT_PIPE\",\"Cannot pipe, not readable\",Error),E(\"ERR_STREAM_DESTROYED\",\"Cannot call %s after a stream was destroyed\",Error),E(\"ERR_STREAM_NULL_VALUES\",\"May not write null values to stream\",TypeError),E(\"ERR_STREAM_PREMATURE_CLOSE\",\"Premature close\",Error),E(\"ERR_STREAM_PUSH_AFTER_EOF\",\"stream.push() after EOF\",Error),E(\"ERR_STREAM_UNSHIFT_AFTER_END_EVENT\",\"stream.unshift() after end event\",Error),E(\"ERR_STREAM_WRITE_AFTER_END\",\"write after end\",Error),E(\"ERR_UNKNOWN_ENCODING\",\"Unknown encoding: %s\",TypeError),module.exports={AbortError:AbortError2,aggregateTwoErrors:hideStackFrames(aggregateTwoErrors),hideStackFrames,codes}}}),require_validators=__commonJS({\"node_modules/readable-stream/lib/internal/validators.js\"(exports2,module){var{ArrayIsArray:ArrayIsArray2,ArrayPrototypeIncludes,ArrayPrototypeJoin,ArrayPrototypeMap,NumberIsInteger,NumberMAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER,NumberParseInt,RegExpPrototypeTest,String:String2,StringPrototypeToUpperCase,StringPrototypeTrim}=require_primordials(),{hideStackFrames,codes:{ERR_SOCKET_BAD_PORT,ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2,ERR_OUT_OF_RANGE,ERR_UNKNOWN_SIGNAL}}=require_errors(),{normalizeEncoding}=require_util(),{isAsyncFunction,isArrayBufferView}=require_util().types,signals={};function isInt32(value){return value===(value|0)}function isUint32(value){return value===value>>>0}var octalReg=/^[0-7]+$/,modeDesc=\"must be a 32-bit unsigned integer or an octal string\";function parseFileMode(value,name,def){if(typeof value===\"undefined\")value=def;if(typeof value===\"string\"){if(!RegExpPrototypeTest(octalReg,value))throw new ERR_INVALID_ARG_VALUE2(name,value,modeDesc);value=NumberParseInt(value,8)}return validateInt32(value,name,0,4294967295),value}var validateInteger=hideStackFrames((value,name,min=NumberMIN_SAFE_INTEGER,max=NumberMAX_SAFE_INTEGER)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}),validateInt32=hideStackFrames((value,name,min=-2147483648,max=2147483647)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!isInt32(value)){if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}),validateUint32=hideStackFrames((value,name,positive)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!isUint32(value)){if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);throw new ERR_OUT_OF_RANGE(name,`>= ${positive\?1:0} && < 4294967296`,value)}if(positive&&value===0)throw new ERR_OUT_OF_RANGE(name,\">= 1 && < 4294967296\",value)});function validateString2(value,name){if(typeof value!==\"string\")throw new ERR_INVALID_ARG_TYPE2(name,\"string\",value)}function validateNumber(value,name){if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value)}var validateOneOf=hideStackFrames((value,name,oneOf)=>{if(!ArrayPrototypeIncludes(oneOf,value)){const reason=\"must be one of: \"+ArrayPrototypeJoin(ArrayPrototypeMap(oneOf,(v)=>typeof v===\"string\"\?`'${v}'`:String2(v)),\", \");throw new ERR_INVALID_ARG_VALUE2(name,value,reason)}});function validateBoolean2(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE2(name,\"boolean\",value)}var validateObject2=hideStackFrames((value,name,options)=>{const useDefaultOptions=options==null,allowArray=useDefaultOptions\?!1:options.allowArray,allowFunction=useDefaultOptions\?!1:options.allowFunction;if(!(useDefaultOptions\?!1:options.nullable)&&value===null||!allowArray&&ArrayIsArray2(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE2(name,\"Object\",value)}),validateArray=hideStackFrames((value,name,minLength=0)=>{if(!ArrayIsArray2(value))throw new ERR_INVALID_ARG_TYPE2(name,\"Array\",value);if(value.length{if(!isArrayBufferView(buffer))throw new ERR_INVALID_ARG_TYPE2(name,[\"Buffer\",\"TypedArray\",\"DataView\"],buffer)});function validateEncoding(data,encoding){const normalizedEncoding=normalizeEncoding(encoding),length=data.length;if(normalizedEncoding===\"hex\"&&length%2!==0)throw new ERR_INVALID_ARG_VALUE2(\"encoding\",encoding,`is invalid for data of length ${length}`)}function validatePort(port,name=\"Port\",allowZero=!0){if(typeof port!==\"number\"&&typeof port!==\"string\"||typeof port===\"string\"&&StringPrototypeTrim(port).length===0||+port!==+port>>>0||port>65535||port===0&&!allowZero)throw new ERR_SOCKET_BAD_PORT(name,port,allowZero);return port|0}var validateAbortSignal=hideStackFrames((signal,name)=>{if(signal!==void 0&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE2(name,\"AbortSignal\",signal)}),validateFunction=hideStackFrames((value,name)=>{if(typeof value!==\"function\")throw new ERR_INVALID_ARG_TYPE2(name,\"Function\",value)}),validatePlainFunction=hideStackFrames((value,name)=>{if(typeof value!==\"function\"||isAsyncFunction(value))throw new ERR_INVALID_ARG_TYPE2(name,\"Function\",value)}),validateUndefined=hideStackFrames((value,name)=>{if(value!==void 0)throw new ERR_INVALID_ARG_TYPE2(name,\"undefined\",value)});module.exports={isInt32,isUint32,parseFileMode,validateArray,validateBoolean:validateBoolean2,validateBuffer,validateEncoding,validateFunction,validateInt32,validateInteger,validateNumber,validateObject:validateObject2,validateOneOf,validatePlainFunction,validatePort,validateSignalName,validateString:validateString2,validateUint32,validateUndefined,validateAbortSignal}}}),require_utils=__commonJS({\"node_modules/readable-stream/lib/internal/streams/utils.js\"(exports2,module){var{Symbol:Symbol2,SymbolAsyncIterator,SymbolIterator}=require_primordials(),kDestroyed=Symbol2(\"kDestroyed\"),kIsErrored=Symbol2(\"kIsErrored\"),kIsReadable=Symbol2(\"kIsReadable\"),kIsDisturbed=Symbol2(\"kIsDisturbed\");function isReadableNodeStream(obj,strict=!1){var _obj$_readableState;return!!(obj&&typeof obj.pipe===\"function\"&&typeof obj.on===\"function\"&&(!strict||typeof obj.pause===\"function\"&&typeof obj.resume===\"function\")&&(!obj._writableState||((_obj$_readableState=obj._readableState)===null||_obj$_readableState===void 0\?void 0:_obj$_readableState.readable)!==!1)&&(!obj._writableState||obj._readableState))}function isWritableNodeStream(obj){var _obj$_writableState;return!!(obj&&typeof obj.write===\"function\"&&typeof obj.on===\"function\"&&(!obj._readableState||((_obj$_writableState=obj._writableState)===null||_obj$_writableState===void 0\?void 0:_obj$_writableState.writable)!==!1))}function isDuplexNodeStream(obj){return!!(obj&&typeof obj.pipe===\"function\"&&obj._readableState&&typeof obj.on===\"function\"&&typeof obj.write===\"function\")}function isNodeStream(obj){return obj&&(obj._readableState||obj._writableState||typeof obj.write===\"function\"&&typeof obj.on===\"function\"||typeof obj.pipe===\"function\"&&typeof obj.on===\"function\")}function isIterable(obj,isAsync){if(obj==null)return!1;if(isAsync===!0)return typeof obj[SymbolAsyncIterator]===\"function\";if(isAsync===!1)return typeof obj[SymbolIterator]===\"function\";return typeof obj[SymbolAsyncIterator]===\"function\"||typeof obj[SymbolIterator]===\"function\"}function isDestroyed(stream){if(!isNodeStream(stream))return null;const{_writableState:wState,_readableState:rState}=stream,state=wState||rState;return!!(stream.destroyed||stream[kDestroyed]||state!==null&&state!==void 0&&state.destroyed)}function isWritableEnded(stream){if(!isWritableNodeStream(stream))return null;if(stream.writableEnded===!0)return!0;const wState=stream._writableState;if(wState!==null&&wState!==void 0&&wState.errored)return!1;if(typeof(wState===null||wState===void 0\?void 0:wState.ended)!==\"boolean\")return null;return wState.ended}function isWritableFinished(stream,strict){if(!isWritableNodeStream(stream))return null;if(stream.writableFinished===!0)return!0;const wState=stream._writableState;if(wState!==null&&wState!==void 0&&wState.errored)return!1;if(typeof(wState===null||wState===void 0\?void 0:wState.finished)!==\"boolean\")return null;return!!(wState.finished||strict===!1&&wState.ended===!0&&wState.length===0)}function isReadableEnded(stream){if(!isReadableNodeStream(stream))return null;if(stream.readableEnded===!0)return!0;const rState=stream._readableState;if(!rState||rState.errored)return!1;if(typeof(rState===null||rState===void 0\?void 0:rState.ended)!==\"boolean\")return null;return rState.ended}function isReadableFinished(stream,strict){if(!isReadableNodeStream(stream))return null;const rState=stream._readableState;if(rState!==null&&rState!==void 0&&rState.errored)return!1;if(typeof(rState===null||rState===void 0\?void 0:rState.endEmitted)!==\"boolean\")return null;return!!(rState.endEmitted||strict===!1&&rState.ended===!0&&rState.length===0)}function isReadable(stream){if(stream&&stream[kIsReadable]!=null)return stream[kIsReadable];if(typeof(stream===null||stream===void 0\?void 0:stream.readable)!==\"boolean\")return null;if(isDestroyed(stream))return!1;return isReadableNodeStream(stream)&&stream.readable&&!isReadableFinished(stream)}function isWritable(stream){if(typeof(stream===null||stream===void 0\?void 0:stream.writable)!==\"boolean\")return null;if(isDestroyed(stream))return!1;return isWritableNodeStream(stream)&&stream.writable&&!isWritableEnded(stream)}function isFinished(stream,opts){if(!isNodeStream(stream))return null;if(isDestroyed(stream))return!0;if((opts===null||opts===void 0\?void 0:opts.readable)!==!1&&isReadable(stream))return!1;if((opts===null||opts===void 0\?void 0:opts.writable)!==!1&&isWritable(stream))return!1;return!0}function isWritableErrored(stream){var _stream$_writableStat,_stream$_writableStat2;if(!isNodeStream(stream))return null;if(stream.writableErrored)return stream.writableErrored;return(_stream$_writableStat=(_stream$_writableStat2=stream._writableState)===null||_stream$_writableStat2===void 0\?void 0:_stream$_writableStat2.errored)!==null&&_stream$_writableStat!==void 0\?_stream$_writableStat:null}function isReadableErrored(stream){var _stream$_readableStat,_stream$_readableStat2;if(!isNodeStream(stream))return null;if(stream.readableErrored)return stream.readableErrored;return(_stream$_readableStat=(_stream$_readableStat2=stream._readableState)===null||_stream$_readableStat2===void 0\?void 0:_stream$_readableStat2.errored)!==null&&_stream$_readableStat!==void 0\?_stream$_readableStat:null}function isClosed(stream){if(!isNodeStream(stream))return null;if(typeof stream.closed===\"boolean\")return stream.closed;const{_writableState:wState,_readableState:rState}=stream;if(typeof(wState===null||wState===void 0\?void 0:wState.closed)===\"boolean\"||typeof(rState===null||rState===void 0\?void 0:rState.closed)===\"boolean\")return(wState===null||wState===void 0\?void 0:wState.closed)||(rState===null||rState===void 0\?void 0:rState.closed);if(typeof stream._closed===\"boolean\"&&isOutgoingMessage(stream))return stream._closed;return null}function isOutgoingMessage(stream){return typeof stream._closed===\"boolean\"&&typeof stream._defaultKeepAlive===\"boolean\"&&typeof stream._removedConnection===\"boolean\"&&typeof stream._removedContLen===\"boolean\"}function isServerResponse(stream){return typeof stream._sent100===\"boolean\"&&isOutgoingMessage(stream)}function isServerRequest(stream){var _stream$req;return typeof stream._consuming===\"boolean\"&&typeof stream._dumped===\"boolean\"&&((_stream$req=stream.req)===null||_stream$req===void 0\?void 0:_stream$req.upgradeOrConnect)===void 0}function willEmitClose(stream){if(!isNodeStream(stream))return null;const{_writableState:wState,_readableState:rState}=stream,state=wState||rState;return!state&&isServerResponse(stream)||!!(state&&state.autoDestroy&&state.emitClose&&state.closed===!1)}function isDisturbed(stream){var _stream$kIsDisturbed;return!!(stream&&((_stream$kIsDisturbed=stream[kIsDisturbed])!==null&&_stream$kIsDisturbed!==void 0\?_stream$kIsDisturbed:stream.readableDidRead||stream.readableAborted))}function isErrored(stream){var _ref,_ref2,_ref3,_ref4,_ref5,_stream$kIsErrored,_stream$_readableStat3,_stream$_writableStat3,_stream$_readableStat4,_stream$_writableStat4;return!!(stream&&((_ref=(_ref2=(_ref3=(_ref4=(_ref5=(_stream$kIsErrored=stream[kIsErrored])!==null&&_stream$kIsErrored!==void 0\?_stream$kIsErrored:stream.readableErrored)!==null&&_ref5!==void 0\?_ref5:stream.writableErrored)!==null&&_ref4!==void 0\?_ref4:(_stream$_readableStat3=stream._readableState)===null||_stream$_readableStat3===void 0\?void 0:_stream$_readableStat3.errorEmitted)!==null&&_ref3!==void 0\?_ref3:(_stream$_writableStat3=stream._writableState)===null||_stream$_writableStat3===void 0\?void 0:_stream$_writableStat3.errorEmitted)!==null&&_ref2!==void 0\?_ref2:(_stream$_readableStat4=stream._readableState)===null||_stream$_readableStat4===void 0\?void 0:_stream$_readableStat4.errored)!==null&&_ref!==void 0\?_ref:(_stream$_writableStat4=stream._writableState)===null||_stream$_writableStat4===void 0\?void 0:_stream$_writableStat4.errored))}module.exports={kDestroyed,isDisturbed,kIsDisturbed,isErrored,kIsErrored,isReadable,kIsReadable,isClosed,isDestroyed,isDuplexNodeStream,isFinished,isIterable,isReadableNodeStream,isReadableEnded,isReadableFinished,isReadableErrored,isNodeStream,isWritable,isWritableNodeStream,isWritableEnded,isWritableFinished,isWritableErrored,isServerRequest,isServerResponse,willEmitClose}}}),require_end_of_stream=__commonJS({\"node_modules/readable-stream/lib/internal/streams/end-of-stream.js\"(exports2,module){var{AbortError:AbortError2,codes}=require_errors(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_STREAM_PREMATURE_CLOSE}=codes,{once}=require_util(),{validateAbortSignal,validateFunction,validateObject:validateObject2}=require_validators(),{Promise:Promise2}=require_primordials(),{isClosed,isReadable,isReadableNodeStream,isReadableFinished,isReadableErrored,isWritable,isWritableNodeStream,isWritableFinished,isWritableErrored,isNodeStream,willEmitClose:_willEmitClose}=require_utils();function isRequest(stream){return stream.setHeader&&typeof stream.abort===\"function\"}var nop=()=>{};function eos(stream,options,callback){var _options$readable,_options$writable;if(arguments.length===2)callback=options,options={};else if(options==null)options={};else validateObject2(options,\"options\");validateFunction(callback,\"callback\"),validateAbortSignal(options.signal,\"options.signal\"),callback=once(callback);const readable=(_options$readable=options.readable)!==null&&_options$readable!==void 0\?_options$readable:isReadableNodeStream(stream),writable=(_options$writable=options.writable)!==null&&_options$writable!==void 0\?_options$writable:isWritableNodeStream(stream);if(!isNodeStream(stream))throw new ERR_INVALID_ARG_TYPE2(\"stream\",\"Stream\",stream);const{_writableState:wState,_readableState:rState}=stream,onlegacyfinish=()=>{if(!stream.writable)onfinish()};let willEmitClose=_willEmitClose(stream)&&isReadableNodeStream(stream)===readable&&isWritableNodeStream(stream)===writable,writableFinished=isWritableFinished(stream,!1);const onfinish=()=>{if(writableFinished=!0,stream.destroyed)willEmitClose=!1;if(willEmitClose&&(!stream.readable||readable))return;if(!readable||readableFinished)callback.call(stream)};let readableFinished=isReadableFinished(stream,!1);const onend=()=>{if(readableFinished=!0,stream.destroyed)willEmitClose=!1;if(willEmitClose&&(!stream.writable||writable))return;if(!writable||writableFinished)callback.call(stream)},onerror=(err)=>{callback.call(stream,err)};let closed=isClosed(stream);const onclose=()=>{closed=!0;const errored=isWritableErrored(stream)||isReadableErrored(stream);if(errored&&typeof errored!==\"boolean\")return callback.call(stream,errored);if(readable&&!readableFinished&&isReadableNodeStream(stream,!0)){if(!isReadableFinished(stream,!1))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}if(writable&&!writableFinished){if(!isWritableFinished(stream,!1))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}callback.call(stream)},onrequest=()=>{stream.req.on(\"finish\",onfinish)};if(isRequest(stream)){if(stream.on(\"complete\",onfinish),!willEmitClose)stream.on(\"abort\",onclose);if(stream.req)onrequest();else stream.on(\"request\",onrequest)}else if(writable&&!wState)stream.on(\"end\",onlegacyfinish),stream.on(\"close\",onlegacyfinish);if(!willEmitClose&&typeof stream.aborted===\"boolean\")stream.on(\"aborted\",onclose);if(stream.on(\"end\",onend),stream.on(\"finish\",onfinish),options.error!==!1)stream.on(\"error\",onerror);if(stream.on(\"close\",onclose),closed)runOnNextTick(onclose);else if(wState!==null&&wState!==void 0&&wState.errorEmitted||rState!==null&&rState!==void 0&&rState.errorEmitted){if(!willEmitClose)runOnNextTick(onclose)}else if(!readable&&(!willEmitClose||isReadable(stream))&&(writableFinished||isWritable(stream)===!1))runOnNextTick(onclose);else if(!writable&&(!willEmitClose||isWritable(stream))&&(readableFinished||isReadable(stream)===!1))runOnNextTick(onclose);else if(rState&&stream.req&&stream.aborted)runOnNextTick(onclose);const cleanup=()=>{if(callback=nop,stream.removeListener(\"aborted\",onclose),stream.removeListener(\"complete\",onfinish),stream.removeListener(\"abort\",onclose),stream.removeListener(\"request\",onrequest),stream.req)stream.req.removeListener(\"finish\",onfinish);stream.removeListener(\"end\",onlegacyfinish),stream.removeListener(\"close\",onlegacyfinish),stream.removeListener(\"finish\",onfinish),stream.removeListener(\"end\",onend),stream.removeListener(\"error\",onerror),stream.removeListener(\"close\",onclose)};if(options.signal&&!closed){const abort=()=>{const endCallback=callback;cleanup(),endCallback.call(stream,new AbortError2(void 0,{cause:options.signal.reason}))};if(options.signal.aborted)runOnNextTick(abort);else{const originalCallback=callback;callback=once((...args)=>{options.signal.removeEventListener(\"abort\",abort),originalCallback.apply(stream,args)}),options.signal.addEventListener(\"abort\",abort)}}return cleanup}function finished2(stream,opts){return new Promise2((resolve,reject)=>{eos(stream,opts,(err)=>{if(err)reject(err);else resolve()})})}module.exports=eos,module.exports.finished=finished2}}),require_operators=__commonJS({\"node_modules/readable-stream/lib/internal/streams/operators.js\"(exports2,module){var{codes:{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_MISSING_ARGS,ERR_OUT_OF_RANGE},AbortError:AbortError2}=require_errors(),{validateAbortSignal,validateInteger,validateObject:validateObject2}=require_validators(),kWeakHandler=require_primordials().Symbol(\"kWeak\"),{finished:finished2}=require_end_of_stream(),{ArrayPrototypePush,MathFloor,Number:Number2,NumberIsNaN,Promise:Promise2,PromiseReject,PromisePrototypeCatch,Symbol:Symbol2}=require_primordials(),kEmpty=Symbol2(\"kEmpty\"),kEof=Symbol2(\"kEof\");function map(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");let concurrency=1;if((options===null||options===void 0\?void 0:options.concurrency)!=null)concurrency=MathFloor(options.concurrency);return validateInteger(concurrency,\"concurrency\",1),async function*map2(){var _options$signal,_options$signal2;const ac=new AbortController,stream=this,queue=[],signal=ac.signal,signalOpt={signal},abort=()=>ac.abort();if(options!==null&&options!==void 0&&(_options$signal=options.signal)!==null&&_options$signal!==void 0&&_options$signal.aborted)abort();options===null||options===void 0||(_options$signal2=options.signal)===null||_options$signal2===void 0||_options$signal2.addEventListener(\"abort\",abort);let next,resume,done=!1;function onDone(){done=!0}async function pump(){try{for await(let val of stream){var _val;if(done)return;if(signal.aborted)throw new AbortError2;try{val=fn(val,signalOpt)}catch(err){val=PromiseReject(err)}if(val===kEmpty)continue;if(typeof((_val=val)===null||_val===void 0\?void 0:_val.catch)===\"function\")val.catch(onDone);if(queue.push(val),next)next(),next=null;if(!done&&queue.length&&queue.length>=concurrency)await new Promise2((resolve)=>{resume=resolve})}queue.push(kEof)}catch(err){const val=PromiseReject(err);PromisePrototypeCatch(val,onDone),queue.push(val)}finally{var _options$signal3;if(done=!0,next)next(),next=null;options===null||options===void 0||(_options$signal3=options.signal)===null||_options$signal3===void 0||_options$signal3.removeEventListener(\"abort\",abort)}}pump();try{while(!0){while(queue.length>0){const val=await queue[0];if(val===kEof)return;if(signal.aborted)throw new AbortError2;if(val!==kEmpty)yield val;if(queue.shift(),resume)resume(),resume=null}await new Promise2((resolve)=>{next=resolve})}}finally{if(ac.abort(),done=!0,resume)resume(),resume=null}}.call(this)}function asIndexedPairs(options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return async function*asIndexedPairs2(){let index=0;for await(let val of this){var _options$signal4;if(options!==null&&options!==void 0&&(_options$signal4=options.signal)!==null&&_options$signal4!==void 0&&_options$signal4.aborted)throw new AbortError2({cause:options.signal.reason});yield[index++,val]}}.call(this)}async function some(fn,options=void 0){for await(let unused of filter.call(this,fn,options))return!0;return!1}async function every(fn,options=void 0){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);return!await some.call(this,async(...args)=>{return!await fn(...args)},options)}async function find(fn,options){for await(let result of filter.call(this,fn,options))return result;return}async function forEach(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);async function forEachFn(value,options2){return await fn(value,options2),kEmpty}for await(let unused of map.call(this,forEachFn,options));}function filter(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);async function filterFn(value,options2){if(await fn(value,options2))return value;return kEmpty}return map.call(this,filterFn,options)}var ReduceAwareErrMissingArgs=class extends ERR_MISSING_ARGS{constructor(){super(\"reduce\");this.message=\"Reduce of an empty stream requires an initial value\"}};async function reduce(reducer,initialValue,options){var _options$signal5;if(typeof reducer!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"reducer\",[\"Function\",\"AsyncFunction\"],reducer);if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");let hasInitialValue=arguments.length>1;if(options!==null&&options!==void 0&&(_options$signal5=options.signal)!==null&&_options$signal5!==void 0&&_options$signal5.aborted){const err=new AbortError2(void 0,{cause:options.signal.reason});throw this.once(\"error\",()=>{}),await finished2(this.destroy(err)),err}const ac=new AbortController,signal=ac.signal;if(options!==null&&options!==void 0&&options.signal){const opts={once:!0,[kWeakHandler]:this};options.signal.addEventListener(\"abort\",()=>ac.abort(),opts)}let gotAnyItemFromStream=!1;try{for await(let value of this){var _options$signal6;if(gotAnyItemFromStream=!0,options!==null&&options!==void 0&&(_options$signal6=options.signal)!==null&&_options$signal6!==void 0&&_options$signal6.aborted)throw new AbortError2;if(!hasInitialValue)initialValue=value,hasInitialValue=!0;else initialValue=await reducer(initialValue,value,{signal})}if(!gotAnyItemFromStream&&!hasInitialValue)throw new ReduceAwareErrMissingArgs}finally{ac.abort()}return initialValue}async function toArray(options){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");const result=[];for await(let val of this){var _options$signal7;if(options!==null&&options!==void 0&&(_options$signal7=options.signal)!==null&&_options$signal7!==void 0&&_options$signal7.aborted)throw new AbortError2(void 0,{cause:options.signal.reason});ArrayPrototypePush(result,val)}return result}function flatMap(fn,options){const values=map.call(this,fn,options);return async function*flatMap2(){for await(let val of values)yield*val}.call(this)}function toIntegerOrInfinity(number){if(number=Number2(number),NumberIsNaN(number))return 0;if(number<0)throw new ERR_OUT_OF_RANGE(\"number\",\">= 0\",number);return number}function drop(number,options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return number=toIntegerOrInfinity(number),async function*drop2(){var _options$signal8;if(options!==null&&options!==void 0&&(_options$signal8=options.signal)!==null&&_options$signal8!==void 0&&_options$signal8.aborted)throw new AbortError2;for await(let val of this){var _options$signal9;if(options!==null&&options!==void 0&&(_options$signal9=options.signal)!==null&&_options$signal9!==void 0&&_options$signal9.aborted)throw new AbortError2;if(number--<=0)yield val}}.call(this)}function take(number,options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return number=toIntegerOrInfinity(number),async function*take2(){var _options$signal10;if(options!==null&&options!==void 0&&(_options$signal10=options.signal)!==null&&_options$signal10!==void 0&&_options$signal10.aborted)throw new AbortError2;for await(let val of this){var _options$signal11;if(options!==null&&options!==void 0&&(_options$signal11=options.signal)!==null&&_options$signal11!==void 0&&_options$signal11.aborted)throw new AbortError2;if(number-- >0)yield val;else return}}.call(this)}module.exports.streamReturningOperators={asIndexedPairs,drop,filter,flatMap,map,take},module.exports.promiseReturningOperators={every,forEach,reduce,toArray,some,find}}}),require_destroy=__commonJS({\"node_modules/readable-stream/lib/internal/streams/destroy.js\"(exports2,module){var{aggregateTwoErrors,codes:{ERR_MULTIPLE_CALLBACK},AbortError:AbortError2}=require_errors(),{Symbol:Symbol2}=require_primordials(),{kDestroyed,isDestroyed,isFinished,isServerRequest}=require_utils(),kDestroy=\"#kDestroy\",kConstruct=\"#kConstruct\";function checkError(err,w,r){if(err){if(err.stack,w&&!w.errored)w.errored=err;if(r&&!r.errored)r.errored=err}}function destroy2(err,cb){const r=this._readableState,w=this._writableState,s=w||r;if(w&&w.destroyed||r&&r.destroyed){if(typeof cb===\"function\")cb();return this}if(checkError(err,w,r),w)w.destroyed=!0;if(r)r.destroyed=!0;if(!s.constructed)this.once(kDestroy,(er)=>{_destroy(this,aggregateTwoErrors(er,err),cb)});else _destroy(this,err,cb);return this}function _destroy(self,err,cb){let called=!1;function onDestroy(err2){if(called)return;called=!0;const{_readableState:r,_writableState:w}=self;if(checkError(err2,w,r),w)w.closed=!0;if(r)r.closed=!0;if(typeof cb===\"function\")cb(err2);if(err2)runOnNextTick(emitErrorCloseNT,self,err2);else runOnNextTick(emitCloseNT,self)}try{self._destroy(err||null,onDestroy)}catch(err2){onDestroy(err2)}}function emitErrorCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){const{_readableState:r,_writableState:w}=self;if(w)w.closeEmitted=!0;if(r)r.closeEmitted=!0;if(w&&w.emitClose||r&&r.emitClose)self.emit(\"close\")}function emitErrorNT(self,err){const r=self\?._readableState,w=self\?._writableState;if(w\?.errorEmitted||r\?.errorEmitted)return;if(w)w.errorEmitted=!0;if(r)r.errorEmitted=!0;self\?.emit\?.(\"error\",err)}function undestroy(){const r=this._readableState,w=this._writableState;if(r)r.constructed=!0,r.closed=!1,r.closeEmitted=!1,r.destroyed=!1,r.errored=null,r.errorEmitted=!1,r.reading=!1,r.ended=r.readable===!1,r.endEmitted=r.readable===!1;if(w)w.constructed=!0,w.destroyed=!1,w.closed=!1,w.closeEmitted=!1,w.errored=null,w.errorEmitted=!1,w.finalCalled=!1,w.prefinished=!1,w.ended=w.writable===!1,w.ending=w.writable===!1,w.finished=w.writable===!1}function errorOrDestroy2(stream,err,sync){const r=stream\?._readableState,w=stream\?._writableState;if(w&&w.destroyed||r&&r.destroyed)return this;if(r&&r.autoDestroy||w&&w.autoDestroy)stream.destroy(err);else if(err){if(Error.captureStackTrace(err),w&&!w.errored)w.errored=err;if(r&&!r.errored)r.errored=err;if(sync)runOnNextTick(emitErrorNT,stream,err);else emitErrorNT(stream,err)}}function construct(stream,cb){if(typeof stream._construct!==\"function\")return;const{_readableState:r,_writableState:w}=stream;if(r)r.constructed=!1;if(w)w.constructed=!1;if(stream.once(kConstruct,cb),stream.listenerCount(kConstruct)>1)return;runOnNextTick(constructNT,stream)}function constructNT(stream){let called=!1;function onConstruct(err){if(called){errorOrDestroy2(stream,err!==null&&err!==void 0\?err:new ERR_MULTIPLE_CALLBACK);return}called=!0;const{_readableState:r,_writableState:w}=stream,s=w||r;if(r)r.constructed=!0;if(w)w.constructed=!0;if(s.destroyed)stream.emit(kDestroy,err);else if(err)errorOrDestroy2(stream,err,!0);else runOnNextTick(emitConstructNT,stream)}try{stream._construct(onConstruct)}catch(err){onConstruct(err)}}function emitConstructNT(stream){stream.emit(kConstruct)}function isRequest(stream){return stream&&stream.setHeader&&typeof stream.abort===\"function\"}function emitCloseLegacy(stream){stream.emit(\"close\")}function emitErrorCloseLegacy(stream,err){stream.emit(\"error\",err),runOnNextTick(emitCloseLegacy,stream)}function destroyer(stream,err){if(!stream||isDestroyed(stream))return;if(!err&&!isFinished(stream))err=new AbortError2;if(isServerRequest(stream))stream.socket=null,stream.destroy(err);else if(isRequest(stream))stream.abort();else if(isRequest(stream.req))stream.req.abort();else if(typeof stream.destroy===\"function\")stream.destroy(err);else if(typeof stream.close===\"function\")stream.close();else if(err)runOnNextTick(emitErrorCloseLegacy,stream);else runOnNextTick(emitCloseLegacy,stream);if(!stream.destroyed)stream[kDestroyed]=!0}module.exports={construct,destroyer,destroy:destroy2,undestroy,errorOrDestroy:errorOrDestroy2}}}),require_legacy=__commonJS({\"node_modules/readable-stream/lib/internal/streams/legacy.js\"(exports2,module){var{ArrayIsArray:ArrayIsArray2,ObjectSetPrototypeOf}=require_primordials();function Stream(options){if(!(this instanceof Stream))return new Stream(options);EE.call(this,options)}Stream.prototype={},ObjectSetPrototypeOf(Stream.prototype,EE.prototype),ObjectSetPrototypeOf(Stream,EE),Stream.prototype.pipe=function(dest,options){const source=this;function ondata(chunk){if(dest.writable&&dest.write(chunk)===!1&&source.pause)source.pause()}source.on(\"data\",ondata);function ondrain(){if(source.readable&&source.resume)source.resume()}if(dest.on(\"drain\",ondrain),!dest._isStdio&&(!options||options.end!==!1))source.on(\"end\",onend),source.on(\"close\",onclose);let didOnEnd=!1;function onend(){if(didOnEnd)return;didOnEnd=!0,dest.end()}function onclose(){if(didOnEnd)return;if(didOnEnd=!0,typeof dest.destroy===\"function\")dest.destroy()}function onerror(er){if(cleanup(),EE.listenerCount(this,\"error\")===0)this.emit(\"error\",er)}prependListener(source,\"error\",onerror),prependListener(dest,\"error\",onerror);function cleanup(){source.removeListener(\"data\",ondata),dest.removeListener(\"drain\",ondrain),source.removeListener(\"end\",onend),source.removeListener(\"close\",onclose),source.removeListener(\"error\",onerror),dest.removeListener(\"error\",onerror),source.removeListener(\"end\",cleanup),source.removeListener(\"close\",cleanup),dest.removeListener(\"close\",cleanup)}return source.on(\"end\",cleanup),source.on(\"close\",cleanup),dest.on(\"close\",cleanup),dest.emit(\"pipe\",source),dest};function prependListener(emitter,event,fn){if(typeof emitter.prependListener===\"function\")return emitter.prependListener(event,fn);if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(ArrayIsArray2(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}module.exports={Stream,prependListener}}}),require_add_abort_signal=__commonJS({\"node_modules/readable-stream/lib/internal/streams/add-abort-signal.js\"(exports2,module){var{AbortError:AbortError2,codes}=require_errors(),eos=require_end_of_stream(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2}=codes,validateAbortSignal=(signal,name)=>{if(typeof signal!==\"object\"||!(\"aborted\"in signal))throw new ERR_INVALID_ARG_TYPE2(name,\"AbortSignal\",signal)};function isNodeStream(obj){return!!(obj&&typeof obj.pipe===\"function\")}module.exports.addAbortSignal=function addAbortSignal(signal,stream){if(validateAbortSignal(signal,\"signal\"),!isNodeStream(stream))throw new ERR_INVALID_ARG_TYPE2(\"stream\",\"stream.Stream\",stream);return module.exports.addAbortSignalNoValidate(signal,stream)},module.exports.addAbortSignalNoValidate=function(signal,stream){if(typeof signal!==\"object\"||!(\"aborted\"in signal))return stream;const onAbort=()=>{stream.destroy(new AbortError2(void 0,{cause:signal.reason}))};if(signal.aborted)onAbort();else signal.addEventListener(\"abort\",onAbort),eos(stream,()=>signal.removeEventListener(\"abort\",onAbort));return stream}}}),require_state=__commonJS({\"node_modules/readable-stream/lib/internal/streams/state.js\"(exports2,module){var{MathFloor,NumberIsInteger}=require_primordials(),{ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2}=require_errors().codes;function highWaterMarkFrom(options,isDuplex,duplexKey){return options.highWaterMark!=null\?options.highWaterMark:isDuplex\?options[duplexKey]:null}function getDefaultHighWaterMark(objectMode){return objectMode\?16:16384}function getHighWaterMark(state,options,duplexKey,isDuplex){const hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(hwm!=null){if(!NumberIsInteger(hwm)||hwm<0){const name=isDuplex\?`options.${duplexKey}`:\"options.highWaterMark\";throw new ERR_INVALID_ARG_VALUE2(name,hwm)}return MathFloor(hwm)}return getDefaultHighWaterMark(state.objectMode)}module.exports={getHighWaterMark,getDefaultHighWaterMark}}}),require_from=__commonJS({\"node_modules/readable-stream/lib/internal/streams/from.js\"(exports2,module){var{PromisePrototypeThen,SymbolAsyncIterator,SymbolIterator}=require_primordials(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_STREAM_NULL_VALUES}=require_errors().codes;function from(Readable,iterable,opts){let iterator;if(typeof iterable===\"string\"||iterable instanceof Buffer)return new Readable({objectMode:!0,...opts,read(){this.push(iterable),this.push(null)}});let isAsync;if(iterable&&iterable[SymbolAsyncIterator])isAsync=!0,iterator=iterable[SymbolAsyncIterator]();else if(iterable&&iterable[SymbolIterator])isAsync=!1,iterator=iterable[SymbolIterator]();else throw new ERR_INVALID_ARG_TYPE2(\"iterable\",[\"Iterable\"],iterable);const readable=new Readable({objectMode:!0,highWaterMark:1,...opts});let reading=!1;readable._read=function(){if(!reading)reading=!0,next()},readable._destroy=function(error,cb){PromisePrototypeThen(close(error),()=>runOnNextTick(cb,error),(e)=>runOnNextTick(cb,e||error))};async function close(error){const hadError=error!==void 0&&error!==null,hasThrow=typeof iterator.throw===\"function\";if(hadError&&hasThrow){const{value,done}=await iterator.throw(error);if(await value,done)return}if(typeof iterator.return===\"function\"){const{value}=await iterator.return();await value}}async function next(){for(;;){try{const{value,done}=isAsync\?await iterator.next():iterator.next();if(done)readable.push(null);else{const res=value&&typeof value.then===\"function\"\?await value:value;if(res===null)throw reading=!1,new ERR_STREAM_NULL_VALUES;else if(readable.push(res))continue;else reading=!1}}catch(err){readable.destroy(err)}break}}return readable}module.exports=from}}),_ReadableFromWeb,_ReadableFromWebForUndici,require_readable=__commonJS({\"node_modules/readable-stream/lib/internal/streams/readable.js\"(exports2,module){var{ArrayPrototypeIndexOf,NumberIsInteger,NumberIsNaN,NumberParseInt,ObjectDefineProperties,ObjectKeys,ObjectSetPrototypeOf,Promise:Promise2,SafeSet,SymbolAsyncIterator,Symbol:Symbol2}=require_primordials(),ReadableState=globalThis[globalThis.Symbol.for('Bun.lazy')](\"bun:stream\").ReadableState,{Stream,prependListener}=require_legacy();function Readable(options){if(!(this instanceof Readable))return new Readable(options);const isDuplex=this instanceof require_duplex();if(this._readableState=new ReadableState(options,this,isDuplex),options){const{read,destroy:destroy2,construct,signal}=options;if(typeof read===\"function\")this._read=read;if(typeof destroy2===\"function\")this._destroy=destroy2;if(typeof construct===\"function\")this._construct=construct;if(signal&&!isDuplex)addAbortSignal(signal,this)}Stream.call(this,options),destroyImpl.construct(this,()=>{if(this._readableState.needReadable)maybeReadMore(this,this._readableState)})}Readable.prototype={},ObjectSetPrototypeOf(Readable.prototype,Stream.prototype),ObjectSetPrototypeOf(Readable,Stream),Readable.prototype.on=function(ev,fn){const res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;if(ev===\"data\"){if(state.readableListening=this.listenerCount(\"readable\")>0,state.flowing!==!1)this.resume()}else if(ev===\"readable\"){if(!state.endEmitted&&!state.readableListening){if(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,state.length)emitReadable(this,state);else if(!state.reading)runOnNextTick(nReadingNextTick,this)}else if(state.endEmitted);}return res};class ReadableFromWeb extends Readable{#reader;#closed;#pendingChunks;#stream;constructor(options,stream){const{objectMode,highWaterMark,encoding,signal}=options;super({objectMode,highWaterMark,encoding,signal});this.#pendingChunks=[],this.#reader=void 0,this.#stream=stream,this.#closed=!1}#drainPending(){var pendingChunks=this.#pendingChunks,pendingChunksI=0,pendingChunksCount=pendingChunks.length;for(;pendingChunksI0)this.#pendingChunks=[];return!1}#handleDone(reader){reader.releaseLock(),this.#reader=void 0,this.#closed=!0,this.push(null);return}async _read(){var stream=this.#stream,reader=this.#reader;if(stream)reader=this.#reader=stream.getReader(),this.#stream=void 0;else if(this.#drainPending())return;var deferredError;try{do{var done=!1,value;const firstResult=reader.readMany();if(@isPromise(firstResult)){if({done,value}=await firstResult,this.#closed){this.#pendingChunks.push(...value);return}}else({done,value}=firstResult);if(done){this.#handleDone(reader);return}if(!this.push(value[0])){this.#pendingChunks=value.slice(1);return}for(let i=1,count=value.length;i{this.#closed=!0,callback(error)});return}try{callback(error)}catch(error2){globalThis.reportError(error2)}}}_ReadableFromWebForUndici=ReadableFromWeb;function newStreamReadableFromReadableStream(readableStream,options={}){if(!isReadableStream(readableStream))throw new ERR_INVALID_ARG_TYPE2(\"readableStream\",\"ReadableStream\",readableStream);validateObject2(options,\"options\");const{highWaterMark,encoding,objectMode=!1,signal}=options;if(encoding!==void 0&&!Buffer.isEncoding(encoding))throw new ERR_INVALID_ARG_VALUE(encoding,\"options.encoding\");return validateBoolean(objectMode,\"options.objectMode\"),getNativeReadableStream(Readable,readableStream,options)||new ReadableFromWeb({highWaterMark,encoding,objectMode,signal},readableStream)}module.exports=Readable,_ReadableFromWeb=newStreamReadableFromReadableStream;var{addAbortSignal}=require_add_abort_signal(),eos=require_end_of_stream();const{maybeReadMore:_maybeReadMore,resume,emitReadable:_emitReadable,onEofChunk}=globalThis[globalThis.Symbol.for('Bun.lazy')](\"bun:stream\");function maybeReadMore(stream,state){process.nextTick(_maybeReadMore,stream,state)}function emitReadable(stream,state){_emitReadable(stream,state)}var destroyImpl=require_destroy(),{aggregateTwoErrors,codes:{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_METHOD_NOT_IMPLEMENTED,ERR_OUT_OF_RANGE,ERR_STREAM_PUSH_AFTER_EOF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT}}=require_errors(),{validateObject:validateObject2}=require_validators(),from=require_from(),nop=()=>{},{errorOrDestroy:errorOrDestroy2}=destroyImpl;Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype[EE.captureRejectionSymbol]=function(err){this.destroy(err)},Readable.prototype.push=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,!0)};function readableAddChunk(stream,chunk,encoding,addToFront){const state=stream._readableState;let err;if(!state.objectMode){if(typeof chunk===\"string\"){if(encoding=encoding||state.defaultEncoding,state.encoding!==encoding)if(addToFront&&state.encoding)chunk=Buffer.from(chunk,encoding).toString(state.encoding);else chunk=Buffer.from(chunk,encoding),encoding=\"\"}else if(chunk instanceof Buffer)encoding=\"\";else if(Stream._isUint8Array(chunk)){if(addToFront||!state.decoder)chunk=Stream._uint8ArrayToBuffer(chunk);encoding=\"\"}else if(chunk!=null)err=new ERR_INVALID_ARG_TYPE2(\"chunk\",[\"string\",\"Buffer\",\"Uint8Array\"],chunk)}if(err)errorOrDestroy2(stream,err);else if(chunk===null)state.reading=!1,onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(addToFront)if(state.endEmitted)errorOrDestroy2(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);else if(state.destroyed||state.errored)return!1;else addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy2(stream,new ERR_STREAM_PUSH_AFTER_EOF);else if(state.destroyed||state.errored)return!1;else if(state.reading=!1,state.decoder&&!encoding)if(chunk=state.decoder.write(chunk),state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,!1);else maybeReadMore(stream,state);else addChunk(stream,state,chunk,!1);else if(!addToFront)state.reading=!1,maybeReadMore(stream,state);return!state.ended&&(state.length0){if(state.multiAwaitDrain)state.awaitDrainWriters.clear();else state.awaitDrainWriters=null;state.dataEmitted=!0,stream.emit(\"data\",chunk)}else{if(state.length+=state.objectMode\?1:chunk.length,addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream,state)}maybeReadMore(stream,state)}Readable.prototype.isPaused=function(){const state=this._readableState;return state.paused===!0||state.flowing===!1},Readable.prototype.setEncoding=function(enc){const decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;const buffer=this._readableState.buffer;let content=\"\";for(let i=buffer.length;i>0;i--)content+=decoder.write(buffer.shift());if(content!==\"\")buffer.push(content);return this._readableState.length=content.length,this};var MAX_HWM=1073741824;function computeNewHighWaterMark(n){if(n>MAX_HWM)throw new ERR_OUT_OF_RANGE(\"size\",\"<= 1GiB\",n);else n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++;return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(NumberIsNaN(n)){if(state.flowing&&state.length)return state.buffer.first().length;return state.length}if(n<=state.length)return n;return state.ended\?state.length:0}Readable.prototype.read=function(n){if(!NumberIsInteger(n))n=NumberParseInt(n,10);const state=this._readableState,nOrig=n;if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n!==0)state.emittedReadable=!1;if(n===0&&state.needReadable&&((state.highWaterMark!==0\?state.length>=state.highWaterMark:state.length>0)||state.ended)){if(state.length===0&&state.ended)endReadable(this);else emitReadable(this,state);return null}if(n=howMuchToRead(n,state),n===0&&state.ended){if(state.length===0)endReadable(this);return null}let doRead=state.needReadable;if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null)state.needReadable=state.length<=state.highWaterMark,n=0;else if(state.length-=n,state.multiAwaitDrain)state.awaitDrainWriters.clear();else state.awaitDrainWriters=null;if(state.length===0){if(!state.ended)state.needReadable=!0;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null&&!state.errorEmitted&&!state.closeEmitted)state.dataEmitted=!0,this.emit(\"data\",ret);return ret},Readable.prototype._read=function(n){throw new ERR_METHOD_NOT_IMPLEMENTED(\"_read()\")},Readable.prototype.pipe=function(dest,pipeOpts){const src=this,state=this._readableState;if(state.pipes.length===1){if(!state.multiAwaitDrain)state.multiAwaitDrain=!0,state.awaitDrainWriters=new SafeSet(state.awaitDrainWriters\?[state.awaitDrainWriters]:[])}state.pipes.push(dest);const endFn=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr\?onend:unpipe;if(state.endEmitted)runOnNextTick(endFn);else src.once(\"end\",endFn);dest.on(\"unpipe\",onunpipe);function onunpipe(readable,unpipeInfo){if(readable===src){if(unpipeInfo&&unpipeInfo.hasUnpiped===!1)unpipeInfo.hasUnpiped=!0,cleanup()}}function onend(){dest.end()}let ondrain,cleanedUp=!1;function cleanup(){if(dest.removeListener(\"close\",onclose),dest.removeListener(\"finish\",onfinish),ondrain)dest.removeListener(\"drain\",ondrain);if(dest.removeListener(\"error\",onerror),dest.removeListener(\"unpipe\",onunpipe),src.removeListener(\"end\",onend),src.removeListener(\"end\",unpipe),src.removeListener(\"data\",ondata),cleanedUp=!0,ondrain&&state.awaitDrainWriters&&(!dest._writableState||dest._writableState.needDrain))ondrain()}function pause(){if(!cleanedUp){if(state.pipes.length===1&&state.pipes[0]===dest)state.awaitDrainWriters=dest,state.multiAwaitDrain=!1;else if(state.pipes.length>1&&state.pipes.includes(dest))state.awaitDrainWriters.add(dest);src.pause()}if(!ondrain)ondrain=pipeOnDrain(src,dest),dest.on(\"drain\",ondrain)}src.on(\"data\",ondata);function ondata(chunk){if(dest.write(chunk)===!1)pause()}function onerror(er){if(unpipe(),dest.removeListener(\"error\",onerror),dest.listenerCount(\"error\")===0){const s=dest._writableState||dest._readableState;if(s&&!s.errorEmitted)errorOrDestroy2(dest,er);else dest.emit(\"error\",er)}}prependListener(dest,\"error\",onerror);function onclose(){dest.removeListener(\"finish\",onfinish),unpipe()}dest.once(\"close\",onclose);function onfinish(){dest.removeListener(\"close\",onclose),unpipe()}dest.once(\"finish\",onfinish);function unpipe(){src.unpipe(dest)}if(dest.emit(\"pipe\",src),dest.writableNeedDrain===!0){if(state.flowing)pause()}else if(!state.flowing)src.resume();return dest};function pipeOnDrain(src,dest){return function pipeOnDrainFunctionResult(){const state=src._readableState;if(state.awaitDrainWriters===dest)state.awaitDrainWriters=null;else if(state.multiAwaitDrain)state.awaitDrainWriters.delete(dest);if((!state.awaitDrainWriters||state.awaitDrainWriters.size===0)&&src.listenerCount(\"data\"))src.resume()}}Readable.prototype.unpipe=function(dest){const state=this._readableState,unpipeInfo={hasUnpiped:!1};if(state.pipes.length===0)return this;if(!dest){const dests=state.pipes;state.pipes=[],this.pause();for(let i=0;i0,state.resumeScheduled&&state.paused===!1)state.flowing=!0;else if(self.listenerCount(\"data\")>0)self.resume();else if(!state.readableListening)state.flowing=null}function nReadingNextTick(self){self.read(0)}Readable.prototype.resume=function(){const state=this._readableState;if(!state.flowing)state.flowing=!state.readableListening,resume(this,state);return state.paused=!1,this},Readable.prototype.pause=function(){if(this._readableState.flowing!==!1)this._readableState.flowing=!1,this.emit(\"pause\");return this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){let paused=!1;stream.on(\"data\",(chunk)=>{if(!this.push(chunk)&&stream.pause)paused=!0,stream.pause()}),stream.on(\"end\",()=>{this.push(null)}),stream.on(\"error\",(err)=>{errorOrDestroy2(this,err)}),stream.on(\"close\",()=>{this.destroy()}),stream.on(\"destroy\",()=>{this.destroy()}),this._read=()=>{if(paused&&stream.resume)paused=!1,stream.resume()};const streamKeys=ObjectKeys(stream);for(let j=1;j{error=err\?aggregateTwoErrors(error,err):null,callback(),callback=nop});try{while(!0){const chunk=stream.destroyed\?null:stream.read();if(chunk!==null)yield chunk;else if(error)throw error;else if(error===null)return;else await new Promise2(next)}}catch(err){throw error=aggregateTwoErrors(error,err),error}finally{if((error||(options===null||options===void 0\?void 0:options.destroyOnReturn)!==!1)&&(error===void 0||stream._readableState.autoDestroy))destroyImpl.destroyer(stream,null);else stream.off(\"readable\",next),cleanup()}}ObjectDefineProperties(Readable.prototype,{readable:{get(){const r=this._readableState;return!!r&&r.readable!==!1&&!r.destroyed&&!r.errorEmitted&&!r.endEmitted},set(val){if(this._readableState)this._readableState.readable=!!val}},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(state){if(this._readableState)this._readableState.flowing=state}},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(value){if(!this._readableState)return;this._readableState.destroyed=value}},readableEnded:{enumerable:!1,get(){return this._readableState\?this._readableState.endEmitted:!1}}}),Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;let ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){if(state.decoder)ret=state.buffer.join(\"\");else if(state.buffer.length===1)ret=state.buffer.first();else ret=state.buffer.concat(state.length);state.buffer.clear()}else ret=state.buffer.consume(n,state.decoder);return ret}function endReadable(stream){const state=stream._readableState;if(!state.endEmitted)state.ended=!0,runOnNextTick(endReadableNT,state,stream)}function endReadableNT(state,stream){if(!state.errored&&!state.closeEmitted&&!state.endEmitted&&state.length===0){if(state.endEmitted=!0,stream.emit(\"end\"),stream.writable&&stream.allowHalfOpen===!1)runOnNextTick(endWritableNT,stream);else if(state.autoDestroy){const wState=stream._writableState;if(!wState||wState.autoDestroy&&(wState.finished||wState.writable===!1))stream.destroy()}}}function endWritableNT(stream){if(stream.writable&&!stream.writableEnded&&!stream.destroyed)stream.end()}Readable.from=function(iterable,opts){return from(Readable,iterable,opts)};var webStreamsAdapters={newStreamReadableFromReadableStream,newReadableStreamFromStreamReadable(streamReadable,options={}){if(typeof streamReadable\?._readableState!==\"object\")throw new ERR_INVALID_ARG_TYPE2(\"streamReadable\",\"stream.Readable\",streamReadable);var{isDestroyed,isReadable}=require_utils();if(isDestroyed(streamReadable)||!isReadable(streamReadable)){const readable=new ReadableStream;return readable.cancel(),readable}const{readableObjectMode:objectMode,readableHighWaterMark:highWaterMark}=streamReadable,strategy=((strategy2)=>{if(strategy2)return strategy2;if(objectMode)return new CountQueuingStrategy({highWaterMark});return{highWaterMark}})(options\?.strategy);let controller;function onData(chunk){if(controller.enqueue(chunk),controller.desiredSize<=0)streamReadable.pause()}streamReadable.pause();const cleanup=finished(streamReadable,(error)=>{if(error\?.code===\"ERR_STREAM_PREMATURE_CLOSE\")error=new AbortError(void 0,{cause:error});if(cleanup(),streamReadable.on(\"error\",()=>{}),error)return controller.error(error);controller.close()});return streamReadable.on(\"data\",onData),new ReadableStream({start(c){controller=c},pull(){streamReadable.resume()},cancel(reason){destroy(streamReadable,reason)}},strategy)}};Readable.fromWeb=function(readableStream,options){return webStreamsAdapters.newStreamReadableFromReadableStream(readableStream,options)},Readable.toWeb=function(streamReadable,options){return webStreamsAdapters.newReadableStreamFromStreamReadable(streamReadable,options)},Readable.wrap=function(src,options){var _ref,_src$readableObjectMo;return new Readable({objectMode:(_ref=(_src$readableObjectMo=src.readableObjectMode)!==null&&_src$readableObjectMo!==void 0\?_src$readableObjectMo:src.objectMode)!==null&&_ref!==void 0\?_ref:!0,...options,destroy(err,callback){destroyImpl.destroyer(src,err),callback(err)}}).wrap(src)}}}),require_writable=__commonJS({\"node_modules/readable-stream/lib/internal/streams/writable.js\"(exports2,module){var{ArrayPrototypeSlice,Error:Error2,FunctionPrototypeSymbolHasInstance,ObjectDefineProperty,ObjectDefineProperties,ObjectSetPrototypeOf,StringPrototypeToLowerCase,Symbol:Symbol2,SymbolHasInstance}=require_primordials(),Stream=require_legacy().Stream,destroyImpl=require_destroy(),{addAbortSignal}=require_add_abort_signal(),{getHighWaterMark,getDefaultHighWaterMark}=require_state(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED,ERR_STREAM_ALREADY_FINISHED,ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING}=require_errors().codes,{errorOrDestroy:errorOrDestroy2}=destroyImpl;function Writable2(options={}){const isDuplex=this instanceof require_duplex();if(!isDuplex&&!FunctionPrototypeSymbolHasInstance(Writable2,this))return new Writable2(options);if(this._writableState=new WritableState(options,this,isDuplex),options){if(typeof options.write===\"function\")this._write=options.write;if(typeof options.writev===\"function\")this._writev=options.writev;if(typeof options.destroy===\"function\")this._destroy=options.destroy;if(typeof options.final===\"function\")this._final=options.final;if(typeof options.construct===\"function\")this._construct=options.construct;if(options.signal)addAbortSignal(options.signal,this)}Stream.call(this,options),destroyImpl.construct(this,()=>{const state=this._writableState;if(!state.writing)clearBuffer(this,state);finishMaybe(this,state)})}Writable2.prototype={},ObjectSetPrototypeOf(Writable2.prototype,Stream.prototype),ObjectSetPrototypeOf(Writable2,Stream),module.exports=Writable2;function nop(){}var kOnFinished=Symbol2(\"kOnFinished\");function WritableState(options,stream,isDuplex){if(typeof isDuplex!==\"boolean\")isDuplex=stream instanceof require_duplex();if(this.objectMode=!!(options&&options.objectMode),isDuplex)this.objectMode=this.objectMode||!!(options&&options.writableObjectMode);this.highWaterMark=options\?getHighWaterMark(this,options,\"writableHighWaterMark\",isDuplex):getDefaultHighWaterMark(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const noDecode=!!(options&&options.decodeStrings===!1);this.decodeStrings=!noDecode,this.defaultEncoding=options&&options.defaultEncoding||\"utf8\",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=onwrite.bind(void 0,stream),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,resetBuffer(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!options||options.emitClose!==!1,this.autoDestroy=!options||options.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[kOnFinished]=[]}WritableState.prototype={};function resetBuffer(state){state.buffered=[],state.bufferedIndex=0,state.allBuffers=!0,state.allNoop=!0}WritableState.prototype.getBuffer=function getBuffer(){return ArrayPrototypeSlice(this.buffered,this.bufferedIndex)},ObjectDefineProperty(WritableState.prototype,\"bufferedRequestCount\",{get(){return this.buffered.length-this.bufferedIndex}}),ObjectDefineProperty(Writable2,SymbolHasInstance,{value:function(object){if(FunctionPrototypeSymbolHasInstance(this,object))return!0;if(this!==Writable2)return!1;return object&&object._writableState instanceof WritableState}}),Writable2.prototype.pipe=function(){errorOrDestroy2(this,new ERR_STREAM_CANNOT_PIPE)};function _write(stream,chunk,encoding,cb){const state=stream._writableState;if(typeof encoding===\"function\")cb=encoding,encoding=state.defaultEncoding;else{if(!encoding)encoding=state.defaultEncoding;else if(encoding!==\"buffer\"&&!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);if(typeof cb!==\"function\")cb=nop}if(chunk===null)throw new ERR_STREAM_NULL_VALUES;else if(!state.objectMode)if(typeof chunk===\"string\"){if(state.decodeStrings!==!1)chunk=Buffer.from(chunk,encoding),encoding=\"buffer\"}else if(chunk instanceof Buffer)encoding=\"buffer\";else if(Stream._isUint8Array(chunk))chunk=Stream._uint8ArrayToBuffer(chunk),encoding=\"buffer\";else throw new ERR_INVALID_ARG_TYPE2(\"chunk\",[\"string\",\"Buffer\",\"Uint8Array\"],chunk);let err;if(state.ending)err=new ERR_STREAM_WRITE_AFTER_END;else if(state.destroyed)err=new ERR_STREAM_DESTROYED(\"write\");if(err)return runOnNextTick(cb,err),errorOrDestroy2(stream,err,!0),err;return state.pendingcb++,writeOrBuffer(stream,state,chunk,encoding,cb)}Writable2.prototype.write=function(chunk,encoding,cb){return _write(this,chunk,encoding,cb)===!0},Writable2.prototype.cork=function(){this._writableState.corked++},Writable2.prototype.uncork=function(){const state=this._writableState;if(state.corked){if(state.corked--,!state.writing)clearBuffer(this,state)}},Writable2.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding===\"string\")encoding=StringPrototypeToLowerCase(encoding);if(!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this};function writeOrBuffer(stream,state,chunk,encoding,callback){const len=state.objectMode\?1:chunk.length;state.length+=len;const ret=state.lengthstate.bufferedIndex)clearBuffer(stream,state);if(sync)if(state.afterWriteTickInfo!==null&&state.afterWriteTickInfo.cb===cb)state.afterWriteTickInfo.count++;else state.afterWriteTickInfo={count:1,cb,stream,state},runOnNextTick(afterWriteTick,state.afterWriteTickInfo);else afterWrite(stream,state,1,cb)}}function afterWriteTick({stream,state,count,cb}){return state.afterWriteTickInfo=null,afterWrite(stream,state,count,cb)}function afterWrite(stream,state,count,cb){if(!state.ending&&!stream.destroyed&&state.length===0&&state.needDrain)state.needDrain=!1,stream.emit(\"drain\");while(count-- >0)state.pendingcb--,cb();if(state.destroyed)errorBuffer(state);finishMaybe(stream,state)}function errorBuffer(state){if(state.writing)return;for(let n=state.bufferedIndex;n1&&stream._writev){state.pendingcb-=bufferedLength-1;const callback=state.allNoop\?nop:(err)=>{for(let n=i;n256)buffered.splice(0,i),state.bufferedIndex=0;else state.bufferedIndex=i}state.bufferProcessing=!1}Writable2.prototype._write=function(chunk,encoding,cb){if(this._writev)this._writev([{chunk,encoding}],cb);else throw new ERR_METHOD_NOT_IMPLEMENTED(\"_write()\")},Writable2.prototype._writev=null,Writable2.prototype.end=function(chunk,encoding,cb,native=!1){const state=this._writableState;if(typeof chunk===\"function\")cb=chunk,chunk=null,encoding=null;else if(typeof encoding===\"function\")cb=encoding,encoding=null;let err;if(chunk!==null&&chunk!==void 0){let ret;if(!native)ret=_write(this,chunk,encoding);else ret=this.write(chunk,encoding);if(ret instanceof Error2)err=ret}if(state.corked)state.corked=1,this.uncork();if(err)this.emit(\"error\",err);else if(!state.errored&&!state.ending)state.ending=!0,finishMaybe(this,state,!0),state.ended=!0;else if(state.finished)err=new ERR_STREAM_ALREADY_FINISHED(\"end\");else if(state.destroyed)err=new ERR_STREAM_DESTROYED(\"end\");if(typeof cb===\"function\")if(err||state.finished)runOnNextTick(cb,err);else state[kOnFinished].push(cb);return this};function needFinish(state,tag){var needFinish2=state.ending&&!state.destroyed&&state.constructed&&state.length===0&&!state.errored&&state.buffered.length===0&&!state.finished&&!state.writing&&!state.errorEmitted&&!state.closeEmitted;return needFinish2}function callFinal(stream,state){let called=!1;function onFinish(err){if(called){errorOrDestroy2(stream,err!==null&&err!==void 0\?err:ERR_MULTIPLE_CALLBACK());return}if(called=!0,state.pendingcb--,err){const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i{if(needFinish(state2))finish(stream2,state2);else state2.pendingcb--},stream,state);else if(needFinish(state))state.pendingcb++,finish(stream,state)}}function finish(stream,state){state.pendingcb--,state.finished=!0;const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i{if(val!=null)throw new ERR_INVALID_RETURN_VALUE(\"nully\",\"body\",val)},(err)=>{destroyer(d,err)});return d=new Duplexify({objectMode:!0,readable:!1,write,final(cb){final(async()=>{try{await promise,runOnNextTick(cb,null)}catch(err){runOnNextTick(cb,err)}})},destroy:destroy2})}throw new ERR_INVALID_RETURN_VALUE(\"Iterable, AsyncIterable or AsyncFunction\",name,value)}if(isBlob(body))return duplexify(body.arrayBuffer());if(isIterable(body))return from(Duplexify,body,{objectMode:!0,writable:!1});if(typeof(body===null||body===void 0\?void 0:body.writable)===\"object\"||typeof(body===null||body===void 0\?void 0:body.readable)===\"object\"){const readable=body!==null&&body!==void 0&&body.readable\?isReadableNodeStream(body===null||body===void 0\?void 0:body.readable)\?body===null||body===void 0\?void 0:body.readable:duplexify(body.readable):void 0,writable=body!==null&&body!==void 0&&body.writable\?isWritableNodeStream(body===null||body===void 0\?void 0:body.writable)\?body===null||body===void 0\?void 0:body.writable:duplexify(body.writable):void 0;return _duplexify({readable,writable})}const then=body===null||body===void 0\?void 0:body.then;if(typeof then===\"function\"){let d;return FunctionPrototypeCall(then,body,(val)=>{if(val!=null)d.push(val);d.push(null)},(err)=>{destroyer(d,err)}),d=new Duplexify({objectMode:!0,writable:!1,read(){}})}throw new ERR_INVALID_ARG_TYPE2(name,[\"Blob\",\"ReadableStream\",\"WritableStream\",\"Stream\",\"Iterable\",\"AsyncIterable\",\"Function\",\"{ readable, writable } pair\",\"Promise\"],body)};function fromAsyncGen(fn){let{promise,resolve}=createDeferredPromise();const ac=new AbortController,signal=ac.signal;return{value:fn(async function*(){while(!0){const _promise=promise;promise=null;const{chunk,done,cb}=await _promise;if(runOnNextTick(cb),done)return;if(signal.aborted)throw new AbortError2(void 0,{cause:signal.reason});({promise,resolve}=createDeferredPromise()),yield chunk}}(),{signal}),write(chunk,encoding,cb){const _resolve=resolve;resolve=null,_resolve({chunk,done:!1,cb})},final(cb){const _resolve=resolve;resolve=null,_resolve({done:!0,cb})},destroy(err,cb){ac.abort(),cb(err)}}}function _duplexify(pair){const r=pair.readable&&typeof pair.readable.read!==\"function\"\?Readable.wrap(pair.readable):pair.readable,w=pair.writable;let readable=!!isReadable(r),writable=!!isWritable(w),ondrain,onfinish,onreadable,onclose,d;function onfinished(err){const cb=onclose;if(onclose=null,cb)cb(err);else if(err)d.destroy(err);else if(!readable&&!writable)d.destroy()}if(d=new Duplexify({readableObjectMode:!!(r!==null&&r!==void 0&&r.readableObjectMode),writableObjectMode:!!(w!==null&&w!==void 0&&w.writableObjectMode),readable,writable}),writable)eos(w,(err)=>{if(writable=!1,err)destroyer(r,err);onfinished(err)}),d._write=function(chunk,encoding,callback){if(w.write(chunk,encoding))callback();else ondrain=callback},d._final=function(callback){w.end(),onfinish=callback},w.on(\"drain\",function(){if(ondrain){const cb=ondrain;ondrain=null,cb()}}),w.on(\"finish\",function(){if(onfinish){const cb=onfinish;onfinish=null,cb()}});if(readable)eos(r,(err)=>{if(readable=!1,err)destroyer(r,err);onfinished(err)}),r.on(\"readable\",function(){if(onreadable){const cb=onreadable;onreadable=null,cb()}}),r.on(\"end\",function(){d.push(null)}),d._read=function(){while(!0){const buf=r.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf))return}};return d._destroy=function(err,callback){if(!err&&onclose!==null)err=new AbortError2;if(onreadable=null,ondrain=null,onfinish=null,onclose===null)callback(err);else onclose=callback,destroyer(w,err),destroyer(r,err)},d}}}),require_duplex=__commonJS({\"node_modules/readable-stream/lib/internal/streams/duplex.js\"(exports2,module){var{ObjectDefineProperties,ObjectGetOwnPropertyDescriptor,ObjectKeys,ObjectSetPrototypeOf}=require_primordials(),Readable=require_readable();function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);if(Readable.call(this,options),Writable.call(this,options),options){if(this.allowHalfOpen=options.allowHalfOpen!==!1,options.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(options.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}Duplex.prototype={},module.exports=Duplex,ObjectSetPrototypeOf(Duplex.prototype,Readable.prototype),ObjectSetPrototypeOf(Duplex,Readable);for(var method in Writable.prototype)if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method];ObjectDefineProperties(Duplex.prototype,{writable:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writable\"),writableHighWaterMark:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableHighWaterMark\"),writableObjectMode:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableObjectMode\"),writableBuffer:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableBuffer\"),writableLength:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableLength\"),writableFinished:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableFinished\"),writableCorked:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableCorked\"),writableEnded:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableEnded\"),writableNeedDrain:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableNeedDrain\"),destroyed:{get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(value){if(this._readableState&&this._writableState)this._readableState.destroyed=value,this._writableState.destroyed=value}}});var webStreamsAdapters;function lazyWebStreams(){if(webStreamsAdapters===void 0)webStreamsAdapters={};return webStreamsAdapters}Duplex.fromWeb=function(pair,options){return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair,options)},Duplex.toWeb=function(duplex){return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)};var duplexify;Duplex.from=function(body){if(!duplexify)duplexify=require_duplexify();return duplexify(body,\"body\")}}}),require_transform=__commonJS({\"node_modules/readable-stream/lib/internal/streams/transform.js\"(exports2,module){var{ObjectSetPrototypeOf,Symbol:Symbol2}=require_primordials(),{ERR_METHOD_NOT_IMPLEMENTED}=require_errors().codes,Duplex=require_duplex();function Transform(options){if(!(this instanceof Transform))return new Transform(options);if(Duplex.call(this,options),this._readableState.sync=!1,this[kCallback]=null,options){if(typeof options.transform===\"function\")this._transform=options.transform;if(typeof options.flush===\"function\")this._flush=options.flush}this.on(\"prefinish\",prefinish.bind(this))}Transform.prototype={},ObjectSetPrototypeOf(Transform.prototype,Duplex.prototype),ObjectSetPrototypeOf(Transform,Duplex),module.exports=Transform;var kCallback=Symbol2(\"kCallback\");function final(cb){if(typeof this._flush===\"function\"&&!this.destroyed)this._flush((er,data)=>{if(er){if(cb)cb(er);else this.destroy(er);return}if(data!=null)this.push(data);if(this.push(null),cb)cb()});else if(this.push(null),cb)cb()}function prefinish(){if(this._final!==final)final.call(this)}Transform.prototype._final=final,Transform.prototype._transform=function(chunk,encoding,callback){throw new ERR_METHOD_NOT_IMPLEMENTED(\"_transform()\")},Transform.prototype._write=function(chunk,encoding,callback){const rState=this._readableState,wState=this._writableState,length=rState.length;this._transform(chunk,encoding,(err,val)=>{if(err){callback(err);return}if(val!=null)this.push(val);if(wState.ended||length===rState.length||rState.length{finished2=!0});const cleanup=eos(stream,{readable:reading,writable:writing},(err)=>{finished2=!err});return{destroy:(err)=>{if(finished2)return;finished2=!0,destroyImpl.destroyer(stream,err||new ERR_STREAM_DESTROYED(\"pipe\"))},cleanup}}function popCallback(streams){return validateFunction(streams[streams.length-1],\"streams[stream.length - 1]\"),streams.pop()}function makeAsyncIterable(val){if(isIterable(val))return val;else if(isReadableNodeStream(val))return fromReadable(val);throw new ERR_INVALID_ARG_TYPE2(\"val\",[\"Readable\",\"Iterable\",\"AsyncIterable\"],val)}async function*fromReadable(val){if(!Readable)Readable=require_readable();yield*Readable.prototype[SymbolAsyncIterator].call(val)}async function pump(iterable,writable,finish,{end}){let error,onresolve=null;const resume=(err)=>{if(err)error=err;if(onresolve){const callback=onresolve;onresolve=null,callback()}},wait=()=>new Promise2((resolve,reject)=>{if(error)reject(error);else onresolve=()=>{if(error)reject(error);else resolve()}});writable.on(\"drain\",resume);const cleanup=eos(writable,{readable:!1},resume);try{if(writable.writableNeedDrain)await wait();for await(let chunk of iterable)if(!writable.write(chunk))await wait();if(end)writable.end();await wait(),finish()}catch(err){finish(error!==err\?aggregateTwoErrors(error,err):err)}finally{cleanup(),writable.off(\"drain\",resume)}}function pipeline(...streams){return pipelineImpl(streams,once(popCallback(streams)))}function pipelineImpl(streams,callback,opts){if(streams.length===1&&ArrayIsArray2(streams[0]))streams=streams[0];if(streams.length<2)throw new ERR_MISSING_ARGS(\"streams\");const ac=new AbortController,signal=ac.signal,outerSignal=opts===null||opts===void 0\?void 0:opts.signal,lastStreamCleanup=[];validateAbortSignal(outerSignal,\"options.signal\");function abort(){finishImpl(new AbortError2)}outerSignal===null||outerSignal===void 0||outerSignal.addEventListener(\"abort\",abort);let error,value;const destroys=[];let finishCount=0;function finish(err){finishImpl(err,--finishCount===0)}function finishImpl(err,final){if(err&&(!error||error.code===\"ERR_STREAM_PREMATURE_CLOSE\"))error=err;if(!error&&!final)return;while(destroys.length)destroys.shift()(error);if(outerSignal===null||outerSignal===void 0||outerSignal.removeEventListener(\"abort\",abort),ac.abort(),final){if(!error)lastStreamCleanup.forEach((fn)=>fn());runOnNextTick(callback,error,value)}}let ret;for(let i=0;i0,end=reading||(opts===null||opts===void 0\?void 0:opts.end)!==!1,isLastStream=i===streams.length-1;if(isNodeStream(stream)){let onError=function(err){if(err&&err.name!==\"AbortError\"&&err.code!==\"ERR_STREAM_PREMATURE_CLOSE\")finish(err)};if(end){const{destroy:destroy2,cleanup}=destroyer(stream,reading,writing);if(destroys.push(destroy2),isReadable(stream)&&isLastStream)lastStreamCleanup.push(cleanup)}if(stream.on(\"error\",onError),isReadable(stream)&&isLastStream)lastStreamCleanup.push(()=>{stream.removeListener(\"error\",onError)})}if(i===0)if(typeof stream===\"function\"){if(ret=stream({signal}),!isIterable(ret))throw new ERR_INVALID_RETURN_VALUE(\"Iterable, AsyncIterable or Stream\",\"source\",ret)}else if(isIterable(stream)||isReadableNodeStream(stream))ret=stream;else ret=Duplex.from(stream);else if(typeof stream===\"function\")if(ret=makeAsyncIterable(ret),ret=stream(ret,{signal}),reading){if(!isIterable(ret,!0))throw new ERR_INVALID_RETURN_VALUE(\"AsyncIterable\",`transform[${i-1}]`,ret)}else{var _ret;if(!PassThrough)PassThrough=require_passthrough();const pt=new PassThrough({objectMode:!0}),then=(_ret=ret)===null||_ret===void 0\?void 0:_ret.then;if(typeof then===\"function\")finishCount++,then.call(ret,(val)=>{if(value=val,val!=null)pt.write(val);if(end)pt.end();runOnNextTick(finish)},(err)=>{pt.destroy(err),runOnNextTick(finish,err)});else if(isIterable(ret,!0))finishCount++,pump(ret,pt,finish,{end});else throw new ERR_INVALID_RETURN_VALUE(\"AsyncIterable or Promise\",\"destination\",ret);ret=pt;const{destroy:destroy2,cleanup}=destroyer(ret,!1,!0);if(destroys.push(destroy2),isLastStream)lastStreamCleanup.push(cleanup)}else if(isNodeStream(stream)){if(isReadableNodeStream(ret)){finishCount+=2;const cleanup=pipe(ret,stream,finish,{end});if(isReadable(stream)&&isLastStream)lastStreamCleanup.push(cleanup)}else if(isIterable(ret))finishCount++,pump(ret,stream,finish,{end});else throw new ERR_INVALID_ARG_TYPE2(\"val\",[\"Readable\",\"Iterable\",\"AsyncIterable\"],ret);ret=stream}else ret=Duplex.from(stream)}if(signal!==null&&signal!==void 0&&signal.aborted||outerSignal!==null&&outerSignal!==void 0&&outerSignal.aborted)runOnNextTick(abort);return ret}function pipe(src,dst,finish,{end}){if(src.pipe(dst,{end}),end)src.once(\"end\",()=>dst.end());else finish();return eos(src,{readable:!0,writable:!1},(err)=>{const rState=src._readableState;if(err&&err.code===\"ERR_STREAM_PREMATURE_CLOSE\"&&rState&&rState.ended&&!rState.errored&&!rState.errorEmitted)src.once(\"end\",finish).once(\"error\",finish);else finish(err)}),eos(dst,{readable:!1,writable:!0},finish)}module.exports={pipelineImpl,pipeline}}}),require_compose=__commonJS({\"node_modules/readable-stream/lib/internal/streams/compose.js\"(exports2,module){var{pipeline}=require_pipeline(),Duplex=require_duplex(),{destroyer}=require_destroy(),{isNodeStream,isReadable,isWritable}=require_utils(),{AbortError:AbortError2,codes:{ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2,ERR_MISSING_ARGS}}=require_errors();module.exports=function compose(...streams){if(streams.length===0)throw new ERR_MISSING_ARGS(\"streams\");if(streams.length===1)return Duplex.from(streams[0]);const orgStreams=[...streams];if(typeof streams[0]===\"function\")streams[0]=Duplex.from(streams[0]);if(typeof streams[streams.length-1]===\"function\"){const idx=streams.length-1;streams[idx]=Duplex.from(streams[idx])}for(let n=0;n0&&!isWritable(streams[n]))throw new ERR_INVALID_ARG_VALUE2(`streams[${n}]`,orgStreams[n],\"must be writable\")}let ondrain,onfinish,onreadable,onclose,d;function onfinished(err){const cb=onclose;if(onclose=null,cb)cb(err);else if(err)d.destroy(err);else if(!readable&&!writable)d.destroy()}const head=streams[0],tail=pipeline(streams,onfinished),writable=!!isWritable(head),readable=!!isReadable(tail);if(d=new Duplex({writableObjectMode:!!(head!==null&&head!==void 0&&head.writableObjectMode),readableObjectMode:!!(tail!==null&&tail!==void 0&&tail.writableObjectMode),writable,readable}),writable)d._write=function(chunk,encoding,callback){if(head.write(chunk,encoding))callback();else ondrain=callback},d._final=function(callback){head.end(),onfinish=callback},head.on(\"drain\",function(){if(ondrain){const cb=ondrain;ondrain=null,cb()}}),tail.on(\"finish\",function(){if(onfinish){const cb=onfinish;onfinish=null,cb()}});if(readable)tail.on(\"readable\",function(){if(onreadable){const cb=onreadable;onreadable=null,cb()}}),tail.on(\"end\",function(){d.push(null)}),d._read=function(){while(!0){const buf=tail.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf))return}};return d._destroy=function(err,callback){if(!err&&onclose!==null)err=new AbortError2;if(onreadable=null,ondrain=null,onfinish=null,onclose===null)callback(err);else onclose=callback,destroyer(tail,err)},d}}}),require_promises=__commonJS({\"node_modules/readable-stream/lib/stream/promises.js\"(exports2,module){var{ArrayPrototypePop,Promise:Promise2}=require_primordials(),{isIterable,isNodeStream}=require_utils(),{pipelineImpl:pl}=require_pipeline(),{finished:finished2}=require_end_of_stream();function pipeline(...streams){return new Promise2((resolve,reject)=>{let signal,end;const lastArg=streams[streams.length-1];if(lastArg&&typeof lastArg===\"object\"&&!isNodeStream(lastArg)&&!isIterable(lastArg)){const options=ArrayPrototypePop(streams);signal=options.signal,end=options.end}pl(streams,(err,value)=>{if(err)reject(err);else resolve(value)},{signal,end})})}module.exports={finished:finished2,pipeline}}}),require_stream=__commonJS({\"node_modules/readable-stream/lib/stream.js\"(exports2,module){var{ObjectDefineProperty,ObjectKeys,ReflectApply}=require_primordials(),{promisify:{custom:customPromisify}}=require_util(),{streamReturningOperators,promiseReturningOperators}=require_operators(),{codes:{ERR_ILLEGAL_CONSTRUCTOR}}=require_errors(),compose=require_compose(),{pipeline}=require_pipeline(),{destroyer}=require_destroy(),eos=require_end_of_stream(),promises2=require_promises(),utils=require_utils(),Stream=module.exports=require_legacy().Stream;Stream.isDisturbed=utils.isDisturbed,Stream.isErrored=utils.isErrored,Stream.isWritable=utils.isWritable,Stream.isReadable=utils.isReadable,Stream.Readable=require_readable();for(let key of ObjectKeys(streamReturningOperators)){let fn=function(...args){if(new.target)throw ERR_ILLEGAL_CONSTRUCTOR();return Stream.Readable.from(ReflectApply(op,this,args))};const op=streamReturningOperators[key];ObjectDefineProperty(fn,\"name\",{value:op.name}),ObjectDefineProperty(fn,\"length\",{value:op.length}),ObjectDefineProperty(Stream.Readable.prototype,key,{value:fn,enumerable:!1,configurable:!0,writable:!0})}for(let key of ObjectKeys(promiseReturningOperators)){let fn=function(...args){if(new.target)throw ERR_ILLEGAL_CONSTRUCTOR();return ReflectApply(op,this,args)};const op=promiseReturningOperators[key];ObjectDefineProperty(fn,\"name\",{value:op.name}),ObjectDefineProperty(fn,\"length\",{value:op.length}),ObjectDefineProperty(Stream.Readable.prototype,key,{value:fn,enumerable:!1,configurable:!0,writable:!0})}Stream.Writable=require_writable(),Stream.Duplex=require_duplex(),Stream.Transform=require_transform(),Stream.PassThrough=require_passthrough(),Stream.pipeline=pipeline;var{addAbortSignal}=require_add_abort_signal();Stream.addAbortSignal=addAbortSignal,Stream.finished=eos,Stream.destroy=destroyer,Stream.compose=compose,ObjectDefineProperty(Stream,\"promises\",{configurable:!0,enumerable:!0,get(){return promises2}}),ObjectDefineProperty(pipeline,customPromisify,{enumerable:!0,get(){return promises2.pipeline}}),ObjectDefineProperty(eos,customPromisify,{enumerable:!0,get(){return promises2.finished}}),Stream.Stream=Stream,Stream._isUint8Array=function isUint8Array(value){return value instanceof Uint8Array},Stream._uint8ArrayToBuffer=function _uint8ArrayToBuffer(chunk){return new Buffer(chunk.buffer,chunk.byteOffset,chunk.byteLength)}}});function createNativeStreamReadable(nativeType,Readable){var[pull,start,cancel,setClose,deinit,updateRef,drainFn]=globalThis[globalThis.Symbol.for('Bun.lazy')](nativeType),closer=[!1],handleNumberResult=function(nativeReadable,result,view,isClosed){if(result>0){const slice=view.subarray(0,result),remainder=view.subarray(result);if(slice.byteLength>0)nativeReadable.push(slice);if(isClosed)nativeReadable.push(null);return remainder.byteLength>0\?remainder:void 0}if(isClosed)nativeReadable.push(null);return view},handleArrayBufferViewResult=function(nativeReadable,result,view,isClosed){if(result.byteLength>0)nativeReadable.push(result);if(isClosed)nativeReadable.push(null);return view},DYNAMICALLY_ADJUST_CHUNK_SIZE=process.env.BUN_DISABLE_DYNAMIC_CHUNK_SIZE!==\"1\";const finalizer=new FinalizationRegistry((ptr)=>ptr&&deinit(ptr)),MIN_BUFFER_SIZE=512;var NativeReadable=class NativeReadable2 extends Readable{#bunNativePtr;#refCount=1;#constructed=!1;#remainingChunk=void 0;#highWaterMark;#pendingRead=!1;#hasResized=!DYNAMICALLY_ADJUST_CHUNK_SIZE;#unregisterToken;constructor(ptr,options={}){super(options);if(typeof options.highWaterMark===\"number\")this.#highWaterMark=options.highWaterMark;else this.#highWaterMark=262144;this.#bunNativePtr=ptr,this.#constructed=!1,this.#remainingChunk=void 0,this.#pendingRead=!1,this.#unregisterToken={},finalizer.register(this,this.#bunNativePtr,this.#unregisterToken)}_read(maxToRead){if(this.#pendingRead)return;var ptr=this.#bunNativePtr;if(ptr===0){this.push(null);return}if(!this.#constructed)this.#internalConstruct(ptr);return this.#internalRead(this.#getRemainingChunk(maxToRead),ptr)}#internalConstruct(ptr){this.#constructed=!0;const result=start(ptr,this.#highWaterMark);if(typeof result===\"number\"&&result>1)this.#hasResized=!0,this.#highWaterMark=Math.min(this.#highWaterMark,result);if(drainFn){const drainResult=drainFn(ptr);if((drainResult\?.byteLength\?\?0)>0)this.push(drainResult)}}#getRemainingChunk(maxToRead=this.#highWaterMark){var chunk=this.#remainingChunk;if(chunk\?.byteLength\?\?0MIN_BUFFER_SIZE\?maxToRead:MIN_BUFFER_SIZE;this.#remainingChunk=chunk=new Buffer(size)}return chunk}#handleResult(result,view,isClosed){if(typeof result===\"number\"){if(result>=this.#highWaterMark&&!this.#hasResized&&!isClosed)this.#highWaterMark*=2,this.#hasResized=!0;return handleNumberResult(this,result,view,isClosed)}else if(typeof result===\"boolean\")return process.nextTick(()=>{this.push(null)}),view\?.byteLength\?\?0>0\?view:void 0;else if(ArrayBuffer.isView(result)){if(result.byteLength>=this.#highWaterMark&&!this.#hasResized&&!isClosed)this.#highWaterMark*=2,this.#hasResized=!0;return handleArrayBufferViewResult(this,result,view,isClosed)}else throw new Error(\"Invalid result from pull\")}#internalRead(view,ptr){closer[0]=!1;var result=pull(ptr,view,closer);if(@isPromise(result))return this.#pendingRead=!0,result.then((result2)=>{this.#pendingRead=!1,this.#remainingChunk=this.#handleResult(result2,view,closer[0])},(reason)=>{errorOrDestroy(this,reason)});else this.#remainingChunk=this.#handleResult(result,view,closer[0])}_destroy(error,callback){var ptr=this.#bunNativePtr;if(ptr===0){callback(error);return}if(finalizer.unregister(this.#unregisterToken),this.#bunNativePtr=0,updateRef)updateRef(ptr,!1);cancel(ptr,error),callback(error)}ref(){var ptr=this.#bunNativePtr;if(ptr===0)return;if(this.#refCount++===0)updateRef(ptr,!0)}unref(){var ptr=this.#bunNativePtr;if(ptr===0)return;if(this.#refCount--===1)updateRef(ptr,!1)}};if(!updateRef)NativeReadable.prototype.ref=void 0,NativeReadable.prototype.unref=void 0;return NativeReadable}var nativeReadableStreamPrototypes={0:void 0,1:void 0,2:void 0,3:void 0,4:void 0,5:void 0};function getNativeReadableStreamPrototype(nativeType,Readable){return nativeReadableStreamPrototypes[nativeType]||=createNativeStreamReadable(nativeType,Readable)}function getNativeReadableStream(Readable,stream,options){if(!(stream&&typeof stream===\"object\"&&stream instanceof ReadableStream))return;const native=@direct(stream);if(!native)return;const{stream:ptr,data:type}=native;return new(getNativeReadableStreamPrototype(type,Readable))(ptr,options)}var Writable=require_writable(),NativeWritable=class NativeWritable2 extends Writable{#pathOrFdOrSink;#fileSink;#native=!0;_construct;_destroy;_final;constructor(pathOrFdOrSink,options={}){super(options);this._construct=this.#internalConstruct,this._destroy=this.#internalDestroy,this._final=this.#internalFinal,this.#pathOrFdOrSink=pathOrFdOrSink}#internalConstruct(cb){this._writableState.constructed=!0,this.constructed=!0,cb()}#lazyConstruct(){if(typeof this.#pathOrFdOrSink===\"object\")if(typeof this.#pathOrFdOrSink.write===\"function\")this.#fileSink=this.#pathOrFdOrSink;else throw new Error(\"Invalid FileSink\");else this.#fileSink=Bun.file(this.#pathOrFdOrSink).writer()}write(chunk,encoding,cb,native=this.#native){if(!native)return this.#native=!1,super.write(chunk,encoding,cb);if(!this.#fileSink)this.#lazyConstruct();var fileSink=this.#fileSink,result=fileSink.write(chunk);if(@isPromise(result))return result.then(()=>{this.emit(\"drain\"),fileSink.flush(!0)}),!1;if(fileSink.flush(!0),cb)cb(null,chunk.byteLength);return!0}end(chunk,encoding,cb,native=this.#native){return super.end(chunk,encoding,cb,native)}#internalDestroy(error,cb){if(this._writableState.destroyed=!0,cb)cb(error)}#internalFinal(cb){if(this.#fileSink)this.#fileSink.end();if(cb)cb()}ref(){if(!this.#fileSink)this.#lazyConstruct();this.#fileSink.ref()}unref(){if(!this.#fileSink)return;this.#fileSink.unref()}};const exports=require_stream(),promises=require_promises();return exports._getNativeReadableStreamPrototype=getNativeReadableStreamPrototype,exports.NativeWritable=NativeWritable,Object.defineProperty(exports,\"promises\",{configurable:!0,enumerable:!0,get(){return promises}}),exports[Symbol.for(\"::bunternal::\")]={_ReadableFromWeb,_ReadableFromWebForUndici},exports.eos=require_end_of_stream(),exports})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamPromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamWebCode = "(function (){\"use strict\";return{ReadableStream,ReadableStreamDefaultReader,ReadableStreamBYOBReader,ReadableStreamBYOBRequest,ReadableByteStreamController,ReadableStreamDefaultController,TransformStream,TransformStreamDefaultController,WritableStream,WritableStreamDefaultWriter,WritableStreamDefaultController,ByteLengthQueuingStrategy,CountQueuingStrategy}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTimersCode = "(function (){\"use strict\";return{setTimeout,clearTimeout,setInterval,setImmediate,clearInterval,clearImmediate}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTimersPromisesCode = "(function (){\"use strict\";var $;const symbolAsyncIterator=Symbol.asyncIterator;class ERR_INVALID_ARG_TYPE extends Error{constructor(name,expected,actual){super(`${name} must be ${expected}, ${typeof actual} given`);this.code=\"ERR_INVALID_ARG_TYPE\"}}class AbortError extends Error{constructor(){super(\"The operation was aborted\");this.code=\"ABORT_ERR\"}}function validateObject(object,name){if(object===null||typeof object!==\"object\")throw new ERR_INVALID_ARG_TYPE(name,\"Object\",object)}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}function validateAbortSignal(signal,name){if(typeof signal!==\"undefined\"&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE(name,\"AbortSignal\",signal)}function asyncIterator({next:nextFunction,return:returnFunction}){const result={};if(typeof nextFunction===\"function\")result.next=nextFunction;if(typeof returnFunction===\"function\")result.return=returnFunction;return result[symbolAsyncIterator]=function(){return this},result}function setTimeoutPromise(after=1,value,options={}){const arguments_=[].concat(value\?\?[]);try{validateObject(options,\"options\")}catch(error){return Promise.reject(error)}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return Promise.reject(error)}try{validateBoolean(reference,\"options.ref\")}catch(error){return Promise.reject(error)}if(signal\?.aborted)return Promise.reject(new AbortError);let onCancel;const returnValue=new Promise((resolve,reject)=>{const timeout=setTimeout(()=>resolve(value),after,...arguments_);if(!reference)timeout\?.unref\?.();if(signal)onCancel=()=>{clearTimeout(timeout),reject(new AbortError)},signal.addEventListener(\"abort\",onCancel)});if(typeof onCancel!==\"undefined\")returnValue.finally(()=>signal.removeEventListener(\"abort\",onCancel));return returnValue}function setImmediatePromise(value,options={}){try{validateObject(options,\"options\")}catch(error){return Promise.reject(error)}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return Promise.reject(error)}try{validateBoolean(reference,\"options.ref\")}catch(error){return Promise.reject(error)}if(signal\?.aborted)return Promise.reject(new AbortError);let onCancel;const returnValue=new Promise((resolve,reject)=>{const immediate=setImmediate(()=>resolve(value));if(!reference)immediate\?.unref\?.();if(signal)onCancel=()=>{clearImmediate(immediate),reject(new AbortError)},signal.addEventListener(\"abort\",onCancel)});if(typeof onCancel!==\"undefined\")returnValue.finally(()=>signal.removeEventListener(\"abort\",onCancel));return returnValue}function setIntervalPromise(after=1,value,options={}){try{validateObject(options,\"options\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}try{validateBoolean(reference,\"options.ref\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}if(signal\?.aborted)return asyncIterator({next:function(){return Promise.reject(new AbortError)}});let onCancel,interval;try{let notYielded=0,callback;if(interval=setInterval(()=>{if(notYielded++,callback)callback(),callback=void 0},after),!reference)interval\?.unref\?.();if(signal)onCancel=()=>{if(clearInterval(interval),callback)callback(),callback=void 0},signal.addEventListener(\"abort\",onCancel);return asyncIterator({next:function(){return new Promise((resolve,reject)=>{if(!signal\?.aborted)if(notYielded===0)callback=resolve;else resolve();else if(notYielded===0)reject(new AbortError);else resolve()}).then(()=>{if(notYielded>0)return notYielded=notYielded-1,{done:!1,value};return{done:!0}})},return:function(){return clearInterval(interval),signal\?.removeEventListener(\"abort\",onCancel),Promise.resolve({})}})}catch(error){return asyncIterator({next:function(){clearInterval(interval),signal\?.removeEventListener(\"abort\",onCancel)}})}}return $={setTimeout:setTimeoutPromise,setImmediate:setImmediatePromise,setInterval:setIntervalPromise,scheduler:{wait:(delay,options)=>setTimeoutPromise(delay,void 0,options),yield:setImmediatePromise}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTLSCode = "(function (){\"use strict\";const{isArrayBufferView,isTypedArray}=@requireNativeModule(\"node:util/types\"),net=@getInternalField(@internalModuleRegistry,22)||@createInternalModuleById(22),{Server:NetServer,[Symbol.for(\"::bunternal::\")]:InternalTCPSocket}=net,bunSocketInternal=Symbol.for(\"::bunnetsocketinternal::\"),{rootCertificates,canonicalizeIP}=globalThis[globalThis.Symbol.for('Bun.lazy')](\"internal/tls\"),SymbolReplace=Symbol.replace,RegExpPrototypeSymbolReplace=RegExp.prototype[SymbolReplace],RegExpPrototypeExec=RegExp.prototype.exec,StringPrototypeStartsWith=String.prototype.startsWith,StringPrototypeSlice=String.prototype.slice,StringPrototypeIncludes=String.prototype.includes,StringPrototypeSplit=String.prototype.split,StringPrototypeIndexOf=String.prototype.indexOf,StringPrototypeSubstring=String.prototype.substring,StringPrototypeEndsWith=String.prototype.endsWith,StringFromCharCode=String.fromCharCode,StringPrototypeCharCodeAt=String.prototype.charCodeAt,ArrayPrototypeIncludes=Array.prototype.includes,ArrayPrototypeJoin=Array.prototype.join,ArrayPrototypeForEach=Array.prototype.forEach,ArrayPrototypePush=Array.prototype.push,ArrayPrototypeSome=Array.prototype.some,ArrayPrototypeReduce=Array.prototype.reduce;function parseCertString(){throwNotImplemented(\"Not implemented\")}function isValidTLSArray(obj){if(typeof obj===\"string\"||isTypedArray(obj)||obj instanceof ArrayBuffer||obj instanceof Blob)return!0;if(Array.isArray(obj)){for(var i=0;iRegExpPrototypeExec.call(/[^\\u0021-\\u007F]/u,s)!==null;if(ArrayPrototypeSome.call(patternParts,isBad))return!1;for(let i=hostParts.length-1;i>0;i-=1)if(hostParts[i]!==patternParts[i])return!1;const hostSubdomain=hostParts[0],patternSubdomain=patternParts[0],patternSubdomainParts=StringPrototypeSplit.call(patternSubdomain,\"*\");if(patternSubdomainParts.length===1||StringPrototypeIncludes.call(patternSubdomain,\"xn--\"))return hostSubdomain===patternSubdomain;if(!wildcards)return!1;if(patternSubdomainParts.length>2)return!1;if(patternParts.length<=2)return!1;const{0:prefix,1:suffix}=patternSubdomainParts;if(prefix.length+suffix.length>hostSubdomain.length)return!1;if(!StringPrototypeStartsWith.call(hostSubdomain,prefix))return!1;if(!StringPrototypeEndsWith.call(hostSubdomain,suffix))return!1;return!0}const jsonStringPattern=/^\"(\?:[^\"\\\\\\u0000-\\u001f]|\\\\(\?:[\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"/;function splitEscapedAltNames(altNames){const result=[];let currentToken=\"\",offset=0;while(offset!==altNames.length){const nextSep=StringPrototypeIndexOf.call(altNames,\", \",offset),nextQuote=StringPrototypeIndexOf.call(altNames,'\"',offset);if(nextQuote!==-1&&(nextSep===-1||nextQuote{if(StringPrototypeStartsWith.call(name,\"DNS:\"))ArrayPrototypePush.call(dnsNames,StringPrototypeSlice.call(name,4));else if(StringPrototypeStartsWith.call(name,\"IP Address:\"))ArrayPrototypePush.call(ips,canonicalizeIP(StringPrototypeSlice.call(name,11)))})}let valid=!1,reason=\"Unknown reason\";if(hostname=unfqdn(hostname),net.isIP(hostname)){if(valid=ArrayPrototypeIncludes.call(ips,canonicalizeIP(hostname)),!valid)reason=`IP: ${hostname} is not in the cert's list: `+ArrayPrototypeJoin.call(ips,\", \")}else if(dnsNames.length>0||subject\?.CN){const hostParts=splitHost(hostname),wildcard=(pattern)=>check(hostParts,pattern,!0);if(dnsNames.length>0){if(valid=ArrayPrototypeSome.call(dnsNames,wildcard),!valid)reason=`Host: ${hostname}. is not in the cert's altnames: ${altNames}`}else{const cn=subject.CN;if(Array.isArray(cn))valid=ArrayPrototypeSome.call(cn,wildcard);else if(cn)valid=wildcard(cn);if(!valid)reason=`Host: ${hostname}. is not cert's CN: ${cn}`}}else reason=\"Cert does not contain a DNS name\";if(!valid){let error=new Error(`ERR_TLS_CERT_ALTNAME_INVALID: Hostname/IP does not match certificate's altnames: ${reason}`);return error.name=\"ERR_TLS_CERT_ALTNAME_INVALID\",error.reason=reason,error.host=host,error.cert=cert,error}}var InternalSecureContext=class SecureContext2{context;constructor(options){const context={};if(options){let key=options.key;if(key){if(!isValidTLSArray(key))@throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.key=key}let cert=options.cert;if(cert){if(!isValidTLSArray(cert))@throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.cert=cert}let ca=options.ca;if(ca){if(!isValidTLSArray(ca))@throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.ca=ca}let passphrase=options.passphrase;if(passphrase&&typeof passphrase!==\"string\")@throwTypeError(\"passphrase argument must be an string\");this.passphrase=passphrase;let servername=options.servername;if(servername&&typeof servername!==\"string\")@throwTypeError(\"servername argument must be an string\");this.servername=servername;let secureOptions=options.secureOptions||0;if(secureOptions&&typeof secureOptions!==\"number\")@throwTypeError(\"secureOptions argument must be an number\");this.secureOptions=secureOptions}this.context=context}};function SecureContext(options){return new InternalSecureContext(options)}function createSecureContext(options){return new SecureContext(options)}function translatePeerCertificate(c){if(!c)return null;if(c.issuerCertificate!=null&&c.issuerCertificate!==c)c.issuerCertificate=translatePeerCertificate(c.issuerCertificate);if(c.infoAccess!=null){const info=c.infoAccess;c.infoAccess={__proto__:null},RegExpPrototypeSymbolReplace.call(/([^\\n:]*):([^\\n]*)(\?:\\n|$)/g,info,(all,key,val)=>{if(val.charCodeAt(0)===34)val=JSONParse(val);if(key in c.infoAccess)ArrayPrototypePush.call(c.infoAccess[key],val);else c.infoAccess[key]=[val]})}return c}const buntls=Symbol.for(\"::buntls::\");var SocketClass;const TLSSocket=function(InternalTLSSocket){return SocketClass=InternalTLSSocket,Object.defineProperty(SocketClass.prototype,Symbol.toStringTag,{value:\"TLSSocket\",enumerable:!1}),Object.defineProperty(function Socket(options){return new InternalTLSSocket(options)},Symbol.hasInstance,{value(instance){return instance instanceof InternalTLSSocket}})}(class TLSSocket2 extends InternalTCPSocket{#secureContext;ALPNProtocols;#socket;#checkServerIdentity;#session;constructor(socket,options){super(socket instanceof InternalTCPSocket\?options:options||socket);if(options=options||socket||{},typeof options===\"object\"){const{ALPNProtocols}=options;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,this);if(socket instanceof InternalTCPSocket)this.#socket=socket}this.#secureContext=options.secureContext||createSecureContext(options),this.authorized=!1,this.secureConnecting=!0,this._secureEstablished=!1,this._securePending=!0,this.#checkServerIdentity=options.checkServerIdentity||checkServerIdentity,this.#session=options.session||null}_secureEstablished=!1;_securePending=!0;_newSessionPending;_controlReleased;secureConnecting=!1;_SNICallback;servername;authorized=!1;authorizationError;#renegotiationDisabled=!1;encrypted=!0;_start(){this.connect()}getSession(){return this[bunSocketInternal]\?.getSession()}getEphemeralKeyInfo(){return this[bunSocketInternal]\?.getEphemeralKeyInfo()}getCipher(){return this[bunSocketInternal]\?.getCipher()}getSharedSigalgs(){return this[bunSocketInternal]\?.getSharedSigalgs()}getProtocol(){return this[bunSocketInternal]\?.getTLSVersion()}getFinished(){return this[bunSocketInternal]\?.getTLSFinishedMessage()||void 0}getPeerFinished(){return this[bunSocketInternal]\?.getTLSPeerFinishedMessage()||void 0}isSessionReused(){return!!this.#session}renegotiate(){if(this.#renegotiationDisabled){const error=new Error(\"ERR_TLS_RENEGOTIATION_DISABLED: TLS session renegotiation disabled for this socket\");throw error.name=\"ERR_TLS_RENEGOTIATION_DISABLED\",error}throw Error(\"Not implented in Bun yet\")}disableRenegotiation(){this.#renegotiationDisabled=!0}getTLSTicket(){return this[bunSocketInternal]\?.getTLSTicket()}exportKeyingMaterial(length,label,context){if(context)return this[bunSocketInternal]\?.exportKeyingMaterial(length,label,context);return this[bunSocketInternal]\?.exportKeyingMaterial(length,label)}setMaxSendFragment(size){return this[bunSocketInternal]\?.setMaxSendFragment(size)||!1}enableTrace(){}setServername(name){if(this.isServer){let error=new Error(\"ERR_TLS_SNI_FROM_SERVER: Cannot issue SNI from a TLS server-side socket\");throw error.name=\"ERR_TLS_SNI_FROM_SERVER\",error}this.servername=name,this[bunSocketInternal]\?.setServername(name)}setSession(session){if(this.#session=session,typeof session===\"string\")session=Buffer.from(session,\"latin1\");return this[bunSocketInternal]\?.setSession(session)}getPeerCertificate(abbreviated){const cert=arguments.length<1\?this[bunSocketInternal]\?.getPeerCertificate():this[bunSocketInternal]\?.getPeerCertificate(abbreviated);if(cert)return translatePeerCertificate(cert)}getCertificate(){const cert=this[bunSocketInternal]\?.getCertificate();if(cert)return translatePeerCertificate(cert)}getPeerX509Certificate(){throw Error(\"Not implented in Bun yet\")}getX509Certificate(){throw Error(\"Not implented in Bun yet\")}get alpnProtocol(){return this[bunSocketInternal]\?.alpnProtocol}[buntls](port,host2){return{socket:this.#socket,ALPNProtocols:this.ALPNProtocols,serverName:this.servername||host2||\"localhost\",checkServerIdentity:this.#checkServerIdentity,session:this.#session,...this.#secureContext}}});class Server extends NetServer{key;cert;ca;passphrase;secureOptions;_rejectUnauthorized;_requestCert;servername;ALPNProtocols;constructor(options,secureConnectionListener){super(options,secureConnectionListener);this.setSecureContext(options)}setSecureContext(options){if(options instanceof InternalSecureContext)options=options.context;if(options){const{ALPNProtocols}=options;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,this);let key=options.key;if(key){if(!isValidTLSArray(key))@throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.key=key}let cert=options.cert;if(cert){if(!isValidTLSArray(cert))@throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.cert=cert}let ca=options.ca;if(ca){if(!isValidTLSArray(ca))@throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.ca=ca}let passphrase=options.passphrase;if(passphrase&&typeof passphrase!==\"string\")@throwTypeError(\"passphrase argument must be an string\");this.passphrase=passphrase;let servername=options.servername;if(servername&&typeof servername!==\"string\")@throwTypeError(\"servername argument must be an string\");this.servername=servername;let secureOptions=options.secureOptions||0;if(secureOptions&&typeof secureOptions!==\"number\")@throwTypeError(\"secureOptions argument must be an number\");this.secureOptions=secureOptions;const requestCert=options.requestCert||!1;if(requestCert)this._requestCert=requestCert;else this._requestCert=void 0;const rejectUnauthorized=options.rejectUnauthorized||!1;if(rejectUnauthorized)this._rejectUnauthorized=rejectUnauthorized;else this._rejectUnauthorized=void 0}}getTicketKeys(){throw Error(\"Not implented in Bun yet\")}setTicketKeys(){throw Error(\"Not implented in Bun yet\")}[buntls](port,host2,isClient){return[{serverName:this.servername||host2||\"localhost\",key:this.key,cert:this.cert,ca:this.ca,passphrase:this.passphrase,secureOptions:this.secureOptions,rejectUnauthorized:isClient\?!1:this._rejectUnauthorized,requestCert:isClient\?!1:this._requestCert,ALPNProtocols:this.ALPNProtocols},SocketClass]}}function createServer(options,connectionListener){return new Server(options,connectionListener)}const CLIENT_RENEG_LIMIT=3,CLIENT_RENEG_WINDOW=600,DEFAULT_ECDH_CURVE=\"auto\",DEFAULT_CIPHERS=\"DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256\",DEFAULT_MIN_VERSION=\"TLSv1.2\",DEFAULT_MAX_VERSION=\"TLSv1.3\",createConnection=(port,host2,connectListener)=>{if(typeof port===\"object\"){port.checkServerIdentity;const{ALPNProtocols}=port;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,port);return new TLSSocket(port).connect(port,host2,connectListener)}return new TLSSocket().connect(port,host2,connectListener)},connect=createConnection;function getCiphers(){return DEFAULT_CIPHERS.split(\":\")}function convertProtocols(protocols){const lens=new Array(protocols.length),buff=Buffer.allocUnsafe(ArrayPrototypeReduce.call(protocols,(p,c,i)=>{const len=Buffer.byteLength(c);if(len>255)@throwRangeError(\"The byte length of the protocol at index \"+`${i} exceeds the maximum length.`,\"<= 255\",len,!0);return lens[i]=len,p+1+len},0));let offset=0;for(let i=0,c=protocols.length;i\",'\"',\"`\",\" \",\"\\r\",\"\\n\",\"\\t\"],unwise=[\"{\",\"}\",\"|\",\"\\\\\",\"^\",\"`\"].concat(delims),autoEscape=[\"'\"].concat(unwise),nonHostChars=[\"%\",\"/\",\"\?\",\";\",\"#\"].concat(autoEscape),hostEndingChars=[\"/\",\"\?\",\"#\"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,\"javascript:\":!0},hostlessProtocol={javascript:!0,\"javascript:\":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,\"http:\":!0,\"https:\":!0,\"ftp:\":!0,\"gopher:\":!0,\"file:\":!0};function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&typeof url===\"object\"&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(typeof url!==\"string\")@throwTypeError(\"Parameter 'url' must be a string, not \"+typeof url);var queryIndex=url.indexOf(\"\?\"),splitter=queryIndex!==-1&&queryIndex127)newpart+=\"x\";else newpart+=part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);if(bit)validParts.push(bit[1]),notHost.unshift(bit[2]);if(notHost.length)rest=\"/\"+notHost.join(\".\")+rest;this.hostname=validParts.join(\".\");break}}}}if(this.hostname.length>hostnameMaxLen)this.hostname=\"\";else this.hostname=this.hostname.toLowerCase();if(!ipv6Hostname)this.hostname=new URL(\"http://\"+this.hostname).hostname;var p=this.port\?\":\"+this.port:\"\",h=this.hostname||\"\";if(this.host=h+p,this.href+=this.host,ipv6Hostname){if(this.hostname=this.hostname.substr(1,this.hostname.length-2),rest[0]!==\"/\")rest=\"/\"+rest}}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length;i0\?result.host.split(\"@\"):!1;if(authInHost)result.auth=authInHost.shift(),result.hostname=authInHost.shift(),result.host=result.hostname}if(result.search=relative.search,result.query=relative.query,result.pathname!==null||result.search!==null)result.path=(result.pathname\?result.pathname:\"\")+(result.search\?result.search:\"\");return result.href=result.format(),result}if(!srcPath.length){if(result.pathname=null,result.search)result.path=\"/\"+result.search;else result.path=null;return result.href=result.format(),result}var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last===\".\"||last===\"..\")||last===\"\",up=0;for(var i=srcPath.length;i>=0;i--)if(last=srcPath[i],last===\".\")srcPath.splice(i,1);else if(last===\"..\")srcPath.splice(i,1),up++;else if(up)srcPath.splice(i,1),up--;if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift(\"..\");if(mustEndAbs&&srcPath[0]!==\"\"&&(!srcPath[0]||srcPath[0].charAt(0)!==\"/\"))srcPath.unshift(\"\");if(hasTrailingSlash&&srcPath.join(\"/\").substr(-1)!==\"/\")srcPath.push(\"\");var isAbsolute=srcPath[0]===\"\"||srcPath[0]&&srcPath[0].charAt(0)===\"/\";if(psychotic){result.hostname=isAbsolute\?\"\":srcPath.length\?srcPath.shift():\"\",result.host=result.hostname;var authInHost=result.host&&result.host.indexOf(\"@\")>0\?result.host.split(\"@\"):!1;if(authInHost)result.auth=authInHost.shift(),result.hostname=authInHost.shift(),result.host=result.hostname}if(mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute)srcPath.unshift(\"\");if(srcPath.length>0)result.pathname=srcPath.join(\"/\");else result.pathname=null,result.path=null;if(result.pathname!==null||result.search!==null)result.path=(result.pathname\?result.pathname:\"\")+(result.search\?result.search:\"\");return result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);if(port){if(port=port[0],port!==\":\")this.port=port.substr(1);host=host.substr(0,host.length-port.length)}if(host)this.hostname=host};function urlToHttpOptions(url){const options={protocol:url.protocol,hostname:typeof url.hostname===\"string\"&&url.hostname.startsWith(\"[\")\?url.hostname.slice(1,-1):url.hostname,hash:url.hash,search:url.search,pathname:url.pathname,path:`${url.pathname||\"\"}${url.search||\"\"}`,href:url.href};if(url.port!==\"\")options.port=Number(url.port);if(url.username||url.password)options.auth=`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;return options}const pathToFileURL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"pathToFileURL\"),fileURLToPath=globalThis[globalThis.Symbol.for('Bun.lazy')](\"fileURLToPath\");return{parse:urlParse,resolve:urlResolve,resolveObject:urlResolveObject,format:urlFormat,Url,URLSearchParams,URL,pathToFileURL,fileURLToPath,urlToHttpOptions}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeUtilCode = "(function (){\"use strict\";const types=@requireNativeModule(\"node:util/types\");var cjs_exports={};function isBufferInterface({copy,fill,readUint8}){return typeof copy===\"function\"&&typeof fill===\"function\"&&typeof readUint8===\"function\"}function isBuffer(value){return Buffer.isBuffer(value)||typeof value===\"object\"&&isBufferInterface(value||{})}function isFunction(value){return typeof value===\"function\"}const deepEquals=Bun.deepEquals,isDeepStrictEqual=(a,b)=>deepEquals(a,b,!0);var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors,formatRegExp=/%[sdj%]/g;function format(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x2;switch(x2){case\"%s\":return String(args[i++]);case\"%d\":return Number(args[i++]);case\"%j\":try{return JSON.stringify(args[i++])}catch(_){return\"[Circular]\"}default:return x2}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts))ctx.showHidden=opts;else if(opts)_extend(ctx,opts);if(isUndefined(ctx.showHidden))ctx.showHidden=!1;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=!1;if(isUndefined(ctx.customInspect))ctx.customInspect=!0;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:\"cyan\",number:\"yellow\",boolean:\"yellow\",undefined:\"grey\",null:\"bold\",string:\"green\",date:\"magenta\",regexp:\"red\"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style)return\"\\x1B[\"+inspect.colors[style][0]+\"m\"+str+\"\\x1B[\"+inspect.colors[style][1]+\"m\";else return str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret))ret=formatValue(ctx,ret,recurseTimes);return ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden)keys=Object.getOwnPropertyNames(value);if(isError(value)&&(keys.indexOf(\"message\")>=0||keys.indexOf(\"description\")>=0))return formatError(value);if(keys.length===0){if(isFunction(value)){var name=value.name\?\": \"+value.name:\"\";return ctx.stylize(\"[Function\"+name+\"]\",\"special\")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),\"regexp\");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),\"date\");if(isError(value))return formatError(value)}var base=\"\",array=!1,braces=[\"{\",\"}\"];if(@isArray(value))array=!0,braces=[\"[\",\"]\"];if(isFunction(value)){var n=value.name\?\": \"+value.name:\"\";base=\" [Function\"+n+\"]\"}if(isRegExp(value))base=\" \"+RegExp.prototype.toString.call(value);if(isDate(value))base=\" \"+Date.prototype.toUTCString.call(value);if(isError(value))base=\" \"+formatError(value);if(keys.length===0&&(!array||value.length==0))return braces[0]+base+braces[1];if(recurseTimes<0)if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),\"regexp\");else return ctx.stylize(\"[Object]\",\"special\");ctx.seen.push(value);var output;if(array)output=formatArray(ctx,value,recurseTimes,visibleKeys,keys);else output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)});return ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize(\"undefined\",\"undefined\");if(isString(value)){var simple=\"'\"+JSON.stringify(value).replace(/^\"|\"$/g,\"\").replace(/'/g,\"\\\\'\").replace(/\\\\\"/g,'\"')+\"'\";return ctx.stylize(simple,\"string\")}if(isNumber(value))return ctx.stylize(\"\"+value,\"number\");if(isBoolean(value))return ctx.stylize(\"\"+value,\"boolean\");if(isNull(value))return ctx.stylize(\"null\",\"null\")}function formatError(value){return\"[\"+Error.prototype.toString.call(value)+\"]\"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1)if(array)str=str.split(\"\\n\").map(function(line){return\" \"+line}).join(\"\\n\").substr(2);else str=\"\\n\"+str.split(\"\\n\").map(function(line){return\" \"+line}).join(\"\\n\")}else str=ctx.stylize(\"[Circular]\",\"special\");if(isUndefined(name)){if(array&&key.match(/^\\d+$/))return str;if(name=JSON.stringify(\"\"+key),name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/))name=name.substr(1,name.length-2),name=ctx.stylize(name,\"name\");else name=name.replace(/'/g,\"\\\\'\").replace(/\\\\\"/g,'\"').replace(/(^\"|\"$)/g,\"'\"),name=ctx.stylize(name,\"string\")}return name+\": \"+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){if(numLinesEst++,cur.indexOf(\"\\n\")>=0)numLinesEst++;return prev+cur.replace(/\\u001b\\[\\d\\d\?m/g,\"\").length+1},0);if(length>60)return braces[0]+(base===\"\"\?\"\":base+\"\\n \")+\" \"+output.join(\",\\n \")+\" \"+braces[1];return braces[0]+base+\" \"+output.join(\", \")+\" \"+braces[1]}function isBoolean(arg){return typeof arg===\"boolean\"}function isNull(arg){return arg===null}function isNullOrUndefined(arg){return arg==null}function isNumber(arg){return typeof arg===\"number\"}function isString(arg){return typeof arg===\"string\"}function isSymbol(arg){return typeof arg===\"symbol\"}function isUndefined(arg){return arg===void 0}var isRegExp=types.isRegExp;function isObject(arg){return typeof arg===\"object\"&&arg!==null}var{isDate,isNativeError:isError}=types;function isPrimitive(arg){return arg===null||typeof arg===\"boolean\"||typeof arg===\"number\"||typeof arg===\"string\"||typeof arg===\"symbol\"||typeof arg===\"undefined\"}function pad(n){return n<10\?\"0\"+n.toString(10):n.toString(10)}var months=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"];function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(\":\");return[d.getDate(),months[d.getMonth()],time].join(\" \")}var log=function log(){console.log(\"%s - %s\",timestamp(),format.apply(cjs_exports,arguments))},inherits=function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},_extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add),i=keys.length;while(i--)origin[keys[i]]=add[keys[i]];return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var kCustomPromisifiedSymbol=Symbol.for(\"util.promisify.custom\"),promisify=function promisify(original){if(typeof original!==\"function\")@throwTypeError('The \"original\" argument must be of type Function');if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if(typeof fn!==\"function\")@throwTypeError('The \"util.promisify.custom\" argument must be of type Function');return Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),fn}function fn(){var promiseResolve,promiseReject,promise=new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject}),args=[];for(var i=0;i{return(input+\"\").toWellFormed()};return Object.assign(cjs_exports,{format,deprecate,debuglog,_extend,inspect,types,isArray:@isArray,isBoolean,isNull,isNullOrUndefined,isNumber,isString,isSymbol,isUndefined,isRegExp,isObject,isDate,isFunction,isError,isPrimitive,isBuffer,log,inherits,toUSVString,promisify,callbackify,isDeepStrictEqual,TextDecoder,TextEncoder})})\n"_s; +// + +// +static constexpr ASCIILiteral NodeV8Code = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),jsc=@requireNativeModule(\"bun:jsc\");function notimpl(message){throwNotImplemented(\"node:v8 \"+message)}class Deserializer{constructor(){notimpl(\"Deserializer\")}}class Serializer{constructor(){notimpl(\"Serializer\")}}class DefaultDeserializer extends Deserializer{constructor(){super(...arguments)}}class DefaultSerializer extends Serializer{constructor(){super(...arguments)}}class GCProfiler{constructor(){notimpl(\"GCProfiler\")}}function cachedDataVersionTag(){notimpl(\"cachedDataVersionTag\")}function getHeapSnapshot(){notimpl(\"getHeapSnapshot\")}function getHeapStatistics(){notimpl(\"getHeapStatistics\")}function getHeapSpaceStatistics(){notimpl(\"getHeapSpaceStatistics\")}function getHeapCodeStatistics(){notimpl(\"getHeapCodeStatistics\")}function setFlagsFromString(){notimpl(\"setFlagsFromString\")}function deserialize(value){return jsc.deserialize(value)}function takeCoverage(){notimpl(\"takeCoverage\")}function stopCoverage(){notimpl(\"stopCoverage\")}function serialize(arg1){return jsc.serialize(arg1,{binaryType:\"nodebuffer\"})}function writeHeapSnapshot(){notimpl(\"writeHeapSnapshot\")}function setHeapSnapshotNearHeapLimit(){notimpl(\"setHeapSnapshotNearHeapLimit\")}return $={cachedDataVersionTag,getHeapSnapshot,getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,deserialize,takeCoverage,stopCoverage,serialize,writeHeapSnapshot,setHeapSnapshotNearHeapLimit,promiseHooks:{createHook:()=>{notimpl(\"createHook\")},onInit:()=>{notimpl(\"onInit\")},onBefore:()=>{notimpl(\"onBefore\")},onAfter:()=>{notimpl(\"onAfter\")},onSettled:()=>{notimpl(\"onSettled\")}},startupSnapshot:{addDeserializeCallback:()=>notimpl(\"addDeserializeCallback\"),addSerializeCallback:()=>notimpl(\"addSerializeCallback\"),setDeserializeMainFunction:()=>notimpl(\"setDeserializeMainFunction\"),isBuildingSnapshot:()=>notimpl(\"isBuildingSnapshot\")},Deserializer,Serializer},hideFromStack(notimpl,cachedDataVersionTag,getHeapSnapshot,getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,deserialize,takeCoverage,stopCoverage,serialize,writeHeapSnapshot,setHeapSnapshotNearHeapLimit,Deserializer,Serializer,DefaultDeserializer,DefaultSerializer,GCProfiler),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeVMCode = "(function (){\"use strict\";const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),vm=globalThis[globalThis.Symbol.for('Bun.lazy')](\"vm\"),{createContext,isContext,Script,runInNewContext,runInThisContext}=vm;function runInContext(code,context,options){return new Script(code,options).runInContext(context)}function compileFunction(){throwNotImplemented(\"node:vm compileFunction\")}function measureMemory(){throwNotImplemented(\"node:vm measureMemory\")}class Module{constructor(){throwNotImplemented(\"node:vm Module\")}}class SourceTextModule{constructor(){throwNotImplemented(\"node:vm Module\")}}class SyntheticModule{constructor(){throwNotImplemented(\"node:vm Module\")}}return{createContext,runInContext,runInNewContext,runInThisContext,isContext,compileFunction,measureMemory,Script,Module,SourceTextModule,SyntheticModule}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeWasiCode = "(function (){\"use strict\";const nodeFsConstants=@processBindingConstants.fs;var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_types=__commonJS({\"node_modules/wasi-js/dist/types.js\"(exports){Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.WASIKillError=exports.WASIExitError=exports.WASIError=void 0;var WASIError=class extends Error{constructor(errno){super();this.errno=errno,Object.setPrototypeOf(this,WASIError.prototype)}};exports.WASIError=WASIError;var WASIExitError=class extends Error{constructor(code){super(`WASI Exit error: ${code}`);this.code=code,Object.setPrototypeOf(this,WASIExitError.prototype)}};exports.WASIExitError=WASIExitError;var WASIKillError=class extends Error{constructor(signal){super(`WASI Kill signal: ${signal}`);this.signal=signal,Object.setPrototypeOf(this,WASIKillError.prototype)}};exports.WASIKillError=WASIKillError}}),require_constants=__commonJS({\"node_modules/wasi-js/dist/constants.js\"(exports){Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.WASI_ENOMSG=exports.WASI_ENOMEM=exports.WASI_ENOLINK=exports.WASI_ENOLCK=exports.WASI_ENOEXEC=exports.WASI_ENOENT=exports.WASI_ENODEV=exports.WASI_ENOBUFS=exports.WASI_ENFILE=exports.WASI_ENETUNREACH=exports.WASI_ENETRESET=exports.WASI_ENETDOWN=exports.WASI_ENAMETOOLONG=exports.WASI_EMULTIHOP=exports.WASI_EMSGSIZE=exports.WASI_EMLINK=exports.WASI_EMFILE=exports.WASI_ELOOP=exports.WASI_EISDIR=exports.WASI_EISCONN=exports.WASI_EIO=exports.WASI_EINVAL=exports.WASI_EINTR=exports.WASI_EINPROGRESS=exports.WASI_EILSEQ=exports.WASI_EIDRM=exports.WASI_EHOSTUNREACH=exports.WASI_EFBIG=exports.WASI_EFAULT=exports.WASI_EEXIST=exports.WASI_EDQUOT=exports.WASI_EDOM=exports.WASI_EDESTADDRREQ=exports.WASI_EDEADLK=exports.WASI_ECONNRESET=exports.WASI_ECONNREFUSED=exports.WASI_ECONNABORTED=exports.WASI_ECHILD=exports.WASI_ECANCELED=exports.WASI_EBUSY=exports.WASI_EBADMSG=exports.WASI_EBADF=exports.WASI_EALREADY=exports.WASI_EAGAIN=exports.WASI_EAFNOSUPPORT=exports.WASI_EADDRNOTAVAIL=exports.WASI_EADDRINUSE=exports.WASI_EACCES=exports.WASI_E2BIG=exports.WASI_ESUCCESS=void 0,exports.WASI_SIGVTALRM=exports.WASI_SIGUSR2=exports.WASI_SIGUSR1=exports.WASI_SIGURG=exports.WASI_SIGTTOU=exports.WASI_SIGTTIN=exports.WASI_SIGTSTP=exports.WASI_SIGTRAP=exports.WASI_SIGTERM=exports.WASI_SIGSTOP=exports.WASI_SIGSEGV=exports.WASI_SIGQUIT=exports.WASI_SIGPIPE=exports.WASI_SIGKILL=exports.WASI_SIGINT=exports.WASI_SIGILL=exports.WASI_SIGHUP=exports.WASI_SIGFPE=exports.WASI_SIGCONT=exports.WASI_SIGCHLD=exports.WASI_SIGBUS=exports.WASI_SIGALRM=exports.WASI_SIGABRT=exports.WASI_ENOTCAPABLE=exports.WASI_EXDEV=exports.WASI_ETXTBSY=exports.WASI_ETIMEDOUT=exports.WASI_ESTALE=exports.WASI_ESRCH=exports.WASI_ESPIPE=exports.WASI_EROFS=exports.WASI_ERANGE=exports.WASI_EPROTOTYPE=exports.WASI_EPROTONOSUPPORT=exports.WASI_EPROTO=exports.WASI_EPIPE=exports.WASI_EPERM=exports.WASI_EOWNERDEAD=exports.WASI_EOVERFLOW=exports.WASI_ENXIO=exports.WASI_ENOTTY=exports.WASI_ENOTSUP=exports.WASI_ENOTSOCK=exports.WASI_ENOTRECOVERABLE=exports.WASI_ENOTEMPTY=exports.WASI_ENOTDIR=exports.WASI_ENOTCONN=exports.WASI_ENOSYS=exports.WASI_ENOSPC=exports.WASI_ENOPROTOOPT=void 0,exports.RIGHTS_REGULAR_FILE_BASE=exports.RIGHTS_CHARACTER_DEVICE_INHERITING=exports.RIGHTS_CHARACTER_DEVICE_BASE=exports.RIGHTS_BLOCK_DEVICE_INHERITING=exports.RIGHTS_BLOCK_DEVICE_BASE=exports.RIGHTS_ALL=exports.WASI_RIGHT_SOCK_SHUTDOWN=exports.WASI_RIGHT_POLL_FD_READWRITE=exports.WASI_RIGHT_PATH_UNLINK_FILE=exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY=exports.WASI_RIGHT_PATH_SYMLINK=exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES=exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE=exports.WASI_RIGHT_FD_FILESTAT_GET=exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES=exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE=exports.WASI_RIGHT_PATH_FILESTAT_GET=exports.WASI_RIGHT_PATH_RENAME_TARGET=exports.WASI_RIGHT_PATH_RENAME_SOURCE=exports.WASI_RIGHT_PATH_READLINK=exports.WASI_RIGHT_FD_READDIR=exports.WASI_RIGHT_PATH_OPEN=exports.WASI_RIGHT_PATH_LINK_TARGET=exports.WASI_RIGHT_PATH_LINK_SOURCE=exports.WASI_RIGHT_PATH_CREATE_FILE=exports.WASI_RIGHT_PATH_CREATE_DIRECTORY=exports.WASI_RIGHT_FD_ALLOCATE=exports.WASI_RIGHT_FD_ADVISE=exports.WASI_RIGHT_FD_WRITE=exports.WASI_RIGHT_FD_TELL=exports.WASI_RIGHT_FD_SYNC=exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS=exports.WASI_RIGHT_FD_SEEK=exports.WASI_RIGHT_FD_READ=exports.WASI_RIGHT_FD_DATASYNC=exports.WASI_FDFLAG_SYNC=exports.WASI_FDFLAG_RSYNC=exports.WASI_FDFLAG_NONBLOCK=exports.WASI_FDFLAG_DSYNC=exports.WASI_FDFLAG_APPEND=exports.WASI_FILETYPE_SYMBOLIC_LINK=exports.WASI_FILETYPE_SOCKET_STREAM=exports.WASI_FILETYPE_SOCKET_DGRAM=exports.WASI_FILETYPE_REGULAR_FILE=exports.WASI_FILETYPE_DIRECTORY=exports.WASI_FILETYPE_CHARACTER_DEVICE=exports.WASI_FILETYPE_BLOCK_DEVICE=exports.WASI_FILETYPE_UNKNOWN=exports.WASI_SIGXFSZ=exports.WASI_SIGXCPU=void 0,exports.SIGNAL_MAP=exports.ERROR_MAP=exports.WASI_WHENCE_END=exports.WASI_WHENCE_CUR=exports.WASI_WHENCE_SET=exports.WASI_STDERR_FILENO=exports.WASI_STDOUT_FILENO=exports.WASI_STDIN_FILENO=exports.WASI_DIRCOOKIE_START=exports.WASI_PREOPENTYPE_DIR=exports.WASI_O_TRUNC=exports.WASI_O_EXCL=exports.WASI_O_DIRECTORY=exports.WASI_O_CREAT=exports.WASI_FILESTAT_SET_MTIM_NOW=exports.WASI_FILESTAT_SET_MTIM=exports.WASI_FILESTAT_SET_ATIM_NOW=exports.WASI_FILESTAT_SET_ATIM=exports.WASI_EVENTTYPE_FD_WRITE=exports.WASI_EVENTTYPE_FD_READ=exports.WASI_EVENTTYPE_CLOCK=exports.WASI_CLOCK_THREAD_CPUTIME_ID=exports.WASI_CLOCK_PROCESS_CPUTIME_ID=exports.WASI_CLOCK_MONOTONIC=exports.WASI_CLOCK_REALTIME=exports.RIGHTS_TTY_INHERITING=exports.RIGHTS_TTY_BASE=exports.RIGHTS_SOCKET_INHERITING=exports.RIGHTS_SOCKET_BASE=exports.RIGHTS_DIRECTORY_INHERITING=exports.RIGHTS_DIRECTORY_BASE=exports.RIGHTS_REGULAR_FILE_INHERITING=void 0,exports.WASI_ESUCCESS=0,exports.WASI_E2BIG=1,exports.WASI_EACCES=2,exports.WASI_EADDRINUSE=3,exports.WASI_EADDRNOTAVAIL=4,exports.WASI_EAFNOSUPPORT=5,exports.WASI_EAGAIN=6,exports.WASI_EALREADY=7,exports.WASI_EBADF=8,exports.WASI_EBADMSG=9,exports.WASI_EBUSY=10,exports.WASI_ECANCELED=11,exports.WASI_ECHILD=12,exports.WASI_ECONNABORTED=13,exports.WASI_ECONNREFUSED=14,exports.WASI_ECONNRESET=15,exports.WASI_EDEADLK=16,exports.WASI_EDESTADDRREQ=17,exports.WASI_EDOM=18,exports.WASI_EDQUOT=19,exports.WASI_EEXIST=20,exports.WASI_EFAULT=21,exports.WASI_EFBIG=22,exports.WASI_EHOSTUNREACH=23,exports.WASI_EIDRM=24,exports.WASI_EILSEQ=25,exports.WASI_EINPROGRESS=26,exports.WASI_EINTR=27,exports.WASI_EINVAL=28,exports.WASI_EIO=29,exports.WASI_EISCONN=30,exports.WASI_EISDIR=31,exports.WASI_ELOOP=32,exports.WASI_EMFILE=33,exports.WASI_EMLINK=34,exports.WASI_EMSGSIZE=35,exports.WASI_EMULTIHOP=36,exports.WASI_ENAMETOOLONG=37,exports.WASI_ENETDOWN=38,exports.WASI_ENETRESET=39,exports.WASI_ENETUNREACH=40,exports.WASI_ENFILE=41,exports.WASI_ENOBUFS=42,exports.WASI_ENODEV=43,exports.WASI_ENOENT=44,exports.WASI_ENOEXEC=45,exports.WASI_ENOLCK=46,exports.WASI_ENOLINK=47,exports.WASI_ENOMEM=48,exports.WASI_ENOMSG=49,exports.WASI_ENOPROTOOPT=50,exports.WASI_ENOSPC=51,exports.WASI_ENOSYS=52,exports.WASI_ENOTCONN=53,exports.WASI_ENOTDIR=54,exports.WASI_ENOTEMPTY=55,exports.WASI_ENOTRECOVERABLE=56,exports.WASI_ENOTSOCK=57,exports.WASI_ENOTSUP=58,exports.WASI_ENOTTY=59,exports.WASI_ENXIO=60,exports.WASI_EOVERFLOW=61,exports.WASI_EOWNERDEAD=62,exports.WASI_EPERM=63,exports.WASI_EPIPE=64,exports.WASI_EPROTO=65,exports.WASI_EPROTONOSUPPORT=66,exports.WASI_EPROTOTYPE=67,exports.WASI_ERANGE=68,exports.WASI_EROFS=69,exports.WASI_ESPIPE=70,exports.WASI_ESRCH=71,exports.WASI_ESTALE=72,exports.WASI_ETIMEDOUT=73,exports.WASI_ETXTBSY=74,exports.WASI_EXDEV=75,exports.WASI_ENOTCAPABLE=76,exports.WASI_SIGABRT=0,exports.WASI_SIGALRM=1,exports.WASI_SIGBUS=2,exports.WASI_SIGCHLD=3,exports.WASI_SIGCONT=4,exports.WASI_SIGFPE=5,exports.WASI_SIGHUP=6,exports.WASI_SIGILL=7,exports.WASI_SIGINT=8,exports.WASI_SIGKILL=9,exports.WASI_SIGPIPE=10,exports.WASI_SIGQUIT=11,exports.WASI_SIGSEGV=12,exports.WASI_SIGSTOP=13,exports.WASI_SIGTERM=14,exports.WASI_SIGTRAP=15,exports.WASI_SIGTSTP=16,exports.WASI_SIGTTIN=17,exports.WASI_SIGTTOU=18,exports.WASI_SIGURG=19,exports.WASI_SIGUSR1=20,exports.WASI_SIGUSR2=21,exports.WASI_SIGVTALRM=22,exports.WASI_SIGXCPU=23,exports.WASI_SIGXFSZ=24,exports.WASI_FILETYPE_UNKNOWN=0,exports.WASI_FILETYPE_BLOCK_DEVICE=1,exports.WASI_FILETYPE_CHARACTER_DEVICE=2,exports.WASI_FILETYPE_DIRECTORY=3,exports.WASI_FILETYPE_REGULAR_FILE=4,exports.WASI_FILETYPE_SOCKET_DGRAM=5,exports.WASI_FILETYPE_SOCKET_STREAM=6,exports.WASI_FILETYPE_SYMBOLIC_LINK=7,exports.WASI_FDFLAG_APPEND=1,exports.WASI_FDFLAG_DSYNC=2,exports.WASI_FDFLAG_NONBLOCK=4,exports.WASI_FDFLAG_RSYNC=8,exports.WASI_FDFLAG_SYNC=16,exports.WASI_RIGHT_FD_DATASYNC=BigInt(1),exports.WASI_RIGHT_FD_READ=BigInt(2),exports.WASI_RIGHT_FD_SEEK=BigInt(4),exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS=BigInt(8),exports.WASI_RIGHT_FD_SYNC=BigInt(16),exports.WASI_RIGHT_FD_TELL=BigInt(32),exports.WASI_RIGHT_FD_WRITE=BigInt(64),exports.WASI_RIGHT_FD_ADVISE=BigInt(128),exports.WASI_RIGHT_FD_ALLOCATE=BigInt(256),exports.WASI_RIGHT_PATH_CREATE_DIRECTORY=BigInt(512),exports.WASI_RIGHT_PATH_CREATE_FILE=BigInt(1024),exports.WASI_RIGHT_PATH_LINK_SOURCE=BigInt(2048),exports.WASI_RIGHT_PATH_LINK_TARGET=BigInt(4096),exports.WASI_RIGHT_PATH_OPEN=BigInt(8192),exports.WASI_RIGHT_FD_READDIR=BigInt(16384),exports.WASI_RIGHT_PATH_READLINK=BigInt(32768),exports.WASI_RIGHT_PATH_RENAME_SOURCE=BigInt(65536),exports.WASI_RIGHT_PATH_RENAME_TARGET=BigInt(131072),exports.WASI_RIGHT_PATH_FILESTAT_GET=BigInt(262144),exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE=BigInt(524288),exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES=BigInt(1048576),exports.WASI_RIGHT_FD_FILESTAT_GET=BigInt(2097152),exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE=BigInt(4194304),exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES=BigInt(8388608),exports.WASI_RIGHT_PATH_SYMLINK=BigInt(16777216),exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY=BigInt(33554432),exports.WASI_RIGHT_PATH_UNLINK_FILE=BigInt(67108864),exports.WASI_RIGHT_POLL_FD_READWRITE=BigInt(134217728),exports.WASI_RIGHT_SOCK_SHUTDOWN=BigInt(268435456),exports.RIGHTS_ALL=exports.WASI_RIGHT_FD_DATASYNC|exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_SEEK|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_TELL|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_FD_ALLOCATE|exports.WASI_RIGHT_PATH_CREATE_DIRECTORY|exports.WASI_RIGHT_PATH_CREATE_FILE|exports.WASI_RIGHT_PATH_LINK_SOURCE|exports.WASI_RIGHT_PATH_LINK_TARGET|exports.WASI_RIGHT_PATH_OPEN|exports.WASI_RIGHT_FD_READDIR|exports.WASI_RIGHT_PATH_READLINK|exports.WASI_RIGHT_PATH_RENAME_SOURCE|exports.WASI_RIGHT_PATH_RENAME_TARGET|exports.WASI_RIGHT_PATH_FILESTAT_GET|exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_SYMLINK|exports.WASI_RIGHT_PATH_UNLINK_FILE|exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY|exports.WASI_RIGHT_POLL_FD_READWRITE|exports.WASI_RIGHT_SOCK_SHUTDOWN,exports.RIGHTS_BLOCK_DEVICE_BASE=exports.RIGHTS_ALL,exports.RIGHTS_BLOCK_DEVICE_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_CHARACTER_DEVICE_BASE=exports.RIGHTS_ALL,exports.RIGHTS_CHARACTER_DEVICE_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_REGULAR_FILE_BASE=exports.WASI_RIGHT_FD_DATASYNC|exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_SEEK|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_TELL|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_FD_ALLOCATE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_REGULAR_FILE_INHERITING=BigInt(0),exports.RIGHTS_DIRECTORY_BASE=exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_PATH_CREATE_DIRECTORY|exports.WASI_RIGHT_PATH_CREATE_FILE|exports.WASI_RIGHT_PATH_LINK_SOURCE|exports.WASI_RIGHT_PATH_LINK_TARGET|exports.WASI_RIGHT_PATH_OPEN|exports.WASI_RIGHT_FD_READDIR|exports.WASI_RIGHT_PATH_READLINK|exports.WASI_RIGHT_PATH_RENAME_SOURCE|exports.WASI_RIGHT_PATH_RENAME_TARGET|exports.WASI_RIGHT_PATH_FILESTAT_GET|exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_PATH_SYMLINK|exports.WASI_RIGHT_PATH_UNLINK_FILE|exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_DIRECTORY_INHERITING=exports.RIGHTS_DIRECTORY_BASE|exports.RIGHTS_REGULAR_FILE_BASE,exports.RIGHTS_SOCKET_BASE=exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_POLL_FD_READWRITE|exports.WASI_RIGHT_SOCK_SHUTDOWN,exports.RIGHTS_SOCKET_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_TTY_BASE=exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_TTY_INHERITING=BigInt(0),exports.WASI_CLOCK_REALTIME=0,exports.WASI_CLOCK_MONOTONIC=1,exports.WASI_CLOCK_PROCESS_CPUTIME_ID=2,exports.WASI_CLOCK_THREAD_CPUTIME_ID=3,exports.WASI_EVENTTYPE_CLOCK=0,exports.WASI_EVENTTYPE_FD_READ=1,exports.WASI_EVENTTYPE_FD_WRITE=2,exports.WASI_FILESTAT_SET_ATIM=1<<0,exports.WASI_FILESTAT_SET_ATIM_NOW=1<<1,exports.WASI_FILESTAT_SET_MTIM=1<<2,exports.WASI_FILESTAT_SET_MTIM_NOW=1<<3,exports.WASI_O_CREAT=1<<0,exports.WASI_O_DIRECTORY=1<<1,exports.WASI_O_EXCL=1<<2,exports.WASI_O_TRUNC=1<<3,exports.WASI_PREOPENTYPE_DIR=0,exports.WASI_DIRCOOKIE_START=0,exports.WASI_STDIN_FILENO=0,exports.WASI_STDOUT_FILENO=1,exports.WASI_STDERR_FILENO=2,exports.WASI_WHENCE_SET=0,exports.WASI_WHENCE_CUR=1,exports.WASI_WHENCE_END=2,exports.ERROR_MAP={E2BIG:exports.WASI_E2BIG,EACCES:exports.WASI_EACCES,EADDRINUSE:exports.WASI_EADDRINUSE,EADDRNOTAVAIL:exports.WASI_EADDRNOTAVAIL,EAFNOSUPPORT:exports.WASI_EAFNOSUPPORT,EALREADY:exports.WASI_EALREADY,EAGAIN:exports.WASI_EAGAIN,EBADF:exports.WASI_EBADF,EBADMSG:exports.WASI_EBADMSG,EBUSY:exports.WASI_EBUSY,ECANCELED:exports.WASI_ECANCELED,ECHILD:exports.WASI_ECHILD,ECONNABORTED:exports.WASI_ECONNABORTED,ECONNREFUSED:exports.WASI_ECONNREFUSED,ECONNRESET:exports.WASI_ECONNRESET,EDEADLOCK:exports.WASI_EDEADLK,EDESTADDRREQ:exports.WASI_EDESTADDRREQ,EDOM:exports.WASI_EDOM,EDQUOT:exports.WASI_EDQUOT,EEXIST:exports.WASI_EEXIST,EFAULT:exports.WASI_EFAULT,EFBIG:exports.WASI_EFBIG,EHOSTDOWN:exports.WASI_EHOSTUNREACH,EHOSTUNREACH:exports.WASI_EHOSTUNREACH,EIDRM:exports.WASI_EIDRM,EILSEQ:exports.WASI_EILSEQ,EINPROGRESS:exports.WASI_EINPROGRESS,EINTR:exports.WASI_EINTR,EINVAL:exports.WASI_EINVAL,EIO:exports.WASI_EIO,EISCONN:exports.WASI_EISCONN,EISDIR:exports.WASI_EISDIR,ELOOP:exports.WASI_ELOOP,EMFILE:exports.WASI_EMFILE,EMLINK:exports.WASI_EMLINK,EMSGSIZE:exports.WASI_EMSGSIZE,EMULTIHOP:exports.WASI_EMULTIHOP,ENAMETOOLONG:exports.WASI_ENAMETOOLONG,ENETDOWN:exports.WASI_ENETDOWN,ENETRESET:exports.WASI_ENETRESET,ENETUNREACH:exports.WASI_ENETUNREACH,ENFILE:exports.WASI_ENFILE,ENOBUFS:exports.WASI_ENOBUFS,ENODEV:exports.WASI_ENODEV,ENOENT:exports.WASI_ENOENT,ENOEXEC:exports.WASI_ENOEXEC,ENOLCK:exports.WASI_ENOLCK,ENOLINK:exports.WASI_ENOLINK,ENOMEM:exports.WASI_ENOMEM,ENOMSG:exports.WASI_ENOMSG,ENOPROTOOPT:exports.WASI_ENOPROTOOPT,ENOSPC:exports.WASI_ENOSPC,ENOSYS:exports.WASI_ENOSYS,ENOTCONN:exports.WASI_ENOTCONN,ENOTDIR:exports.WASI_ENOTDIR,ENOTEMPTY:exports.WASI_ENOTEMPTY,ENOTRECOVERABLE:exports.WASI_ENOTRECOVERABLE,ENOTSOCK:exports.WASI_ENOTSOCK,ENOTTY:exports.WASI_ENOTTY,ENXIO:exports.WASI_ENXIO,EOVERFLOW:exports.WASI_EOVERFLOW,EOWNERDEAD:exports.WASI_EOWNERDEAD,EPERM:exports.WASI_EPERM,EPIPE:exports.WASI_EPIPE,EPROTO:exports.WASI_EPROTO,EPROTONOSUPPORT:exports.WASI_EPROTONOSUPPORT,EPROTOTYPE:exports.WASI_EPROTOTYPE,ERANGE:exports.WASI_ERANGE,EROFS:exports.WASI_EROFS,ESPIPE:exports.WASI_ESPIPE,ESRCH:exports.WASI_ESRCH,ESTALE:exports.WASI_ESTALE,ETIMEDOUT:exports.WASI_ETIMEDOUT,ETXTBSY:exports.WASI_ETXTBSY,EXDEV:exports.WASI_EXDEV},exports.SIGNAL_MAP={[exports.WASI_SIGHUP]:\"SIGHUP\",[exports.WASI_SIGINT]:\"SIGINT\",[exports.WASI_SIGQUIT]:\"SIGQUIT\",[exports.WASI_SIGILL]:\"SIGILL\",[exports.WASI_SIGTRAP]:\"SIGTRAP\",[exports.WASI_SIGABRT]:\"SIGABRT\",[exports.WASI_SIGBUS]:\"SIGBUS\",[exports.WASI_SIGFPE]:\"SIGFPE\",[exports.WASI_SIGKILL]:\"SIGKILL\",[exports.WASI_SIGUSR1]:\"SIGUSR1\",[exports.WASI_SIGSEGV]:\"SIGSEGV\",[exports.WASI_SIGUSR2]:\"SIGUSR2\",[exports.WASI_SIGPIPE]:\"SIGPIPE\",[exports.WASI_SIGALRM]:\"SIGALRM\",[exports.WASI_SIGTERM]:\"SIGTERM\",[exports.WASI_SIGCHLD]:\"SIGCHLD\",[exports.WASI_SIGCONT]:\"SIGCONT\",[exports.WASI_SIGSTOP]:\"SIGSTOP\",[exports.WASI_SIGTSTP]:\"SIGTSTP\",[exports.WASI_SIGTTIN]:\"SIGTTIN\",[exports.WASI_SIGTTOU]:\"SIGTTOU\",[exports.WASI_SIGURG]:\"SIGURG\",[exports.WASI_SIGXCPU]:\"SIGXCPU\",[exports.WASI_SIGXFSZ]:\"SIGXFSZ\",[exports.WASI_SIGVTALRM]:\"SIGVTALRM\"}}}),require_wasi=__commonJS({\"node_modules/wasi-js/dist/wasi.js\"(exports){var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule\?mod:{default:mod}};let fs;Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.SOCKET_DEFAULT_RIGHTS=void 0;var log=()=>{},logOpen=()=>{},SC_OPEN_MAX=32768,types_1=require_types(),constants_1=require_constants(),STDIN_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_SYNC|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE,STDOUT_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_SYNC|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE,STDERR_DEFAULT_RIGHTS=STDOUT_DEFAULT_RIGHTS;exports.SOCKET_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE|constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS;var msToNs=(ms)=>{const msInt=Math.trunc(ms),decimal=BigInt(Math.round((ms-msInt)*1e6));return BigInt(msInt)*BigInt(1e6)+decimal},nsToMs=(ns)=>{if(typeof ns===\"number\")ns=Math.trunc(ns);const nsInt=BigInt(ns);return Number(nsInt/BigInt(1e6))},wrap=(f)=>(...args)=>{try{return f(...args)}catch(err){let e=err;while(e.prev!=null)e=e.prev;if(e\?.code&&typeof e\?.code===\"string\")return constants_1.ERROR_MAP[e.code]||constants_1.WASI_EINVAL;if(e instanceof types_1.WASIError)return e.errno;throw e}},stat=(wasi,fd)=>{const entry=wasi.FD_MAP.get(fd);if(!entry)throw new types_1.WASIError(constants_1.WASI_EBADF);if(entry.filetype===void 0){const stats=wasi.fstatSync(entry.real),{filetype,rightsBase,rightsInheriting}=translateFileAttributes(wasi,fd,stats);if(entry.filetype=filetype,!entry.rights)entry.rights={base:rightsBase,inheriting:rightsInheriting}}return entry},translateFileAttributes=(wasi,fd,stats)=>{switch(!0){case stats.isBlockDevice():return{filetype:constants_1.WASI_FILETYPE_BLOCK_DEVICE,rightsBase:constants_1.RIGHTS_BLOCK_DEVICE_BASE,rightsInheriting:constants_1.RIGHTS_BLOCK_DEVICE_INHERITING};case stats.isCharacterDevice():{const filetype=constants_1.WASI_FILETYPE_CHARACTER_DEVICE;if(fd!==void 0&&wasi.bindings.isTTY(fd))return{filetype,rightsBase:constants_1.RIGHTS_TTY_BASE,rightsInheriting:constants_1.RIGHTS_TTY_INHERITING};return{filetype,rightsBase:constants_1.RIGHTS_CHARACTER_DEVICE_BASE,rightsInheriting:constants_1.RIGHTS_CHARACTER_DEVICE_INHERITING}}case stats.isDirectory():return{filetype:constants_1.WASI_FILETYPE_DIRECTORY,rightsBase:constants_1.RIGHTS_DIRECTORY_BASE,rightsInheriting:constants_1.RIGHTS_DIRECTORY_INHERITING};case stats.isFIFO():return{filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rightsBase:constants_1.RIGHTS_SOCKET_BASE,rightsInheriting:constants_1.RIGHTS_SOCKET_INHERITING};case stats.isFile():return{filetype:constants_1.WASI_FILETYPE_REGULAR_FILE,rightsBase:constants_1.RIGHTS_REGULAR_FILE_BASE,rightsInheriting:constants_1.RIGHTS_REGULAR_FILE_INHERITING};case stats.isSocket():return{filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rightsBase:constants_1.RIGHTS_SOCKET_BASE,rightsInheriting:constants_1.RIGHTS_SOCKET_INHERITING};case stats.isSymbolicLink():return{filetype:constants_1.WASI_FILETYPE_SYMBOLIC_LINK,rightsBase:BigInt(0),rightsInheriting:BigInt(0)};default:return{filetype:constants_1.WASI_FILETYPE_UNKNOWN,rightsBase:BigInt(0),rightsInheriting:BigInt(0)}}},warnedAboutSleep=!1,defaultConfig;function getDefaults(){if(defaultConfig)return defaultConfig;const defaultBindings={hrtime:()=>process.hrtime.bigint(),exit:(code)=>{process.exit(code)},kill:(signal)=>{process.kill(process.pid,signal)},randomFillSync:(array)=>crypto.getRandomValues(array),isTTY:(fd)=>@requireNativeModule(\"node:tty\").isatty(fd),fs:Bun.fs(),path:@getInternalField(@internalModuleRegistry,25)||@createInternalModuleById(25)};return defaultConfig={args:[],env:{},preopens:{},bindings:defaultBindings,sleep:(ms)=>{Bun.sleepSync(ms)}}}var WASI=class WASI2{constructor(wasiConfig={}){const defaultConfig2=getDefaults();this.lastStdin=0,this.sleep=wasiConfig.sleep||defaultConfig2.sleep,this.getStdin=wasiConfig.getStdin,this.sendStdout=wasiConfig.sendStdout,this.sendStderr=wasiConfig.sendStderr;let preopens=wasiConfig.preopens\?\?defaultConfig2.preopens;this.env=wasiConfig.env\?\?defaultConfig2.env;const args=wasiConfig.args\?\?defaultConfig2.args;this.memory=void 0,this.view=void 0,this.bindings=wasiConfig.bindings||defaultConfig2.bindings;const bindings2=this.bindings;fs=bindings2.fs,this.FD_MAP=new Map([[constants_1.WASI_STDIN_FILENO,{real:0,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDIN_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stdin\"}],[constants_1.WASI_STDOUT_FILENO,{real:1,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDOUT_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stdout\"}],[constants_1.WASI_STDERR_FILENO,{real:2,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDERR_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stderr\"}]]);const path=bindings2.path;for(let[k,v]of Object.entries(preopens)){const real=fs.openSync(v,nodeFsConstants.O_RDONLY),newfd=this.getUnusedFileDescriptor();this.FD_MAP.set(newfd,{real,filetype:constants_1.WASI_FILETYPE_DIRECTORY,rights:{base:constants_1.RIGHTS_DIRECTORY_BASE,inheriting:constants_1.RIGHTS_DIRECTORY_INHERITING},fakePath:k,path:v})}const getiovs=(iovs,iovsLen)=>{this.refreshMemory();const{view,memory}=this,{buffer}=memory,{byteLength}=buffer;if(iovsLen===1){const ptr=iovs,buf=view.getUint32(ptr,!0);let bufLen=view.getUint32(ptr+4,!0);if(bufLen>byteLength-buf)console.log({buf,bufLen,total_memory:byteLength}),log(\"getiovs: warning -- truncating buffer to fit in memory\"),bufLen=Math.min(bufLen,Math.max(0,byteLength-buf));try{return[new Uint8Array(buffer,buf,bufLen)]}catch(err){throw console.warn(\"WASI.getiovs -- invalid buffer\",err),new types_1.WASIError(constants_1.WASI_EINVAL)}}const buffers=[];buffers.length=iovsLen;for(let i=0,ptr=iovs;ibyteLength-buf)console.log({buf,bufLen,total_memory:byteLength}),log(\"getiovs: warning -- truncating buffer to fit in memory\"),bufLen=Math.min(bufLen,Math.max(0,byteLength-buf));try{buffers[i]=new Uint8Array(buffer,buf,bufLen)}catch(err){throw console.warn(\"WASI.getiovs -- invalid buffer\",err),new types_1.WASIError(constants_1.WASI_EINVAL)}}return buffers},CHECK_FD=(fd,rights)=>{const stats=stat(this,fd);if(rights!==BigInt(0)&&(stats.rights.base&rights)===BigInt(0))throw new types_1.WASIError(constants_1.WASI_EPERM);return stats},CPUTIME_START=Bun.nanoseconds(),timeOrigin=Math.trunc(performance.timeOrigin*1e6),now=(clockId)=>{switch(clockId){case constants_1.WASI_CLOCK_MONOTONIC:return Bun.nanoseconds();case constants_1.WASI_CLOCK_REALTIME:return Bun.nanoseconds()+timeOrigin;case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID:case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID:return Bun.nanoseconds()-CPUTIME_START;default:return null}};if(this.wasiImport={args_get:(argv,argvBuf)=>{this.refreshMemory();let coffset=argv,offset=argvBuf;return args.forEach((a)=>{this.view.setUint32(coffset,offset,!0),coffset+=4,offset+=Buffer.from(this.memory.buffer).write(`${a}\\0`,offset)}),constants_1.WASI_ESUCCESS},args_sizes_get:(argc,argvBufSize)=>{this.refreshMemory(),this.view.setUint32(argc,args.length,!0);const size=args.reduce((acc,a)=>acc+Buffer.byteLength(a)+1,0);return this.view.setUint32(argvBufSize,size,!0),constants_1.WASI_ESUCCESS},environ_get:(environ,environBuf)=>{this.refreshMemory();let coffset=environ,offset=environBuf;return Object.entries(this.env).forEach(([key,value])=>{this.view.setUint32(coffset,offset,!0),coffset+=4,offset+=Buffer.from(this.memory.buffer).write(`${key}=${value}\\0`,offset)}),constants_1.WASI_ESUCCESS},environ_sizes_get:(environCount,environBufSize)=>{this.refreshMemory();const envProcessed=Object.entries(this.env).map(([key,value])=>`${key}=${value}\\0`),size=envProcessed.reduce((acc,e)=>acc+Buffer.byteLength(e),0);return this.view.setUint32(environCount,envProcessed.length,!0),this.view.setUint32(environBufSize,size,!0),constants_1.WASI_ESUCCESS},clock_res_get:(clockId,resolution)=>{let res;switch(clockId){case constants_1.WASI_CLOCK_MONOTONIC:case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID:case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID:{res=BigInt(1);break}case constants_1.WASI_CLOCK_REALTIME:{res=BigInt(1000);break}}if(!res)throw Error(\"invalid clockId\");return this.view.setBigUint64(resolution,res),constants_1.WASI_ESUCCESS},clock_time_get:(clockId,_precision,time)=>{this.refreshMemory();const n=now(clockId);if(n===null)return constants_1.WASI_EINVAL;return this.view.setBigUint64(time,BigInt(n),!0),constants_1.WASI_ESUCCESS},fd_advise:wrap((fd,_offset,_len,_advice)=>{return CHECK_FD(fd,constants_1.WASI_RIGHT_FD_ADVISE),constants_1.WASI_ENOSYS}),fd_allocate:wrap((fd,_offset,_len)=>{return CHECK_FD(fd,constants_1.WASI_RIGHT_FD_ALLOCATE),constants_1.WASI_ENOSYS}),fd_close:wrap((fd)=>{const stats=CHECK_FD(fd,BigInt(0));return fs.closeSync(stats.real),this.FD_MAP.delete(fd),constants_1.WASI_ESUCCESS}),fd_datasync:wrap((fd)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_DATASYNC);return fs.fdatasyncSync(stats.real),constants_1.WASI_ESUCCESS}),fd_fdstat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,BigInt(0));if(this.refreshMemory(),stats.filetype==null)throw Error(\"stats.filetype must be set\");return this.view.setUint8(bufPtr,stats.filetype),this.view.setUint16(bufPtr+2,0,!0),this.view.setUint16(bufPtr+4,0,!0),this.view.setBigUint64(bufPtr+8,BigInt(stats.rights.base),!0),this.view.setBigUint64(bufPtr+8+8,BigInt(stats.rights.inheriting),!0),constants_1.WASI_ESUCCESS}),fd_fdstat_set_flags:wrap((fd,flags)=>{if(CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS),this.wasiImport.sock_fcntlSetFlags(fd,flags)==0)return constants_1.WASI_ESUCCESS;return constants_1.WASI_ENOSYS}),fd_fdstat_set_rights:wrap((fd,fsRightsBase,fsRightsInheriting)=>{const stats=CHECK_FD(fd,BigInt(0));if((stats.rights.base|fsRightsBase)>stats.rights.base)return constants_1.WASI_EPERM;if((stats.rights.inheriting|fsRightsInheriting)>stats.rights.inheriting)return constants_1.WASI_EPERM;return stats.rights.base=fsRightsBase,stats.rights.inheriting=fsRightsInheriting,constants_1.WASI_ESUCCESS}),fd_filestat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_GET),rstats=this.fstatSync(stats.real);if(this.refreshMemory(),this.view.setBigUint64(bufPtr,BigInt(rstats.dev),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,stats.filetype==null)throw Error(\"stats.filetype must be set\");return this.view.setUint8(bufPtr,stats.filetype),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.nlink),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.size),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.atimeMs),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.mtimeMs),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.ctimeMs),!0),constants_1.WASI_ESUCCESS}),fd_filestat_set_size:wrap((fd,stSize)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE);return fs.ftruncateSync(stats.real,Number(stSize)),constants_1.WASI_ESUCCESS}),fd_filestat_set_times:wrap((fd,stAtim,stMtim,fstflags)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_SET_TIMES),rstats=this.fstatSync(stats.real);let{atime:atim,mtime:mtim}=rstats;const n=nsToMs(now(constants_1.WASI_CLOCK_REALTIME)),atimflags=constants_1.WASI_FILESTAT_SET_ATIM|constants_1.WASI_FILESTAT_SET_ATIM_NOW;if((fstflags&atimflags)===atimflags)return constants_1.WASI_EINVAL;const mtimflags=constants_1.WASI_FILESTAT_SET_MTIM|constants_1.WASI_FILESTAT_SET_MTIM_NOW;if((fstflags&mtimflags)===mtimflags)return constants_1.WASI_EINVAL;if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM)===constants_1.WASI_FILESTAT_SET_ATIM)atim=nsToMs(stAtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM_NOW)===constants_1.WASI_FILESTAT_SET_ATIM_NOW)atim=n;if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM)===constants_1.WASI_FILESTAT_SET_MTIM)mtim=nsToMs(stMtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM_NOW)===constants_1.WASI_FILESTAT_SET_MTIM_NOW)mtim=n;return fs.futimesSync(stats.real,new Date(atim),new Date(mtim)),constants_1.WASI_ESUCCESS}),fd_prestat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,BigInt(0));return this.refreshMemory(),this.view.setUint8(bufPtr,constants_1.WASI_PREOPENTYPE_DIR),this.view.setUint32(bufPtr+4,Buffer.byteLength(stats.fakePath\?\?stats.path\?\?\"\"),!0),constants_1.WASI_ESUCCESS}),fd_prestat_dir_name:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,BigInt(0));return this.refreshMemory(),Buffer.from(this.memory.buffer).write(stats.fakePath\?\?stats.path\?\?\"\",pathPtr,pathLen,\"utf8\"),constants_1.WASI_ESUCCESS}),fd_pwrite:wrap((fd,iovs,iovsLen,offset,nwritten)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_SEEK);let written=0;return getiovs(iovs,iovsLen).forEach((iov)=>{let w=0;while(w{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_WRITE),IS_STDOUT=fd==constants_1.WASI_STDOUT_FILENO,IS_STDERR=fd==constants_1.WASI_STDERR_FILENO;let written=0;return getiovs(iovs,iovsLen).forEach((iov)=>{if(iov.byteLength==0)return;if(IS_STDOUT&&this.sendStdout!=null)this.sendStdout(iov),written+=iov.byteLength;else if(IS_STDERR&&this.sendStderr!=null)this.sendStderr(iov),written+=iov.byteLength;else{let w=0;while(w{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_SEEK);let read=0;outer:for(let iov of getiovs(iovs,iovsLen)){let r=0;while(r{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READ),IS_STDIN=fd==constants_1.WASI_STDIN_FILENO;let read=0;outer:for(let iov of getiovs(iovs,iovsLen)){let r=0;while(r0)this.lastStdin=(new Date()).valueOf()}}else{if(this.sleep==null&&!warnedAboutSleep)warnedAboutSleep=!0,console.log(\"(cpu waiting for stdin: please define a way to sleep!) \");try{rr=fs.readSync(stats.real,iov,r,length,position)}catch(_err){}if(rr==0)this.shortPause();else this.lastStdin=(new Date()).valueOf()}else rr=fs.readSync(stats.real,iov,r,length,position);if(stats.filetype==constants_1.WASI_FILETYPE_REGULAR_FILE)stats.offset=(stats.offset\?stats.offset:BigInt(0))+BigInt(rr);if(r+=rr,read+=rr,rr===0||rr{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READDIR);this.refreshMemory();const entries=fs.readdirSync(stats.path,{withFileTypes:!0}),startPtr=bufPtr;for(let i=Number(cookie);ibufLen)break;if(this.view.setBigUint64(bufPtr,BigInt(i+1),!0),bufPtr+=8,bufPtr-startPtr>bufLen)break;const rstats=fs.lstatSync(path.resolve(stats.path,entry.name));if(this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,bufPtr-startPtr>bufLen)break;if(this.view.setUint32(bufPtr,nameLength,!0),bufPtr+=4,bufPtr-startPtr>bufLen)break;let filetype;switch(!0){case rstats.isBlockDevice():filetype=constants_1.WASI_FILETYPE_BLOCK_DEVICE;break;case rstats.isCharacterDevice():filetype=constants_1.WASI_FILETYPE_CHARACTER_DEVICE;break;case rstats.isDirectory():filetype=constants_1.WASI_FILETYPE_DIRECTORY;break;case rstats.isFIFO():filetype=constants_1.WASI_FILETYPE_SOCKET_STREAM;break;case rstats.isFile():filetype=constants_1.WASI_FILETYPE_REGULAR_FILE;break;case rstats.isSocket():filetype=constants_1.WASI_FILETYPE_SOCKET_STREAM;break;case rstats.isSymbolicLink():filetype=constants_1.WASI_FILETYPE_SYMBOLIC_LINK;break;default:filetype=constants_1.WASI_FILETYPE_UNKNOWN;break}if(this.view.setUint8(bufPtr,filetype),bufPtr+=1,bufPtr+=3,bufPtr+nameLength>=startPtr+bufLen)break;Buffer.from(this.memory.buffer).write(entry.name,bufPtr),bufPtr+=nameLength}const bufused=bufPtr-startPtr;return this.view.setUint32(bufusedPtr,Math.min(bufused,bufLen),!0),constants_1.WASI_ESUCCESS}),fd_renumber:wrap((from,to)=>{return CHECK_FD(from,BigInt(0)),CHECK_FD(to,BigInt(0)),fs.closeSync(this.FD_MAP.get(from).real),this.FD_MAP.set(from,this.FD_MAP.get(to)),this.FD_MAP.delete(to),constants_1.WASI_ESUCCESS}),fd_seek:wrap((fd,offset,whence,newOffsetPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_SEEK);switch(this.refreshMemory(),whence){case constants_1.WASI_WHENCE_CUR:stats.offset=(stats.offset\?stats.offset:BigInt(0))+BigInt(offset);break;case constants_1.WASI_WHENCE_END:const{size}=this.fstatSync(stats.real);stats.offset=BigInt(size)+BigInt(offset);break;case constants_1.WASI_WHENCE_SET:stats.offset=BigInt(offset);break}if(stats.offset==null)throw Error(\"stats.offset must be defined\");return this.view.setBigUint64(newOffsetPtr,stats.offset,!0),constants_1.WASI_ESUCCESS}),fd_tell:wrap((fd,offsetPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_TELL);if(this.refreshMemory(),!stats.offset)stats.offset=BigInt(0);return this.view.setBigUint64(offsetPtr,stats.offset,!0),constants_1.WASI_ESUCCESS}),fd_sync:wrap((fd)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_SYNC);return fs.fsyncSync(stats.real),constants_1.WASI_ESUCCESS}),path_create_directory:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_CREATE_DIRECTORY);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.mkdirSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),path_filestat_get:wrap((fd,flags,pathPtr,pathLen,bufPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_FILESTAT_GET);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();let rstats;if(flags)rstats=fs.statSync(path.resolve(stats.path,p));else rstats=fs.lstatSync(path.resolve(stats.path,p));return this.view.setBigUint64(bufPtr,BigInt(rstats.dev),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,this.view.setUint8(bufPtr,translateFileAttributes(this,void 0,rstats).filetype),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.nlink),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.size),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.atime.getTime()*1e6),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.mtime.getTime()*1e6),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ctime.getTime()*1e6),!0),constants_1.WASI_ESUCCESS}),path_filestat_set_times:wrap((fd,_dirflags,pathPtr,pathLen,stAtim,stMtim,fstflags)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_FILESTAT_SET_TIMES);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const rstats=this.fstatSync(stats.real);let{atime:atim,mtime:mtim}=rstats;const n=nsToMs(now(constants_1.WASI_CLOCK_REALTIME)),atimflags=constants_1.WASI_FILESTAT_SET_ATIM|constants_1.WASI_FILESTAT_SET_ATIM_NOW;if((fstflags&atimflags)===atimflags)return constants_1.WASI_EINVAL;const mtimflags=constants_1.WASI_FILESTAT_SET_MTIM|constants_1.WASI_FILESTAT_SET_MTIM_NOW;if((fstflags&mtimflags)===mtimflags)return constants_1.WASI_EINVAL;if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM)===constants_1.WASI_FILESTAT_SET_ATIM)atim=nsToMs(stAtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM_NOW)===constants_1.WASI_FILESTAT_SET_ATIM_NOW)atim=n;if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM)===constants_1.WASI_FILESTAT_SET_MTIM)mtim=nsToMs(stMtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM_NOW)===constants_1.WASI_FILESTAT_SET_MTIM_NOW)mtim=n;const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.utimesSync(path.resolve(stats.path,p),new Date(atim),new Date(mtim)),constants_1.WASI_ESUCCESS}),path_link:wrap((oldFd,_oldFlags,oldPath,oldPathLen,newFd,newPath,newPathLen)=>{const ostats=CHECK_FD(oldFd,constants_1.WASI_RIGHT_PATH_LINK_SOURCE),nstats=CHECK_FD(newFd,constants_1.WASI_RIGHT_PATH_LINK_TARGET);if(!ostats.path||!nstats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.linkSync(path.resolve(ostats.path,op),path.resolve(nstats.path,np)),constants_1.WASI_ESUCCESS}),path_open:wrap((dirfd,_dirflags,pathPtr,pathLen,oflags,fsRightsBase,fsRightsInheriting,fsFlags,fdPtr)=>{try{const stats=CHECK_FD(dirfd,constants_1.WASI_RIGHT_PATH_OPEN);fsRightsBase=BigInt(fsRightsBase),fsRightsInheriting=BigInt(fsRightsInheriting);const read=(fsRightsBase&(constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_READDIR))!==BigInt(0),write=(fsRightsBase&(constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_ALLOCATE|constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE))!==BigInt(0);let noflags;if(write&&read)noflags=nodeFsConstants.O_RDWR;else if(read)noflags=nodeFsConstants.O_RDONLY;else if(write)noflags=nodeFsConstants.O_WRONLY;let neededBase=fsRightsBase|constants_1.WASI_RIGHT_PATH_OPEN,neededInheriting=fsRightsBase|fsRightsInheriting;if((oflags&constants_1.WASI_O_CREAT)!==0)noflags|=nodeFsConstants.O_CREAT,neededBase|=constants_1.WASI_RIGHT_PATH_CREATE_FILE;if((oflags&constants_1.WASI_O_DIRECTORY)!==0)noflags|=nodeFsConstants.O_DIRECTORY;if((oflags&constants_1.WASI_O_EXCL)!==0)noflags|=nodeFsConstants.O_EXCL;if((oflags&constants_1.WASI_O_TRUNC)!==0)noflags|=nodeFsConstants.O_TRUNC,neededBase|=constants_1.WASI_RIGHT_PATH_FILESTAT_SET_SIZE;if((fsFlags&constants_1.WASI_FDFLAG_APPEND)!==0)noflags|=nodeFsConstants.O_APPEND;if((fsFlags&constants_1.WASI_FDFLAG_DSYNC)!==0){if(nodeFsConstants.O_DSYNC)noflags|=nodeFsConstants.O_DSYNC;else noflags|=nodeFsConstants.O_SYNC;neededInheriting|=constants_1.WASI_RIGHT_FD_DATASYNC}if((fsFlags&constants_1.WASI_FDFLAG_NONBLOCK)!==0)noflags|=nodeFsConstants.O_NONBLOCK;if((fsFlags&constants_1.WASI_FDFLAG_RSYNC)!==0){if(nodeFsConstants.O_RSYNC)noflags|=nodeFsConstants.O_RSYNC;else noflags|=nodeFsConstants.O_SYNC;neededInheriting|=constants_1.WASI_RIGHT_FD_SYNC}if((fsFlags&constants_1.WASI_FDFLAG_SYNC)!==0)noflags|=nodeFsConstants.O_SYNC,neededInheriting|=constants_1.WASI_RIGHT_FD_SYNC;if(write&&(noflags&(nodeFsConstants.O_APPEND|nodeFsConstants.O_TRUNC))===0)neededInheriting|=constants_1.WASI_RIGHT_FD_SEEK;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();if(p==\"dev/tty\")return this.view.setUint32(fdPtr,constants_1.WASI_STDIN_FILENO,!0),constants_1.WASI_ESUCCESS;if(logOpen(\"path_open\",p),p.startsWith(\"proc/\"))throw new types_1.WASIError(constants_1.WASI_EBADF);const fullUnresolved=path.resolve(p);let full;try{full=fs.realpathSync(fullUnresolved)}catch(e){if(e\?.code===\"ENOENT\")full=fullUnresolved;else throw e}let isDirectory;if(write)try{isDirectory=fs.statSync(full).isDirectory()}catch(_err){}let realfd;if(!write&&isDirectory)realfd=fs.openSync(full,nodeFsConstants.O_RDONLY);else realfd=fs.openSync(full,noflags);const newfd=this.getUnusedFileDescriptor();this.FD_MAP.set(newfd,{real:realfd,filetype:void 0,rights:{base:neededBase,inheriting:neededInheriting},path:full}),stat(this,newfd),this.view.setUint32(fdPtr,newfd,!0)}catch(e){console.error(e)}return constants_1.WASI_ESUCCESS}),path_readlink:wrap((fd,pathPtr,pathLen,buf,bufLen,bufused)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_READLINK);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString(),full=path.resolve(stats.path,p),r=fs.readlinkSync(full),used=Buffer.from(this.memory.buffer).write(r,buf,bufLen);return this.view.setUint32(bufused,used,!0),constants_1.WASI_ESUCCESS}),path_remove_directory:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_REMOVE_DIRECTORY);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.rmdirSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),path_rename:wrap((oldFd,oldPath,oldPathLen,newFd,newPath,newPathLen)=>{const ostats=CHECK_FD(oldFd,constants_1.WASI_RIGHT_PATH_RENAME_SOURCE),nstats=CHECK_FD(newFd,constants_1.WASI_RIGHT_PATH_RENAME_TARGET);if(!ostats.path||!nstats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.renameSync(path.resolve(ostats.path,op),path.resolve(nstats.path,np)),constants_1.WASI_ESUCCESS}),path_symlink:wrap((oldPath,oldPathLen,fd,newPath,newPathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_SYMLINK);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.symlinkSync(op,path.resolve(stats.path,np)),constants_1.WASI_ESUCCESS}),path_unlink_file:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_UNLINK_FILE);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.unlinkSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),poll_oneoff:(sin,sout,nsubscriptions,neventsPtr)=>{let nevents=0,name=\"\",waitTimeNs=BigInt(0),fd=-1,fd_type=\"read\",fd_timeout_ms=0;const startNs=BigInt(bindings2.hrtime());this.refreshMemory();let last_sin=sin;for(let i=0;iwaitTimeNs)waitTimeNs=waitNs}this.view.setBigUint64(sout,userdata,!0),sout+=8,this.view.setUint16(sout,e,!0),sout+=2,this.view.setUint8(sout,constants_1.WASI_EVENTTYPE_CLOCK),sout+=1,sout+=5,nevents+=1;break}case constants_1.WASI_EVENTTYPE_FD_READ:case constants_1.WASI_EVENTTYPE_FD_WRITE:{if(fd=this.view.getUint32(sin,!0),fd_type=type==constants_1.WASI_EVENTTYPE_FD_READ\?\"read\":\"write\",sin+=4,log(name,\"fd =\",fd),sin+=28,this.view.setBigUint64(sout,userdata,!0),sout+=8,this.view.setUint16(sout,constants_1.WASI_ENOSYS,!0),sout+=2,this.view.setUint8(sout,type),sout+=1,sout+=5,nevents+=1,fd==constants_1.WASI_STDIN_FILENO&&constants_1.WASI_EVENTTYPE_FD_READ==type)this.shortPause();break}default:return constants_1.WASI_EINVAL}if(sin-last_sin!=48)console.warn(\"*** BUG in wasi-js in poll_oneoff \",{i,sin,last_sin,diff:sin-last_sin});last_sin=sin}if(this.view.setUint32(neventsPtr,nevents,!0),nevents==2&&fd>=0){const r=this.wasiImport.sock_pollSocket(fd,fd_type,fd_timeout_ms);if(r!=constants_1.WASI_ENOSYS)return r}if(waitTimeNs>0){if(waitTimeNs-=Bun.nanoseconds()-timeOrigin,waitTimeNs>=1e6){if(this.sleep==null&&!warnedAboutSleep)warnedAboutSleep=!0,console.log(\"(100% cpu burning waiting for stdin: please define a way to sleep!) \");if(this.sleep!=null){const ms=nsToMs(waitTimeNs);this.sleep(ms)}else{const end=BigInt(bindings2.hrtime())+waitTimeNs;while(BigInt(bindings2.hrtime()){return bindings2.exit(rval),constants_1.WASI_ESUCCESS},proc_raise:(sig)=>{if(!(sig in constants_1.SIGNAL_MAP))return constants_1.WASI_EINVAL;return bindings2.kill(constants_1.SIGNAL_MAP[sig]),constants_1.WASI_ESUCCESS},random_get:(bufPtr,bufLen)=>{return this.refreshMemory(),crypto.getRandomValues(this.memory.buffer,bufPtr,bufLen),bufLen},sched_yield(){return constants_1.WASI_ESUCCESS},sock_recv(){return constants_1.WASI_ENOSYS},sock_send(){return constants_1.WASI_ENOSYS},sock_shutdown(){return constants_1.WASI_ENOSYS},sock_fcntlSetFlags(_fd,_flags){return constants_1.WASI_ENOSYS},sock_pollSocket(_fd,_eventtype,_timeout_ms){return constants_1.WASI_ENOSYS}},log.enabled)Object.keys(this.wasiImport).forEach((key)=>{const prevImport=this.wasiImport[key];this.wasiImport[key]=function(...args2){log(key,args2);try{let result=prevImport(...args2);return log(\"result\",result),result}catch(e){throw log(\"error: \",e),e}}})}getState(){return{env:this.env,FD_MAP:this.FD_MAP,bindings}}setState(state){this.env=state.env,this.FD_MAP=state.FD_MAP,bindings=state.bindings}fstatSync(real_fd){if(real_fd<=2)try{return fs.fstatSync(real_fd)}catch(_){const now=new Date;return{dev:0,mode:8592,nlink:1,uid:0,gid:0,rdev:0,blksize:65536,ino:0,size:0,blocks:0,atimeMs:now.valueOf(),mtimeMs:now.valueOf(),ctimeMs:now.valueOf(),birthtimeMs:0,atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date(0)}}return fs.fstatSync(real_fd)}shortPause(){if(this.sleep==null)return;if((new Date()).valueOf()-this.lastStdin>2000)this.sleep(50)}getUnusedFileDescriptor(start=3){let fd=start;while(this.FD_MAP.has(fd))fd+=1;if(fd>SC_OPEN_MAX)throw Error(\"no available file descriptors\");return fd}refreshMemory(){if(!this.view||this.view.buffer.byteLength===0)this.view=new DataView(this.memory.buffer)}setMemory(memory){this.memory=memory}start(instance,memory){const exports2=instance.exports;if(exports2===null||typeof exports2!==\"object\")throw new Error(`instance.exports must be an Object. Received ${exports2}.`);if(memory==null){if(memory=exports2.memory,!(memory instanceof WebAssembly.Memory))throw new Error(`instance.exports.memory must be a WebAssembly.Memory. Recceived ${memory}.`)}if(this.setMemory(memory),exports2._start)exports2._start()}getImports(module2){let namespace=null;const imports=WebAssembly.Module.imports(module2);for(let imp of imports){if(imp.kind!==\"function\")continue;if(!imp.module.startsWith(\"wasi_\"))continue;namespace=imp.module;break}switch(namespace){case\"wasi_unstable\":return{wasi_unstable:this.wasiImport};case\"wasi_snapshot_preview1\":return{wasi_snapshot_preview1:this.wasiImport};default:throw new Error(\"No WASI namespace found. Only wasi_unstable and wasi_snapshot_preview1 are supported.\\n\\nList of imports:\\n\\n\"+imports.map(({name,kind,module})=>`${module}:${name} (${kind})`).join(\"\\n\")+\"\\n\")}}initWasiFdInfo(){if(this.env.WASI_FD_INFO!=null){const fdInfo=JSON.parse(this.env.WASI_FD_INFO);for(let wasi_fd in fdInfo){console.log(wasi_fd);const fd=parseInt(wasi_fd);if(this.FD_MAP.has(fd))continue;const real=fdInfo[wasi_fd];try{this.fstatSync(real)}catch(_err){console.log(\"discarding \",{wasi_fd,real});continue}const file={real,filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rights:{base:STDIN_DEFAULT_RIGHTS,inheriting:BigInt(0)}};this.FD_MAP.set(fd,file)}console.log(\"after initWasiFdInfo: \",this.FD_MAP),console.log(\"fdInfo = \",fdInfo)}else console.log(\"no WASI_FD_INFO\")}};exports.default=WASI}});return{WASI:require_wasi().default}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeWorkerThreadsCode = "(function (){\"use strict\";var $;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),{MessageChannel,BroadcastChannel,Worker:WebWorker}=globalThis,SHARE_ENV=Symbol(\"nodejs.worker_threads.SHARE_ENV\"),isMainThread=Bun.isMainThread;let[_workerData,_threadId,_receiveMessageOnPort]=globalThis[globalThis.Symbol.for('Bun.lazy')](\"worker_threads\");const emittedWarnings=new Set;function emitWarning(type,message){if(emittedWarnings.has(type))return;emittedWarnings.add(type),console.warn(\"[bun] Warning:\",message)}function injectFakeEmitter(Class){function messageEventHandler(event){return event.data}function errorEventHandler(event){return event.error}const wrappedListener=Symbol(\"wrappedListener\");function wrapped(run,listener){const callback=function(event){return listener(run(event))};return listener[wrappedListener]=callback,callback}function functionForEventType(event,listener){switch(event){case\"error\":case\"messageerror\":return wrapped(errorEventHandler,listener);default:return wrapped(messageEventHandler,listener)}}Class.prototype.on=function(event,listener){return this.addEventListener(event,functionForEventType(event,listener)),this},Class.prototype.off=function(event,listener){if(listener)this.removeEventListener(event,listener[wrappedListener]||listener);else this.removeEventListener(event);return this},Class.prototype.once=function(event,listener){return this.addEventListener(event,functionForEventType(event,listener),{once:!0}),this};function EventClass(eventName){if(eventName===\"error\"||eventName===\"messageerror\")return ErrorEvent;return MessageEvent}Class.prototype.emit=function(event,...args){return this.dispatchEvent(new(EventClass(event))(event,...args)),this},Class.prototype.prependListener=Class.prototype.on,Class.prototype.prependOnceListener=Class.prototype.once}const _MessagePort=globalThis.MessagePort;injectFakeEmitter(_MessagePort);const MessagePort=_MessagePort;let resourceLimits={},workerData=_workerData,threadId=_threadId;function receiveMessageOnPort(port){let res=_receiveMessageOnPort(port);if(!res)return;return{message:res}}function fakeParentPort(){const fake=Object.create(MessagePort.prototype);return Object.defineProperty(fake,\"onmessage\",{get(){return self.onmessage},set(value){self.onmessage=value}}),Object.defineProperty(fake,\"onmessageerror\",{get(){return self.onmessageerror},set(value){}}),Object.defineProperty(fake,\"postMessage\",{value(...args){return self.postMessage(...args)}}),Object.defineProperty(fake,\"close\",{value(){return process.exit(0)}}),Object.defineProperty(fake,\"start\",{value(){}}),Object.defineProperty(fake,\"unref\",{value(){}}),Object.defineProperty(fake,\"ref\",{value(){}}),Object.defineProperty(fake,\"hasRef\",{value(){return!1}}),Object.defineProperty(fake,\"setEncoding\",{value(){}}),Object.defineProperty(fake,\"addEventListener\",{value:self.addEventListener.bind(self)}),Object.defineProperty(fake,\"removeEventListener\",{value:self.removeEventListener.bind(self)}),fake}let parentPort=isMainThread\?null:fakeParentPort();function getEnvironmentData(){return process.env}function setEnvironmentData(env){process.env=env}function markAsUntransferable(){throwNotImplemented(\"worker_threads.markAsUntransferable\")}function moveMessagePortToContext(){throwNotImplemented(\"worker_threads.moveMessagePortToContext\")}const unsupportedOptions=[\"eval\",\"argv\",\"execArgv\",\"stdin\",\"stdout\",\"stderr\",\"trackedUnmanagedFds\",\"resourceLimits\"];class Worker extends EventEmitter{#worker;#performance;#onExitPromise=void 0;constructor(filename,options={}){super();for(let key of unsupportedOptions)if(key in options)emitWarning(\"option.\"+key,`worker_threads.Worker option \"${key}\" is not implemented.`);this.#worker=new WebWorker(filename,options),this.#worker.addEventListener(\"close\",this.#onClose.bind(this)),this.#worker.addEventListener(\"error\",this.#onError.bind(this)),this.#worker.addEventListener(\"message\",this.#onMessage.bind(this)),this.#worker.addEventListener(\"messageerror\",this.#onMessageError.bind(this)),this.#worker.addEventListener(\"open\",this.#onOpen.bind(this))}ref(){this.#worker.ref()}unref(){this.#worker.unref()}get stdin(){return null}get stdout(){return null}get stderr(){return null}get performance(){return this.#performance\?\?={eventLoopUtilization(){return emitWarning(\"performance\",\"worker_threads.Worker.performance is not implemented.\"),{idle:0,active:0,utilization:0}}}}terminate(){if(this.#onExitPromise)return this.#onExitPromise;const{resolve,promise}=Promise.withResolvers();return this.once(\"exit\",(code)=>{resolve(code)}),this.#worker.terminate(),this.#onExitPromise=promise}postMessage(...args){return this.#worker.postMessage(...args)}#onClose(e){console.log(\"worker closed\",e),this.#onExitPromise=e.code,this.emit(\"exit\",e.code)}#onError(event){this.emit(\"error\",event.error)}#onMessage(event){this.emit(\"message\",event.data)}#onMessageError(event){this.emit(\"messageerror\",event.error\?\?event.data\?\?event)}#onOpen(){this.emit(\"online\")}async getHeapSnapshot(){throwNotImplemented(\"worker_threads.Worker.getHeapSnapshot\")}}return $={Worker,workerData,parentPort,resourceLimits,isMainThread,MessageChannel,BroadcastChannel,MessagePort,getEnvironmentData,setEnvironmentData,getHeapSnapshot(){return{}},markAsUntransferable,moveMessagePortToContext,receiveMessageOnPort,SHARE_ENV,threadId},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeZlibCode = "(function (){\"use strict\";const assert=@getInternalField(@internalModuleRegistry,3)||@createInternalModuleById(3),BufferModule=@requireNativeModule(\"node:buffer\"),StreamModule=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),Util=@getInternalField(@internalModuleRegistry,42)||@createInternalModuleById(42);var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_zstream=__commonJS({\"node_modules/pako/lib/zlib/zstream.js\"(exports,module2){function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0}module2.exports=ZStream}}),require_common=__commonJS({\"node_modules/pako/lib/utils/common.js\"(exports){var TYPED_OK=typeof Uint8Array!==\"undefined\"&&typeof Uint16Array!==\"undefined\"&&typeof Int32Array!==\"undefined\";function _has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}exports.assign=function(obj){var sources=Array.prototype.slice.call(arguments,1);while(sources.length){var source=sources.shift();if(!source)continue;if(typeof source!==\"object\")@throwTypeError(source+\"must be non-object\");for(var p in source)if(_has(source,p))obj[p]=source[p]}return obj},exports.shrinkBuf=function(buf,size){if(buf.length===size)return buf;if(buf.subarray)return buf.subarray(0,size);return buf.length=size,buf};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i=0)buf[len]=0}var STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH=3,MAX_MATCH=258,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],DIST_CODE_LEN=512,static_ltree=new Array((L_CODES+2)*2);zero(static_ltree);var static_dtree=new Array(D_CODES*2);zero(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero(_dist_code);var _length_code=new Array(MAX_MATCH-MIN_MATCH+1);zero(_length_code);var base_length=new Array(LENGTH_CODES);zero(base_length);var base_dist=new Array(D_CODES);zero(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}var static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}function d_code(dist){return dist<256\?_dist_code[dist]:_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=w&255,s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){if(s.bi_valid>Buf_size-length)s.bi_buf|=value<>Buf_size-s.bi_valid,s.bi_valid+=length-Buf_size;else s.bi_buf|=value<>>=1,res<<=1;while(--len>0);return res>>>1}function bi_flush(s){if(s.bi_valid===16)put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0;else if(s.bi_valid>=8)s.pending_buf[s.pending++]=s.bi_buf&255,s.bi_buf>>=8,s.bi_valid-=8}function gen_bitlen(s,desc){var{dyn_tree:tree,max_code}=desc,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length,h,n,m,bits,xbits,f,overflow=0;for(bits=0;bits<=MAX_BITS;bits++)s.bl_count[bits]=0;tree[s.heap[s.heap_max]*2+1]=0;for(h=s.heap_max+1;hmax_length)bits=max_length,overflow++;if(tree[n*2+1]=bits,n>max_code)continue;if(s.bl_count[bits]++,xbits=0,n>=base)xbits=extra[n-base];if(f=tree[n*2],s.opt_len+=f*(bits+xbits),has_stree)s.static_len+=f*(stree[n*2+1]+xbits)}if(overflow===0)return;do{bits=max_length-1;while(s.bl_count[bits]===0)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){if(m=s.heap[--h],m>max_code)continue;if(tree[m*2+1]!==bits)s.opt_len+=(bits-tree[m*2+1])*tree[m*2],tree[m*2+1]=bits;n--}}}function gen_codes(tree,max_code,bl_count){var next_code=new Array(MAX_BITS+1),code=0,bits,n;for(bits=1;bits<=MAX_BITS;bits++)next_code[bits]=code=code+bl_count[bits-1]<<1;for(n=0;n<=max_code;n++){var len=tree[n*2+1];if(len===0)continue;tree[n*2]=bi_reverse(next_code[len]++,len)}}function tr_static_init(){var n,bits,length,code,dist,bl_count=new Array(MAX_BITS+1);length=0;for(code=0;code>=7;for(;code8)put_short(s,s.bi_buf);else if(s.bi_valid>0)s.pending_buf[s.pending++]=s.bi_buf;s.bi_buf=0,s.bi_valid=0}function copy_block(s,buf,len,header){if(bi_windup(s),header)put_short(s,len),put_short(s,~len);utils.arraySet(s.pending_buf,s.window,buf,len,s.pending),s.pending+=len}function smaller(tree,n,m,depth){var _n2=n*2,_m2=m*2;return tree[_n2]>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[node*2]=tree[n*2]+tree[m*2],s.depth[node]=(s.depth[n]>=s.depth[m]\?s.depth[n]:s.depth[m])+1,tree[n*2+1]=tree[m*2+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],gen_bitlen(s,desc),gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n,prevlen=-1,curlen,nextlen=tree[1],count=0,max_count=7,min_count=4;if(nextlen===0)max_count=138,min_count=3;tree[(max_code+1)*2+1]=65535;for(n=0;n<=max_code;n++){if(curlen=nextlen,nextlen=tree[(n+1)*2+1],++count=3;max_blindex--)if(s.bl_tree[bl_order[max_blindex]*2+1]!==0)break;return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4);for(rank=0;rank>>=1)if(black_mask&1&&s.dyn_ltree[n*2]!==0)return Z_BINARY;if(s.dyn_ltree[18]!==0||s.dyn_ltree[20]!==0||s.dyn_ltree[26]!==0)return Z_TEXT;for(n=32;n0){if(s.strm.data_type===Z_UNKNOWN)s.strm.data_type=detect_data_type(s);if(build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=build_bl_tree(s),opt_lenb=s.opt_len+3+7>>>3,static_lenb=s.static_len+3+7>>>3,static_lenb<=opt_lenb)opt_lenb=static_lenb}else opt_lenb=static_lenb=stored_len+5;if(stored_len+4<=opt_lenb&&buf!==-1)_tr_stored_block(s,buf,stored_len,last);else if(s.strategy===Z_FIXED||static_lenb===opt_lenb)send_bits(s,(STATIC_TREES<<1)+(last\?1:0),3),compress_block(s,static_ltree,static_dtree);else send_bits(s,(DYN_TREES<<1)+(last\?1:0),3),send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree);if(init_block(s),last)bi_windup(s)}function _tr_tally(s,dist,lc){if(s.pending_buf[s.d_buf+s.last_lit*2]=dist>>>8&255,s.pending_buf[s.d_buf+s.last_lit*2+1]=dist&255,s.pending_buf[s.l_buf+s.last_lit]=lc&255,s.last_lit++,dist===0)s.dyn_ltree[lc*2]++;else s.matches++,dist--,s.dyn_ltree[(_length_code[lc]+LITERALS+1)*2]++,s.dyn_dtree[d_code(dist)*2]++;return s.last_lit===s.lit_bufsize-1}exports._tr_init=_tr_init,exports._tr_stored_block=_tr_stored_block,exports._tr_flush_block=_tr_flush_block,exports._tr_tally=_tr_tally,exports._tr_align=_tr_align}}),require_adler32=__commonJS({\"node_modules/pako/lib/zlib/adler32.js\"(exports,module2){function adler32(adler,buf,len,pos){var s1=adler&65535|0,s2=adler>>>16&65535|0,n=0;while(len!==0){n=len>2000\?2000:len,len-=n;do s1=s1+buf[pos++]|0,s2=s2+s1|0;while(--n);s1%=65521,s2%=65521}return s1|s2<<16|0}module2.exports=adler32}}),require_crc32=__commonJS({\"node_modules/pako/lib/zlib/crc32.js\"(exports,module2){function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=c&1\?3988292384^c>>>1:c>>>1;table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255];return crc^-1}module2.exports=crc32}}),require_messages=__commonJS({\"node_modules/pako/lib/zlib/messages.js\"(exports,module2){module2.exports={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"}}}),require_deflate=__commonJS({\"node_modules/pako/lib/zlib/deflate.js\"(exports){var utils=require_common(),trees=require_trees(),adler32=require_adler32(),crc32=require_crc32(),msg=require_messages(),Z_NO_FLUSH=0,Z_PARTIAL_FLUSH=1,Z_FULL_FLUSH=3,Z_FINISH=4,Z_BLOCK=5,Z_OK=0,Z_STREAM_END=1,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_BUF_ERROR=-5,Z_DEFAULT_COMPRESSION=-1,Z_FILTERED=1,Z_HUFFMAN_ONLY=2,Z_RLE=3,Z_FIXED=4,Z_DEFAULT_STRATEGY=0,Z_UNKNOWN=2,Z_DEFLATED=8,MAX_MEM_LEVEL=9,MAX_WBITS=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3;function err(strm,errorCode){return strm.msg=msg[errorCode],errorCode}function rank(f){return(f<<1)-(f>4\?9:0)}function zero(buf){var len=buf.length;while(--len>=0)buf[len]=0}function flush_pending(strm){var s=strm.state,len=s.pending;if(len>strm.avail_out)len=strm.avail_out;if(len===0)return;if(utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,s.pending===0)s.pending_out=0}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0\?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=b&255}function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size)len=size;if(len===0)return 0;if(strm.avail_in-=len,utils.arraySet(buf,strm.input,strm.next_in,len,start),strm.state.wrap===1)strm.adler=adler32(strm.adler,buf,len,start);else if(strm.state.wrap===2)strm.adler=crc32(strm.adler,buf,len,start);return strm.next_in+=len,strm.total_in+=len,len}function longest_match(s,cur_match){var{max_chain_length:chain_length,strstart:scan}=s,match,len,best_len=s.prev_length,nice_match=s.nice_match,limit=s.strstart>s.w_size-MIN_LOOKAHEAD\?s.strstart-(s.w_size-MIN_LOOKAHEAD):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+MAX_MATCH,scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match)chain_length>>=2;if(nice_match>s.lookahead)nice_match=s.lookahead;do{if(match=cur_match,_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1])continue;scan+=2,match++;do;while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scanbest_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead)return best_len;return s.lookahead}function fill_window(s){var _w_size=s.w_size,p,n,m,more,str;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){utils.arraySet(s.window,s.window,_w_size,_w_size,0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,n=s.hash_size,p=n;do m=s.head[--p],s.head[p]=m>=_w_size\?m-_w_size:0;while(--n);n=_w_size,p=n;do m=s.prev[--p],s.prev[p]=m>=_w_size\?m-_w_size:0;while(--n);more+=_w_size}if(s.strm.avail_in===0)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=(s.ins_h<s.pending_buf_size-5)max_block_size=s.pending_buf_size-5;for(;;){if(s.lookahead<=1){if(fill_window(s),s.lookahead===0&&flush===Z_NO_FLUSH)return BS_NEED_MORE;if(s.lookahead===0)break}s.strstart+=s.lookahead,s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){if(s.lookahead=s.strstart-max_start,s.strstart=max_start,flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.strstart>s.block_start){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_NEED_MORE}function deflate_fast(s,flush){var hash_head,bflush;for(;;){if(s.lookahead=MIN_MATCH)s.ins_h=(s.ins_h<=MIN_MATCH)if(bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=MIN_MATCH)s.ins_h=(s.ins_h<4096))s.match_length=MIN_MATCH-1}if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH,bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH),s.lookahead-=s.prev_length-1,s.prev_length-=2;do if(++s.strstart<=max_insert)s.ins_h=(s.ins_h<=MIN_MATCH&&s.strstart>0){if(scan=s.strstart-1,prev=_win[scan],prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do;while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scans.lookahead)s.match_length=s.lookahead}}if(s.match_length>=MIN_MATCH)bflush=trees._tr_tally(s,1,s.match_length-MIN_MATCH),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0;else bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.last_lit){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_BLOCK_DONE}function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){if(fill_window(s),s.lookahead===0){if(flush===Z_NO_FLUSH)return BS_NEED_MORE;break}}if(s.match_length=0,bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.last_lit){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_BLOCK_DONE}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}var configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function lm_init(s){s.window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=MIN_MATCH-1,s.match_available=0,s.ins_h=0}function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new utils.Buf16(HEAP_SIZE*2),this.dyn_dtree=new utils.Buf16((2*D_CODES+1)*2),this.bl_tree=new utils.Buf16((2*BL_CODES+1)*2),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new utils.Buf16(MAX_BITS+1),this.heap=new utils.Buf16(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new utils.Buf16(2*L_CODES+1),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(strm){var s;if(!strm||!strm.state)return err(strm,Z_STREAM_ERROR);if(strm.total_in=strm.total_out=0,strm.data_type=Z_UNKNOWN,s=strm.state,s.pending=0,s.pending_out=0,s.wrap<0)s.wrap=-s.wrap;return s.status=s.wrap\?INIT_STATE:BUSY_STATE,strm.adler=s.wrap===2\?0:1,s.last_flush=Z_NO_FLUSH,trees._tr_init(s),Z_OK}function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK)lm_init(strm.state);return ret}function deflateSetHeader(strm,head){if(!strm||!strm.state)return Z_STREAM_ERROR;if(strm.state.wrap!==2)return Z_STREAM_ERROR;return strm.state.gzhead=head,Z_OK}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm)return Z_STREAM_ERROR;var wrap=1;if(level===Z_DEFAULT_COMPRESSION)level=6;if(windowBits<0)wrap=0,windowBits=-windowBits;else if(windowBits>15)wrap=2,windowBits-=16;if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED)return err(strm,Z_STREAM_ERROR);if(windowBits===8)windowBits=9;var s=new DeflateState;return strm.state=s,s.strm=strm,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<Z_BLOCK||flush<0)return strm\?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR;if(s=strm.state,!strm.output||!strm.input&&strm.avail_in!==0||s.status===FINISH_STATE&&flush!==Z_FINISH)return err(strm,strm.avail_out===0\?Z_BUF_ERROR:Z_STREAM_ERROR);if(s.strm=strm,old_flush=s.last_flush,s.last_flush=flush,s.status===INIT_STATE)if(s.wrap===2)if(strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),!s.gzhead)put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,s.level===9\?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2\?4:0),put_byte(s,OS_CODE),s.status=BUSY_STATE;else{if(put_byte(s,(s.gzhead.text\?1:0)+(s.gzhead.hcrc\?2:0)+(!s.gzhead.extra\?0:4)+(!s.gzhead.name\?0:8)+(!s.gzhead.comment\?0:16)),put_byte(s,s.gzhead.time&255),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,s.level===9\?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2\?4:0),put_byte(s,s.gzhead.os&255),s.gzhead.extra&&s.gzhead.extra.length)put_byte(s,s.gzhead.extra.length&255),put_byte(s,s.gzhead.extra.length>>8&255);if(s.gzhead.hcrc)strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0);s.gzindex=0,s.status=EXTRA_STATE}else{var header=Z_DEFLATED+(s.w_bits-8<<4)<<8,level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2)level_flags=0;else if(s.level<6)level_flags=1;else if(s.level===6)level_flags=2;else level_flags=3;if(header|=level_flags<<6,s.strstart!==0)header|=PRESET_DICT;if(header+=31-header%31,s.status=BUSY_STATE,putShortMSB(s,header),s.strstart!==0)putShortMSB(s,strm.adler>>>16),putShortMSB(s,strm.adler&65535);strm.adler=1}if(s.status===EXTRA_STATE)if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&65535)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size)break}put_byte(s,s.gzhead.extra[s.gzindex]&255),s.gzindex++}if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(s.gzindex===s.gzhead.extra.length)s.gzindex=0,s.status=NAME_STATE}else s.status=NAME_STATE;if(s.status===NAME_STATE)if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size){val=1;break}}if(s.gzindexbeg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(val===0)s.gzindex=0,s.status=COMMENT_STATE}else s.status=COMMENT_STATE;if(s.status===COMMENT_STATE)if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size){val=1;break}}if(s.gzindexbeg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(val===0)s.status=HCRC_STATE}else s.status=HCRC_STATE;if(s.status===HCRC_STATE)if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size)flush_pending(strm);if(s.pending+2<=s.pending_buf_size)put_byte(s,strm.adler&255),put_byte(s,strm.adler>>8&255),strm.adler=0,s.status=BUSY_STATE}else s.status=BUSY_STATE;if(s.pending!==0){if(flush_pending(strm),strm.avail_out===0)return s.last_flush=-1,Z_OK}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH)return err(strm,Z_BUF_ERROR);if(s.status===FINISH_STATE&&strm.avail_in!==0)return err(strm,Z_BUF_ERROR);if(strm.avail_in!==0||s.lookahead!==0||flush!==Z_NO_FLUSH&&s.status!==FINISH_STATE){var bstate=s.strategy===Z_HUFFMAN_ONLY\?deflate_huff(s,flush):s.strategy===Z_RLE\?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE)s.status=FINISH_STATE;if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0)s.last_flush=-1;return Z_OK}if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH)trees._tr_align(s);else if(flush!==Z_BLOCK){if(trees._tr_stored_block(s,0,0,!1),flush===Z_FULL_FLUSH){if(zero(s.head),s.lookahead===0)s.strstart=0,s.block_start=0,s.insert=0}}if(flush_pending(strm),strm.avail_out===0)return s.last_flush=-1,Z_OK}}if(flush!==Z_FINISH)return Z_OK;if(s.wrap<=0)return Z_STREAM_END;if(s.wrap===2)put_byte(s,strm.adler&255),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,strm.total_in&255),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255);else putShortMSB(s,strm.adler>>>16),putShortMSB(s,strm.adler&65535);if(flush_pending(strm),s.wrap>0)s.wrap=-s.wrap;return s.pending!==0\?Z_OK:Z_STREAM_END}function deflateEnd(strm){var status;if(!strm||!strm.state)return Z_STREAM_ERROR;if(status=strm.state.status,status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE)return err(strm,Z_STREAM_ERROR);return strm.state=null,status===BUSY_STATE\?err(strm,Z_DATA_ERROR):Z_OK}function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length,s,str,n,wrap,avail,next,input,tmpDict;if(!strm||!strm.state)return Z_STREAM_ERROR;if(s=strm.state,wrap=s.wrap,wrap===2||wrap===1&&s.status!==INIT_STATE||s.lookahead)return Z_STREAM_ERROR;if(wrap===1)strm.adler=adler32(strm.adler,dictionary,dictLength,0);if(s.wrap=0,dictLength>=s.w_size){if(wrap===0)zero(s.head),s.strstart=0,s.block_start=0,s.insert=0;tmpDict=new utils.Buf8(s.w_size),utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0),dictionary=tmpDict,dictLength=s.w_size}avail=strm.avail_in,next=strm.next_in,input=strm.input,strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);while(s.lookahead>=MIN_MATCH){str=s.strstart,n=s.lookahead-(MIN_MATCH-1);do s.ins_h=(s.ins_h<>>24,hold>>>=op,bits-=op,op=here>>>16&255,op===0)output[_out++]=here&65535;else if(op&16){if(len=here&65535,op&=15,op){if(bits>>=op,bits-=op}if(bits<15)hold+=input[_in++]<>>24,hold>>>=op,bits-=op,op=here>>>16&255,op&16){if(dist=here&65535,op&=15,bitsdmax){strm.msg=\"invalid distance too far back\",state.mode=BAD;break top}if(hold>>>=op,bits-=op,op=_out-beg,dist>op){if(op=dist-op,op>whave){if(state.sane){strm.msg=\"invalid distance too far back\",state.mode=BAD;break top}}if(from=0,from_source=s_window,wnext===0){if(from+=wsize-op,op2)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;if(len){if(output[_out++]=from_source[from++],len>1)output[_out++]=from_source[from++]}}else{from=_out-dist;do output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3;while(len>2);if(len){if(output[_out++]=output[from++],len>1)output[_out++]=output[from++]}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3,_in-=len,bits-=len<<3,hold&=(1<=1;max--)if(count[max]!==0)break;if(root>max)root=max;if(max===0)return table[table_index++]=1<<24|64<<16|0,table[table_index++]=1<<24|64<<16|0,opts.bits=1,0;for(min=1;min0&&(type===CODES||max!==1))return-1;offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS)return 1;for(;;){if(here_bits=len-drop,work[sym]end)here_op=extra[extra_index+work[sym]],here_val=base[base_index+work[sym]];else here_op=96,here_val=0;incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0;while(fill!==0);incr=1<>=1;if(incr!==0)huff&=incr-1,huff+=incr;else huff=0;if(sym++,--count[len]===0){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0)drop=root;next+=min,curr=len-drop,left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS)return 1;low=huff&mask,table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0)table[next+huff]=len-drop<<24|64<<16|0;return opts.bits=root,0}}}),require_inflate=__commonJS({\"node_modules/pako/lib/zlib/inflate.js\"(exports){var utils=require_common(),adler32=require_adler32(),crc32=require_crc32(),inflate_fast=require_inffast(),inflate_table=require_inftrees(),CODES=0,LENS=1,DISTS=2,Z_FINISH=4,Z_BLOCK=5,Z_TREES=6,Z_OK=0,Z_STREAM_END=1,Z_NEED_DICT=2,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_MEM_ERROR=-4,Z_BUF_ERROR=-5,Z_DEFLATED=8,HEAD=1,FLAGS=2,TIME=3,OS=4,EXLEN=5,EXTRA=6,NAME=7,COMMENT=8,HCRC=9,DICTID=10,DICT=11,TYPE=12,TYPEDO=13,STORED=14,COPY_=15,COPY=16,TABLE=17,LENLENS=18,CODELENS=19,LEN_=20,LEN=21,LENEXT=22,DIST=23,DISTEXT=24,MATCH=25,LIT=26,CHECK=27,LENGTH=28,DONE=29,BAD=30,MEM=31,SYNC=32,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new utils.Buf16(320),this.work=new utils.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state)return Z_STREAM_ERROR;if(state=strm.state,strm.total_in=strm.total_out=state.total=0,strm.msg=\"\",state.wrap)strm.adler=state.wrap&1;return state.mode=HEAD,state.last=0,state.havedict=0,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS),state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS),state.sane=1,state.back=-1,Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state)return Z_STREAM_ERROR;return state=strm.state,state.wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap,state;if(!strm||!strm.state)return Z_STREAM_ERROR;if(state=strm.state,windowBits<0)wrap=0,windowBits=-windowBits;else if(wrap=(windowBits>>4)+1,windowBits<48)windowBits&=15;if(windowBits&&(windowBits<8||windowBits>15))return Z_STREAM_ERROR;if(state.window!==null&&state.wbits!==windowBits)state.window=null;return state.wrap=wrap,state.wbits=windowBits,inflateReset(strm)}function inflateInit2(strm,windowBits){var ret,state;if(!strm)return Z_STREAM_ERROR;if(state=new InflateState,strm.state=state,state.window=null,ret=inflateReset2(strm,windowBits),ret!==Z_OK)strm.state=null;return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=!0,lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512),distfix=new utils.Buf32(32),sym=0;while(sym<144)state.lens[sym++]=8;while(sym<256)state.lens[sym++]=9;while(sym<280)state.lens[sym++]=7;while(sym<288)state.lens[sym++]=8;inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;while(sym<32)state.lens[sym++]=5;inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5}function updatewindow(strm,src,end,copy){var dist,state=strm.state;if(state.window===null)state.wsize=1<=state.wsize)utils.arraySet(state.window,src,end-state.wsize,state.wsize,0),state.wnext=0,state.whave=state.wsize;else{if(dist=state.wsize-state.wnext,dist>copy)dist=copy;if(utils.arraySet(state.window,src,end-copy,dist,state.wnext),copy-=dist,copy)utils.arraySet(state.window,src,end-copy,copy,0),state.wnext=copy,state.whave=state.wsize;else{if(state.wnext+=dist,state.wnext===state.wsize)state.wnext=0;if(state.whave>>8&255,state.check=crc32(state.check,hbuf,2,0),hold=0,bits=0,state.mode=FLAGS;break}if(state.flags=0,state.head)state.head.done=!1;if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg=\"incorrect header check\",state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg=\"unknown compression method\",state.mode=BAD;break}if(hold>>>=4,bits-=4,len=(hold&15)+8,state.wbits===0)state.wbits=len;else if(len>state.wbits){strm.msg=\"invalid window size\",state.mode=BAD;break}state.dmax=1<>8&1;if(state.flags&512)hbuf[0]=hold&255,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0,state.mode=TIME;case TIME:while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32(state.check,hbuf,4,0);hold=0,bits=0,state.mode=OS;case OS:while(bits<16){if(have===0)break inf_leave;have--,hold+=input[next++]<>8;if(state.flags&512)hbuf[0]=hold&255,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0,state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0)break inf_leave;have--,hold+=input[next++]<>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0}else if(state.head)state.head.extra=null;state.mode=EXTRA;case EXTRA:if(state.flags&1024){if(copy=state.length,copy>have)copy=have;if(copy){if(state.head){if(len=state.head.extra_len-state.length,!state.head.extra)state.head.extra=new Array(state.head.extra_len);utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512)state.check=crc32(state.check,input,copy,next);have-=copy,next+=copy,state.length-=copy}if(state.length)break inf_leave}state.length=0,state.mode=NAME;case NAME:if(state.flags&2048){if(have===0)break inf_leave;copy=0;do if(len=input[next+copy++],state.head&&len&&state.length<65536)state.head.name+=String.fromCharCode(len);while(len&©>9&1,state.head.done=!0;strm.adler=state.check=0,state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=bits&7,bits-=bits&7,state.mode=CHECK;break}while(bits<3){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=1,bits-=1,hold&3){case 0:state.mode=STORED;break;case 1:if(fixedtables(state),state.mode=LEN_,flush===Z_TREES){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg=\"invalid block type\",state.mode=BAD}hold>>>=2,bits-=2;break;case STORED:hold>>>=bits&7,bits-=bits&7;while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>16^65535)){strm.msg=\"invalid stored block lengths\",state.mode=BAD;break}if(state.length=hold&65535,hold=0,bits=0,state.mode=COPY_,flush===Z_TREES)break inf_leave;case COPY_:state.mode=COPY;case COPY:if(copy=state.length,copy){if(copy>have)copy=have;if(copy>left)copy=left;if(copy===0)break inf_leave;utils.arraySet(output,input,next,copy,put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=5,bits-=5,state.ndist=(hold&31)+1,hold>>>=5,bits-=5,state.ncode=(hold&15)+4,hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg=\"too many length or distance symbols\",state.mode=BAD;break}state.have=0,state.mode=LENLENS;case LENLENS:while(state.have>>=3,bits-=3}while(state.have<19)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg=\"invalid code lengths set\",state.mode=BAD;break}state.have=0,state.mode=CODELENS;case CODELENS:while(state.have>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits,bits-=here_bits,state.have===0){strm.msg=\"invalid bit length repeat\",state.mode=BAD;break}len=state.lens[state.have-1],copy=3+(hold&3),hold>>>=2,bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits,bits-=here_bits,len=0,copy=3+(hold&7),hold>>>=3,bits-=3}else{n=here_bits+7;while(bits>>=here_bits,bits-=here_bits,len=0,copy=11+(hold&127),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg=\"invalid bit length repeat\",state.mode=BAD;break}while(copy--)state.lens[state.have++]=len}}if(state.mode===BAD)break;if(state.lens[256]===0){strm.msg=\"invalid code -- missing end-of-block\",state.mode=BAD;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg=\"invalid literal/lengths set\",state.mode=BAD;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg=\"invalid distances set\",state.mode=BAD;break}if(state.mode=LEN_,flush===Z_TREES)break inf_leave;case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){if(strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inflate_fast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,state.mode===TYPE)state.back=-1;break}state.back=0;for(;;){if(here=state.lencode[hold&(1<>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=here&65535,last_bits+here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1,state.mode=TYPE;break}if(here_op&64){strm.msg=\"invalid literal/length code\",state.mode=BAD;break}state.extra=here_op&15,state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=DIST;case DIST:for(;;){if(here=state.distcode[hold&(1<>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=here&65535,last_bits+here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,here_op&64){strm.msg=\"invalid distance code\",state.mode=BAD;break}state.offset=here_val,state.extra=here_op&15,state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg=\"invalid distance too far back\",state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0)break inf_leave;if(copy=_out-left,state.offset>copy){if(copy=state.offset-copy,copy>state.whave){if(state.sane){strm.msg=\"invalid distance too far back\",state.mode=BAD;break}}if(copy>state.wnext)copy-=state.wnext,from=state.wsize-copy;else from=state.wnext-copy;if(copy>state.length)copy=state.length;from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;if(copy>left)copy=left;left-=copy,state.length-=copy;do output[put++]=from_source[from++];while(--copy);if(state.length===0)state.mode=LEN;break;case LIT:if(left===0)break inf_leave;output[put++]=state.length,left--,state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0)break inf_leave;have--,hold|=input[next++]<exports.UNZIP)@throwTypeError(\"Bad argument\");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=mode,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}Zlib.prototype={},Zlib.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}if(this.pending_close=!1,assert(this.init_done,\"close before init\"),assert(this.mode<=exports.UNZIP),this.mode===exports.DEFLATE||this.mode===exports.GZIP||this.mode===exports.DEFLATERAW)zlib_deflate.deflateEnd(this.strm);else if(this.mode===exports.INFLATE||this.mode===exports.GUNZIP||this.mode===exports.INFLATERAW||this.mode===exports.UNZIP)zlib_inflate.inflateEnd(this.strm);this.mode=exports.NONE,this.dictionary=null},Zlib.prototype.write=function(flush,input,in_off,in_len,out,out_off,out_len){return this._write(!0,flush,input,in_off,in_len,out,out_off,out_len)},Zlib.prototype.writeSync=function(flush,input,in_off,in_len,out,out_off,out_len){return this._write(!1,flush,input,in_off,in_len,out,out_off,out_len)},Zlib.prototype._write=function(async,flush,input,in_off,in_len,out,out_off,out_len){if(assert.equal(arguments.length,8),assert(this.init_done,\"write before init\"),assert(this.mode!==exports.NONE,\"already finalized\"),assert.equal(!1,this.write_in_progress,\"write already in progress\"),assert.equal(!1,this.pending_close,\"close is pending\"),this.write_in_progress=!0,assert.equal(!1,flush===void 0,\"must provide flush value\"),this.write_in_progress=!0,flush!==exports.Z_NO_FLUSH&&flush!==exports.Z_PARTIAL_FLUSH&&flush!==exports.Z_SYNC_FLUSH&&flush!==exports.Z_FULL_FLUSH&&flush!==exports.Z_FINISH&&flush!==exports.Z_BLOCK)throw new Error(\"Invalid flush value\");if(input==null)input=Buffer.alloc(0),in_len=0,in_off=0;if(this.strm.avail_in=in_len,this.strm.input=input,this.strm.next_in=in_off,this.strm.avail_out=out_len,this.strm.output=out,this.strm.next_out=out_off,this.flush=flush,!async){if(this._process(),this._checkError())return this._afterSync();return}var self=this;return process.nextTick(function(){self._process(),self._after()}),this},Zlib.prototype._afterSync=function(){var avail_out=this.strm.avail_out,avail_in=this.strm.avail_in;return this.write_in_progress=!1,[avail_in,avail_out]},Zlib.prototype._process=function(){var next_expected_header_byte=null;switch(this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:this.err=zlib_deflate.deflate(this.strm,this.flush);break;case exports.UNZIP:if(this.strm.avail_in>0)next_expected_header_byte=this.strm.next_in;switch(this.gzip_id_bytes_read){case 0:if(next_expected_header_byte===null)break;if(this.strm.input[next_expected_header_byte]===GZIP_HEADER_ID1){if(this.gzip_id_bytes_read=1,next_expected_header_byte++,this.strm.avail_in===1)break}else{this.mode=exports.INFLATE;break}case 1:if(next_expected_header_byte===null)break;if(this.strm.input[next_expected_header_byte]===GZIP_HEADER_ID2)this.gzip_id_bytes_read=2,this.mode=exports.GUNZIP;else this.mode=exports.INFLATE;break;default:throw new Error(\"invalid number of gzip magic number bytes read\")}case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:if(this.err=zlib_inflate.inflate(this.strm,this.flush),this.err===exports.Z_NEED_DICT&&this.dictionary){if(this.err=zlib_inflate.inflateSetDictionary(this.strm,this.dictionary),this.err===exports.Z_OK)this.err=zlib_inflate.inflate(this.strm,this.flush);else if(this.err===exports.Z_DATA_ERROR)this.err=exports.Z_NEED_DICT}while(this.strm.avail_in>0&&this.mode===exports.GUNZIP&&this.err===exports.Z_STREAM_END&&this.strm.next_in[0]!==0)this.reset(),this.err=zlib_inflate.inflate(this.strm,this.flush);break;default:throw new Error(\"Unknown mode \"+this.mode)}},Zlib.prototype._checkError=function(){switch(this.err){case exports.Z_OK:case exports.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===exports.Z_FINISH)return this._error(\"unexpected end of file\"),!1;break;case exports.Z_STREAM_END:break;case exports.Z_NEED_DICT:if(this.dictionary==null)this._error(\"Missing dictionary\");else this._error(\"Bad dictionary\");return!1;default:return this._error(\"Zlib error\"),!1}return!0},Zlib.prototype._after=function(){if(!this._checkError())return;var avail_out=this.strm.avail_out,avail_in=this.strm.avail_in;if(this.write_in_progress=!1,this.callback(avail_in,avail_out),this.pending_close)this.close()},Zlib.prototype._error=function(message){if(this.strm.msg)message=this.strm.msg;if(this.onerror(message,this.err),this.write_in_progress=!1,this.pending_close)this.close()},Zlib.prototype.init=function(windowBits,level,memLevel,strategy,dictionary){assert(arguments.length===4||arguments.length===5,\"init(windowBits, level, memLevel, strategy, [dictionary])\"),assert(windowBits>=8&&windowBits<=15,\"invalid windowBits\"),assert(level>=-1&&level<=9,\"invalid compression level\"),assert(memLevel>=1&&memLevel<=9,\"invalid memlevel\"),assert(strategy===exports.Z_FILTERED||strategy===exports.Z_HUFFMAN_ONLY||strategy===exports.Z_RLE||strategy===exports.Z_FIXED||strategy===exports.Z_DEFAULT_STRATEGY,\"invalid strategy\"),this._init(level,windowBits,memLevel,strategy,dictionary),this._setDictionary()},Zlib.prototype.params=function(){throw new Error(\"deflateParams Not supported\")},Zlib.prototype.reset=function(){this._reset(),this._setDictionary()},Zlib.prototype._init=function(level,windowBits,memLevel,strategy,dictionary){if(this.level=level,this.windowBits=windowBits,this.memLevel=memLevel,this.strategy=strategy,this.flush=exports.Z_NO_FLUSH,this.err=exports.Z_OK,this.mode===exports.GZIP||this.mode===exports.GUNZIP)this.windowBits+=16;if(this.mode===exports.UNZIP)this.windowBits+=32;if(this.mode===exports.DEFLATERAW||this.mode===exports.INFLATERAW)this.windowBits=-1*this.windowBits;switch(this.strm=new Zstream,this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:this.err=zlib_deflate.deflateInit2(this.strm,this.level,exports.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:case exports.UNZIP:this.err=zlib_inflate.inflateInit2(this.strm,this.windowBits);break;default:throw new Error(\"Unknown mode \"+this.mode)}if(this.err!==exports.Z_OK)this._error(\"Init error\");this.dictionary=dictionary,this.write_in_progress=!1,this.init_done=!0},Zlib.prototype._setDictionary=function(){if(this.dictionary==null)return;switch(this.err=exports.Z_OK,this.mode){case exports.DEFLATE:case exports.DEFLATERAW:this.err=zlib_deflate.deflateSetDictionary(this.strm,this.dictionary);break;default:break}if(this.err!==exports.Z_OK)this._error(\"Failed to set dictionary\")},Zlib.prototype._reset=function(){switch(this.err=exports.Z_OK,this.mode){case exports.DEFLATE:case exports.DEFLATERAW:case exports.GZIP:this.err=zlib_deflate.deflateReset(this.strm);break;case exports.INFLATE:case exports.INFLATERAW:case exports.GUNZIP:this.err=zlib_inflate.inflateReset(this.strm);break;default:break}if(this.err!==exports.Z_OK)this._error(\"Failed to reset stream\")},exports.Zlib=Zlib}}),require_lib=__commonJS({\"node_modules/browserify-zlib/lib/index.js\"(exports){var Buffer2=BufferModule.Buffer,Transform=StreamModule.Transform,binding=require_binding(),util=Util,kMaxLength=BufferModule.kMaxLength,kRangeErrorMessage=\"Cannot create final Buffer. It would be larger than 0x\"+kMaxLength.toString(16)+\" bytes\";binding.Z_MIN_WINDOWBITS=8,binding.Z_MAX_WINDOWBITS=15,binding.Z_DEFAULT_WINDOWBITS=15,binding.Z_MIN_CHUNK=64,binding.Z_MAX_CHUNK=Infinity,binding.Z_DEFAULT_CHUNK=16384,binding.Z_MIN_MEMLEVEL=1,binding.Z_MAX_MEMLEVEL=9,binding.Z_DEFAULT_MEMLEVEL=8,binding.Z_MIN_LEVEL=-1,binding.Z_MAX_LEVEL=9,binding.Z_DEFAULT_LEVEL=binding.Z_DEFAULT_COMPRESSION;var bkeys=Object.keys(binding);for(bk=0;bk=kMaxLength)err=new RangeError(kRangeErrorMessage);else buf=Buffer2.concat(buffers,nread);buffers=[],engine.close(),callback(err,buf)}}function zlibBufferSync(engine,buffer){if(typeof buffer===\"string\")buffer=Buffer2.from(buffer);if(!Buffer2.isBuffer(buffer))@throwTypeError(\"Not a string or buffer\");var flushFlag=engine._finishFlushFlag;return engine._processChunk(buffer,flushFlag)}function Deflate(opts){if(!(this instanceof Deflate))return new Deflate(opts);Zlib.call(this,opts,binding.DEFLATE)}function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);Zlib.call(this,opts,binding.INFLATE)}function Gzip(opts){if(!(this instanceof Gzip))return new Gzip(opts);Zlib.call(this,opts,binding.GZIP)}function Gunzip(opts){if(!(this instanceof Gunzip))return new Gunzip(opts);Zlib.call(this,opts,binding.GUNZIP)}function DeflateRaw(opts){if(!(this instanceof DeflateRaw))return new DeflateRaw(opts);Zlib.call(this,opts,binding.DEFLATERAW)}function InflateRaw(opts){if(!(this instanceof InflateRaw))return new InflateRaw(opts);Zlib.call(this,opts,binding.INFLATERAW)}function Unzip(opts){if(!(this instanceof Unzip))return new Unzip(opts);Zlib.call(this,opts,binding.UNZIP)}function isValidFlushFlag(flag){return flag===binding.Z_NO_FLUSH||flag===binding.Z_PARTIAL_FLUSH||flag===binding.Z_SYNC_FLUSH||flag===binding.Z_FULL_FLUSH||flag===binding.Z_FINISH||flag===binding.Z_BLOCK}function Zlib(opts,mode){var _this=this;if(this._opts=opts=opts||{},this._chunkSize=opts.chunkSize||exports.Z_DEFAULT_CHUNK,Transform.call(this,opts),opts.flush&&!isValidFlushFlag(opts.flush))throw new Error(\"Invalid flush flag: \"+opts.flush);if(opts.finishFlush&&!isValidFlushFlag(opts.finishFlush))throw new Error(\"Invalid flush flag: \"+opts.finishFlush);if(this._flushFlag=opts.flush||binding.Z_NO_FLUSH,this._finishFlushFlag=typeof opts.finishFlush!==\"undefined\"\?opts.finishFlush:binding.Z_FINISH,opts.chunkSize){if(opts.chunkSizeexports.Z_MAX_CHUNK)throw new Error(\"Invalid chunk size: \"+opts.chunkSize)}if(opts.windowBits){if(opts.windowBitsexports.Z_MAX_WINDOWBITS)throw new Error(\"Invalid windowBits: \"+opts.windowBits)}if(opts.level){if(opts.levelexports.Z_MAX_LEVEL)throw new Error(\"Invalid compression level: \"+opts.level)}if(opts.memLevel){if(opts.memLevelexports.Z_MAX_MEMLEVEL)throw new Error(\"Invalid memLevel: \"+opts.memLevel)}if(opts.strategy){if(opts.strategy!=exports.Z_FILTERED&&opts.strategy!=exports.Z_HUFFMAN_ONLY&&opts.strategy!=exports.Z_RLE&&opts.strategy!=exports.Z_FIXED&&opts.strategy!=exports.Z_DEFAULT_STRATEGY)throw new Error(\"Invalid strategy: \"+opts.strategy)}if(opts.dictionary){if(!Buffer2.isBuffer(opts.dictionary))throw new Error(\"Invalid dictionary: it should be a Buffer instance\")}this._handle=new binding.Zlib(mode);var self=this;this._hadError=!1,this._handle.onerror=function(message,errno){_close(self),self._hadError=!0;var error=new Error(message);error.errno=errno,error.code=exports.codes[errno],self.emit(\"error\",error)};var level=exports.Z_DEFAULT_COMPRESSION;if(typeof opts.level===\"number\")level=opts.level;var strategy=exports.Z_DEFAULT_STRATEGY;if(typeof opts.strategy===\"number\")strategy=opts.strategy;this._handle.init(opts.windowBits||exports.Z_DEFAULT_WINDOWBITS,level,opts.memLevel||exports.Z_DEFAULT_MEMLEVEL,strategy,opts.dictionary),this._buffer=Buffer2.allocUnsafe(this._chunkSize),this._offset=0,this._level=level,this._strategy=strategy,this.once(\"end\",this.close),Object.defineProperty(this,\"_closed\",{get:function(){return!_this._handle},configurable:!0,enumerable:!0})}util.inherits(Zlib,Transform),Zlib.prototype.params=function(level,strategy,callback){if(levelexports.Z_MAX_LEVEL)@throwRangeError(\"Invalid compression level: \"+level);if(strategy!=exports.Z_FILTERED&&strategy!=exports.Z_HUFFMAN_ONLY&&strategy!=exports.Z_RLE&&strategy!=exports.Z_FIXED&&strategy!=exports.Z_DEFAULT_STRATEGY)@throwTypeError(\"Invalid strategy: \"+strategy);if(this._level!==level||this._strategy!==strategy){var self=this;this.flush(binding.Z_SYNC_FLUSH,function(){if(assert(self._handle,\"zlib binding closed\"),self._handle.params(level,strategy),!self._hadError){if(self._level=level,self._strategy=strategy,callback)callback()}})}else process.nextTick(callback)},Zlib.prototype.reset=function(){return assert(this._handle,\"zlib binding closed\"),this._handle.reset()},Zlib.prototype._flush=function(callback){this._transform(Buffer2.alloc(0),\"\",callback)},Zlib.prototype.flush=function(kind,callback){var _this2=this,ws=this._writableState;if(typeof kind===\"function\"||kind===void 0&&!callback)callback=kind,kind=binding.Z_FULL_FLUSH;if(ws.ended){if(callback)process.nextTick(callback)}else if(ws.ending){if(callback)this.once(\"end\",callback)}else if(ws.needDrain){if(callback)this.once(\"drain\",function(){return _this2.flush(kind,callback)})}else this._flushFlag=kind,this.write(Buffer2.alloc(0),\"\",callback)},Zlib.prototype.close=function(callback){_close(this,callback),process.nextTick(emitCloseNT,this)};function _close(engine,callback){if(callback)process.nextTick(callback);if(!engine._handle)return;engine._handle.close(),engine._handle=null}function emitCloseNT(self){self.emit(\"close\")}Zlib.prototype._transform=function(chunk,encoding,cb){var flushFlag,ws=this._writableState,ending=ws.ending||ws.ended,last=ending&&(!chunk||ws.length===chunk.length);if(chunk!==null&&!Buffer2.isBuffer(chunk))return cb(new Error(\"invalid input\"));if(!this._handle)return cb(new Error(\"zlib binding closed\"));if(last)flushFlag=this._finishFlushFlag;else if(flushFlag=this._flushFlag,chunk.length>=ws.length)this._flushFlag=this._opts.flush||binding.Z_NO_FLUSH;this._processChunk(chunk,flushFlag,cb)},Zlib.prototype._processChunk=function(chunk,flushFlag,cb){var availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,inOff=0,self=this,async=typeof cb===\"function\";if(!async){var buffers=[],nread=0,error;this.on(\"error\",function(er){error=er}),assert(this._handle,\"zlib binding closed\");do var res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);while(!this._hadError&&callback(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)_close(this),@throwRangeError(kRangeErrorMessage);var buf=Buffer2.concat(buffers,nread);return _close(this),buf}assert(this._handle,\"zlib binding closed\");var req=this._handle.write(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);req.buffer=chunk,req.callback=callback;function callback(availInAfter,availOutAfter){if(this)this.buffer=null,this.callback=null;if(self._hadError)return;var have=availOutBefore-availOutAfter;if(assert(have>=0,\"have should not go down\"),have>0){var out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,async)self.push(out);else buffers.push(out),nread+=out.length}if(availOutAfter===0||self._offset>=self._chunkSize)availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer2.allocUnsafe(self._chunkSize);if(availOutAfter===0){if(inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!async)return!0;var newReq=self._handle.write(flushFlag,chunk,inOff,availInBefore,self._buffer,self._offset,self._chunkSize);newReq.callback=callback,newReq.buffer=chunk;return}if(!async)return!1;cb()}},util.inherits(Deflate,Zlib),util.inherits(Inflate,Zlib),util.inherits(Gzip,Zlib),util.inherits(Gunzip,Zlib),util.inherits(DeflateRaw,Zlib),util.inherits(InflateRaw,Zlib),util.inherits(Unzip,Zlib)}});return require_lib()})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDepdCode = "(function (){\"use strict\";var $=function depd(namespace){if(!namespace)@throwTypeError(\"argument namespace is required\");function deprecate(message){}return deprecate._file=void 0,deprecate._ignored=!0,deprecate._namespace=namespace,deprecate._traced=!1,deprecate._warned=Object.create(null),deprecate.function=wrapfunction,deprecate.property=wrapproperty,deprecate};function wrapfunction(fn,message){if(typeof fn!==\"function\")@throwTypeError(\"argument fn must be a function\");return fn}function wrapproperty(obj,prop,message){if(!obj||typeof obj!==\"object\"&&typeof obj!==\"function\")@throwTypeError(\"argument obj must be object\");var descriptor=Object.getOwnPropertyDescriptor(obj,prop);if(!descriptor)@throwTypeError(\"must call property on owner object\");if(!descriptor.configurable)@throwTypeError(\"property must be configurable\")}return $})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDetectLibcCode = "(function (){\"use strict\";function family(){return Promise.resolve(familySync())}function familySync(){return null}const GLIBC=\"glibc\",MUSL=\"musl\";function versionAsync(){return Promise.resolve(version())}function version(){return null}function isNonGlibcLinuxSync(){return!1}function isNonGlibcLinux(){return Promise.resolve(isNonGlibcLinuxSync())}return{GLIBC,MUSL,family,familySync,isNonGlibcLinux,isNonGlibcLinuxSync,version,versionAsync}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDetectLibcLinuxCode = "(function (){\"use strict\";function family(){return Promise.resolve(familySync())}function familySync(){return GLIBC}const GLIBC=\"glibc\",MUSL=\"musl\";function versionAsync(){return Promise.resolve(version())}function version(){return\"2.29\"}function isNonGlibcLinuxSync(){return!1}function isNonGlibcLinux(){return Promise.resolve(isNonGlibcLinuxSync())}return{GLIBC,MUSL,family,familySync,isNonGlibcLinux,isNonGlibcLinuxSync,version,versionAsync}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyIsomorphicFetchCode = "(function (){\"use strict\";const bunFetch=Bun.fetch,fetch=(...args)=>bunFetch(...args);return fetch.default=fetch,fetch.fetch=fetch,fetch})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyNodeFetchCode = "(function (){\"use strict\";const{Headers,Request,Response,Blob,File=Blob,FormData}=globalThis,realFetch=Bun.fetch;function fetch(...args){return realFetch(...args)}class AbortError extends DOMException{constructor(message){super(message,\"AbortError\")}}class FetchBaseError extends Error{constructor(message,type){super(message);this.type=type}}class FetchError extends FetchBaseError{constructor(message,type,systemError){super(message,type);this.code=systemError\?.code}}function blobFrom(path,options){return Promise.resolve(Bun.file(data))}function blobFromSync(path,options){return Bun.file(data)}var fileFrom=blobFrom,fileFromSync=blobFromSync;function isRedirect(code){return code===301||code===302||code===303||code===307||code===308}return Object.assign(fetch,{AbortError,Blob,FetchBaseError,FetchError,File,FormData,Headers,Request,Response,blobFrom,blobFromSync,fileFrom,fileFromSync,isRedirect,fetch,default:fetch})})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyUndiciCode = "(function (){\"use strict\";const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),StreamModule=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),{Readable}=StreamModule,{_ReadableFromWebForUndici:ReadableFromWeb}=StreamModule[Symbol.for(\"::bunternal::\")],ObjectCreate=Object.create,kEmptyObject=ObjectCreate(null);var fetch=Bun.fetch,Response=globalThis.Response,Headers=globalThis.Headers,Request=globalThis.Request,URLSearchParams=globalThis.URLSearchParams,URL=globalThis.URL;class File extends Blob{constructor(){super(...arguments)}}class FileReader extends EventTarget{constructor(){throw new Error(\"Not implemented yet!\")}}var FormData=globalThis.FormData;function notImplemented(){throw new Error(\"Not implemented in bun\")}class BodyReadable extends ReadableFromWeb{#response;#bodyUsed;constructor(response,options={}){var{body}=response;if(!body)throw new Error(\"Response body is null\");super(options,body);this.#response=response,this.#bodyUsed=response.bodyUsed}get bodyUsed(){return this.#bodyUsed}#consume(){if(this.#bodyUsed)@throwTypeError(\"unusable\");this.#bodyUsed=!0}async arrayBuffer(){return this.#consume(),await this.#response.arrayBuffer()}async blob(){return this.#consume(),await this.#response.blob()}async formData(){return this.#consume(),await this.#response.formData()}async json(){return this.#consume(),await this.#response.json()}async text(){return this.#consume(),await this.#response.text()}}async function request(url,options={method:\"GET\",signal:null,headers:null,query:null,reset:!1,throwOnError:!1,body:null}){let{method=\"GET\",headers:inputHeaders,query,signal,reset=!1,throwOnError=!1,body:inputBody,maxRedirections}=options;if(typeof url===\"string\"){if(query)url=new URL(url)}else if(typeof url===\"object\"&&url!==null){if(!(url instanceof URL))throw new Error(\"not implemented\")}else @throwTypeError(\"url must be a string, URL, or UrlObject\");if(typeof url===\"string\"&&query)url=new URL(url);if(typeof url===\"object\"&&url!==null&&query){if(query)url.search=new URLSearchParams(query).toString()}if(method=method&&typeof method===\"string\"\?method.toUpperCase():null,inputBody&&(method===\"GET\"||method===\"HEAD\"))throw new Error(\"Body not allowed for GET or HEAD requests\");if(inputBody&&inputBody.read&&inputBody instanceof Readable){let data=\"\";inputBody.setEncoding(\"utf8\");for await(let chunk of stream)data+=chunk;inputBody=(new TextEncoder()).encode(data)}if(maxRedirections!==void 0&&Number.isNaN(maxRedirections))throw new Error(\"maxRedirections must be a number if defined\");if(signal&&!(signal instanceof AbortSignal))throw new Error(\"signal must be an instance of AbortSignal\");let resp;const{status:statusCode,headers,trailers}=resp=await fetch(url,{signal,mode:\"cors\",method,headers:inputHeaders||kEmptyObject,body:inputBody,redirect:maxRedirections===\"undefined\"||maxRedirections>0\?\"follow\":\"manual\",keepalive:!reset});if(throwOnError&&statusCode>=400&&statusCode<600)throw new Error(`Request failed with status code ${statusCode}`);const body=resp.body\?new BodyReadable(resp):null;return{statusCode,headers:headers.toJSON(),body,trailers,opaque:kEmptyObject,context:kEmptyObject}}function stream(){throw new Error(\"Not implemented in bun\")}function pipeline(){throw new Error(\"Not implemented in bun\")}function connect(){throw new Error(\"Not implemented in bun\")}function upgrade(){throw new Error(\"Not implemented in bun\")}class MockClient{constructor(){throw new Error(\"Not implemented in bun\")}}class MockPool{constructor(){throw new Error(\"Not implemented in bun\")}}class MockAgent{constructor(){throw new Error(\"Not implemented in bun\")}}function mockErrors(){throw new Error(\"Not implemented in bun\")}function Undici(){throw new Error(\"Not implemented in bun\")}class Dispatcher extends EventEmitter{constructor(){super(...arguments)}}class Agent extends Dispatcher{constructor(){super(...arguments)}}class Pool extends Dispatcher{constructor(){super(...arguments)}request(){throw new Error(\"Not implemented in bun\")}}class BalancedPool extends Dispatcher{constructor(){super(...arguments)}}class Client extends Dispatcher{constructor(){super(...arguments)}request(){throw new Error(\"Not implemented in bun\")}}return Undici.Dispatcher=Dispatcher,Undici.Pool=Pool,Undici.BalancedPool=BalancedPool,Undici.Client=Client,Undici.Agent=Agent,Undici.buildConnector=Undici.errors=Undici.setGlobalDispatcher=Undici.getGlobalDispatcher=Undici.request=Undici.stream=Undici.pipeline=Undici.connect=Undici.upgrade=Undici.MockClient=Undici.MockPool=Undici.MockAgent=Undici.mockErrors=notImplemented,Undici.fetch=fetch,{fetch,Response,Headers,Request,URLSearchParams,URL,File,FileReader,FormData,request,stream,pipeline,connect,upgrade,MockClient,MockPool,MockAgent,mockErrors,Dispatcher,Pool,BalancedPool,Client,Agent,Undici}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyVercelFetchCode = "(function (){\"use strict\";var $=(wrapper=Bun.fetch)=>{async function vercelFetch(url,opts={}){if(opts.body&&typeof opts.body===\"object\"&&(!(\"buffer\"in opts.body)||typeof opts.body.buffer!==\"object\"||!(opts.body.buffer instanceof ArrayBuffer))){if(opts.body=JSON.stringify(opts.body),!opts.headers)opts.headers=new Headers;opts.headers.set(\"Content-Type\",\"application/json\")}try{return await wrapper(url,opts)}catch(err){if(typeof err===\"string\")err=new Error(err);throw err.url=url,err.opts=opts,err}}return vercelFetch.default=vercelFetch,vercelFetch};return $})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyWSCode = "(function (){\"use strict\";const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),http=@getInternalField(@internalModuleRegistry,18)||@createInternalModuleById(18),kBunInternals=Symbol.for(\"::bunternal::\"),readyStates=[\"CONNECTING\",\"OPEN\",\"CLOSING\",\"CLOSED\"],encoder=new TextEncoder,eventIds={open:1,close:2,message:3,error:4,ping:5,pong:6},emittedWarnings=new Set;function emitWarning(type,message){if(emittedWarnings.has(type))return;emittedWarnings.add(type),console.warn(\"[bun] Warning:\",message)}class BunWebSocket extends EventEmitter{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;#ws;#paused=!1;#fragments=!1;#binaryType=\"nodebuffer\";#eventId=0;constructor(url,protocols,options){super();let ws=this.#ws=new WebSocket(url,protocols);ws.binaryType=\"nodebuffer\"}on(event,listener){if(event===\"unexpected-response\"||event===\"upgrade\"||event===\"redirect\")emitWarning(event,\"ws.WebSocket '\"+event+\"' event is not implemented in bun\");const mask=1<{this.emit(\"open\")});else if(event===\"close\")this.#ws.addEventListener(\"close\",({code,reason,wasClean})=>{this.emit(\"close\",code,reason,wasClean)});else if(event===\"message\")this.#ws.addEventListener(\"message\",({data})=>{const isBinary=typeof data!==\"string\";if(isBinary)this.emit(\"message\",this.#fragments\?[data]:data,isBinary);else{let encoded=encoder.encode(data);if(this.#binaryType!==\"arraybuffer\")encoded=Buffer.from(encoded.buffer,encoded.byteOffset,encoded.byteLength);this.emit(\"message\",this.#fragments\?[encoded]:encoded,isBinary)}});else if(event===\"error\")this.#ws.addEventListener(\"error\",(err)=>{this.emit(\"error\",err)});else if(event===\"ping\")this.#ws.addEventListener(\"ping\",({data})=>{this.emit(\"ping\",data)});else if(event===\"pong\")this.#ws.addEventListener(\"pong\",({data})=>{this.emit(\"pong\",data)})}return super.on(event,listener)}send(data,opts,cb){try{this.#ws.send(data,opts\?.compress)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}close(code,reason){this.#ws.close(code,reason)}terminate(){this.#ws.terminate()}get url(){return this.#ws.url}get readyState(){return this.#ws.readyState}get binaryType(){return this.#binaryType}set binaryType(value){if(value===\"nodebuffer\"||value===\"arraybuffer\")this.#ws.binaryType=this.#binaryType=value,this.#fragments=!1;else if(value===\"fragments\")this.#ws.binaryType=\"nodebuffer\",this.#binaryType=\"fragments\",this.#fragments=!0;else throw new Error(`Invalid binaryType: ${value}`)}get protocol(){return this.#ws.protocol}get extensions(){return this.#ws.extensions}addEventListener(type,listener,options){this.#ws.addEventListener(type,listener,options)}removeEventListener(type,listener){this.#ws.removeEventListener(type,listener)}get onopen(){return this.#ws.onopen}set onopen(value){this.#ws.onopen=value}get onerror(){return this.#ws.onerror}set onerror(value){this.#ws.onerror=value}get onclose(){return this.#ws.onclose}set onclose(value){this.#ws.onclose=value}get onmessage(){return this.#ws.onmessage}set onmessage(value){this.#ws.onmessage=value}get bufferedAmount(){return this.#ws.bufferedAmount}get isPaused(){return this.#paused}ping(data,mask,cb){if(typeof data===\"function\")cb=data,data=mask=void 0;else if(typeof mask===\"function\")cb=mask,mask=void 0;if(typeof data===\"number\")data=data.toString();try{this.#ws.ping(data)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}pong(data,mask,cb){if(typeof data===\"function\")cb=data,data=mask=void 0;else if(typeof mask===\"function\")cb=mask,mask=void 0;if(typeof data===\"number\")data=data.toString();try{this.#ws.pong(data)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}pause(){switch(this.readyState){case WebSocket.CONNECTING:case WebSocket.CLOSED:return}this.#paused=!0,emitWarning(\"pause()\",\"ws.WebSocket.pause() is not implemented in bun\")}resume(){switch(this.readyState){case WebSocket.CONNECTING:case WebSocket.CLOSED:return}this.#paused=!1,emitWarning(\"resume()\",\"ws.WebSocket.resume() is not implemented in bun\")}}Object.defineProperty(BunWebSocket,\"name\",{value:\"WebSocket\"});const wsKeyRegex=/^[+/0-9A-Za-z]{22}==$/,wsTokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,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,0,0,0,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,0,1,0,1,0];function subprotocolParse(header){const protocols=new Set;let start=-1,end=-1,i=0;for(i;i{const body=http.STATUS_CODES[426];res.writeHead(426,{\"Content-Length\":body.length,\"Content-Type\":\"text/plain\"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback);else if(options.server)this._server=options.server;if(this._server){const emitConnection=this.emit.bind(this,\"connection\"),emitListening=this.emit.bind(this,\"listening\"),emitError=this.emit.bind(this,\"error\"),doUpgrade=(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)};this._server.on(\"listening\",emitListening),this._server.on(\"error\",emitError),this._server.on(\"upgrade\",doUpgrade),this._removeListeners=()=>{this._server.removeListener(\"upgrade\",doUpgrade),this._server.removeListener(\"listening\",emitListening),this._server.removeListener(\"error\",emitError)}}if(options.perMessageDeflate===!0)options.perMessageDeflate={};if(options.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=options,this._state=RUNNING}address(){if(this.options.noServer)throw new Error('The server is operating in \"noServer\" mode');if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb)this.once(\"close\",()=>{cb(new Error(\"The server is not running\"))});process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this);return}if(cb)this.once(\"close\",cb);if(this._state===CLOSING)return;if(this._state=CLOSING,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this);else this._shouldEmitClose=!0;else process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this)}else{const server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{this._state=CLOSED,this.emit(\"close\")})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf(\"\?\");if((index!==-1\?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}completeUpgrade(extensions,key,protocols,request,socket,head,cb){const[server,response,req]=socket[kBunInternals];if(this._state>RUNNING)return abortHandshake(response,503);let protocol=\"\";if(protocols.size)protocol=this.options.handleProtocols\?this.options.handleProtocols(protocols,request):protocols.values().next().value;const ws=new BunWebSocketMocked(request.url,protocol,extensions,\"nodebuffer\"),headers=[\"HTTP/1.1 101 Switching Protocols\",\"Upgrade: websocket\",\"Connection: Upgrade\"];if(this.emit(\"headers\",headers,request),server.upgrade(req,{data:ws[kBunInternals]})){if(response._reply(void 0),this.clients)this.clients.add(ws),ws.on(\"close\",()=>{if(this.clients.delete(ws),this._shouldEmitClose&&!this.clients.size)process.nextTick(wsEmitClose,this)});cb(ws,request)}else abortHandshake(response,500)}handleUpgrade(req,socket,head,cb){const[_,response]=socket[kBunInternals],key=req.headers[\"sec-websocket-key\"],version=+req.headers[\"sec-websocket-version\"];if(req.method!==\"GET\"){abortHandshakeOrEmitwsClientError(this,req,response,socket,405,\"Invalid HTTP method\");return}if(req.headers.upgrade.toLowerCase()!==\"websocket\"){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Invalid Upgrade header\");return}if(!key||!wsKeyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Missing or invalid Sec-WebSocket-Key header\");return}if(version!==8&&version!==13){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Missing or invalid Sec-WebSocket-Version header\");return}if(!this.shouldHandle(req)){abortHandshake(response,400);return}const secWebSocketProtocol=req.headers[\"sec-websocket-protocol\"];let protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocolParse(secWebSocketProtocol)}catch(err){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Invalid Sec-WebSocket-Protocol header\");return}const extensions={};if(this.options.verifyClient){const info={origin:req.headers[`${version===8\?\"sec-websocket-origin\":\"origin\"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(response,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(response,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}}Object.defineProperty(BunWebSocket,\"CONNECTING\",{enumerable:!0,value:readyStates.indexOf(\"CONNECTING\")}),Object.defineProperty(BunWebSocket.prototype,\"CONNECTING\",{enumerable:!0,value:readyStates.indexOf(\"CONNECTING\")}),Object.defineProperty(BunWebSocket,\"OPEN\",{enumerable:!0,value:readyStates.indexOf(\"OPEN\")}),Object.defineProperty(BunWebSocket.prototype,\"OPEN\",{enumerable:!0,value:readyStates.indexOf(\"OPEN\")}),Object.defineProperty(BunWebSocket,\"CLOSING\",{enumerable:!0,value:readyStates.indexOf(\"CLOSING\")}),Object.defineProperty(BunWebSocket.prototype,\"CLOSING\",{enumerable:!0,value:readyStates.indexOf(\"CLOSING\")}),Object.defineProperty(BunWebSocket,\"CLOSED\",{enumerable:!0,value:readyStates.indexOf(\"CLOSED\")}),Object.defineProperty(BunWebSocket.prototype,\"CLOSED\",{enumerable:!0,value:readyStates.indexOf(\"CLOSED\")});class Sender{constructor(){throw new Error(\"Not supported yet in Bun\")}}class Receiver{constructor(){throw new Error(\"Not supported yet in Bun\")}}var createWebSocketStream=(ws)=>{throw new Error(\"Not supported yet in Bun\")};return Object.assign(BunWebSocket,{createWebSocketStream,Receiver,Sender,WebSocket:BunWebSocket,Server:WebSocketServer,WebSocketServer})})\n"_s; +// + + #else + // Not 100% accurate, but basically inlining linux on non-windows non-mac platforms. + // +static constexpr ASCIILiteral BunFFICode = "(function (){\"use strict\";const FFIType={\"0\":0,\"1\":1,\"2\":2,\"3\":3,\"4\":4,\"5\":5,\"6\":6,\"7\":7,\"8\":8,\"9\":9,\"10\":10,\"11\":11,\"12\":12,\"13\":13,\"14\":14,\"15\":15,\"16\":16,\"17\":17,bool:11,c_int:5,c_uint:6,char:0,\"char*\":12,double:9,f32:10,f64:9,float:10,i16:3,i32:5,i64:7,i8:1,int:5,int16_t:3,int32_t:5,int64_t:7,int8_t:1,isize:7,u16:4,u32:6,u64:8,u8:2,uint16_t:4,uint32_t:6,uint64_t:8,uint8_t:2,usize:8,\"void*\":12,ptr:12,pointer:12,void:13,cstring:14,i64_fast:15,u64_fast:16,function:17,callback:17,fn:17};var ffi=globalThis.Bun.FFI;const ptr=(arg1,arg2)=>typeof arg2===\"undefined\"\?ffi.ptr(arg1):ffi.ptr(arg1,arg2),toBuffer=ffi.toBuffer,toArrayBuffer=ffi.toArrayBuffer,viewSource=ffi.viewSource,BunCString=ffi.CString,nativeLinkSymbols=ffi.linkSymbols,nativeDLOpen=ffi.dlopen,nativeCallback=ffi.callback,closeCallback=ffi.closeCallback;delete ffi.callback,delete ffi.closeCallback;class JSCallback{constructor(cb,options){const{ctx,ptr:ptr2}=nativeCallback(options,cb);this.#ctx=ctx,this.ptr=ptr2,this.#threadsafe=!!options\?.threadsafe}ptr;#ctx;#threadsafe;get threadsafe(){return this.#threadsafe}[Symbol.toPrimitive](){const{ptr:ptr2}=this;return typeof ptr2===\"number\"\?ptr2:0}close(){const ctx=this.#ctx;if(this.ptr=null,this.#ctx=null,ctx)closeCallback(ctx)}}class CString extends String{constructor(ptr2,byteOffset,byteLength){super(ptr2\?typeof byteLength===\"number\"&&Number.isSafeInteger(byteLength)\?new BunCString(ptr2,byteOffset||0,byteLength):new BunCString(ptr2):\"\");if(this.ptr=typeof ptr2===\"number\"\?ptr2:0,typeof byteOffset!==\"undefined\")this.byteOffset=byteOffset;if(typeof byteLength!==\"undefined\")this.byteLength=byteLength}ptr;byteOffset;byteLength;#cachedArrayBuffer;get arrayBuffer(){if(this.#cachedArrayBuffer)return this.#cachedArrayBuffer;if(!this.ptr)return this.#cachedArrayBuffer=new ArrayBuffer(0);return this.#cachedArrayBuffer=toArrayBuffer(this.ptr,this.byteOffset,this.byteLength)}}Object.defineProperty(globalThis,\"__GlobalBunCString\",{value:CString,enumerable:!1,configurable:!1});const ffiWrappers=new Array(18);var char=\"val|0\";ffiWrappers.fill(char),ffiWrappers[FFIType.uint8_t]=\"val<0\?0:val>=255\?255:val|0\",ffiWrappers[FFIType.int16_t]=\"val<=-32768\?-32768:val>=32768\?32768:val|0\",ffiWrappers[FFIType.uint16_t]=\"val<=0\?0:val>=65536\?65536:val|0\",ffiWrappers[FFIType.int32_t]=\"val|0\",ffiWrappers[FFIType.uint32_t]=\"val<=0\?0:val>=0xffffffff\?0xffffffff:+val||0\",ffiWrappers[FFIType.i64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.i64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.u64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= 0) {\n return Number(val).valueOf() || 0;\n }\n\n return val;\n }\n\n return !val \? 0 : +val || 0;\n}`,ffiWrappers[FFIType.int64_t]=`{\n if (typeof val === \"bigint\") {\n return val;\n }\n\n if (typeof val === \"number\") {\n return BigInt(val || 0);\n }\n\n return BigInt(+val || 0);\n}`,ffiWrappers[FFIType.uint64_t]=`{\n if (typeof val === \"bigint\") {\n return val;\n }\n\n if (typeof val === \"number\") {\n return val <= 0 \? BigInt(0) : BigInt(val || 0);\n }\n\n return BigInt(+val || 0);\n}`,ffiWrappers[FFIType.u64_fast]=`{\n if (typeof val === \"bigint\") {\n if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(0)) return Number(val);\n return val;\n }\n\n return typeof val === \"number\" \? (val <= 0 \? 0 : +val || 0) : +val || 0;\n}`,ffiWrappers[FFIType.uint16_t]=`{\n const ret = (typeof val === \"bigint\" \? Number(val) : val) | 0;\n return ret <= 0 \? 0 : ret > 0xffff \? 0xffff : ret;\n}`,ffiWrappers[FFIType.double]=`{\n if (typeof val === \"bigint\") {\n if (val.valueOf() < BigInt(Number.MAX_VALUE)) {\n return Math.abs(Number(val).valueOf()) + 0.00000000000001 - 0.00000000000001;\n }\n }\n\n if (!val) {\n return 0 + 0.00000000000001 - 0.00000000000001;\n }\n\n return val + 0.00000000000001 - 0.00000000000001;\n}`,ffiWrappers[FFIType.float]=ffiWrappers[10]=`{\n return Math.fround(val);\n}`,ffiWrappers[FFIType.bool]=`{\n return !!val;\n}`,Object.defineProperty(globalThis,\"__GlobalBunFFIPtrFunctionForWrapper\",{value:ptr,enumerable:!1,configurable:!0}),ffiWrappers[FFIType.cstring]=ffiWrappers[FFIType.pointer]=`{\n if (typeof val === \"number\") return val;\n if (!val) {\n return null;\n }\n\n if (ArrayBuffer.isView(val) || val instanceof ArrayBuffer) {\n return __GlobalBunFFIPtrFunctionForWrapper(val);\n }\n\n if (typeof val === \"string\") {\n throw new TypeError(\"To convert a string to a pointer, encode it as a buffer\");\n }\n\n throw new TypeError(\\`Unable to convert \\${ val } to a pointer\\`);\n}`,ffiWrappers[FFIType.function]=`{\n if (typeof val === \"number\") {\n return val;\n }\n\n if (typeof val === \"bigint\") {\n return Number(val);\n }\n\n var ptr = val && val.ptr;\n\n if (!ptr) {\n throw new TypeError(\"Expected function to be a JSCallback or a number\");\n }\n\n return ptr;\n}`;function FFIBuilder(params,returnType,functionToCall,name){const hasReturnType=typeof FFIType[returnType]===\"number\"&&FFIType[returnType]!==FFIType.void;var paramNames=new Array(params.length),args=new Array(params.length);for(let i=0;i${wrapper})(p${i})`;else @throwTypeError(`Unsupported type ${params[i]}. Must be one of: ${Object.keys(FFIType).sort().join(\", \")}`)}var code=`functionToCall(${args.join(\", \")})`;if(hasReturnType)if(FFIType[returnType]===FFIType.cstring)code=`return new __GlobalBunCString(${code})`;else code=`return ${code}`;var func=new Function(\"functionToCall\",...paramNames,code);Object.defineProperty(func,\"name\",{value:name});var wrap;switch(paramNames.length){case 0:wrap=()=>func(functionToCall);break;case 1:wrap=(arg1)=>func(functionToCall,arg1);break;case 2:wrap=(arg1,arg2)=>func(functionToCall,arg1,arg2);break;case 3:wrap=(arg1,arg2,arg3)=>func(functionToCall,arg1,arg2,arg3);break;case 4:wrap=(arg1,arg2,arg3,arg4)=>func(functionToCall,arg1,arg2,arg3,arg4);break;case 5:wrap=(arg1,arg2,arg3,arg4,arg5)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5);break;case 6:wrap=(arg1,arg2,arg3,arg4,arg5,arg6)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6);break;case 7:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7);break;case 8:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);break;case 9:wrap=(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9)=>func(functionToCall,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);break;default:{wrap=(...args2)=>func(functionToCall,...args2);break}}return wrap.native=functionToCall,wrap.ptr=functionToCall.ptr,wrap}const native={dlopen:nativeDLOpen,callback:()=>{throw new Error(\"Deprecated. Use new JSCallback(options, fn) instead\")}};function dlopen(path,options){const result=nativeDLOpen(path,options);for(let key in result.symbols){var symbol=result.symbols[key];if(options[key]\?.args\?.length||FFIType[options[key]\?.returns]===FFIType.cstring)result.symbols[key]=FFIBuilder(options[key].args\?\?[],options[key].returns\?\?FFIType.void,symbol,path.includes(\"/\")\?`${key} (${path.split(\"/\").pop()})`:`${key} (${path})`);else result.symbols[key].native=result.symbols[key]}return result}function linkSymbols(options){const result=nativeLinkSymbols(options);for(let key in result.symbols){var symbol=result.symbols[key];if(options[key]\?.args\?.length||FFIType[options[key]\?.returns]===FFIType.cstring)result.symbols[key]=FFIBuilder(options[key].args\?\?[],options[key].returns\?\?FFIType.void,symbol,key);else result.symbols[key].native=result.symbols[key]}return result}var cFunctionI=0,cFunctionRegistry;function onCloseCFunction(close){close()}function CFunction(options){const identifier=`CFunction${cFunctionI++}`;var result=linkSymbols({[identifier]:options}),hasClosed=!1,close=result.close;return result.symbols[identifier].close=()=>{if(hasClosed||!close)return;hasClosed=!0,close(),close=void 0},cFunctionRegistry||=new FinalizationRegistry(onCloseCFunction),cFunctionRegistry.register(result.symbols[identifier],result.symbols[identifier].close),result.symbols[identifier]}const read=ffi.read;return{CFunction,CString,FFIType,JSCallback,dlopen,linkSymbols,native,ptr,read,suffix:\"so\",toArrayBuffer,toBuffer,viewSource}})\n"_s; +// + +// +static constexpr ASCIILiteral BunSqliteCode = "(function (){\"use strict\";var defineProperties=Object.defineProperties,toStringTag=Symbol.toStringTag,isArray=Array.isArray,isTypedArray=ArrayBuffer.isView;const constants={SQLITE_OPEN_READONLY:1,SQLITE_OPEN_READWRITE:2,SQLITE_OPEN_CREATE:4,SQLITE_OPEN_DELETEONCLOSE:8,SQLITE_OPEN_EXCLUSIVE:16,SQLITE_OPEN_AUTOPROXY:32,SQLITE_OPEN_URI:64,SQLITE_OPEN_MEMORY:128,SQLITE_OPEN_MAIN_DB:256,SQLITE_OPEN_TEMP_DB:512,SQLITE_OPEN_TRANSIENT_DB:1024,SQLITE_OPEN_MAIN_JOURNAL:2048,SQLITE_OPEN_TEMP_JOURNAL:4096,SQLITE_OPEN_SUBJOURNAL:8192,SQLITE_OPEN_SUPER_JOURNAL:16384,SQLITE_OPEN_NOMUTEX:32768,SQLITE_OPEN_FULLMUTEX:65536,SQLITE_OPEN_SHAREDCACHE:131072,SQLITE_OPEN_PRIVATECACHE:262144,SQLITE_OPEN_WAL:524288,SQLITE_OPEN_NOFOLLOW:16777216,SQLITE_OPEN_EXRESCODE:33554432,SQLITE_PREPARE_PERSISTENT:1,SQLITE_PREPARE_NORMALIZE:2,SQLITE_PREPARE_NO_VTAB:4};var SQL,controllers;class Statement{constructor(raw){switch(this.#raw=raw,raw.paramsCount){case 0:{this.get=this.#getNoArgs,this.all=this.#allNoArgs,this.values=this.#valuesNoArgs,this.run=this.#runNoArgs;break}default:{this.get=this.#get,this.all=this.#all,this.values=this.#values,this.run=this.#run;break}}}#raw;get;all;values;run;isFinalized=!1;toJSON(){return{sql:this.native.toString(),isFinalized:this.isFinalized,paramsCount:this.paramsCount,columnNames:this.columnNames}}get[toStringTag](){return`\"${this.native.toString()}\"`}toString(){return this.native.toString()}get native(){return this.#raw}#getNoArgs(){return this.#raw.get()}#allNoArgs(){return this.#raw.all()}#valuesNoArgs(){return this.#raw.values()}#runNoArgs(){this.#raw.run()}#get(...args){if(args.length===0)return this.#getNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.get(args):this.#raw.get(...args)}#all(...args){if(args.length===0)return this.#allNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.all(args):this.#raw.all(...args)}#values(...args){if(args.length===0)return this.#valuesNoArgs();var arg0=args[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.values(args):this.#raw.values(...args)}#run(...args){if(args.length===0)return this.#runNoArgs();var arg0=args[0];!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?this.#raw.run(args):this.#raw.run(...args)}get columnNames(){return this.#raw.columns}get paramsCount(){return this.#raw.paramsCount}finalize(...args){return this.isFinalized=!0,this.#raw.finalize(...args)}}var cachedCount=Symbol.for(\"Bun.Database.cache.count\");class Database{constructor(filenameGiven,options){if(typeof filenameGiven===\"undefined\");else if(typeof filenameGiven!==\"string\"){if(isTypedArray(filenameGiven)){this.#handle=Database.deserialize(filenameGiven,typeof options===\"object\"&&options\?!!options.readonly:((options|0)&constants.SQLITE_OPEN_READONLY)!=0),this.filename=\":memory:\";return}@throwTypeError(`Expected 'filename' to be a string, got '${typeof filenameGiven}'`)}var filename=typeof filenameGiven===\"string\"\?filenameGiven.trim():\":memory:\",flags=constants.SQLITE_OPEN_READWRITE|constants.SQLITE_OPEN_CREATE;if(typeof options===\"object\"&&options){if(flags=0,options.readonly)flags=constants.SQLITE_OPEN_READONLY;if(\"readOnly\"in options)@throwTypeError('Misspelled option \"readOnly\" should be \"readonly\"');if(options.create)flags=constants.SQLITE_OPEN_READWRITE|constants.SQLITE_OPEN_CREATE;if(options.readwrite)flags|=constants.SQLITE_OPEN_READWRITE}else if(typeof options===\"number\")flags=options;const anonymous=filename===\"\"||filename===\":memory:\";if(anonymous&&(flags&constants.SQLITE_OPEN_READONLY)!==0)throw new Error(\"Cannot open an anonymous database in read-only mode.\");if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");this.#handle=SQL.open(anonymous\?\":memory:\":filename,flags),this.filename=filename}#handle;#cachedQueriesKeys=[];#cachedQueriesLengths=[];#cachedQueriesValues=[];filename;get handle(){return this.#handle}get inTransaction(){return SQL.isInTransaction(this.#handle)}static open(filename,options){return new Database(filename,options)}loadExtension(name,entryPoint){return SQL.loadExtension(this.#handle,name,entryPoint)}serialize(optionalName){return SQL.serialize(this.#handle,optionalName||\"main\")}static deserialize(serialized,isReadOnly=!1){if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");return SQL.deserialize(serialized,isReadOnly)}static setCustomSQLite(path){if(!SQL)SQL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"sqlite\");return SQL.setCustomSQLite(path)}close(){return this.clearQueryCache(),SQL.close(this.#handle)}clearQueryCache(){for(let item of this.#cachedQueriesValues)item.finalize();this.#cachedQueriesKeys.length=0,this.#cachedQueriesValues.length=0,this.#cachedQueriesLengths.length=0}run(query,...params){if(params.length===0){SQL.run(this.#handle,query);return}var arg0=params[0];return!isArray(arg0)&&(!arg0||typeof arg0!==\"object\"||isTypedArray(arg0))\?SQL.run(this.#handle,query,params):SQL.run(this.#handle,query,...params)}prepare(query,params,flags){return new Statement(SQL.prepare(this.#handle,query,params,flags||0))}static MAX_QUERY_CACHE_SIZE=20;get[cachedCount](){return this.#cachedQueriesKeys.length}query(query){if(typeof query!==\"string\")@throwTypeError(`Expected 'query' to be a string, got '${typeof query}'`);if(query.length===0)throw new Error(\"SQL query cannot be empty.\");var index=this.#cachedQueriesLengths.indexOf(query.length);while(index!==-1){if(this.#cachedQueriesKeys[index]!==query){index=this.#cachedQueriesLengths.indexOf(query.length,index+1);continue}var stmt=this.#cachedQueriesValues[index];if(stmt.isFinalized)return this.#cachedQueriesValues[index]=this.prepare(query,void 0,willCache\?constants.SQLITE_PREPARE_PERSISTENT:0);return stmt}const willCache=this.#cachedQueriesKeys.length{let controller=(controllers||=new WeakMap).get(db);if(!controller){const shared={commit:db.prepare(\"COMMIT\",void 0,0),rollback:db.prepare(\"ROLLBACK\",void 0,0),savepoint:db.prepare(\"SAVEPOINT `\\t_bs3.\\t`\",void 0,0),release:db.prepare(\"RELEASE `\\t_bs3.\\t`\",void 0,0),rollbackTo:db.prepare(\"ROLLBACK TO `\\t_bs3.\\t`\",void 0,0)};controllers.set(db,controller={default:Object.assign({begin:db.prepare(\"BEGIN\",void 0,0)},shared),deferred:Object.assign({begin:db.prepare(\"BEGIN DEFERRED\",void 0,0)},shared),immediate:Object.assign({begin:db.prepare(\"BEGIN IMMEDIATE\",void 0,0)},shared),exclusive:Object.assign({begin:db.prepare(\"BEGIN EXCLUSIVE\",void 0,0)},shared)})}return controller},wrapTransaction=(fn,db,{begin,commit,rollback,savepoint,release,rollbackTo})=>function transaction(...args){let before,after,undo;if(db.inTransaction)before=savepoint,after=release,undo=rollbackTo;else before=begin,after=commit,undo=rollback;try{before.run();const result=fn.apply(this,args);return after.run(),result}catch(ex){if(db.inTransaction){if(undo.run(),undo!==rollback)after.run()}throw ex}};return{__esModule:!0,Database,Statement,constants,default:Database}})\n"_s; +// + +// +static constexpr ASCIILiteral InternalSharedCode = "(function (){\"use strict\";class NotImplementedError extends Error{code;constructor(feature,issue){super(feature+\" is not yet implemented in Bun.\"+(issue\?\" Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/\"+issue:\"\"));this.name=\"NotImplementedError\",this.code=\"ERR_NOT_IMPLEMENTED\",hideFromStack(NotImplementedError)}}function throwNotImplemented(feature,issue){throw hideFromStack(throwNotImplemented),new NotImplementedError(feature,issue)}function hideFromStack(...fns){for(let fn of fns)Object.defineProperty(fn,\"name\",{value:\"::bunternal::\"})}return{NotImplementedError,throwNotImplemented,hideFromStack}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeAssertCode = "(function (){\"use strict\";const util=@getInternalField(@internalModuleRegistry,42)||@createInternalModuleById(42);var isDeepEqual=Bun.deepEquals,__commonJS=(cb,mod)=>function(){return mod||(0,cb[Object.keys(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_errors=__commonJS({\"assert/build/internal/errors.js\"(exports,module2){function _typeof(obj){return typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"\?_typeof=function(obj2){return typeof obj2}:_typeof=function(obj2){return obj2&&typeof Symbol==\"function\"&&obj2.constructor===Symbol&&obj2!==Symbol.prototype\?\"symbol\":typeof obj2},_typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))@throwTypeError(\"Cannot call a class as a function\")}function _possibleConstructorReturn(self,call){return call&&(_typeof(call)===\"object\"||typeof call==\"function\")\?call:_assertThisInitialized(self)}function _assertThisInitialized(self){if(self===void 0)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return self}function _getPrototypeOf(o){return _getPrototypeOf=Object.setPrototypeOf\?Object.getPrototypeOf:function(o2){return o2.__proto__||Object.getPrototypeOf(o2)},_getPrototypeOf(o)}function _inherits(subClass,superClass){if(typeof superClass!=\"function\"&&superClass!==null)@throwTypeError(\"Super expression must either be null or a function\");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),superClass&&_setPrototypeOf(subClass,superClass)}function _setPrototypeOf(o,p){return _setPrototypeOf=Object.setPrototypeOf||function(o2,p2){return o2.__proto__=p2,o2},_setPrototypeOf(o,p)}var codes={},assert,util2;function createErrorType(code,message,Base){Base||(Base=Error);function getMessage(arg1,arg2,arg3){return typeof message==\"string\"\?message:message(arg1,arg2,arg3)}var NodeError=function(_Base){_inherits(NodeError2,_Base);function NodeError2(arg1,arg2,arg3){var _this;return _classCallCheck(this,NodeError2),_this=_possibleConstructorReturn(this,_getPrototypeOf(NodeError2).call(this,getMessage(arg1,arg2,arg3))),_this.code=code,_this}return NodeError2}(Base);codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map(function(i){return String(i)}),len>2\?\"one of \".concat(thing,\" \").concat(expected.slice(0,len-1).join(\", \"),\", or \")+expected[len-1]:len===2\?\"one of \".concat(thing,\" \").concat(expected[0],\" or \").concat(expected[1]):\"of \".concat(thing,\" \").concat(expected[0])}else return\"of \".concat(thing,\" \").concat(String(expected))}function startsWith(str,search,pos){return str.substr(!pos||pos<0\?0:+pos,search.length)===search}function endsWith(str,search,this_len){return(this_len===void 0||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){return typeof start!=\"number\"&&(start=0),start+search.length>str.length\?!1:str.indexOf(search,start)!==-1}createErrorType(\"ERR_AMBIGUOUS_ARGUMENT\",'The \"%s\" argument is ambiguous. %s',TypeError),createErrorType(\"ERR_INVALID_ARG_TYPE\",function(name,expected,actual){assert===void 0&&(assert=require_assert()),assert(typeof name==\"string\",\"'name' must be a string\");var determiner;typeof expected==\"string\"&&startsWith(expected,\"not \")\?(determiner=\"must not be\",expected=expected.replace(/^not /,\"\")):determiner=\"must be\";var msg;if(endsWith(name,\" argument\"))msg=\"The \".concat(name,\" \").concat(determiner,\" \").concat(oneOf(expected,\"type\"));else{var type=includes(name,\".\")\?\"property\":\"argument\";msg='The \"'.concat(name,'\" ').concat(type,\" \").concat(determiner,\" \").concat(oneOf(expected,\"type\"))}return msg+=\". Received type \".concat(_typeof(actual)),msg},TypeError),createErrorType(\"ERR_INVALID_ARG_VALUE\",function(name,value){var reason=arguments.length>2&&arguments[2]!==void 0\?arguments[2]:\"is invalid\",inspected=util2.inspect(value);return inspected.length>128&&(inspected=\"\".concat(inspected.slice(0,128),\"...\")),\"The argument '\".concat(name,\"' \").concat(reason,\". Received \").concat(inspected)},TypeError,RangeError),createErrorType(\"ERR_INVALID_RETURN_VALUE\",function(input,name,value){var type;return value&&value.constructor&&value.constructor.name\?type=\"instance of \".concat(value.constructor.name):type=\"type \".concat(_typeof(value)),\"Expected \".concat(input,' to be returned from the \"').concat(name,'\"')+\" function but got \".concat(type,\".\")},TypeError),createErrorType(\"ERR_MISSING_ARGS\",function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];assert===void 0&&(assert=require_assert()),assert(args.length>0,\"At least one arg needs to be specified\");var msg=\"The \",len=args.length;switch(args=args.map(function(a){return'\"'.concat(a,'\"')}),len){case 1:msg+=\"\".concat(args[0],\" argument\");break;case 2:msg+=\"\".concat(args[0],\" and \").concat(args[1],\" arguments\");break;default:msg+=args.slice(0,len-1).join(\", \"),msg+=\", and \".concat(args[len-1],\" arguments\");break}return\"\".concat(msg,\" must be specified\")},TypeError),module2.exports.codes=codes}}),require_assertion_error=__commonJS({\"assert/build/internal/assert/assertion_error.js\"(exports,module2){function _objectSpread(target){for(var i=1;istr.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}function repeat(str,count){if(count=Math.floor(count),str.length==0||count==0)return\"\";var maxCount=str.length*count;for(count=Math.floor(Math.log(count)/Math.log(2));count;)str+=str,count--;return str+=str.substring(0,maxCount-str.length),str}var blue=\"\",green=\"\",red=\"\",white=\"\",kReadableOperator={deepStrictEqual:\"Expected values to be strictly deep-equal:\",strictEqual:\"Expected values to be strictly equal:\",strictEqualObject:'Expected \"actual\" to be reference-equal to \"expected\":',deepEqual:\"Expected values to be loosely deep-equal:\",equal:\"Expected values to be loosely equal:\",notDeepStrictEqual:'Expected \"actual\" not to be strictly deep-equal to:',notStrictEqual:'Expected \"actual\" to be strictly unequal to:',notStrictEqualObject:'Expected \"actual\" not to be reference-equal to \"expected\":',notDeepEqual:'Expected \"actual\" not to be loosely deep-equal to:',notEqual:'Expected \"actual\" to be loosely unequal to:',notIdentical:\"Values identical but not reference-equal:\"},kMaxShortLength=10;function copyError(source){var keys=Object.keys(source),target=Object.create(Object.getPrototypeOf(source));return keys.forEach(function(key){target[key]=source[key]}),Object.defineProperty(target,\"message\",{value:source.message}),target}function inspectValue(val){return inspect(val,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:Infinity,showHidden:!1,breakLength:Infinity,showProxy:!1,sorted:!0,getters:!0})}function createErrDiff(actual,expected,operator){var other=\"\",res=\"\",lastPos=0,end=\"\",skipped=!1,actualInspected=inspectValue(actual),actualLines=actualInspected.split(`\n`),expectedLines=inspectValue(expected).split(`\n`),i=0,indicator=\"\";if(operator===\"strictEqual\"&&_typeof(actual)===\"object\"&&_typeof(expected)===\"object\"&&actual!==null&&expected!==null&&(operator=\"strictEqualObject\"),actualLines.length===1&&expectedLines.length===1&&actualLines[0]!==expectedLines[0]){var inputLength=actualLines[0].length+expectedLines[0].length;if(inputLength<=kMaxShortLength){if((_typeof(actual)!==\"object\"||actual===null)&&(_typeof(expected)!==\"object\"||expected===null)&&(actual!==0||expected!==0))return\"\".concat(kReadableOperator[operator],`\n\n`)+\"\".concat(actualLines[0],\" !== \").concat(expectedLines[0],`\n`)}else if(operator!==\"strictEqualObject\"){var maxLength=process.stderr&&process.stderr.isTTY\?process.stderr.columns:80;if(inputLength2&&(indicator=`\n `.concat(repeat(\" \",i),\"^\"),i=0)}}}for(var a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];a===b&&(i++<2\?end=`\n `.concat(a).concat(end):other=a,actualLines.pop(),expectedLines.pop(),!(actualLines.length===0||expectedLines.length===0));)a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];var maxLines=Math.max(actualLines.length,expectedLines.length);if(maxLines===0){var _actualLines=actualInspected.split(`\n`);if(_actualLines.length>30)for(_actualLines[26]=\"\".concat(blue,\"...\").concat(white);_actualLines.length>27;)_actualLines.pop();return\"\".concat(kReadableOperator.notIdentical,`\n\n`).concat(_actualLines.join(`\n`),`\n`)}i>3&&(end=`\n`.concat(blue,\"...\").concat(white).concat(end),skipped=!0),other!==\"\"&&(end=`\n `.concat(other).concat(end),other=\"\");var printedLines=0,msg=kReadableOperator[operator]+`\n`.concat(green,\"+ actual\").concat(white,\" \").concat(red,\"- expected\").concat(white),skippedMsg=\" \".concat(blue,\"...\").concat(white,\" Lines skipped\");for(i=0;i1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(expectedLines[i-2]),printedLines++),res+=`\n `.concat(expectedLines[i-1]),printedLines++),lastPos=i,other+=`\n`.concat(red,\"-\").concat(white,\" \").concat(expectedLines[i]),printedLines++;else if(expectedLines.length1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(actualLines[i-2]),printedLines++),res+=`\n `.concat(actualLines[i-1]),printedLines++),lastPos=i,res+=`\n`.concat(green,\"+\").concat(white,\" \").concat(actualLines[i]),printedLines++;else{var expectedLine=expectedLines[i],actualLine=actualLines[i],divergingLines=actualLine!==expectedLine&&(!endsWith(actualLine,\",\")||actualLine.slice(0,-1)!==expectedLine);divergingLines&&endsWith(expectedLine,\",\")&&expectedLine.slice(0,-1)===actualLine&&(divergingLines=!1,actualLine+=\",\"),divergingLines\?(cur>1&&i>2&&(cur>4\?(res+=`\n`.concat(blue,\"...\").concat(white),skipped=!0):cur>3&&(res+=`\n `.concat(actualLines[i-2]),printedLines++),res+=`\n `.concat(actualLines[i-1]),printedLines++),lastPos=i,res+=`\n`.concat(green,\"+\").concat(white,\" \").concat(actualLine),other+=`\n`.concat(red,\"-\").concat(white,\" \").concat(expectedLine),printedLines+=2):(res+=other,other=\"\",(cur===1||i===0)&&(res+=`\n `.concat(actualLine),printedLines++))}if(printedLines>20&&i30)for(res[26]=\"\".concat(blue,\"...\").concat(white);res.length>27;)res.pop();res.length===1\?_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(base,\" \").concat(res[0]))):_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(base,`\n\n`).concat(res.join(`\n`),`\n`)))}else{var _res=inspectValue(actual),other=\"\",knownOperators=kReadableOperator[operator];operator===\"notDeepEqual\"||operator===\"notEqual\"\?(_res=\"\".concat(kReadableOperator[operator],`\n\n`).concat(_res),_res.length>1024&&(_res=\"\".concat(_res.slice(0,1021),\"...\"))):(other=\"\".concat(inspectValue(expected)),_res.length>512&&(_res=\"\".concat(_res.slice(0,509),\"...\")),other.length>512&&(other=\"\".concat(other.slice(0,509),\"...\")),operator===\"deepEqual\"||operator===\"equal\"\?_res=\"\".concat(knownOperators,`\n\n`).concat(_res,`\n\nshould equal\n\n`):other=\" \".concat(operator,\" \").concat(other)),_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError2).call(this,\"\".concat(_res).concat(other)))}return Error.stackTraceLimit=limit,_this.generatedMessage=!message,Object.defineProperty(_assertThisInitialized(_this),\"name\",{value:\"AssertionError [ERR_ASSERTION]\",enumerable:!1,writable:!0,configurable:!0}),_this.code=\"ERR_ASSERTION\",_this.actual=actual,_this.expected=expected,_this.operator=operator,Error.captureStackTrace&&Error.captureStackTrace(_assertThisInitialized(_this),stackStartFn),_this.stack,_this.name=\"AssertionError\",_possibleConstructorReturn(_this)}return AssertionError2.prototype={},_inherits(AssertionError2,_Error),_createClass(AssertionError2,[{key:\"toString\",value:function(){return\"\".concat(this.name,\" [\").concat(this.code,\"]: \").concat(this.message)}},{key:inspect.custom,value:function(recurseTimes,ctx){return inspect(this,_objectSpread({},ctx,{customInspect:!1,depth:0}))}}]),AssertionError2}(_wrapNativeSuper(Error));module2.exports=AssertionError}}),require_assert=__commonJS({\"assert/build/assert.js\"(exports,module2){function _typeof(obj){return typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"\?_typeof=function(obj2){return typeof obj2}:_typeof=function(obj2){return obj2&&typeof Symbol==\"function\"&&obj2.constructor===Symbol&&obj2!==Symbol.prototype\?\"symbol\":typeof obj2},_typeof(obj)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))@throwTypeError(\"Cannot call a class as a function\")}var _require=require_errors(),_require$codes=_require.codes,ERR_AMBIGUOUS_ARGUMENT=_require$codes.ERR_AMBIGUOUS_ARGUMENT,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_INVALID_ARG_VALUE=_require$codes.ERR_INVALID_ARG_VALUE,ERR_INVALID_RETURN_VALUE=_require$codes.ERR_INVALID_RETURN_VALUE,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,AssertionError=require_assertion_error(),_require2=util,inspect=_require2.inspect,_require$types=util.types,isPromise=_require$types.isPromise,isRegExp=_require$types.isRegExp,objectAssign=Object.assign,objectIs=Object.is,errorCache=new Map,warned=!1,assert=module2.exports=ok,NO_EXCEPTION_SENTINEL={};function innerFail(obj){throw obj.message instanceof Error\?obj.message:new AssertionError(obj)}function fail(actual,expected,message,operator,stackStartFn){var argsLen=arguments.length,internalMessage;if(argsLen===0)internalMessage=\"Failed\";else if(argsLen===1)message=actual,actual=void 0;else{if(warned===!1){warned=!0;var warn=process.emitWarning\?process.emitWarning:console.warn.bind(console);warn(\"assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.\",\"DeprecationWarning\",\"DEP0094\")}argsLen===2&&(operator=\"!=\")}if(message instanceof Error)throw message;var errArgs={actual,expected,operator:operator===void 0\?\"fail\":operator,stackStartFn:stackStartFn||fail};message!==void 0&&(errArgs.message=message);var err=new AssertionError(errArgs);throw internalMessage&&(err.message=internalMessage,err.generatedMessage=!0),err}assert.fail=fail,assert.AssertionError=AssertionError;function innerOk(fn,argLen,value,message){if(!value){var generatedMessage=!1;if(argLen===0)generatedMessage=!0,message=\"No value argument passed to `assert.ok()`\";else if(message instanceof Error)throw message;var err=new AssertionError({actual:value,expected:!0,message,operator:\"==\",stackStartFn:fn});throw err.generatedMessage=generatedMessage,err}}function ok(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];innerOk.apply(void 0,[ok,args.length].concat(args))}assert.ok=ok,assert.equal=function equal(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");actual!=expected&&innerFail({actual,expected,message,operator:\"==\",stackStartFn:equal})},assert.notEqual=function notEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");actual==expected&&innerFail({actual,expected,message,operator:\"!=\",stackStartFn:notEqual})},assert.deepEqual=function deepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!1)||innerFail({actual,expected,message,operator:\"deepEqual\",stackStartFn:deepEqual})},assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!1)&&innerFail({actual,expected,message,operator:\"notDeepEqual\",stackStartFn:notDeepEqual})},assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!0)||innerFail({actual,expected,message,operator:\"deepStrictEqual\",stackStartFn:deepStrictEqual})},assert.notDeepStrictEqual=notDeepStrictEqual;function notDeepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");isDeepEqual(actual,expected,!0)&&innerFail({actual,expected,message,operator:\"notDeepStrictEqual\",stackStartFn:notDeepStrictEqual})}assert.strictEqual=function strictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");objectIs(actual,expected)||innerFail({actual,expected,message,operator:\"strictEqual\",stackStartFn:strictEqual})},assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");objectIs(actual,expected)&&innerFail({actual,expected,message,operator:\"notStrictEqual\",stackStartFn:notStrictEqual})},assert.match=function match(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS(\"actual\",\"expected\");if(!isRegExp(expected))throw new ERR_INVALID_ARG_TYPE(\"expected\",\"RegExp\",expected);expected.test(actual)||innerFail({actual,expected,message,operator:\"match\",stackStartFn:match})};var Comparison=function Comparison2(obj,keys,actual){var _this=this;_classCallCheck(this,Comparison2),keys.forEach(function(key){(key in obj)&&(actual!==void 0&&typeof actual[key]==\"string\"&&isRegExp(obj[key])&&obj[key].test(actual[key])\?_this[key]=actual[key]:_this[key]=obj[key])})};function compareExceptionKey(actual,expected,key,message,keys,fn){if(!(key in actual)||!isDeepEqual(actual[key],expected[key],!0)){if(!message){var a=new Comparison(actual,keys),b=new Comparison(expected,keys,actual),err=new AssertionError({actual:a,expected:b,operator:\"deepStrictEqual\",stackStartFn:fn});throw err.actual=actual,err.expected=expected,err.operator=fn.name,err}innerFail({actual,expected,message,operator:fn.name,stackStartFn:fn})}}function expectedException(actual,expected,msg,fn){if(typeof expected!=\"function\"){if(isRegExp(expected))return expected.test(actual);if(arguments.length===2)throw new ERR_INVALID_ARG_TYPE(\"expected\",[\"Function\",\"RegExp\"],expected);if(_typeof(actual)!==\"object\"||actual===null){var err=new AssertionError({actual,expected,message:msg,operator:\"deepStrictEqual\",stackStartFn:fn});throw err.operator=fn.name,err}var keys=Object.keys(expected);if(expected instanceof Error)keys.push(\"name\",\"message\");else if(keys.length===0)throw new ERR_INVALID_ARG_VALUE(\"error\",expected,\"may not be an empty object\");return keys.forEach(function(key){return typeof actual[key]==\"string\"&&isRegExp(expected[key])&&expected[key].test(actual[key])||compareExceptionKey(actual,expected,key,msg,keys,fn)}),!0}return expected.prototype!==void 0&&actual instanceof expected\?!0:Error.isPrototypeOf(expected)\?!1:expected.call({},actual)===!0}function getActual(fn){if(typeof fn!=\"function\")throw new ERR_INVALID_ARG_TYPE(\"fn\",\"Function\",fn);try{fn()}catch(e){return e}return NO_EXCEPTION_SENTINEL}function checkIsPromise(obj){return isPromise(obj)||obj!==null&&_typeof(obj)===\"object\"&&typeof obj.then==\"function\"&&typeof obj.catch==\"function\"}function waitForActual(promiseFn){return Promise.resolve().then(function(){var resultPromise;if(typeof promiseFn==\"function\"){if(resultPromise=promiseFn(),!checkIsPromise(resultPromise))throw new ERR_INVALID_RETURN_VALUE(\"instance of Promise\",\"promiseFn\",resultPromise)}else if(checkIsPromise(promiseFn))resultPromise=promiseFn;else throw new ERR_INVALID_ARG_TYPE(\"promiseFn\",[\"Function\",\"Promise\"],promiseFn);return Promise.resolve().then(function(){return resultPromise}).then(function(){return NO_EXCEPTION_SENTINEL}).catch(function(e){return e})})}function expectsError(stackStartFn,actual,error,message){if(typeof error==\"string\"){if(arguments.length===4)throw new ERR_INVALID_ARG_TYPE(\"error\",[\"Object\",\"Error\",\"Function\",\"RegExp\"],error);if(_typeof(actual)===\"object\"&&actual!==null){if(actual.message===error)throw new ERR_AMBIGUOUS_ARGUMENT(\"error/message\",'The error message \"'.concat(actual.message,'\" is identical to the message.'))}else if(actual===error)throw new ERR_AMBIGUOUS_ARGUMENT(\"error/message\",'The error \"'.concat(actual,'\" is identical to the message.'));message=error,error=void 0}else if(error!=null&&_typeof(error)!==\"object\"&&typeof error!=\"function\")throw new ERR_INVALID_ARG_TYPE(\"error\",[\"Object\",\"Error\",\"Function\",\"RegExp\"],error);if(actual===NO_EXCEPTION_SENTINEL){var details=\"\";error&&error.name&&(details+=\" (\".concat(error.name,\")\")),details+=message\?\": \".concat(message):\".\";var fnType=stackStartFn.name===\"rejects\"\?\"rejection\":\"exception\";innerFail({actual:void 0,expected:error,operator:stackStartFn.name,message:\"Missing expected \".concat(fnType).concat(details),stackStartFn})}if(error&&!expectedException(actual,error,message,stackStartFn))throw actual}function expectsNoError(stackStartFn,actual,error,message){if(actual!==NO_EXCEPTION_SENTINEL){if(typeof error==\"string\"&&(message=error,error=void 0),!error||expectedException(actual,error)){var details=message\?\": \".concat(message):\".\",fnType=stackStartFn.name===\"doesNotReject\"\?\"rejection\":\"exception\";innerFail({actual,expected:error,operator:stackStartFn.name,message:\"Got unwanted \".concat(fnType).concat(details,`\n`)+'Actual message: \"'.concat(actual&&actual.message,'\"'),stackStartFn})}throw actual}}assert.throws=function throws(promiseFn){for(var _len2=arguments.length,args=new Array(_len2>1\?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];expectsError.apply(void 0,[throws,getActual(promiseFn)].concat(args))},assert.rejects=function rejects(promiseFn){for(var _len3=arguments.length,args=new Array(_len3>1\?_len3-1:0),_key3=1;_key3<_len3;_key3++)args[_key3-1]=arguments[_key3];return waitForActual(promiseFn).then(function(result){return expectsError.apply(void 0,[rejects,result].concat(args))})},assert.doesNotThrow=function doesNotThrow(fn){for(var _len4=arguments.length,args=new Array(_len4>1\?_len4-1:0),_key4=1;_key4<_len4;_key4++)args[_key4-1]=arguments[_key4];expectsNoError.apply(void 0,[doesNotThrow,getActual(fn)].concat(args))},assert.doesNotReject=function doesNotReject(fn){for(var _len5=arguments.length,args=new Array(_len5>1\?_len5-1:0),_key5=1;_key5<_len5;_key5++)args[_key5-1]=arguments[_key5];return waitForActual(fn).then(function(result){return expectsNoError.apply(void 0,[doesNotReject,result].concat(args))})},assert.ifError=function ifError(err){if(err!=null){var message=\"ifError got unwanted exception: \";_typeof(err)===\"object\"&&typeof err.message==\"string\"\?err.message.length===0&&err.constructor\?message+=err.constructor.name:message+=err.message:message+=inspect(err);var newErr=new AssertionError({actual:err,expected:null,operator:\"ifError\",message,stackStartFn:ifError}),origStack=err.stack;if(typeof origStack==\"string\"){var tmp2=origStack.split(`\n`);tmp2.shift();for(var tmp1=newErr.stack.split(`\n`),i=0;i{var prev=get();set(context);try{return fn(...args)}catch(error){throw error}finally{set(prev)}}}enterWith(store){cleanupLater();var context=get();if(!context){set([this,store]);return}var{length}=context;for(var i=0;i-1)hasPrevious=!0,previous=context[i+1],context[i+1]=store;else context.push(this,store);set(context)}try{return callback(...args)}catch(e){throw e}finally{if(!this.#disableCalled){var context2=get();if(context2===context&&contextWasInit)set(void 0);else if(context2=context2.slice(),hasPrevious)context2[i+1]=previous,set(context2);else context2.splice(i,2),set(context2.length\?context2:void 0)}}}disable(){if(!this.#disableCalled){var context=get();if(context){var{length}=context;for(var i=0;i-1){try{child.kill(killSignal)}catch(err){child.emit(\"error\",err)}timeoutHolder.timeoutId=-1}}function spawn(file,args,options){options=normalizeSpawnArguments(file,args,options),validateTimeout(options.timeout),validateAbortSignal(options.signal,\"options.signal\");const killSignal2=sanitizeKillSignal(options.killSignal),child=new ChildProcess;if(child.spawn(options),options.timeout>0){let timeoutId=setTimeout(()=>{if(timeoutId){try{child.kill(killSignal2)}catch(err){child.emit(\"error\",err)}timeoutId=null}});child.once(\"exit\",()=>{if(timeoutId)clearTimeout(timeoutId),timeoutId=null})}if(options.signal){let onAbortListener2=function(){abortChildProcess(child,killSignal2,options.signal.reason)};var onAbortListener=onAbortListener2;const signal=options.signal;if(signal.aborted)process.nextTick(onAbortListener2);else signal.addEventListener(\"abort\",onAbortListener2,{once:!0}),child.once(\"exit\",()=>signal.removeEventListener(\"abort\",onAbortListener2))}return child}function execFile(file,args,options,callback){({file,args,options,callback}=normalizeExecFileArgs(file,args,options,callback)),options={encoding:\"utf8\",timeout:0,maxBuffer:MAX_BUFFER,killSignal:\"SIGTERM\",cwd:null,env:null,shell:!1,...options};const maxBuffer=options.maxBuffer;validateTimeout(options.timeout),validateMaxBuffer(maxBuffer),options.killSignal=sanitizeKillSignal(options.killSignal);const child=spawn(file,args,{cwd:options.cwd,env:options.env,shell:options.shell,signal:options.signal});let encoding;const _stdout=[],_stderr=[];if(options.encoding!==\"buffer\"&&BufferIsEncoding(options.encoding))encoding=options.encoding;else encoding=null;let stdoutLen=0,stderrLen=0,killed=!1,exited=!1,timeoutId,encodedStdoutLen,encodedStderrLen,ex=null,cmd=file;function exitHandler(code,signal){if(exited)return;if(exited=!0,timeoutId)clearTimeout(timeoutId),timeoutId=null;if(!callback)return;const readableEncoding=child\?.stdout\?.readableEncoding;let stdout,stderr;if(encoding||child.stdout&&readableEncoding)stdout=ArrayPrototypeJoin.call(_stdout,\"\");else stdout=BufferConcat(_stdout);if(encoding||child.stderr&&readableEncoding)stderr=ArrayPrototypeJoin.call(_stderr,\"\");else stderr=BufferConcat(_stderr);if(!ex&&code===0&&signal===null){callback(null,stdout,stderr);return}if(args\?.length)cmd+=` ${ArrayPrototypeJoin.call(args,\" \")}`;if(!ex){let message=`Command failed: ${cmd}`;if(stderr)message+=`\\n${stderr}`;ex=genericNodeError(message,{code,killed:child.killed||killed,signal})}ex.cmd=cmd,callback(ex,stdout,stderr)}function errorHandler(e){if(ex=e,child.stdout)child.stdout.destroy();if(child.stderr)child.stderr.destroy();exitHandler()}function kill(){if(child.stdout)child.stdout.destroy();if(child.stderr)child.stderr.destroy();killed=!0;try{child.kill(options.killSignal)}catch(e){ex=e,exitHandler()}}if(options.timeout>0)timeoutId=setTimeout(function delayedKill(){kill(),timeoutId=null},options.timeout);if(child.stdout){if(encoding)child.stdout.setEncoding(encoding);child.stdout.on(\"data\",maxBuffer===Infinity\?function onUnlimitedSizeBufferedData(chunk){ArrayPrototypePush.call(_stdout,chunk)}:encoding\?function onChildStdoutEncoded(chunk){if(stdoutLen+=chunk.length,stdoutLen*4>maxBuffer){const encoding2=child.stdout.readableEncoding,actualLen=Buffer.byteLength(chunk,encoding2);if(encodedStdoutLen===void 0)for(let i=0;i<_stdout.length;i++)encodedStdoutLen+=Buffer.byteLength(_stdout[i],encoding2);else encodedStdoutLen+=actualLen;const truncatedLen=maxBuffer-(encodedStdoutLen-actualLen);ArrayPrototypePush.call(_stdout,StringPrototypeSlice.apply(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stdout\"),kill()}else ArrayPrototypePush.call(_stdout,chunk)}:function onChildStdoutRaw(chunk){if(stdoutLen+=chunk.length,stdoutLen>maxBuffer){const truncatedLen=maxBuffer-(stdoutLen-chunk.length);ArrayPrototypePush.call(_stdout,chunk.slice(0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stdout\"),kill()}else ArrayPrototypePush.call(_stdout,chunk)})}if(child.stderr){if(encoding)child.stderr.setEncoding(encoding);child.stderr.on(\"data\",maxBuffer===Infinity\?function onUnlimitedSizeBufferedData(chunk){ArrayPrototypePush.call(_stderr,chunk)}:encoding\?function onChildStderrEncoded(chunk){if(stderrLen+=chunk.length,stderrLen*4>maxBuffer){const encoding2=child.stderr.readableEncoding,actualLen=Buffer.byteLength(chunk,encoding2);if(encodedStderrLen===void 0)for(let i=0;i<_stderr.length;i++)encodedStderrLen+=Buffer.byteLength(_stderr[i],encoding2);else encodedStderrLen+=actualLen;const truncatedLen=maxBuffer-(encodedStderrLen-actualLen);ArrayPrototypePush.call(_stderr,StringPrototypeSlice.call(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stderr\"),kill()}else ArrayPrototypePush.call(_stderr,chunk)}:function onChildStderrRaw(chunk){if(stderrLen+=chunk.length,stderrLen>maxBuffer){const truncatedLen=maxBuffer-(stderrLen-chunk.length);ArrayPrototypePush.call(_stderr,StringPrototypeSlice.call(chunk,0,truncatedLen)),ex=new ERR_CHILD_PROCESS_STDIO_MAXBUFFER(\"stderr\"),kill()}else ArrayPrototypePush.call(_stderr,chunk)})}return child.addListener(\"close\",exitHandler),child.addListener(\"error\",errorHandler),child}function exec(command,options,callback){const opts=normalizeExecArgs(command,options,callback);return execFile(opts.file,opts.options,opts.callback)}const customPromiseExecFunction=(orig)=>{return(...args)=>{let resolve,reject;const promise=new Promise((res,rej)=>{resolve=res,reject=rej});return promise.child=orig(...args,(err,stdout,stderr)=>{if(err!==null)err.stdout=stdout,err.stderr=stderr,reject(err);else resolve({stdout,stderr})}),promise}};ObjectDefineProperty(exec,promisify.custom,{__proto__:null,enumerable:!1,value:customPromiseExecFunction(exec)});function spawnSync(file,args,options){options={maxBuffer:MAX_BUFFER,...normalizeSpawnArguments(file,args,options)};const{maxBuffer,encoding}=options;validateTimeout(options.timeout),validateMaxBuffer(maxBuffer),options.killSignal=sanitizeKillSignal(options.killSignal);const stdio=options.stdio||\"pipe\",bunStdio=getBunStdioFromOptions(stdio);var{input}=options;if(input)if(ArrayBufferIsView(input))bunStdio[0]=input;else if(typeof input===\"string\")bunStdio[0]=Buffer.from(input,encoding||\"utf8\");else throw new ERR_INVALID_ARG_TYPE(\"options.stdio[0]\",[\"Buffer\",\"TypedArray\",\"DataView\",\"string\"],input);const{stdout,stderr,success,exitCode}=Bun.spawnSync({cmd:options.args,env:options.env||void 0,cwd:options.cwd||void 0,stdin:bunStdio[0],stdout:bunStdio[1],stderr:bunStdio[2]}),result={signal:null,status:exitCode,output:[null,stdout,stderr]};if(stdout&&encoding&&encoding!==\"buffer\")result.output[1]=result.output[1]\?.toString(encoding);if(stderr&&encoding&&encoding!==\"buffer\")result.output[2]=result.output[2]\?.toString(encoding);if(result.stdout=result.output[1],result.stderr=result.output[2],!success)result.error=new SystemError(result.output[2],options.file,\"spawnSync\",-1,result.status),result.error.spawnargs=ArrayPrototypeSlice.call(options.args,1);return result}function execFileSync(file,args,options){({file,args,options}=normalizeExecFileArgs(file,args,options));const ret=spawnSync(file,args,options),errArgs=[options.argv0||file];ArrayPrototypePush.apply(errArgs,args);const err=checkExecSyncError(ret,errArgs);if(err)throw err;return ret.stdout}function execSync(command,options){const opts=normalizeExecArgs(command,options,null),ret=spawnSync(opts.file,opts.options),err=checkExecSyncError(ret,void 0,command);if(err)throw err;return ret.stdout}function stdioStringToArray(stdio,channel){const options=[];switch(stdio){case\"ignore\":case\"overlapped\":case\"pipe\":ArrayPrototypePush.call(options,stdio,stdio,stdio);break;case\"inherit\":ArrayPrototypePush.call(options,0,1,2);break;default:throw new ERR_INVALID_ARG_VALUE(\"stdio\",stdio)}if(channel)ArrayPrototypePush.call(options,channel);return options}function fork(modulePath,args=[],options){modulePath=getValidatedPath(modulePath,\"modulePath\");let execArgv;if(args==null)args=[];else if(typeof args===\"object\"&&!ArrayIsArray(args))options=args,args=[];else validateArray(args,\"args\");if(options!=null)validateObject(options,\"options\");if(options={__proto__:null,...options,shell:!1},options.execPath=options.execPath||process.execPath,validateArgumentNullCheck(options.execPath,\"options.execPath\"),execArgv=options.execArgv||process.execArgv,validateArgumentsNullCheck(execArgv,\"options.execArgv\"),execArgv===process.execArgv&&process._eval!=null){const index=ArrayPrototypeLastIndexOf.call(execArgv,process._eval);if(index>0)execArgv=ArrayPrototypeSlice.call(execArgv),ArrayPrototypeSplice.call(execArgv,index-1,2)}if(args=[...execArgv,modulePath,...args],typeof options.stdio===\"string\")options.stdio=stdioStringToArray(options.stdio,\"ipc\");else if(!ArrayIsArray(options.stdio))options.stdio=stdioStringToArray(options.silent\?\"pipe\":\"inherit\",\"ipc\");else if(!ArrayPrototypeIncludes.call(options.stdio,\"ipc\"))throw new ERR_CHILD_PROCESS_IPC_REQUIRED(\"options.stdio\");return spawn(options.execPath,args,options)}function convertToValidSignal(signal){if(typeof signal===\"number\"&&getSignalsToNamesMapping()[signal])return signal;if(typeof signal===\"string\"){const signalName=signals[StringPrototypeToUpperCase.call(signal)];if(signalName)return signalName}throw new ERR_UNKNOWN_SIGNAL(signal)}function sanitizeKillSignal(killSignal2){if(typeof killSignal2===\"string\"||typeof killSignal2===\"number\")return convertToValidSignal(killSignal2);else if(killSignal2!=null)throw new ERR_INVALID_ARG_TYPE(\"options.killSignal\",[\"string\",\"number\"],killSignal2)}let signalsToNamesMapping;function getSignalsToNamesMapping(){if(signalsToNamesMapping!==void 0)return signalsToNamesMapping;signalsToNamesMapping=ObjectCreate(null);for(let key in signals)signalsToNamesMapping[signals[key]]=key;return signalsToNamesMapping}function normalizeExecFileArgs(file,args,options,callback){if(ArrayIsArray(args))args=ArrayPrototypeSlice.call(args);else if(args!=null&&typeof args===\"object\")callback=options,options=args,args=null;else if(typeof args===\"function\")callback=args,options=null,args=null;if(args==null)args=[];if(typeof options===\"function\")callback=options;else if(options!=null)validateObject(options,\"options\");if(options==null)options=kEmptyObject;if(callback!=null)validateFunction(callback,\"callback\");if(options.argv0!=null)validateString(options.argv0,\"options.argv0\"),validateArgumentNullCheck(options.argv0,\"options.argv0\");return{file,args,options,callback}}function normalizeExecArgs(command,options,callback){if(validateString(command,\"command\"),validateArgumentNullCheck(command,\"command\"),typeof options===\"function\")callback=options,options=void 0;return options={...options},options.shell=typeof options.shell===\"string\"\?options.shell:!0,{file:command,options,callback}}function normalizeSpawnArguments(file,args,options){if(validateString(file,\"file\"),validateArgumentNullCheck(file,\"file\"),file.length===0)throw new ERR_INVALID_ARG_VALUE(\"file\",file,\"cannot be empty\");if(ArrayIsArray(args))args=ArrayPrototypeSlice.call(args);else if(args==null)args=[];else if(typeof args!==\"object\")throw new ERR_INVALID_ARG_TYPE(\"args\",\"object\",args);else options=args,args=[];if(validateArgumentsNullCheck(args,\"args\"),options===void 0)options={};else validateObject(options,\"options\");let cwd=options.cwd;if(cwd!=null)cwd=getValidatedPath(cwd,\"options.cwd\");if(options.shell!=null&&typeof options.shell!==\"boolean\"&&typeof options.shell!==\"string\")throw new ERR_INVALID_ARG_TYPE(\"options.shell\",[\"boolean\",\"string\"],options.shell);if(options.argv0!=null)validateString(options.argv0,\"options.argv0\"),validateArgumentNullCheck(options.argv0,\"options.argv0\");if(options.shell){validateArgumentNullCheck(options.shell,\"options.shell\");const command=ArrayPrototypeJoin.call([file,...args],\" \");if(typeof options.shell===\"string\")file=options.shell;else file=\"sh\";args=[\"-c\",command]}if(typeof options.argv0===\"string\")ArrayPrototypeUnshift.call(args,options.argv0);else ArrayPrototypeUnshift.call(args,file);const envPairs=options.env||process.env;return{...options,file,args,cwd,envPairs}}function checkExecSyncError(ret,args,cmd){let err;if(ret.error)err=ret.error,ObjectAssign(err,ret);else if(ret.status!==0){let msg=\"Command failed: \";if(msg+=cmd||ArrayPrototypeJoin.call(args,\" \"),ret.stderr&&ret.stderr.length>0)msg+=`\\n${ret.stderr.toString()}`;err=genericNodeError(msg,ret)}return err}class ChildProcess extends EventEmitter{constructor(){super(...arguments)}#handle;#exited=!1;#closesNeeded=1;#closesGot=0;connected=!1;signalCode=null;exitCode=null;spawnfile;spawnargs;pid;channel;get killed(){if(this.#handle==null)return!1}#handleOnExit(exitCode,signalCode,err){if(this.#exited)return;if(signalCode)this.signalCode=signalCode;else this.exitCode=exitCode;if(this.#stdin)this.#stdin.destroy();if(this.#handle)this.#handle=null;if(exitCode<0){const err2=new SystemError(`Spawned process exited with error code: ${exitCode}`,void 0,\"spawn\",\"EUNKNOWN\",\"ERR_CHILD_PROCESS_UNKNOWN_ERROR\");if(this.spawnfile)err2.path=this.spawnfile;err2.spawnargs=ArrayPrototypeSlice.call(this.spawnargs,1),this.emit(\"error\",err2)}else this.emit(\"exit\",this.exitCode,this.signalCode);process.nextTick(flushStdio,this),this.#maybeClose(),this.#exited=!0,this.#stdioOptions=[\"destroyed\",\"destroyed\",\"destroyed\"]}#getBunSpawnIo(i,encoding){NativeWritable||=StreamModule.NativeWritable,ReadableFromWeb||=StreamModule.Readable.fromWeb;const io=this.#stdioOptions[i];switch(i){case 0:switch(io){case\"pipe\":return new NativeWritable(this.#handle.stdin);case\"inherit\":return process.stdin||null;case\"destroyed\":return new ShimmedStdin;default:return null}case 2:case 1:switch(io){case\"pipe\":return ReadableFromWeb(this.#handle[fdToStdioName(i)],{encoding});case\"inherit\":return process[fdToStdioName(i)]||null;case\"destroyed\":return new ShimmedStdioOutStream;default:return null}}}#stdin;#stdout;#stderr;#stdioObject;#encoding;#stdioOptions;#createStdioObject(){return Object.create(null,{0:{get:()=>this.stdin},1:{get:()=>this.stdout},2:{get:()=>this.stderr}})}get stdin(){return this.#stdin\?\?=this.#getBunSpawnIo(0,this.#encoding)}get stdout(){return this.#stdout\?\?=this.#getBunSpawnIo(1,this.#encoding)}get stderr(){return this.#stderr\?\?=this.#getBunSpawnIo(2,this.#encoding)}get stdio(){return this.#stdioObject\?\?=this.#createStdioObject()}spawn(options){validateObject(options,\"options\"),validateString(options.file,\"options.file\");var file=this.spawnfile=options.file,spawnargs;if(options.args==null)spawnargs=this.spawnargs=[];else validateArray(options.args,\"options.args\"),spawnargs=this.spawnargs=options.args;const stdio=options.stdio||[\"pipe\",\"pipe\",\"pipe\"],bunStdio=getBunStdioFromOptions(stdio);var env=options.envPairs||void 0;this.#encoding=options.encoding||void 0,this.#stdioOptions=bunStdio,this.#handle=Bun.spawn({cmd:spawnargs,stdin:bunStdio[0],stdout:bunStdio[1],stderr:bunStdio[2],cwd:options.cwd||void 0,env:env||process.env,onExit:(handle,exitCode,signalCode,err)=>{this.#handle=handle,this.pid=this.#handle.pid,process.nextTick((exitCode2,signalCode2,err2)=>this.#handleOnExit(exitCode2,signalCode2,err2),exitCode,signalCode,err)},lazy:!0}),this.pid=this.#handle.pid,onSpawnNT(this)}send(){console.log(\"ChildProcess.prototype.send() - Sorry! Not implemented yet\")}disconnect(){console.log(\"ChildProcess.prototype.disconnect() - Sorry! Not implemented yet\")}kill(sig){const signal=sig===0\?sig:convertToValidSignal(sig===void 0\?\"SIGTERM\":sig);if(this.#handle)this.#handle.kill(signal);return this.#maybeClose(),!0}#maybeClose(){if(this.#closesGot++,this.#closesGot===this.#closesNeeded)this.emit(\"close\",this.exitCode,this.signalCode)}ref(){if(this.#handle)this.#handle.ref()}unref(){if(this.#handle)this.#handle.unref()}}const nodeToBunLookup={ignore:null,pipe:\"pipe\",overlapped:\"pipe\",inherit:\"inherit\"};function nodeToBun(item){if(typeof item===\"number\")return item;else{const result=nodeToBunLookup[item];if(result===void 0)throw new Error(\"Invalid stdio option\");return result}}function fdToStdioName(fd){switch(fd){case 0:return\"stdin\";case 1:return\"stdout\";case 2:return\"stderr\";default:return null}}function getBunStdioFromOptions(stdio){return normalizeStdio(stdio).map((item)=>nodeToBun(item))}function normalizeStdio(stdio){if(typeof stdio===\"string\")switch(stdio){case\"ignore\":return[\"ignore\",\"ignore\",\"ignore\"];case\"pipe\":return[\"pipe\",\"pipe\",\"pipe\"];case\"inherit\":return[\"inherit\",\"inherit\",\"inherit\"];default:throw new ERR_INVALID_OPT_VALUE(\"stdio\",stdio)}else if(ArrayIsArray(stdio)){let processedStdio;if(stdio.length===0)processedStdio=[\"pipe\",\"pipe\",\"pipe\"];else if(stdio.length===1)processedStdio=[stdio[0],\"pipe\",\"pipe\"];else if(stdio.length===2)processedStdio=[stdio[0],stdio[1],\"pipe\"];else if(stdio.length>=3)processedStdio=[stdio[0],stdio[1],stdio[2]];return processedStdio.map((item)=>!item\?\"pipe\":item)}else throw new ERR_INVALID_OPT_VALUE(\"stdio\",stdio)}function flushStdio(subprocess){const stdio=subprocess.stdio;if(stdio==null)return;for(let i=0;i=0))throw new ERR_OUT_OF_RANGE(\"options.maxBuffer\",\"a positive number\",maxBuffer)}function validateArgumentNullCheck(arg,propName){if(typeof arg===\"string\"&&StringPrototypeIncludes.call(arg,\"\\0\"))throw new ERR_INVALID_ARG_VALUE(propName,arg,\"must be a string without null bytes\")}function validateArgumentsNullCheck(args,propName){for(let i=0;i=0))throw new ERR_OUT_OF_RANGE(\"timeout\",\"an unsigned integer\",timeout)}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}function validateFunction(value,name){if(typeof value!==\"function\")throw new ERR_INVALID_ARG_TYPE(name,\"Function\",value)}const validateAbortSignal=(signal,name)=>{if(signal!==void 0&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE(name,\"AbortSignal\",signal)},validateOneOf=(value,name,oneOf)=>{if(!ArrayPrototypeIncludes.call(oneOf,value)){const reason=\"must be one of: \"+ArrayPrototypeJoin.call(ArrayPrototypeMap.call(oneOf,(v)=>typeof v===\"string\"\?`'${v}'`:String(v)),\", \");throw new ERR_INVALID_ARG_VALUE(name,value,reason)}},validateObject=(value,name,options=null)=>{const allowArray=options\?.allowArray\?\?!1,allowFunction=options\?.allowFunction\?\?!1;if(!(options\?.nullable\?\?!1)&&value===null||!allowArray&&ArrayIsArray.call(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE(name,\"object\",value)},validateArray=(value,name,minLength=0)=>{if(!ArrayIsArray(value))throw new ERR_INVALID_ARG_TYPE(name,\"Array\",value);if(value.lengthfunction(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},require_safe_buffer=__commonJS({\"node_modules/safe-buffer/index.js\"(exports,module){var buffer=BufferModule,Buffer2=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}Buffer2.from&&Buffer2.alloc&&Buffer2.allocUnsafe&&Buffer2.allocUnsafeSlow\?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer);function SafeBuffer(arg,encodingOrOffset,length){return Buffer2(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer2.prototype),copyProps(Buffer2,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==\"number\")@throwTypeError(\"Argument must not be a number\");return Buffer2(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");var buf=Buffer2(size);return fill!==void 0\?typeof encoding==\"string\"\?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");return Buffer2(size)},SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=\"number\")@throwTypeError(\"Argument must be a number\");return buffer.SlowBuffer(size)}}}),require_browser=__commonJS({\"node_modules/randombytes/browser.js\"(exports,module){var MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser(){throw new Error(`Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11`)}var Buffer2=require_safe_buffer().Buffer,crypto2=globalCrypto;crypto2&&crypto2.getRandomValues\?module.exports=randomBytes:module.exports=oldBrowser;function randomBytes(size,cb){if(size>MAX_UINT32)@throwRangeError(\"requested too many random bytes\");var bytes=Buffer2.allocUnsafe(size);if(size>0)if(size>MAX_BYTES)for(var generated=0;generated=this._blockSize;){for(var i=this._blockOffset;i0;++j)this._length[j]+=carry,carry=this._length[j]/4294967296|0,carry>0&&(this._length[j]-=4294967296*carry);return this},HashBase.prototype._update=function(){throw new Error(\"_update is not implemented\")},HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error(\"Digest already called\");this._finalized=!0;var digest=this._digest();encoding!==void 0&&(digest=digest.toString(encoding)),this._block.fill(0),this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return digest},HashBase.prototype._digest=function(){throw new Error(\"_digest is not implemented\")},module.exports=HashBase}}),require_md5=__commonJS({\"node_modules/md5.js/index.js\"(exports,module){var inherits=require_inherits_browser(),HashBase=require_hash_base(),Buffer2=require_safe_buffer().Buffer,ARRAY16=new Array(16);function MD5(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}inherits(MD5,HashBase),MD5.prototype._update=function(){for(var M=ARRAY16,i=0;i<16;++i)M[i]=this._block.readInt32LE(i*4);var a=this._a,b=this._b,c=this._c,d=this._d;a=fnF(a,b,c,d,M[0],3614090360,7),d=fnF(d,a,b,c,M[1],3905402710,12),c=fnF(c,d,a,b,M[2],606105819,17),b=fnF(b,c,d,a,M[3],3250441966,22),a=fnF(a,b,c,d,M[4],4118548399,7),d=fnF(d,a,b,c,M[5],1200080426,12),c=fnF(c,d,a,b,M[6],2821735955,17),b=fnF(b,c,d,a,M[7],4249261313,22),a=fnF(a,b,c,d,M[8],1770035416,7),d=fnF(d,a,b,c,M[9],2336552879,12),c=fnF(c,d,a,b,M[10],4294925233,17),b=fnF(b,c,d,a,M[11],2304563134,22),a=fnF(a,b,c,d,M[12],1804603682,7),d=fnF(d,a,b,c,M[13],4254626195,12),c=fnF(c,d,a,b,M[14],2792965006,17),b=fnF(b,c,d,a,M[15],1236535329,22),a=fnG(a,b,c,d,M[1],4129170786,5),d=fnG(d,a,b,c,M[6],3225465664,9),c=fnG(c,d,a,b,M[11],643717713,14),b=fnG(b,c,d,a,M[0],3921069994,20),a=fnG(a,b,c,d,M[5],3593408605,5),d=fnG(d,a,b,c,M[10],38016083,9),c=fnG(c,d,a,b,M[15],3634488961,14),b=fnG(b,c,d,a,M[4],3889429448,20),a=fnG(a,b,c,d,M[9],568446438,5),d=fnG(d,a,b,c,M[14],3275163606,9),c=fnG(c,d,a,b,M[3],4107603335,14),b=fnG(b,c,d,a,M[8],1163531501,20),a=fnG(a,b,c,d,M[13],2850285829,5),d=fnG(d,a,b,c,M[2],4243563512,9),c=fnG(c,d,a,b,M[7],1735328473,14),b=fnG(b,c,d,a,M[12],2368359562,20),a=fnH(a,b,c,d,M[5],4294588738,4),d=fnH(d,a,b,c,M[8],2272392833,11),c=fnH(c,d,a,b,M[11],1839030562,16),b=fnH(b,c,d,a,M[14],4259657740,23),a=fnH(a,b,c,d,M[1],2763975236,4),d=fnH(d,a,b,c,M[4],1272893353,11),c=fnH(c,d,a,b,M[7],4139469664,16),b=fnH(b,c,d,a,M[10],3200236656,23),a=fnH(a,b,c,d,M[13],681279174,4),d=fnH(d,a,b,c,M[0],3936430074,11),c=fnH(c,d,a,b,M[3],3572445317,16),b=fnH(b,c,d,a,M[6],76029189,23),a=fnH(a,b,c,d,M[9],3654602809,4),d=fnH(d,a,b,c,M[12],3873151461,11),c=fnH(c,d,a,b,M[15],530742520,16),b=fnH(b,c,d,a,M[2],3299628645,23),a=fnI(a,b,c,d,M[0],4096336452,6),d=fnI(d,a,b,c,M[7],1126891415,10),c=fnI(c,d,a,b,M[14],2878612391,15),b=fnI(b,c,d,a,M[5],4237533241,21),a=fnI(a,b,c,d,M[12],1700485571,6),d=fnI(d,a,b,c,M[3],2399980690,10),c=fnI(c,d,a,b,M[10],4293915773,15),b=fnI(b,c,d,a,M[1],2240044497,21),a=fnI(a,b,c,d,M[8],1873313359,6),d=fnI(d,a,b,c,M[15],4264355552,10),c=fnI(c,d,a,b,M[6],2734768916,15),b=fnI(b,c,d,a,M[13],1309151649,21),a=fnI(a,b,c,d,M[4],4149444226,6),d=fnI(d,a,b,c,M[11],3174756917,10),c=fnI(c,d,a,b,M[2],718787259,15),b=fnI(b,c,d,a,M[9],3951481745,21),this._a=this._a+a|0,this._b=this._b+b|0,this._c=this._c+c|0,this._d=this._d+d|0},MD5.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer2.allocUnsafe(16);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer};function rotl(x,n){return x<>>32-n}function fnF(a,b,c,d,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+b|0}function fnG(a,b,c,d,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+b|0}function fnH(a,b,c,d,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+b|0}function fnI(a,b,c,d,m,k,s){return rotl(a+(c^(b|~d))+m+k|0,s)+b|0}module.exports=MD5}}),require_ripemd160=__commonJS({\"node_modules/ripemd160/index.js\"(exports,module){var Buffer2=Buffer,inherits=require_inherits_browser(),HashBase=require_hash_base(),ARRAY16=new Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;j<16;++j)words[j]=this._block.readInt32LE(j*4);for(var al=this._a|0,bl=this._b|0,cl=this._c|0,dl=this._d|0,el=this._e|0,ar=this._a|0,br=this._b|0,cr=this._c|0,dr=this._d|0,er=this._e|0,i=0;i<80;i+=1){var tl,tr;i<16\?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):i<32\?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):i<48\?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):i<64\?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=this._b+cl+dr|0;this._b=this._c+dl+er|0,this._c=this._d+el+ar|0,this._d=this._e+al+br|0,this._e=this._a+bl+cr|0,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer2.alloc\?Buffer2.alloc(20):new Buffer2(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer};function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+e|0}function fn2(a,b,c,d,e,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+e|0}function fn3(a,b,c,d,e,m,k,s){return rotl(a+((b|~c)^d)+m+k|0,s)+e|0}function fn4(a,b,c,d,e,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+e|0}function fn5(a,b,c,d,e,m,k,s){return rotl(a+(b^(c|~d))+m+k|0,s)+e|0}module.exports=RIPEMD160}}),require_hash=__commonJS({\"node_modules/sha.js/hash.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer;function Hash(blockSize,finalSize){this._block=Buffer2.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}Hash.prototype={},Hash.prototype.update=function(data,enc){typeof data==\"string\"&&(enc=enc||\"utf8\",data=Buffer2.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=this._len*8;if(bits<=4294967295)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(bits&4294967295)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc\?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error(\"_update must be implemented by subclass\")},module.exports=Hash}}),require_sha=__commonJS({\"node_modules/sha.js/sha.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return s===0\?b&c|~b&d:s===2\?b&c|b&d|c&d:b^c^d}Sha.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<80;++i)W2[i]=W2[i-3]^W2[i-8]^W2[i-14]^W2[i-16];for(var j=0;j<80;++j){var s=~~(j/20),t=rotl5(a)+ft(s,b,c,d)+e+W2[j]+K[s]|0;e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha.prototype._hash=function(){var H=Buffer2.allocUnsafe(20);return H.writeInt32BE(this._a|0,0),H.writeInt32BE(this._b|0,4),H.writeInt32BE(this._c|0,8),H.writeInt32BE(this._d|0,12),H.writeInt32BE(this._e|0,16),H},module.exports=Sha}}),require_sha1=__commonJS({\"node_modules/sha.js/sha1.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function rotl1(num){return num<<1|num>>>31}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return s===0\?b&c|~b&d:s===2\?b&c|b&d|c&d:b^c^d}Sha1.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<80;++i)W2[i]=rotl1(W2[i-3]^W2[i-8]^W2[i-14]^W2[i-16]);for(var j=0;j<80;++j){var s=~~(j/20),t=rotl5(a)+ft(s,b,c,d)+e+W2[j]+K[s]|0;e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha1.prototype._hash=function(){var H=Buffer2.allocUnsafe(20);return H.writeInt32BE(this._a|0,0),H.writeInt32BE(this._b|0,4),H.writeInt32BE(this._c|0,8),H.writeInt32BE(this._d|0,12),H.writeInt32BE(this._e|0,16),H},module.exports=Sha1}}),require_sha256=__commonJS({\"node_modules/sha.js/sha256.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=new Array(64);function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}function gamma1(x){return(x>>>17|x<<15)^(x>>>19|x<<13)^x>>>10}Sha256.prototype._update=function(M){for(var W2=this._w,a=this._a|0,b=this._b|0,c=this._c|0,d=this._d|0,e=this._e|0,f=this._f|0,g=this._g|0,h=this._h|0,i=0;i<16;++i)W2[i]=M.readInt32BE(i*4);for(;i<64;++i)W2[i]=gamma1(W2[i-2])+W2[i-7]+gamma0(W2[i-15])+W2[i-16]|0;for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W2[j]|0,T2=sigma0(a)+maj(a,b,c)|0;h=g,g=f,f=e,e=d+T1|0,d=c,c=b,b=a,a=T1+T2|0}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0,this._f=f+this._f|0,this._g=g+this._g|0,this._h=h+this._h|0},Sha256.prototype._hash=function(){var H=Buffer2.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256}}),require_sha224=__commonJS({\"node_modules/sha.js/sha224.js\"(exports,module){var inherits=require_inherits_browser(),Sha256=require_sha256(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,W=new Array(64);function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer2.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224}}),require_sha512=__commonJS({\"node_modules/sha.js/sha512.js\"(exports,module){var inherits=require_inherits_browser(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=new Array(160);function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0\?1:0}Sha512.prototype._update=function(M){for(var W2=this._w,ah=this._ah|0,bh=this._bh|0,ch=this._ch|0,dh=this._dh|0,eh=this._eh|0,fh=this._fh|0,gh=this._gh|0,hh=this._hh|0,al=this._al|0,bl=this._bl|0,cl=this._cl|0,dl=this._dl|0,el=this._el|0,fl=this._fl|0,gl=this._gl|0,hl=this._hl|0,i=0;i<32;i+=2)W2[i]=M.readInt32BE(i*4),W2[i+1]=M.readInt32BE(i*4+4);for(;i<160;i+=2){var xh=W2[i-30],xl=W2[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh);xh=W2[i-4],xl=W2[i-4+1];var gamma1=Gamma1(xh,xl),gamma1l=Gamma1l(xl,xh),Wi7h=W2[i-14],Wi7l=W2[i-14+1],Wi16h=W2[i-32],Wi16l=W2[i-32+1],Wil=gamma0l+Wi7l|0,Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wil=Wil+gamma1l|0,Wih=Wih+gamma1+getCarry(Wil,gamma1l)|0,Wil=Wil+Wi16l|0,Wih=Wih+Wi16h+getCarry(Wil,Wi16l)|0,W2[i]=Wih,W2[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W2[j],Wil=W2[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=hl+sigma1l|0,t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1l=t1l+chl|0,t1h=t1h+chh+getCarry(t1l,chl)|0,t1l=t1l+Kil|0,t1h=t1h+Kih+getCarry(t1l,Kil)|0,t1l=t1l+Wil|0,t1h=t1h+Wih+getCarry(t1l,Wil)|0;var t2l=sigma0l+majl|0,t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,el=dl+t1l|0,eh=dh+t1h+getCarry(el,dl)|0,dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,al=t1l+t2l|0,ah=t1h+t2h+getCarry(al,t1l)|0}this._al=this._al+al|0,this._bl=this._bl+bl|0,this._cl=this._cl+cl|0,this._dl=this._dl+dl|0,this._el=this._el+el|0,this._fl=this._fl+fl|0,this._gl=this._gl+gl|0,this._hl=this._hl+hl|0,this._ah=this._ah+ah+getCarry(this._al,al)|0,this._bh=this._bh+bh+getCarry(this._bl,bl)|0,this._ch=this._ch+ch+getCarry(this._cl,cl)|0,this._dh=this._dh+dh+getCarry(this._dl,dl)|0,this._eh=this._eh+eh+getCarry(this._el,el)|0,this._fh=this._fh+fh+getCarry(this._fl,fl)|0,this._gh=this._gh+gh+getCarry(this._gl,gl)|0,this._hh=this._hh+hh+getCarry(this._hl,hl)|0},Sha512.prototype._hash=function(){var H=Buffer2.allocUnsafe(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512}}),require_sha384=__commonJS({\"node_modules/sha.js/sha384.js\"(exports,module){var inherits=require_inherits_browser(),SHA512=require_sha512(),Hash=require_hash(),Buffer2=require_safe_buffer().Buffer,W=new Array(160);function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){var H=Buffer2.allocUnsafe(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384}}),require_sha2=__commonJS({\"node_modules/sha.js/index.js\"(exports,module){var exports=module.exports=function(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+\" is not supported (we accept pull requests)\");return new Algorithm};exports.sha=require_sha(),exports.sha1=require_sha1(),exports.sha224=require_sha224(),exports.sha256=require_sha256(),exports.sha384=require_sha384(),exports.sha512=require_sha512()}}),require_cipher_base=__commonJS({\"node_modules/cipher-base/index.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,inherits=require_inherits_browser();function CipherBase(hashMode){StreamModule.Transform.call(this),this.hashMode=typeof hashMode==\"string\",this.hashMode\?this[hashMode]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}inherits(CipherBase,StreamModule.Transform),CipherBase.prototype.update=function(data,inputEnc,outputEnc){typeof data==\"string\"&&(data=Buffer2.from(data,inputEnc));var outData=this._update(data);return this.hashMode\?this:(outputEnc&&(outData=this._toString(outData,outputEnc)),outData)},CipherBase.prototype.setAutoPadding=function(){},CipherBase.prototype.getAuthTag=function(){throw new Error(\"trying to get auth tag in unsupported state\")},CipherBase.prototype.setAuthTag=function(){throw new Error(\"trying to set auth tag in unsupported state\")},CipherBase.prototype.setAAD=function(){throw new Error(\"trying to set aad in unsupported state\")},CipherBase.prototype._transform=function(data,_,next){var err;try{this.hashMode\?this._update(data):this.push(this._update(data))}catch(e){err=e}finally{next(err)}},CipherBase.prototype._flush=function(done){var err;try{this.push(this.__final())}catch(e){err=e}done(err)},CipherBase.prototype._finalOrDigest=function(outputEnc){var outData=this.__final()||Buffer2.alloc(0);return outputEnc&&(outData=this._toString(outData,outputEnc,!0)),outData},CipherBase.prototype._toString=function(value,enc,fin){if(this._decoder||(this._decoder=new StringDecoder(enc),this._encoding=enc),this._encoding!==enc)throw new Error(\"can't switch encodings\");var out=this._decoder.write(value);return fin&&(out+=this._decoder.end()),out},module.exports=CipherBase}}),require_browser2=__commonJS({\"node_modules/create-hash/browser.js\"(exports,module){const LazyHash=function Hash(algorithm,options){this._options=options,this._hasher=new CryptoHasher(algorithm,options),this._finalized=!1};LazyHash.prototype=Object.create(StreamModule.Transform.prototype),LazyHash.prototype.update=function update(data,encoding){return this._checkFinalized(),this._hasher.update(data,encoding),this},LazyHash.prototype.digest=function update(data,encoding){return this._checkFinalized(),this._finalized=!0,this._hasher.digest(data,encoding)},LazyHash.prototype._checkFinalized=function _checkFinalized(){if(this._finalized){var err=new Error(\"Digest already called\");throw err.code=\"ERR_CRYPTO_HASH_FINALIZED\",err}},LazyHash.prototype.copy=function copy(){const copy=Object.create(LazyHash.prototype);return copy._options=this._options,copy._hasher=this._hasher.copy(),copy._finalized=this._finalized,copy};const lazyHashFullInitProto={__proto__:StreamModule.Transform.prototype,...LazyHash.prototype,_transform(data,encoding,callback){this.update(data,encoding),callback&&callback()},_flush(callback){this.push(this.digest()),callback()}},triggerMethods=[\"_events\",\"_eventsCount\",\"_final\",\"_maxListeners\",\"_maxListeners\",\"_read\",\"_undestroy\",\"_writableState\",\"_write\",\"_writev\",\"addListener\",\"asIndexedPairs\",\"closed\",\"compose\",\"constructor\",\"cork\",\"destroy\",\"destroyed\",\"drop\",\"emit\",\"end\",\"errored\",\"eventNames\",\"every\",\"filter\",\"find\",\"flatMap\",\"forEach\",\"getMaxListeners\",\"hasOwnProperty\",\"isPaused\",\"isPrototypeOf\",\"iterator\",\"listenerCount\",\"listeners\",\"map\",\"off\",\"on\",\"once\",\"pause\",\"pipe\",\"prependListener\",\"prependOnceListener\",\"propertyIsEnumerable\",\"push\",\"rawListeners\",\"read\",\"readable\",\"readableAborted\",\"readableBuffer\",\"readableDidRead\",\"readableEncoding\",\"readableEnded\",\"readableFlowing\",\"readableHighWaterMark\",\"readableLength\",\"readableObjectMode\",\"reduce\",\"removeAllListeners\",\"removeListener\",\"resume\",\"setDefaultEncoding\",\"setEncoding\",\"setMaxListeners\",\"some\",\"take\",\"toArray\",\"toLocaleString\",\"toString\",\"uncork\",\"unpipe\",\"unshift\",\"valueOf\",\"wrap\",\"writable\",\"writableBuffer\",\"writableCorked\",\"writableEnded\",\"writableFinished\",\"writableHighWaterMark\",\"writableLength\",\"writableNeedDrain\",\"writableObjectMode\",\"write\"];for(let method of triggerMethods)Object.defineProperty(LazyHash.prototype,method,{get(){return Object.setPrototypeOf(this,lazyHashFullInitProto),StreamModule.Transform.call(this,this._options),this[method]},enumerable:!1,configurable:!0});module.exports=function createHash(algorithm){return new LazyHash(algorithm)},module.exports.createHash=module.exports,module.exports.Hash=LazyHash}}),require_legacy=__commonJS({\"node_modules/create-hmac/legacy.js\"(exports,module){var inherits=require_inherits_browser(),Buffer2=require_safe_buffer().Buffer,Base=require_cipher_base(),ZEROS=Buffer2.alloc(128),blocksize=64;function Hmac(alg,key){Base.call(this,\"digest\"),typeof key==\"string\"&&(key=Buffer2.from(key)),this._alg=alg,this._key=key,key.length>blocksize\?key=alg(key):key.lengthblocksize){var hash=alg===\"rmd160\"\?new RIPEMD160:sha(alg);key=hash.update(key).digest()}else key.lengthMAX_ALLOC||keylen!==keylen)@throwTypeError(\"Bad key length\")}}}),require_default_encoding=__commonJS({\"node_modules/pbkdf2/lib/default-encoding.js\"(exports,module){var defaultEncoding;global.process&&global.process.browser\?defaultEncoding=\"utf-8\":global.process&&global.process.version\?(pVersionMajor=parseInt(process.version.split(\".\")[0].slice(1),10),defaultEncoding=pVersionMajor>=6\?\"utf-8\":\"binary\"):defaultEncoding=\"utf-8\";var pVersionMajor;module.exports=defaultEncoding}}),require_to_buffer=__commonJS({\"node_modules/pbkdf2/lib/to-buffer.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer;module.exports=function(thing,encoding,name){if(Buffer2.isBuffer(thing))return thing;if(typeof thing==\"string\")return Buffer2.from(thing,encoding);if(ArrayBuffer.isView(thing))return Buffer2.from(thing.buffer);@throwTypeError(name+\" must be a string, a Buffer, a typed array or a DataView\")}}}),require_sync_browser=__commonJS({\"node_modules/pbkdf2/lib/sync-browser.js\"(exports,module){var md5=require_md52(),RIPEMD160=require_ripemd160(),sha=require_sha2(),Buffer2=require_safe_buffer().Buffer,checkParameters=require_precondition(),defaultEncoding=require_default_encoding(),toBuffer=require_to_buffer(),ZEROS=Buffer2.alloc(128),sizes={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function Hmac(alg,key,saltLen){var hash=getDigest(alg),blocksize=alg===\"sha512\"||alg===\"sha384\"\?128:64;key.length>blocksize\?key=hash(key):key.length>>0},exports.writeUInt32BE=function(bytes,value,off){bytes[0+off]=value>>>24,bytes[1+off]=value>>>16&255,bytes[2+off]=value>>>8&255,bytes[3+off]=value&255},exports.ip=function(inL,inR,out,off){for(var outL=0,outR=0,i=6;i>=0;i-=2){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>>j+i&1;for(var j=0;j<=24;j+=8)outL<<=1,outL|=inL>>>j+i&1}for(var i=6;i>=0;i-=2){for(var j=1;j<=25;j+=8)outR<<=1,outR|=inR>>>j+i&1;for(var j=1;j<=25;j+=8)outR<<=1,outR|=inL>>>j+i&1}out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.rip=function(inL,inR,out,off){for(var outL=0,outR=0,i=0;i<4;i++)for(var j=24;j>=0;j-=8)outL<<=1,outL|=inR>>>j+i&1,outL<<=1,outL|=inL>>>j+i&1;for(var i=4;i<8;i++)for(var j=24;j>=0;j-=8)outR<<=1,outR|=inR>>>j+i&1,outR<<=1,outR|=inL>>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.pc1=function(inL,inR,out,off){for(var outL=0,outR=0,i=7;i>=5;i--){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(var j=0;j<=24;j+=8)outL<<=1,outL|=inL>>j+i&1}for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(var i=1;i<=3;i++){for(var j=0;j<=24;j+=8)outR<<=1,outR|=inR>>j+i&1;for(var j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1}for(var j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.r28shl=function(num,shift){return num<>>28-shift};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];exports.pc2=function(inL,inR,out,off){for(var outL=0,outR=0,len=pc2table.length>>>1,i=0;i>>pc2table[i]&1;for(var i=len;i>>pc2table[i]&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.expand=function(r,out,off){var outL=0,outR=0;outL=(r&1)<<5|r>>>27;for(var i=23;i>=15;i-=4)outL<<=6,outL|=r>>>i&63;for(var i=11;i>=3;i-=4)outR|=r>>>i&63,outR<<=6;outR|=(r&31)<<1|r>>>31,out[off+0]=outL>>>0,out[off+1]=outR>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];exports.substitute=function(inL,inR){for(var out=0,i=0;i<4;i++){var b=inL>>>18-i*6&63,sb=sTable[i*64+b];out<<=4,out|=sb}for(var i=0;i<4;i++){var b=inR>>>18-i*6&63,sb=sTable[256+i*64+b];out<<=4,out|=sb}return out>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];exports.permute=function(num){for(var out=0,i=0;i>>permuteTable[i]&1;return out>>>0},exports.padSplit=function(num,size,group){for(var str=num.toString(2);str.length0;count--)inputOff+=this._buffer(data,inputOff),outputOff+=this._flushBuffer(out,outputOff);return inputOff+=this._buffer(data,inputOff),out},Cipher.prototype.final=function(buffer){var first;buffer&&(first=this.update(buffer));var last;return this.type===\"encrypt\"\?last=this._finalEncrypt():last=this._finalDecrypt(),first\?first.concat(last):last},Cipher.prototype._pad=function(buffer,off){if(off===0)return!1;for(;off>>1];kL=utils.r28shl(kL,shift),kR=utils.r28shl(kR,shift),utils.pc2(kL,kR,state.keys,i)}},DES.prototype._update=function(inp,inOff,out,outOff){var state=this._desState,l=utils.readUInt32BE(inp,inOff),r=utils.readUInt32BE(inp,inOff+4);utils.ip(l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],this.type===\"encrypt\"\?this._encrypt(state,l,r,state.tmp,0):this._decrypt(state,l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],utils.writeUInt32BE(out,l,outOff),utils.writeUInt32BE(out,r,outOff+4)},DES.prototype._pad=function(buffer,off){for(var value=buffer.length-off,i=off;i>>0,l=t}utils.rip(r,l,out,off)},DES.prototype._decrypt=function(state,lStart,rStart,out,off){for(var l=rStart,r=lStart,i=state.keys.length-2;i>=0;i-=2){var keyL=state.keys[i],keyR=state.keys[i+1];utils.expand(l,state.tmp,0),keyL^=state.tmp[0],keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR),f=utils.permute(s),t=l;l=(r^f)>>>0,r=t}utils.rip(l,r,out,off)}}}),require_cbc=__commonJS({\"node_modules/des.js/lib/des/cbc.js\"(exports){var assert=require_minimalistic_assert(),inherits=require_inherits_browser(),proto={};function CBCState(iv){assert.equal(iv.length,8,\"Invalid IV length\"),this.iv=new Array(8);for(var i=0;i>i%8,self2._prev=shiftIn(self2._prev,decrypt\?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer2.allocUnsafe(buffer.length);for(buffer=Buffer2.concat([buffer,Buffer2.from([value])]);++i>7;return out}exports.encrypt=function(self2,chunk,decrypt){for(var len=chunk.length,out=Buffer2.allocUnsafe(len),i=-1;++i>>24]^SUB_MIX1[s1>>>16&255]^SUB_MIX2[s2>>>8&255]^SUB_MIX3[s3&255]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[s2>>>16&255]^SUB_MIX2[s3>>>8&255]^SUB_MIX3[s0&255]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[s3>>>16&255]^SUB_MIX2[s0>>>8&255]^SUB_MIX3[s1&255]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[s0>>>16&255]^SUB_MIX2[s1>>>8&255]^SUB_MIX3[s2&255]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[s3&255])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[s0&255])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[s1&255])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[s2&255])^keySchedule[ksRow++],t0=t0>>>0,t1=t1>>>0,t2=t2>>>0,t3=t3>>>0,[t0,t1,t2,t3]}var RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=new Array(256),j=0;j<256;j++)j<128\?d[j]=j<<1:d[j]=j<<1^283;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0;i<256;++i){var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^sx&255^99,SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=d[sx]*257^sx*16843008;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=x8*16843009^x4*65537^x2*257^x*16843008,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,x===0\?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX,INV_SBOX,SUB_MIX,INV_SUB_MIX}}();function AES(key){this._key=asUInt32Array(key),this._reset()}AES.prototype={},AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=(nRounds+1)*4,keySchedule=[],k=0;k>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255],t^=RCON[k/keySize|0]<<24):keySize>6&&k%keySize===4&&(t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[t&255]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik>>24]]^G.INV_SUB_MIX[1][G.SBOX[tt>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[tt>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[tt&255]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return M=asUInt32Array(M),cryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=asUInt32Array(M);var m1=M[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES}}),require_ghash=__commonJS({\"node_modules/browserify-aes/ghash.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,ZEROES=Buffer2.alloc(16,0);function toArray(buf){return[buf.readUInt32BE(0),buf.readUInt32BE(4),buf.readUInt32BE(8),buf.readUInt32BE(12)]}function fromArray(out){var buf=Buffer2.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer2.alloc(16,0),this.cache=Buffer2.allocUnsafe(0)}GHASH.prototype={},GHASH.prototype.ghash=function(block){for(var i=-1;++i0;j--)Vi[j]=Vi[j]>>>1|(Vi[j-1]&1)<<31;Vi[0]=Vi[0]>>>1,lsbVi&&(Vi[0]=Vi[0]^225<<24)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer2.concat([this.cache,buf]);for(var chunk;this.cache.length>=16;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer2.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH}}),require_authCipher=__commonJS({\"node_modules/browserify-aes/authCipher.js\"(exports,module){var aes=require_aes(),Buffer2=require_safe_buffer().Buffer,Transform=require_cipher_base(),inherits=require_inherits_browser(),GHASH=require_ghash(),xor=require_buffer_xor(),incr32=require_incr32();function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=Math.min(a.length,b.length),i=0;i0||ivLen>0;){var hash=new MD5;hash.update(tmp),hash.update(password),salt&&hash.update(salt),tmp=hash.digest();var used=0;if(keyLen>0){var keyStart=key.length-keyLen;used=Math.min(keyLen,tmp.length),tmp.copy(key,keyStart,0,used),keyLen-=used}if(used0){var ivStart=iv.length-ivLen,length=Math.min(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length),ivLen-=length}}return tmp.fill(0),{key,iv}}module.exports=EVP_BytesToKey}}),require_encrypter=__commonJS({\"node_modules/browserify-aes/encrypter.js\"(exports){var MODES=require_modes(),AuthCipher=require_authCipher(),Buffer2=require_safe_buffer().Buffer,StreamCipher=require_streamCipher(),Transform=require_cipher_base(),aes=require_aes(),ebtk=require_evp_bytestokey(),inherits=require_inherits_browser();function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer2.from(iv),this._mode=mode,this._autopadding=!0}inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var chunk,thing,out=[];chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer2.concat(out)};var PADDING=Buffer2.alloc(16,16);Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error(\"data not multiple of block length\")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this};function Splitter(){this.cache=Buffer2.allocUnsafe(0)}Splitter.prototype={},Splitter.prototype.add=function(data){this.cache=Buffer2.concat([this.cache,data])},Splitter.prototype.get=function(){if(this.cache.length>15){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer2.allocUnsafe(len),i=-1;++i16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out}else if(this.cache.length>=16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache};function unpad(last){var padded=last[15];if(padded<1||padded>16)throw new Error(\"unable to decrypt data\");for(var i=-1;++i0\?left:right},BN.min=function(left,right){return left.cmp(right)<0\?left:right},BN.prototype._init=function(number,base,endian){if(typeof number==\"number\")return this._initNumber(number,base,endian);if(typeof number==\"object\")return this._initArray(number,base,endian);base===\"hex\"&&(base=16),assert(base===(base|0)&&base>=2&&base<=36),number=number.toString().replace(/\\s+/g,\"\");var start=0;number[0]===\"-\"&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);else if(endian===\"le\")for(i=0,j=0;i>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);return this.strip()};function parseHex4Bits(string,index){var c=string.charCodeAt(index);return c>=65&&c<=70\?c-55:c>=97&&c<=102\?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}BN.prototype._parseHex=function(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18\?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else{var parseLength=number.length-start;for(i=parseLength%2===0\?start+1:start;i=18\?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8}this.strip()};function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49\?r+=c-49+10:c>=17\?r+=c-17+10:r+=c}return r}BN.prototype._parseBase=function(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},BN.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},BN.prototype.inspect=function(){return(this.red\?\"\"};var zeros=[\"\",\"0\",\"00\",\"000\",\"0000\",\"00000\",\"000000\",\"0000000\",\"00000000\",\"000000000\",\"0000000000\",\"00000000000\",\"000000000000\",\"0000000000000\",\"00000000000000\",\"000000000000000\",\"0000000000000000\",\"00000000000000000\",\"000000000000000000\",\"0000000000000000000\",\"00000000000000000000\",\"000000000000000000000\",\"0000000000000000000000\",\"00000000000000000000000\",\"000000000000000000000000\",\"0000000000000000000000000\"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function(base,padding){base=base||10,padding=padding|0||1;var out;if(base===16||base===\"hex\"){out=\"\";for(var off=0,carry=0,i=0;i>>24-off&16777215,carry!==0||i!==this.length-1\?out=zeros[6-word.length]+word+out:out=word+out,off+=2,off>=26&&(off-=26,i--)}for(carry!==0&&(out=carry.toString(16)+out);out.length%padding!==0;)out=\"0\"+out;return this.negative!==0&&(out=\"-\"+out),out}if(base===(base|0)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out=\"\";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),c.isZero()\?out=r+out:out=zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out=\"0\"+out);out.length%padding!==0;)out=\"0\"+out;return this.negative!==0&&(out=\"-\"+out),out}assert(!1,\"Base should be between 2 and 36\")},BN.prototype.toNumber=function(){var ret=this.words[0];return this.length===2\?ret+=this.words[1]*67108864:this.length===3&&this.words[2]===1\?ret+=4503599627370496+this.words[1]*67108864:this.length>2&&assert(!1,\"Number can only safely store up to 53 bits\"),this.negative!==0\?-ret:ret},BN.prototype.toJSON=function(){return this.toString(16)},BN.prototype.toBuffer=function(endian,length){return assert(typeof Buffer2<\"u\"),this.toArrayLike(Buffer2,endian,length)},BN.prototype.toArray=function(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,\"byte array longer than desired length\"),assert(reqLength>0,\"Requested array length <= 0\"),this.strip();var littleEndian=endian===\"le\",res=new ArrayType(reqLength),b,i,q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(w===0)return 26;var t=w,r=0;return(t&8191)===0&&(r+=13,t>>>=13),(t&127)===0&&(r+=7,t>>>=7),(t&15)===0&&(r+=4,t>>>=4),(t&3)===0&&(r+=2,t>>>=2),(t&1)===0&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return(this.length-1)*26+hi};function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0;inum.length\?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length\?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b;this.length>num.length\?b=num:b=this;for(var i=0;inum.length\?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length\?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length\?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length\?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length\?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert(typeof width==\"number\"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0,bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert(typeof bit==\"number\"&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),val\?this.words[off]=this.words[off]|1<num.length\?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;carry!==0&&i>>26;if(this.length=a.length,carry!==0)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length\?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(cmp===0)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;cmp>0\?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=r&67108863;for(;carry!==0&&i>26,this.words[i]=r&67108863;if(carry===0&&i>>26,rword=carry&67108863,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self2.length+1);j<=maxJ;j++){var i=k-j|0;a=self2.words[i]|0,b=num.words[j]|0,r=a*b+rword,ncarry+=r/67108864|0,rword=r&67108863}out.words[k]=rword|0,carry=ncarry|0}return carry!==0\?out.words[k]=carry|0:out.length--,out.strip()}var comb10MulTo=function(self2,num,out){var a=self2.words,b=num.words,o=out.words,c=0,lo,mid,hi,a0=a[0]|0,al0=a0&8191,ah0=a0>>>13,a1=a[1]|0,al1=a1&8191,ah1=a1>>>13,a2=a[2]|0,al2=a2&8191,ah2=a2>>>13,a3=a[3]|0,al3=a3&8191,ah3=a3>>>13,a4=a[4]|0,al4=a4&8191,ah4=a4>>>13,a5=a[5]|0,al5=a5&8191,ah5=a5>>>13,a6=a[6]|0,al6=a6&8191,ah6=a6>>>13,a7=a[7]|0,al7=a7&8191,ah7=a7>>>13,a8=a[8]|0,al8=a8&8191,ah8=a8>>>13,a9=a[9]|0,al9=a9&8191,ah9=a9>>>13,b0=b[0]|0,bl0=b0&8191,bh0=b0>>>13,b1=b[1]|0,bl1=b1&8191,bh1=b1>>>13,b2=b[2]|0,bl2=b2&8191,bh2=b2>>>13,b3=b[3]|0,bl3=b3&8191,bh3=b3>>>13,b4=b[4]|0,bl4=b4&8191,bh4=b4>>>13,b5=b[5]|0,bl5=b5&8191,bh5=b5>>>13,b6=b[6]|0,bl6=b6&8191,bh6=b6>>>13,b7=b[7]|0,bl7=b7&8191,bh7=b7>>>13,b8=b[8]|0,bl8=b8&8191,bh8=b8>>>13,b9=b[9]|0,bl9=b9&8191,bh9=b9>>>13;out.negative=self2.negative^num.negative,out.length=19,lo=Math.imul(al0,bl0),mid=Math.imul(al0,bh0),mid=mid+Math.imul(ah0,bl0)|0,hi=Math.imul(ah0,bh0);var w0=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=Math.imul(al1,bh0),mid=mid+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0),lo=lo+Math.imul(al0,bl1)|0,mid=mid+Math.imul(al0,bh1)|0,mid=mid+Math.imul(ah0,bl1)|0,hi=hi+Math.imul(ah0,bh1)|0;var w1=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=Math.imul(al2,bh0),mid=mid+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=mid+Math.imul(al1,bh1)|0,mid=mid+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0,lo=lo+Math.imul(al0,bl2)|0,mid=mid+Math.imul(al0,bh2)|0,mid=mid+Math.imul(ah0,bl2)|0,hi=hi+Math.imul(ah0,bh2)|0;var w2=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=Math.imul(al3,bh0),mid=mid+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=mid+Math.imul(al2,bh1)|0,mid=mid+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=mid+Math.imul(al1,bh2)|0,mid=mid+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0,lo=lo+Math.imul(al0,bl3)|0,mid=mid+Math.imul(al0,bh3)|0,mid=mid+Math.imul(ah0,bl3)|0,hi=hi+Math.imul(ah0,bh3)|0;var w3=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=Math.imul(al4,bh0),mid=mid+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=mid+Math.imul(al3,bh1)|0,mid=mid+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=mid+Math.imul(al2,bh2)|0,mid=mid+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=mid+Math.imul(al1,bh3)|0,mid=mid+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0,lo=lo+Math.imul(al0,bl4)|0,mid=mid+Math.imul(al0,bh4)|0,mid=mid+Math.imul(ah0,bl4)|0,hi=hi+Math.imul(ah0,bh4)|0;var w4=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=Math.imul(al5,bh0),mid=mid+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=mid+Math.imul(al4,bh1)|0,mid=mid+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=mid+Math.imul(al3,bh2)|0,mid=mid+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=mid+Math.imul(al2,bh3)|0,mid=mid+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=mid+Math.imul(al1,bh4)|0,mid=mid+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0,lo=lo+Math.imul(al0,bl5)|0,mid=mid+Math.imul(al0,bh5)|0,mid=mid+Math.imul(ah0,bl5)|0,hi=hi+Math.imul(ah0,bh5)|0;var w5=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=Math.imul(al6,bh0),mid=mid+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=mid+Math.imul(al5,bh1)|0,mid=mid+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=mid+Math.imul(al4,bh2)|0,mid=mid+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=mid+Math.imul(al3,bh3)|0,mid=mid+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=mid+Math.imul(al2,bh4)|0,mid=mid+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=mid+Math.imul(al1,bh5)|0,mid=mid+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0,lo=lo+Math.imul(al0,bl6)|0,mid=mid+Math.imul(al0,bh6)|0,mid=mid+Math.imul(ah0,bl6)|0,hi=hi+Math.imul(ah0,bh6)|0;var w6=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=Math.imul(al7,bh0),mid=mid+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=mid+Math.imul(al6,bh1)|0,mid=mid+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=mid+Math.imul(al5,bh2)|0,mid=mid+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=mid+Math.imul(al4,bh3)|0,mid=mid+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=mid+Math.imul(al3,bh4)|0,mid=mid+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=mid+Math.imul(al2,bh5)|0,mid=mid+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=mid+Math.imul(al1,bh6)|0,mid=mid+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0,lo=lo+Math.imul(al0,bl7)|0,mid=mid+Math.imul(al0,bh7)|0,mid=mid+Math.imul(ah0,bl7)|0,hi=hi+Math.imul(ah0,bh7)|0;var w7=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=Math.imul(al8,bh0),mid=mid+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=mid+Math.imul(al7,bh1)|0,mid=mid+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=mid+Math.imul(al6,bh2)|0,mid=mid+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=mid+Math.imul(al5,bh3)|0,mid=mid+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=mid+Math.imul(al4,bh4)|0,mid=mid+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=mid+Math.imul(al3,bh5)|0,mid=mid+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=mid+Math.imul(al2,bh6)|0,mid=mid+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=mid+Math.imul(al1,bh7)|0,mid=mid+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0,lo=lo+Math.imul(al0,bl8)|0,mid=mid+Math.imul(al0,bh8)|0,mid=mid+Math.imul(ah0,bl8)|0,hi=hi+Math.imul(ah0,bh8)|0;var w8=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=Math.imul(al9,bh0),mid=mid+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=mid+Math.imul(al8,bh1)|0,mid=mid+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=mid+Math.imul(al7,bh2)|0,mid=mid+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=mid+Math.imul(al6,bh3)|0,mid=mid+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=mid+Math.imul(al5,bh4)|0,mid=mid+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=mid+Math.imul(al4,bh5)|0,mid=mid+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=mid+Math.imul(al3,bh6)|0,mid=mid+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=mid+Math.imul(al2,bh7)|0,mid=mid+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=mid+Math.imul(al1,bh8)|0,mid=mid+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0,lo=lo+Math.imul(al0,bl9)|0,mid=mid+Math.imul(al0,bh9)|0,mid=mid+Math.imul(ah0,bl9)|0,hi=hi+Math.imul(ah0,bh9)|0;var w9=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=Math.imul(al9,bh1),mid=mid+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=mid+Math.imul(al8,bh2)|0,mid=mid+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=mid+Math.imul(al7,bh3)|0,mid=mid+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=mid+Math.imul(al6,bh4)|0,mid=mid+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=mid+Math.imul(al5,bh5)|0,mid=mid+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=mid+Math.imul(al4,bh6)|0,mid=mid+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=mid+Math.imul(al3,bh7)|0,mid=mid+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=mid+Math.imul(al2,bh8)|0,mid=mid+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0,lo=lo+Math.imul(al1,bl9)|0,mid=mid+Math.imul(al1,bh9)|0,mid=mid+Math.imul(ah1,bl9)|0,hi=hi+Math.imul(ah1,bh9)|0;var w10=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=Math.imul(al9,bh2),mid=mid+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=mid+Math.imul(al8,bh3)|0,mid=mid+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=mid+Math.imul(al7,bh4)|0,mid=mid+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=mid+Math.imul(al6,bh5)|0,mid=mid+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=mid+Math.imul(al5,bh6)|0,mid=mid+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=mid+Math.imul(al4,bh7)|0,mid=mid+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=mid+Math.imul(al3,bh8)|0,mid=mid+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0,lo=lo+Math.imul(al2,bl9)|0,mid=mid+Math.imul(al2,bh9)|0,mid=mid+Math.imul(ah2,bl9)|0,hi=hi+Math.imul(ah2,bh9)|0;var w11=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=Math.imul(al9,bh3),mid=mid+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=mid+Math.imul(al8,bh4)|0,mid=mid+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=mid+Math.imul(al7,bh5)|0,mid=mid+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=mid+Math.imul(al6,bh6)|0,mid=mid+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=mid+Math.imul(al5,bh7)|0,mid=mid+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=mid+Math.imul(al4,bh8)|0,mid=mid+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0,lo=lo+Math.imul(al3,bl9)|0,mid=mid+Math.imul(al3,bh9)|0,mid=mid+Math.imul(ah3,bl9)|0,hi=hi+Math.imul(ah3,bh9)|0;var w12=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=Math.imul(al9,bh4),mid=mid+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=mid+Math.imul(al8,bh5)|0,mid=mid+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=mid+Math.imul(al7,bh6)|0,mid=mid+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=mid+Math.imul(al6,bh7)|0,mid=mid+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=mid+Math.imul(al5,bh8)|0,mid=mid+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0,lo=lo+Math.imul(al4,bl9)|0,mid=mid+Math.imul(al4,bh9)|0,mid=mid+Math.imul(ah4,bl9)|0,hi=hi+Math.imul(ah4,bh9)|0;var w13=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=Math.imul(al9,bh5),mid=mid+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=mid+Math.imul(al8,bh6)|0,mid=mid+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=mid+Math.imul(al7,bh7)|0,mid=mid+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=mid+Math.imul(al6,bh8)|0,mid=mid+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0,lo=lo+Math.imul(al5,bl9)|0,mid=mid+Math.imul(al5,bh9)|0,mid=mid+Math.imul(ah5,bl9)|0,hi=hi+Math.imul(ah5,bh9)|0;var w14=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=Math.imul(al9,bh6),mid=mid+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=mid+Math.imul(al8,bh7)|0,mid=mid+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=mid+Math.imul(al7,bh8)|0,mid=mid+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0,lo=lo+Math.imul(al6,bl9)|0,mid=mid+Math.imul(al6,bh9)|0,mid=mid+Math.imul(ah6,bl9)|0,hi=hi+Math.imul(ah6,bh9)|0;var w15=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=Math.imul(al9,bh7),mid=mid+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=mid+Math.imul(al8,bh8)|0,mid=mid+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0,lo=lo+Math.imul(al7,bl9)|0,mid=mid+Math.imul(al7,bh9)|0,mid=mid+Math.imul(ah7,bl9)|0,hi=hi+Math.imul(ah7,bh9)|0;var w16=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=Math.imul(al9,bh8),mid=mid+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8),lo=lo+Math.imul(al8,bl9)|0,mid=mid+Math.imul(al8,bh9)|0,mid=mid+Math.imul(ah8,bl9)|0,hi=hi+Math.imul(ah8,bh9)|0;var w17=(c+lo|0)+((mid&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863,lo=Math.imul(al9,bl9),mid=Math.imul(al9,bh9),mid=mid+Math.imul(ah9,bl9)|0,hi=Math.imul(ah9,bh9);var w18=(c+lo|0)+((mid&8191)<<13)|0;return c=(hi+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,c!==0&&(o[19]=c,out.length++),out};Math.imul||(comb10MulTo=smallMulTo);function bigMulTo(self2,num,out){out.negative=num.negative^self2.negative,out.length=self2.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0,hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return carry!==0\?out.words[k]=carry:out.length--,out.strip()}function jumboMulTo(self2,num,out){var fftm=new FFTM;return fftm.mulp(self2,num,out)}BN.prototype.mulTo=function(num,out){var res,len=this.length+num.length;return this.length===10&&num.length===10\?res=comb10MulTo(this,num,out):len<63\?res=smallMulTo(this,num,out):len<1024\?res=bigMulTo(this,num,out):res=jumboMulTo(this,num,out),res};function FFTM(x,y){this.x=x,this.y=y}FFTM.prototype={},FFTM.prototype.makeRBT=function(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1)i++;return 1<>>13,rws[2*i+1]=carry&8191,carry=carry>>>13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=lo&67108863}return carry!==0&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(w.length===0)return new BN(1);for(var res=this,i=0;i=0);var r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r,i;if(r!==0){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(s!==0){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0);var h;hint\?h=(hint-hint%26)/26:h=0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&carry!==0&&(maskedWords.words[maskedWords.length++]=carry),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function(bits,hint,extended){return assert(this.negative===0),this.iushrn(bits,hint,extended)},BN.prototype.shln=function(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function(bit){assert(typeof bit==\"number\"&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(this.negative===0,\"imaskn works only with positive numbers\"),this.length<=s)return this;if(r!==0&&s++,this.length=Math.min(s,this.length),r!==0){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1\?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function(num){if(assert(typeof num==\"number\"),assert(num<67108864),num<0)return this.iaddn(-num);if(this.negative!==0)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=w&67108863}for(;i>26,this.words[i+shift]=w&67108863;if(carry===0)return this.strip();for(assert(carry===-1),carry=0,i=0;i>26,this.words[i]=w&67108863;return this.negative=1,this.strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=b.words[b.length-1]|0,bhiBits=this._countBits(bhi);shift=26-bhiBits,shift!==0&&(b=b.ushln(shift),a.iushln(shift),bhi=b.words[b.length-1]|0);var m=a.length-b.length,q;if(mode!==\"mod\"){q=new BN(null),q.length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);a.negative!==0;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),mode!==\"div\"&&shift!==0&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return this.negative!==0&&num.negative===0\?(res=this.neg().divmod(num,mode),mode!==\"mod\"&&(div=res.div.neg()),mode!==\"div\"&&(mod=res.mod.neg(),positive&&mod.negative!==0&&mod.iadd(num)),{div,mod}):this.negative===0&&num.negative!==0\?(res=this.divmod(num.neg(),mode),mode!==\"mod\"&&(div=res.div.neg()),{div,mod:res.mod}):(this.negative&num.negative)!==0\?(res=this.neg().divmod(num.neg(),mode),mode!==\"div\"&&(mod=res.mod.neg(),positive&&mod.negative!==0&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0\?{div:new BN(0),mod:this}:num.length===1\?mode===\"div\"\?{div:this.divn(num.words[0]),mod:null}:mode===\"mod\"\?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode)},BN.prototype.div=function(num){return this.divmod(num,\"div\",!1).div},BN.prototype.mod=function(num){return this.divmod(num,\"mod\",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,\"mod\",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=dm.div.negative!==0\?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||r2===1&&cmp===0\?dm.div:dm.div.negative!==0\?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(this.words[i]|0))%num;return acc},BN.prototype.idivn=function(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(p.negative===0),assert(!p.isZero());var x=this,y=p.clone();x.negative!==0\?x=x.umod(p):x=x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;(x.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;(y.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0\?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function(p){assert(p.negative===0),assert(!p.isZero());var a=this,b=p.clone();a.negative!==0\?a=a.umod(p):a=a.clone();for(var x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;(a.words[0]&im)===0&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;(b.words[0]&jm)===0&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0\?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return a.cmpn(1)===0\?res=x1:res=x2,res.cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);do{for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(r===0||b.cmpn(1)===0)break;a.isub(b)}while(!0);return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return(this.words[0]&1)===0},BN.prototype.isOdd=function(){return(this.words[0]&1)===1},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert(typeof bit==\"number\");var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return carry!==0&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return this.length===1&&this.words[0]===0},BN.prototype.cmpn=function(num){var negative=num<0;if(this.negative!==0&&!negative)return-1;if(this.negative===0&&negative)return 1;this.strip();var res;if(this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,\"Number is too big\");var w=this.words[0]|0;res=w===num\?0:wnum.length)return 1;if(this.length=0;i--){var a=this.words[i]|0,b=num.words[i]|0;if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function(num){return this.cmpn(num)===1},BN.prototype.gt=function(num){return this.cmp(num)===1},BN.prototype.gten=function(num){return this.cmpn(num)>=0},BN.prototype.gte=function(num){return this.cmp(num)>=0},BN.prototype.ltn=function(num){return this.cmpn(num)===-1},BN.prototype.lt=function(num){return this.cmp(num)===-1},BN.prototype.lten=function(num){return this.cmpn(num)<=0},BN.prototype.lte=function(num){return this.cmp(num)<=0},BN.prototype.eqn=function(num){return this.cmpn(num)===0},BN.prototype.eq=function(num){return this.cmp(num)===0},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,\"Already a number in reduction context\"),assert(this.negative===0,\"red works only with positives\"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,\"fromRed works only with numbers in reduction context\"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,\"Already a number in reduction context\"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,\"redAdd works only with red numbers\"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,\"redIAdd works only with red numbers\"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,\"redSub works only with red numbers\"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,\"redISub works only with red numbers\"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,\"redShl works only with red numbers\"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,\"redMul works only with red numbers\"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,\"redMul works only with red numbers\"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,\"redSqr works only with red numbers\"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,\"redISqr works only with red numbers\"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,\"redSqrt works only with red numbers\"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,\"redInvm works only with red numbers\"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,\"redNeg works only with red numbers\"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,\"redPow(normalNum)\"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}MPrime.prototype={},MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var r=num,rlen;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen0\?r.isub(this.p):r.strip!==void 0\?r.strip():r._strip(),r},MPrime.prototype.split=function(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function(num){return num.imul(this.k)};function K256(){MPrime.call(this,\"k256\",\"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f\")}inherits(K256,MPrime),K256.prototype.split=function(input,output){for(var mask=4194303,outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,prev===0&&input.length>10\?input.length-=10:input.length-=9},K256.prototype.imulK=function(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return carry!==0&&(num.words[num.length++]=carry),num},BN._prime=function(name){if(primes[name])return primes[name];var prime2;if(name===\"k256\")prime2=new K256;else if(name===\"p224\")prime2=new P224;else if(name===\"p192\")prime2=new P192;else if(name===\"p25519\")prime2=new P25519;else throw new Error(\"Unknown prime \"+name);return primes[name]=prime2,prime2};function Red(m){if(typeof m==\"string\"){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),\"modulus must be greater than 1\"),this.m=m,this.prime=null}Red.prototype={},Red.prototype._verify1=function(a){assert(a.negative===0,\"red works only with positives\"),assert(a.red,\"red works only with red numbers\")},Red.prototype._verify2=function(a,b){assert((a.negative|b.negative)===0,\"red works only with positives\"),assert(a.red&&a.red===b.red,\"red works only with red numbers\")},Red.prototype.imod=function(a){return this.prime\?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function(a){return a.isZero()\?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2===1),mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&q.andln(1)===0;)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);this.pow(z,lpow).cmp(nOne)!==0;)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;t.cmp(one)!==0;){for(var tmp=t,i=0;tmp.cmp(one)!==0;i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;if(res!==wnd[0]&&(res=this.sqr(res)),bit===0&¤t===0){currentLen=0;continue}current<<=1,current|=bit,currentLen++,!(currentLen!==windowSize&&(i!==0||j!==0))&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num\?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)};function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0\?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0\?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(typeof module>\"u\"||module,exports)}}),require_bn2=require_bn,require_brorand=__commonJS({\"node_modules/brorand/index.js\"(exports,module){var r;module.exports=function(len){return r||(r=new Rand(null)),r.generate(len)};function Rand(rand){this.rand=rand}Rand.prototype={},module.exports.Rand=Rand,Rand.prototype.generate=function(len){return this._rand(len)},Rand.prototype._rand=function(n){var out=new Buffer(n);return crypto.getRandomValues(out),out}}}),require_mr=__commonJS({\"node_modules/miller-rabin/lib/mr.js\"(exports,module){var bn=require_bn2(),brorand=require_brorand();function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin,MillerRabin.create=function(rand){return new MillerRabin(rand)},MillerRabin.prototype={},MillerRabin.prototype._randbelow=function(n){var len=n.bitLength(),min_bytes=Math.ceil(len/8);do var a=new bn(this.rand.generate(min_bytes));while(a.cmp(n)>=0);return a},MillerRabin.prototype._randrange=function(start,stop){var size=stop.sub(start);return start.add(this._randbelow(size))},MillerRabin.prototype.test=function(n,k,cb){var len=n.bitLength(),red=bn.mont(n),rone=new bn(1).toRed(red);k||(k=Math.max(1,len/48|0));for(var n1=n.subn(1),s=0;!n1.testn(s);s++);for(var d=n.shrn(s),rn1=n1.toRed(red),prime=!0;k>0;k--){var a=this._randrange(new bn(2),n1);cb&&cb(a);var x=a.toRed(red).redPow(d);if(!(x.cmp(rone)===0||x.cmp(rn1)===0)){for(var i=1;i0;k--){var a=this._randrange(new bn(2),n1),g=n.gcd(a);if(g.cmpn(1)!==0)return g;var x=a.toRed(red).redPow(d);if(!(x.cmp(rone)===0||x.cmp(rn1)===0)){for(var i=1;ibits;)num.ishrn(1);if(num.isEven()&&num.iadd(ONE),num.testn(1)||num.iadd(TWO),gen.cmp(TWO)){if(!gen.cmp(FIVE))for(;num.mod(TEN).cmp(THREE);)num.iadd(FOUR)}else for(;num.mod(TWENTYFOUR).cmp(ELEVEN);)num.iadd(FOUR);if(n2=num.shrn(1),simpleSieve(n2)&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num))return num}}}}),require_primes=__commonJS({\"node_modules/diffie-hellman/lib/primes.json\"(exports,module){module.exports={modp1:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff\"},modp2:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff\"},modp5:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff\"},modp14:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff\"},modp15:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff\"},modp16:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff\"},modp17:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff\"},modp18:{gen:\"02\",prime:\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff\"}}}}),require_dh=__commonJS({\"node_modules/diffie-hellman/lib/dh.js\"(exports,module){var BN=require_bn(),MillerRabin=require_mr(),millerRabin=new MillerRabin,TWENTYFOUR=new BN(24),ELEVEN=new BN(11),TEN=new BN(10),THREE=new BN(3),SEVEN=new BN(7),primes=require_generatePrime(),randomBytes=require_browser();module.exports=DH;function setPublicKey(pub,enc){return enc=enc||\"utf8\",Buffer.isBuffer(pub)||(pub=new Buffer(pub,enc)),this._pub=new BN(pub),this}function setPrivateKey(priv,enc){return enc=enc||\"utf8\",Buffer.isBuffer(priv)||(priv=new Buffer(priv,enc)),this._priv=new BN(priv),this}var primeCache={};function checkPrime(prime,generator){var gen=generator.toString(\"hex\"),hex=[gen,prime.toString(16)].join(\"_\");if(hex in primeCache)return primeCache[hex];var error=0;if(prime.isEven()||!primes.simpleSieve||!primes.fermatTest(prime)||!millerRabin.test(prime))return error+=1,gen===\"02\"||gen===\"05\"\?error+=8:error+=4,primeCache[hex]=error,error;millerRabin.test(prime.shrn(1))||(error+=2);var rem;switch(gen){case\"02\":prime.mod(TWENTYFOUR).cmp(ELEVEN)&&(error+=8);break;case\"05\":rem=prime.mod(TEN),rem.cmp(THREE)&&rem.cmp(SEVEN)&&(error+=8);break;default:error+=4}return primeCache[hex]=error,error}function DH(prime,generator,malleable){this.setGenerator(generator),this.__prime=new BN(prime),this._prime=BN.mont(this.__prime),this._primeLen=prime.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,malleable\?(this.setPublicKey=setPublicKey,this.setPrivateKey=setPrivateKey):this._primeCode=8}DH.prototype={},Object.defineProperty(DH.prototype,\"verifyError\",{enumerable:!0,get:function(){return typeof this._primeCode!=\"number\"&&(this._primeCode=checkPrime(this.__prime,this.__gen)),this._primeCode}}),DH.prototype.generateKeys=function(){return this._priv||(this._priv=new BN(randomBytes(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},DH.prototype.computeSecret=function(other){other=new BN(other),other=other.toRed(this._prime);var secret=other.redPow(this._priv).fromRed(),out=new Buffer(secret.toArray()),prime=this.getPrime();if(out.length=0||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=blind(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,\"be\",len)}crt.getr=getr,module.exports=crt}}),require_package=__commonJS({\"node_modules/elliptic/package.json\"(exports,module){module.exports={name:\"elliptic\",version:\"6.5.4\",description:\"EC cryptography\",main:\"lib/elliptic.js\",files:[\"lib\"],scripts:{lint:\"eslint lib test\",\"lint:fix\":\"npm run lint -- --fix\",unit:\"istanbul test _mocha --reporter=spec test/index.js\",test:\"npm run lint && npm run unit\",version:\"grunt dist && git add dist/\"},repository:{type:\"git\",url:\"git@github.com:indutny/elliptic\"},keywords:[\"EC\",\"Elliptic\",\"curve\",\"Cryptography\"],author:\"Fedor Indutny \",license:\"MIT\",bugs:{url:\"https://github.com/indutny/elliptic/issues\"},homepage:\"https://github.com/indutny/elliptic\",devDependencies:{brfs:\"^2.0.2\",coveralls:\"^3.1.0\",eslint:\"^7.6.0\",grunt:\"^1.2.1\",\"grunt-browserify\":\"^5.3.0\",\"grunt-cli\":\"^1.3.2\",\"grunt-contrib-connect\":\"^3.0.0\",\"grunt-contrib-copy\":\"^1.0.0\",\"grunt-contrib-uglify\":\"^5.0.0\",\"grunt-mocha-istanbul\":\"^5.0.2\",\"grunt-saucelabs\":\"^9.0.1\",istanbul:\"^0.4.5\",mocha:\"^8.0.1\"},dependencies:{\"bn.js\":\"^4.11.9\",brorand:\"^1.1.0\",\"hash.js\":\"^1.0.0\",\"hmac-drbg\":\"^1.0.1\",inherits:\"^2.0.4\",\"minimalistic-assert\":\"^1.0.1\",\"minimalistic-crypto-utils\":\"^1.0.1\"}}}}),require_bn4=require_bn,require_utils2=__commonJS({\"node_modules/minimalistic-crypto-utils/lib/utils.js\"(exports){var utils=exports;function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg!=\"string\"){for(var i=0;i>8,lo=c&255;hi\?res.push(hi,lo):res.push(lo)}return res}utils.toArray=toArray;function zero2(word){return word.length===1\?\"0\"+word:word}utils.zero2=zero2;function toHex(msg){for(var res=\"\",i=0;i(ws>>1)-1\?z=(ws>>1)-mod:z=mod,k.isubn(z)):z=0,naf[i]=z,k.iushrn(1)}return naf}utils.getNAF=getNAF;function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone(),k2=k2.clone();for(var d1=0,d2=0,m8;k1.cmpn(-d1)>0||k2.cmpn(-d2)>0;){var m14=k1.andln(3)+d1&3,m24=k2.andln(3)+d2&3;m14===3&&(m14=-1),m24===3&&(m24=-1);var u1;(m14&1)===0\?u1=0:(m8=k1.andln(7)+d1&7,(m8===3||m8===5)&&m24===2\?u1=-m14:u1=m14),jsf[0].push(u1);var u2;(m24&1)===0\?u2=0:(m8=k2.andln(7)+d2&7,(m8===3||m8===5)&&m14===2\?u2=-m24:u2=m24),jsf[1].push(u2),2*d1===u1+1&&(d1=1-d1),2*d2===u2+1&&(d2=1-d2),k1.iushrn(1),k2.iushrn(1)}return jsf}utils.getJSF=getJSF;function cachedProperty(obj,name,computer){var key=\"_\"+name;obj.prototype[name]=function(){return this[key]!==void 0\?this[key]:this[key]=computer.call(this)}}utils.cachedProperty=cachedProperty;function parseBytes(bytes){return typeof bytes==\"string\"\?utils.toArray(bytes,\"hex\"):bytes}utils.parseBytes=parseBytes;function intFromLE(bytes){return new BN(bytes,\"hex\",\"le\")}utils.intFromLE=intFromLE}}),require_base=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/base.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),getNAF=utils.getNAF,getJSF=utils.getJSF,assert=utils.assert;function BaseCurve(type,conf){this.type=type,this.p=new BN(conf.p,16),this.red=conf.prime\?BN.red(conf.prime):BN.mont(this.p),this.zero=new BN(0).toRed(this.red),this.one=new BN(1).toRed(this.red),this.two=new BN(2).toRed(this.red),this.n=conf.n&&new BN(conf.n,16),this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n\?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);!adjustCount||adjustCount.cmpn(100)>0\?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}module.exports=BaseCurve,BaseCurve.prototype={},BaseCurve.prototype.point=function(){throw new Error(\"Not implemented\")},BaseCurve.prototype.validate=function(){throw new Error(\"Not implemented\")},BaseCurve.prototype._fixedNafMul=function(p,k){assert(p.precomputed);var doubles=p._getDoubles(),naf=getNAF(k,1,this._bitLength),I=(1<=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}for(var a=this.jpoint(null,null,null),b=this.jpoint(null,null,null),i=I;i>0;i--){for(j=0;j=0;i--){for(var l=0;i>=0&&naf[i]===0;i--)l++;if(i>=0&&l++,acc=acc.dblp(l),i<0)break;var z=naf[i];assert(z!==0),p.type===\"affine\"\?z>0\?acc=acc.mixedAdd(wnd[z-1>>1]):acc=acc.mixedAdd(wnd[-z-1>>1].neg()):z>0\?acc=acc.add(wnd[z-1>>1]):acc=acc.add(wnd[-z-1>>1].neg())}return p.type===\"affine\"\?acc.toP():acc},BaseCurve.prototype._wnafMulAdd=function(defW,points,coeffs,len,jacobianResult){var wndWidth=this._wnafT1,wnd=this._wnafT2,naf=this._wnafT3,max=0,i,j,p;for(i=0;i=1;i-=2){var a=i-1,b=i;if(wndWidth[a]!==1||wndWidth[b]!==1){naf[a]=getNAF(coeffs[a],wndWidth[a],this._bitLength),naf[b]=getNAF(coeffs[b],wndWidth[b],this._bitLength),max=Math.max(naf[a].length,max),max=Math.max(naf[b].length,max);continue}var comb=[points[a],null,null,points[b]];points[a].y.cmp(points[b].y)===0\?(comb[1]=points[a].add(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg())):points[a].y.cmp(points[b].y.redNeg())===0\?(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].add(points[b].neg())):(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg()));var index=[-3,-1,-5,-7,0,7,5,1,3],jsf=getJSF(coeffs[a],coeffs[b]);for(max=Math.max(jsf[0].length,max),naf[a]=new Array(max),naf[b]=new Array(max),j=0;j=0;i--){for(var k=0;i>=0;){var zero=!0;for(j=0;j=0&&k++,acc=acc.dblp(k),i<0)break;for(j=0;j0\?p=wnd[j][z-1>>1]:z<0&&(p=wnd[j][-z-1>>1].neg()),p.type===\"affine\"\?acc=acc.mixedAdd(p):acc=acc.add(p))}}for(i=0;i=Math.ceil((k.bitLength()+1)/doubles.step):!1},BasePoint.prototype._getDoubles=function(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var doubles=[this],acc=this,i=0;i=0&&(a2=a0,b2=b0),a1.negative&&(a1=a1.neg(),b1=b1.neg()),a2.negative&&(a2=a2.neg(),b2=b2.neg()),[{a:a1,b:b1},{a:a2,b:b2}]},ShortCurve.prototype._endoSplit=function(k){var basis=this.endo.basis,v1=basis[0],v2=basis[1],c1=v2.b.mul(k).divRound(this.n),c2=v1.b.neg().mul(k).divRound(this.n),p1=c1.mul(v1.a),p2=c2.mul(v2.a),q1=c1.mul(v1.b),q2=c2.mul(v2.b),k1=k.sub(p1).sub(p2),k2=q1.add(q2).neg();return{k1,k2}},ShortCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b),y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error(\"invalid point\");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},ShortCurve.prototype.validate=function(point){if(point.inf)return!0;var{x,y}=point,ax=this.a.redMul(x),rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return y.redSqr().redISub(rhs).cmpn(0)===0},ShortCurve.prototype._endoWnafMulAdd=function(points,coeffs,jacobianResult){for(var npoints=this._endoWnafT1,ncoeffs=this._endoWnafT2,i=0;i\":\"\"},Point.prototype.isInfinity=function(){return this.inf},Point.prototype.add=function(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(this.x.cmp(p.x)===0)return this.curve.point(null,null);var c=this.y.redSub(p.y);c.cmpn(0)!==0&&(c=c.redMul(this.x.redSub(p.x).redInvm()));var nx=c.redSqr().redISub(this.x).redISub(p.x),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.dbl=function(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(ys1.cmpn(0)===0)return this.curve.point(null,null);var a=this.curve.a,x2=this.x.redSqr(),dyinv=ys1.redInvm(),c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv),nx=c.redSqr().redISub(this.x.redAdd(this.x)),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.getX=function(){return this.x.fromRed()},Point.prototype.getY=function(){return this.y.fromRed()},Point.prototype.mul=function(k){return k=new BN(k,16),this.isInfinity()\?this:this._hasDoubles(k)\?this.curve._fixedNafMul(this,k):this.curve.endo\?this.curve._endoWnafMulAdd([this],[k]):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo\?this.curve._endoWnafMulAdd(points,coeffs):this.curve._wnafMulAdd(1,points,coeffs,2)},Point.prototype.jmulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo\?this.curve._endoWnafMulAdd(points,coeffs,!0):this.curve._wnafMulAdd(1,points,coeffs,2,!0)},Point.prototype.eq=function(p){return this===p||this.inf===p.inf&&(this.inf||this.x.cmp(p.x)===0&&this.y.cmp(p.y)===0)},Point.prototype.neg=function(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed,negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res},Point.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res};function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,\"jacobian\"),x===null&&y===null&&z===null\?(this.x=this.curve.one,this.y=this.curve.one,this.z=new BN(0)):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=new BN(z,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}inherits(JPoint,Base.BasePoint),ShortCurve.prototype.jpoint=function(x,y,z){return new JPoint(this,x,y,z)},JPoint.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm(),zinv2=zinv.redSqr(),ax=this.x.redMul(zinv2),ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)},JPoint.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},JPoint.prototype.add=function(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr(),z2=this.z.redSqr(),u1=this.x.redMul(pz2),u2=p.x.redMul(z2),s1=this.y.redMul(pz2.redMul(p.z)),s2=p.y.redMul(z2.redMul(this.z)),h=u1.redSub(u2),r=s1.redSub(s2);if(h.cmpn(0)===0)return r.cmpn(0)!==0\?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.mixedAdd=function(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr(),u1=this.x,u2=p.x.redMul(z2),s1=this.y,s2=p.y.redMul(z2).redMul(this.z),h=u1.redSub(u2),r=s1.redSub(s2);if(h.cmpn(0)===0)return r.cmpn(0)!==0\?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.dblp=function(pow){if(pow===0)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i=0)return!1;if(rx.redIAdd(t),this.x.cmp(rx)===0)return!0}},JPoint.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},JPoint.prototype.isInfinity=function(){return this.z.cmpn(0)===0}}}),require_mont=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/mont.js\"(exports,module){var BN=require_bn4(),inherits=require_inherits_browser(),Base=require_base(),utils=require_utils3();function MontCurve(conf){Base.call(this,\"mont\",conf),this.a=new BN(conf.a,16).toRed(this.red),this.b=new BN(conf.b,16).toRed(this.red),this.i4=new BN(4).toRed(this.red).redInvm(),this.two=new BN(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}inherits(MontCurve,Base),module.exports=MontCurve,MontCurve.prototype.validate=function(point){var x=point.normalize().x,x2=x.redSqr(),rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x),y=rhs.redSqrt();return y.redSqr().cmp(rhs)===0};function Point(curve,x,z){Base.BasePoint.call(this,curve,\"projective\"),x===null&&z===null\?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new BN(x,16),this.z=new BN(z,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}inherits(Point,Base.BasePoint),MontCurve.prototype.decodePoint=function(bytes,enc){return this.point(utils.toArray(bytes,enc),1)},MontCurve.prototype.point=function(x,z){return new Point(this,x,z)},MontCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},Point.prototype.precompute=function(){},Point.prototype._encode=function(){return this.getX().toArray(\"be\",this.curve.p.byteLength())},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)},Point.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},Point.prototype.isInfinity=function(){return this.z.cmpn(0)===0},Point.prototype.dbl=function(){var a=this.x.redAdd(this.z),aa=a.redSqr(),b=this.x.redSub(this.z),bb=b.redSqr(),c=aa.redSub(bb),nx=aa.redMul(bb),nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)},Point.prototype.add=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.diffAdd=function(p,diff){var a=this.x.redAdd(this.z),b=this.x.redSub(this.z),c=p.x.redAdd(p.z),d=p.x.redSub(p.z),da=d.redMul(a),cb=c.redMul(b),nx=diff.z.redMul(da.redAdd(cb).redSqr()),nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)},Point.prototype.mul=function(k){for(var t=k.clone(),a=this,b=this.curve.point(null,null),c=this,bits=[];t.cmpn(0)!==0;t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--)bits[i]===0\?(a=a.diffAdd(b,c),b=b.dbl()):(b=a.diffAdd(b,c),a=a.dbl());return b},Point.prototype.mulAdd=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.jumlAdd=function(){throw new Error(\"Not supported on Montgomery curve\")},Point.prototype.eq=function(other){return this.getX().cmp(other.getX())===0},Point.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()}}}),require_edwards=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/edwards.js\"(exports,module){var utils=require_utils3(),BN=require_bn4(),inherits=require_inherits_browser(),Base=require_base(),assert=utils.assert;function EdwardsCurve(conf){this.twisted=(conf.a|0)!==1,this.mOneA=this.twisted&&(conf.a|0)===-1,this.extended=this.mOneA,Base.call(this,\"edwards\",conf),this.a=new BN(conf.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new BN(conf.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new BN(conf.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),assert(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(conf.c|0)===1}inherits(EdwardsCurve,Base),module.exports=EdwardsCurve,EdwardsCurve.prototype._mulA=function(num){return this.mOneA\?num.redNeg():this.a.redMul(num)},EdwardsCurve.prototype._mulC=function(num){return this.oneC\?num:this.c.redMul(num)},EdwardsCurve.prototype.jpoint=function(x,y,z,t){return this.point(x,y,z,t)},EdwardsCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var x2=x.redSqr(),rhs=this.c2.redSub(this.a.redMul(x2)),lhs=this.one.redSub(this.c2.redMul(this.d).redMul(x2)),y2=rhs.redMul(lhs.redInvm()),y=y2.redSqrt();if(y.redSqr().redSub(y2).cmp(this.zero)!==0)throw new Error(\"invalid point\");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},EdwardsCurve.prototype.pointFromY=function(y,odd){y=new BN(y,16),y.red||(y=y.toRed(this.red));var y2=y.redSqr(),lhs=y2.redSub(this.c2),rhs=y2.redMul(this.d).redMul(this.c2).redSub(this.a),x2=lhs.redMul(rhs.redInvm());if(x2.cmp(this.zero)===0){if(odd)throw new Error(\"invalid point\");return this.point(this.zero,y)}var x=x2.redSqrt();if(x.redSqr().redSub(x2).cmp(this.zero)!==0)throw new Error(\"invalid point\");return x.fromRed().isOdd()!==odd&&(x=x.redNeg()),this.point(x,y)},EdwardsCurve.prototype.validate=function(point){if(point.isInfinity())return!0;point.normalize();var x2=point.x.redSqr(),y2=point.y.redSqr(),lhs=x2.redMul(this.a).redAdd(y2),rhs=this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));return lhs.cmp(rhs)===0};function Point(curve,x,y,z,t){Base.BasePoint.call(this,curve,\"projective\"),x===null&&y===null&&z===null\?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=z\?new BN(z,16):this.curve.one,this.t=t&&new BN(t,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}inherits(Point,Base.BasePoint),EdwardsCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},EdwardsCurve.prototype.point=function(x,y,z,t){return new Point(this,x,y,z,t)},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1],obj[2])},Point.prototype.inspect=function(){return this.isInfinity()\?\"\":\"\"},Point.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},Point.prototype._extDbl=function(){var a=this.x.redSqr(),b=this.y.redSqr(),c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a),e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b),g=d.redAdd(b),f=g.redSub(c),h=d.redSub(b),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projDbl=function(){var b=this.x.redAdd(this.y).redSqr(),c=this.x.redSqr(),d=this.y.redSqr(),nx,ny,nz,e,h,j;if(this.curve.twisted){e=this.curve._mulA(c);var f=e.redAdd(d);this.zOne\?(nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)),ny=f.redMul(e.redSub(d)),nz=f.redSqr().redSub(f).redSub(f)):(h=this.z.redSqr(),j=f.redSub(h).redISub(h),nx=b.redSub(c).redISub(d).redMul(j),ny=f.redMul(e.redSub(d)),nz=f.redMul(j))}else e=c.redAdd(d),h=this.curve._mulC(this.z).redSqr(),j=e.redSub(h).redSub(h),nx=this.curve._mulC(b.redISub(e)).redMul(j),ny=this.curve._mulC(e).redMul(c.redISub(d)),nz=e.redMul(j);return this.curve.point(nx,ny,nz)},Point.prototype.dbl=function(){return this.isInfinity()\?this:this.curve.extended\?this._extDbl():this._projDbl()},Point.prototype._extAdd=function(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x)),b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)),c=this.t.redMul(this.curve.dd).redMul(p.t),d=this.z.redMul(p.z.redAdd(p.z)),e=b.redSub(a),f=d.redSub(c),g=d.redAdd(c),h=b.redAdd(a),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projAdd=function(p){var a=this.z.redMul(p.z),b=a.redSqr(),c=this.x.redMul(p.x),d=this.y.redMul(p.y),e=this.curve.d.redMul(c).redMul(d),f=b.redSub(e),g=b.redAdd(e),tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d),nx=a.redMul(f).redMul(tmp),ny,nz;return this.curve.twisted\?(ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c))),nz=f.redMul(g)):(ny=a.redMul(g).redMul(d.redSub(c)),nz=this.curve._mulC(f).redMul(g)),this.curve.point(nx,ny,nz)},Point.prototype.add=function(p){return this.isInfinity()\?p:p.isInfinity()\?this:this.curve.extended\?this._extAdd(p):this._projAdd(p)},Point.prototype.mul=function(k){return this._hasDoubles(k)\?this.curve._fixedNafMul(this,k):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!1)},Point.prototype.jmulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!0)},Point.prototype.normalize=function(){if(this.zOne)return this;var zi=this.z.redInvm();return this.x=this.x.redMul(zi),this.y=this.y.redMul(zi),this.t&&(this.t=this.t.redMul(zi)),this.z=this.curve.one,this.zOne=!0,this},Point.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Point.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Point.prototype.eq=function(other){return this===other||this.getX().cmp(other.getX())===0&&this.getY().cmp(other.getY())===0},Point.prototype.eqXToP=function(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(rx)===0)return!0;for(var xc=x.clone(),t=this.curve.redN.redMul(this.z);;){if(xc.iadd(this.curve.n),xc.cmp(this.curve.p)>=0)return!1;if(rx.redIAdd(t),this.x.cmp(rx)===0)return!0}},Point.prototype.toP=Point.prototype.normalize,Point.prototype.mixedAdd=Point.prototype.add}}),require_curve=__commonJS({\"node_modules/elliptic/lib/elliptic/curve/index.js\"(exports){var curve=exports;curve.base=require_base(),curve.short=require_short(),curve.mont=require_mont(),curve.edwards=require_edwards()}}),require_utils4=__commonJS({\"node_modules/hash.js/lib/hash/utils.js\"(exports){var assert=require_minimalistic_assert(),inherits=require_inherits_browser();exports.inherits=inherits;function isSurrogatePair(msg,i){return(msg.charCodeAt(i)&64512)!==55296||i<0||i+1>=msg.length\?!1:(msg.charCodeAt(i+1)&64512)===56320}function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if(typeof msg==\"string\")if(enc){if(enc===\"hex\")for(msg=msg.replace(/[^a-z0-9]+/gi,\"\"),msg.length%2!==0&&(msg=\"0\"+msg),i=0;i>6|192,res[p++]=c&63|128):isSurrogatePair(msg,i)\?(c=65536+((c&1023)<<10)+(msg.charCodeAt(++i)&1023),res[p++]=c>>18|240,res[p++]=c>>12&63|128,res[p++]=c>>6&63|128,res[p++]=c&63|128):(res[p++]=c>>12|224,res[p++]=c>>6&63|128,res[p++]=c&63|128)}else for(i=0;i>>24|w>>>8&65280|w<<8&16711680|(w&255)<<24;return res>>>0}exports.htonl=htonl;function toHex32(msg,endian){for(var res=\"\",i=0;i>>0}return res}exports.join32=join32;function split32(msg,endian){for(var res=new Array(msg.length*4),i=0,k=0;i>>24,res[k+1]=m>>>16&255,res[k+2]=m>>>8&255,res[k+3]=m&255):(res[k+3]=m>>>24,res[k+2]=m>>>16&255,res[k+1]=m>>>8&255,res[k]=m&255)}return res}exports.split32=split32;function rotr32(w,b){return w>>>b|w<<32-b}exports.rotr32=rotr32;function rotl32(w,b){return w<>>32-b}exports.rotl32=rotl32;function sum32(a,b){return a+b>>>0}exports.sum32=sum32;function sum32_3(a,b,c){return a+b+c>>>0}exports.sum32_3=sum32_3;function sum32_4(a,b,c,d){return a+b+c+d>>>0}exports.sum32_4=sum32_4;function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}exports.sum32_5=sum32_5;function sum64(buf,pos,ah,al){var bh=buf[pos],bl=buf[pos+1],lo=al+bl>>>0,hi=(lo>>0,buf[pos+1]=lo}exports.sum64=sum64;function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0,hi=(lo>>0}exports.sum64_hi=sum64_hi;function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}exports.sum64_lo=sum64_lo;function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}exports.sum64_4_hi=sum64_4_hi;function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}exports.sum64_4_lo=sum64_4_lo;function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}exports.sum64_5_hi=sum64_5_hi;function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el;return lo>>>0}exports.sum64_5_lo=sum64_5_lo;function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}exports.rotr64_hi=rotr64_hi;function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.rotr64_lo=rotr64_lo;function shr64_hi(ah,al,num){return ah>>>num}exports.shr64_hi=shr64_hi;function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}exports.shr64_lo=shr64_lo}}),require_common=__commonJS({\"node_modules/hash.js/lib/hash/common.js\"(exports){var utils=require_utils4(),assert=require_minimalistic_assert();function BlockHash(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian=\"big\",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}BlockHash.prototype={},exports.BlockHash=BlockHash,BlockHash.prototype.update=function(msg,enc){if(msg=utils.toArray(msg,enc),this.pending\?this.pending=this.pending.concat(msg):this.pending=msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),this.pending.length===0&&(this.pending=null),msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i>>24&255,res[i++]=len>>>16&255,res[i++]=len>>>8&255,res[i++]=len&255}else for(res[i++]=len&255,res[i++]=len>>>8&255,res[i++]=len>>>16&255,res[i++]=len>>>24&255,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,t=8;t>>3}exports.g0_256=g0_256;function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}exports.g1_256=g1_256}}),require__=__commonJS({\"node_modules/hash.js/lib/hash/sha/1.js\"(exports,module){var utils=require_utils4(),common=require_common(),shaCommon=require_common2(),rotl32=utils.rotl32,sum32=utils.sum32,sum32_5=utils.sum32_5,ft_1=shaCommon.ft_1,BlockHash=common.BlockHash,sha1_K=[1518500249,1859775393,2400959708,3395469782];function SHA1(){if(!(this instanceof SHA1))return new SHA1;BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}utils.inherits(SHA1,BlockHash),module.exports=SHA1,SHA1.blockSize=512,SHA1.outSize=160,SHA1.hmacStrength=80,SHA1.padLength=64,SHA1.prototype._update=function(msg,start){for(var W=this.W,i=0;i<16;i++)W[i]=msg[start+i];for(;ithis.blockSize&&(key=new this.Hash().update(key).digest()),assert(key.length<=this.blockSize);for(var i=key.length;i=this.minEntropy/8,\"Not enough entropy. Minimum is: \"+this.minEntropy+\" bits\"),this._init(entropy,nonce,pers)}HmacDRBG.prototype={},module.exports=HmacDRBG,HmacDRBG.prototype._init=function(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,\"Not enough entropy. Minimum is: \"+this.minEntropy+\" bits\"),this._update(entropy.concat(add||[])),this._reseed=1},HmacDRBG.prototype.generate=function(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error(\"Reseed is required\");typeof enc!=\"string\"&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc||\"hex\"),this._update(add));for(var temp=[];temp.length\"}}}),require_signature=__commonJS({\"node_modules/elliptic/lib/elliptic/ec/signature.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),assert=utils.assert;function Signature(options,enc){if(options instanceof Signature)return options;this._importDER(options,enc)||(assert(options.r&&options.s,\"Signature without r or s\"),this.r=new BN(options.r,16),this.s=new BN(options.s,16),options.recoveryParam===void 0\?this.recoveryParam=null:this.recoveryParam=options.recoveryParam)}Signature.prototype={},module.exports=Signature;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(initial&128))return initial;var octetLen=initial&15;if(octetLen===0||octetLen>4)return!1;for(var val=0,i=0,off=p.place;i>>=0;return val<=127\?!1:(p.place=off,val)}function rmPadding(buf){for(var i=0,len=buf.length-1;!buf[i]&&!(buf[i+1]&128)&&i>>3);for(arr.push(octets|128);--octets;)arr.push(len>>>(octets<<3)&255);arr.push(len)}Signature.prototype.toDER=function(enc){var r=this.r.toArray(),s=this.s.toArray();for(r[0]&128&&(r=[0].concat(r)),s[0]&128&&(s=[0].concat(s)),r=rmPadding(r),s=rmPadding(s);!s[0]&&!(s[1]&128);)s=s.slice(1);var arr=[2];constructLength(arr,r.length),arr=arr.concat(r),arr.push(2),constructLength(arr,s.length);var backHalf=arr.concat(s),res=[48];return constructLength(res,backHalf.length),res=res.concat(backHalf),utils.encode(res,enc)}}}),require_ec=__commonJS({\"node_modules/elliptic/lib/elliptic/ec/index.js\"(exports,module){var BN=require_bn4(),HmacDRBG=require_hmac_drbg(),utils=require_utils3(),curves=require_curves(),rand=require_brorand(),assert=utils.assert,KeyPair=require_key(),Signature=require_signature();function EC(options){if(!(this instanceof EC))return new EC(options);typeof options==\"string\"&&(assert(Object.prototype.hasOwnProperty.call(curves,options),\"Unknown curve \"+options),options=curves[options]),options instanceof curves.PresetCurve&&(options={curve:options}),this.curve=options.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=options.curve.g,this.g.precompute(options.curve.n.bitLength()+1),this.hash=options.hash||options.curve.hash}EC.prototype={},module.exports=EC,EC.prototype.keyPair=function(options){return new KeyPair(this,options)},EC.prototype.keyFromPrivate=function(priv,enc){return KeyPair.fromPrivate(this,priv,enc)},EC.prototype.keyFromPublic=function(pub,enc){return KeyPair.fromPublic(this,pub,enc)},EC.prototype.genKeyPair=function(options){options||(options={});for(var drbg=new HmacDRBG({hash:this.hash,pers:options.pers,persEnc:options.persEnc||\"utf8\",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||\"utf8\",nonce:this.n.toArray()}),bytes=this.n.byteLength(),ns2=this.n.sub(new BN(2));;){var priv=new BN(drbg.generate(bytes));if(!(priv.cmp(ns2)>0))return priv.iaddn(1),this.keyFromPrivate(priv)}},EC.prototype._truncateToN=function(msg,truncOnly){var delta=msg.byteLength()*8-this.n.bitLength();return delta>0&&(msg=msg.ushrn(delta)),!truncOnly&&msg.cmp(this.n)>=0\?msg.sub(this.n):msg},EC.prototype.sign=function(msg,key,enc,options){typeof enc==\"object\"&&(options=enc,enc=null),options||(options={}),key=this.keyFromPrivate(key,enc),msg=this._truncateToN(new BN(msg,16));for(var bytes=this.n.byteLength(),bkey=key.getPrivate().toArray(\"be\",bytes),nonce=msg.toArray(\"be\",bytes),drbg=new HmacDRBG({hash:this.hash,entropy:bkey,nonce,pers:options.pers,persEnc:options.persEnc||\"utf8\"}),ns1=this.n.sub(new BN(1)),iter=0;;iter++){var k=options.k\?options.k(iter):new BN(drbg.generate(this.n.byteLength()));if(k=this._truncateToN(k,!0),!(k.cmpn(1)<=0||k.cmp(ns1)>=0)){var kp=this.g.mul(k);if(!kp.isInfinity()){var kpX=kp.getX(),r=kpX.umod(this.n);if(r.cmpn(0)!==0){var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));if(s=s.umod(this.n),s.cmpn(0)!==0){var recoveryParam=(kp.getY().isOdd()\?1:0)|(kpX.cmp(r)!==0\?2:0);return options.canonical&&s.cmp(this.nh)>0&&(s=this.n.sub(s),recoveryParam^=1),new Signature({r,s,recoveryParam})}}}}}},EC.prototype.verify=function(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16)),key=this.keyFromPublic(key,enc),signature=new Signature(signature,\"hex\");var{r,s}=signature;if(r.cmpn(1)<0||r.cmp(this.n)>=0||s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var sinv=s.invm(this.n),u1=sinv.mul(msg).umod(this.n),u2=sinv.mul(r).umod(this.n),p;return this.curve._maxwellTrick\?(p=this.g.jmulAdd(u1,key.getPublic(),u2),p.isInfinity()\?!1:p.eqXToP(r)):(p=this.g.mulAdd(u1,key.getPublic(),u2),p.isInfinity()\?!1:p.getX().umod(this.n).cmp(r)===0)},EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,\"The recovery param is more than two bits\"),signature=new Signature(signature,enc);var n=this.n,e=new BN(msg),r=signature.r,s=signature.s,isYOdd=j&1,isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error(\"Unable to find sencond key candinate\");isSecondKey\?r=this.curve.pointFromX(r.add(this.curve.n),isYOdd):r=this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n),s1=n.sub(e).mul(rInv).umod(n),s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)},EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){if(signature=new Signature(signature,enc),signature.recoveryParam!==null)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch{continue}if(Qprime.eq(Q))return i}throw new Error(\"Unable to find valid recovery factor\")}}}),require_key2=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/key.js\"(exports,module){var utils=require_utils3(),assert=utils.assert,parseBytes=utils.parseBytes,cachedProperty=utils.cachedProperty;function KeyPair(eddsa,params){this.eddsa=eddsa,this._secret=parseBytes(params.secret),eddsa.isPoint(params.pub)\?this._pub=params.pub:this._pubBytes=parseBytes(params.pub)}KeyPair.prototype={},KeyPair.fromPublic=function(eddsa,pub){return pub instanceof KeyPair\?pub:new KeyPair(eddsa,{pub})},KeyPair.fromSecret=function(eddsa,secret){return secret instanceof KeyPair\?secret:new KeyPair(eddsa,{secret})},KeyPair.prototype.secret=function(){return this._secret},cachedProperty(KeyPair,\"pubBytes\",function(){return this.eddsa.encodePoint(this.pub())}),cachedProperty(KeyPair,\"pub\",function(){return this._pubBytes\?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())}),cachedProperty(KeyPair,\"privBytes\",function(){var eddsa=this.eddsa,hash=this.hash(),lastIx=eddsa.encodingLength-1,a=hash.slice(0,eddsa.encodingLength);return a[0]&=248,a[lastIx]&=127,a[lastIx]|=64,a}),cachedProperty(KeyPair,\"priv\",function(){return this.eddsa.decodeInt(this.privBytes())}),cachedProperty(KeyPair,\"hash\",function(){return this.eddsa.hash().update(this.secret()).digest()}),cachedProperty(KeyPair,\"messagePrefix\",function(){return this.hash().slice(this.eddsa.encodingLength)}),KeyPair.prototype.sign=function(message){return assert(this._secret,\"KeyPair can only verify\"),this.eddsa.sign(message,this)},KeyPair.prototype.verify=function(message,sig){return this.eddsa.verify(message,sig,this)},KeyPair.prototype.getSecret=function(enc){return assert(this._secret,\"KeyPair is public only\"),utils.encode(this.secret(),enc)},KeyPair.prototype.getPublic=function(enc){return utils.encode(this.pubBytes(),enc)},module.exports=KeyPair}}),require_signature2=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/signature.js\"(exports,module){var BN=require_bn4(),utils=require_utils3(),assert=utils.assert,cachedProperty=utils.cachedProperty,parseBytes=utils.parseBytes;function Signature(eddsa,sig){this.eddsa=eddsa,typeof sig!=\"object\"&&(sig=parseBytes(sig)),Array.isArray(sig)&&(sig={R:sig.slice(0,eddsa.encodingLength),S:sig.slice(eddsa.encodingLength)}),assert(sig.R&&sig.S,\"Signature without R or S\"),eddsa.isPoint(sig.R)&&(this._R=sig.R),sig.S instanceof BN&&(this._S=sig.S),this._Rencoded=Array.isArray(sig.R)\?sig.R:sig.Rencoded,this._Sencoded=Array.isArray(sig.S)\?sig.S:sig.Sencoded}Signature.prototype={},cachedProperty(Signature,\"S\",function(){return this.eddsa.decodeInt(this.Sencoded())}),cachedProperty(Signature,\"R\",function(){return this.eddsa.decodePoint(this.Rencoded())}),cachedProperty(Signature,\"Rencoded\",function(){return this.eddsa.encodePoint(this.R())}),cachedProperty(Signature,\"Sencoded\",function(){return this.eddsa.encodeInt(this.S())}),Signature.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Signature.prototype.toHex=function(){return utils.encode(this.toBytes(),\"hex\").toUpperCase()},module.exports=Signature}}),require_eddsa=__commonJS({\"node_modules/elliptic/lib/elliptic/eddsa/index.js\"(exports,module){var hash=require_hash2(),curves=require_curves(),utils=require_utils3(),assert=utils.assert,parseBytes=utils.parseBytes,KeyPair=require_key2(),Signature=require_signature2();function EDDSA(curve){if(assert(curve===\"ed25519\",\"only tested with ed25519 so far\"),!(this instanceof EDDSA))return new EDDSA(curve);curve=curves[curve].curve,this.curve=curve,this.g=curve.g,this.g.precompute(curve.n.bitLength()+1),this.pointClass=curve.point().constructor,this.encodingLength=Math.ceil(curve.n.bitLength()/8),this.hash=hash.sha512}EDDSA.prototype={},module.exports=EDDSA,EDDSA.prototype.sign=function(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret),r=this.hashInt(key.messagePrefix(),message),R=this.g.mul(r),Rencoded=this.encodePoint(R),s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv()),S=r.add(s_).umod(this.curve.n);return this.makeSignature({R,S,Rencoded})},EDDSA.prototype.verify=function(message,sig,pub){message=parseBytes(message),sig=this.makeSignature(sig);var key=this.keyFromPublic(pub),h=this.hashInt(sig.Rencoded(),key.pubBytes(),message),SG=this.g.mul(sig.S()),RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)},EDDSA.prototype.hashInt=function(){for(var hash2=this.hash(),i=0;i\"u\")@throwTypeError(\"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type \"+typeof value);return Buffer2(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if(typeof size!=\"number\")@throwTypeError('The \"size\" argument must be of type number. Received type '+typeof size);if(size<0||size>=2*(1<<30))@throwRangeError('The value \"'+size+'\" is invalid for option \"size\"');var buf=Buffer2(size);return!fill||fill.length===0\?buf.fill(0):typeof encoding==\"string\"\?buf.fill(fill,encoding):buf.fill(fill),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=MAX_STRING_LENGTH}catch{}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer}}),require_reporter=__commonJS({\"node_modules/asn1.js/lib/asn1/base/reporter.js\"(exports){var inherits=require_inherits_browser();function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}Reporter.prototype={},exports.Reporter=Reporter,Reporter.prototype.isError=function(obj){return obj instanceof ReporterError},Reporter.prototype.save=function(){let state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function(data){let state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function(index){let state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function(index,key,value){let state=this._reporterState;this.exitKey(index),state.obj!==null&&(state.obj[key]=value)},Reporter.prototype.path=function(){return this._reporterState.path.join(\"/\")},Reporter.prototype.enterObject=function(){let state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function(prev){let state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function(msg){let err,state=this._reporterState,inherited=msg instanceof ReporterError;if(inherited\?err=msg:err=new ReporterError(state.path.map(function(elem){return\"[\"+JSON.stringify(elem)+\"]\"}).join(\"\"),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function(result){let state=this._reporterState;return state.options.partial\?{result:this.isError(result)\?null:result,errors:state.errors}:result};function ReporterError(path,msg){this.path=path,this.rethrow(msg)}inherits(ReporterError,Error),ReporterError.prototype.rethrow=function(msg){if(this.message=msg+\" at: \"+(this.path||\"(shallow)\"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}}}),require_buffer=__commonJS({\"node_modules/asn1.js/lib/asn1/base/buffer.js\"(exports){var inherits=require_inherits_browser(),Reporter=require_reporter().Reporter,Buffer2=require_safer().Buffer;function DecoderBuffer(base,options){if(Reporter.call(this,options),!Buffer2.isBuffer(base)){this.error(\"Input not Buffer\");return}this.base=base,this.offset=0,this.length=base.length}inherits(DecoderBuffer,Reporter),exports.DecoderBuffer=DecoderBuffer,DecoderBuffer.isDecoderBuffer=function(data){return data instanceof DecoderBuffer\?!0:typeof data==\"object\"&&Buffer2.isBuffer(data.base)&&data.constructor.name===\"DecoderBuffer\"&&typeof data.offset==\"number\"&&typeof data.length==\"number\"&&typeof data.save==\"function\"&&typeof data.restore==\"function\"&&typeof data.isEmpty==\"function\"&&typeof data.readUInt8==\"function\"&&typeof data.skip==\"function\"&&typeof data.raw==\"function\"},DecoderBuffer.prototype.save=function(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function(save){let res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function(fail){return this.offset+1<=this.length\?this.base.readUInt8(this.offset++,!0):this.error(fail||\"DecoderBuffer overrun\")},DecoderBuffer.prototype.skip=function(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||\"DecoderBuffer overrun\");let res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function(save){return this.base.slice(save\?save.offset:this.offset,this.length)};function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return EncoderBuffer.isEncoderBuffer(item)||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if(typeof value==\"number\"){if(!(0<=value&&value<=255))return reporter.error(\"non-byte EncoderBuffer value\");this.value=value,this.length=1}else if(typeof value==\"string\")this.value=value,this.length=Buffer2.byteLength(value);else if(Buffer2.isBuffer(value))this.value=value,this.length=value.length;else return reporter.error(\"Unsupported type: \"+typeof value)}EncoderBuffer.prototype={},exports.EncoderBuffer=EncoderBuffer,EncoderBuffer.isEncoderBuffer=function(data){return data instanceof EncoderBuffer\?!0:typeof data==\"object\"&&data.constructor.name===\"EncoderBuffer\"&&typeof data.length==\"number\"&&typeof data.join==\"function\"},EncoderBuffer.prototype.join=function(out,offset){return out||(out=Buffer2.alloc(this.length)),offset||(offset=0),this.length===0||(Array.isArray(this.value)\?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):(typeof this.value==\"number\"\?out[offset]=this.value:typeof this.value==\"string\"\?out.write(this.value,offset):Buffer2.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length)),out}}}),require_node=__commonJS({\"node_modules/asn1.js/lib/asn1/base/node.js\"(exports,module){var Reporter=require_reporter().Reporter,EncoderBuffer=require_buffer().EncoderBuffer,DecoderBuffer=require_buffer().DecoderBuffer,assert=require_minimalistic_assert(),tags=[\"seq\",\"seqof\",\"set\",\"setof\",\"objid\",\"bool\",\"gentime\",\"utctime\",\"null_\",\"enum\",\"int\",\"objDesc\",\"bitstr\",\"bmpstr\",\"charstr\",\"genstr\",\"graphstr\",\"ia5str\",\"iso646str\",\"numstr\",\"octstr\",\"printstr\",\"t61str\",\"unistr\",\"utf8str\",\"videostr\"],methods=[\"key\",\"obj\",\"use\",\"optional\",\"explicit\",\"implicit\",\"def\",\"choice\",\"any\",\"contains\"].concat(tags),overrided=[\"_peekTag\",\"_decodeTag\",\"_use\",\"_decodeStr\",\"_decodeObjid\",\"_decodeTime\",\"_decodeNull\",\"_decodeInt\",\"_decodeBool\",\"_decodeList\",\"_encodeComposite\",\"_encodeStr\",\"_encodeObjid\",\"_encodeTime\",\"_encodeNull\",\"_encodeInt\",\"_encodeBool\"];function Node(enc,parent,name){let state={};this._baseState=state,state.name=name,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state.default=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}Node.prototype={},module.exports=Node;var stateProps=[\"enc\",\"parent\",\"children\",\"tag\",\"args\",\"reverseArgs\",\"choice\",\"optional\",\"any\",\"obj\",\"use\",\"alteredUse\",\"key\",\"default\",\"explicit\",\"implicit\",\"contains\"];Node.prototype.clone=function(){let state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});let res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function(){let state=this._baseState;methods.forEach(function(method){this[method]=function(){let clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function(body){let state=this._baseState;assert(state.parent===null),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,\"Root node can have only one child\")},Node.prototype._useArgs=function(args){let state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),children.length!==0&&(assert(state.children===null),state.children=children,children.forEach(function(child){child._baseState.parent=this},this)),args.length!==0&&(assert(state.args===null),state.args=args,state.reverseArgs=args.map(function(arg){if(typeof arg!=\"object\"||arg.constructor!==Object)return arg;let res={};return Object.keys(arg).forEach(function(key){key==(key|0)&&(key|=0);let value=arg[key];res[value]=key}),res}))},overrided.forEach(function(method){Node.prototype[method]=function(){let state=this._baseState;throw new Error(method+\" not implemented for encoding: \"+state.enc)}}),tags.forEach(function(tag){Node.prototype[tag]=function(){let state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(state.tag===null),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function(item){assert(item);let state=this._baseState;return assert(state.use===null),state.use=item,this},Node.prototype.optional=function(){let state=this._baseState;return state.optional=!0,this},Node.prototype.def=function(val){let state=this._baseState;return assert(state.default===null),state.default=val,state.optional=!0,this},Node.prototype.explicit=function(num){let state=this._baseState;return assert(state.explicit===null&&state.implicit===null),state.explicit=num,this},Node.prototype.implicit=function(num){let state=this._baseState;return assert(state.explicit===null&&state.implicit===null),state.implicit=num,this},Node.prototype.obj=function(){let state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,args.length!==0&&this._useArgs(args),this},Node.prototype.key=function(newKey){let state=this._baseState;return assert(state.key===null),state.key=newKey,this},Node.prototype.any=function(){let state=this._baseState;return state.any=!0,this},Node.prototype.choice=function(obj){let state=this._baseState;return assert(state.choice===null),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function(item){let state=this._baseState;return assert(state.use===null),state.contains=item,this},Node.prototype._decode=function(input,options){let state=this._baseState;if(state.parent===null)return input.wrapResult(state.children[0]._decode(input,options));let result=state.default,present=!0,prevKey=null;if(state.key!==null&&(prevKey=input.enterKey(state.key)),state.optional){let tag=null;if(state.explicit!==null\?tag=state.explicit:state.implicit!==null\?tag=state.implicit:state.tag!==null&&(tag=state.tag),tag===null&&!state.any){let save=input.save();try{state.choice===null\?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch{present=!1}input.restore(save)}else if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}let prevObj;if(state.obj&&present&&(prevObj=input.enterObject()),present){if(state.explicit!==null){let explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}let start=input.offset;if(state.use===null&&state.choice===null){let save;state.any&&(save=input.save());let body=this._decodeTag(input,state.implicit!==null\?state.implicit:state.tag,state.any);if(input.isError(body))return body;state.any\?result=input.raw(save):input=body}if(options&&options.track&&state.tag!==null&&options.track(input.path(),start,input.length,\"tagged\"),options&&options.track&&state.tag!==null&&options.track(input.path(),input.offset,input.length,\"content\"),state.any||(state.choice===null\?result=this._decodeGeneric(state.tag,input,options):result=this._decodeChoice(input,options)),input.isError(result))return result;if(!state.any&&state.choice===null&&state.children!==null&&state.children.forEach(function(child){child._decode(input,options)}),state.contains&&(state.tag===\"octstr\"||state.tag===\"bitstr\")){let data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),state.key!==null&&(result!==null||present===!0)\?input.leaveKey(prevKey,state.key,result):prevKey!==null&&input.exitKey(prevKey),result},Node.prototype._decodeGeneric=function(tag,input,options){let state=this._baseState;return tag===\"seq\"||tag===\"set\"\?null:tag===\"seqof\"||tag===\"setof\"\?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)\?this._decodeStr(input,tag,options):tag===\"objid\"&&state.args\?this._decodeObjid(input,state.args[0],state.args[1],options):tag===\"objid\"\?this._decodeObjid(input,null,null,options):tag===\"gentime\"||tag===\"utctime\"\?this._decodeTime(input,tag,options):tag===\"null_\"\?this._decodeNull(input,options):tag===\"bool\"\?this._decodeBool(input,options):tag===\"objDesc\"\?this._decodeStr(input,tag,options):tag===\"int\"||tag===\"enum\"\?this._decodeInt(input,state.args&&state.args[0],options):state.use!==null\?this._getUse(state.use,input._reporterState.obj)._decode(input,options):input.error(\"unknown tag: \"+tag)},Node.prototype._getUse=function(entity,obj){let state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(state.useDecoder._baseState.parent===null),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function(input,options){let state=this._baseState,result=null,match=!1;return Object.keys(state.choice).some(function(key){let save=input.save(),node=state.choice[key];try{let value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value},match=!0}catch{return input.restore(save),!1}return!0},this),match\?result:input.error(\"Choice not matched\")},Node.prototype._createEncoderBuffer=function(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function(data,reporter,parent){let state=this._baseState;if(state.default!==null&&state.default===data)return;let result=this._encodeValue(data,reporter,parent);if(result!==void 0&&!this._skipDefault(result,reporter,parent))return result},Node.prototype._encodeValue=function(data,reporter,parent){let state=this._baseState;if(state.parent===null)return state.children[0]._encode(data,reporter||new Reporter);let result=null;if(this.reporter=reporter,state.optional&&data===void 0)if(state.default!==null)data=state.default;else return;let content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){if(child._baseState.tag===\"null_\")return child._encode(null,reporter,data);if(child._baseState.key===null)return reporter.error(\"Child should have a key\");let prevKey=reporter.enterKey(child._baseState.key);if(typeof data!=\"object\")return reporter.error(\"Child expected, but input is not object\");let res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if(state.tag===\"seqof\"||state.tag===\"setof\"){if(!(state.args&&state.args.length===1))return reporter.error(\"Too many args for : \"+state.tag);if(!Array.isArray(data))return reporter.error(\"seqof/setof, but data is not Array\");let child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){let state2=this._baseState;return this._getUse(state2.args[0],data)._encode(item,reporter)},child))}else state.use!==null\?result=this._getUse(state.use,parent)._encode(data,reporter):(content=this._encodePrimitive(state.tag,data),primitive=!0);if(!state.any&&state.choice===null){let tag=state.implicit!==null\?state.implicit:state.tag,cls=state.implicit===null\?\"universal\":\"context\";tag===null\?state.use===null&&reporter.error(\"Tag could be omitted only for .use()\"):state.use===null&&(result=this._encodeComposite(tag,primitive,cls,content))}return state.explicit!==null&&(result=this._encodeComposite(state.explicit,!1,\"context\",result)),result},Node.prototype._encodeChoice=function(data,reporter){let state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+\" not found in \"+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function(tag,data){let state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if(tag===\"objid\"&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if(tag===\"objid\")return this._encodeObjid(data,null,null);if(tag===\"gentime\"||tag===\"utctime\")return this._encodeTime(data,tag);if(tag===\"null_\")return this._encodeNull();if(tag===\"int\"||tag===\"enum\")return this._encodeInt(data,state.args&&state.reverseArgs[0]);if(tag===\"bool\")return this._encodeBool(data);if(tag===\"objDesc\")return this._encodeStr(data,tag);throw new Error(\"Unsupported tag: \"+tag)},Node.prototype._isNumstr=function(str){return/^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function(str){return/^[A-Za-z0-9 '()+,-./:=\?]*$/.test(str)}}}),require_der=__commonJS({\"node_modules/asn1.js/lib/asn1/constants/der.js\"(exports){function reverse(map){let res={};return Object.keys(map).forEach(function(key){(key|0)==key&&(key=key|0);let value=map[key];res[value]=key}),res}exports.tagClass={0:\"universal\",1:\"application\",2:\"context\",3:\"private\"},exports.tagClassByName=reverse(exports.tagClass),exports.tag={0:\"end\",1:\"bool\",2:\"int\",3:\"bitstr\",4:\"octstr\",5:\"null_\",6:\"objid\",7:\"objDesc\",8:\"external\",9:\"real\",10:\"enum\",11:\"embed\",12:\"utf8str\",13:\"relativeOid\",16:\"seq\",17:\"set\",18:\"numstr\",19:\"printstr\",20:\"t61str\",21:\"videostr\",22:\"ia5str\",23:\"utctime\",24:\"gentime\",25:\"graphstr\",26:\"iso646str\",27:\"genstr\",28:\"unistr\",29:\"charstr\",30:\"bmpstr\"},exports.tagByName=reverse(exports.tag)}}),require_der2=__commonJS({\"node_modules/asn1.js/lib/asn1/encoders/der.js\"(exports,module){var inherits=require_inherits_browser(),Buffer2=require_safer().Buffer,Node=require_node(),der=require_der();function DEREncoder(entity){this.enc=\"der\",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}DEREncoder.prototype={},module.exports=DEREncoder,DEREncoder.prototype.encode=function(data,reporter){return this.tree._encode(data,reporter).join()};function DERNode(parent){Node.call(this,\"der\",parent)}inherits(DERNode,Node),DERNode.prototype._encodeComposite=function(tag,primitive,cls,content){let encodedTag=encodeTag(tag,primitive,cls,this.reporter);if(content.length<128){let header2=Buffer2.alloc(2);return header2[0]=encodedTag,header2[1]=content.length,this._createEncoderBuffer([header2,content])}let lenOctets=1;for(let i=content.length;i>=256;i>>=8)lenOctets++;let header=Buffer2.alloc(2+lenOctets);header[0]=encodedTag,header[1]=128|lenOctets;for(let i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=j&255;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function(str,tag){if(tag===\"bitstr\")return this._createEncoderBuffer([str.unused|0,str.data]);if(tag===\"bmpstr\"){let buf=Buffer2.alloc(str.length*2);for(let i=0;i=40)return this.reporter.error(\"Second objid identifier OOB\");id.splice(0,2,id[0]*40+id[1])}let size=0;for(let i=0;i=128;ident>>=7)size++}let objid=Buffer2.alloc(size),offset=objid.length-1;for(let i=id.length-1;i>=0;i--){let ident=id[i];for(objid[offset--]=ident&127;(ident>>=7)>0;)objid[offset--]=128|ident&127}return this._createEncoderBuffer(objid)};function two(num){return num<10\?\"0\"+num:num}DERNode.prototype._encodeTime=function(time,tag){let str,date=new Date(time);return tag===\"gentime\"\?str=[two(date.getUTCFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),\"Z\"].join(\"\"):tag===\"utctime\"\?str=[two(date.getUTCFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),\"Z\"].join(\"\"):this.reporter.error(\"Encoding \"+tag+\" time is not supported yet\"),this._encodeStr(str,\"octstr\")},DERNode.prototype._encodeNull=function(){return this._createEncoderBuffer(\"\")},DERNode.prototype._encodeInt=function(num,values){if(typeof num==\"string\"){if(!values)return this.reporter.error(\"String int or enum given, but no values map\");if(!values.hasOwnProperty(num))return this.reporter.error(\"Values map doesn't contain: \"+JSON.stringify(num));num=values[num]}if(typeof num!=\"number\"&&!Buffer2.isBuffer(num)){let numArray=num.toArray();!num.sign&&numArray[0]&128&&numArray.unshift(0),num=Buffer2.from(numArray)}if(Buffer2.isBuffer(num)){let size2=num.length;num.length===0&&size2++;let out2=Buffer2.alloc(size2);return num.copy(out2),num.length===0&&(out2[0]=0),this._createEncoderBuffer(out2)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);let size=1;for(let i=num;i>=256;i>>=8)size++;let out=new Array(size);for(let i=out.length-1;i>=0;i--)out[i]=num&255,num>>=8;return out[0]&128&&out.unshift(0),this._createEncoderBuffer(Buffer2.from(out))},DERNode.prototype._encodeBool=function(value){return this._createEncoderBuffer(value\?255:0)},DERNode.prototype._use=function(entity,obj){return typeof entity==\"function\"&&(entity=entity(obj)),entity._getEncoder(\"der\").tree},DERNode.prototype._skipDefault=function(dataBuffer,reporter,parent){let state=this._baseState,i;if(state.default===null)return!1;let data=dataBuffer.join();if(state.defaultBuffer===void 0&&(state.defaultBuffer=this._encodeValue(state.default,reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i=31\?reporter.error(\"Multi-octet tag encoding unsupported\"):(primitive||(res|=32),res|=der.tagClassByName[cls||\"universal\"]<<6,res)}}}),require_pem=__commonJS({\"node_modules/asn1.js/lib/asn1/encoders/pem.js\"(exports,module){var inherits=require_inherits_browser(),DEREncoder=require_der2();function PEMEncoder(entity){DEREncoder.call(this,entity),this.enc=\"pem\"}inherits(PEMEncoder,DEREncoder),module.exports=PEMEncoder,PEMEncoder.prototype.encode=function(data,options){let p=DEREncoder.prototype.encode.call(this,data).toString(\"base64\"),out=[\"-----BEGIN \"+options.label+\"-----\"];for(let i=0;i>6],primitive=(tag&32)===0;if((tag&31)===31){let oct=tag;for(tag=0;(oct&128)===128;){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=oct&127}}else tag&=31;let tagStr=der.tag[tag];return{cls,primitive,tag,tagStr}}function derDecodeLen(buf,primitive,fail){let len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&len===128)return null;if((len&128)===0)return len;let num=len&127;if(num>4)return buf.error(\"length octect is too long\");len=0;for(let i=0;i0&&bits.ishrn(shift),bits}function bits2octets(bits,q){bits=bits2int(bits,q),bits=bits.mod(q);var out=Buffer2.from(bits.toArray());if(out.length=q)throw new Error(\"invalid sig\")}module.exports=verify}}),require_browser8=__commonJS({\"node_modules/browserify-sign/browser/index.js\"(exports,module){var Buffer2=require_safe_buffer().Buffer,createHash=require_browser2(),inherits=require_inherits_browser(),sign=require_sign(),verify=require_verify(),algorithms=require_algorithms();Object.keys(algorithms).forEach(function(key){algorithms[key].id=Buffer2.from(algorithms[key].id,\"hex\"),algorithms[key.toLowerCase()]=algorithms[key]});function Sign(algorithm){StreamModule.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error(\"Unknown message digest\");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}inherits(Sign,StreamModule.Writable),Sign.prototype._write=function(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function(data,enc){return typeof data==\"string\"&&(data=Buffer2.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc\?sig.toString(enc):sig};function Verify(algorithm){StreamModule.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error(\"Unknown message digest\");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}inherits(Verify,StreamModule.Writable),Verify.prototype._write=function(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function(data,enc){return typeof data==\"string\"&&(data=Buffer2.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function(key,sig,enc){typeof sig==\"string\"&&(sig=Buffer2.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)};function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}module.exports={Sign:createSign,Verify:createVerify,createSign,createVerify}}}),require_bn6=require_bn,require_browser9=__commonJS({\"node_modules/create-ecdh/browser.js\"(exports,module){var elliptic=require_elliptic(),BN=require_bn6();module.exports=function(curve){return new ECDH(curve)};var aliases={secp256k1:{name:\"secp256k1\",byteLength:32},secp224r1:{name:\"p224\",byteLength:28},prime256v1:{name:\"p256\",byteLength:32},prime192v1:{name:\"p192\",byteLength:24},ed25519:{name:\"ed25519\",byteLength:32},secp384r1:{name:\"p384\",byteLength:48},secp521r1:{name:\"p521\",byteLength:66}};aliases.p224=aliases.secp224r1,aliases.p256=aliases.secp256r1=aliases.prime256v1,aliases.p192=aliases.secp192r1=aliases.prime192v1,aliases.p384=aliases.secp384r1,aliases.p521=aliases.secp521r1;function ECDH(curve){this.curveType=aliases[curve],this.curveType||(this.curveType={name:curve}),this.curve=new elliptic.ec(this.curveType.name),this.keys=void 0}ECDH.prototype={},ECDH.prototype.generateKeys=function(enc,format){return this.keys=this.curve.genKeyPair(),this.getPublicKey(enc,format)},ECDH.prototype.computeSecret=function(other,inenc,enc){inenc=inenc||\"utf8\",Buffer.isBuffer(other)||(other=new Buffer(other,inenc));var otherPub=this.curve.keyFromPublic(other).getPublic(),out=otherPub.mul(this.keys.getPrivate()).getX();return formatReturnValue(out,enc,this.curveType.byteLength)},ECDH.prototype.getPublicKey=function(enc,format){var key=this.keys.getPublic(format===\"compressed\",!0);return format===\"hybrid\"&&(key[key.length-1]%2\?key[0]=7:key[0]=6),formatReturnValue(key,enc)},ECDH.prototype.getPrivateKey=function(enc){return formatReturnValue(this.keys.getPrivate(),enc)},ECDH.prototype.setPublicKey=function(pub,enc){return enc=enc||\"utf8\",Buffer.isBuffer(pub)||(pub=new Buffer(pub,enc)),this.keys._importPublic(pub),this},ECDH.prototype.setPrivateKey=function(priv,enc){enc=enc||\"utf8\",Buffer.isBuffer(priv)||(priv=new Buffer(priv,enc));var _priv=new BN(priv);return _priv=_priv.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(_priv),this};function formatReturnValue(bn,enc,len){Array.isArray(bn)||(bn=bn.toArray());var buf=new Buffer(bn);if(len&&buf.length=0)throw new Error(\"data too long for modulus\")}else throw new Error(\"unknown padding\");return reverse\?crt(paddedMsg,key):withPublic(paddedMsg,key)};function oaep(key,msg){var k=key.modulus.byteLength(),mLen=msg.length,iHash=createHash(\"sha1\").update(Buffer2.alloc(0)).digest(),hLen=iHash.length,hLen2=2*hLen;if(mLen>k-hLen2-2)throw new Error(\"message too long\");var ps=Buffer2.alloc(k-mLen-hLen2-2),dblen=k-hLen-1,seed=randomBytes(hLen),maskedDb=xor(Buffer2.concat([iHash,ps,Buffer2.alloc(1,1),msg],dblen),mgf(seed,dblen)),maskedSeed=xor(seed,mgf(maskedDb,hLen));return new BN(Buffer2.concat([Buffer2.alloc(1),maskedSeed,maskedDb],k))}function pkcs1(key,msg,reverse){var mLen=msg.length,k=key.modulus.byteLength();if(mLen>k-11)throw new Error(\"message too long\");var ps;return reverse\?ps=Buffer2.alloc(k-mLen-3,255):ps=nonZero(k-mLen-3),new BN(Buffer2.concat([Buffer2.from([0,reverse\?1:2]),ps,Buffer2.alloc(1),msg],k))}function nonZero(len){for(var out=Buffer2.allocUnsafe(len),i=0,cache=randomBytes(len*2),cur=0,num;ik||new BN(enc).cmp(key.modulus)>=0)throw new Error(\"decryption error\");var msg;reverse\?msg=withPublic(new BN(enc),key):msg=crt(enc,key);var zBuffer=Buffer2.alloc(k-msg.length);if(msg=Buffer2.concat([zBuffer,msg],k),padding===4)return oaep(key,msg);if(padding===1)return pkcs1(key,msg,reverse);if(padding===3)return msg;throw new Error(\"unknown padding\")};function oaep(key,msg){var k=key.modulus.byteLength(),iHash=createHash(\"sha1\").update(Buffer2.alloc(0)).digest(),hLen=iHash.length;if(msg[0]!==0)throw new Error(\"decryption error\");var maskedSeed=msg.slice(1,hLen+1),maskedDb=msg.slice(hLen+1),seed=xor(maskedSeed,mgf(maskedDb,hLen)),db=xor(maskedDb,mgf(seed,k-hLen-1));if(compare(iHash,db.slice(0,hLen)))throw new Error(\"decryption error\");for(var i=hLen;db[i]===0;)i++;if(db[i++]!==1)throw new Error(\"decryption error\");return db.slice(i)}function pkcs1(key,msg,reverse){for(var p1=msg.slice(0,2),i=2,status=0;msg[i++]!==0;)if(i>=msg.length){status++;break}var ps=msg.slice(2,i-1);if((p1.toString(\"hex\")!==\"0002\"&&!reverse||p1.toString(\"hex\")!==\"0001\"&&reverse)&&status++,ps.length<8&&status++,status)throw new Error(\"decryption error\");return msg.slice(i)}function compare(a,b){a=Buffer2.from(a),b=Buffer2.from(b);var dif=0,len=a.length;a.length!==b.length&&(dif++,len=Math.min(a.length,b.length));for(var i=-1;++ikMaxUint32||offset<0)@throwTypeError(\"offset must be a uint32\");if(offset>kBufferMaxLength||offset>length)@throwRangeError(\"offset out of range\")}function assertSize(size,offset,length){if(typeof size!=\"number\"||size!==size)@throwTypeError(\"size must be a number\");if(size>kMaxUint32||size<0)@throwTypeError(\"size must be a uint32\");if(size+offset>length||size>kBufferMaxLength)@throwRangeError(\"buffer too small\")}exports.randomFill=randomFill,exports.randomFillSync=randomFillSync;function randomFill(buf,offset,size,cb){if(!Buffer2.isBuffer(buf)&&!(buf instanceof global.Uint8Array))@throwTypeError('\"buf\" argument must be a Buffer or Uint8Array');if(typeof offset==\"function\")cb=offset,offset=0,size=buf.length;else if(typeof size==\"function\")cb=size,size=buf.length-offset;else if(typeof cb!=\"function\")@throwTypeError('\"cb\" argument must be a function');return assertOffset(offset,buf.length),assertSize(size,offset,buf.length),actualFill(buf,offset,size,cb)}function actualFill(buf,offset,size,cb){if(cb){randombytes(size,function(err,bytes2){if(err)return cb(err);bytes2.copy(buf,offset),cb(null,buf)});return}var bytes=randombytes(size);return bytes.copy(buf,offset),buf}function randomFillSync(buf,offset,size){if(typeof offset>\"u\"&&(offset=0),!Buffer2.isBuffer(buf)&&!(buf instanceof global.Uint8Array))@throwTypeError('\"buf\" argument must be a Buffer or Uint8Array');return assertOffset(offset,buf.length),size===void 0&&(size=buf.length-offset),assertSize(size,offset,buf.length),actualFill(buf,offset,size)}}}),require_crypto_browserify2=__commonJS({\"node_modules/crypto-browserify/index.js\"(exports){exports.randomBytes=exports.rng=exports.pseudoRandomBytes=exports.prng=require_browser(),exports.createHash=require_browser2(),exports.Hash=exports.createHash.Hash,exports.createHmac=exports.Hmac=require_browser3();var algos=require_algos(),algoKeys=Object.keys(algos),hashes=[\"sha1\",\"sha224\",\"sha256\",\"sha384\",\"sha512\",\"md5\",\"rmd160\"].concat(algoKeys);exports.getHashes=function(){return hashes};var p=require_browser4();exports.pbkdf2=p.pbkdf2,exports.pbkdf2Sync=p.pbkdf2Sync;var aes=require_browser6();exports.Cipher=aes.Cipher,exports.createCipher=aes.createCipher,exports.Cipheriv=aes.Cipheriv,exports.createCipheriv=aes.createCipheriv,exports.Decipher=aes.Decipher,exports.createDecipher=aes.createDecipher,exports.Decipheriv=aes.Decipheriv,exports.createDecipheriv=aes.createDecipheriv,exports.getCiphers=aes.getCiphers,exports.listCiphers=aes.listCiphers;var dh=require_browser7();exports.DiffieHellmanGroup=dh.DiffieHellmanGroup,exports.createDiffieHellmanGroup=dh.createDiffieHellmanGroup,exports.getDiffieHellman=dh.getDiffieHellman,exports.createDiffieHellman=dh.createDiffieHellman,exports.DiffieHellman=dh.DiffieHellman;var sign=require_browser8();exports.createSign=sign.createSign,exports.Sign=sign.Sign,exports.createVerify=sign.createVerify,exports.Verify=sign.Verify,exports.createECDH=require_browser9();var publicEncrypt=require_browser10();exports.publicEncrypt=publicEncrypt.publicEncrypt,exports.privateEncrypt=publicEncrypt.privateEncrypt,exports.publicDecrypt=publicEncrypt.publicDecrypt,exports.privateDecrypt=publicEncrypt.privateDecrypt,exports.getRandomValues=(values)=>crypto.getRandomValues(values);var rf=require_browser11();exports.randomFill=rf.randomFill,exports.randomFillSync=rf.randomFillSync,exports.createCredentials=function(){throw new Error([\"sorry, createCredentials is not implemented yet\",\"we accept pull requests\",\"https://github.com/crypto-browserify/crypto-browserify\"].join(`\n`))},exports.constants=@processBindingConstants.crypto}}),crypto_exports=require_crypto_browserify2(),DEFAULT_ENCODING=\"buffer\",getRandomValues=(array)=>crypto.getRandomValues(array),randomUUID=()=>crypto.randomUUID(),randomInt=(...args)=>crypto.randomInt(...args),timingSafeEqual=\"timingSafeEqual\"in crypto\?(a,b)=>{let{byteLength:byteLengthA}=a,{byteLength:byteLengthB}=b;if(typeof byteLengthA!=\"number\"||typeof byteLengthB!=\"number\")@throwTypeError(\"Input must be an array buffer view\");if(byteLengthA!==byteLengthB)@throwRangeError(\"Input buffers must have the same length\");return crypto.timingSafeEqual(a,b)}:void 0,scryptSync=\"scryptSync\"in crypto\?(password,salt,keylen,options)=>{let res=crypto.scryptSync(password,salt,keylen,options);return DEFAULT_ENCODING!==\"buffer\"\?new Buffer(res).toString(DEFAULT_ENCODING):new Buffer(res)}:void 0,scrypt=\"scryptSync\"in crypto\?function(password,salt,keylen,options,callback){if(typeof options==\"function\"&&(callback=options,options=void 0),typeof callback!=\"function\"){var err=@makeTypeError(\"callback must be a function\");throw err.code=\"ERR_INVALID_CALLBACK\",err}try{let result=crypto.scryptSync(password,salt,keylen,options);process.nextTick(callback,null,DEFAULT_ENCODING!==\"buffer\"\?new Buffer(result).toString(DEFAULT_ENCODING):new Buffer(result))}catch(err2){throw err2}}:void 0;timingSafeEqual&&(Object.defineProperty(timingSafeEqual,\"name\",{value:\"::bunternal::\"}),Object.defineProperty(scrypt,\"name\",{value:\"::bunternal::\"}),Object.defineProperty(scryptSync,\"name\",{value:\"::bunternal::\"}));const harcoded_curves=[\"p192\",\"p224\",\"p256\",\"p384\",\"p521\",\"curve25519\",\"ed25519\",\"secp256k1\",\"secp224r1\",\"prime256v1\",\"prime192v1\",\"ed25519\",\"secp384r1\",\"secp521r1\"];function getCurves(){return harcoded_curves}var webcrypto=crypto;__export(crypto_exports,{DEFAULT_ENCODING:()=>DEFAULT_ENCODING,getRandomValues:()=>getRandomValues,randomUUID:()=>randomUUID,randomInt:()=>randomInt,getCurves:()=>getCurves,scrypt:()=>scrypt,scryptSync:()=>scryptSync,timingSafeEqual:()=>timingSafeEqual,webcrypto:()=>webcrypto,subtle:()=>webcrypto.subtle}),$=crypto_exports;/*! safe-buffer. MIT License. Feross Aboukhadijeh */return $})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDgramCode = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function createSocket(){throwNotImplemented(\"node:dgram createSocket\",1630)}function Socket(){throwNotImplemented(\"node:dgram Socket\",1630)}function _createSocketHandle(){throwNotImplemented(\"node:dgram _createSocketHandle\",1630)}return $={createSocket,Socket,_createSocketHandle},hideFromStack(createSocket,Socket,_createSocketHandle),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDiagnosticsChannelCode = "(function (){\"use strict\";const SafeMap=Map,SafeFinalizationRegistry=FinalizationRegistry,ArrayPrototypeAt=(array,index)=>array[index],ArrayPrototypeIndexOf=(array,value)=>array.indexOf(value),ArrayPrototypePush=(array,value)=>array.push(value),ArrayPrototypeSplice=(array,start,deleteCount)=>array.splice(start,deleteCount),ObjectGetPrototypeOf=Object.getPrototypeOf,ObjectSetPrototypeOf=Object.setPrototypeOf,SymbolHasInstance=Symbol.hasInstance,ReflectApply=Reflect.apply,PromiseResolve=Promise.resolve,PromiseReject=Promise.reject,PromisePrototypeThen=(promise,onFulfilled,onRejected)=>promise.then(onFulfilled,onRejected);class WeakReference extends WeakRef{constructor(){super(...arguments)}#refs=0;get(){return this.deref()}incRef(){return++this.#refs}decRef(){return--this.#refs}}class WeakRefMap extends SafeMap{constructor(){super(...arguments)}#finalizers=new SafeFinalizationRegistry((key)=>{this.delete(key)});set(key,value){return this.#finalizers.register(value,key),super.set(key,new WeakReference(value))}get(key){return super.get(key)\?.get()}incRef(key){return super.get(key)\?.incRef()}decRef(key){return super.get(key)\?.decRef()}}function markActive(channel2){ObjectSetPrototypeOf(channel2,ActiveChannel.prototype),channel2._subscribers=[],channel2._stores=new SafeMap}function maybeMarkInactive(channel2){if(!channel2._subscribers.length&&!channel2._stores.size)ObjectSetPrototypeOf(channel2,Channel.prototype),channel2._subscribers=void 0,channel2._stores=void 0}function defaultTransform(data){return data}function wrapStoreRun(store,data,next,transform=defaultTransform){return()=>{let context;try{context=transform(data)}catch(err){return process.nextTick(()=>reportError(err)),next()}return store.run(context,next)}}class ActiveChannel{subscribe(subscription){validateFunction(subscription,\"subscription\"),ArrayPrototypePush(this._subscribers,subscription),channels.incRef(this.name)}unsubscribe(subscription){const index=ArrayPrototypeIndexOf(this._subscribers,subscription);if(index===-1)return!1;return ArrayPrototypeSplice(this._subscribers,index,1),channels.decRef(this.name),maybeMarkInactive(this),!0}bindStore(store,transform){if(!this._stores.has(store))channels.incRef(this.name);this._stores.set(store,transform)}unbindStore(store){if(!this._stores.has(store))return!1;return this._stores.delete(store),channels.decRef(this.name),maybeMarkInactive(this),!0}get hasSubscribers(){return!0}publish(data){for(let i=0;i<(this._subscribers\?.length||0);i++)try{const onMessage=this._subscribers[i];onMessage(data,this.name)}catch(err){process.nextTick(()=>reportError(err))}}runStores(data,fn,thisArg,...args){let run=()=>{return this.publish(data),ReflectApply(fn,thisArg,args)};for(let entry of this._stores.entries()){const store=entry[0],transform=entry[1];run=wrapStoreRun(store,data,run,transform)}return run()}}class Channel{constructor(name){this._subscribers=void 0,this._stores=void 0,this.name=name,channels.set(name,this)}static[SymbolHasInstance](instance){const prototype=ObjectGetPrototypeOf(instance);return prototype===Channel.prototype||prototype===ActiveChannel.prototype}subscribe(subscription){markActive(this),this.subscribe(subscription)}unsubscribe(){return!1}bindStore(store,transform){markActive(this),this.bindStore(store,transform)}unbindStore(){return!1}get hasSubscribers(){return!1}publish(){}runStores(data,fn,thisArg,...args){return ReflectApply(fn,thisArg,args)}}const channels=new WeakRefMap;function channel(name){const channel2=channels.get(name);if(channel2)return channel2;if(typeof name!==\"string\"&&typeof name!==\"symbol\")throw new ERR_INVALID_ARG_TYPE(\"channel\",[\"string\",\"symbol\"],name);return new Channel(name)}function subscribe(name,subscription){return channel(name).subscribe(subscription)}function unsubscribe(name,subscription){return channel(name).unsubscribe(subscription)}function hasSubscribers(name){const channel2=channels.get(name);if(!channel2)return!1;return channel2.hasSubscribers}const traceEvents=[\"start\",\"end\",\"asyncStart\",\"asyncEnd\",\"error\"];function assertChannel(value,name){if(!(value instanceof Channel))throw new ERR_INVALID_ARG_TYPE(name,[\"Channel\"],value)}class TracingChannel{constructor(nameOrChannels){if(typeof nameOrChannels===\"string\")this.start=channel(`tracing:${nameOrChannels}:start`),this.end=channel(`tracing:${nameOrChannels}:end`),this.asyncStart=channel(`tracing:${nameOrChannels}:asyncStart`),this.asyncEnd=channel(`tracing:${nameOrChannels}:asyncEnd`),this.error=channel(`tracing:${nameOrChannels}:error`);else if(typeof nameOrChannels===\"object\"){const{start,end,asyncStart,asyncEnd,error}=nameOrChannels;assertChannel(start,\"nameOrChannels.start\"),assertChannel(end,\"nameOrChannels.end\"),assertChannel(asyncStart,\"nameOrChannels.asyncStart\"),assertChannel(asyncEnd,\"nameOrChannels.asyncEnd\"),assertChannel(error,\"nameOrChannels.error\"),this.start=start,this.end=end,this.asyncStart=asyncStart,this.asyncEnd=asyncEnd,this.error=error}else throw new ERR_INVALID_ARG_TYPE(\"nameOrChannels\",[\"string\",\"object\",\"Channel\"],nameOrChannels)}subscribe(handlers){for(let name of traceEvents){if(!handlers[name])continue;this[name]\?.subscribe(handlers[name])}}unsubscribe(handlers){let done=!0;for(let name of traceEvents){if(!handlers[name])continue;if(!this[name]\?.unsubscribe(handlers[name]))done=!1}return done}traceSync(fn,context={},thisArg,...args){const{start,end,error}=this;return start.runStores(context,()=>{try{const result=ReflectApply(fn,thisArg,args);return context.result=result,result}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}tracePromise(fn,context={},thisArg,...args){const{start,end,asyncStart,asyncEnd,error}=this;function reject(err){return context.error=err,error.publish(context),asyncStart.publish(context),asyncEnd.publish(context),PromiseReject(err)}function resolve(result){return context.result=result,asyncStart.publish(context),asyncEnd.publish(context),result}return start.runStores(context,()=>{try{let promise=ReflectApply(fn,thisArg,args);if(!(promise instanceof Promise))promise=PromiseResolve(promise);return PromisePrototypeThen(promise,resolve,reject)}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}traceCallback(fn,position=-1,context={},thisArg,...args){const{start,end,asyncStart,asyncEnd,error}=this;function wrappedCallback(err,res){if(err)context.error=err,error.publish(context);else context.result=res;asyncStart.runStores(context,()=>{try{if(callback)return ReflectApply(callback,this,arguments)}finally{asyncEnd.publish(context)}})}const callback=ArrayPrototypeAt(args,position);if(typeof callback!==\"function\")throw new ERR_INVALID_ARG_TYPE(\"callback\",[\"function\"],callback);return ArrayPrototypeSplice(args,position,1,wrappedCallback),start.runStores(context,()=>{try{return ReflectApply(fn,thisArg,args)}catch(err){throw context.error=err,error.publish(context),err}finally{end.publish(context)}})}}function tracingChannel(nameOrChannels){return new TracingChannel(nameOrChannels)}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 validateFunction(callable,field){if(typeof callable!==\"function\")throw new ERR_INVALID_ARG_TYPE(field,\"Function\",callable);return callable}return{channel,hasSubscribers,subscribe,tracingChannel,unsubscribe,Channel}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDNSCode = "(function (){\"use strict\";const dns=Bun.dns;function getServers(){return dns.getServers()}function lookup(domain,options,callback){if(typeof options==\"function\")callback=options;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");if(typeof options==\"number\")options={family:options};dns.lookup(domain,options).then((res)=>{if(res.sort((a,b)=>a.family-b.family),options\?.all)callback(null,res.map(mapLookupAll));else{const[{address,family}]=res;callback(null,address,family)}},(error)=>{callback(error)})}function resolveSrv(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSrv(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveTxt(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveTxt(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveSoa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSoa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveNaptr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNaptr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveMx(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveMx(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveCaa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCaa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveNs(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNs(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolvePtr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolvePtr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function resolveCname(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCname(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}function lookupService(address,port,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");callback(null,address,port)}var InternalResolver=class Resolver2{constructor(options){}cancel(){}getServers(){return[]}resolve(hostname,rrtype,callback){if(typeof rrtype==\"function\")callback=rrtype,rrtype=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolve(hostname).then((results)=>{switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":callback(null,hostname,results.map(mapResolveX));break;default:callback(null,results);break}},(error)=>{callback(error)})}resolve4(hostname,options,callback){if(typeof options==\"function\")callback=options,options=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.lookup(hostname,{family:4}).then((addresses)=>{callback(null,options\?.ttl\?addresses:addresses.map(mapResolveX))},(error)=>{callback(error)})}resolve6(hostname,options,callback){if(typeof options==\"function\")callback=options,options=null;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.lookup(hostname,{family:6}).then((addresses)=>{callback(null,options\?.ttl\?addresses:addresses.map(({address})=>address))},(error)=>{callback(error)})}resolveAny(hostname,callback){callback(null,[])}resolveCname(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCname(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveMx(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveMx(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveNaptr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNaptr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveNs(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveNs(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolvePtr(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolvePtr(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveSrv(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSrv(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveCaa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveCaa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveTxt(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveTxt(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}resolveSoa(hostname,callback){if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolveSoa(hostname,callback).then((results)=>{callback(null,results)},(error)=>{callback(error)})}reverse(ip,callback){callback(null,[])}setServers(servers){}};function resolve(hostname,rrtype,callback){if(typeof rrtype==\"function\")callback=rrtype;if(typeof callback!=\"function\")@throwTypeError(\"callback must be a function\");dns.resolve(hostname).then((results)=>{switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":callback(null,hostname,results.map(({address})=>address));break;default:callback(null,results);break}},(error)=>{callback(error)})}function Resolver(options){return new InternalResolver(options)}Resolver.prototype={},Object.setPrototypeOf(Resolver.prototype,InternalResolver.prototype),Object.setPrototypeOf(Resolver,InternalResolver);var{resolve,resolve4,resolve6,resolveAny,resolveCname,resolveCaa,resolveMx,resolveNaptr,resolveNs,resolvePtr,resolveSoa,resolveSrv,reverse,resolveTxt}=InternalResolver.prototype;function setDefaultResultOrder(){}function setServers(){}const promisifyLookup=(res)=>{res.sort((a,b)=>a.family-b.family);const[{address,family}]=res;return{address,family}},mapLookupAll=(res)=>{const{address,family}=res;return{address,family}},promisifyLookupAll=(res)=>{return res.sort((a,b)=>a.family-b.family),res.map(mapLookupAll)},mapResolveX=(a)=>a.address,promisifyResolveX=(res)=>{return res\?.map(mapResolveX)},promises={lookup(domain,options){if(options\?.all)return dns.lookup(domain,options).then(promisifyLookupAll);return dns.lookup(domain,options).then(promisifyLookup)},lookupService(address,port){return Promise.resolve([])},resolve(hostname,rrtype){if(typeof rrtype!==\"string\")rrtype=null;switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":return dns.resolve(hostname,rrtype).then(promisifyLookup);default:return dns.resolve(hostname,rrtype)}},resolve4(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:4});return dns.lookup(hostname,{family:4}).then(promisifyResolveX)},resolve6(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:6});return dns.lookup(hostname,{family:6}).then(promisifyResolveX)},resolveSrv(hostname){return dns.resolveSrv(hostname)},resolveTxt(hostname){return dns.resolveTxt(hostname)},resolveSoa(hostname){return dns.resolveSoa(hostname)},resolveNaptr(hostname){return dns.resolveNaptr(hostname)},resolveMx(hostname){return dns.resolveMx(hostname)},resolveCaa(hostname){return dns.resolveCaa(hostname)},resolveNs(hostname){return dns.resolveNs(hostname)},resolvePtr(hostname){return dns.resolvePtr(hostname)},resolveCname(hostname){return dns.resolveCname(hostname)},Resolver:class Resolver2{constructor(options){}cancel(){}getServers(){return[]}resolve(hostname,rrtype){if(typeof rrtype!==\"string\")rrtype=null;switch(rrtype\?.toLowerCase()){case\"a\":case\"aaaa\":return dns.resolve(hostname,rrtype).then(promisifyLookup);default:return dns.resolve(hostname,rrtype)}}resolve4(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:4});return dns.lookup(hostname,{family:4}).then(promisifyResolveX)}resolve6(hostname,options){if(options\?.ttl)return dns.lookup(hostname,{family:6});return dns.lookup(hostname,{family:6}).then(promisifyResolveX)}resolveAny(hostname){return Promise.resolve([])}resolveCname(hostname){return dns.resolveCname(hostname)}resolveMx(hostname){return dns.resolveMx(hostname)}resolveNaptr(hostname){return dns.resolveNaptr(hostname)}resolveNs(hostname){return dns.resolveNs(hostname)}resolvePtr(hostname){return dns.resolvePtr(hostname)}resolveSoa(hostname){return dns.resolveSoa(hostname)}resolveSrv(hostname){return dns.resolveSrv(hostname)}resolveCaa(hostname){return dns.resolveCaa(hostname)}resolveTxt(hostname){return dns.resolveTxt(hostname)}reverse(ip){return Promise.resolve([])}setServers(servers){}}};for(let key of[\"resolveAny\",\"reverse\"])promises[key]=()=>Promise.resolve(void 0);return{ADDRCONFIG:0,ALL:1,V4MAPPED:2,NODATA:\"DNS_ENODATA\",FORMERR:\"DNS_EFORMERR\",SERVFAIL:\"DNS_ESERVFAIL\",NOTFOUND:\"DNS_ENOTFOUND\",NOTIMP:\"DNS_ENOTIMP\",REFUSED:\"DNS_EREFUSED\",BADQUERY:\"DNS_EBADQUERY\",BADNAME:\"DNS_EBADNAME\",BADFAMILY:\"DNS_EBADFAMILY\",BADRESP:\"DNS_EBADRESP\",CONNREFUSED:\"DNS_ECONNREFUSED\",TIMEOUT:\"DNS_ETIMEOUT\",EOF:\"DNS_EEOF\",FILE:\"DNS_EFILE\",NOMEM:\"DNS_ENOMEM\",DESTRUCTION:\"DNS_EDESTRUCTION\",BADSTR:\"DNS_EBADSTR\",BADFLAGS:\"DNS_EBADFLAGS\",NONAME:\"DNS_ENONAME\",BADHINTS:\"DNS_EBADHINTS\",NOTINITIALIZED:\"DNS_ENOTINITIALIZED\",LOADIPHLPAPI:\"DNS_ELOADIPHLPAPI\",ADDRGETNETWORKPARAMS:\"DNS_EADDRGETNETWORKPARAMS\",CANCELLED:\"DNS_ECANCELLED\",lookup,lookupService,Resolver,setServers,setDefaultResultOrder,resolve,reverse,resolve4,resolve6,resolveAny,resolveCname,resolveCaa,resolveMx,resolveNs,resolvePtr,resolveSoa,resolveSrv,resolveTxt,resolveNaptr,promises,getServers}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDNSPromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,12)||@createInternalModuleById(12)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeDomainCode = "(function (){\"use strict\";var EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),domain={};return domain.createDomain=domain.create=function(){var d=new EventEmitter;function emitError(e){d.emit(\"error\",e)}return d.add=function(emitter){emitter.on(\"error\",emitError)},d.remove=function(emitter){emitter.removeListener(\"error\",emitError)},d.bind=function(fn){return function(){var args=Array.prototype.slice.call(arguments);try{fn.apply(null,args)}catch(err){emitError(err)}}},d.intercept=function(fn){return function(err){if(err)emitError(err);else{var args=Array.prototype.slice.call(arguments,1);try{fn.apply(null,args)}catch(err2){emitError(err2)}}}},d.run=function(fn){try{fn()}catch(err){emitError(err)}return this},d.dispose=function(){return this.removeAllListeners(),this},d.enter=d.exit=function(){return this},d},domain})\n"_s; +// + +// +static constexpr ASCIILiteral NodeEventsCode = "(function (){\"use strict\";const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),SymbolFor=Symbol.for,kCapture=Symbol(\"kCapture\"),kErrorMonitor=SymbolFor(\"events.errorMonitor\"),kMaxEventTargetListeners=Symbol(\"events.maxEventTargetListeners\"),kMaxEventTargetListenersWarned=Symbol(\"events.maxEventTargetListenersWarned\"),kWatermarkData=SymbolFor(\"nodejs.watermarkData\"),kRejection=SymbolFor(\"nodejs.rejection\"),captureRejectionSymbol=SymbolFor(\"nodejs.rejection\"),ArrayPrototypeSlice=Array.prototype.slice;var defaultMaxListeners=10;const EventEmitter=function EventEmitter(opts){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners\?\?=void 0,this[kCapture]=opts\?.captureRejections\?Boolean(opts\?.captureRejections):EventEmitterPrototype[kCapture])this.emit=emitWithRejectionCapture},EventEmitterPrototype=EventEmitter.prototype={};EventEmitterPrototype._events=void 0,EventEmitterPrototype._eventsCount=0,EventEmitterPrototype._maxListeners=void 0,EventEmitterPrototype.setMaxListeners=function setMaxListeners(n){return validateNumber(n,\"setMaxListeners\",0),this._maxListeners=n,this},EventEmitterPrototype.getMaxListeners=function getMaxListeners(){return this._maxListeners\?\?defaultMaxListeners};function emitError(emitter,args){var{_events:events}=emitter;if(args[0]\?\?=new Error(\"Unhandled error.\"),!events)throw args[0];var errorMonitor=events[kErrorMonitor];if(errorMonitor)for(var handler of ArrayPrototypeSlice.call(errorMonitor))handler.apply(emitter,args);var handlers=events.error;if(!handlers)throw args[0];for(var handler of ArrayPrototypeSlice.call(handlers))handler.apply(emitter,args);return!0}function addCatch(emitter,promise,type,args){promise.then(void 0,function(err){process.nextTick(emitUnhandledRejectionOrErr,emitter,err,type,args)})}function emitUnhandledRejectionOrErr(emitter,err,type,args){if(typeof emitter[kRejection]===\"function\")emitter[kRejection](err,type,...args);else try{emitter[kCapture]=!1,emitter.emit(\"error\",err)}finally{emitter[kCapture]=!0}}const emitWithoutRejectionCapture=function emit(type,...args){if(type===\"error\")return emitError(this,args);var{_events:events}=this;if(events===void 0)return!1;var handlers=events[type];if(handlers===void 0)return!1;for(var handler of[...handlers])handler.apply(this,args);return!0},emitWithRejectionCapture=function emit(type,...args){if(type===\"error\")return emitError(this,args);var{_events:events}=this;if(events===void 0)return!1;var handlers=events[type];if(handlers===void 0)return!1;for(var handler of[...handlers]){var result=handler.apply(this,args);if(result!==void 0&&@isPromise(result))addCatch(this,result,type,args)}return!0};EventEmitterPrototype.emit=emitWithoutRejectionCapture,EventEmitterPrototype.addListener=function addListener(type,fn){checkListener(fn);var events=this._events;if(!events)events=this._events={__proto__:null},this._eventsCount=0;else if(events.newListener)this.emit(\"newListener\",type,fn.listener\?\?fn);var handlers=events[type];if(!handlers)events[type]=[fn],this._eventsCount++;else{handlers.push(fn);var m=this._maxListeners\?\?defaultMaxListeners;if(m>0&&handlers.length>m&&!handlers.warned)overflowWarning(this,type,handlers)}return this},EventEmitterPrototype.on=EventEmitterPrototype.addListener,EventEmitterPrototype.prependListener=function prependListener(type,fn){checkListener(fn);var events=this._events;if(!events)events=this._events={__proto__:null},this._eventsCount=0;else if(events.newListener)this.emit(\"newListener\",type,fn.listener\?\?fn);var handlers=events[type];if(!handlers)events[type]=[fn],this._eventsCount++;else{handlers.unshift(fn);var m=this._maxListeners\?\?defaultMaxListeners;if(m>0&&handlers.length>m&&!handlers.warned)overflowWarning(this,type,handlers)}return this};function overflowWarning(emitter,type,handlers){handlers.warned=!0;const warn=new Error(`Possible EventEmitter memory leak detected. ${handlers.length} ${String(type)} listeners `+`added to [${emitter.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);warn.name=\"MaxListenersExceededWarning\",warn.emitter=emitter,warn.type=type,warn.count=handlers.length,process.emitWarning(warn)}function onceWrapper(type,listener,...args){this.removeListener(type,listener),listener.apply(this,args)}EventEmitterPrototype.once=function once(type,fn){checkListener(fn);const bound=onceWrapper.bind(this,type,fn);return bound.listener=fn,this.addListener(type,bound),this},EventEmitterPrototype.prependOnceListener=function prependOnceListener(type,fn){checkListener(fn);const bound=onceWrapper.bind(this,type,fn);return bound.listener=fn,this.prependListener(type,bound),this},EventEmitterPrototype.removeListener=function removeListener(type,fn){checkListener(fn);var{_events:events}=this;if(!events)return this;var handlers=events[type];if(!handlers)return this;var length=handlers.length;let position=-1;for(let i=length-1;i>=0;i--)if(handlers[i]===fn||handlers[i].listener===fn){position=i;break}if(position<0)return this;if(position===0)handlers.shift();else handlers.splice(position,1);if(handlers.length===0)delete events[type],this._eventsCount--;return this},EventEmitterPrototype.off=EventEmitterPrototype.removeListener,EventEmitterPrototype.removeAllListeners=function removeAllListeners(type){var{_events:events}=this;if(type&&events){if(events[type])delete events[type],this._eventsCount--}else this._events={__proto__:null};return this},EventEmitterPrototype.listeners=function listeners(type){var{_events:events}=this;if(!events)return[];var handlers=events[type];if(!handlers)return[];return handlers.map((x)=>x.listener\?\?x)},EventEmitterPrototype.rawListeners=function rawListeners(type){var{_events}=this;if(!_events)return[];var handlers=_events[type];if(!handlers)return[];return handlers.slice()},EventEmitterPrototype.listenerCount=function listenerCount(type){var{_events:events}=this;if(!events)return 0;return events[type]\?.length\?\?0},EventEmitterPrototype.eventNames=function eventNames(){return this._eventsCount>0\?Reflect.ownKeys(this._events):[]},EventEmitterPrototype[kCapture]=!1;function once(emitter,type,options){var signal=options\?.signal;if(validateAbortSignal(signal,\"options.signal\"),signal\?.aborted)throw new AbortError(void 0,{cause:signal\?.reason});return new Promise((resolve,reject)=>{const errorListener=(err)=>{if(emitter.removeListener(type,resolver),signal!=null)eventTargetAgnosticRemoveListener(signal,\"abort\",abortListener);reject(err)},resolver=(...args)=>{if(typeof emitter.removeListener===\"function\")emitter.removeListener(\"error\",errorListener);if(signal!=null)eventTargetAgnosticRemoveListener(signal,\"abort\",abortListener);resolve(args)};if(eventTargetAgnosticAddListener(emitter,type,resolver,{once:!0}),type!==\"error\"&&typeof emitter.once===\"function\")emitter.once(\"error\",errorListener);function abortListener(){eventTargetAgnosticRemoveListener(emitter,type,resolver),eventTargetAgnosticRemoveListener(emitter,\"error\",errorListener),reject(new AbortError(void 0,{cause:signal\?.reason}))}if(signal!=null)eventTargetAgnosticAddListener(signal,\"abort\",abortListener,{once:!0})})}function on(emitter,type,options){var{signal,close,highWatermark=Number.MAX_SAFE_INTEGER,lowWatermark=1}=options||{};throwNotImplemented(\"events.on\",2679)}function getEventListeners(emitter,type){if(emitter instanceof EventTarget)throwNotImplemented(\"getEventListeners with an EventTarget\",2678);return emitter.listeners(type)}function setMaxListeners(n,...eventTargets){validateNumber(n,\"setMaxListeners\",0);var length;if(eventTargets&&(length=eventTargets.length))for(let i=0;imax||(min!=null||max!=null)&&Number.isNaN(value))throw new ERR_OUT_OF_RANGE(name,`${min!=null\?`>= ${min}`:\"\"}${min!=null&&max!=null\?\" && \":\"\"}${max!=null\?`<= ${max}`:\"\"}`,value)}function checkListener(listener){if(typeof listener!==\"function\")@throwTypeError(\"The listener must be a function\")}let AsyncResource=null;class EventEmitterAsyncResource extends EventEmitter{triggerAsyncId;asyncResource;constructor(options){if(!AsyncResource)AsyncResource=(@getInternalField(@internalModuleRegistry,5)||@createInternalModuleById(5)).AsyncResource;var{captureRejections=!1,triggerAsyncId,name=new.target.name,requireManualDestroy}=options||{};super({captureRejections});this.triggerAsyncId=triggerAsyncId\?\?0,this.asyncResource=new AsyncResource(name,{triggerAsyncId,requireManualDestroy})}emit(...args){this.asyncResource.runInAsyncScope(()=>super.emit(...args))}emitDestroy(){this.asyncResource.emitDestroy()}}return Object.defineProperties(EventEmitter,{captureRejections:{get(){return EventEmitterPrototype[kCapture]},set(value){validateBoolean(value,\"EventEmitter.captureRejections\"),EventEmitterPrototype[kCapture]=value},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return defaultMaxListeners},set:(arg)=>{validateNumber(arg,\"defaultMaxListeners\",0),defaultMaxListeners=arg}},kMaxEventTargetListeners:{value:kMaxEventTargetListeners,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:kMaxEventTargetListenersWarned,enumerable:!1,configurable:!1,writable:!1}}),Object.assign(EventEmitter,{once,on,getEventListeners,setMaxListeners,EventEmitter,usingDomains:!1,captureRejectionSymbol,EventEmitterAsyncResource,errorMonitor:kErrorMonitor,setMaxListeners,init:EventEmitter,listenerCount}),EventEmitter})\n"_s; +// + +// +static constexpr ASCIILiteral NodeFSCode = "(function (){\"use strict\";var $,ReadStream,WriteStream;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),promises=@getInternalField(@internalModuleRegistry,17)||@createInternalModuleById(17),Stream=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34);var fs=Bun.fs();class FSWatcher extends EventEmitter{#watcher;#listener;constructor(path,options,listener){super();if(typeof options===\"function\")listener=options,options={};else if(typeof options===\"string\")options={encoding:options};if(typeof listener!==\"function\")listener=()=>{};this.#listener=listener;try{this.#watcher=fs.watch(path,options||{},this.#onEvent.bind(this))}catch(e){if(!e.message\?.startsWith(\"FileNotFound\"))throw e;const notFound=new Error(`ENOENT: no such file or directory, watch '${path}'`);throw notFound.code=\"ENOENT\",notFound.errno=-2,notFound.path=path,notFound.syscall=\"watch\",notFound.filename=path,notFound}}#onEvent(eventType,filenameOrError){if(eventType===\"error\"||eventType===\"close\")this.emit(eventType,filenameOrError);else this.emit(\"change\",eventType,filenameOrError),this.#listener(eventType,filenameOrError)}close(){this.#watcher\?.close(),this.#watcher=null}ref(){this.#watcher\?.ref()}unref(){this.#watcher\?.unref()}}var access=function access(...args){callbackify(fs.accessSync,args)},appendFile=function appendFile(...args){callbackify(fs.appendFileSync,args)},close=function close(...args){callbackify(fs.closeSync,args)},rm=function rm(...args){callbackify(fs.rmSync,args)},rmdir=function rmdir(...args){callbackify(fs.rmdirSync,args)},copyFile=function copyFile(...args){callbackify(fs.copyFileSync,args)},exists=function exists(...args){callbackify(fs.existsSync,args)},chown=function chown(...args){callbackify(fs.chownSync,args)},chmod=function chmod(...args){callbackify(fs.chmodSync,args)},fchmod=function fchmod(...args){callbackify(fs.fchmodSync,args)},fchown=function fchown(...args){callbackify(fs.fchownSync,args)},fstat=function fstat(...args){callbackify(fs.fstatSync,args)},fsync=function fsync(...args){callbackify(fs.fsyncSync,args)},ftruncate=function ftruncate(...args){callbackify(fs.ftruncateSync,args)},futimes=function futimes(...args){callbackify(fs.futimesSync,args)},lchmod=function lchmod(...args){callbackify(fs.lchmodSync,args)},lchown=function lchown(...args){callbackify(fs.lchownSync,args)},link=function link(...args){callbackify(fs.linkSync,args)},mkdir=function mkdir(...args){callbackify(fs.mkdirSync,args)},mkdtemp=function mkdtemp(...args){callbackify(fs.mkdtempSync,args)},open=function open(...args){callbackify(fs.openSync,args)},read=function read(...args){callbackify(fs.readSync,args)},write=function write(...args){callbackify(fs.writeSync,args)},readdir=function readdir(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.readdir(...args).then((result)=>callback(null,result),callback)},readFile=function readFile(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.readFile(...args).then((result)=>callback(null,result),callback)},writeFile=function writeFile(...args){callbackify(fs.writeFileSync,args)},readlink=function readlink(...args){callbackify(fs.readlinkSync,args)},realpath=function realpath(...args){callbackify(fs.realpathSync,args)},rename=function rename(...args){callbackify(fs.renameSync,args)},lstat=function lstat(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.lstat(...args).then((result)=>callback(null,result),callback)},stat=function stat(...args){const callback=args[args.length-1];if(typeof callback!==\"function\")@throwTypeError(\"Callback must be a function\");fs.stat(...args).then((result)=>callback(null,result),callback)},symlink=function symlink(...args){callbackify(fs.symlinkSync,args)},truncate=function truncate(...args){callbackify(fs.truncateSync,args)},unlink=function unlink(...args){callbackify(fs.unlinkSync,args)},utimes=function utimes(...args){callbackify(fs.utimesSync,args)},lutimes=function lutimes(...args){callbackify(fs.lutimesSync,args)},accessSync=fs.accessSync.bind(fs),appendFileSync=fs.appendFileSync.bind(fs),closeSync=fs.closeSync.bind(fs),copyFileSync=fs.copyFileSync.bind(fs),existsSync=fs.existsSync.bind(fs),chownSync=fs.chownSync.bind(fs),chmodSync=fs.chmodSync.bind(fs),fchmodSync=fs.fchmodSync.bind(fs),fchownSync=fs.fchownSync.bind(fs),fstatSync=fs.fstatSync.bind(fs),fsyncSync=fs.fsyncSync.bind(fs),ftruncateSync=fs.ftruncateSync.bind(fs),futimesSync=fs.futimesSync.bind(fs),lchmodSync=fs.lchmodSync.bind(fs),lchownSync=fs.lchownSync.bind(fs),linkSync=fs.linkSync.bind(fs),lstatSync=fs.lstatSync.bind(fs),mkdirSync=fs.mkdirSync.bind(fs),mkdtempSync=fs.mkdtempSync.bind(fs),openSync=fs.openSync.bind(fs),readSync=fs.readSync.bind(fs),writeSync=fs.writeSync.bind(fs),readdirSync=fs.readdirSync.bind(fs),readFileSync=fs.readFileSync.bind(fs),writeFileSync=fs.writeFileSync.bind(fs),readlinkSync=fs.readlinkSync.bind(fs),realpathSync=fs.realpathSync.bind(fs),renameSync=fs.renameSync.bind(fs),statSync=fs.statSync.bind(fs),symlinkSync=fs.symlinkSync.bind(fs),truncateSync=fs.truncateSync.bind(fs),unlinkSync=fs.unlinkSync.bind(fs),utimesSync=fs.utimesSync.bind(fs),lutimesSync=fs.lutimesSync.bind(fs),rmSync=fs.rmSync.bind(fs),rmdirSync=fs.rmdirSync.bind(fs),writev=(fd,buffers,position,callback)=>{if(typeof position===\"function\")callback=position,position=null;queueMicrotask(()=>{try{var written=fs.writevSync(fd,buffers,position)}catch(e){callback(e)}callback(null,written,buffers)})},writevSync=fs.writevSync.bind(fs),readv=(fd,buffers,position,callback)=>{if(typeof position===\"function\")callback=position,position=null;queueMicrotask(()=>{try{var written=fs.readvSync(fd,buffers,position)}catch(e){callback(e)}callback(null,written,buffers)})},readvSync=fs.readvSync.bind(fs),Dirent=fs.Dirent,Stats=fs.Stats,watch=function watch(path,options,listener){return new FSWatcher(path,options,listener)};function callbackify(fsFunction,args){try{const result=fsFunction.apply(fs,args.slice(0,args.length-1)),callback=args[args.length-1];if(typeof callback===\"function\")queueMicrotask(()=>callback(null,result))}catch(e){const callback=args[args.length-1];if(typeof callback===\"function\")queueMicrotask(()=>callback(e))}}var readStreamPathFastPathSymbol=Symbol.for(\"Bun.Node.readStreamPathFastPath\");const readStreamSymbol=Symbol.for(\"Bun.NodeReadStream\"),readStreamPathOrFdSymbol=Symbol.for(\"Bun.NodeReadStreamPathOrFd\"),writeStreamSymbol=Symbol.for(\"Bun.NodeWriteStream\");var writeStreamPathFastPathSymbol=Symbol.for(\"Bun.NodeWriteStreamFastPath\"),writeStreamPathFastPathCallSymbol=Symbol.for(\"Bun.NodeWriteStreamFastPathCall\"),kIoDone=Symbol.for(\"kIoDone\"),defaultReadStreamOptions={file:void 0,fd:void 0,flags:\"r\",encoding:void 0,mode:438,autoClose:!0,emitClose:!0,start:0,end:Infinity,highWaterMark:65536,fs:{read,open:(path,flags,mode,cb)=>{var fd;try{fd=openSync(path,flags,mode)}catch(e){cb(e);return}cb(null,fd)},openSync,close},autoDestroy:!0},ReadStreamClass;ReadStream=function(InternalReadStream){ReadStreamClass=InternalReadStream,Object.defineProperty(ReadStreamClass.prototype,Symbol.toStringTag,{value:\"ReadStream\",enumerable:!1});function ReadStream2(path,options){return new InternalReadStream(path,options)}return ReadStream2.prototype=InternalReadStream.prototype,Object.defineProperty(ReadStream2,Symbol.hasInstance,{value(instance){return instance instanceof InternalReadStream}})}(class ReadStream2 extends Stream._getNativeReadableStreamPrototype(2,Stream.Readable){constructor(pathOrFd,options=defaultReadStreamOptions){if(typeof options!==\"object\"||!options)@throwTypeError(\"Expected options to be an object\");var{flags=defaultReadStreamOptions.flags,encoding=defaultReadStreamOptions.encoding,mode=defaultReadStreamOptions.mode,autoClose=defaultReadStreamOptions.autoClose,emitClose=defaultReadStreamOptions.emitClose,start=defaultReadStreamOptions.start,end=defaultReadStreamOptions.end,autoDestroy=defaultReadStreamOptions.autoClose,fs:fs2=defaultReadStreamOptions.fs,highWaterMark=defaultReadStreamOptions.highWaterMark}=options;if(pathOrFd\?.constructor\?.name===\"URL\")pathOrFd=Bun.fileURLToPath(pathOrFd);var tempThis={};if(typeof pathOrFd===\"string\"){if(pathOrFd.startsWith(\"file://\"))pathOrFd=Bun.fileURLToPath(pathOrFd);if(pathOrFd.length===0)@throwTypeError(\"Expected path to be a non-empty string\");tempThis.path=tempThis.file=tempThis[readStreamPathOrFdSymbol]=pathOrFd}else if(typeof pathOrFd===\"number\"){if(pathOrFd|=0,pathOrFd<0)@throwTypeError(\"Expected fd to be a positive integer\");tempThis.fd=tempThis[readStreamPathOrFdSymbol]=pathOrFd,tempThis.autoClose=!1}else @throwTypeError(\"Expected a path or file descriptor\");if(!tempThis.fd)tempThis.fd=fs2.openSync(pathOrFd,flags,mode);var fileRef=Bun.file(tempThis.fd),stream=fileRef.stream(),native=@direct(stream);if(!native)throw new Error(\"no native readable stream\");var{stream:ptr}=native;super(ptr,{...options,encoding,autoDestroy,autoClose,emitClose,highWaterMark});if(Object.assign(this,tempThis),this.#fileRef=fileRef,this.end=end,this._read=this.#internalRead,this.start=start,this.flags=flags,this.mode=mode,this.emitClose=emitClose,this[readStreamPathFastPathSymbol]=start===0&&end===Infinity&&autoClose&&fs2===defaultReadStreamOptions.fs&&(encoding===\"buffer\"||encoding===\"binary\"||encoding==null||encoding===\"utf-8\"||encoding===\"utf8\"),this._readableState.autoClose=autoDestroy=autoClose,this._readableState.highWaterMark=highWaterMark,start!==void 0)this.pos=start}#fileRef;#fs;file;path;fd=null;flags;mode;start;end;pos;bytesRead=0;#fileSize=-1;_read;[readStreamSymbol]=!0;[readStreamPathOrFdSymbol];[readStreamPathFastPathSymbol];_construct(callback){if(super._construct)super._construct(callback);else callback();this.emit(\"open\",this.fd),this.emit(\"ready\")}_destroy(err,cb){super._destroy(err,cb);try{var fd=this.fd;if(this[readStreamPathFastPathSymbol]=!1,!fd)cb(err);else this.#fs.close(fd,(er)=>{cb(er||err)}),this.fd=null}catch(e){throw e}}close(cb){if(typeof cb===\"function\")eos_()(this,cb);this.destroy()}push(chunk){var bytesRead=chunk\?.length\?\?0;if(bytesRead>0){this.bytesRead+=bytesRead;var currPos=this.pos;if(currPos!==void 0){if(this.bytesReadthis.end)chunk=chunk.slice(0,this.end-this.start+1);return super.push(chunk,...rest)}var end=this.end;if(end!==void 0&&this.bytesRead>end){chunk=chunk.slice(0,end-currPos+1);var[_,...rest]=arguments;return this.pos=this.bytesRead,super.push(chunk,...rest)}this.pos=this.bytesRead}}return super.push(...arguments)}#internalRead(n){var{pos,end,bytesRead,fd,encoding}=this;if(n=pos!==void 0\?Math.min(end-pos+1,n):Math.min(end-bytesRead+1,n),n<=0){this.push(null);return}if(this.#fileSize===-1&&bytesRead===0&&pos===void 0){var stat2=fstatSync(fd);if(this.#fileSize=stat2.size,this.#fileSize>0&&n>this.#fileSize)n=this.#fileSize+1}this[kIoDone]=!1;var res=super._read(n);if(@isPromise(res)){var then=res\?.then;if(then&&@isCallable(then))then(()=>{if(this[kIoDone]=!0,this.destroyed)this.emit(kIoDone)},(er)=>{this[kIoDone]=!0,this.#errorOrDestroy(er)})}else if(this[kIoDone]=!0,this.destroyed)this.emit(kIoDone),this.#errorOrDestroy(new Error(\"ERR_STREAM_PREMATURE_CLOSE\"))}#errorOrDestroy(err,sync=null){var{_readableState:r={destroyed:!1,autoDestroy:!1},_writableState:w={destroyed:!1,autoDestroy:!1}}=this;if(w\?.destroyed||r\?.destroyed)return this;if(r\?.autoDestroy||w\?.autoDestroy)this.destroy(err);else if(err)this.emit(\"error\",err)}pause(){return this[readStreamPathFastPathSymbol]=!1,super.pause()}resume(){return this[readStreamPathFastPathSymbol]=!1,super.resume()}unshift(...args){return this[readStreamPathFastPathSymbol]=!1,super.unshift(...args)}pipe(dest,pipeOpts){if(this[readStreamPathFastPathSymbol]&&(pipeOpts\?.end\?\?!0)&&this._readableState\?.pipes\?.length===0){if((writeStreamPathFastPathSymbol in dest)&&dest[writeStreamPathFastPathSymbol]){if(dest[writeStreamPathFastPathCallSymbol](this,pipeOpts))return this}}return this[readStreamPathFastPathSymbol]=!1,super.pipe(dest,pipeOpts)}});function createReadStream(path,options){return new ReadStream(path,options)}var defaultWriteStreamOptions={fd:null,start:void 0,pos:void 0,encoding:void 0,flags:\"w\",mode:438,fs:{write,close,open,openSync}},WriteStreamClass;WriteStream=function(InternalWriteStream){WriteStreamClass=InternalWriteStream,Object.defineProperty(WriteStreamClass.prototype,Symbol.toStringTag,{value:\"WritesStream\",enumerable:!1});function WriteStream2(path,options){return new InternalWriteStream(path,options)}return WriteStream2.prototype=InternalWriteStream.prototype,Object.defineProperty(WriteStream2,Symbol.hasInstance,{value(instance){return instance instanceof InternalWriteStream}})}(class WriteStream2 extends Stream.NativeWritable{constructor(path,options=defaultWriteStreamOptions){if(!options)@throwTypeError(\"Expected options to be an object\");var{fs:fs2=defaultWriteStreamOptions.fs,start=defaultWriteStreamOptions.start,flags=defaultWriteStreamOptions.flags,mode=defaultWriteStreamOptions.mode,autoClose=!0,emitClose=!1,autoDestroy=autoClose,encoding=defaultWriteStreamOptions.encoding,fd=defaultWriteStreamOptions.fd,pos=defaultWriteStreamOptions.pos}=options,tempThis={};if(typeof path===\"string\"){if(path.length===0)@throwTypeError(\"Expected a non-empty path\");if(path.startsWith(\"file:\"))path=Bun.fileURLToPath(path);tempThis.path=path,tempThis.fd=null,tempThis[writeStreamPathFastPathSymbol]=autoClose&&(start===void 0||start===0)&&fs2.write===defaultWriteStreamOptions.fs.write&&fs2.close===defaultWriteStreamOptions.fs.close}else tempThis.fd=fd,tempThis[writeStreamPathFastPathSymbol]=!1;if(!tempThis.fd)tempThis.fd=fs2.openSync(path,flags,mode);super(tempThis.fd,{...options,decodeStrings:!1,autoDestroy,emitClose,fd:tempThis});if(Object.assign(this,tempThis),typeof fs2\?.write!==\"function\")@throwTypeError(\"Expected fs.write to be a function\");if(typeof fs2\?.close!==\"function\")@throwTypeError(\"Expected fs.close to be a function\");if(typeof fs2\?.open!==\"function\")@throwTypeError(\"Expected fs.open to be a function\");if(typeof path===\"object\"&&path){if(path instanceof URL)path=Bun.fileURLToPath(path)}if(typeof path!==\"string\"&&typeof fd!==\"number\")@throwTypeError(\"Expected a path or file descriptor\");if(this.start=start,this.#fs=fs2,this.flags=flags,this.mode=mode,this.start!==void 0)this.pos=this.start;if(encoding!==defaultWriteStreamOptions.encoding){if(this.setDefaultEncoding(encoding),encoding!==\"buffer\"&&encoding!==\"utf8\"&&encoding!==\"utf-8\"&&encoding!==\"binary\")this[writeStreamPathFastPathSymbol]=!1}}get autoClose(){return this._writableState.autoDestroy}set autoClose(val){this._writableState.autoDestroy=val}destroySoon=this.end;open(){}path;fd;flags;mode;#fs;bytesWritten=0;pos;[writeStreamPathFastPathSymbol];[writeStreamSymbol]=!0;start;[writeStreamPathFastPathCallSymbol](readStream,pipeOpts){if(!this[writeStreamPathFastPathSymbol])return!1;if(this.fd!==null)return this[writeStreamPathFastPathSymbol]=!1,!1;return this[kIoDone]=!1,readStream[kIoDone]=!1,Bun.write(this[writeStreamPathFastPathSymbol],readStream[readStreamPathOrFdSymbol]).then((bytesWritten)=>{readStream[kIoDone]=this[kIoDone]=!0,this.bytesWritten+=bytesWritten,readStream.bytesRead+=bytesWritten,this.end(),readStream.close()},(err)=>{readStream[kIoDone]=this[kIoDone]=!0,this.#errorOrDestroy(err),readStream.emit(\"error\",err)})}isBunFastPathEnabled(){return this[writeStreamPathFastPathSymbol]}disableBunFastPath(){this[writeStreamPathFastPathSymbol]=!1}#handleWrite(er,bytes){if(er)return this.#errorOrDestroy(er);this.bytesWritten+=bytes}#internalClose(err,cb){this[writeStreamPathFastPathSymbol]=!1;var fd=this.fd;this.#fs.close(fd,(er)=>{this.fd=null,cb(err||er)})}_construct(callback){if(typeof this.fd===\"number\"){callback();return}callback(),this.emit(\"open\",this.fd),this.emit(\"ready\")}_destroy(err,cb){if(this.fd===null)return cb(err);if(this[kIoDone]){this.once(kIoDone,()=>this.#internalClose(err,cb));return}this.#internalClose(err,cb)}[kIoDone]=!1;close(cb){if(cb){if(this.closed){process.nextTick(cb);return}this.on(\"close\",cb)}if(!this.autoClose)this.on(\"finish\",this.destroy);this.end()}write(chunk,encoding=this._writableState.defaultEncoding,cb){if(this[writeStreamPathFastPathSymbol]=!1,typeof chunk===\"string\")chunk=Buffer.from(chunk,encoding);var native=this.pos===void 0;return this[kIoDone]=!0,super.write(chunk,encoding,native\?(err,bytes)=>{if(this[kIoDone]=!1,this.#handleWrite(err,bytes),this.emit(kIoDone),cb)!err\?cb():cb(err)}:()=>{},native)}#internalWriteSlow(chunk,encoding,cb){this.#fs.write(this.fd,chunk,0,chunk.length,this.pos,(err,bytes)=>{this[kIoDone]=!1,this.#handleWrite(err,bytes),this.emit(kIoDone),!err\?cb():cb(err)})}end(chunk,encoding,cb){var native=this.pos===void 0;return super.end(chunk,encoding,cb,native)}_write=this.#internalWriteSlow;_writev=void 0;get pending(){return this.fd===null}_destroy(err,cb){this.close(err,cb)}#errorOrDestroy(err){var{_readableState:r={destroyed:!1,autoDestroy:!1},_writableState:w={destroyed:!1,autoDestroy:!1}}=this;if(w\?.destroyed||r\?.destroyed)return this;if(r\?.autoDestroy||w\?.autoDestroy)this.destroy(err);else if(err)this.emit(\"error\",err)}});function createWriteStream(path,options){return new WriteStream(path,options)}return Object.defineProperties(fs,{createReadStream:{value:createReadStream},createWriteStream:{value:createWriteStream},ReadStream:{value:ReadStream},WriteStream:{value:WriteStream}}),realpath.native=realpath,realpathSync.native=realpathSync,$={access,accessSync,appendFile,appendFileSync,chmod,chmodSync,chown,chownSync,close,closeSync,constants:promises.constants,copyFile,copyFileSync,createReadStream,createWriteStream,Dirent,exists,existsSync,fchmod,fchmodSync,fchown,fchownSync,fstat,fstatSync,fsync,fsyncSync,ftruncate,ftruncateSync,futimes,futimesSync,lchmod,lchmodSync,lchown,lchownSync,link,linkSync,lstat,lstatSync,lutimes,lutimesSync,mkdir,mkdirSync,mkdtemp,mkdtempSync,open,openSync,promises,read,readFile,readFileSync,readSync,readdir,readdirSync,readlink,readlinkSync,realpath,realpathSync,rename,renameSync,rm,rmSync,rmdir,rmdirSync,stat,statSync,Stats,symlink,symlinkSync,truncate,truncateSync,unlink,unlinkSync,utimes,utimesSync,write,writeFile,writeFileSync,writeSync,WriteStream,ReadStream,watch,FSWatcher,writev,writevSync,readv,readvSync,[Symbol.for(\"::bunternal::\")]:{ReadStreamClass,WriteStreamClass}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeFSPromisesCode = "(function (){\"use strict\";var $;const constants=@processBindingConstants.fs;var fs=Bun.fs();const notrace=\"::bunternal::\";var promisify={[notrace]:(fsFunction)=>{return async function(...args){return await 1,fsFunction.apply(fs,args)}}}[notrace];function watch(filename,options={}){if(filename instanceof URL)@throwTypeError(\"Watch URLs are not supported yet\");else if(Buffer.isBuffer(filename))filename=filename.toString();else if(typeof filename!==\"string\")@throwTypeError(\"Expected path to be a string or Buffer\");let nextEventResolve=null;if(typeof options===\"string\")options={encoding:options};const queue=@createFIFO(),watcher=fs.watch(filename,options||{},(eventType,filename2)=>{if(queue.push({eventType,filename:filename2}),nextEventResolve){const resolve=nextEventResolve;nextEventResolve=null,resolve()}});return{[Symbol.asyncIterator](){let closed=!1;return{async next(){while(!closed){let event;while(event=queue.shift()){if(event.eventType===\"close\")return closed=!0,{value:void 0,done:!0};if(event.eventType===\"error\")throw closed=!0,event.filename;return{value:event,done:!1}}const{promise,resolve}=Promise.withResolvers();nextEventResolve=resolve,await promise}return{value:void 0,done:!0}},return(){if(!closed){if(watcher.close(),closed=!0,nextEventResolve){const resolve=nextEventResolve;nextEventResolve=null,resolve()}}return{value:void 0,done:!0}}}}}}return $={access:promisify(fs.accessSync),appendFile:promisify(fs.appendFileSync),close:promisify(fs.closeSync),copyFile:promisify(fs.copyFileSync),exists:promisify(fs.existsSync),chown:promisify(fs.chownSync),chmod:promisify(fs.chmodSync),fchmod:promisify(fs.fchmodSync),fchown:promisify(fs.fchownSync),fstat:promisify(fs.fstatSync),fsync:promisify(fs.fsyncSync),ftruncate:promisify(fs.ftruncateSync),futimes:promisify(fs.futimesSync),lchmod:promisify(fs.lchmodSync),lchown:promisify(fs.lchownSync),link:promisify(fs.linkSync),lstat:fs.lstat.bind(fs),mkdir:promisify(fs.mkdirSync),mkdtemp:promisify(fs.mkdtempSync),open:promisify(fs.openSync),read:promisify(fs.readSync),write:promisify(fs.writeSync),readdir:fs.readdir.bind(fs),readFile:fs.readFile.bind(fs),writeFile:promisify(fs.writeFileSync),readlink:promisify(fs.readlinkSync),realpath:promisify(fs.realpathSync),rename:promisify(fs.renameSync),stat:fs.stat.bind(fs),symlink:promisify(fs.symlinkSync),truncate:promisify(fs.truncateSync),unlink:promisify(fs.unlinkSync),utimes:promisify(fs.utimesSync),lutimes:promisify(fs.lutimesSync),rm:promisify(fs.rmSync),rmdir:promisify(fs.rmdirSync),writev:(fd,buffers,position)=>{return new Promise((resolve,reject)=>{try{var bytesWritten=fs.writevSync(fd,buffers,position)}catch(err){reject(err);return}resolve({bytesWritten,buffers})})},readv:(fd,buffers,position)=>{return new Promise((resolve,reject)=>{try{var bytesRead=fs.readvSync(fd,buffers,position)}catch(err){reject(err);return}resolve({bytesRead,buffers})})},constants,watch},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttpCode = "(function (){\"use strict\";var $;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),{isTypedArray}=@requireNativeModule(\"node:util/types\"),{Duplex,Readable,Writable}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),headerCharRegex=/[^\\t\\x20-\\x7e\\x80-\\xff]/;function checkInvalidHeaderChar(val){return RegExpPrototypeExec.call(headerCharRegex,val)!==null}const validateHeaderName=(name,label)=>{if(typeof name!==\"string\"||!name||!checkIsHttpToken(name))throw new Error(\"ERR_INVALID_HTTP_TOKEN\")},validateHeaderValue=(name,value)=>{if(value===void 0)throw new Error(\"ERR_HTTP_INVALID_HEADER_VALUE\");if(checkInvalidHeaderChar(value))throw new Error(\"ERR_INVALID_CHAR\")};function isIPv6(input){return new RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\").test(input)}const{URL}=globalThis,globalReportError=globalThis.reportError,setTimeout=globalThis.setTimeout,fetch=Bun.fetch,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.\";var _defaultHTTPSAgent,kInternalRequest=Symbol(\"kInternalRequest\"),kInternalSocketData=Symbol.for(\"::bunternal::\");const kEmptyBuffer=Buffer.alloc(0);function isValidTLSArray(obj){if(typeof obj===\"string\"||isTypedArray(obj)||obj instanceof ArrayBuffer||obj instanceof Blob)return!0;if(Array.isArray(obj)){for(var i=0;i{this.close()}),host=port\?.host,port=port\?.port,typeof port\?.callback===\"function\")onListen=port\?.callback}if(typeof backlog===\"function\")onListen=backlog;const ResponseClass=this.#options.ServerResponse||ServerResponse,RequestClass=this.#options.IncomingMessage||IncomingMessage;try{const tls=this.#tls;if(tls)this.serverName=tls.serverName||host||\"localhost\";this.#server=Bun.serve({tls,port,hostname:host,websocket:{open(ws){ws.data.open(ws)},message(ws,message){ws.data.message(ws,message)},close(ws,code,reason){ws.data.close(ws,code,reason)},drain(ws){ws.data.drain(ws)}},fetch(req,_server){var pendingResponse,pendingError,rejectFunction,resolveFunction,reject=(err)=>{if(pendingError)return;if(pendingError=err,rejectFunction)rejectFunction(err)},reply=function(resp){if(pendingResponse)return;if(pendingResponse=resp,resolveFunction)resolveFunction(resp)};const http_req=new RequestClass(req),http_res=new ResponseClass({reply,req:http_req});if(http_req.once(\"error\",(err)=>reject(err)),http_res.once(\"error\",(err)=>reject(err)),req.headers.get(\"upgrade\")){const socket=new FakeSocket;socket[kInternalSocketData]=[_server,http_res,req],server.emit(\"upgrade\",http_req,socket,kEmptyBuffer)}else server.emit(\"request\",http_req,http_res);if(pendingError)throw pendingError;if(pendingResponse)return pendingResponse;return new Promise((resolve,reject2)=>{resolveFunction=resolve,rejectFunction=reject2})}}),setTimeout(emitListeningNextTick,1,this,onListen,null,this.#server.hostname,this.#server.port)}catch(err){setTimeout(emitListeningNextTick,1,this,onListen,err)}return this}setTimeout(msecs,callback){}}function assignHeaders(object,req){var headers=req.headers.toJSON();const rawHeaders=@newArrayWithSize(req.headers.count*2);var i=0;for(let key in headers)rawHeaders[i++]=key,rawHeaders[i++]=headers[key];object.headers=headers,object.rawHeaders=rawHeaders}function destroyBodyStreamNT(bodyStream){bodyStream.destroy()}var defaultIncomingOpts={type:\"request\"};function getDefaultHTTPSAgent(){return _defaultHTTPSAgent\?\?=new Agent({defaultPort:443,protocol:\"https:\"})}class IncomingMessage extends Readable{method;complete;constructor(req,defaultIncomingOpts2){const method=req.method;super();const url=new URL(req.url);var{type=\"request\",[kInternalRequest]:nodeReq}=defaultIncomingOpts2||{};this.#noBody=type===\"request\"\?method===\"GET\"||method===\"HEAD\"||method===\"TRACE\"||method===\"CONNECT\"||method===\"OPTIONS\"||(parseInt(req.headers.get(\"Content-Length\")||\"\")||0)===0:!1,this.#req=req,this.method=method,this.#type=type,this.complete=!!this.#noBody,this.#bodyStream=void 0;const socket=new FakeSocket;socket.remoteAddress=url.hostname,socket.remotePort=url.port,this.#fakeSocket=socket,this.url=url.pathname+url.search,this.#nodeReq=nodeReq,assignHeaders(this,req)}headers;rawHeaders;_consuming=!1;_dumped=!1;#bodyStream;#fakeSocket;#noBody=!1;#aborted=!1;#req;url;#type;#nodeReq;get req(){return this.#nodeReq}_construct(callback){if(this.#type===\"response\"||this.#noBody){callback();return}const contentLength=this.#req.headers.get(\"content-length\");if((contentLength\?parseInt(contentLength,10):0)===0){this.#noBody=!0,callback();return}callback()}async#consumeStream(reader){while(!0){var{done,value}=await reader.readMany();if(this.#aborted)return;if(done){this.push(null),this.destroy();break}for(var v of value)this.push(v)}}_read(size){if(this.#noBody)this.push(null),this.complete=!0;else if(this.#bodyStream==null){const reader=this.#req.body\?.getReader();if(!reader){this.push(null);return}this.#bodyStream=reader,this.#consumeStream(reader)}}get aborted(){return this.#aborted}#abort(){if(this.#aborted)return;this.#aborted=!0;var bodyStream=this.#bodyStream;if(!bodyStream)return;bodyStream.cancel(),this.complete=!0,this.#bodyStream=void 0,this.push(null)}get connection(){return this.#fakeSocket}get statusCode(){return this.#req.status}get statusMessage(){return STATUS_CODES[this.#req.status]}get httpVersion(){return\"1.1\"}get rawTrailers(){return[]}get httpVersionMajor(){return 1}get httpVersionMinor(){return 1}get trailers(){return kEmptyObject}get socket(){return this.#fakeSocket\?\?=new FakeSocket}set socket(val){this.#fakeSocket=val}setTimeout(msecs,callback){throw new Error(\"not implemented\")}}function emitErrorNt(msg,err,callback){if(callback(err),typeof msg.emit===\"function\"&&!msg._closed)msg.emit(\"error\",err)}function onError(self,err,cb){process.nextTick(()=>emitErrorNt(self,err,cb))}function write_(msg,chunk,encoding,callback,fromEnd){if(typeof callback!==\"function\")callback=nop;let len;if(chunk===null)throw new Error(\"ERR_STREAM_NULL_VALUES\");else if(typeof chunk===\"string\")len=Buffer.byteLength(chunk,encoding);else throw new Error(\"Invalid arg type for chunk\");let err;if(msg.finished)err=new Error(\"ERR_STREAM_WRITE_AFTER_END\");else if(msg.destroyed)err=new Error(\"ERR_STREAM_DESTROYED\");if(err){if(!msg.destroyed)onError(msg,err,callback);else process.nextTick(callback,err);return!1}if(!msg._header){if(fromEnd)msg._contentLength=len}if(!msg._hasBody)return process.nextTick(callback),!0;return!0}class OutgoingMessage extends Writable{constructor(){super(...arguments)}#headers;headersSent=!1;sendDate=!0;req;timeout;#finished=!1;[kEndCalled]=!1;#fakeSocket;#timeoutTimer;[kAbortController]=null;_implicitHeader(){}get headers(){if(!this.#headers)return kEmptyObject;return this.#headers.toJSON()}get shouldKeepAlive(){return!0}get chunkedEncoding(){return!1}set chunkedEncoding(value){}set shouldKeepAlive(value){}get useChunkedEncodingByDefault(){return!0}set useChunkedEncodingByDefault(value){}get socket(){return this.#fakeSocket\?\?=new FakeSocket}set socket(val){this.#fakeSocket=val}get connection(){return this.socket}get finished(){return this.#finished}appendHeader(name,value){var headers=this.#headers\?\?=new Headers;headers.append(name,value)}flushHeaders(){}getHeader(name){return getHeader(this.#headers,name)}getHeaders(){if(!this.#headers)return kEmptyObject;return this.#headers.toJSON()}getHeaderNames(){var headers=this.#headers;if(!headers)return[];return Array.from(headers.keys())}removeHeader(name){if(!this.#headers)return;this.#headers.delete(name)}setHeader(name,value){var headers=this.#headers\?\?=new Headers;return headers.set(name,value),this}hasHeader(name){if(!this.#headers)return!1;return this.#headers.has(name)}addTrailers(headers){throw new Error(\"not implemented\")}[kClearTimeout](){if(this.#timeoutTimer)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.destroyed)return 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}}let OriginalWriteHeadFn,OriginalImplicitHeadFn;class ServerResponse extends Writable{constructor({req,reply}){super();if(this.req=req,this._reply=reply,this.sendDate=!0,this.statusCode=200,this.headersSent=!1,this.statusMessage=void 0,this.#controller=void 0,this.#firstWrite=void 0,this._writableState.decodeStrings=!1,this.#deferred=void 0,req.method===\"HEAD\")this._hasBody=!1}req;_reply;sendDate;statusCode;#headers;headersSent=!1;statusMessage;#controller;#firstWrite;_sent100=!1;_defaultKeepAlive=!1;_removedConnection=!1;_removedContLen=!1;_hasBody=!0;#deferred=void 0;#finished=!1;_implicitHeader(){this.writeHead(this.statusCode)}_write(chunk,encoding,callback){if(!this.#firstWrite&&!this.headersSent){this.#firstWrite=chunk,callback();return}this.#ensureReadableStreamController((controller)=>{controller.write(chunk),callback()})}_writev(chunks,callback){if(chunks.length===1&&!this.headersSent&&!this.#firstWrite){this.#firstWrite=chunks[0].chunk,callback();return}this.#ensureReadableStreamController((controller)=>{for(let chunk of chunks)controller.write(chunk.chunk);callback()})}#ensureReadableStreamController(run){var thisController=this.#controller;if(thisController)return run(thisController);this.headersSent=!0;var firstWrite=this.#firstWrite;this.#firstWrite=void 0,this._reply(new Response(new ReadableStream({type:\"direct\",pull:(controller)=>{if(this.#controller=controller,firstWrite)controller.write(firstWrite);if(firstWrite=void 0,run(controller),!this.#finished)return new Promise((resolve)=>{this.#deferred=resolve})}}),{headers:this.#headers,status:this.statusCode,statusText:this.statusMessage\?\?STATUS_CODES[this.statusCode]}))}#drainHeadersIfObservable(){if(this._implicitHeader===OriginalImplicitHeadFn&&this.writeHead===OriginalWriteHeadFn)return;this._implicitHeader()}_final(callback){if(!this.headersSent){var data=this.#firstWrite||\"\";this.#firstWrite=void 0,this.#finished=!0,this.#drainHeadersIfObservable(),this._reply(new Response(data,{headers:this.#headers,status:this.statusCode,statusText:this.statusMessage\?\?STATUS_CODES[this.statusCode]})),callback&&callback();return}this.#finished=!0,this.#ensureReadableStreamController((controller)=>{controller.end(),callback();var deferred=this.#deferred;if(deferred)this.#deferred=void 0,deferred()})}writeProcessing(){throw new Error(\"not implemented\")}addTrailers(headers){throw new Error(\"not implemented\")}assignSocket(socket){throw new Error(\"not implemented\")}detachSocket(socket){throw new Error(\"not implemented\")}writeContinue(callback){throw new Error(\"not implemented\")}setTimeout(msecs,callback){throw new Error(\"not implemented\")}get shouldKeepAlive(){return!0}get chunkedEncoding(){return!1}set chunkedEncoding(value){}set shouldKeepAlive(value){}get useChunkedEncodingByDefault(){return!0}set useChunkedEncodingByDefault(value){}appendHeader(name,value){var headers=this.#headers\?\?=new Headers;headers.append(name,value)}flushHeaders(){}getHeader(name){return getHeader(this.#headers,name)}getHeaders(){var headers=this.#headers;if(!headers)return kEmptyObject;return headers.toJSON()}getHeaderNames(){var headers=this.#headers;if(!headers)return[];return Array.from(headers.keys())}removeHeader(name){if(!this.#headers)return;this.#headers.delete(name)}setHeader(name,value){var headers=this.#headers\?\?=new Headers;return headers.set(name,value),this}hasHeader(name){if(!this.#headers)return!1;return this.#headers.has(name)}writeHead(statusCode,statusMessage,headers){return _writeHead(statusCode,statusMessage,headers,this),this}}OriginalWriteHeadFn=ServerResponse.prototype.writeHead,OriginalImplicitHeadFn=ServerResponse.prototype._implicitHeader;class ClientRequest extends OutgoingMessage{#timeout;#res=null;#upgradeOrConnect=!1;#parser=null;#maxHeadersCount=null;#reusedSocket=!1;#host;#protocol;#method;#port;#useDefaultPort;#joinDuplicateHeaders;#maxHeaderSize;#agent=globalAgent;#path;#socketPath;#bodyChunks=null;#fetchRequest;#signal=null;[kAbortController]=null;#timeoutTimer=void 0;#options;#finished;get path(){return this.#path}get port(){return this.#port}get method(){return this.#method}get host(){return this.#host}get protocol(){return this.#protocol}_write(chunk,encoding,callback){if(!this.#bodyChunks){this.#bodyChunks=[chunk],callback();return}this.#bodyChunks.push(chunk),callback()}_writev(chunks,callback){if(!this.#bodyChunks){this.#bodyChunks=chunks,callback();return}this.#bodyChunks.push(...chunks),callback()}_final(callback){if(this.#finished=!0,this[kAbortController]=new AbortController,this[kAbortController].signal.addEventListener(\"abort\",()=>{this[kClearTimeout]()}),this.#signal\?.aborted)this[kAbortController].abort();var method=this.#method,body=this.#bodyChunks\?.length===1\?this.#bodyChunks[0]:Buffer.concat(this.#bodyChunks||[]);try{this.#fetchRequest=fetch(`${this.#protocol}//${this.#host}${this.#useDefaultPort\?\"\":\":\"+this.#port}${this.#path}`,{method,headers:this.getHeaders(),body:body&&method!==\"GET\"&&method!==\"HEAD\"&&method!==\"OPTIONS\"\?body:void 0,redirect:\"manual\",verbose:!1,signal:this[kAbortController].signal,timeout:!1}).then((response)=>{var res=this.#res=new IncomingMessage(response,{type:\"response\",[kInternalRequest]:this});this.emit(\"response\",res)}).catch((err)=>{this.emit(\"error\",err)}).finally(()=>{this.#fetchRequest=null,this[kClearTimeout]()})}catch(err){this.emit(\"error\",err)}finally{callback()}}get aborted(){return this.#signal\?.aborted||!!this[kAbortController]\?.signal.aborted}abort(){if(this.aborted)return;this[kAbortController].abort()}constructor(input,options,cb){super();if(typeof input===\"string\"){const urlStr=input;try{var urlObject=new URL(urlStr)}catch(e){@throwTypeError(`Invalid URL: ${urlStr}`)}input=urlToHttpOptions(urlObject)}else if(input&&typeof input===\"object\"&&input instanceof URL)input=urlToHttpOptions(input);else cb=options,options=input,input=null;if(typeof options===\"function\")cb=options,options=input||kEmptyObject;else options=ObjectAssign(input||{},options);var defaultAgent=options._defaultAgent||Agent.globalAgent;let protocol=options.protocol;if(!protocol)if(options.port===443)protocol=\"https:\";else protocol=defaultAgent.protocol||\"http:\";switch(this.#protocol=protocol,this.#agent\?.protocol){case void 0:break;case\"http:\":if(protocol===\"https:\"){defaultAgent=this.#agent=getDefaultHTTPSAgent();break}case\"https:\":if(protocol===\"https\"){defaultAgent=this.#agent=Agent.globalAgent;break}default:break}if(options.path){const path=String(options.path);if(RegExpPrototypeExec.call(INVALID_PATH_REGEX,path)!==null)throw new Error(\"Path contains unescaped characters\")}if(protocol!==\"http:\"&&protocol!==\"https:\"&&protocol){const expectedProtocol=defaultAgent\?.protocol\?\?\"http:\";throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`)}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\";this.#socketPath=options.socketPath;const signal=options.signal;if(signal)signal.addEventListener(\"abort\",()=>{this[kAbortController]\?.abort()}),this.#signal=signal;let method=options.method;const methodIsString=typeof method===\"string\";if(method!==null&&method!==void 0&&!methodIsString)throw new Error(\"ERR_INVALID_ARG_TYPE: options.method\");if(methodIsString&&method){if(!checkIsHttpToken(method))throw new Error(\"ERR_INVALID_HTTP_TOKEN: Method\");method=this.#method=StringPrototypeToUpperCase.call(method)}else method=this.#method=\"GET\";const _maxHeaderSize=options.maxHeaderSize;this.#maxHeaderSize=_maxHeaderSize;var _joinDuplicateHeaders=options.joinDuplicateHeaders;if(this.#joinDuplicateHeaders=_joinDuplicateHeaders,this.#path=options.path||\"/\",cb)this.once(\"response\",cb);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)this.setHeader(key,headers[key]);var auth=options.auth;if(auth&&!this.getHeader(\"Authorization\"))this.setHeader(\"Authorization\",\"Basic \"+Buffer.from(auth).toString(\"base64\"))}var{signal:_signal,...optsWithoutSignal}=options;this.#options=optsWithoutSignal}setSocketKeepAlive(enable=!0,initialDelay=0){}setNoDelay(noDelay=!0){}[kClearTimeout](){if(this.#timeoutTimer)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.destroyed)return 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}}function urlToHttpOptions(url){var{protocol,hostname,hash,search,pathname,href,port,username,password}=url;return{protocol,hostname:typeof hostname===\"string\"&&StringPrototypeStartsWith.call(hostname,\"[\")\?StringPrototypeSlice.call(hostname,1,-1):hostname,hash,search,pathname,path:`${pathname||\"\"}${search||\"\"}`,href,port:port\?Number(port):protocol===\"https:\"\?443:protocol===\"http:\"\?80:void 0,auth:username||password\?`${decodeURIComponent(username)}:${decodeURIComponent(password)}`:void 0}}function validateHost(host,name){if(host!==null&&host!==void 0&&typeof host!==\"string\")throw new Error(\"Invalid arg type in options\");return host}const tokenRegExp=/^[\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]+$/;function checkIsHttpToken(val){return RegExpPrototypeExec.call(tokenRegExp,val)!==null}const METHODS=[\"ACL\",\"BIND\",\"CHECKOUT\",\"CONNECT\",\"COPY\",\"DELETE\",\"GET\",\"HEAD\",\"LINK\",\"LOCK\",\"M-SEARCH\",\"MERGE\",\"MKACTIVITY\",\"MKCALENDAR\",\"MKCOL\",\"MOVE\",\"NOTIFY\",\"OPTIONS\",\"PATCH\",\"POST\",\"PROPFIND\",\"PROPPATCH\",\"PURGE\",\"PUT\",\"REBIND\",\"REPORT\",\"SEARCH\",\"SOURCE\",\"SUBSCRIBE\",\"TRACE\",\"UNBIND\",\"UNLINK\",\"UNLOCK\",\"UNSUBSCRIBE\"],STATUS_CODES={100:\"Continue\",101:\"Switching Protocols\",102:\"Processing\",103:\"Early Hints\",200:\"OK\",201:\"Created\",202:\"Accepted\",203:\"Non-Authoritative Information\",204:\"No Content\",205:\"Reset Content\",206:\"Partial Content\",207:\"Multi-Status\",208:\"Already Reported\",226:\"IM Used\",300:\"Multiple Choices\",301:\"Moved Permanently\",302:\"Found\",303:\"See Other\",304:\"Not Modified\",305:\"Use Proxy\",307:\"Temporary Redirect\",308:\"Permanent Redirect\",400:\"Bad Request\",401:\"Unauthorized\",402:\"Payment Required\",403:\"Forbidden\",404:\"Not Found\",405:\"Method Not Allowed\",406:\"Not Acceptable\",407:\"Proxy Authentication Required\",408:\"Request Timeout\",409:\"Conflict\",410:\"Gone\",411:\"Length Required\",412:\"Precondition Failed\",413:\"Payload Too Large\",414:\"URI Too Long\",415:\"Unsupported Media Type\",416:\"Range Not Satisfiable\",417:\"Expectation Failed\",418:\"I'm a Teapot\",421:\"Misdirected Request\",422:\"Unprocessable Entity\",423:\"Locked\",424:\"Failed Dependency\",425:\"Too Early\",426:\"Upgrade Required\",428:\"Precondition Required\",429:\"Too Many Requests\",431:\"Request Header Fields Too Large\",451:\"Unavailable For Legal Reasons\",500:\"Internal Server Error\",501:\"Not Implemented\",502:\"Bad Gateway\",503:\"Service Unavailable\",504:\"Gateway Timeout\",505:\"HTTP Version Not Supported\",506:\"Variant Also Negotiates\",507:\"Insufficient Storage\",508:\"Loop Detected\",509:\"Bandwidth Limit Exceeded\",510:\"Not Extended\",511:\"Network Authentication Required\"};function _normalizeArgs(args){let arr;if(args.length===0)return arr=[{},null],arr;const arg0=args[0];let options={};if(typeof arg0===\"object\"&&arg0!==null)options=arg0;else if(options.port=arg0,args.length>1&&typeof args[1]===\"string\")options.host=args[1];const cb=args[args.length-1];if(typeof cb!==\"function\")arr=[options,null];else arr=[options,cb];return arr}function _writeHead(statusCode,reason,obj,response){if(statusCode|=0,statusCode<100||statusCode>999)throw new Error(\"status code must be between 100 and 999\");if(typeof reason===\"string\")response.statusMessage=reason;else{if(!response.statusMessage)response.statusMessage=STATUS_CODES[statusCode]||\"unknown\";obj=reason}response.statusCode=statusCode;{let k;if(Array.isArray(obj)){if(obj.length%2!==0)throw new Error(\"raw headers must have an even number of elements\");for(let n=0;n=100&&statusCode<=199)response._hasBody=!1}function request(url,options,cb){return new ClientRequest(url,options,cb)}function get(url,options,cb){const req=request(url,options,cb);return req.end(),req}var globalAgent=new Agent;return $={Agent,Server,METHODS,STATUS_CODES,createServer,ServerResponse,IncomingMessage,request,get,maxHeaderSize:16384,validateHeaderName,validateHeaderValue,setMaxIdleHTTPParsers(max){},globalAgent,ClientRequest,OutgoingMessage},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttp2Code = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function connect(){throwNotImplemented(\"node:http2 connect\",887)}const constants={NGHTTP2_ERR_FRAME_SIZE_ERROR:-522,NGHTTP2_SESSION_SERVER:0,NGHTTP2_SESSION_CLIENT:1,NGHTTP2_STREAM_STATE_IDLE:1,NGHTTP2_STREAM_STATE_OPEN:2,NGHTTP2_STREAM_STATE_RESERVED_LOCAL:3,NGHTTP2_STREAM_STATE_RESERVED_REMOTE:4,NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL:5,NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE:6,NGHTTP2_STREAM_STATE_CLOSED:7,NGHTTP2_FLAG_NONE:0,NGHTTP2_FLAG_END_STREAM:1,NGHTTP2_FLAG_END_HEADERS:4,NGHTTP2_FLAG_ACK:1,NGHTTP2_FLAG_PADDED:8,NGHTTP2_FLAG_PRIORITY:32,DEFAULT_SETTINGS_HEADER_TABLE_SIZE:4096,DEFAULT_SETTINGS_ENABLE_PUSH:1,DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS:4294967295,DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE:65535,DEFAULT_SETTINGS_MAX_FRAME_SIZE:16384,DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE:65535,DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL:0,MAX_MAX_FRAME_SIZE:16777215,MIN_MAX_FRAME_SIZE:16384,MAX_INITIAL_WINDOW_SIZE:2147483647,NGHTTP2_SETTINGS_HEADER_TABLE_SIZE:1,NGHTTP2_SETTINGS_ENABLE_PUSH:2,NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS:3,NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE:4,NGHTTP2_SETTINGS_MAX_FRAME_SIZE:5,NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE:6,NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL:8,PADDING_STRATEGY_NONE:0,PADDING_STRATEGY_ALIGNED:1,PADDING_STRATEGY_MAX:2,PADDING_STRATEGY_CALLBACK:1,NGHTTP2_NO_ERROR:0,NGHTTP2_PROTOCOL_ERROR:1,NGHTTP2_INTERNAL_ERROR:2,NGHTTP2_FLOW_CONTROL_ERROR:3,NGHTTP2_SETTINGS_TIMEOUT:4,NGHTTP2_STREAM_CLOSED:5,NGHTTP2_FRAME_SIZE_ERROR:6,NGHTTP2_REFUSED_STREAM:7,NGHTTP2_CANCEL:8,NGHTTP2_COMPRESSION_ERROR:9,NGHTTP2_CONNECT_ERROR:10,NGHTTP2_ENHANCE_YOUR_CALM:11,NGHTTP2_INADEQUATE_SECURITY:12,NGHTTP2_HTTP_1_1_REQUIRED:13,NGHTTP2_DEFAULT_WEIGHT:16,HTTP2_HEADER_STATUS:\":status\",HTTP2_HEADER_METHOD:\":method\",HTTP2_HEADER_AUTHORITY:\":authority\",HTTP2_HEADER_SCHEME:\":scheme\",HTTP2_HEADER_PATH:\":path\",HTTP2_HEADER_PROTOCOL:\":protocol\",HTTP2_HEADER_ACCEPT_ENCODING:\"accept-encoding\",HTTP2_HEADER_ACCEPT_LANGUAGE:\"accept-language\",HTTP2_HEADER_ACCEPT_RANGES:\"accept-ranges\",HTTP2_HEADER_ACCEPT:\"accept\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS:\"access-control-allow-credentials\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS:\"access-control-allow-headers\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS:\"access-control-allow-methods\",HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN:\"access-control-allow-origin\",HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS:\"access-control-expose-headers\",HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS:\"access-control-request-headers\",HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD:\"access-control-request-method\",HTTP2_HEADER_AGE:\"age\",HTTP2_HEADER_AUTHORIZATION:\"authorization\",HTTP2_HEADER_CACHE_CONTROL:\"cache-control\",HTTP2_HEADER_CONNECTION:\"connection\",HTTP2_HEADER_CONTENT_DISPOSITION:\"content-disposition\",HTTP2_HEADER_CONTENT_ENCODING:\"content-encoding\",HTTP2_HEADER_CONTENT_LENGTH:\"content-length\",HTTP2_HEADER_CONTENT_TYPE:\"content-type\",HTTP2_HEADER_COOKIE:\"cookie\",HTTP2_HEADER_DATE:\"date\",HTTP2_HEADER_ETAG:\"etag\",HTTP2_HEADER_FORWARDED:\"forwarded\",HTTP2_HEADER_HOST:\"host\",HTTP2_HEADER_IF_MODIFIED_SINCE:\"if-modified-since\",HTTP2_HEADER_IF_NONE_MATCH:\"if-none-match\",HTTP2_HEADER_IF_RANGE:\"if-range\",HTTP2_HEADER_LAST_MODIFIED:\"last-modified\",HTTP2_HEADER_LINK:\"link\",HTTP2_HEADER_LOCATION:\"location\",HTTP2_HEADER_RANGE:\"range\",HTTP2_HEADER_REFERER:\"referer\",HTTP2_HEADER_SERVER:\"server\",HTTP2_HEADER_SET_COOKIE:\"set-cookie\",HTTP2_HEADER_STRICT_TRANSPORT_SECURITY:\"strict-transport-security\",HTTP2_HEADER_TRANSFER_ENCODING:\"transfer-encoding\",HTTP2_HEADER_TE:\"te\",HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS:\"upgrade-insecure-requests\",HTTP2_HEADER_UPGRADE:\"upgrade\",HTTP2_HEADER_USER_AGENT:\"user-agent\",HTTP2_HEADER_VARY:\"vary\",HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS:\"x-content-type-options\",HTTP2_HEADER_X_FRAME_OPTIONS:\"x-frame-options\",HTTP2_HEADER_KEEP_ALIVE:\"keep-alive\",HTTP2_HEADER_PROXY_CONNECTION:\"proxy-connection\",HTTP2_HEADER_X_XSS_PROTECTION:\"x-xss-protection\",HTTP2_HEADER_ALT_SVC:\"alt-svc\",HTTP2_HEADER_CONTENT_SECURITY_POLICY:\"content-security-policy\",HTTP2_HEADER_EARLY_DATA:\"early-data\",HTTP2_HEADER_EXPECT_CT:\"expect-ct\",HTTP2_HEADER_ORIGIN:\"origin\",HTTP2_HEADER_PURPOSE:\"purpose\",HTTP2_HEADER_TIMING_ALLOW_ORIGIN:\"timing-allow-origin\",HTTP2_HEADER_X_FORWARDED_FOR:\"x-forwarded-for\",HTTP2_HEADER_PRIORITY:\"priority\",HTTP2_HEADER_ACCEPT_CHARSET:\"accept-charset\",HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE:\"access-control-max-age\",HTTP2_HEADER_ALLOW:\"allow\",HTTP2_HEADER_CONTENT_LANGUAGE:\"content-language\",HTTP2_HEADER_CONTENT_LOCATION:\"content-location\",HTTP2_HEADER_CONTENT_MD5:\"content-md5\",HTTP2_HEADER_CONTENT_RANGE:\"content-range\",HTTP2_HEADER_DNT:\"dnt\",HTTP2_HEADER_EXPECT:\"expect\",HTTP2_HEADER_EXPIRES:\"expires\",HTTP2_HEADER_FROM:\"from\",HTTP2_HEADER_IF_MATCH:\"if-match\",HTTP2_HEADER_IF_UNMODIFIED_SINCE:\"if-unmodified-since\",HTTP2_HEADER_MAX_FORWARDS:\"max-forwards\",HTTP2_HEADER_PREFER:\"prefer\",HTTP2_HEADER_PROXY_AUTHENTICATE:\"proxy-authenticate\",HTTP2_HEADER_PROXY_AUTHORIZATION:\"proxy-authorization\",HTTP2_HEADER_REFRESH:\"refresh\",HTTP2_HEADER_RETRY_AFTER:\"retry-after\",HTTP2_HEADER_TRAILER:\"trailer\",HTTP2_HEADER_TK:\"tk\",HTTP2_HEADER_VIA:\"via\",HTTP2_HEADER_WARNING:\"warning\",HTTP2_HEADER_WWW_AUTHENTICATE:\"www-authenticate\",HTTP2_HEADER_HTTP2_SETTINGS:\"http2-settings\",HTTP2_METHOD_ACL:\"ACL\",HTTP2_METHOD_BASELINE_CONTROL:\"BASELINE-CONTROL\",HTTP2_METHOD_BIND:\"BIND\",HTTP2_METHOD_CHECKIN:\"CHECKIN\",HTTP2_METHOD_CHECKOUT:\"CHECKOUT\",HTTP2_METHOD_CONNECT:\"CONNECT\",HTTP2_METHOD_COPY:\"COPY\",HTTP2_METHOD_DELETE:\"DELETE\",HTTP2_METHOD_GET:\"GET\",HTTP2_METHOD_HEAD:\"HEAD\",HTTP2_METHOD_LABEL:\"LABEL\",HTTP2_METHOD_LINK:\"LINK\",HTTP2_METHOD_LOCK:\"LOCK\",HTTP2_METHOD_MERGE:\"MERGE\",HTTP2_METHOD_MKACTIVITY:\"MKACTIVITY\",HTTP2_METHOD_MKCALENDAR:\"MKCALENDAR\",HTTP2_METHOD_MKCOL:\"MKCOL\",HTTP2_METHOD_MKREDIRECTREF:\"MKREDIRECTREF\",HTTP2_METHOD_MKWORKSPACE:\"MKWORKSPACE\",HTTP2_METHOD_MOVE:\"MOVE\",HTTP2_METHOD_OPTIONS:\"OPTIONS\",HTTP2_METHOD_ORDERPATCH:\"ORDERPATCH\",HTTP2_METHOD_PATCH:\"PATCH\",HTTP2_METHOD_POST:\"POST\",HTTP2_METHOD_PRI:\"PRI\",HTTP2_METHOD_PROPFIND:\"PROPFIND\",HTTP2_METHOD_PROPPATCH:\"PROPPATCH\",HTTP2_METHOD_PUT:\"PUT\",HTTP2_METHOD_REBIND:\"REBIND\",HTTP2_METHOD_REPORT:\"REPORT\",HTTP2_METHOD_SEARCH:\"SEARCH\",HTTP2_METHOD_TRACE:\"TRACE\",HTTP2_METHOD_UNBIND:\"UNBIND\",HTTP2_METHOD_UNCHECKOUT:\"UNCHECKOUT\",HTTP2_METHOD_UNLINK:\"UNLINK\",HTTP2_METHOD_UNLOCK:\"UNLOCK\",HTTP2_METHOD_UPDATE:\"UPDATE\",HTTP2_METHOD_UPDATEREDIRECTREF:\"UPDATEREDIRECTREF\",HTTP2_METHOD_VERSION_CONTROL:\"VERSION-CONTROL\",HTTP_STATUS_CONTINUE:100,HTTP_STATUS_SWITCHING_PROTOCOLS:101,HTTP_STATUS_PROCESSING:102,HTTP_STATUS_EARLY_HINTS:103,HTTP_STATUS_OK:200,HTTP_STATUS_CREATED:201,HTTP_STATUS_ACCEPTED:202,HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION:203,HTTP_STATUS_NO_CONTENT:204,HTTP_STATUS_RESET_CONTENT:205,HTTP_STATUS_PARTIAL_CONTENT:206,HTTP_STATUS_MULTI_STATUS:207,HTTP_STATUS_ALREADY_REPORTED:208,HTTP_STATUS_IM_USED:226,HTTP_STATUS_MULTIPLE_CHOICES:300,HTTP_STATUS_MOVED_PERMANENTLY:301,HTTP_STATUS_FOUND:302,HTTP_STATUS_SEE_OTHER:303,HTTP_STATUS_NOT_MODIFIED:304,HTTP_STATUS_USE_PROXY:305,HTTP_STATUS_TEMPORARY_REDIRECT:307,HTTP_STATUS_PERMANENT_REDIRECT:308,HTTP_STATUS_BAD_REQUEST:400,HTTP_STATUS_UNAUTHORIZED:401,HTTP_STATUS_PAYMENT_REQUIRED:402,HTTP_STATUS_FORBIDDEN:403,HTTP_STATUS_NOT_FOUND:404,HTTP_STATUS_METHOD_NOT_ALLOWED:405,HTTP_STATUS_NOT_ACCEPTABLE:406,HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED:407,HTTP_STATUS_REQUEST_TIMEOUT:408,HTTP_STATUS_CONFLICT:409,HTTP_STATUS_GONE:410,HTTP_STATUS_LENGTH_REQUIRED:411,HTTP_STATUS_PRECONDITION_FAILED:412,HTTP_STATUS_PAYLOAD_TOO_LARGE:413,HTTP_STATUS_URI_TOO_LONG:414,HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE:415,HTTP_STATUS_RANGE_NOT_SATISFIABLE:416,HTTP_STATUS_EXPECTATION_FAILED:417,HTTP_STATUS_TEAPOT:418,HTTP_STATUS_MISDIRECTED_REQUEST:421,HTTP_STATUS_UNPROCESSABLE_ENTITY:422,HTTP_STATUS_LOCKED:423,HTTP_STATUS_FAILED_DEPENDENCY:424,HTTP_STATUS_TOO_EARLY:425,HTTP_STATUS_UPGRADE_REQUIRED:426,HTTP_STATUS_PRECONDITION_REQUIRED:428,HTTP_STATUS_TOO_MANY_REQUESTS:429,HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE:431,HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS:451,HTTP_STATUS_INTERNAL_SERVER_ERROR:500,HTTP_STATUS_NOT_IMPLEMENTED:501,HTTP_STATUS_BAD_GATEWAY:502,HTTP_STATUS_SERVICE_UNAVAILABLE:503,HTTP_STATUS_GATEWAY_TIMEOUT:504,HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED:505,HTTP_STATUS_VARIANT_ALSO_NEGOTIATES:506,HTTP_STATUS_INSUFFICIENT_STORAGE:507,HTTP_STATUS_LOOP_DETECTED:508,HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED:509,HTTP_STATUS_NOT_EXTENDED:510,HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED:511};function createServer(){throwNotImplemented(\"node:http2 createServer\",887)}function createSecureServer(){throwNotImplemented(\"node:http2 createSecureServer\",887)}function getDefaultSettings(){return{headerTableSize:4096,enablePush:!0,initialWindowSize:65535,maxFrameSize:16384,maxConcurrentStreams:4294967295,maxHeaderSize:65535,maxHeaderListSize:65535,enableConnectProtocol:!1}}function getPackedSettings(){return Buffer.alloc(0)}function getUnpackedSettings(){return Buffer.alloc(0)}const sensitiveHeaders=Symbol.for(\"nodejs.http2.sensitiveHeaders\");function Http2ServerRequest(){throwNotImplemented(\"node:http2 Http2ServerRequest\",887)}function Http2ServerResponse(){throwNotImplemented(\"node:http2 Http2ServerResponse\",887)}return $={constants,createServer,createSecureServer,getDefaultSettings,getPackedSettings,getUnpackedSettings,sensitiveHeaders,Http2ServerRequest,Http2ServerResponse,connect},hideFromStack([Http2ServerRequest,Http2ServerResponse,connect,createServer,createSecureServer,getDefaultSettings,getPackedSettings,getUnpackedSettings]),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeHttpsCode = "(function (){\"use strict\";const http=@getInternalField(@internalModuleRegistry,18)||@createInternalModuleById(18);function request(input,options,cb){if(input&&typeof input===\"object\"&&!(input instanceof URL))input.protocol\?\?=\"https:\";else if(typeof options===\"object\")options.protocol\?\?=\"https:\";return http.request(input,options,cb)}function get(input,options,cb){const req=request(input,options,cb);return req.end(),req}return{...http,get,request}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeInspectorCode = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15);function open(){throwNotImplemented(\"node:inspector open\",2445)}function close(){throwNotImplemented(\"node:inspector close\",2445)}function url(){throwNotImplemented(\"node:inspector url\",2445)}function waitForDebugger(){throwNotImplemented(\"node:inspector waitForDebugger\",2445)}class Session extends EventEmitter{constructor(){super();throwNotImplemented(\"node:inspector Session\",2445)}}return $={console:{...globalThis.console,context:{console:globalThis.console}},open,close,url,waitForDebugger,Session},hideFromStack(open,close,url,waitForDebugger,Session.prototype.constructor),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeNetCode = "(function (){\"use strict\";const{Duplex}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),IPv4Reg=new RegExp(\"^((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$\"),IPv6Reg=new RegExp(\"^((\?:(\?:[0-9a-fA-F]{1,4}):){7}(\?:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){6}(\?:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(\?:[0-9a-fA-F]{1,4})|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){5}(\?::((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,2}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){4}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,1}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,3}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){3}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,2}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,4}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){2}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,3}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,5}|:)|(\?:(\?:[0-9a-fA-F]{1,4}):){1}(\?:(:(\?:[0-9a-fA-F]{1,4})){0,4}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(\?:[0-9a-fA-F]{1,4})){1,6}|:)|(\?::((\?::(\?:[0-9a-fA-F]{1,4})){0,5}:((\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(\?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(\?::(\?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})\?$\");function isIPv4(s){return IPv4Reg.test(s)}function isIPv6(s){return IPv6Reg.test(s)}function isIP(s){if(isIPv4(s))return 4;if(isIPv6(s))return 6;return 0}const{connect:bunConnect}=Bun;var{setTimeout}=globalThis;const bunTlsSymbol=Symbol.for(\"::buntls::\"),bunSocketServerHandlers=Symbol.for(\"::bunsocket_serverhandlers::\"),bunSocketServerConnections=Symbol.for(\"::bunnetserverconnections::\"),bunSocketServerOptions=Symbol.for(\"::bunnetserveroptions::\"),bunSocketInternal=Symbol.for(\"::bunnetsocketinternal::\"),bunTLSConnectOptions=Symbol.for(\"::buntlsconnectoptions::\");var SocketClass;const Socket=function(InternalSocket){return SocketClass=InternalSocket,Object.defineProperty(SocketClass.prototype,Symbol.toStringTag,{value:\"Socket\",enumerable:!1}),Object.defineProperty(function Socket(options){return new InternalSocket(options)},Symbol.hasInstance,{value(instance){return instance instanceof InternalSocket}})}(class Socket2 extends Duplex{static#Handlers={close:Socket2.#Close,connectError(socket,error){socket.data.emit(\"error\",error)},data({data:self},buffer){self.bytesRead+=buffer.length;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(buffer))return}queue.push(buffer)},drain:Socket2.#Drain,end:Socket2.#Close,error(socket,error){const self=socket.data,callback=self.#writeCallback;if(callback)self.#writeCallback=null,callback(error);self.emit(\"error\",error)},open(socket){const self=socket.data;socket.timeout(self.timeout),socket.ref(),self[bunSocketInternal]=socket,self.connecting=!1;const options=self[bunTLSConnectOptions];if(options){const{session}=options;if(session)self.setSession(session)}if(!self.#upgraded)self.emit(\"connect\",self);Socket2.#Drain(socket)},handshake(socket,success,verifyError){const{data:self}=socket;self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self.emit(\"secure\",self);const{checkServerIdentity}=self[bunTLSConnectOptions];if(!verifyError&&typeof checkServerIdentity===\"function\"&&self.servername){const cert=self.getPeerCertificate(!0);verifyError=checkServerIdentity(self.servername,cert)}if(self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit(\"secureConnect\",verifyError)},timeout(socket){const self=socket.data;self.emit(\"timeout\",self)},binaryType:\"buffer\"};static#Close(socket){const self=socket.data;if(self.#closed)return;self.#closed=!0,self[bunSocketInternal]=null;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(null))return}queue.push(null)}static#Drain(socket){const self=socket.data,callback=self.#writeCallback;if(callback){const chunk=self.#writeChunk,written=socket.write(chunk);if(self.bytesWritten+=written,written=self.maxConnections){const data={localAddress:_socket.localAddress,localPort:_socket.localPort,localFamily:_socket.localFamily,remoteAddress:_socket.remoteAddress,remotePort:_socket.remotePort,remoteFamily:_socket.remoteFamily||\"IPv4\"};socket.end(),self.emit(\"drop\",data);return}if(!pauseOnConnect)_socket.resume();if(self[bunSocketServerConnections]++,typeof connectionListener==\"function\")if(InternalSocketClass.name===\"TLSSocket\")self.once(\"secureConnection\",()=>connectionListener(_socket));else connectionListener(_socket);self.emit(\"connection\",_socket)},handshake(socket,success,verifyError){const{data:self}=socket;if(self.emit(\"secure\",self),self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit(\"secureConnection\",verifyError)},error(socket,error){Socket2.#Handlers.error(socket,error),this.data.emit(\"error\",error)},timeout:Socket2.#Handlers.timeout,connectError:Socket2.#Handlers.connectError,drain:Socket2.#Handlers.drain,binaryType:\"buffer\"};bytesRead=0;bytesWritten=0;#closed=!1;connecting=!1;localAddress=\"127.0.0.1\";#readQueue=@createFIFO();remotePort;[bunSocketInternal]=null;[bunTLSConnectOptions]=null;timeout=0;#writeCallback;#writeChunk;#pendingRead;isServer=!1;_handle;_parent;_parentWrap;#socket;#upgraded;constructor(options){const{socket,signal,write,read,allowHalfOpen=!1,...opts}=options||{};super({...opts,allowHalfOpen,readable:!0,writable:!0});if(this._handle=this,this._parent=this,this._parentWrap=this,this.#pendingRead=void 0,this.#upgraded=!1,socket instanceof Socket2)this.#socket=socket;signal\?.once(\"abort\",()=>this.destroy()),this.once(\"connect\",()=>this.emit(\"ready\"))}address(){return{address:this.localAddress,family:this.localFamily,port:this.localPort}}get bufferSize(){return this.writableLength}#attach(port,socket){if(this.remotePort=port,socket.data=this,socket.timeout(this.timeout),socket.ref(),this[bunSocketInternal]=socket,this.connecting=!1,!this.#upgraded)this.emit(\"connect\",this);Socket2.#Drain(socket)}connect(port,host,connectListener){var path,connection=this.#socket,_checkServerIdentity=void 0;if(typeof port===\"string\"){if(path=port,port=void 0,typeof host===\"function\")connectListener=host,host=void 0}else if(typeof host==\"function\"){if(typeof port===\"string\")path=port,port=void 0;connectListener=host,host=void 0}if(typeof port==\"object\"){var{port,host,path,socket,localAddress,localPort,family,hints,lookup,noDelay,keepAlive,keepAliveInitialDelay,requestCert,rejectUnauthorized,pauseOnConnect,servername,checkServerIdentity,session}=port;if(_checkServerIdentity=checkServerIdentity,this.servername=servername,socket)connection=socket}if(!pauseOnConnect)this.resume();this.connecting=!0,this.remotePort=port;const bunTLS=this[bunTlsSymbol];var tls=void 0;if(typeof bunTLS===\"function\"){if(tls=bunTLS.call(this,port,host,!0),this._requestCert=!0,this._rejectUnauthorized=rejectUnauthorized,tls){if(tls.rejectUnauthorized=rejectUnauthorized,tls.requestCert=!0,tls.session=session||tls.session,this.servername=tls.servername,tls.checkServerIdentity=_checkServerIdentity||tls.checkServerIdentity,this[bunTLSConnectOptions]=tls,!connection&&tls.socket)connection=tls.socket}if(connection){if(typeof connection!==\"object\"||!(connection instanceof Socket2)||typeof connection[bunTlsSymbol]===\"function\")@throwTypeError(\"socket must be an instance of net.Socket\")}if(this.authorized=!1,this.secureConnecting=!0,this._secureEstablished=!1,this._securePending=!0,connectListener)this.on(\"secureConnect\",connectListener)}else if(connectListener)this.on(\"connect\",connectListener);if(connection){const socket2=connection[bunSocketInternal];if(socket2){this.connecting=!0,this.#upgraded=!0;const result=socket2.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error(\"Invalid socket\")}else connection.once(\"connect\",()=>{const socket3=connection[bunSocketInternal];if(!socket3)return;this.connecting=!0,this.#upgraded=!0;const result=socket3.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error(\"Invalid socket\")})}else if(path)bunConnect({data:this,unix:path,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit(\"error\",error)});else bunConnect({data:this,hostname:host||\"localhost\",port,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit(\"error\",error)});return this}_destroy(err,callback){this[bunSocketInternal]\?.end(),callback(err)}_final(callback){this[bunSocketInternal]\?.end(),callback()}get localAddress(){return\"127.0.0.1\"}get localFamily(){return\"IPv4\"}get localPort(){return this[bunSocketInternal]\?.localPort}get pending(){return this.connecting}_read(size){const queue=this.#readQueue;let chunk;while(chunk=queue.peek()){if(!this.push(chunk))return;queue.shift()}}get readyState(){if(this.connecting)return\"opening\";if(this.readable)return this.writable\?\"open\":\"readOnly\";else return this.writable\?\"writeOnly\":\"closed\"}ref(){this[bunSocketInternal]\?.ref()}get remoteAddress(){return this[bunSocketInternal]\?.remoteAddress}get remoteFamily(){return\"IPv4\"}resetAndDestroy(){this[bunSocketInternal]\?.end()}setKeepAlive(enable=!1,initialDelay=0){return this}setNoDelay(noDelay=!0){return this}setTimeout(timeout,callback){if(this[bunSocketInternal]\?.timeout(timeout),this.timeout=timeout,callback)this.once(\"timeout\",callback);return this}unref(){this[bunSocketInternal]\?.unref()}_write(chunk,encoding,callback){if(typeof chunk==\"string\"&&encoding!==\"ascii\")chunk=Buffer.from(chunk,encoding);var written=this[bunSocketInternal]\?.write(chunk);if(written==chunk.length)callback();else if(this.#writeCallback)callback(new Error(\"overlapping _write()\"));else{if(written>0)if(typeof chunk==\"string\")chunk=chunk.slice(written);else chunk=chunk.subarray(written);this.#writeCallback=callback,this.#writeChunk=chunk}}});function createConnection(port,host,connectListener){if(typeof port===\"object\")return new Socket(port).connect(port,host,connectListener);return new Socket().connect(port,host,connectListener)}const connect=createConnection;class Server extends EventEmitter{#server;#listening=!1;[bunSocketServerConnections]=0;[bunSocketServerOptions];maxConnections=0;constructor(options,connectionListener){super();if(typeof options===\"function\")connectionListener=options,options={};else if(options==null||typeof options===\"object\")options={...options};else throw new Error(\"bun-net-polyfill: invalid arguments\");const{maxConnections}=options;this.maxConnections=Number.isSafeInteger(maxConnections)&&maxConnections>0\?maxConnections:0,options.connectionListener=connectionListener,this[bunSocketServerOptions]=options}ref(){return this.#server\?.ref(),this}unref(){return this.#server\?.unref(),this}close(callback){if(this.#server){if(this.#server.stop(!0),this.#server=null,this.#listening=!1,this[bunSocketServerConnections]=0,this.emit(\"close\"),typeof callback===\"function\")callback();return this}if(typeof callback===\"function\"){const error=new Error(\"Server is not running\");error.code=\"ERR_SERVER_NOT_RUNNING\",callback(error)}return this}address(){const server=this.#server;if(server){const unix=server.unix;if(unix)return unix;let address=server.hostname;const type=isIP(address),port=server.port;if(typeof port===\"number\")return{port,address,family:type\?`IPv${type}`:void 0};if(type)return{address,family:type\?`IPv${type}`:void 0};return address}return null}getConnections(callback){if(typeof callback===\"function\")callback(null,this.#server\?this[bunSocketServerConnections]:0);return this}listen(port,hostname,onListen){let backlog,path,exclusive=!1;if(typeof port===\"string\"){if(Number.isSafeInteger(hostname)){if(hostname>0)backlog=hostname}else if(typeof hostname===\"function\")onListen=hostname;path=port,hostname=void 0,port=void 0}else{if(typeof hostname===\"function\")onListen=hostname,hostname=void 0;if(typeof port===\"function\")onListen=port,port=0;else if(typeof port===\"object\"){const options=port;options.signal\?.addEventListener(\"abort\",()=>this.close()),hostname=options.host,exclusive=options.exclusive===!0;const path2=options.path;if(port=options.port,!Number.isSafeInteger(port)||port<0)if(path2)hostname=path2,port=void 0;else{let message='The argument \\'options\\' must have the property \"port\" or \"path\"';try{message=`${message}. Received ${JSON.stringify(options)}`}catch{}const error=@makeTypeError(message);throw error.code=\"ERR_INVALID_ARG_VALUE\",error}else if(!Number.isSafeInteger(port)||port<0)port=0;if(typeof port.callback===\"function\")onListen=port\?.callback}else if(!Number.isSafeInteger(port)||port<0)port=0;hostname=hostname||\"::\"}try{var tls=void 0,TLSSocketClass=void 0;const bunTLS=this[bunTlsSymbol],options=this[bunSocketServerOptions];if(typeof bunTLS===\"function\")[tls,TLSSocketClass]=bunTLS.call(this,port,hostname,!1),options.servername=tls.serverName,options.InternalSocketClass=TLSSocketClass;else options.InternalSocketClass=SocketClass;this.#server=Bun.listen(path\?{exclusive,unix:path,tls,socket:SocketClass[bunSocketServerHandlers]}:{exclusive,port,hostname,tls,socket:SocketClass[bunSocketServerHandlers]}),this.#server.data=this,this.#listening=!0,setTimeout(emitListeningNextTick,1,this,onListen)}catch(err){this.#listening=!1,setTimeout(emitErrorNextTick,1,this,err)}return this}}function emitErrorNextTick(self,error){self.emit(\"error\",error)}function emitListeningNextTick(self,onListen){if(typeof onListen===\"function\")try{onListen()}catch(err){self.emit(\"error\",err)}self.emit(\"listening\")}function createServer(options,connectionListener){return new Server(options,connectionListener)}return{createServer,Server,createConnection,connect,isIP,isIPv4,isIPv6,Socket,[Symbol.for(\"::bunternal::\")]:SocketClass}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeOSCode = "(function (){\"use strict\";var tmpdir=function(){var env=Bun.env;return tmpdir=function(){var path=env.TMPDIR||env.TMP||env.TEMP||\"/tmp\";const length=path.length;if(length>1&&path[length-1]===\"/\")path=path.slice(0,-1);return path},tmpdir()};function lazyCpus({cpus}){return()=>{const array=new Array(navigator.hardwareConcurrency);function populate(){const results=cpus(),length=results.length;array.length=length;for(let i=0;i= 0x80 (not a basic code point)\",\"invalid-input\":\"Invalid input\"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;function error(type){@throwRangeError(errors[type])}function map(array,callback){const result=[];let length=array.length;while(length--)result[length]=callback(array[length]);return result}function mapDomain(domain,callback){const parts=domain.split(\"@\");let result=\"\";if(parts.length>1)result=parts[0]+\"@\",domain=parts[1];domain=domain.replace(regexSeparators,\".\");const labels=domain.split(\".\"),encoded=map(labels,callback).join(\".\");return result+encoded}function ucs2decode(string){const output=[];let counter=0;const length=string.length;while(counter=55296&&value<=56319&&counterString.fromCodePoint(...codePoints),basicToDigit=function(codePoint){if(codePoint>=48&&codePoint<58)return 26+(codePoint-48);if(codePoint>=65&&codePoint<91)return codePoint-65;if(codePoint>=97&&codePoint<123)return codePoint-97;return base},digitToBasic=function(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)},adapt=function(delta,numPoints,firstTime){let k=0;delta=firstTime\?floor(delta/damp):delta>>1,delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base)delta=floor(delta/baseMinusTMin);return floor(k+(baseMinusTMin+1)*delta/(delta+skew))},decode=function(input){const output=[],inputLength=input.length;let i=0,n=initialN,bias=initialBias,basic=input.lastIndexOf(delimiter);if(basic<0)basic=0;for(let j=0;j=128)error(\"not-basic\");output.push(input.charCodeAt(j))}for(let index=basic>0\?basic+1:0;index=inputLength)error(\"invalid-input\");const digit=basicToDigit(input.charCodeAt(index++));if(digit>=base)error(\"invalid-input\");if(digit>floor((maxInt-i)/w))error(\"overflow\");i+=digit*w;const t=k<=bias\?tMin:k>=bias+tMax\?tMax:k-bias;if(digitfloor(maxInt/baseMinusT))error(\"overflow\");w*=baseMinusT}const out=output.length+1;if(bias=adapt(i-oldi,out,oldi==0),floor(i/out)>maxInt-n)error(\"overflow\");n+=floor(i/out),i%=out,output.splice(i++,0,n)}return String.fromCodePoint(...output)},encode=function(input){const output=[];input=ucs2decode(input);const inputLength=input.length;let n=initialN,delta=0,bias=initialBias;for(let currentValue of input)if(currentValue<128)output.push(stringFromCharCode(currentValue));const basicLength=output.length;let handledCPCount=basicLength;if(basicLength)output.push(delimiter);while(handledCPCount=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne))error(\"overflow\");delta+=(m-n)*handledCPCountPlusOne,n=m;for(let currentValue of input){if(currentValuemaxInt)error(\"overflow\");if(currentValue===n){let q=delta;for(let k=base;;k+=base){const t=k<=bias\?tMin:k>=bias+tMax\?tMax:k-bias;if(q()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports),Buffer=@requireNativeModule(\"node:buffer\").Buffer,require_object_keys=__commonJS((exports,module)=>{var objectKeys=Object.keys||function(){var hasOwnProperty=Object.prototype.hasOwnProperty,hasDontEnumBug=!{toString:null}.propertyIsEnumerable(\"toString\"),dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;return function(obj){if(typeof obj!==\"function\"&&(typeof obj!==\"object\"||obj===null))@throwTypeError(\"Object.keys called on non-object\");var result=[],prop,i;for(prop in obj)if(hasOwnProperty.call(obj,prop))result.push(prop);if(hasDontEnumBug){for(i=0;i{var ParsedQueryString=function(){},unescapeBuffer=function(s,decodeSpaces){var out=Buffer.allocUnsafe(s.length),state=0,n,m,hexchar,c;for(var inIndex=0,outIndex=0;;inIndex++){if(inIndex0){if(out[outIndex++]=37,state===2)out[outIndex++]=hexchar}break}switch(state){case 0:switch(c){case 37:n=0,m=0,state=1;break;case 43:if(decodeSpaces)c=32;default:out[outIndex++]=c;break}break;case 1:if(hexchar=c,n=unhexTable[c],!(n>=0)){out[outIndex++]=37,out[outIndex++]=c,state=0;break}state=2;break;case 2:if(state=0,m=unhexTable[c],!(m>=0)){out[outIndex++]=37,out[outIndex++]=hexchar,out[outIndex++]=c;break}out[outIndex++]=16*n+m;break}}return out.slice(0,outIndex)},qsUnescape=function(s,decodeSpaces){try{return decodeURIComponent(s)}catch(e){return QueryString.unescapeBuffer(s,decodeSpaces).toString()}},qsEscape=function(str){if(typeof str!==\"string\")if(typeof str===\"object\")str=String(str);else str+=\"\";var out=\"\",lastPos=0;for(var i2=0;i2>6]+hexTable[128|c&63];continue}if(c<55296||c>=57344){lastPos=i2+1,out+=hexTable[224|c>>12]+hexTable[128|c>>6&63]+hexTable[128|c&63];continue}++i2;var c2;if(i2>18]+hexTable[128|c>>12&63]+hexTable[128|c>>6&63]+hexTable[128|c&63]}if(lastPos===0)return str;if(lastPos0\?options.maxKeys:-1;var decode=QueryString.unescape;if(options&&typeof options.decodeURIComponent===\"function\")decode=options.decodeURIComponent;const customDecode=decode!==qsUnescape,keys=[];var posIdx=0,lastPos=0,sepIdx=0,eqIdx=0,key=\"\",value=\"\",keyEncoded=customDecode,valEncoded=customDecode,encodeCheck=0;for(var i2=0;i2sepLen||i2===0)if(indexOf(keys,key)===-1)obj[key]=value,keys[keys.length]=key;else{const curValue=obj[key]||\"\";if(curValue.pop)curValue[curValue.length]=value;else if(curValue)obj[key]=[curValue,value]}else if(i2===1)delete obj[key];if(--pairs===0)break;keyEncoded=valEncoded=customDecode,encodeCheck=0,key=value=\"\",posIdx=lastPos,lastPos=i2+1,sepIdx=eqIdx=0}continue}else if(sepIdx=0,!valEncoded)if(code===37)encodeCheck=1;else if(encodeCheck>0&&(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){if(++encodeCheck===3)valEncoded=!0}else encodeCheck=0;if(eqIdx0&&(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)){if(++encodeCheck===3)keyEncoded=!0}else encodeCheck=0}if(code===43){if(eqIdx0)){if(lastPosObject.prototype.toString.call(arg)===\"[object Array]\",indexOf=(arr,searchElement,fromIndex)=>{var k;if(arr==null)@throwTypeError('\"arr\" is null or not defined');var o=Object(arr),len=o.length>>>0;if(len===0)return-1;var n=fromIndex|0;if(n>=len)return-1;k=Math.max(n>=0\?n:len-Math.abs(n),0);while(k{},SymbolAsyncIterator=Symbol.asyncIterator,SymbolIterator=Symbol.iterator,SymbolFor=Symbol.for,SymbolReplace=Symbol.replace,ArrayFrom=Array.from,ArrayIsArray=Array.isArray,ArrayPrototypeFilter=Array.prototype.filter,ArrayPrototypeSort=Array.prototype.sort,ArrayPrototypeIndexOf=Array.prototype.indexOf,ArrayPrototypeJoin=Array.prototype.join,ArrayPrototypeMap=Array.prototype.map,ArrayPrototypePop=Array.prototype.pop,ArrayPrototypePush=Array.prototype.push,ArrayPrototypeSlice=Array.prototype.slice,ArrayPrototypeSplice=Array.prototype.splice,ArrayPrototypeReverse=Array.prototype.reverse,ArrayPrototypeShift=Array.prototype.shift,ArrayPrototypeUnshift=Array.prototype.unshift,RegExpPrototypeExec=RegExp.prototype.exec,RegExpPrototypeSymbolReplace=RegExp.prototype[SymbolReplace],StringFromCharCode=String.fromCharCode,StringPrototypeCharCodeAt=String.prototype.charCodeAt,StringPrototypeCodePointAt=String.prototype.codePointAt,StringPrototypeSlice=String.prototype.slice,StringPrototypeToLowerCase=String.prototype.toLowerCase,StringPrototypeEndsWith=String.prototype.endsWith,StringPrototypeRepeat=String.prototype.repeat,StringPrototypeStartsWith=String.prototype.startsWith,StringPrototypeTrim=String.prototype.trim,StringPrototypeNormalize=String.prototype.normalize,NumberIsNaN=Number.isNaN,NumberIsFinite=Number.isFinite,NumberIsInteger=Number.isInteger,NumberMAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER=Number.MIN_SAFE_INTEGER,MathCeil=Math.ceil,MathFloor=Math.floor,MathMax=Math.max,MathMaxApply=Math.max.apply,DateNow=Date.now,FunctionPrototype=Function.prototype,StringPrototype=String.prototype,StringPrototypeSymbolIterator=StringPrototype[SymbolIterator],StringIteratorPrototypeNext=StringPrototypeSymbolIterator.call(\"\").next,ObjectSetPrototypeOf=Object.setPrototypeOf,ObjectDefineProperty=Object.defineProperty,ObjectDefineProperties=Object.defineProperties,ObjectFreeze=Object.freeze,ObjectAssign=Object.assign,ObjectCreate=Object.create,ObjectKeys=Object.keys,ObjectSeal=Object.seal,createSafeIterator=(factory,next)=>{class SafeIterator{#iterator;constructor(iterable){this.#iterator=factory.call(iterable)}next(){return next.call(this.#iterator)}[SymbolIterator](){return this}}return ObjectSetPrototypeOf(SafeIterator.prototype,null),ObjectFreeze(SafeIterator.prototype),ObjectFreeze(SafeIterator),SafeIterator},SafeStringIterator=createSafeIterator(StringPrototypeSymbolIterator,StringIteratorPrototypeNext),isFullWidthCodePoint=(code)=>{return code>=4352&&(code<=4447||code===9001||code===9002||code>=11904&&code<=12871&&code!==12351||code>=12880&&code<=19903||code>=19968&&code<=42182||code>=43360&&code<=43388||code>=44032&&code<=55203||code>=63744&&code<=64255||code>=65040&&code<=65049||code>=65072&&code<=65131||code>=65281&&code<=65376||code>=65504&&code<=65510||code>=110592&&code<=110593||code>=127488&&code<=127569||code>=127744&&code<=128591||code>=131072&&code<=262141)},isZeroWidthCodePoint=(code)=>{return code<=31||code>=127&&code<=159||code>=768&&code<=879||code>=8203&&code<=8207||code>=8400&&code<=8447||code>=65024&&code<=65039||code>=65056&&code<=65071||code>=917760&&code<=917999},getStringWidth=function getStringWidth(str,removeControlChars=!0){var width=0;if(removeControlChars)str=stripVTControlCharacters(str);str=StringPrototypeNormalize.call(str,\"NFC\");for(var char of new SafeStringIterator(str)){var code=StringPrototypeCodePointAt.call(char,0);if(isFullWidthCodePoint(code))width+=2;else if(!isZeroWidthCodePoint(code))width++}return width},ansiPattern=\"[\\\\u001B\\\\u009B][[\\\\]()#;\?]*(\?:(\?:(\?:(\?:;[-a-zA-Z\\\\d\\\\/#&.:=\?%@~_]+)*|[a-zA-Z\\\\d]+(\?:;[-a-zA-Z\\\\d\\\\/#&.:=\?%@~_]*)*)\?\\\\u0007)|(\?:(\?:\\\\d{1,4}(\?:;\\\\d{0,4})*)\?[\\\\dA-PR-TZcf-ntqry=><~]))\",ansi=new RegExp(ansiPattern,\"g\");function stripVTControlCharacters(str){return validateString(str,\"str\"),RegExpPrototypeSymbolReplace.call(ansi,str,\"\")}var kCustomPromisifiedSymbol=SymbolFor(\"nodejs.util.promisify.custom\"),kCustomPromisifyArgsSymbol=Symbol(\"customPromisifyArgs\");function promisify(original){if(validateFunction(original,\"original\"),original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];return validateFunction(fn,\"util.promisify.custom\"),ObjectDefineProperty(fn,kCustomPromisifiedSymbol,{__proto__:null,value:fn,enumerable:!1,writable:!1,configurable:!0})}var argumentNames=original[kCustomPromisifyArgsSymbol];function fn(...args){return new Promise((resolve,reject)=>{ArrayPrototypePush.call(args,(err,...values)=>{if(err)return reject(err);if(argumentNames!==void 0&&values.length>1){var obj={};for(var i2=0;i2max)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}function validateUint32(value,name,positive=!1){if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE(name,\"number\",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);var min=positive\?1:0,max=4294967295;if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}function CSI(strings,...args){var ret=`${kEscape}[`;for(var n=0;n1&&StringPrototypeCodePointAt.call(str,i-2)>=kUTF16SurrogateThreshold||StringPrototypeCodePointAt.call(str,i-1)>=kUTF16SurrogateThreshold)return 2;return 1}function charLengthAt(str,i){if(str.length<=i)return 1;return StringPrototypeCodePointAt.call(str,i)>=kUTF16SurrogateThreshold\?2:1}function*emitKeys(stream){while(!0){var ch=yield,s=ch,escaped=!1,keySeq=null,keyName,keyCtrl2=!1,keyMeta=!1,keyShift=!1;if(ch===kEscape){if(escaped=!0,s+=ch=yield,ch===kEscape)s+=ch=yield}if(escaped&&(ch===\"O\"||ch===\"[\")){var code=ch,modifier=0;if(ch===\"O\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")modifier=(ch>>0)-1,s+=ch=yield;code+=ch}else if(ch===\"[\"){if(s+=ch=yield,ch===\"[\")code+=ch,s+=ch=yield;var cmdStart=s.length-1;if(ch>=\"0\"&&ch<=\"9\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")s+=ch=yield}if(ch===\";\"){if(s+=ch=yield,ch>=\"0\"&&ch<=\"9\")s+=yield}var cmd=StringPrototypeSlice.call(s,cmdStart),match;if(match=RegExpPrototypeExec.call(/^(\\d\\d\?)(;(\\d))\?([~^$])$/,cmd))code+=match[1]+match[4],modifier=(match[3]||1)-1;else if(match=RegExpPrototypeExec.call(/^((\\d;)\?(\\d))\?([A-Za-z])$/,cmd))code+=match[4],modifier=(match[3]||1)-1;else code+=cmd}switch(keyCtrl2=!!(modifier&4),keyMeta=!!(modifier&10),keyShift=!!(modifier&1),code){case\"[P\":keyName=\"f1\";break;case\"[Q\":keyName=\"f2\";break;case\"[R\":keyName=\"f3\";break;case\"[S\":keyName=\"f4\";break;case\"OP\":keyName=\"f1\";break;case\"OQ\":keyName=\"f2\";break;case\"OR\":keyName=\"f3\";break;case\"OS\":keyName=\"f4\";break;case\"[11~\":keyName=\"f1\";break;case\"[12~\":keyName=\"f2\";break;case\"[13~\":keyName=\"f3\";break;case\"[14~\":keyName=\"f4\";break;case\"[[A\":keyName=\"f1\";break;case\"[[B\":keyName=\"f2\";break;case\"[[C\":keyName=\"f3\";break;case\"[[D\":keyName=\"f4\";break;case\"[[E\":keyName=\"f5\";break;case\"[15~\":keyName=\"f5\";break;case\"[17~\":keyName=\"f6\";break;case\"[18~\":keyName=\"f7\";break;case\"[19~\":keyName=\"f8\";break;case\"[20~\":keyName=\"f9\";break;case\"[21~\":keyName=\"f10\";break;case\"[23~\":keyName=\"f11\";break;case\"[24~\":keyName=\"f12\";break;case\"[A\":keyName=\"up\";break;case\"[B\":keyName=\"down\";break;case\"[C\":keyName=\"right\";break;case\"[D\":keyName=\"left\";break;case\"[E\":keyName=\"clear\";break;case\"[F\":keyName=\"end\";break;case\"[H\":keyName=\"home\";break;case\"OA\":keyName=\"up\";break;case\"OB\":keyName=\"down\";break;case\"OC\":keyName=\"right\";break;case\"OD\":keyName=\"left\";break;case\"OE\":keyName=\"clear\";break;case\"OF\":keyName=\"end\";break;case\"OH\":keyName=\"home\";break;case\"[1~\":keyName=\"home\";break;case\"[2~\":keyName=\"insert\";break;case\"[3~\":keyName=\"delete\";break;case\"[4~\":keyName=\"end\";break;case\"[5~\":keyName=\"pageup\";break;case\"[6~\":keyName=\"pagedown\";break;case\"[[5~\":keyName=\"pageup\";break;case\"[[6~\":keyName=\"pagedown\";break;case\"[7~\":keyName=\"home\";break;case\"[8~\":keyName=\"end\";break;case\"[a\":keyName=\"up\",keyShift=!0;break;case\"[b\":keyName=\"down\",keyShift=!0;break;case\"[c\":keyName=\"right\",keyShift=!0;break;case\"[d\":keyName=\"left\",keyShift=!0;break;case\"[e\":keyName=\"clear\",keyShift=!0;break;case\"[2$\":keyName=\"insert\",keyShift=!0;break;case\"[3$\":keyName=\"delete\",keyShift=!0;break;case\"[5$\":keyName=\"pageup\",keyShift=!0;break;case\"[6$\":keyName=\"pagedown\",keyShift=!0;break;case\"[7$\":keyName=\"home\",keyShift=!0;break;case\"[8$\":keyName=\"end\",keyShift=!0;break;case\"Oa\":keyName=\"up\",keyCtrl2=!0;break;case\"Ob\":keyName=\"down\",keyCtrl2=!0;break;case\"Oc\":keyName=\"right\",keyCtrl2=!0;break;case\"Od\":keyName=\"left\",keyCtrl2=!0;break;case\"Oe\":keyName=\"clear\",keyCtrl2=!0;break;case\"[2^\":keyName=\"insert\",keyCtrl2=!0;break;case\"[3^\":keyName=\"delete\",keyCtrl2=!0;break;case\"[5^\":keyName=\"pageup\",keyCtrl2=!0;break;case\"[6^\":keyName=\"pagedown\",keyCtrl2=!0;break;case\"[7^\":keyName=\"home\",keyCtrl2=!0;break;case\"[8^\":keyName=\"end\",keyCtrl2=!0;break;case\"[Z\":keyName=\"tab\",keyShift=!0;break;default:keyName=\"undefined\";break}}else if(ch===\"\\r\")keyName=\"return\",keyMeta=escaped;else if(ch===\"\\n\")keyName=\"enter\",keyMeta=escaped;else if(ch===\"\\t\")keyName=\"tab\",keyMeta=escaped;else if(ch===\"\\b\"||ch===\"\\x7F\")keyName=\"backspace\",keyMeta=escaped;else if(ch===kEscape)keyName=\"escape\",keyMeta=escaped;else if(ch===\" \")keyName=\"space\",keyMeta=escaped;else if(!escaped&&ch<=\"\\x1A\")keyName=StringFromCharCode(StringPrototypeCharCodeAt.call(ch)+StringPrototypeCharCodeAt.call(\"a\")-1),keyCtrl2=!0;else if(RegExpPrototypeExec.call(/^[0-9A-Za-z]$/,ch)!==null)keyName=StringPrototypeToLowerCase.call(ch),keyShift=RegExpPrototypeExec.call(/^[A-Z]$/,ch)!==null,keyMeta=escaped;else if(escaped)keyName=ch.length\?void 0:\"escape\",keyMeta=!0;if(keySeq=s,s.length!==0&&(keyName!==void 0||escaped))stream.emit(\"keypress\",escaped\?void 0:s,{sequence:keySeq,name:keyName,ctrl:keyCtrl2,meta:keyMeta,shift:keyShift});else if(charLengthAt(s,0)===s.length)stream.emit(\"keypress\",s,{sequence:keySeq,name:keyName,ctrl:keyCtrl2,meta:keyMeta,shift:keyShift})}}function commonPrefix(strings){if(strings.length===0)return\"\";if(strings.length===1)return strings[0];var sorted=ArrayPrototypeSort.call(ArrayPrototypeSlice.call(strings)),min=sorted[0],max=sorted[sorted.length-1];for(var i=0;i0)data+=CSI`${dx}C`;if(dy<0)data+=CSI`${-dy}A`;else if(dy>0)data+=CSI`${dy}B`;return stream.write(data,callback)}function clearLine(stream,dir,callback){if(callback!==void 0)validateFunction(callback,\"callback\");if(stream===null||stream===void 0){if(typeof callback===\"function\")process.nextTick(callback,null);return!0}var type=dir<0\?kClearToLineBeginning:dir>0\?kClearToLineEnd:kClearLine;return stream.write(type,callback)}function clearScreenDown(stream,callback){if(callback!==void 0)validateFunction(callback,\"callback\");if(stream===null||stream===void 0){if(typeof callback===\"function\")process.nextTick(callback,null);return!0}return stream.write(kClearScreenDown,callback)}var KEYPRESS_DECODER=Symbol(\"keypress-decoder\"),ESCAPE_DECODER=Symbol(\"escape-decoder\"),ESCAPE_CODE_TIMEOUT=500;function emitKeypressEvents(stream,iface={}){if(stream[KEYPRESS_DECODER])return;stream[KEYPRESS_DECODER]=new StringDecoder(\"utf8\"),stream[ESCAPE_DECODER]=emitKeys(stream),stream[ESCAPE_DECODER].next();var triggerEscape=()=>stream[ESCAPE_DECODER].next(\"\"),{escapeCodeTimeout=ESCAPE_CODE_TIMEOUT}=iface,timeoutId;function onData2(input){if(stream.listenerCount(\"keypress\")>0){var string=stream[KEYPRESS_DECODER].write(input);if(string){clearTimeout(timeoutId),iface[kSawKeyPress]=charLengthAt(string,0)===string.length,iface.isCompletionEnabled=!1;var length=0;for(var character of new SafeStringIterator(string)){if(length+=character.length,length===string.length)iface.isCompletionEnabled=!0;try{if(stream[ESCAPE_DECODER].next(character),length===string.length&&character===kEscape)timeoutId=setTimeout(triggerEscape,escapeCodeTimeout)}catch(err){throw stream[ESCAPE_DECODER]=emitKeys(stream),stream[ESCAPE_DECODER].next(),err}}}}else stream.removeListener(\"data\",onData2),stream.on(\"newListener\",onNewListener)}function onNewListener(event){if(event===\"keypress\")stream.on(\"data\",onData2),stream.removeListener(\"newListener\",onNewListener)}if(stream.listenerCount(\"keypress\")>0)stream.on(\"data\",onData2);else stream.on(\"newListener\",onNewListener)}var kEmptyObject=ObjectFreeze(ObjectCreate(null)),kHistorySize=30,kMaxUndoRedoStackSize=2048,kMincrlfDelay=100,lineEnding=/\\r\?\\n|\\r(\?!\\n)/g,kMaxLengthOfKillRing=32,kLineObjectStream=Symbol(\"line object stream\"),kQuestionCancel=Symbol(\"kQuestionCancel\"),kQuestion=Symbol(\"kQuestion\"),kAddHistory=Symbol(\"_addHistory\"),kBeforeEdit=Symbol(\"_beforeEdit\"),kDecoder=Symbol(\"_decoder\"),kDeleteLeft=Symbol(\"_deleteLeft\"),kDeleteLineLeft=Symbol(\"_deleteLineLeft\"),kDeleteLineRight=Symbol(\"_deleteLineRight\"),kDeleteRight=Symbol(\"_deleteRight\"),kDeleteWordLeft=Symbol(\"_deleteWordLeft\"),kDeleteWordRight=Symbol(\"_deleteWordRight\"),kGetDisplayPos=Symbol(\"_getDisplayPos\"),kHistoryNext=Symbol(\"_historyNext\"),kHistoryPrev=Symbol(\"_historyPrev\"),kInsertString=Symbol(\"_insertString\"),kLine=Symbol(\"_line\"),kLine_buffer=Symbol(\"_line_buffer\"),kKillRing=Symbol(\"_killRing\"),kKillRingCursor=Symbol(\"_killRingCursor\"),kMoveCursor=Symbol(\"_moveCursor\"),kNormalWrite=Symbol(\"_normalWrite\"),kOldPrompt=Symbol(\"_oldPrompt\"),kOnLine=Symbol(\"_onLine\"),kPreviousKey=Symbol(\"_previousKey\"),kPrompt=Symbol(\"_prompt\"),kPushToKillRing=Symbol(\"_pushToKillRing\"),kPushToUndoStack=Symbol(\"_pushToUndoStack\"),kQuestionCallback=Symbol(\"_questionCallback\"),kRedo=Symbol(\"_redo\"),kRedoStack=Symbol(\"_redoStack\"),kRefreshLine=Symbol(\"_refreshLine\"),kSawKeyPress=Symbol(\"_sawKeyPress\"),kSawReturnAt=Symbol(\"_sawReturnAt\"),kSetRawMode=Symbol(\"_setRawMode\"),kTabComplete=Symbol(\"_tabComplete\"),kTabCompleter=Symbol(\"_tabCompleter\"),kTtyWrite=Symbol(\"_ttyWrite\"),kUndo=Symbol(\"_undo\"),kUndoStack=Symbol(\"_undoStack\"),kWordLeft=Symbol(\"_wordLeft\"),kWordRight=Symbol(\"_wordRight\"),kWriteToOutput=Symbol(\"_writeToOutput\"),kYank=Symbol(\"_yank\"),kYanking=Symbol(\"_yanking\"),kYankPop=Symbol(\"_yankPop\"),kFirstEventParam=Symbol(\"nodejs.kFirstEventParam\"),kOnSelfCloseWithTerminal=Symbol(\"_onSelfCloseWithTerminal\"),kOnSelfCloseWithoutTerminal=Symbol(\"_onSelfCloseWithoutTerminal\"),kOnKeyPress=Symbol(\"_onKeyPress\"),kOnError=Symbol(\"_onError\"),kOnData=Symbol(\"_onData\"),kOnEnd=Symbol(\"_onEnd\"),kOnTermEnd=Symbol(\"_onTermEnd\"),kOnResize=Symbol(\"_onResize\");function onSelfCloseWithTerminal(){var input=this.input,output=this.output;if(!input)throw new Error(\"Input not set, invalid state for readline!\");if(input.removeListener(\"keypress\",this[kOnKeyPress]),input.removeListener(\"error\",this[kOnError]),input.removeListener(\"end\",this[kOnTermEnd]),output!==null&&output!==void 0)output.removeListener(\"resize\",this[kOnResize])}function onSelfCloseWithoutTerminal(){var input=this.input;if(!input)throw new Error(\"Input not set, invalid state for readline!\");input.removeListener(\"data\",this[kOnData]),input.removeListener(\"error\",this[kOnError]),input.removeListener(\"end\",this[kOnEnd])}function onError(err){this.emit(\"error\",err)}function onData(data){debug(\"onData\"),this[kNormalWrite](data)}function onEnd(){if(debug(\"onEnd\"),typeof this[kLine_buffer]===\"string\"&&this[kLine_buffer].length>0)this.emit(\"line\",this[kLine_buffer]);this.close()}function onTermEnd(){if(debug(\"onTermEnd\"),typeof this.line===\"string\"&&this.line.length>0)this.emit(\"line\",this.line);this.close()}function onKeyPress(s,key){if(this[kTtyWrite](s,key),key&&key.sequence){var ch=StringPrototypeCodePointAt.call(key.sequence,0);if(ch>=55296&&ch<=57343)this[kRefreshLine]()}}function onResize(){this[kRefreshLine]()}function InterfaceConstructor(input,output,completer,terminal){if(!(this instanceof InterfaceConstructor))return new InterfaceConstructor(input,output,completer,terminal);EventEmitter.call(this),this[kOnSelfCloseWithoutTerminal]=onSelfCloseWithoutTerminal.bind(this),this[kOnSelfCloseWithTerminal]=onSelfCloseWithTerminal.bind(this),this[kOnError]=onError.bind(this),this[kOnData]=onData.bind(this),this[kOnEnd]=onEnd.bind(this),this[kOnTermEnd]=onTermEnd.bind(this),this[kOnKeyPress]=onKeyPress.bind(this),this[kOnResize]=onResize.bind(this),this[kSawReturnAt]=0,this.isCompletionEnabled=!0,this[kSawKeyPress]=!1,this[kPreviousKey]=null,this.escapeCodeTimeout=ESCAPE_CODE_TIMEOUT,this.tabSize=8;var history,historySize,removeHistoryDuplicates=!1,crlfDelay,prompt=\"> \",signal;if(input\?.input){output=input.output,completer=input.completer,terminal=input.terminal,history=input.history,historySize=input.historySize,signal=input.signal;var tabSize=input.tabSize;if(tabSize!==void 0)validateUint32(tabSize,\"tabSize\",!0),this.tabSize=tabSize;removeHistoryDuplicates=input.removeHistoryDuplicates;var inputPrompt=input.prompt;if(inputPrompt!==void 0)prompt=inputPrompt;var inputEscapeCodeTimeout=input.escapeCodeTimeout;if(inputEscapeCodeTimeout!==void 0)if(NumberIsFinite(inputEscapeCodeTimeout))this.escapeCodeTimeout=inputEscapeCodeTimeout;else throw new ERR_INVALID_ARG_VALUE(\"input.escapeCodeTimeout\",this.escapeCodeTimeout);if(signal)validateAbortSignal(signal,\"options.signal\");crlfDelay=input.crlfDelay,input=input.input}if(completer!==void 0&&typeof completer!==\"function\")throw new ERR_INVALID_ARG_VALUE(\"completer\",completer);if(history===void 0)history=[];else validateArray(history,\"history\");if(historySize===void 0)historySize=kHistorySize;if(typeof historySize!==\"number\"||NumberIsNaN(historySize)||historySize<0)throw new ERR_INVALID_ARG_VALUE(\"historySize\",historySize);if(terminal===void 0&&!(output===null||output===void 0))terminal=!!output.isTTY;if(this.line=\"\",this[kSubstringSearch]=null,this.output=output,this.input=input,this[kUndoStack]=[],this[kRedoStack]=[],this.history=history,this.historySize=historySize,this[kKillRing]=[],this[kKillRingCursor]=0,this.removeHistoryDuplicates=!!removeHistoryDuplicates,this.crlfDelay=crlfDelay\?MathMax(kMincrlfDelay,crlfDelay):kMincrlfDelay,this.completer=completer,this.setPrompt(prompt),this.terminal=!!terminal,this[kLineObjectStream]=void 0,input.on(\"error\",this[kOnError]),!this.terminal)input.on(\"data\",this[kOnData]),input.on(\"end\",this[kOnEnd]),this.once(\"close\",this[kOnSelfCloseWithoutTerminal]),this[kDecoder]=new StringDecoder(\"utf8\");else{if(emitKeypressEvents(input,this),input.on(\"keypress\",this[kOnKeyPress]),input.on(\"end\",this[kOnTermEnd]),this[kSetRawMode](!0),this.terminal=!0,this.cursor=0,this.historyIndex=-1,output!==null&&output!==void 0)output.on(\"resize\",this[kOnResize]);this.once(\"close\",this[kOnSelfCloseWithTerminal])}if(signal){var onAborted=(()=>this.close()).bind(this);if(signal.aborted)process.nextTick(onAborted);else signal.addEventListener(\"abort\",onAborted,{once:!0}),this.once(\"close\",()=>signal.removeEventListener(\"abort\",onAborted))}this.line=\"\",input.resume()}InterfaceConstructor.prototype={},ObjectSetPrototypeOf(InterfaceConstructor.prototype,EventEmitter.prototype);var _Interface=class Interface2 extends InterfaceConstructor{constructor(input,output,completer,terminal){super(input,output,completer,terminal)}get columns(){var output=this.output;if(output&&output.columns)return output.columns;return Infinity}setPrompt(prompt){this[kPrompt]=prompt}getPrompt(){return this[kPrompt]}[kSetRawMode](mode){var input=this.input,{setRawMode,wasInRawMode}=input;return debug(\"setRawMode\",mode,\"set!\"),wasInRawMode}prompt(preserveCursor){if(this.paused)this.resume();if(this.terminal&&process.env.TERM!==\"dumb\"){if(!preserveCursor)this.cursor=0;this[kRefreshLine]()}else this[kWriteToOutput](this[kPrompt])}[kQuestion](query,cb){if(this.closed)throw new ERR_USE_AFTER_CLOSE(\"readline\");if(this[kQuestionCallback])this.prompt();else this[kOldPrompt]=this[kPrompt],this.setPrompt(query),this[kQuestionCallback]=cb,this.prompt()}[kOnLine](line){if(this[kQuestionCallback]){var cb=this[kQuestionCallback];this[kQuestionCallback]=null,this.setPrompt(this[kOldPrompt]),cb(line)}else this.emit(\"line\",line)}[kBeforeEdit](oldText,oldCursor){this[kPushToUndoStack](oldText,oldCursor)}[kQuestionCancel](){if(this[kQuestionCallback])this[kQuestionCallback]=null,this.setPrompt(this[kOldPrompt]),this.clearLine()}[kWriteToOutput](stringToWrite){if(validateString(stringToWrite,\"stringToWrite\"),this.output!==null&&this.output!==void 0)this.output.write(stringToWrite)}[kAddHistory](){if(this.line.length===0)return\"\";if(this.historySize===0)return this.line;if(StringPrototypeTrim.call(this.line).length===0)return this.line;if(this.history.length===0||this.history[0]!==this.line){if(this.removeHistoryDuplicates){var dupIndex=ArrayPrototypeIndexOf.call(this.history,this.line);if(dupIndex!==-1)ArrayPrototypeSplice.call(this.history,dupIndex,1)}if(ArrayPrototypeUnshift.call(this.history,this.line),this.history.length>this.historySize)ArrayPrototypePop.call(this.history)}this.historyIndex=-1;var line=this.history[0];return this.emit(\"history\",this.history),line}[kRefreshLine](){var line=this[kPrompt]+this.line,dispPos=this[kGetDisplayPos](line),lineCols=dispPos.cols,lineRows=dispPos.rows,cursorPos=this.getCursorPos(),prevRows=this.prevRows||0;if(prevRows>0)moveCursor(this.output,0,-prevRows);if(cursorTo(this.output,0),clearScreenDown(this.output),this[kWriteToOutput](line),lineCols===0)this[kWriteToOutput](\" \");cursorTo(this.output,cursorPos.cols);var diff=lineRows-cursorPos.rows;if(diff>0)moveCursor(this.output,0,-diff);this.prevRows=cursorPos.rows}close(){if(this.closed)return;if(this.pause(),this.terminal)this[kSetRawMode](!1);this.closed=!0,this.emit(\"close\")}pause(){if(this.paused)return;return this.input.pause(),this.paused=!0,this.emit(\"pause\"),this}resume(){if(!this.paused)return;return this.input.resume(),this.paused=!1,this.emit(\"resume\"),this}write(d,key){if(this.paused)this.resume();if(this.terminal)this[kTtyWrite](d,key);else this[kNormalWrite](d)}[kNormalWrite](b){if(b===void 0)return;var string=this[kDecoder].write(b);if(this[kSawReturnAt]&&DateNow()-this[kSawReturnAt]<=this.crlfDelay){if(StringPrototypeCodePointAt.call(string)===10)string=StringPrototypeSlice.call(string,1);this[kSawReturnAt]=0}var newPartContainsEnding=RegExpPrototypeExec.call(lineEnding,string);if(newPartContainsEnding!==null){if(this[kLine_buffer])string=this[kLine_buffer]+string,this[kLine_buffer]=null,newPartContainsEnding=RegExpPrototypeExec.call(lineEnding,string);this[kSawReturnAt]=StringPrototypeEndsWith.call(string,\"\\r\")\?DateNow():0;var indexes=[0,newPartContainsEnding.index,lineEnding.lastIndex],nextMatch;while((nextMatch=RegExpPrototypeExec.call(lineEnding,string))!==null)ArrayPrototypePush.call(indexes,nextMatch.index,lineEnding.lastIndex);var lastIndex=indexes.length-1;this[kLine_buffer]=StringPrototypeSlice.call(string,indexes[lastIndex]);for(var i=1;ie!==\"\"));if(StringPrototypeStartsWith.call(prefix,completeOn)&&prefix.length>completeOn.length){this[kInsertString](StringPrototypeSlice.call(prefix,completeOn.length));return}else if(!StringPrototypeStartsWith.call(completeOn,prefix)){this.line=StringPrototypeSlice.call(this.line,0,this.cursor-completeOn.length)+prefix+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor=this.cursor-completeOn.length+prefix.length,this._refreshLine();return}if(!lastKeypressWasTab)return;this[kBeforeEdit](this.line,this.cursor);var completionsWidth=ArrayPrototypeMap.call(completions,(e)=>getStringWidth(e)),width=MathMaxApply(completionsWidth)+2,maxColumns=MathFloor(this.columns/width)||1;if(maxColumns===Infinity)maxColumns=1;var output=\"\\r\\n\",lineIndex=0,whitespace=0;for(var i=0;i0){var leading=StringPrototypeSlice.call(this.line,0,this.cursor),reversed=ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)),\"\"),match=RegExpPrototypeExec.call(/^\\s*(\?:[^\\w\\s]+|\\w+)\?/,reversed);this[kMoveCursor](-match[0].length)}}[kWordRight](){if(this.cursor0&&this.line.length>0){this[kBeforeEdit](this.line,this.cursor);var charSize=charLengthLeft(this.line,this.cursor);this.line=StringPrototypeSlice.call(this.line,0,this.cursor-charSize)+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor-=charSize,this[kRefreshLine]()}}[kDeleteRight](){if(this.cursor0){this[kBeforeEdit](this.line,this.cursor);var leading=StringPrototypeSlice.call(this.line,0,this.cursor),reversed=ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)),\"\"),match=RegExpPrototypeExec.call(/^\\s*(\?:[^\\w\\s]+|\\w+)\?/,reversed);leading=StringPrototypeSlice.call(leading,0,leading.length-match[0].length),this.line=leading+StringPrototypeSlice.call(this.line,this.cursor,this.line.length),this.cursor=leading.length,this[kRefreshLine]()}}[kDeleteWordRight](){if(this.cursorkMaxLengthOfKillRing)ArrayPrototypePop.call(this[kKillRing])}[kYank](){if(this[kKillRing].length>0)this[kYanking]=!0,this[kInsertString](this[kKillRing][this[kKillRingCursor]])}[kYankPop](){if(!this[kYanking])return;if(this[kKillRing].length>1){var lastYank=this[kKillRing][this[kKillRingCursor]];if(this[kKillRingCursor]++,this[kKillRingCursor]>=this[kKillRing].length)this[kKillRingCursor]=0;var currentYank=this[kKillRing][this[kKillRingCursor]],head=StringPrototypeSlice.call(this.line,0,this.cursor-lastYank.length),tail=StringPrototypeSlice.call(this.line,this.cursor);this.line=head+currentYank+tail,this.cursor=head.length+currentYank.length,this[kRefreshLine]()}}clearLine(){this[kMoveCursor](Infinity),this[kWriteToOutput](\"\\r\\n\"),this.line=\"\",this.cursor=0,this.prevRows=0}[kLine](){var line=this[kAddHistory]();this[kUndoStack]=[],this[kRedoStack]=[],this.clearLine(),this[kOnLine](line)}[kPushToUndoStack](text,cursor){if(ArrayPrototypePush.call(this[kUndoStack],{text,cursor})>kMaxUndoRedoStackSize)ArrayPrototypeShift.call(this[kUndoStack])}[kUndo](){if(this[kUndoStack].length<=0)return;ArrayPrototypePush.call(this[kRedoStack],{text:this.line,cursor:this.cursor});var entry=ArrayPrototypePop.call(this[kUndoStack]);this.line=entry.text,this.cursor=entry.cursor,this[kRefreshLine]()}[kRedo](){if(this[kRedoStack].length<=0)return;ArrayPrototypePush.call(this[kUndoStack],{text:this.line,cursor:this.cursor});var entry=ArrayPrototypePop.call(this[kRedoStack]);this.line=entry.text,this.cursor=entry.cursor,this[kRefreshLine]()}[kHistoryNext](){if(this.historyIndex>=0){this[kBeforeEdit](this.line,this.cursor);var search=this[kSubstringSearch]||\"\",index=this.historyIndex-1;while(index>=0&&(!StringPrototypeStartsWith.call(this.history[index],search)||this.line===this.history[index]))index--;if(index===-1)this.line=search;else this.line=this.history[index];this.historyIndex=index,this.cursor=this.line.length,this[kRefreshLine]()}}[kHistoryPrev](){if(this.historyIndexthis.line.length)this.cursor=this.line.length;var newPos=this.getCursorPos();if(oldPos.rows===newPos.rows){var diffWidth=newPos.cols-oldPos.cols;moveCursor(this.output,diffWidth,0)}else this[kRefreshLine]()}[kTtyWrite](s,key){var previousKey=this[kPreviousKey];key=key||kEmptyObject,this[kPreviousKey]=key;var{name:keyName,meta:keyMeta,ctrl:keyCtrl2,shift:keyShift,sequence:keySeq}=key;if(!keyMeta||keyName!==\"y\")this[kYanking]=!1;if((keyName===\"up\"||keyName===\"down\")&&!keyCtrl2&&!keyMeta&&!keyShift){if(this[kSubstringSearch]===null)this[kSubstringSearch]=StringPrototypeSlice.call(this.line,0,this.cursor)}else if(this[kSubstringSearch]!==null){if(this[kSubstringSearch]=null,this.history.length===this.historyIndex)this.historyIndex=-1}if(typeof keySeq===\"string\")switch(StringPrototypeCodePointAt.call(keySeq,0)){case 31:this[kUndo]();return;case 30:this[kRedo]();return;default:break}if(keyName===\"escape\")return;if(keyCtrl2&&keyShift)switch(keyName){case\"backspace\":this[kDeleteLineLeft]();break;case\"delete\":this[kDeleteLineRight]();break}else if(keyCtrl2)switch(keyName){case\"c\":if(this.listenerCount(\"SIGINT\")>0)this.emit(\"SIGINT\");else this.close();break;case\"h\":this[kDeleteLeft]();break;case\"d\":if(this.cursor===0&&this.line.length===0)this.close();else if(this.cursor0)this.emit(\"SIGTSTP\");else process.once(\"SIGCONT\",()=>{if(!this.paused)this.pause(),this.emit(\"SIGCONT\");this[kSetRawMode](!0),this[kRefreshLine]()}),this[kSetRawMode](!1),process.kill(process.pid,\"SIGTSTP\");break;case\"w\":case\"backspace\":this[kDeleteWordLeft]();break;case\"delete\":this[kDeleteWordRight]();break;case\"left\":this[kWordLeft]();break;case\"right\":this[kWordRight]();break}else if(keyMeta)switch(keyName){case\"b\":this[kWordLeft]();break;case\"f\":this[kWordRight]();break;case\"d\":case\"delete\":this[kDeleteWordRight]();break;case\"backspace\":this[kDeleteWordLeft]();break;case\"y\":this[kYankPop]();break}else{if(this[kSawReturnAt]&&keyName!==\"enter\")this[kSawReturnAt]=0;switch(keyName){case\"return\":this[kSawReturnAt]=DateNow(),this[kLine]();break;case\"enter\":if(this[kSawReturnAt]===0||DateNow()-this[kSawReturnAt]>this.crlfDelay)this[kLine]();this[kSawReturnAt]=0;break;case\"backspace\":this[kDeleteLeft]();break;case\"delete\":this[kDeleteRight]();break;case\"left\":this[kMoveCursor](-charLengthLeft(this.line,this.cursor));break;case\"right\":this[kMoveCursor](+charLengthAt(this.line,this.cursor));break;case\"home\":this[kMoveCursor]((-Infinity));break;case\"end\":this[kMoveCursor](Infinity);break;case\"up\":this[kHistoryPrev]();break;case\"down\":this[kHistoryNext]();break;case\"tab\":if(typeof this.completer===\"function\"&&this.isCompletionEnabled){var lastKeypressWasTab=previousKey&&previousKey.name===\"tab\";this[kTabComplete](lastKeypressWasTab);break}default:if(typeof s===\"string\"&&s){var nextMatch=RegExpPrototypeExec.call(lineEnding,s);if(nextMatch!==null){this[kInsertString](StringPrototypeSlice.call(s,0,nextMatch.index));var{lastIndex}=lineEnding;while((nextMatch=RegExpPrototypeExec.call(lineEnding,s))!==null)this[kLine](),this[kInsertString](StringPrototypeSlice.call(s,lastIndex,nextMatch.index)),{lastIndex}=lineEnding;if(lastIndex===s.length)this[kLine]()}else this[kInsertString](s)}}}}[SymbolAsyncIterator](){if(this[kLineObjectStream]===void 0)this[kLineObjectStream]=EventEmitter.on(this,\"line\",{close:[\"close\"],highWatermark:1024,[kFirstEventParam]:!0});return this[kLineObjectStream]}};function Interface(input,output,completer,terminal){if(!(this instanceof Interface))return new Interface(input,output,completer,terminal);if(input\?.input&&typeof input.completer===\"function\"&&input.completer.length!==2){var{completer}=input;input.completer=(v,cb)=>cb(null,completer(v))}else if(typeof completer===\"function\"&&completer.length!==2){var realCompleter=completer;completer=(v,cb)=>cb(null,realCompleter(v))}if(InterfaceConstructor.call(this,input,output,completer,terminal),process.env.TERM===\"dumb\")this._ttyWrite=_ttyWriteDumb.bind(this)}Interface.prototype={},ObjectSetPrototypeOf(Interface.prototype,_Interface.prototype),ObjectSetPrototypeOf(Interface,_Interface),Interface.prototype.question=function question(query,options,cb){if(cb=typeof options===\"function\"\?options:cb,options===null||typeof options!==\"object\")options=kEmptyObject;var signal=options\?.signal;if(signal){if(validateAbortSignal(signal,\"options.signal\"),signal.aborted)return;var onAbort=()=>{this[kQuestionCancel]()};signal.addEventListener(\"abort\",onAbort,{once:!0});var cleanup=()=>{signal.removeEventListener(\"abort\",onAbort)},originalCb=cb;cb=typeof cb===\"function\"\?(answer)=>{return cleanup(),originalCb(answer)}:cleanup}if(typeof cb===\"function\")this[kQuestion](query,cb)},Interface.prototype.question[promisify.custom]=function question(query,options){if(options===null||typeof options!==\"object\")options=kEmptyObject;var signal=options\?.signal;if(signal&&signal.aborted)return PromiseReject(new AbortError(void 0,{cause:signal.reason}));return new Promise((resolve,reject)=>{var cb=resolve;if(signal){var onAbort=()=>{reject(new AbortError(void 0,{cause:signal.reason}))};signal.addEventListener(\"abort\",onAbort,{once:!0}),cb=(answer)=>{signal.removeEventListener(\"abort\",onAbort),resolve(answer)}}this.question(query,options,cb)})};function createInterface(input,output,completer,terminal){return new Interface(input,output,completer,terminal)}ObjectDefineProperties(Interface.prototype,{[kSetRawMode]:{__proto__:null,get(){return this._setRawMode}},[kOnLine]:{__proto__:null,get(){return this._onLine}},[kWriteToOutput]:{__proto__:null,get(){return this._writeToOutput}},[kAddHistory]:{__proto__:null,get(){return this._addHistory}},[kRefreshLine]:{__proto__:null,get(){return this._refreshLine}},[kNormalWrite]:{__proto__:null,get(){return this._normalWrite}},[kInsertString]:{__proto__:null,get(){return this._insertString}},[kTabComplete]:{__proto__:null,get(){return this._tabComplete}},[kWordLeft]:{__proto__:null,get(){return this._wordLeft}},[kWordRight]:{__proto__:null,get(){return this._wordRight}},[kDeleteLeft]:{__proto__:null,get(){return this._deleteLeft}},[kDeleteRight]:{__proto__:null,get(){return this._deleteRight}},[kDeleteWordLeft]:{__proto__:null,get(){return this._deleteWordLeft}},[kDeleteWordRight]:{__proto__:null,get(){return this._deleteWordRight}},[kDeleteLineLeft]:{__proto__:null,get(){return this._deleteLineLeft}},[kDeleteLineRight]:{__proto__:null,get(){return this._deleteLineRight}},[kLine]:{__proto__:null,get(){return this._line}},[kHistoryNext]:{__proto__:null,get(){return this._historyNext}},[kHistoryPrev]:{__proto__:null,get(){return this._historyPrev}},[kGetDisplayPos]:{__proto__:null,get(){return this._getDisplayPos}},[kMoveCursor]:{__proto__:null,get(){return this._moveCursor}},[kTtyWrite]:{__proto__:null,get(){return this._ttyWrite}},_decoder:{__proto__:null,get(){return this[kDecoder]},set(value){this[kDecoder]=value}},_line_buffer:{__proto__:null,get(){return this[kLine_buffer]},set(value){this[kLine_buffer]=value}},_oldPrompt:{__proto__:null,get(){return this[kOldPrompt]},set(value){this[kOldPrompt]=value}},_previousKey:{__proto__:null,get(){return this[kPreviousKey]},set(value){this[kPreviousKey]=value}},_prompt:{__proto__:null,get(){return this[kPrompt]},set(value){this[kPrompt]=value}},_questionCallback:{__proto__:null,get(){return this[kQuestionCallback]},set(value){this[kQuestionCallback]=value}},_sawKeyPress:{__proto__:null,get(){return this[kSawKeyPress]},set(value){this[kSawKeyPress]=value}},_sawReturnAt:{__proto__:null,get(){return this[kSawReturnAt]},set(value){this[kSawReturnAt]=value}}}),Interface.prototype._setRawMode=_Interface.prototype[kSetRawMode],Interface.prototype._onLine=_Interface.prototype[kOnLine],Interface.prototype._writeToOutput=_Interface.prototype[kWriteToOutput],Interface.prototype._addHistory=_Interface.prototype[kAddHistory],Interface.prototype._refreshLine=_Interface.prototype[kRefreshLine],Interface.prototype._normalWrite=_Interface.prototype[kNormalWrite],Interface.prototype._insertString=_Interface.prototype[kInsertString],Interface.prototype._tabComplete=function(lastKeypressWasTab){this.pause();var string=StringPrototypeSlice.call(this.line,0,this.cursor);this.completer(string,(err,value)=>{if(this.resume(),err){this._writeToOutput(`Tab completion error: ${inspect(err)}`);return}this[kTabCompleter](lastKeypressWasTab,value)})},Interface.prototype._wordLeft=_Interface.prototype[kWordLeft],Interface.prototype._wordRight=_Interface.prototype[kWordRight],Interface.prototype._deleteLeft=_Interface.prototype[kDeleteLeft],Interface.prototype._deleteRight=_Interface.prototype[kDeleteRight],Interface.prototype._deleteWordLeft=_Interface.prototype[kDeleteWordLeft],Interface.prototype._deleteWordRight=_Interface.prototype[kDeleteWordRight],Interface.prototype._deleteLineLeft=_Interface.prototype[kDeleteLineLeft],Interface.prototype._deleteLineRight=_Interface.prototype[kDeleteLineRight],Interface.prototype._line=_Interface.prototype[kLine],Interface.prototype._historyNext=_Interface.prototype[kHistoryNext],Interface.prototype._historyPrev=_Interface.prototype[kHistoryPrev],Interface.prototype._getDisplayPos=_Interface.prototype[kGetDisplayPos],Interface.prototype._getCursorPos=_Interface.prototype.getCursorPos,Interface.prototype._moveCursor=_Interface.prototype[kMoveCursor],Interface.prototype._ttyWrite=_Interface.prototype[kTtyWrite];function _ttyWriteDumb(s,key){if(key=key||kEmptyObject,key.name===\"escape\")return;if(this[kSawReturnAt]&&key.name!==\"enter\")this[kSawReturnAt]=0;if(keyCtrl){if(key.name===\"c\"){if(this.listenerCount(\"SIGINT\")>0)this.emit(\"SIGINT\");else this.close();return}else if(key.name===\"d\"){this.close();return}}switch(key.name){case\"return\":this[kSawReturnAt]=DateNow(),this._line();break;case\"enter\":if(this[kSawReturnAt]===0||DateNow()-this[kSawReturnAt]>this.crlfDelay)this._line();this[kSawReturnAt]=0;break;default:if(typeof s===\"string\"&&s)this.line+=s,this.cursor+=s.length,this._writeToOutput(s)}}class Readline{#autoCommit=!1;#stream;#todo=[];constructor(stream,options=void 0){if(isWritable\?\?=(@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34)).isWritable,!isWritable(stream))throw new ERR_INVALID_ARG_TYPE(\"stream\",\"Writable\",stream);if(this.#stream=stream,options\?.autoCommit!=null)validateBoolean(options.autoCommit,\"options.autoCommit\"),this.#autoCommit=options.autoCommit}cursorTo(x,y=void 0){if(validateInteger(x,\"x\"),y!=null)validateInteger(y,\"y\");var data=y==null\?CSI`${x+1}G`:CSI`${y+1};${x+1}H`;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data);return this}moveCursor(dx,dy){if(dx||dy){validateInteger(dx,\"dx\"),validateInteger(dy,\"dy\");var data=\"\";if(dx<0)data+=CSI`${-dx}D`;else if(dx>0)data+=CSI`${dx}C`;if(dy<0)data+=CSI`${-dy}A`;else if(dy>0)data+=CSI`${dy}B`;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data)}return this}clearLine(dir){validateInteger(dir,\"dir\",-1,1);var data=dir<0\?kClearToLineBeginning:dir>0\?kClearToLineEnd:kClearLine;if(this.#autoCommit)process.nextTick(()=>this.#stream.write(data));else ArrayPrototypePush.call(this.#todo,data);return this}clearScreenDown(){if(this.#autoCommit)process.nextTick(()=>this.#stream.write(kClearScreenDown));else ArrayPrototypePush.call(this.#todo,kClearScreenDown);return this}commit(){return new Promise((resolve)=>{this.#stream.write(ArrayPrototypeJoin.call(this.#todo,\"\"),resolve),this.#todo=[]})}rollback(){return this.#todo=[],this}}var PromisesInterface=class Interface2 extends _Interface{constructor(input,output,completer,terminal){super(input,output,completer,terminal)}question(query,options=kEmptyObject){var signal=options\?.signal;if(signal){if(validateAbortSignal(signal,\"options.signal\"),signal.aborted)return PromiseReject(new AbortError(void 0,{cause:signal.reason}))}return new Promise((resolve,reject)=>{var cb=resolve;if(options\?.signal){var onAbort=()=>{this[kQuestionCancel](),reject(new AbortError(void 0,{cause:signal.reason}))};signal.addEventListener(\"abort\",onAbort,{once:!0}),cb=(answer)=>{signal.removeEventListener(\"abort\",onAbort),resolve(answer)}}this[kQuestion](query,cb)})}};return $={Interface,clearLine,clearScreenDown,createInterface,cursorTo,emitKeypressEvents,moveCursor,promises:{Readline,Interface:PromisesInterface,createInterface(input,output,completer,terminal){return new PromisesInterface(input,output,completer,terminal)}},[SymbolFor(\"__BUN_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED__\")]:{CSI,utils:{getStringWidth,stripVTControlCharacters}}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeReadlinePromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,30)||@createInternalModuleById(30)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeReplCode = "(function (){\"use strict\";var $;const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2);function REPLServer(){throwNotImplemented(\"node:repl REPLServer\")}function Recoverable(){throwNotImplemented(\"node:repl Recoverable\")}var REPL_MODE_SLOPPY=0,REPL_MODE_STRICT=1;function start(){throwNotImplemented(\"node:repl\")}return $={lines:[],context:globalThis,historyIndex:-1,cursor:0,historySize:1000,removeHistoryDuplicates:!1,crlfDelay:100,completer:()=>{throwNotImplemented(\"node:repl\")},history:[],_initialPrompt:\"> \",terminal:!0,input:new Proxy({},{get(){throwNotImplemented(\"node:repl\")},has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{return},set(){throwNotImplemented(\"node:repl\")}}),line:\"\",eval:()=>{throwNotImplemented(\"node:repl\")},isCompletionEnabled:!0,escapeCodeTimeout:500,tabSize:8,breakEvalOnSigint:!0,useGlobal:!0,underscoreAssigned:!1,last:void 0,_domain:void 0,allowBlockingCompletions:!1,useColors:!0,output:new Proxy({},{get(){throwNotImplemented(\"node:repl\")},has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{return},set(){throwNotImplemented(\"node:repl\")}})},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamConsumersCode = "(function (){\"use strict\";const{readableStreamToArrayBuffer:arrayBuffer,readableStreamToText:text}=Bun,json=(stream)=>Bun.readableStreamToText(stream).then(JSON.parse),buffer=async(readableStream)=>{return new Buffer(await arrayBuffer(readableStream))},blob=Bun.readableStreamToBlob;return{arrayBuffer,text,json,buffer,blob}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamCode = "(function (){\"use strict\";const EE=globalThis[globalThis.Symbol.for('Bun.lazy')](\"events\"),StringDecoder=@requireNativeModule(\"node:string_decoder\").StringDecoder;var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},runOnNextTick=process.nextTick;function isReadableStream(value){return typeof value===\"object\"&&value!==null&&value instanceof ReadableStream}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}const validateObject=(value,name,options=null)=>{const allowArray=options\?.allowArray\?\?!1,allowFunction=options\?.allowFunction\?\?!1;if(!(options\?.nullable\?\?!1)&&value===null||!allowArray&&ArrayIsArray(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE(name,\"Object\",value)};function validateString(value,name){if(typeof value!==\"string\")throw new ERR_INVALID_ARG_TYPE(name,\"string\",value)}var ArrayIsArray=Array.isArray;function ERR_INVALID_ARG_TYPE(name,type,value){return new Error(`The argument '${name}' is invalid. Received '${value}' for type '${type}'`)}function ERR_INVALID_ARG_VALUE(name,value,reason){return new Error(`The value '${value}' is invalid for argument '${name}'. Reason: ${reason}`)}var require_primordials=__commonJS({\"node_modules/readable-stream/lib/ours/primordials.js\"(exports2,module){module.exports={ArrayIsArray(self){return Array.isArray(self)},ArrayPrototypeIncludes(self,el){return self.includes(el)},ArrayPrototypeIndexOf(self,el){return self.indexOf(el)},ArrayPrototypeJoin(self,sep){return self.join(sep)},ArrayPrototypeMap(self,fn){return self.map(fn)},ArrayPrototypePop(self,el){return self.pop(el)},ArrayPrototypePush(self,el){return self.push(el)},ArrayPrototypeSlice(self,start,end){return self.slice(start,end)},Error,FunctionPrototypeCall(fn,thisArgs,...args){return fn.call(thisArgs,...args)},FunctionPrototypeSymbolHasInstance(self,instance){return Function.prototype[Symbol.hasInstance].call(self,instance)},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(self,props){return Object.defineProperties(self,props)},ObjectDefineProperty(self,name,prop){return Object.defineProperty(self,name,prop)},ObjectGetOwnPropertyDescriptor(self,name){return Object.getOwnPropertyDescriptor(self,name)},ObjectKeys(obj){return Object.keys(obj)},ObjectSetPrototypeOf(target,proto){return Object.setPrototypeOf(target,proto)},Promise,PromisePrototypeCatch(self,fn){return self.catch(fn)},PromisePrototypeThen(self,thenFn,catchFn){return self.then(thenFn,catchFn)},PromiseReject(err){return Promise.reject(err)},ReflectApply:Reflect.apply,RegExpPrototypeTest(self,value){return self.test(value)},SafeSet:Set,String,StringPrototypeSlice(self,start,end){return self.slice(start,end)},StringPrototypeToLowerCase(self){return self.toLowerCase()},StringPrototypeToUpperCase(self){return self.toUpperCase()},StringPrototypeTrim(self){return self.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(self,buf,len){return self.set(buf,len)},Uint8Array}}}),require_util=__commonJS({\"node_modules/readable-stream/lib/ours/util.js\"(exports2,module){var AsyncFunction=Object.getPrototypeOf(async function(){}).constructor,isBlob=typeof Blob!==\"undefined\"\?function isBlob2(b){return b instanceof Blob}:function isBlob2(b){return!1},AggregateError=class extends Error{constructor(errors){if(!Array.isArray(errors))@throwTypeError(`Expected input to be an Array, got ${typeof errors}`);let message=\"\";for(let i=0;i{resolve=res,reject=rej}),resolve,reject}},promisify(fn){return new Promise((resolve,reject)=>{fn((err,...args)=>{if(err)return reject(err);return resolve(...args)})})},debuglog(){return function(){}},format(format,...args){return format.replace(/%([sdifj])/g,function(...[_unused,type]){const replacement=args.shift();if(type===\"f\")return replacement.toFixed(6);else if(type===\"j\")return JSON.stringify(replacement);else if(type===\"s\"&&typeof replacement===\"object\")return`${replacement.constructor!==Object\?replacement.constructor.name:\"\"} {}`.trim();else return replacement.toString()})},inspect(value){switch(typeof value){case\"string\":if(value.includes(\"'\")){if(!value.includes('\"'))return`\"${value}\"`;else if(!value.includes(\"`\")&&!value.includes(\"${\"))return`\\`${value}\\``}return`'${value}'`;case\"number\":if(isNaN(value))return\"NaN\";else if(Object.is(value,-0))return String(value);return value;case\"bigint\":return`${String(value)}n`;case\"boolean\":case\"undefined\":return String(value);case\"object\":return\"{}\"}},types:{isAsyncFunction(fn){return fn instanceof AsyncFunction},isArrayBufferView(arr){return ArrayBuffer.isView(arr)}},isBlob},module.exports.promisify.custom=Symbol.for(\"nodejs.util.promisify.custom\")}}),require_errors=__commonJS({\"node_modules/readable-stream/lib/ours/errors.js\"(exports2,module){var{format,inspect,AggregateError:CustomAggregateError}=require_util(),AggregateError=globalThis.AggregateError||CustomAggregateError,kIsNodeError=Symbol(\"kIsNodeError\"),kTypes=[\"string\",\"function\",\"number\",\"object\",\"Function\",\"Object\",\"boolean\",\"bigint\",\"symbol\"],classRegExp=/^([A-Z][a-z0-9]*)+$/,nodeInternalPrefix=\"__node_internal_\",codes={};function assert(value,message){if(!value)throw new codes.ERR_INTERNAL_ASSERTION(message)}function addNumericalSeparator(val){let res=\"\",i=val.length;const start=val[0]===\"-\"\?1:0;for(;i>=start+4;i-=3)res=`_${val.slice(i-3,i)}${res}`;return`${val.slice(0,i)}${res}`}function getMessage(key,msg,args){if(typeof msg===\"function\")return assert(msg.length<=args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`),msg(...args);const expectedLength=(msg.match(/%[dfijoOs]/g)||[]).length;if(assert(expectedLength===args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`),args.length===0)return msg;return format(msg,...args)}function E(code,message,Base){if(!Base)Base=Error;class NodeError extends Base{constructor(...args){super(getMessage(code,message,args))}toString(){return`${this.name} [${code}]: ${this.message}`}}Object.defineProperties(NodeError.prototype,{name:{value:Base.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${code}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),NodeError.prototype.code=code,NodeError.prototype[kIsNodeError]=!0,codes[code]=NodeError}function hideStackFrames(fn){const hidden=nodeInternalPrefix+fn.name;return Object.defineProperty(fn,\"name\",{value:hidden}),fn}function aggregateTwoErrors(innerError,outerError){if(innerError&&outerError&&innerError!==outerError){if(Array.isArray(outerError.errors))return outerError.errors.push(innerError),outerError;const err=new AggregateError([outerError,innerError],outerError.message);return err.code=outerError.code,err}return innerError||outerError}var AbortError2=class extends Error{constructor(message=\"The operation was aborted\",options=void 0){if(options!==void 0&&typeof options!==\"object\")throw new codes.ERR_INVALID_ARG_TYPE(\"options\",\"Object\",options);super(message,options);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};E(\"ERR_ASSERTION\",\"%s\",Error),E(\"ERR_INVALID_ARG_TYPE\",(name,expected,actual)=>{if(assert(typeof name===\"string\",\"'name' must be a string\"),!Array.isArray(expected))expected=[expected];let msg=\"The \";if(name.endsWith(\" argument\"))msg+=`${name} `;else msg+=`\"${name}\" ${name.includes(\".\")\?\"property\":\"argument\"} `;msg+=\"must be \";const types=[],instances=[],other=[];for(let value of expected)if(assert(typeof value===\"string\",\"All expected entries have to be of type string\"),kTypes.includes(value))types.push(value.toLowerCase());else if(classRegExp.test(value))instances.push(value);else assert(value!==\"object\",'The value \"object\" should be written as \"Object\"'),other.push(value);if(instances.length>0){const pos=types.indexOf(\"object\");if(pos!==-1)types.splice(types,pos,1),instances.push(\"Object\")}if(types.length>0){switch(types.length){case 1:msg+=`of type ${types[0]}`;break;case 2:msg+=`one of type ${types[0]} or ${types[1]}`;break;default:{const last=types.pop();msg+=`one of type ${types.join(\", \")}, or ${last}`}}if(instances.length>0||other.length>0)msg+=\" or \"}if(instances.length>0){switch(instances.length){case 1:msg+=`an instance of ${instances[0]}`;break;case 2:msg+=`an instance of ${instances[0]} or ${instances[1]}`;break;default:{const last=instances.pop();msg+=`an instance of ${instances.join(\", \")}, or ${last}`}}if(other.length>0)msg+=\" or \"}switch(other.length){case 0:break;case 1:if(other[0].toLowerCase()!==other[0])msg+=\"an \";msg+=`${other[0]}`;break;case 2:msg+=`one of ${other[0]} or ${other[1]}`;break;default:{const last=other.pop();msg+=`one of ${other.join(\", \")}, or ${last}`}}if(actual==null)msg+=`. Received ${actual}`;else if(typeof actual===\"function\"&&actual.name)msg+=`. Received function ${actual.name}`;else if(typeof actual===\"object\"){var _actual$constructor;if((_actual$constructor=actual.constructor)!==null&&_actual$constructor!==void 0&&_actual$constructor.name)msg+=`. Received an instance of ${actual.constructor.name}`;else{const inspected=inspect(actual,{depth:-1});msg+=`. Received ${inspected}`}}else{let inspected=inspect(actual,{colors:!1});if(inspected.length>25)inspected=`${inspected.slice(0,25)}...`;msg+=`. Received type ${typeof actual} (${inspected})`}return msg},TypeError),E(\"ERR_INVALID_ARG_VALUE\",(name,value,reason=\"is invalid\")=>{let inspected=inspect(value);if(inspected.length>128)inspected=inspected.slice(0,128)+\"...\";return`The ${name.includes(\".\")\?\"property\":\"argument\"} '${name}' ${reason}. Received ${inspected}`},TypeError),E(\"ERR_INVALID_RETURN_VALUE\",(input,name,value)=>{var _value$constructor;const type=value!==null&&value!==void 0&&(_value$constructor=value.constructor)!==null&&_value$constructor!==void 0&&_value$constructor.name\?`instance of ${value.constructor.name}`:`type ${typeof value}`;return`Expected ${input} to be returned from the \"${name}\" function but got ${type}.`},TypeError),E(\"ERR_MISSING_ARGS\",(...args)=>{assert(args.length>0,\"At least one arg needs to be specified\");let msg;const len=args.length;switch(args=(Array.isArray(args)\?args:[args]).map((a)=>`\"${a}\"`).join(\" or \"),len){case 1:msg+=`The ${args[0]} argument`;break;case 2:msg+=`The ${args[0]} and ${args[1]} arguments`;break;default:{const last=args.pop();msg+=`The ${args.join(\", \")}, and ${last} arguments`}break}return`${msg} must be specified`},TypeError),E(\"ERR_OUT_OF_RANGE\",(str,range,input)=>{assert(range,'Missing \"range\" argument');let received;if(Number.isInteger(input)&&Math.abs(input)>4294967296)received=addNumericalSeparator(String(input));else if(typeof input===\"bigint\"){if(received=String(input),input>2n**32n||input<-(2n**32n))received=addNumericalSeparator(received);received+=\"n\"}else received=inspect(input);return`The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`},RangeError),E(\"ERR_MULTIPLE_CALLBACK\",\"Callback called multiple times\",Error),E(\"ERR_METHOD_NOT_IMPLEMENTED\",\"The %s method is not implemented\",Error),E(\"ERR_STREAM_ALREADY_FINISHED\",\"Cannot call %s after a stream was finished\",Error),E(\"ERR_STREAM_CANNOT_PIPE\",\"Cannot pipe, not readable\",Error),E(\"ERR_STREAM_DESTROYED\",\"Cannot call %s after a stream was destroyed\",Error),E(\"ERR_STREAM_NULL_VALUES\",\"May not write null values to stream\",TypeError),E(\"ERR_STREAM_PREMATURE_CLOSE\",\"Premature close\",Error),E(\"ERR_STREAM_PUSH_AFTER_EOF\",\"stream.push() after EOF\",Error),E(\"ERR_STREAM_UNSHIFT_AFTER_END_EVENT\",\"stream.unshift() after end event\",Error),E(\"ERR_STREAM_WRITE_AFTER_END\",\"write after end\",Error),E(\"ERR_UNKNOWN_ENCODING\",\"Unknown encoding: %s\",TypeError),module.exports={AbortError:AbortError2,aggregateTwoErrors:hideStackFrames(aggregateTwoErrors),hideStackFrames,codes}}}),require_validators=__commonJS({\"node_modules/readable-stream/lib/internal/validators.js\"(exports2,module){var{ArrayIsArray:ArrayIsArray2,ArrayPrototypeIncludes,ArrayPrototypeJoin,ArrayPrototypeMap,NumberIsInteger,NumberMAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER,NumberParseInt,RegExpPrototypeTest,String:String2,StringPrototypeToUpperCase,StringPrototypeTrim}=require_primordials(),{hideStackFrames,codes:{ERR_SOCKET_BAD_PORT,ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2,ERR_OUT_OF_RANGE,ERR_UNKNOWN_SIGNAL}}=require_errors(),{normalizeEncoding}=require_util(),{isAsyncFunction,isArrayBufferView}=require_util().types,signals={};function isInt32(value){return value===(value|0)}function isUint32(value){return value===value>>>0}var octalReg=/^[0-7]+$/,modeDesc=\"must be a 32-bit unsigned integer or an octal string\";function parseFileMode(value,name,def){if(typeof value===\"undefined\")value=def;if(typeof value===\"string\"){if(!RegExpPrototypeTest(octalReg,value))throw new ERR_INVALID_ARG_VALUE2(name,value,modeDesc);value=NumberParseInt(value,8)}return validateInt32(value,name,0,4294967295),value}var validateInteger=hideStackFrames((value,name,min=NumberMIN_SAFE_INTEGER,max=NumberMAX_SAFE_INTEGER)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}),validateInt32=hideStackFrames((value,name,min=-2147483648,max=2147483647)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!isInt32(value)){if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}if(valuemax)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}),validateUint32=hideStackFrames((value,name,positive)=>{if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value);if(!isUint32(value)){if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,\"an integer\",value);throw new ERR_OUT_OF_RANGE(name,`>= ${positive\?1:0} && < 4294967296`,value)}if(positive&&value===0)throw new ERR_OUT_OF_RANGE(name,\">= 1 && < 4294967296\",value)});function validateString2(value,name){if(typeof value!==\"string\")throw new ERR_INVALID_ARG_TYPE2(name,\"string\",value)}function validateNumber(value,name){if(typeof value!==\"number\")throw new ERR_INVALID_ARG_TYPE2(name,\"number\",value)}var validateOneOf=hideStackFrames((value,name,oneOf)=>{if(!ArrayPrototypeIncludes(oneOf,value)){const reason=\"must be one of: \"+ArrayPrototypeJoin(ArrayPrototypeMap(oneOf,(v)=>typeof v===\"string\"\?`'${v}'`:String2(v)),\", \");throw new ERR_INVALID_ARG_VALUE2(name,value,reason)}});function validateBoolean2(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE2(name,\"boolean\",value)}var validateObject2=hideStackFrames((value,name,options)=>{const useDefaultOptions=options==null,allowArray=useDefaultOptions\?!1:options.allowArray,allowFunction=useDefaultOptions\?!1:options.allowFunction;if(!(useDefaultOptions\?!1:options.nullable)&&value===null||!allowArray&&ArrayIsArray2(value)||typeof value!==\"object\"&&(!allowFunction||typeof value!==\"function\"))throw new ERR_INVALID_ARG_TYPE2(name,\"Object\",value)}),validateArray=hideStackFrames((value,name,minLength=0)=>{if(!ArrayIsArray2(value))throw new ERR_INVALID_ARG_TYPE2(name,\"Array\",value);if(value.length{if(!isArrayBufferView(buffer))throw new ERR_INVALID_ARG_TYPE2(name,[\"Buffer\",\"TypedArray\",\"DataView\"],buffer)});function validateEncoding(data,encoding){const normalizedEncoding=normalizeEncoding(encoding),length=data.length;if(normalizedEncoding===\"hex\"&&length%2!==0)throw new ERR_INVALID_ARG_VALUE2(\"encoding\",encoding,`is invalid for data of length ${length}`)}function validatePort(port,name=\"Port\",allowZero=!0){if(typeof port!==\"number\"&&typeof port!==\"string\"||typeof port===\"string\"&&StringPrototypeTrim(port).length===0||+port!==+port>>>0||port>65535||port===0&&!allowZero)throw new ERR_SOCKET_BAD_PORT(name,port,allowZero);return port|0}var validateAbortSignal=hideStackFrames((signal,name)=>{if(signal!==void 0&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE2(name,\"AbortSignal\",signal)}),validateFunction=hideStackFrames((value,name)=>{if(typeof value!==\"function\")throw new ERR_INVALID_ARG_TYPE2(name,\"Function\",value)}),validatePlainFunction=hideStackFrames((value,name)=>{if(typeof value!==\"function\"||isAsyncFunction(value))throw new ERR_INVALID_ARG_TYPE2(name,\"Function\",value)}),validateUndefined=hideStackFrames((value,name)=>{if(value!==void 0)throw new ERR_INVALID_ARG_TYPE2(name,\"undefined\",value)});module.exports={isInt32,isUint32,parseFileMode,validateArray,validateBoolean:validateBoolean2,validateBuffer,validateEncoding,validateFunction,validateInt32,validateInteger,validateNumber,validateObject:validateObject2,validateOneOf,validatePlainFunction,validatePort,validateSignalName,validateString:validateString2,validateUint32,validateUndefined,validateAbortSignal}}}),require_utils=__commonJS({\"node_modules/readable-stream/lib/internal/streams/utils.js\"(exports2,module){var{Symbol:Symbol2,SymbolAsyncIterator,SymbolIterator}=require_primordials(),kDestroyed=Symbol2(\"kDestroyed\"),kIsErrored=Symbol2(\"kIsErrored\"),kIsReadable=Symbol2(\"kIsReadable\"),kIsDisturbed=Symbol2(\"kIsDisturbed\");function isReadableNodeStream(obj,strict=!1){var _obj$_readableState;return!!(obj&&typeof obj.pipe===\"function\"&&typeof obj.on===\"function\"&&(!strict||typeof obj.pause===\"function\"&&typeof obj.resume===\"function\")&&(!obj._writableState||((_obj$_readableState=obj._readableState)===null||_obj$_readableState===void 0\?void 0:_obj$_readableState.readable)!==!1)&&(!obj._writableState||obj._readableState))}function isWritableNodeStream(obj){var _obj$_writableState;return!!(obj&&typeof obj.write===\"function\"&&typeof obj.on===\"function\"&&(!obj._readableState||((_obj$_writableState=obj._writableState)===null||_obj$_writableState===void 0\?void 0:_obj$_writableState.writable)!==!1))}function isDuplexNodeStream(obj){return!!(obj&&typeof obj.pipe===\"function\"&&obj._readableState&&typeof obj.on===\"function\"&&typeof obj.write===\"function\")}function isNodeStream(obj){return obj&&(obj._readableState||obj._writableState||typeof obj.write===\"function\"&&typeof obj.on===\"function\"||typeof obj.pipe===\"function\"&&typeof obj.on===\"function\")}function isIterable(obj,isAsync){if(obj==null)return!1;if(isAsync===!0)return typeof obj[SymbolAsyncIterator]===\"function\";if(isAsync===!1)return typeof obj[SymbolIterator]===\"function\";return typeof obj[SymbolAsyncIterator]===\"function\"||typeof obj[SymbolIterator]===\"function\"}function isDestroyed(stream){if(!isNodeStream(stream))return null;const{_writableState:wState,_readableState:rState}=stream,state=wState||rState;return!!(stream.destroyed||stream[kDestroyed]||state!==null&&state!==void 0&&state.destroyed)}function isWritableEnded(stream){if(!isWritableNodeStream(stream))return null;if(stream.writableEnded===!0)return!0;const wState=stream._writableState;if(wState!==null&&wState!==void 0&&wState.errored)return!1;if(typeof(wState===null||wState===void 0\?void 0:wState.ended)!==\"boolean\")return null;return wState.ended}function isWritableFinished(stream,strict){if(!isWritableNodeStream(stream))return null;if(stream.writableFinished===!0)return!0;const wState=stream._writableState;if(wState!==null&&wState!==void 0&&wState.errored)return!1;if(typeof(wState===null||wState===void 0\?void 0:wState.finished)!==\"boolean\")return null;return!!(wState.finished||strict===!1&&wState.ended===!0&&wState.length===0)}function isReadableEnded(stream){if(!isReadableNodeStream(stream))return null;if(stream.readableEnded===!0)return!0;const rState=stream._readableState;if(!rState||rState.errored)return!1;if(typeof(rState===null||rState===void 0\?void 0:rState.ended)!==\"boolean\")return null;return rState.ended}function isReadableFinished(stream,strict){if(!isReadableNodeStream(stream))return null;const rState=stream._readableState;if(rState!==null&&rState!==void 0&&rState.errored)return!1;if(typeof(rState===null||rState===void 0\?void 0:rState.endEmitted)!==\"boolean\")return null;return!!(rState.endEmitted||strict===!1&&rState.ended===!0&&rState.length===0)}function isReadable(stream){if(stream&&stream[kIsReadable]!=null)return stream[kIsReadable];if(typeof(stream===null||stream===void 0\?void 0:stream.readable)!==\"boolean\")return null;if(isDestroyed(stream))return!1;return isReadableNodeStream(stream)&&stream.readable&&!isReadableFinished(stream)}function isWritable(stream){if(typeof(stream===null||stream===void 0\?void 0:stream.writable)!==\"boolean\")return null;if(isDestroyed(stream))return!1;return isWritableNodeStream(stream)&&stream.writable&&!isWritableEnded(stream)}function isFinished(stream,opts){if(!isNodeStream(stream))return null;if(isDestroyed(stream))return!0;if((opts===null||opts===void 0\?void 0:opts.readable)!==!1&&isReadable(stream))return!1;if((opts===null||opts===void 0\?void 0:opts.writable)!==!1&&isWritable(stream))return!1;return!0}function isWritableErrored(stream){var _stream$_writableStat,_stream$_writableStat2;if(!isNodeStream(stream))return null;if(stream.writableErrored)return stream.writableErrored;return(_stream$_writableStat=(_stream$_writableStat2=stream._writableState)===null||_stream$_writableStat2===void 0\?void 0:_stream$_writableStat2.errored)!==null&&_stream$_writableStat!==void 0\?_stream$_writableStat:null}function isReadableErrored(stream){var _stream$_readableStat,_stream$_readableStat2;if(!isNodeStream(stream))return null;if(stream.readableErrored)return stream.readableErrored;return(_stream$_readableStat=(_stream$_readableStat2=stream._readableState)===null||_stream$_readableStat2===void 0\?void 0:_stream$_readableStat2.errored)!==null&&_stream$_readableStat!==void 0\?_stream$_readableStat:null}function isClosed(stream){if(!isNodeStream(stream))return null;if(typeof stream.closed===\"boolean\")return stream.closed;const{_writableState:wState,_readableState:rState}=stream;if(typeof(wState===null||wState===void 0\?void 0:wState.closed)===\"boolean\"||typeof(rState===null||rState===void 0\?void 0:rState.closed)===\"boolean\")return(wState===null||wState===void 0\?void 0:wState.closed)||(rState===null||rState===void 0\?void 0:rState.closed);if(typeof stream._closed===\"boolean\"&&isOutgoingMessage(stream))return stream._closed;return null}function isOutgoingMessage(stream){return typeof stream._closed===\"boolean\"&&typeof stream._defaultKeepAlive===\"boolean\"&&typeof stream._removedConnection===\"boolean\"&&typeof stream._removedContLen===\"boolean\"}function isServerResponse(stream){return typeof stream._sent100===\"boolean\"&&isOutgoingMessage(stream)}function isServerRequest(stream){var _stream$req;return typeof stream._consuming===\"boolean\"&&typeof stream._dumped===\"boolean\"&&((_stream$req=stream.req)===null||_stream$req===void 0\?void 0:_stream$req.upgradeOrConnect)===void 0}function willEmitClose(stream){if(!isNodeStream(stream))return null;const{_writableState:wState,_readableState:rState}=stream,state=wState||rState;return!state&&isServerResponse(stream)||!!(state&&state.autoDestroy&&state.emitClose&&state.closed===!1)}function isDisturbed(stream){var _stream$kIsDisturbed;return!!(stream&&((_stream$kIsDisturbed=stream[kIsDisturbed])!==null&&_stream$kIsDisturbed!==void 0\?_stream$kIsDisturbed:stream.readableDidRead||stream.readableAborted))}function isErrored(stream){var _ref,_ref2,_ref3,_ref4,_ref5,_stream$kIsErrored,_stream$_readableStat3,_stream$_writableStat3,_stream$_readableStat4,_stream$_writableStat4;return!!(stream&&((_ref=(_ref2=(_ref3=(_ref4=(_ref5=(_stream$kIsErrored=stream[kIsErrored])!==null&&_stream$kIsErrored!==void 0\?_stream$kIsErrored:stream.readableErrored)!==null&&_ref5!==void 0\?_ref5:stream.writableErrored)!==null&&_ref4!==void 0\?_ref4:(_stream$_readableStat3=stream._readableState)===null||_stream$_readableStat3===void 0\?void 0:_stream$_readableStat3.errorEmitted)!==null&&_ref3!==void 0\?_ref3:(_stream$_writableStat3=stream._writableState)===null||_stream$_writableStat3===void 0\?void 0:_stream$_writableStat3.errorEmitted)!==null&&_ref2!==void 0\?_ref2:(_stream$_readableStat4=stream._readableState)===null||_stream$_readableStat4===void 0\?void 0:_stream$_readableStat4.errored)!==null&&_ref!==void 0\?_ref:(_stream$_writableStat4=stream._writableState)===null||_stream$_writableStat4===void 0\?void 0:_stream$_writableStat4.errored))}module.exports={kDestroyed,isDisturbed,kIsDisturbed,isErrored,kIsErrored,isReadable,kIsReadable,isClosed,isDestroyed,isDuplexNodeStream,isFinished,isIterable,isReadableNodeStream,isReadableEnded,isReadableFinished,isReadableErrored,isNodeStream,isWritable,isWritableNodeStream,isWritableEnded,isWritableFinished,isWritableErrored,isServerRequest,isServerResponse,willEmitClose}}}),require_end_of_stream=__commonJS({\"node_modules/readable-stream/lib/internal/streams/end-of-stream.js\"(exports2,module){var{AbortError:AbortError2,codes}=require_errors(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_STREAM_PREMATURE_CLOSE}=codes,{once}=require_util(),{validateAbortSignal,validateFunction,validateObject:validateObject2}=require_validators(),{Promise:Promise2}=require_primordials(),{isClosed,isReadable,isReadableNodeStream,isReadableFinished,isReadableErrored,isWritable,isWritableNodeStream,isWritableFinished,isWritableErrored,isNodeStream,willEmitClose:_willEmitClose}=require_utils();function isRequest(stream){return stream.setHeader&&typeof stream.abort===\"function\"}var nop=()=>{};function eos(stream,options,callback){var _options$readable,_options$writable;if(arguments.length===2)callback=options,options={};else if(options==null)options={};else validateObject2(options,\"options\");validateFunction(callback,\"callback\"),validateAbortSignal(options.signal,\"options.signal\"),callback=once(callback);const readable=(_options$readable=options.readable)!==null&&_options$readable!==void 0\?_options$readable:isReadableNodeStream(stream),writable=(_options$writable=options.writable)!==null&&_options$writable!==void 0\?_options$writable:isWritableNodeStream(stream);if(!isNodeStream(stream))throw new ERR_INVALID_ARG_TYPE2(\"stream\",\"Stream\",stream);const{_writableState:wState,_readableState:rState}=stream,onlegacyfinish=()=>{if(!stream.writable)onfinish()};let willEmitClose=_willEmitClose(stream)&&isReadableNodeStream(stream)===readable&&isWritableNodeStream(stream)===writable,writableFinished=isWritableFinished(stream,!1);const onfinish=()=>{if(writableFinished=!0,stream.destroyed)willEmitClose=!1;if(willEmitClose&&(!stream.readable||readable))return;if(!readable||readableFinished)callback.call(stream)};let readableFinished=isReadableFinished(stream,!1);const onend=()=>{if(readableFinished=!0,stream.destroyed)willEmitClose=!1;if(willEmitClose&&(!stream.writable||writable))return;if(!writable||writableFinished)callback.call(stream)},onerror=(err)=>{callback.call(stream,err)};let closed=isClosed(stream);const onclose=()=>{closed=!0;const errored=isWritableErrored(stream)||isReadableErrored(stream);if(errored&&typeof errored!==\"boolean\")return callback.call(stream,errored);if(readable&&!readableFinished&&isReadableNodeStream(stream,!0)){if(!isReadableFinished(stream,!1))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}if(writable&&!writableFinished){if(!isWritableFinished(stream,!1))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}callback.call(stream)},onrequest=()=>{stream.req.on(\"finish\",onfinish)};if(isRequest(stream)){if(stream.on(\"complete\",onfinish),!willEmitClose)stream.on(\"abort\",onclose);if(stream.req)onrequest();else stream.on(\"request\",onrequest)}else if(writable&&!wState)stream.on(\"end\",onlegacyfinish),stream.on(\"close\",onlegacyfinish);if(!willEmitClose&&typeof stream.aborted===\"boolean\")stream.on(\"aborted\",onclose);if(stream.on(\"end\",onend),stream.on(\"finish\",onfinish),options.error!==!1)stream.on(\"error\",onerror);if(stream.on(\"close\",onclose),closed)runOnNextTick(onclose);else if(wState!==null&&wState!==void 0&&wState.errorEmitted||rState!==null&&rState!==void 0&&rState.errorEmitted){if(!willEmitClose)runOnNextTick(onclose)}else if(!readable&&(!willEmitClose||isReadable(stream))&&(writableFinished||isWritable(stream)===!1))runOnNextTick(onclose);else if(!writable&&(!willEmitClose||isWritable(stream))&&(readableFinished||isReadable(stream)===!1))runOnNextTick(onclose);else if(rState&&stream.req&&stream.aborted)runOnNextTick(onclose);const cleanup=()=>{if(callback=nop,stream.removeListener(\"aborted\",onclose),stream.removeListener(\"complete\",onfinish),stream.removeListener(\"abort\",onclose),stream.removeListener(\"request\",onrequest),stream.req)stream.req.removeListener(\"finish\",onfinish);stream.removeListener(\"end\",onlegacyfinish),stream.removeListener(\"close\",onlegacyfinish),stream.removeListener(\"finish\",onfinish),stream.removeListener(\"end\",onend),stream.removeListener(\"error\",onerror),stream.removeListener(\"close\",onclose)};if(options.signal&&!closed){const abort=()=>{const endCallback=callback;cleanup(),endCallback.call(stream,new AbortError2(void 0,{cause:options.signal.reason}))};if(options.signal.aborted)runOnNextTick(abort);else{const originalCallback=callback;callback=once((...args)=>{options.signal.removeEventListener(\"abort\",abort),originalCallback.apply(stream,args)}),options.signal.addEventListener(\"abort\",abort)}}return cleanup}function finished2(stream,opts){return new Promise2((resolve,reject)=>{eos(stream,opts,(err)=>{if(err)reject(err);else resolve()})})}module.exports=eos,module.exports.finished=finished2}}),require_operators=__commonJS({\"node_modules/readable-stream/lib/internal/streams/operators.js\"(exports2,module){var{codes:{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_MISSING_ARGS,ERR_OUT_OF_RANGE},AbortError:AbortError2}=require_errors(),{validateAbortSignal,validateInteger,validateObject:validateObject2}=require_validators(),kWeakHandler=require_primordials().Symbol(\"kWeak\"),{finished:finished2}=require_end_of_stream(),{ArrayPrototypePush,MathFloor,Number:Number2,NumberIsNaN,Promise:Promise2,PromiseReject,PromisePrototypeCatch,Symbol:Symbol2}=require_primordials(),kEmpty=Symbol2(\"kEmpty\"),kEof=Symbol2(\"kEof\");function map(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");let concurrency=1;if((options===null||options===void 0\?void 0:options.concurrency)!=null)concurrency=MathFloor(options.concurrency);return validateInteger(concurrency,\"concurrency\",1),async function*map2(){var _options$signal,_options$signal2;const ac=new AbortController,stream=this,queue=[],signal=ac.signal,signalOpt={signal},abort=()=>ac.abort();if(options!==null&&options!==void 0&&(_options$signal=options.signal)!==null&&_options$signal!==void 0&&_options$signal.aborted)abort();options===null||options===void 0||(_options$signal2=options.signal)===null||_options$signal2===void 0||_options$signal2.addEventListener(\"abort\",abort);let next,resume,done=!1;function onDone(){done=!0}async function pump(){try{for await(let val of stream){var _val;if(done)return;if(signal.aborted)throw new AbortError2;try{val=fn(val,signalOpt)}catch(err){val=PromiseReject(err)}if(val===kEmpty)continue;if(typeof((_val=val)===null||_val===void 0\?void 0:_val.catch)===\"function\")val.catch(onDone);if(queue.push(val),next)next(),next=null;if(!done&&queue.length&&queue.length>=concurrency)await new Promise2((resolve)=>{resume=resolve})}queue.push(kEof)}catch(err){const val=PromiseReject(err);PromisePrototypeCatch(val,onDone),queue.push(val)}finally{var _options$signal3;if(done=!0,next)next(),next=null;options===null||options===void 0||(_options$signal3=options.signal)===null||_options$signal3===void 0||_options$signal3.removeEventListener(\"abort\",abort)}}pump();try{while(!0){while(queue.length>0){const val=await queue[0];if(val===kEof)return;if(signal.aborted)throw new AbortError2;if(val!==kEmpty)yield val;if(queue.shift(),resume)resume(),resume=null}await new Promise2((resolve)=>{next=resolve})}}finally{if(ac.abort(),done=!0,resume)resume(),resume=null}}.call(this)}function asIndexedPairs(options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return async function*asIndexedPairs2(){let index=0;for await(let val of this){var _options$signal4;if(options!==null&&options!==void 0&&(_options$signal4=options.signal)!==null&&_options$signal4!==void 0&&_options$signal4.aborted)throw new AbortError2({cause:options.signal.reason});yield[index++,val]}}.call(this)}async function some(fn,options=void 0){for await(let unused of filter.call(this,fn,options))return!0;return!1}async function every(fn,options=void 0){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);return!await some.call(this,async(...args)=>{return!await fn(...args)},options)}async function find(fn,options){for await(let result of filter.call(this,fn,options))return result;return}async function forEach(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);async function forEachFn(value,options2){return await fn(value,options2),kEmpty}for await(let unused of map.call(this,forEachFn,options));}function filter(fn,options){if(typeof fn!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"fn\",[\"Function\",\"AsyncFunction\"],fn);async function filterFn(value,options2){if(await fn(value,options2))return value;return kEmpty}return map.call(this,filterFn,options)}var ReduceAwareErrMissingArgs=class extends ERR_MISSING_ARGS{constructor(){super(\"reduce\");this.message=\"Reduce of an empty stream requires an initial value\"}};async function reduce(reducer,initialValue,options){var _options$signal5;if(typeof reducer!==\"function\")throw new ERR_INVALID_ARG_TYPE2(\"reducer\",[\"Function\",\"AsyncFunction\"],reducer);if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");let hasInitialValue=arguments.length>1;if(options!==null&&options!==void 0&&(_options$signal5=options.signal)!==null&&_options$signal5!==void 0&&_options$signal5.aborted){const err=new AbortError2(void 0,{cause:options.signal.reason});throw this.once(\"error\",()=>{}),await finished2(this.destroy(err)),err}const ac=new AbortController,signal=ac.signal;if(options!==null&&options!==void 0&&options.signal){const opts={once:!0,[kWeakHandler]:this};options.signal.addEventListener(\"abort\",()=>ac.abort(),opts)}let gotAnyItemFromStream=!1;try{for await(let value of this){var _options$signal6;if(gotAnyItemFromStream=!0,options!==null&&options!==void 0&&(_options$signal6=options.signal)!==null&&_options$signal6!==void 0&&_options$signal6.aborted)throw new AbortError2;if(!hasInitialValue)initialValue=value,hasInitialValue=!0;else initialValue=await reducer(initialValue,value,{signal})}if(!gotAnyItemFromStream&&!hasInitialValue)throw new ReduceAwareErrMissingArgs}finally{ac.abort()}return initialValue}async function toArray(options){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");const result=[];for await(let val of this){var _options$signal7;if(options!==null&&options!==void 0&&(_options$signal7=options.signal)!==null&&_options$signal7!==void 0&&_options$signal7.aborted)throw new AbortError2(void 0,{cause:options.signal.reason});ArrayPrototypePush(result,val)}return result}function flatMap(fn,options){const values=map.call(this,fn,options);return async function*flatMap2(){for await(let val of values)yield*val}.call(this)}function toIntegerOrInfinity(number){if(number=Number2(number),NumberIsNaN(number))return 0;if(number<0)throw new ERR_OUT_OF_RANGE(\"number\",\">= 0\",number);return number}function drop(number,options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return number=toIntegerOrInfinity(number),async function*drop2(){var _options$signal8;if(options!==null&&options!==void 0&&(_options$signal8=options.signal)!==null&&_options$signal8!==void 0&&_options$signal8.aborted)throw new AbortError2;for await(let val of this){var _options$signal9;if(options!==null&&options!==void 0&&(_options$signal9=options.signal)!==null&&_options$signal9!==void 0&&_options$signal9.aborted)throw new AbortError2;if(number--<=0)yield val}}.call(this)}function take(number,options=void 0){if(options!=null)validateObject2(options,\"options\");if((options===null||options===void 0\?void 0:options.signal)!=null)validateAbortSignal(options.signal,\"options.signal\");return number=toIntegerOrInfinity(number),async function*take2(){var _options$signal10;if(options!==null&&options!==void 0&&(_options$signal10=options.signal)!==null&&_options$signal10!==void 0&&_options$signal10.aborted)throw new AbortError2;for await(let val of this){var _options$signal11;if(options!==null&&options!==void 0&&(_options$signal11=options.signal)!==null&&_options$signal11!==void 0&&_options$signal11.aborted)throw new AbortError2;if(number-- >0)yield val;else return}}.call(this)}module.exports.streamReturningOperators={asIndexedPairs,drop,filter,flatMap,map,take},module.exports.promiseReturningOperators={every,forEach,reduce,toArray,some,find}}}),require_destroy=__commonJS({\"node_modules/readable-stream/lib/internal/streams/destroy.js\"(exports2,module){var{aggregateTwoErrors,codes:{ERR_MULTIPLE_CALLBACK},AbortError:AbortError2}=require_errors(),{Symbol:Symbol2}=require_primordials(),{kDestroyed,isDestroyed,isFinished,isServerRequest}=require_utils(),kDestroy=\"#kDestroy\",kConstruct=\"#kConstruct\";function checkError(err,w,r){if(err){if(err.stack,w&&!w.errored)w.errored=err;if(r&&!r.errored)r.errored=err}}function destroy2(err,cb){const r=this._readableState,w=this._writableState,s=w||r;if(w&&w.destroyed||r&&r.destroyed){if(typeof cb===\"function\")cb();return this}if(checkError(err,w,r),w)w.destroyed=!0;if(r)r.destroyed=!0;if(!s.constructed)this.once(kDestroy,(er)=>{_destroy(this,aggregateTwoErrors(er,err),cb)});else _destroy(this,err,cb);return this}function _destroy(self,err,cb){let called=!1;function onDestroy(err2){if(called)return;called=!0;const{_readableState:r,_writableState:w}=self;if(checkError(err2,w,r),w)w.closed=!0;if(r)r.closed=!0;if(typeof cb===\"function\")cb(err2);if(err2)runOnNextTick(emitErrorCloseNT,self,err2);else runOnNextTick(emitCloseNT,self)}try{self._destroy(err||null,onDestroy)}catch(err2){onDestroy(err2)}}function emitErrorCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){const{_readableState:r,_writableState:w}=self;if(w)w.closeEmitted=!0;if(r)r.closeEmitted=!0;if(w&&w.emitClose||r&&r.emitClose)self.emit(\"close\")}function emitErrorNT(self,err){const r=self\?._readableState,w=self\?._writableState;if(w\?.errorEmitted||r\?.errorEmitted)return;if(w)w.errorEmitted=!0;if(r)r.errorEmitted=!0;self\?.emit\?.(\"error\",err)}function undestroy(){const r=this._readableState,w=this._writableState;if(r)r.constructed=!0,r.closed=!1,r.closeEmitted=!1,r.destroyed=!1,r.errored=null,r.errorEmitted=!1,r.reading=!1,r.ended=r.readable===!1,r.endEmitted=r.readable===!1;if(w)w.constructed=!0,w.destroyed=!1,w.closed=!1,w.closeEmitted=!1,w.errored=null,w.errorEmitted=!1,w.finalCalled=!1,w.prefinished=!1,w.ended=w.writable===!1,w.ending=w.writable===!1,w.finished=w.writable===!1}function errorOrDestroy2(stream,err,sync){const r=stream\?._readableState,w=stream\?._writableState;if(w&&w.destroyed||r&&r.destroyed)return this;if(r&&r.autoDestroy||w&&w.autoDestroy)stream.destroy(err);else if(err){if(Error.captureStackTrace(err),w&&!w.errored)w.errored=err;if(r&&!r.errored)r.errored=err;if(sync)runOnNextTick(emitErrorNT,stream,err);else emitErrorNT(stream,err)}}function construct(stream,cb){if(typeof stream._construct!==\"function\")return;const{_readableState:r,_writableState:w}=stream;if(r)r.constructed=!1;if(w)w.constructed=!1;if(stream.once(kConstruct,cb),stream.listenerCount(kConstruct)>1)return;runOnNextTick(constructNT,stream)}function constructNT(stream){let called=!1;function onConstruct(err){if(called){errorOrDestroy2(stream,err!==null&&err!==void 0\?err:new ERR_MULTIPLE_CALLBACK);return}called=!0;const{_readableState:r,_writableState:w}=stream,s=w||r;if(r)r.constructed=!0;if(w)w.constructed=!0;if(s.destroyed)stream.emit(kDestroy,err);else if(err)errorOrDestroy2(stream,err,!0);else runOnNextTick(emitConstructNT,stream)}try{stream._construct(onConstruct)}catch(err){onConstruct(err)}}function emitConstructNT(stream){stream.emit(kConstruct)}function isRequest(stream){return stream&&stream.setHeader&&typeof stream.abort===\"function\"}function emitCloseLegacy(stream){stream.emit(\"close\")}function emitErrorCloseLegacy(stream,err){stream.emit(\"error\",err),runOnNextTick(emitCloseLegacy,stream)}function destroyer(stream,err){if(!stream||isDestroyed(stream))return;if(!err&&!isFinished(stream))err=new AbortError2;if(isServerRequest(stream))stream.socket=null,stream.destroy(err);else if(isRequest(stream))stream.abort();else if(isRequest(stream.req))stream.req.abort();else if(typeof stream.destroy===\"function\")stream.destroy(err);else if(typeof stream.close===\"function\")stream.close();else if(err)runOnNextTick(emitErrorCloseLegacy,stream);else runOnNextTick(emitCloseLegacy,stream);if(!stream.destroyed)stream[kDestroyed]=!0}module.exports={construct,destroyer,destroy:destroy2,undestroy,errorOrDestroy:errorOrDestroy2}}}),require_legacy=__commonJS({\"node_modules/readable-stream/lib/internal/streams/legacy.js\"(exports2,module){var{ArrayIsArray:ArrayIsArray2,ObjectSetPrototypeOf}=require_primordials();function Stream(options){if(!(this instanceof Stream))return new Stream(options);EE.call(this,options)}Stream.prototype={},ObjectSetPrototypeOf(Stream.prototype,EE.prototype),ObjectSetPrototypeOf(Stream,EE),Stream.prototype.pipe=function(dest,options){const source=this;function ondata(chunk){if(dest.writable&&dest.write(chunk)===!1&&source.pause)source.pause()}source.on(\"data\",ondata);function ondrain(){if(source.readable&&source.resume)source.resume()}if(dest.on(\"drain\",ondrain),!dest._isStdio&&(!options||options.end!==!1))source.on(\"end\",onend),source.on(\"close\",onclose);let didOnEnd=!1;function onend(){if(didOnEnd)return;didOnEnd=!0,dest.end()}function onclose(){if(didOnEnd)return;if(didOnEnd=!0,typeof dest.destroy===\"function\")dest.destroy()}function onerror(er){if(cleanup(),EE.listenerCount(this,\"error\")===0)this.emit(\"error\",er)}prependListener(source,\"error\",onerror),prependListener(dest,\"error\",onerror);function cleanup(){source.removeListener(\"data\",ondata),dest.removeListener(\"drain\",ondrain),source.removeListener(\"end\",onend),source.removeListener(\"close\",onclose),source.removeListener(\"error\",onerror),dest.removeListener(\"error\",onerror),source.removeListener(\"end\",cleanup),source.removeListener(\"close\",cleanup),dest.removeListener(\"close\",cleanup)}return source.on(\"end\",cleanup),source.on(\"close\",cleanup),dest.on(\"close\",cleanup),dest.emit(\"pipe\",source),dest};function prependListener(emitter,event,fn){if(typeof emitter.prependListener===\"function\")return emitter.prependListener(event,fn);if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(ArrayIsArray2(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}module.exports={Stream,prependListener}}}),require_add_abort_signal=__commonJS({\"node_modules/readable-stream/lib/internal/streams/add-abort-signal.js\"(exports2,module){var{AbortError:AbortError2,codes}=require_errors(),eos=require_end_of_stream(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2}=codes,validateAbortSignal=(signal,name)=>{if(typeof signal!==\"object\"||!(\"aborted\"in signal))throw new ERR_INVALID_ARG_TYPE2(name,\"AbortSignal\",signal)};function isNodeStream(obj){return!!(obj&&typeof obj.pipe===\"function\")}module.exports.addAbortSignal=function addAbortSignal(signal,stream){if(validateAbortSignal(signal,\"signal\"),!isNodeStream(stream))throw new ERR_INVALID_ARG_TYPE2(\"stream\",\"stream.Stream\",stream);return module.exports.addAbortSignalNoValidate(signal,stream)},module.exports.addAbortSignalNoValidate=function(signal,stream){if(typeof signal!==\"object\"||!(\"aborted\"in signal))return stream;const onAbort=()=>{stream.destroy(new AbortError2(void 0,{cause:signal.reason}))};if(signal.aborted)onAbort();else signal.addEventListener(\"abort\",onAbort),eos(stream,()=>signal.removeEventListener(\"abort\",onAbort));return stream}}}),require_state=__commonJS({\"node_modules/readable-stream/lib/internal/streams/state.js\"(exports2,module){var{MathFloor,NumberIsInteger}=require_primordials(),{ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2}=require_errors().codes;function highWaterMarkFrom(options,isDuplex,duplexKey){return options.highWaterMark!=null\?options.highWaterMark:isDuplex\?options[duplexKey]:null}function getDefaultHighWaterMark(objectMode){return objectMode\?16:16384}function getHighWaterMark(state,options,duplexKey,isDuplex){const hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(hwm!=null){if(!NumberIsInteger(hwm)||hwm<0){const name=isDuplex\?`options.${duplexKey}`:\"options.highWaterMark\";throw new ERR_INVALID_ARG_VALUE2(name,hwm)}return MathFloor(hwm)}return getDefaultHighWaterMark(state.objectMode)}module.exports={getHighWaterMark,getDefaultHighWaterMark}}}),require_from=__commonJS({\"node_modules/readable-stream/lib/internal/streams/from.js\"(exports2,module){var{PromisePrototypeThen,SymbolAsyncIterator,SymbolIterator}=require_primordials(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_STREAM_NULL_VALUES}=require_errors().codes;function from(Readable,iterable,opts){let iterator;if(typeof iterable===\"string\"||iterable instanceof Buffer)return new Readable({objectMode:!0,...opts,read(){this.push(iterable),this.push(null)}});let isAsync;if(iterable&&iterable[SymbolAsyncIterator])isAsync=!0,iterator=iterable[SymbolAsyncIterator]();else if(iterable&&iterable[SymbolIterator])isAsync=!1,iterator=iterable[SymbolIterator]();else throw new ERR_INVALID_ARG_TYPE2(\"iterable\",[\"Iterable\"],iterable);const readable=new Readable({objectMode:!0,highWaterMark:1,...opts});let reading=!1;readable._read=function(){if(!reading)reading=!0,next()},readable._destroy=function(error,cb){PromisePrototypeThen(close(error),()=>runOnNextTick(cb,error),(e)=>runOnNextTick(cb,e||error))};async function close(error){const hadError=error!==void 0&&error!==null,hasThrow=typeof iterator.throw===\"function\";if(hadError&&hasThrow){const{value,done}=await iterator.throw(error);if(await value,done)return}if(typeof iterator.return===\"function\"){const{value}=await iterator.return();await value}}async function next(){for(;;){try{const{value,done}=isAsync\?await iterator.next():iterator.next();if(done)readable.push(null);else{const res=value&&typeof value.then===\"function\"\?await value:value;if(res===null)throw reading=!1,new ERR_STREAM_NULL_VALUES;else if(readable.push(res))continue;else reading=!1}}catch(err){readable.destroy(err)}break}}return readable}module.exports=from}}),_ReadableFromWeb,_ReadableFromWebForUndici,require_readable=__commonJS({\"node_modules/readable-stream/lib/internal/streams/readable.js\"(exports2,module){var{ArrayPrototypeIndexOf,NumberIsInteger,NumberIsNaN,NumberParseInt,ObjectDefineProperties,ObjectKeys,ObjectSetPrototypeOf,Promise:Promise2,SafeSet,SymbolAsyncIterator,Symbol:Symbol2}=require_primordials(),ReadableState=globalThis[globalThis.Symbol.for('Bun.lazy')](\"bun:stream\").ReadableState,{Stream,prependListener}=require_legacy();function Readable(options){if(!(this instanceof Readable))return new Readable(options);const isDuplex=this instanceof require_duplex();if(this._readableState=new ReadableState(options,this,isDuplex),options){const{read,destroy:destroy2,construct,signal}=options;if(typeof read===\"function\")this._read=read;if(typeof destroy2===\"function\")this._destroy=destroy2;if(typeof construct===\"function\")this._construct=construct;if(signal&&!isDuplex)addAbortSignal(signal,this)}Stream.call(this,options),destroyImpl.construct(this,()=>{if(this._readableState.needReadable)maybeReadMore(this,this._readableState)})}Readable.prototype={},ObjectSetPrototypeOf(Readable.prototype,Stream.prototype),ObjectSetPrototypeOf(Readable,Stream),Readable.prototype.on=function(ev,fn){const res=Stream.prototype.on.call(this,ev,fn),state=this._readableState;if(ev===\"data\"){if(state.readableListening=this.listenerCount(\"readable\")>0,state.flowing!==!1)this.resume()}else if(ev===\"readable\"){if(!state.endEmitted&&!state.readableListening){if(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,state.length)emitReadable(this,state);else if(!state.reading)runOnNextTick(nReadingNextTick,this)}else if(state.endEmitted);}return res};class ReadableFromWeb extends Readable{#reader;#closed;#pendingChunks;#stream;constructor(options,stream){const{objectMode,highWaterMark,encoding,signal}=options;super({objectMode,highWaterMark,encoding,signal});this.#pendingChunks=[],this.#reader=void 0,this.#stream=stream,this.#closed=!1}#drainPending(){var pendingChunks=this.#pendingChunks,pendingChunksI=0,pendingChunksCount=pendingChunks.length;for(;pendingChunksI0)this.#pendingChunks=[];return!1}#handleDone(reader){reader.releaseLock(),this.#reader=void 0,this.#closed=!0,this.push(null);return}async _read(){var stream=this.#stream,reader=this.#reader;if(stream)reader=this.#reader=stream.getReader(),this.#stream=void 0;else if(this.#drainPending())return;var deferredError;try{do{var done=!1,value;const firstResult=reader.readMany();if(@isPromise(firstResult)){if({done,value}=await firstResult,this.#closed){this.#pendingChunks.push(...value);return}}else({done,value}=firstResult);if(done){this.#handleDone(reader);return}if(!this.push(value[0])){this.#pendingChunks=value.slice(1);return}for(let i=1,count=value.length;i{this.#closed=!0,callback(error)});return}try{callback(error)}catch(error2){globalThis.reportError(error2)}}}_ReadableFromWebForUndici=ReadableFromWeb;function newStreamReadableFromReadableStream(readableStream,options={}){if(!isReadableStream(readableStream))throw new ERR_INVALID_ARG_TYPE2(\"readableStream\",\"ReadableStream\",readableStream);validateObject2(options,\"options\");const{highWaterMark,encoding,objectMode=!1,signal}=options;if(encoding!==void 0&&!Buffer.isEncoding(encoding))throw new ERR_INVALID_ARG_VALUE(encoding,\"options.encoding\");return validateBoolean(objectMode,\"options.objectMode\"),getNativeReadableStream(Readable,readableStream,options)||new ReadableFromWeb({highWaterMark,encoding,objectMode,signal},readableStream)}module.exports=Readable,_ReadableFromWeb=newStreamReadableFromReadableStream;var{addAbortSignal}=require_add_abort_signal(),eos=require_end_of_stream();const{maybeReadMore:_maybeReadMore,resume,emitReadable:_emitReadable,onEofChunk}=globalThis[globalThis.Symbol.for('Bun.lazy')](\"bun:stream\");function maybeReadMore(stream,state){process.nextTick(_maybeReadMore,stream,state)}function emitReadable(stream,state){_emitReadable(stream,state)}var destroyImpl=require_destroy(),{aggregateTwoErrors,codes:{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_METHOD_NOT_IMPLEMENTED,ERR_OUT_OF_RANGE,ERR_STREAM_PUSH_AFTER_EOF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT}}=require_errors(),{validateObject:validateObject2}=require_validators(),from=require_from(),nop=()=>{},{errorOrDestroy:errorOrDestroy2}=destroyImpl;Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){cb(err)},Readable.prototype[EE.captureRejectionSymbol]=function(err){this.destroy(err)},Readable.prototype.push=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,!1)},Readable.prototype.unshift=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,!0)};function readableAddChunk(stream,chunk,encoding,addToFront){const state=stream._readableState;let err;if(!state.objectMode){if(typeof chunk===\"string\"){if(encoding=encoding||state.defaultEncoding,state.encoding!==encoding)if(addToFront&&state.encoding)chunk=Buffer.from(chunk,encoding).toString(state.encoding);else chunk=Buffer.from(chunk,encoding),encoding=\"\"}else if(chunk instanceof Buffer)encoding=\"\";else if(Stream._isUint8Array(chunk)){if(addToFront||!state.decoder)chunk=Stream._uint8ArrayToBuffer(chunk);encoding=\"\"}else if(chunk!=null)err=new ERR_INVALID_ARG_TYPE2(\"chunk\",[\"string\",\"Buffer\",\"Uint8Array\"],chunk)}if(err)errorOrDestroy2(stream,err);else if(chunk===null)state.reading=!1,onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(addToFront)if(state.endEmitted)errorOrDestroy2(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);else if(state.destroyed||state.errored)return!1;else addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy2(stream,new ERR_STREAM_PUSH_AFTER_EOF);else if(state.destroyed||state.errored)return!1;else if(state.reading=!1,state.decoder&&!encoding)if(chunk=state.decoder.write(chunk),state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,!1);else maybeReadMore(stream,state);else addChunk(stream,state,chunk,!1);else if(!addToFront)state.reading=!1,maybeReadMore(stream,state);return!state.ended&&(state.length0){if(state.multiAwaitDrain)state.awaitDrainWriters.clear();else state.awaitDrainWriters=null;state.dataEmitted=!0,stream.emit(\"data\",chunk)}else{if(state.length+=state.objectMode\?1:chunk.length,addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream,state)}maybeReadMore(stream,state)}Readable.prototype.isPaused=function(){const state=this._readableState;return state.paused===!0||state.flowing===!1},Readable.prototype.setEncoding=function(enc){const decoder=new StringDecoder(enc);this._readableState.decoder=decoder,this._readableState.encoding=this._readableState.decoder.encoding;const buffer=this._readableState.buffer;let content=\"\";for(let i=buffer.length;i>0;i--)content+=decoder.write(buffer.shift());if(content!==\"\")buffer.push(content);return this._readableState.length=content.length,this};var MAX_HWM=1073741824;function computeNewHighWaterMark(n){if(n>MAX_HWM)throw new ERR_OUT_OF_RANGE(\"size\",\"<= 1GiB\",n);else n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++;return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(NumberIsNaN(n)){if(state.flowing&&state.length)return state.buffer.first().length;return state.length}if(n<=state.length)return n;return state.ended\?state.length:0}Readable.prototype.read=function(n){if(!NumberIsInteger(n))n=NumberParseInt(n,10);const state=this._readableState,nOrig=n;if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n!==0)state.emittedReadable=!1;if(n===0&&state.needReadable&&((state.highWaterMark!==0\?state.length>=state.highWaterMark:state.length>0)||state.ended)){if(state.length===0&&state.ended)endReadable(this);else emitReadable(this,state);return null}if(n=howMuchToRead(n,state),n===0&&state.ended){if(state.length===0)endReadable(this);return null}let doRead=state.needReadable;if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null)state.needReadable=state.length<=state.highWaterMark,n=0;else if(state.length-=n,state.multiAwaitDrain)state.awaitDrainWriters.clear();else state.awaitDrainWriters=null;if(state.length===0){if(!state.ended)state.needReadable=!0;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null&&!state.errorEmitted&&!state.closeEmitted)state.dataEmitted=!0,this.emit(\"data\",ret);return ret},Readable.prototype._read=function(n){throw new ERR_METHOD_NOT_IMPLEMENTED(\"_read()\")},Readable.prototype.pipe=function(dest,pipeOpts){const src=this,state=this._readableState;if(state.pipes.length===1){if(!state.multiAwaitDrain)state.multiAwaitDrain=!0,state.awaitDrainWriters=new SafeSet(state.awaitDrainWriters\?[state.awaitDrainWriters]:[])}state.pipes.push(dest);const endFn=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr\?onend:unpipe;if(state.endEmitted)runOnNextTick(endFn);else src.once(\"end\",endFn);dest.on(\"unpipe\",onunpipe);function onunpipe(readable,unpipeInfo){if(readable===src){if(unpipeInfo&&unpipeInfo.hasUnpiped===!1)unpipeInfo.hasUnpiped=!0,cleanup()}}function onend(){dest.end()}let ondrain,cleanedUp=!1;function cleanup(){if(dest.removeListener(\"close\",onclose),dest.removeListener(\"finish\",onfinish),ondrain)dest.removeListener(\"drain\",ondrain);if(dest.removeListener(\"error\",onerror),dest.removeListener(\"unpipe\",onunpipe),src.removeListener(\"end\",onend),src.removeListener(\"end\",unpipe),src.removeListener(\"data\",ondata),cleanedUp=!0,ondrain&&state.awaitDrainWriters&&(!dest._writableState||dest._writableState.needDrain))ondrain()}function pause(){if(!cleanedUp){if(state.pipes.length===1&&state.pipes[0]===dest)state.awaitDrainWriters=dest,state.multiAwaitDrain=!1;else if(state.pipes.length>1&&state.pipes.includes(dest))state.awaitDrainWriters.add(dest);src.pause()}if(!ondrain)ondrain=pipeOnDrain(src,dest),dest.on(\"drain\",ondrain)}src.on(\"data\",ondata);function ondata(chunk){if(dest.write(chunk)===!1)pause()}function onerror(er){if(unpipe(),dest.removeListener(\"error\",onerror),dest.listenerCount(\"error\")===0){const s=dest._writableState||dest._readableState;if(s&&!s.errorEmitted)errorOrDestroy2(dest,er);else dest.emit(\"error\",er)}}prependListener(dest,\"error\",onerror);function onclose(){dest.removeListener(\"finish\",onfinish),unpipe()}dest.once(\"close\",onclose);function onfinish(){dest.removeListener(\"close\",onclose),unpipe()}dest.once(\"finish\",onfinish);function unpipe(){src.unpipe(dest)}if(dest.emit(\"pipe\",src),dest.writableNeedDrain===!0){if(state.flowing)pause()}else if(!state.flowing)src.resume();return dest};function pipeOnDrain(src,dest){return function pipeOnDrainFunctionResult(){const state=src._readableState;if(state.awaitDrainWriters===dest)state.awaitDrainWriters=null;else if(state.multiAwaitDrain)state.awaitDrainWriters.delete(dest);if((!state.awaitDrainWriters||state.awaitDrainWriters.size===0)&&src.listenerCount(\"data\"))src.resume()}}Readable.prototype.unpipe=function(dest){const state=this._readableState,unpipeInfo={hasUnpiped:!1};if(state.pipes.length===0)return this;if(!dest){const dests=state.pipes;state.pipes=[],this.pause();for(let i=0;i0,state.resumeScheduled&&state.paused===!1)state.flowing=!0;else if(self.listenerCount(\"data\")>0)self.resume();else if(!state.readableListening)state.flowing=null}function nReadingNextTick(self){self.read(0)}Readable.prototype.resume=function(){const state=this._readableState;if(!state.flowing)state.flowing=!state.readableListening,resume(this,state);return state.paused=!1,this},Readable.prototype.pause=function(){if(this._readableState.flowing!==!1)this._readableState.flowing=!1,this.emit(\"pause\");return this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){let paused=!1;stream.on(\"data\",(chunk)=>{if(!this.push(chunk)&&stream.pause)paused=!0,stream.pause()}),stream.on(\"end\",()=>{this.push(null)}),stream.on(\"error\",(err)=>{errorOrDestroy2(this,err)}),stream.on(\"close\",()=>{this.destroy()}),stream.on(\"destroy\",()=>{this.destroy()}),this._read=()=>{if(paused&&stream.resume)paused=!1,stream.resume()};const streamKeys=ObjectKeys(stream);for(let j=1;j{error=err\?aggregateTwoErrors(error,err):null,callback(),callback=nop});try{while(!0){const chunk=stream.destroyed\?null:stream.read();if(chunk!==null)yield chunk;else if(error)throw error;else if(error===null)return;else await new Promise2(next)}}catch(err){throw error=aggregateTwoErrors(error,err),error}finally{if((error||(options===null||options===void 0\?void 0:options.destroyOnReturn)!==!1)&&(error===void 0||stream._readableState.autoDestroy))destroyImpl.destroyer(stream,null);else stream.off(\"readable\",next),cleanup()}}ObjectDefineProperties(Readable.prototype,{readable:{get(){const r=this._readableState;return!!r&&r.readable!==!1&&!r.destroyed&&!r.errorEmitted&&!r.endEmitted},set(val){if(this._readableState)this._readableState.readable=!!val}},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(state){if(this._readableState)this._readableState.flowing=state}},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(value){if(!this._readableState)return;this._readableState.destroyed=value}},readableEnded:{enumerable:!1,get(){return this._readableState\?this._readableState.endEmitted:!1}}}),Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;let ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){if(state.decoder)ret=state.buffer.join(\"\");else if(state.buffer.length===1)ret=state.buffer.first();else ret=state.buffer.concat(state.length);state.buffer.clear()}else ret=state.buffer.consume(n,state.decoder);return ret}function endReadable(stream){const state=stream._readableState;if(!state.endEmitted)state.ended=!0,runOnNextTick(endReadableNT,state,stream)}function endReadableNT(state,stream){if(!state.errored&&!state.closeEmitted&&!state.endEmitted&&state.length===0){if(state.endEmitted=!0,stream.emit(\"end\"),stream.writable&&stream.allowHalfOpen===!1)runOnNextTick(endWritableNT,stream);else if(state.autoDestroy){const wState=stream._writableState;if(!wState||wState.autoDestroy&&(wState.finished||wState.writable===!1))stream.destroy()}}}function endWritableNT(stream){if(stream.writable&&!stream.writableEnded&&!stream.destroyed)stream.end()}Readable.from=function(iterable,opts){return from(Readable,iterable,opts)};var webStreamsAdapters={newStreamReadableFromReadableStream,newReadableStreamFromStreamReadable(streamReadable,options={}){if(typeof streamReadable\?._readableState!==\"object\")throw new ERR_INVALID_ARG_TYPE2(\"streamReadable\",\"stream.Readable\",streamReadable);var{isDestroyed,isReadable}=require_utils();if(isDestroyed(streamReadable)||!isReadable(streamReadable)){const readable=new ReadableStream;return readable.cancel(),readable}const{readableObjectMode:objectMode,readableHighWaterMark:highWaterMark}=streamReadable,strategy=((strategy2)=>{if(strategy2)return strategy2;if(objectMode)return new CountQueuingStrategy({highWaterMark});return{highWaterMark}})(options\?.strategy);let controller;function onData(chunk){if(controller.enqueue(chunk),controller.desiredSize<=0)streamReadable.pause()}streamReadable.pause();const cleanup=finished(streamReadable,(error)=>{if(error\?.code===\"ERR_STREAM_PREMATURE_CLOSE\")error=new AbortError(void 0,{cause:error});if(cleanup(),streamReadable.on(\"error\",()=>{}),error)return controller.error(error);controller.close()});return streamReadable.on(\"data\",onData),new ReadableStream({start(c){controller=c},pull(){streamReadable.resume()},cancel(reason){destroy(streamReadable,reason)}},strategy)}};Readable.fromWeb=function(readableStream,options){return webStreamsAdapters.newStreamReadableFromReadableStream(readableStream,options)},Readable.toWeb=function(streamReadable,options){return webStreamsAdapters.newReadableStreamFromStreamReadable(streamReadable,options)},Readable.wrap=function(src,options){var _ref,_src$readableObjectMo;return new Readable({objectMode:(_ref=(_src$readableObjectMo=src.readableObjectMode)!==null&&_src$readableObjectMo!==void 0\?_src$readableObjectMo:src.objectMode)!==null&&_ref!==void 0\?_ref:!0,...options,destroy(err,callback){destroyImpl.destroyer(src,err),callback(err)}}).wrap(src)}}}),require_writable=__commonJS({\"node_modules/readable-stream/lib/internal/streams/writable.js\"(exports2,module){var{ArrayPrototypeSlice,Error:Error2,FunctionPrototypeSymbolHasInstance,ObjectDefineProperty,ObjectDefineProperties,ObjectSetPrototypeOf,StringPrototypeToLowerCase,Symbol:Symbol2,SymbolHasInstance}=require_primordials(),Stream=require_legacy().Stream,destroyImpl=require_destroy(),{addAbortSignal}=require_add_abort_signal(),{getHighWaterMark,getDefaultHighWaterMark}=require_state(),{ERR_INVALID_ARG_TYPE:ERR_INVALID_ARG_TYPE2,ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED,ERR_STREAM_ALREADY_FINISHED,ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING}=require_errors().codes,{errorOrDestroy:errorOrDestroy2}=destroyImpl;function Writable2(options={}){const isDuplex=this instanceof require_duplex();if(!isDuplex&&!FunctionPrototypeSymbolHasInstance(Writable2,this))return new Writable2(options);if(this._writableState=new WritableState(options,this,isDuplex),options){if(typeof options.write===\"function\")this._write=options.write;if(typeof options.writev===\"function\")this._writev=options.writev;if(typeof options.destroy===\"function\")this._destroy=options.destroy;if(typeof options.final===\"function\")this._final=options.final;if(typeof options.construct===\"function\")this._construct=options.construct;if(options.signal)addAbortSignal(options.signal,this)}Stream.call(this,options),destroyImpl.construct(this,()=>{const state=this._writableState;if(!state.writing)clearBuffer(this,state);finishMaybe(this,state)})}Writable2.prototype={},ObjectSetPrototypeOf(Writable2.prototype,Stream.prototype),ObjectSetPrototypeOf(Writable2,Stream),module.exports=Writable2;function nop(){}var kOnFinished=Symbol2(\"kOnFinished\");function WritableState(options,stream,isDuplex){if(typeof isDuplex!==\"boolean\")isDuplex=stream instanceof require_duplex();if(this.objectMode=!!(options&&options.objectMode),isDuplex)this.objectMode=this.objectMode||!!(options&&options.writableObjectMode);this.highWaterMark=options\?getHighWaterMark(this,options,\"writableHighWaterMark\",isDuplex):getDefaultHighWaterMark(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const noDecode=!!(options&&options.decodeStrings===!1);this.decodeStrings=!noDecode,this.defaultEncoding=options&&options.defaultEncoding||\"utf8\",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=onwrite.bind(void 0,stream),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,resetBuffer(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!options||options.emitClose!==!1,this.autoDestroy=!options||options.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[kOnFinished]=[]}WritableState.prototype={};function resetBuffer(state){state.buffered=[],state.bufferedIndex=0,state.allBuffers=!0,state.allNoop=!0}WritableState.prototype.getBuffer=function getBuffer(){return ArrayPrototypeSlice(this.buffered,this.bufferedIndex)},ObjectDefineProperty(WritableState.prototype,\"bufferedRequestCount\",{get(){return this.buffered.length-this.bufferedIndex}}),ObjectDefineProperty(Writable2,SymbolHasInstance,{value:function(object){if(FunctionPrototypeSymbolHasInstance(this,object))return!0;if(this!==Writable2)return!1;return object&&object._writableState instanceof WritableState}}),Writable2.prototype.pipe=function(){errorOrDestroy2(this,new ERR_STREAM_CANNOT_PIPE)};function _write(stream,chunk,encoding,cb){const state=stream._writableState;if(typeof encoding===\"function\")cb=encoding,encoding=state.defaultEncoding;else{if(!encoding)encoding=state.defaultEncoding;else if(encoding!==\"buffer\"&&!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);if(typeof cb!==\"function\")cb=nop}if(chunk===null)throw new ERR_STREAM_NULL_VALUES;else if(!state.objectMode)if(typeof chunk===\"string\"){if(state.decodeStrings!==!1)chunk=Buffer.from(chunk,encoding),encoding=\"buffer\"}else if(chunk instanceof Buffer)encoding=\"buffer\";else if(Stream._isUint8Array(chunk))chunk=Stream._uint8ArrayToBuffer(chunk),encoding=\"buffer\";else throw new ERR_INVALID_ARG_TYPE2(\"chunk\",[\"string\",\"Buffer\",\"Uint8Array\"],chunk);let err;if(state.ending)err=new ERR_STREAM_WRITE_AFTER_END;else if(state.destroyed)err=new ERR_STREAM_DESTROYED(\"write\");if(err)return runOnNextTick(cb,err),errorOrDestroy2(stream,err,!0),err;return state.pendingcb++,writeOrBuffer(stream,state,chunk,encoding,cb)}Writable2.prototype.write=function(chunk,encoding,cb){return _write(this,chunk,encoding,cb)===!0},Writable2.prototype.cork=function(){this._writableState.corked++},Writable2.prototype.uncork=function(){const state=this._writableState;if(state.corked){if(state.corked--,!state.writing)clearBuffer(this,state)}},Writable2.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding===\"string\")encoding=StringPrototypeToLowerCase(encoding);if(!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this};function writeOrBuffer(stream,state,chunk,encoding,callback){const len=state.objectMode\?1:chunk.length;state.length+=len;const ret=state.lengthstate.bufferedIndex)clearBuffer(stream,state);if(sync)if(state.afterWriteTickInfo!==null&&state.afterWriteTickInfo.cb===cb)state.afterWriteTickInfo.count++;else state.afterWriteTickInfo={count:1,cb,stream,state},runOnNextTick(afterWriteTick,state.afterWriteTickInfo);else afterWrite(stream,state,1,cb)}}function afterWriteTick({stream,state,count,cb}){return state.afterWriteTickInfo=null,afterWrite(stream,state,count,cb)}function afterWrite(stream,state,count,cb){if(!state.ending&&!stream.destroyed&&state.length===0&&state.needDrain)state.needDrain=!1,stream.emit(\"drain\");while(count-- >0)state.pendingcb--,cb();if(state.destroyed)errorBuffer(state);finishMaybe(stream,state)}function errorBuffer(state){if(state.writing)return;for(let n=state.bufferedIndex;n1&&stream._writev){state.pendingcb-=bufferedLength-1;const callback=state.allNoop\?nop:(err)=>{for(let n=i;n256)buffered.splice(0,i),state.bufferedIndex=0;else state.bufferedIndex=i}state.bufferProcessing=!1}Writable2.prototype._write=function(chunk,encoding,cb){if(this._writev)this._writev([{chunk,encoding}],cb);else throw new ERR_METHOD_NOT_IMPLEMENTED(\"_write()\")},Writable2.prototype._writev=null,Writable2.prototype.end=function(chunk,encoding,cb,native=!1){const state=this._writableState;if(typeof chunk===\"function\")cb=chunk,chunk=null,encoding=null;else if(typeof encoding===\"function\")cb=encoding,encoding=null;let err;if(chunk!==null&&chunk!==void 0){let ret;if(!native)ret=_write(this,chunk,encoding);else ret=this.write(chunk,encoding);if(ret instanceof Error2)err=ret}if(state.corked)state.corked=1,this.uncork();if(err)this.emit(\"error\",err);else if(!state.errored&&!state.ending)state.ending=!0,finishMaybe(this,state,!0),state.ended=!0;else if(state.finished)err=new ERR_STREAM_ALREADY_FINISHED(\"end\");else if(state.destroyed)err=new ERR_STREAM_DESTROYED(\"end\");if(typeof cb===\"function\")if(err||state.finished)runOnNextTick(cb,err);else state[kOnFinished].push(cb);return this};function needFinish(state,tag){var needFinish2=state.ending&&!state.destroyed&&state.constructed&&state.length===0&&!state.errored&&state.buffered.length===0&&!state.finished&&!state.writing&&!state.errorEmitted&&!state.closeEmitted;return needFinish2}function callFinal(stream,state){let called=!1;function onFinish(err){if(called){errorOrDestroy2(stream,err!==null&&err!==void 0\?err:ERR_MULTIPLE_CALLBACK());return}if(called=!0,state.pendingcb--,err){const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i{if(needFinish(state2))finish(stream2,state2);else state2.pendingcb--},stream,state);else if(needFinish(state))state.pendingcb++,finish(stream,state)}}function finish(stream,state){state.pendingcb--,state.finished=!0;const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i{if(val!=null)throw new ERR_INVALID_RETURN_VALUE(\"nully\",\"body\",val)},(err)=>{destroyer(d,err)});return d=new Duplexify({objectMode:!0,readable:!1,write,final(cb){final(async()=>{try{await promise,runOnNextTick(cb,null)}catch(err){runOnNextTick(cb,err)}})},destroy:destroy2})}throw new ERR_INVALID_RETURN_VALUE(\"Iterable, AsyncIterable or AsyncFunction\",name,value)}if(isBlob(body))return duplexify(body.arrayBuffer());if(isIterable(body))return from(Duplexify,body,{objectMode:!0,writable:!1});if(typeof(body===null||body===void 0\?void 0:body.writable)===\"object\"||typeof(body===null||body===void 0\?void 0:body.readable)===\"object\"){const readable=body!==null&&body!==void 0&&body.readable\?isReadableNodeStream(body===null||body===void 0\?void 0:body.readable)\?body===null||body===void 0\?void 0:body.readable:duplexify(body.readable):void 0,writable=body!==null&&body!==void 0&&body.writable\?isWritableNodeStream(body===null||body===void 0\?void 0:body.writable)\?body===null||body===void 0\?void 0:body.writable:duplexify(body.writable):void 0;return _duplexify({readable,writable})}const then=body===null||body===void 0\?void 0:body.then;if(typeof then===\"function\"){let d;return FunctionPrototypeCall(then,body,(val)=>{if(val!=null)d.push(val);d.push(null)},(err)=>{destroyer(d,err)}),d=new Duplexify({objectMode:!0,writable:!1,read(){}})}throw new ERR_INVALID_ARG_TYPE2(name,[\"Blob\",\"ReadableStream\",\"WritableStream\",\"Stream\",\"Iterable\",\"AsyncIterable\",\"Function\",\"{ readable, writable } pair\",\"Promise\"],body)};function fromAsyncGen(fn){let{promise,resolve}=createDeferredPromise();const ac=new AbortController,signal=ac.signal;return{value:fn(async function*(){while(!0){const _promise=promise;promise=null;const{chunk,done,cb}=await _promise;if(runOnNextTick(cb),done)return;if(signal.aborted)throw new AbortError2(void 0,{cause:signal.reason});({promise,resolve}=createDeferredPromise()),yield chunk}}(),{signal}),write(chunk,encoding,cb){const _resolve=resolve;resolve=null,_resolve({chunk,done:!1,cb})},final(cb){const _resolve=resolve;resolve=null,_resolve({done:!0,cb})},destroy(err,cb){ac.abort(),cb(err)}}}function _duplexify(pair){const r=pair.readable&&typeof pair.readable.read!==\"function\"\?Readable.wrap(pair.readable):pair.readable,w=pair.writable;let readable=!!isReadable(r),writable=!!isWritable(w),ondrain,onfinish,onreadable,onclose,d;function onfinished(err){const cb=onclose;if(onclose=null,cb)cb(err);else if(err)d.destroy(err);else if(!readable&&!writable)d.destroy()}if(d=new Duplexify({readableObjectMode:!!(r!==null&&r!==void 0&&r.readableObjectMode),writableObjectMode:!!(w!==null&&w!==void 0&&w.writableObjectMode),readable,writable}),writable)eos(w,(err)=>{if(writable=!1,err)destroyer(r,err);onfinished(err)}),d._write=function(chunk,encoding,callback){if(w.write(chunk,encoding))callback();else ondrain=callback},d._final=function(callback){w.end(),onfinish=callback},w.on(\"drain\",function(){if(ondrain){const cb=ondrain;ondrain=null,cb()}}),w.on(\"finish\",function(){if(onfinish){const cb=onfinish;onfinish=null,cb()}});if(readable)eos(r,(err)=>{if(readable=!1,err)destroyer(r,err);onfinished(err)}),r.on(\"readable\",function(){if(onreadable){const cb=onreadable;onreadable=null,cb()}}),r.on(\"end\",function(){d.push(null)}),d._read=function(){while(!0){const buf=r.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf))return}};return d._destroy=function(err,callback){if(!err&&onclose!==null)err=new AbortError2;if(onreadable=null,ondrain=null,onfinish=null,onclose===null)callback(err);else onclose=callback,destroyer(w,err),destroyer(r,err)},d}}}),require_duplex=__commonJS({\"node_modules/readable-stream/lib/internal/streams/duplex.js\"(exports2,module){var{ObjectDefineProperties,ObjectGetOwnPropertyDescriptor,ObjectKeys,ObjectSetPrototypeOf}=require_primordials(),Readable=require_readable();function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);if(Readable.call(this,options),Writable.call(this,options),options){if(this.allowHalfOpen=options.allowHalfOpen!==!1,options.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(options.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}Duplex.prototype={},module.exports=Duplex,ObjectSetPrototypeOf(Duplex.prototype,Readable.prototype),ObjectSetPrototypeOf(Duplex,Readable);for(var method in Writable.prototype)if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method];ObjectDefineProperties(Duplex.prototype,{writable:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writable\"),writableHighWaterMark:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableHighWaterMark\"),writableObjectMode:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableObjectMode\"),writableBuffer:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableBuffer\"),writableLength:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableLength\"),writableFinished:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableFinished\"),writableCorked:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableCorked\"),writableEnded:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableEnded\"),writableNeedDrain:ObjectGetOwnPropertyDescriptor(Writable.prototype,\"writableNeedDrain\"),destroyed:{get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(value){if(this._readableState&&this._writableState)this._readableState.destroyed=value,this._writableState.destroyed=value}}});var webStreamsAdapters;function lazyWebStreams(){if(webStreamsAdapters===void 0)webStreamsAdapters={};return webStreamsAdapters}Duplex.fromWeb=function(pair,options){return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair,options)},Duplex.toWeb=function(duplex){return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)};var duplexify;Duplex.from=function(body){if(!duplexify)duplexify=require_duplexify();return duplexify(body,\"body\")}}}),require_transform=__commonJS({\"node_modules/readable-stream/lib/internal/streams/transform.js\"(exports2,module){var{ObjectSetPrototypeOf,Symbol:Symbol2}=require_primordials(),{ERR_METHOD_NOT_IMPLEMENTED}=require_errors().codes,Duplex=require_duplex();function Transform(options){if(!(this instanceof Transform))return new Transform(options);if(Duplex.call(this,options),this._readableState.sync=!1,this[kCallback]=null,options){if(typeof options.transform===\"function\")this._transform=options.transform;if(typeof options.flush===\"function\")this._flush=options.flush}this.on(\"prefinish\",prefinish.bind(this))}Transform.prototype={},ObjectSetPrototypeOf(Transform.prototype,Duplex.prototype),ObjectSetPrototypeOf(Transform,Duplex),module.exports=Transform;var kCallback=Symbol2(\"kCallback\");function final(cb){if(typeof this._flush===\"function\"&&!this.destroyed)this._flush((er,data)=>{if(er){if(cb)cb(er);else this.destroy(er);return}if(data!=null)this.push(data);if(this.push(null),cb)cb()});else if(this.push(null),cb)cb()}function prefinish(){if(this._final!==final)final.call(this)}Transform.prototype._final=final,Transform.prototype._transform=function(chunk,encoding,callback){throw new ERR_METHOD_NOT_IMPLEMENTED(\"_transform()\")},Transform.prototype._write=function(chunk,encoding,callback){const rState=this._readableState,wState=this._writableState,length=rState.length;this._transform(chunk,encoding,(err,val)=>{if(err){callback(err);return}if(val!=null)this.push(val);if(wState.ended||length===rState.length||rState.length{finished2=!0});const cleanup=eos(stream,{readable:reading,writable:writing},(err)=>{finished2=!err});return{destroy:(err)=>{if(finished2)return;finished2=!0,destroyImpl.destroyer(stream,err||new ERR_STREAM_DESTROYED(\"pipe\"))},cleanup}}function popCallback(streams){return validateFunction(streams[streams.length-1],\"streams[stream.length - 1]\"),streams.pop()}function makeAsyncIterable(val){if(isIterable(val))return val;else if(isReadableNodeStream(val))return fromReadable(val);throw new ERR_INVALID_ARG_TYPE2(\"val\",[\"Readable\",\"Iterable\",\"AsyncIterable\"],val)}async function*fromReadable(val){if(!Readable)Readable=require_readable();yield*Readable.prototype[SymbolAsyncIterator].call(val)}async function pump(iterable,writable,finish,{end}){let error,onresolve=null;const resume=(err)=>{if(err)error=err;if(onresolve){const callback=onresolve;onresolve=null,callback()}},wait=()=>new Promise2((resolve,reject)=>{if(error)reject(error);else onresolve=()=>{if(error)reject(error);else resolve()}});writable.on(\"drain\",resume);const cleanup=eos(writable,{readable:!1},resume);try{if(writable.writableNeedDrain)await wait();for await(let chunk of iterable)if(!writable.write(chunk))await wait();if(end)writable.end();await wait(),finish()}catch(err){finish(error!==err\?aggregateTwoErrors(error,err):err)}finally{cleanup(),writable.off(\"drain\",resume)}}function pipeline(...streams){return pipelineImpl(streams,once(popCallback(streams)))}function pipelineImpl(streams,callback,opts){if(streams.length===1&&ArrayIsArray2(streams[0]))streams=streams[0];if(streams.length<2)throw new ERR_MISSING_ARGS(\"streams\");const ac=new AbortController,signal=ac.signal,outerSignal=opts===null||opts===void 0\?void 0:opts.signal,lastStreamCleanup=[];validateAbortSignal(outerSignal,\"options.signal\");function abort(){finishImpl(new AbortError2)}outerSignal===null||outerSignal===void 0||outerSignal.addEventListener(\"abort\",abort);let error,value;const destroys=[];let finishCount=0;function finish(err){finishImpl(err,--finishCount===0)}function finishImpl(err,final){if(err&&(!error||error.code===\"ERR_STREAM_PREMATURE_CLOSE\"))error=err;if(!error&&!final)return;while(destroys.length)destroys.shift()(error);if(outerSignal===null||outerSignal===void 0||outerSignal.removeEventListener(\"abort\",abort),ac.abort(),final){if(!error)lastStreamCleanup.forEach((fn)=>fn());runOnNextTick(callback,error,value)}}let ret;for(let i=0;i0,end=reading||(opts===null||opts===void 0\?void 0:opts.end)!==!1,isLastStream=i===streams.length-1;if(isNodeStream(stream)){let onError=function(err){if(err&&err.name!==\"AbortError\"&&err.code!==\"ERR_STREAM_PREMATURE_CLOSE\")finish(err)};if(end){const{destroy:destroy2,cleanup}=destroyer(stream,reading,writing);if(destroys.push(destroy2),isReadable(stream)&&isLastStream)lastStreamCleanup.push(cleanup)}if(stream.on(\"error\",onError),isReadable(stream)&&isLastStream)lastStreamCleanup.push(()=>{stream.removeListener(\"error\",onError)})}if(i===0)if(typeof stream===\"function\"){if(ret=stream({signal}),!isIterable(ret))throw new ERR_INVALID_RETURN_VALUE(\"Iterable, AsyncIterable or Stream\",\"source\",ret)}else if(isIterable(stream)||isReadableNodeStream(stream))ret=stream;else ret=Duplex.from(stream);else if(typeof stream===\"function\")if(ret=makeAsyncIterable(ret),ret=stream(ret,{signal}),reading){if(!isIterable(ret,!0))throw new ERR_INVALID_RETURN_VALUE(\"AsyncIterable\",`transform[${i-1}]`,ret)}else{var _ret;if(!PassThrough)PassThrough=require_passthrough();const pt=new PassThrough({objectMode:!0}),then=(_ret=ret)===null||_ret===void 0\?void 0:_ret.then;if(typeof then===\"function\")finishCount++,then.call(ret,(val)=>{if(value=val,val!=null)pt.write(val);if(end)pt.end();runOnNextTick(finish)},(err)=>{pt.destroy(err),runOnNextTick(finish,err)});else if(isIterable(ret,!0))finishCount++,pump(ret,pt,finish,{end});else throw new ERR_INVALID_RETURN_VALUE(\"AsyncIterable or Promise\",\"destination\",ret);ret=pt;const{destroy:destroy2,cleanup}=destroyer(ret,!1,!0);if(destroys.push(destroy2),isLastStream)lastStreamCleanup.push(cleanup)}else if(isNodeStream(stream)){if(isReadableNodeStream(ret)){finishCount+=2;const cleanup=pipe(ret,stream,finish,{end});if(isReadable(stream)&&isLastStream)lastStreamCleanup.push(cleanup)}else if(isIterable(ret))finishCount++,pump(ret,stream,finish,{end});else throw new ERR_INVALID_ARG_TYPE2(\"val\",[\"Readable\",\"Iterable\",\"AsyncIterable\"],ret);ret=stream}else ret=Duplex.from(stream)}if(signal!==null&&signal!==void 0&&signal.aborted||outerSignal!==null&&outerSignal!==void 0&&outerSignal.aborted)runOnNextTick(abort);return ret}function pipe(src,dst,finish,{end}){if(src.pipe(dst,{end}),end)src.once(\"end\",()=>dst.end());else finish();return eos(src,{readable:!0,writable:!1},(err)=>{const rState=src._readableState;if(err&&err.code===\"ERR_STREAM_PREMATURE_CLOSE\"&&rState&&rState.ended&&!rState.errored&&!rState.errorEmitted)src.once(\"end\",finish).once(\"error\",finish);else finish(err)}),eos(dst,{readable:!1,writable:!0},finish)}module.exports={pipelineImpl,pipeline}}}),require_compose=__commonJS({\"node_modules/readable-stream/lib/internal/streams/compose.js\"(exports2,module){var{pipeline}=require_pipeline(),Duplex=require_duplex(),{destroyer}=require_destroy(),{isNodeStream,isReadable,isWritable}=require_utils(),{AbortError:AbortError2,codes:{ERR_INVALID_ARG_VALUE:ERR_INVALID_ARG_VALUE2,ERR_MISSING_ARGS}}=require_errors();module.exports=function compose(...streams){if(streams.length===0)throw new ERR_MISSING_ARGS(\"streams\");if(streams.length===1)return Duplex.from(streams[0]);const orgStreams=[...streams];if(typeof streams[0]===\"function\")streams[0]=Duplex.from(streams[0]);if(typeof streams[streams.length-1]===\"function\"){const idx=streams.length-1;streams[idx]=Duplex.from(streams[idx])}for(let n=0;n0&&!isWritable(streams[n]))throw new ERR_INVALID_ARG_VALUE2(`streams[${n}]`,orgStreams[n],\"must be writable\")}let ondrain,onfinish,onreadable,onclose,d;function onfinished(err){const cb=onclose;if(onclose=null,cb)cb(err);else if(err)d.destroy(err);else if(!readable&&!writable)d.destroy()}const head=streams[0],tail=pipeline(streams,onfinished),writable=!!isWritable(head),readable=!!isReadable(tail);if(d=new Duplex({writableObjectMode:!!(head!==null&&head!==void 0&&head.writableObjectMode),readableObjectMode:!!(tail!==null&&tail!==void 0&&tail.writableObjectMode),writable,readable}),writable)d._write=function(chunk,encoding,callback){if(head.write(chunk,encoding))callback();else ondrain=callback},d._final=function(callback){head.end(),onfinish=callback},head.on(\"drain\",function(){if(ondrain){const cb=ondrain;ondrain=null,cb()}}),tail.on(\"finish\",function(){if(onfinish){const cb=onfinish;onfinish=null,cb()}});if(readable)tail.on(\"readable\",function(){if(onreadable){const cb=onreadable;onreadable=null,cb()}}),tail.on(\"end\",function(){d.push(null)}),d._read=function(){while(!0){const buf=tail.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf))return}};return d._destroy=function(err,callback){if(!err&&onclose!==null)err=new AbortError2;if(onreadable=null,ondrain=null,onfinish=null,onclose===null)callback(err);else onclose=callback,destroyer(tail,err)},d}}}),require_promises=__commonJS({\"node_modules/readable-stream/lib/stream/promises.js\"(exports2,module){var{ArrayPrototypePop,Promise:Promise2}=require_primordials(),{isIterable,isNodeStream}=require_utils(),{pipelineImpl:pl}=require_pipeline(),{finished:finished2}=require_end_of_stream();function pipeline(...streams){return new Promise2((resolve,reject)=>{let signal,end;const lastArg=streams[streams.length-1];if(lastArg&&typeof lastArg===\"object\"&&!isNodeStream(lastArg)&&!isIterable(lastArg)){const options=ArrayPrototypePop(streams);signal=options.signal,end=options.end}pl(streams,(err,value)=>{if(err)reject(err);else resolve(value)},{signal,end})})}module.exports={finished:finished2,pipeline}}}),require_stream=__commonJS({\"node_modules/readable-stream/lib/stream.js\"(exports2,module){var{ObjectDefineProperty,ObjectKeys,ReflectApply}=require_primordials(),{promisify:{custom:customPromisify}}=require_util(),{streamReturningOperators,promiseReturningOperators}=require_operators(),{codes:{ERR_ILLEGAL_CONSTRUCTOR}}=require_errors(),compose=require_compose(),{pipeline}=require_pipeline(),{destroyer}=require_destroy(),eos=require_end_of_stream(),promises2=require_promises(),utils=require_utils(),Stream=module.exports=require_legacy().Stream;Stream.isDisturbed=utils.isDisturbed,Stream.isErrored=utils.isErrored,Stream.isWritable=utils.isWritable,Stream.isReadable=utils.isReadable,Stream.Readable=require_readable();for(let key of ObjectKeys(streamReturningOperators)){let fn=function(...args){if(new.target)throw ERR_ILLEGAL_CONSTRUCTOR();return Stream.Readable.from(ReflectApply(op,this,args))};const op=streamReturningOperators[key];ObjectDefineProperty(fn,\"name\",{value:op.name}),ObjectDefineProperty(fn,\"length\",{value:op.length}),ObjectDefineProperty(Stream.Readable.prototype,key,{value:fn,enumerable:!1,configurable:!0,writable:!0})}for(let key of ObjectKeys(promiseReturningOperators)){let fn=function(...args){if(new.target)throw ERR_ILLEGAL_CONSTRUCTOR();return ReflectApply(op,this,args)};const op=promiseReturningOperators[key];ObjectDefineProperty(fn,\"name\",{value:op.name}),ObjectDefineProperty(fn,\"length\",{value:op.length}),ObjectDefineProperty(Stream.Readable.prototype,key,{value:fn,enumerable:!1,configurable:!0,writable:!0})}Stream.Writable=require_writable(),Stream.Duplex=require_duplex(),Stream.Transform=require_transform(),Stream.PassThrough=require_passthrough(),Stream.pipeline=pipeline;var{addAbortSignal}=require_add_abort_signal();Stream.addAbortSignal=addAbortSignal,Stream.finished=eos,Stream.destroy=destroyer,Stream.compose=compose,ObjectDefineProperty(Stream,\"promises\",{configurable:!0,enumerable:!0,get(){return promises2}}),ObjectDefineProperty(pipeline,customPromisify,{enumerable:!0,get(){return promises2.pipeline}}),ObjectDefineProperty(eos,customPromisify,{enumerable:!0,get(){return promises2.finished}}),Stream.Stream=Stream,Stream._isUint8Array=function isUint8Array(value){return value instanceof Uint8Array},Stream._uint8ArrayToBuffer=function _uint8ArrayToBuffer(chunk){return new Buffer(chunk.buffer,chunk.byteOffset,chunk.byteLength)}}});function createNativeStreamReadable(nativeType,Readable){var[pull,start,cancel,setClose,deinit,updateRef,drainFn]=globalThis[globalThis.Symbol.for('Bun.lazy')](nativeType),closer=[!1],handleNumberResult=function(nativeReadable,result,view,isClosed){if(result>0){const slice=view.subarray(0,result),remainder=view.subarray(result);if(slice.byteLength>0)nativeReadable.push(slice);if(isClosed)nativeReadable.push(null);return remainder.byteLength>0\?remainder:void 0}if(isClosed)nativeReadable.push(null);return view},handleArrayBufferViewResult=function(nativeReadable,result,view,isClosed){if(result.byteLength>0)nativeReadable.push(result);if(isClosed)nativeReadable.push(null);return view},DYNAMICALLY_ADJUST_CHUNK_SIZE=process.env.BUN_DISABLE_DYNAMIC_CHUNK_SIZE!==\"1\";const finalizer=new FinalizationRegistry((ptr)=>ptr&&deinit(ptr)),MIN_BUFFER_SIZE=512;var NativeReadable=class NativeReadable2 extends Readable{#bunNativePtr;#refCount=1;#constructed=!1;#remainingChunk=void 0;#highWaterMark;#pendingRead=!1;#hasResized=!DYNAMICALLY_ADJUST_CHUNK_SIZE;#unregisterToken;constructor(ptr,options={}){super(options);if(typeof options.highWaterMark===\"number\")this.#highWaterMark=options.highWaterMark;else this.#highWaterMark=262144;this.#bunNativePtr=ptr,this.#constructed=!1,this.#remainingChunk=void 0,this.#pendingRead=!1,this.#unregisterToken={},finalizer.register(this,this.#bunNativePtr,this.#unregisterToken)}_read(maxToRead){if(this.#pendingRead)return;var ptr=this.#bunNativePtr;if(ptr===0){this.push(null);return}if(!this.#constructed)this.#internalConstruct(ptr);return this.#internalRead(this.#getRemainingChunk(maxToRead),ptr)}#internalConstruct(ptr){this.#constructed=!0;const result=start(ptr,this.#highWaterMark);if(typeof result===\"number\"&&result>1)this.#hasResized=!0,this.#highWaterMark=Math.min(this.#highWaterMark,result);if(drainFn){const drainResult=drainFn(ptr);if((drainResult\?.byteLength\?\?0)>0)this.push(drainResult)}}#getRemainingChunk(maxToRead=this.#highWaterMark){var chunk=this.#remainingChunk;if(chunk\?.byteLength\?\?0MIN_BUFFER_SIZE\?maxToRead:MIN_BUFFER_SIZE;this.#remainingChunk=chunk=new Buffer(size)}return chunk}#handleResult(result,view,isClosed){if(typeof result===\"number\"){if(result>=this.#highWaterMark&&!this.#hasResized&&!isClosed)this.#highWaterMark*=2,this.#hasResized=!0;return handleNumberResult(this,result,view,isClosed)}else if(typeof result===\"boolean\")return process.nextTick(()=>{this.push(null)}),view\?.byteLength\?\?0>0\?view:void 0;else if(ArrayBuffer.isView(result)){if(result.byteLength>=this.#highWaterMark&&!this.#hasResized&&!isClosed)this.#highWaterMark*=2,this.#hasResized=!0;return handleArrayBufferViewResult(this,result,view,isClosed)}else throw new Error(\"Invalid result from pull\")}#internalRead(view,ptr){closer[0]=!1;var result=pull(ptr,view,closer);if(@isPromise(result))return this.#pendingRead=!0,result.then((result2)=>{this.#pendingRead=!1,this.#remainingChunk=this.#handleResult(result2,view,closer[0])},(reason)=>{errorOrDestroy(this,reason)});else this.#remainingChunk=this.#handleResult(result,view,closer[0])}_destroy(error,callback){var ptr=this.#bunNativePtr;if(ptr===0){callback(error);return}if(finalizer.unregister(this.#unregisterToken),this.#bunNativePtr=0,updateRef)updateRef(ptr,!1);cancel(ptr,error),callback(error)}ref(){var ptr=this.#bunNativePtr;if(ptr===0)return;if(this.#refCount++===0)updateRef(ptr,!0)}unref(){var ptr=this.#bunNativePtr;if(ptr===0)return;if(this.#refCount--===1)updateRef(ptr,!1)}};if(!updateRef)NativeReadable.prototype.ref=void 0,NativeReadable.prototype.unref=void 0;return NativeReadable}var nativeReadableStreamPrototypes={0:void 0,1:void 0,2:void 0,3:void 0,4:void 0,5:void 0};function getNativeReadableStreamPrototype(nativeType,Readable){return nativeReadableStreamPrototypes[nativeType]||=createNativeStreamReadable(nativeType,Readable)}function getNativeReadableStream(Readable,stream,options){if(!(stream&&typeof stream===\"object\"&&stream instanceof ReadableStream))return;const native=@direct(stream);if(!native)return;const{stream:ptr,data:type}=native;return new(getNativeReadableStreamPrototype(type,Readable))(ptr,options)}var Writable=require_writable(),NativeWritable=class NativeWritable2 extends Writable{#pathOrFdOrSink;#fileSink;#native=!0;_construct;_destroy;_final;constructor(pathOrFdOrSink,options={}){super(options);this._construct=this.#internalConstruct,this._destroy=this.#internalDestroy,this._final=this.#internalFinal,this.#pathOrFdOrSink=pathOrFdOrSink}#internalConstruct(cb){this._writableState.constructed=!0,this.constructed=!0,cb()}#lazyConstruct(){if(typeof this.#pathOrFdOrSink===\"object\")if(typeof this.#pathOrFdOrSink.write===\"function\")this.#fileSink=this.#pathOrFdOrSink;else throw new Error(\"Invalid FileSink\");else this.#fileSink=Bun.file(this.#pathOrFdOrSink).writer()}write(chunk,encoding,cb,native=this.#native){if(!native)return this.#native=!1,super.write(chunk,encoding,cb);if(!this.#fileSink)this.#lazyConstruct();var fileSink=this.#fileSink,result=fileSink.write(chunk);if(@isPromise(result))return result.then(()=>{this.emit(\"drain\"),fileSink.flush(!0)}),!1;if(fileSink.flush(!0),cb)cb(null,chunk.byteLength);return!0}end(chunk,encoding,cb,native=this.#native){return super.end(chunk,encoding,cb,native)}#internalDestroy(error,cb){if(this._writableState.destroyed=!0,cb)cb(error)}#internalFinal(cb){if(this.#fileSink)this.#fileSink.end();if(cb)cb()}ref(){if(!this.#fileSink)this.#lazyConstruct();this.#fileSink.ref()}unref(){if(!this.#fileSink)return;this.#fileSink.unref()}};const exports=require_stream(),promises=require_promises();return exports._getNativeReadableStreamPrototype=getNativeReadableStreamPrototype,exports.NativeWritable=NativeWritable,Object.defineProperty(exports,\"promises\",{configurable:!0,enumerable:!0,get(){return promises}}),exports[Symbol.for(\"::bunternal::\")]={_ReadableFromWeb,_ReadableFromWebForUndici},exports.eos=require_end_of_stream(),exports})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamPromisesCode = "(function (){\"use strict\";return(@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34)).promises})\n"_s; +// + +// +static constexpr ASCIILiteral NodeStreamWebCode = "(function (){\"use strict\";return{ReadableStream,ReadableStreamDefaultReader,ReadableStreamBYOBReader,ReadableStreamBYOBRequest,ReadableByteStreamController,ReadableStreamDefaultController,TransformStream,TransformStreamDefaultController,WritableStream,WritableStreamDefaultWriter,WritableStreamDefaultController,ByteLengthQueuingStrategy,CountQueuingStrategy}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTimersCode = "(function (){\"use strict\";return{setTimeout,clearTimeout,setInterval,setImmediate,clearInterval,clearImmediate}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTimersPromisesCode = "(function (){\"use strict\";var $;const symbolAsyncIterator=Symbol.asyncIterator;class ERR_INVALID_ARG_TYPE extends Error{constructor(name,expected,actual){super(`${name} must be ${expected}, ${typeof actual} given`);this.code=\"ERR_INVALID_ARG_TYPE\"}}class AbortError extends Error{constructor(){super(\"The operation was aborted\");this.code=\"ABORT_ERR\"}}function validateObject(object,name){if(object===null||typeof object!==\"object\")throw new ERR_INVALID_ARG_TYPE(name,\"Object\",object)}function validateBoolean(value,name){if(typeof value!==\"boolean\")throw new ERR_INVALID_ARG_TYPE(name,\"boolean\",value)}function validateAbortSignal(signal,name){if(typeof signal!==\"undefined\"&&(signal===null||typeof signal!==\"object\"||!(\"aborted\"in signal)))throw new ERR_INVALID_ARG_TYPE(name,\"AbortSignal\",signal)}function asyncIterator({next:nextFunction,return:returnFunction}){const result={};if(typeof nextFunction===\"function\")result.next=nextFunction;if(typeof returnFunction===\"function\")result.return=returnFunction;return result[symbolAsyncIterator]=function(){return this},result}function setTimeoutPromise(after=1,value,options={}){const arguments_=[].concat(value\?\?[]);try{validateObject(options,\"options\")}catch(error){return Promise.reject(error)}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return Promise.reject(error)}try{validateBoolean(reference,\"options.ref\")}catch(error){return Promise.reject(error)}if(signal\?.aborted)return Promise.reject(new AbortError);let onCancel;const returnValue=new Promise((resolve,reject)=>{const timeout=setTimeout(()=>resolve(value),after,...arguments_);if(!reference)timeout\?.unref\?.();if(signal)onCancel=()=>{clearTimeout(timeout),reject(new AbortError)},signal.addEventListener(\"abort\",onCancel)});if(typeof onCancel!==\"undefined\")returnValue.finally(()=>signal.removeEventListener(\"abort\",onCancel));return returnValue}function setImmediatePromise(value,options={}){try{validateObject(options,\"options\")}catch(error){return Promise.reject(error)}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return Promise.reject(error)}try{validateBoolean(reference,\"options.ref\")}catch(error){return Promise.reject(error)}if(signal\?.aborted)return Promise.reject(new AbortError);let onCancel;const returnValue=new Promise((resolve,reject)=>{const immediate=setImmediate(()=>resolve(value));if(!reference)immediate\?.unref\?.();if(signal)onCancel=()=>{clearImmediate(immediate),reject(new AbortError)},signal.addEventListener(\"abort\",onCancel)});if(typeof onCancel!==\"undefined\")returnValue.finally(()=>signal.removeEventListener(\"abort\",onCancel));return returnValue}function setIntervalPromise(after=1,value,options={}){try{validateObject(options,\"options\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}const{signal,ref:reference=!0}=options;try{validateAbortSignal(signal,\"options.signal\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}try{validateBoolean(reference,\"options.ref\")}catch(error){return asyncIterator({next:function(){return Promise.reject(error)}})}if(signal\?.aborted)return asyncIterator({next:function(){return Promise.reject(new AbortError)}});let onCancel,interval;try{let notYielded=0,callback;if(interval=setInterval(()=>{if(notYielded++,callback)callback(),callback=void 0},after),!reference)interval\?.unref\?.();if(signal)onCancel=()=>{if(clearInterval(interval),callback)callback(),callback=void 0},signal.addEventListener(\"abort\",onCancel);return asyncIterator({next:function(){return new Promise((resolve,reject)=>{if(!signal\?.aborted)if(notYielded===0)callback=resolve;else resolve();else if(notYielded===0)reject(new AbortError);else resolve()}).then(()=>{if(notYielded>0)return notYielded=notYielded-1,{done:!1,value};return{done:!0}})},return:function(){return clearInterval(interval),signal\?.removeEventListener(\"abort\",onCancel),Promise.resolve({})}})}catch(error){return asyncIterator({next:function(){clearInterval(interval),signal\?.removeEventListener(\"abort\",onCancel)}})}}return $={setTimeout:setTimeoutPromise,setImmediate:setImmediatePromise,setInterval:setIntervalPromise,scheduler:{wait:(delay,options)=>setTimeoutPromise(delay,void 0,options),yield:setImmediatePromise}},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeTLSCode = "(function (){\"use strict\";const{isArrayBufferView,isTypedArray}=@requireNativeModule(\"node:util/types\"),net=@getInternalField(@internalModuleRegistry,22)||@createInternalModuleById(22),{Server:NetServer,[Symbol.for(\"::bunternal::\")]:InternalTCPSocket}=net,bunSocketInternal=Symbol.for(\"::bunnetsocketinternal::\"),{rootCertificates,canonicalizeIP}=globalThis[globalThis.Symbol.for('Bun.lazy')](\"internal/tls\"),SymbolReplace=Symbol.replace,RegExpPrototypeSymbolReplace=RegExp.prototype[SymbolReplace],RegExpPrototypeExec=RegExp.prototype.exec,StringPrototypeStartsWith=String.prototype.startsWith,StringPrototypeSlice=String.prototype.slice,StringPrototypeIncludes=String.prototype.includes,StringPrototypeSplit=String.prototype.split,StringPrototypeIndexOf=String.prototype.indexOf,StringPrototypeSubstring=String.prototype.substring,StringPrototypeEndsWith=String.prototype.endsWith,StringFromCharCode=String.fromCharCode,StringPrototypeCharCodeAt=String.prototype.charCodeAt,ArrayPrototypeIncludes=Array.prototype.includes,ArrayPrototypeJoin=Array.prototype.join,ArrayPrototypeForEach=Array.prototype.forEach,ArrayPrototypePush=Array.prototype.push,ArrayPrototypeSome=Array.prototype.some,ArrayPrototypeReduce=Array.prototype.reduce;function parseCertString(){throwNotImplemented(\"Not implemented\")}function isValidTLSArray(obj){if(typeof obj===\"string\"||isTypedArray(obj)||obj instanceof ArrayBuffer||obj instanceof Blob)return!0;if(Array.isArray(obj)){for(var i=0;iRegExpPrototypeExec.call(/[^\\u0021-\\u007F]/u,s)!==null;if(ArrayPrototypeSome.call(patternParts,isBad))return!1;for(let i=hostParts.length-1;i>0;i-=1)if(hostParts[i]!==patternParts[i])return!1;const hostSubdomain=hostParts[0],patternSubdomain=patternParts[0],patternSubdomainParts=StringPrototypeSplit.call(patternSubdomain,\"*\");if(patternSubdomainParts.length===1||StringPrototypeIncludes.call(patternSubdomain,\"xn--\"))return hostSubdomain===patternSubdomain;if(!wildcards)return!1;if(patternSubdomainParts.length>2)return!1;if(patternParts.length<=2)return!1;const{0:prefix,1:suffix}=patternSubdomainParts;if(prefix.length+suffix.length>hostSubdomain.length)return!1;if(!StringPrototypeStartsWith.call(hostSubdomain,prefix))return!1;if(!StringPrototypeEndsWith.call(hostSubdomain,suffix))return!1;return!0}const jsonStringPattern=/^\"(\?:[^\"\\\\\\u0000-\\u001f]|\\\\(\?:[\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"/;function splitEscapedAltNames(altNames){const result=[];let currentToken=\"\",offset=0;while(offset!==altNames.length){const nextSep=StringPrototypeIndexOf.call(altNames,\", \",offset),nextQuote=StringPrototypeIndexOf.call(altNames,'\"',offset);if(nextQuote!==-1&&(nextSep===-1||nextQuote{if(StringPrototypeStartsWith.call(name,\"DNS:\"))ArrayPrototypePush.call(dnsNames,StringPrototypeSlice.call(name,4));else if(StringPrototypeStartsWith.call(name,\"IP Address:\"))ArrayPrototypePush.call(ips,canonicalizeIP(StringPrototypeSlice.call(name,11)))})}let valid=!1,reason=\"Unknown reason\";if(hostname=unfqdn(hostname),net.isIP(hostname)){if(valid=ArrayPrototypeIncludes.call(ips,canonicalizeIP(hostname)),!valid)reason=`IP: ${hostname} is not in the cert's list: `+ArrayPrototypeJoin.call(ips,\", \")}else if(dnsNames.length>0||subject\?.CN){const hostParts=splitHost(hostname),wildcard=(pattern)=>check(hostParts,pattern,!0);if(dnsNames.length>0){if(valid=ArrayPrototypeSome.call(dnsNames,wildcard),!valid)reason=`Host: ${hostname}. is not in the cert's altnames: ${altNames}`}else{const cn=subject.CN;if(Array.isArray(cn))valid=ArrayPrototypeSome.call(cn,wildcard);else if(cn)valid=wildcard(cn);if(!valid)reason=`Host: ${hostname}. is not cert's CN: ${cn}`}}else reason=\"Cert does not contain a DNS name\";if(!valid){let error=new Error(`ERR_TLS_CERT_ALTNAME_INVALID: Hostname/IP does not match certificate's altnames: ${reason}`);return error.name=\"ERR_TLS_CERT_ALTNAME_INVALID\",error.reason=reason,error.host=host,error.cert=cert,error}}var InternalSecureContext=class SecureContext2{context;constructor(options){const context={};if(options){let key=options.key;if(key){if(!isValidTLSArray(key))@throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.key=key}let cert=options.cert;if(cert){if(!isValidTLSArray(cert))@throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.cert=cert}let ca=options.ca;if(ca){if(!isValidTLSArray(ca))@throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.ca=ca}let passphrase=options.passphrase;if(passphrase&&typeof passphrase!==\"string\")@throwTypeError(\"passphrase argument must be an string\");this.passphrase=passphrase;let servername=options.servername;if(servername&&typeof servername!==\"string\")@throwTypeError(\"servername argument must be an string\");this.servername=servername;let secureOptions=options.secureOptions||0;if(secureOptions&&typeof secureOptions!==\"number\")@throwTypeError(\"secureOptions argument must be an number\");this.secureOptions=secureOptions}this.context=context}};function SecureContext(options){return new InternalSecureContext(options)}function createSecureContext(options){return new SecureContext(options)}function translatePeerCertificate(c){if(!c)return null;if(c.issuerCertificate!=null&&c.issuerCertificate!==c)c.issuerCertificate=translatePeerCertificate(c.issuerCertificate);if(c.infoAccess!=null){const info=c.infoAccess;c.infoAccess={__proto__:null},RegExpPrototypeSymbolReplace.call(/([^\\n:]*):([^\\n]*)(\?:\\n|$)/g,info,(all,key,val)=>{if(val.charCodeAt(0)===34)val=JSONParse(val);if(key in c.infoAccess)ArrayPrototypePush.call(c.infoAccess[key],val);else c.infoAccess[key]=[val]})}return c}const buntls=Symbol.for(\"::buntls::\");var SocketClass;const TLSSocket=function(InternalTLSSocket){return SocketClass=InternalTLSSocket,Object.defineProperty(SocketClass.prototype,Symbol.toStringTag,{value:\"TLSSocket\",enumerable:!1}),Object.defineProperty(function Socket(options){return new InternalTLSSocket(options)},Symbol.hasInstance,{value(instance){return instance instanceof InternalTLSSocket}})}(class TLSSocket2 extends InternalTCPSocket{#secureContext;ALPNProtocols;#socket;#checkServerIdentity;#session;constructor(socket,options){super(socket instanceof InternalTCPSocket\?options:options||socket);if(options=options||socket||{},typeof options===\"object\"){const{ALPNProtocols}=options;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,this);if(socket instanceof InternalTCPSocket)this.#socket=socket}this.#secureContext=options.secureContext||createSecureContext(options),this.authorized=!1,this.secureConnecting=!0,this._secureEstablished=!1,this._securePending=!0,this.#checkServerIdentity=options.checkServerIdentity||checkServerIdentity,this.#session=options.session||null}_secureEstablished=!1;_securePending=!0;_newSessionPending;_controlReleased;secureConnecting=!1;_SNICallback;servername;authorized=!1;authorizationError;#renegotiationDisabled=!1;encrypted=!0;_start(){this.connect()}getSession(){return this[bunSocketInternal]\?.getSession()}getEphemeralKeyInfo(){return this[bunSocketInternal]\?.getEphemeralKeyInfo()}getCipher(){return this[bunSocketInternal]\?.getCipher()}getSharedSigalgs(){return this[bunSocketInternal]\?.getSharedSigalgs()}getProtocol(){return this[bunSocketInternal]\?.getTLSVersion()}getFinished(){return this[bunSocketInternal]\?.getTLSFinishedMessage()||void 0}getPeerFinished(){return this[bunSocketInternal]\?.getTLSPeerFinishedMessage()||void 0}isSessionReused(){return!!this.#session}renegotiate(){if(this.#renegotiationDisabled){const error=new Error(\"ERR_TLS_RENEGOTIATION_DISABLED: TLS session renegotiation disabled for this socket\");throw error.name=\"ERR_TLS_RENEGOTIATION_DISABLED\",error}throw Error(\"Not implented in Bun yet\")}disableRenegotiation(){this.#renegotiationDisabled=!0}getTLSTicket(){return this[bunSocketInternal]\?.getTLSTicket()}exportKeyingMaterial(length,label,context){if(context)return this[bunSocketInternal]\?.exportKeyingMaterial(length,label,context);return this[bunSocketInternal]\?.exportKeyingMaterial(length,label)}setMaxSendFragment(size){return this[bunSocketInternal]\?.setMaxSendFragment(size)||!1}enableTrace(){}setServername(name){if(this.isServer){let error=new Error(\"ERR_TLS_SNI_FROM_SERVER: Cannot issue SNI from a TLS server-side socket\");throw error.name=\"ERR_TLS_SNI_FROM_SERVER\",error}this.servername=name,this[bunSocketInternal]\?.setServername(name)}setSession(session){if(this.#session=session,typeof session===\"string\")session=Buffer.from(session,\"latin1\");return this[bunSocketInternal]\?.setSession(session)}getPeerCertificate(abbreviated){const cert=arguments.length<1\?this[bunSocketInternal]\?.getPeerCertificate():this[bunSocketInternal]\?.getPeerCertificate(abbreviated);if(cert)return translatePeerCertificate(cert)}getCertificate(){const cert=this[bunSocketInternal]\?.getCertificate();if(cert)return translatePeerCertificate(cert)}getPeerX509Certificate(){throw Error(\"Not implented in Bun yet\")}getX509Certificate(){throw Error(\"Not implented in Bun yet\")}get alpnProtocol(){return this[bunSocketInternal]\?.alpnProtocol}[buntls](port,host2){return{socket:this.#socket,ALPNProtocols:this.ALPNProtocols,serverName:this.servername||host2||\"localhost\",checkServerIdentity:this.#checkServerIdentity,session:this.#session,...this.#secureContext}}});class Server extends NetServer{key;cert;ca;passphrase;secureOptions;_rejectUnauthorized;_requestCert;servername;ALPNProtocols;constructor(options,secureConnectionListener){super(options,secureConnectionListener);this.setSecureContext(options)}setSecureContext(options){if(options instanceof InternalSecureContext)options=options.context;if(options){const{ALPNProtocols}=options;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,this);let key=options.key;if(key){if(!isValidTLSArray(key))@throwTypeError(\"key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.key=key}let cert=options.cert;if(cert){if(!isValidTLSArray(cert))@throwTypeError(\"cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.cert=cert}let ca=options.ca;if(ca){if(!isValidTLSArray(ca))@throwTypeError(\"ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile\");this.ca=ca}let passphrase=options.passphrase;if(passphrase&&typeof passphrase!==\"string\")@throwTypeError(\"passphrase argument must be an string\");this.passphrase=passphrase;let servername=options.servername;if(servername&&typeof servername!==\"string\")@throwTypeError(\"servername argument must be an string\");this.servername=servername;let secureOptions=options.secureOptions||0;if(secureOptions&&typeof secureOptions!==\"number\")@throwTypeError(\"secureOptions argument must be an number\");this.secureOptions=secureOptions;const requestCert=options.requestCert||!1;if(requestCert)this._requestCert=requestCert;else this._requestCert=void 0;const rejectUnauthorized=options.rejectUnauthorized||!1;if(rejectUnauthorized)this._rejectUnauthorized=rejectUnauthorized;else this._rejectUnauthorized=void 0}}getTicketKeys(){throw Error(\"Not implented in Bun yet\")}setTicketKeys(){throw Error(\"Not implented in Bun yet\")}[buntls](port,host2,isClient){return[{serverName:this.servername||host2||\"localhost\",key:this.key,cert:this.cert,ca:this.ca,passphrase:this.passphrase,secureOptions:this.secureOptions,rejectUnauthorized:isClient\?!1:this._rejectUnauthorized,requestCert:isClient\?!1:this._requestCert,ALPNProtocols:this.ALPNProtocols},SocketClass]}}function createServer(options,connectionListener){return new Server(options,connectionListener)}const CLIENT_RENEG_LIMIT=3,CLIENT_RENEG_WINDOW=600,DEFAULT_ECDH_CURVE=\"auto\",DEFAULT_CIPHERS=\"DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256\",DEFAULT_MIN_VERSION=\"TLSv1.2\",DEFAULT_MAX_VERSION=\"TLSv1.3\",createConnection=(port,host2,connectListener)=>{if(typeof port===\"object\"){port.checkServerIdentity;const{ALPNProtocols}=port;if(ALPNProtocols)convertALPNProtocols(ALPNProtocols,port);return new TLSSocket(port).connect(port,host2,connectListener)}return new TLSSocket().connect(port,host2,connectListener)},connect=createConnection;function getCiphers(){return DEFAULT_CIPHERS.split(\":\")}function convertProtocols(protocols){const lens=new Array(protocols.length),buff=Buffer.allocUnsafe(ArrayPrototypeReduce.call(protocols,(p,c,i)=>{const len=Buffer.byteLength(c);if(len>255)@throwRangeError(\"The byte length of the protocol at index \"+`${i} exceeds the maximum length.`,\"<= 255\",len,!0);return lens[i]=len,p+1+len},0));let offset=0;for(let i=0,c=protocols.length;i\",'\"',\"`\",\" \",\"\\r\",\"\\n\",\"\\t\"],unwise=[\"{\",\"}\",\"|\",\"\\\\\",\"^\",\"`\"].concat(delims),autoEscape=[\"'\"].concat(unwise),nonHostChars=[\"%\",\"/\",\"\?\",\";\",\"#\"].concat(autoEscape),hostEndingChars=[\"/\",\"\?\",\"#\"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,\"javascript:\":!0},hostlessProtocol={javascript:!0,\"javascript:\":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,\"http:\":!0,\"https:\":!0,\"ftp:\":!0,\"gopher:\":!0,\"file:\":!0};function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&typeof url===\"object\"&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(typeof url!==\"string\")@throwTypeError(\"Parameter 'url' must be a string, not \"+typeof url);var queryIndex=url.indexOf(\"\?\"),splitter=queryIndex!==-1&&queryIndex127)newpart+=\"x\";else newpart+=part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);if(bit)validParts.push(bit[1]),notHost.unshift(bit[2]);if(notHost.length)rest=\"/\"+notHost.join(\".\")+rest;this.hostname=validParts.join(\".\");break}}}}if(this.hostname.length>hostnameMaxLen)this.hostname=\"\";else this.hostname=this.hostname.toLowerCase();if(!ipv6Hostname)this.hostname=new URL(\"http://\"+this.hostname).hostname;var p=this.port\?\":\"+this.port:\"\",h=this.hostname||\"\";if(this.host=h+p,this.href+=this.host,ipv6Hostname){if(this.hostname=this.hostname.substr(1,this.hostname.length-2),rest[0]!==\"/\")rest=\"/\"+rest}}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length;i0\?result.host.split(\"@\"):!1;if(authInHost)result.auth=authInHost.shift(),result.hostname=authInHost.shift(),result.host=result.hostname}if(result.search=relative.search,result.query=relative.query,result.pathname!==null||result.search!==null)result.path=(result.pathname\?result.pathname:\"\")+(result.search\?result.search:\"\");return result.href=result.format(),result}if(!srcPath.length){if(result.pathname=null,result.search)result.path=\"/\"+result.search;else result.path=null;return result.href=result.format(),result}var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last===\".\"||last===\"..\")||last===\"\",up=0;for(var i=srcPath.length;i>=0;i--)if(last=srcPath[i],last===\".\")srcPath.splice(i,1);else if(last===\"..\")srcPath.splice(i,1),up++;else if(up)srcPath.splice(i,1),up--;if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift(\"..\");if(mustEndAbs&&srcPath[0]!==\"\"&&(!srcPath[0]||srcPath[0].charAt(0)!==\"/\"))srcPath.unshift(\"\");if(hasTrailingSlash&&srcPath.join(\"/\").substr(-1)!==\"/\")srcPath.push(\"\");var isAbsolute=srcPath[0]===\"\"||srcPath[0]&&srcPath[0].charAt(0)===\"/\";if(psychotic){result.hostname=isAbsolute\?\"\":srcPath.length\?srcPath.shift():\"\",result.host=result.hostname;var authInHost=result.host&&result.host.indexOf(\"@\")>0\?result.host.split(\"@\"):!1;if(authInHost)result.auth=authInHost.shift(),result.hostname=authInHost.shift(),result.host=result.hostname}if(mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute)srcPath.unshift(\"\");if(srcPath.length>0)result.pathname=srcPath.join(\"/\");else result.pathname=null,result.path=null;if(result.pathname!==null||result.search!==null)result.path=(result.pathname\?result.pathname:\"\")+(result.search\?result.search:\"\");return result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);if(port){if(port=port[0],port!==\":\")this.port=port.substr(1);host=host.substr(0,host.length-port.length)}if(host)this.hostname=host};function urlToHttpOptions(url){const options={protocol:url.protocol,hostname:typeof url.hostname===\"string\"&&url.hostname.startsWith(\"[\")\?url.hostname.slice(1,-1):url.hostname,hash:url.hash,search:url.search,pathname:url.pathname,path:`${url.pathname||\"\"}${url.search||\"\"}`,href:url.href};if(url.port!==\"\")options.port=Number(url.port);if(url.username||url.password)options.auth=`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;return options}const pathToFileURL=globalThis[globalThis.Symbol.for('Bun.lazy')](\"pathToFileURL\"),fileURLToPath=globalThis[globalThis.Symbol.for('Bun.lazy')](\"fileURLToPath\");return{parse:urlParse,resolve:urlResolve,resolveObject:urlResolveObject,format:urlFormat,Url,URLSearchParams,URL,pathToFileURL,fileURLToPath,urlToHttpOptions}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeUtilCode = "(function (){\"use strict\";const types=@requireNativeModule(\"node:util/types\");var cjs_exports={};function isBufferInterface({copy,fill,readUint8}){return typeof copy===\"function\"&&typeof fill===\"function\"&&typeof readUint8===\"function\"}function isBuffer(value){return Buffer.isBuffer(value)||typeof value===\"object\"&&isBufferInterface(value||{})}function isFunction(value){return typeof value===\"function\"}const deepEquals=Bun.deepEquals,isDeepStrictEqual=(a,b)=>deepEquals(a,b,!0);var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors,formatRegExp=/%[sdj%]/g;function format(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x2;switch(x2){case\"%s\":return String(args[i++]);case\"%d\":return Number(args[i++]);case\"%j\":try{return JSON.stringify(args[i++])}catch(_){return\"[Circular]\"}default:return x2}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts))ctx.showHidden=opts;else if(opts)_extend(ctx,opts);if(isUndefined(ctx.showHidden))ctx.showHidden=!1;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=!1;if(isUndefined(ctx.customInspect))ctx.customInspect=!0;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:\"cyan\",number:\"yellow\",boolean:\"yellow\",undefined:\"grey\",null:\"bold\",string:\"green\",date:\"magenta\",regexp:\"red\"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style)return\"\\x1B[\"+inspect.colors[style][0]+\"m\"+str+\"\\x1B[\"+inspect.colors[style][1]+\"m\";else return str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret))ret=formatValue(ctx,ret,recurseTimes);return ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden)keys=Object.getOwnPropertyNames(value);if(isError(value)&&(keys.indexOf(\"message\")>=0||keys.indexOf(\"description\")>=0))return formatError(value);if(keys.length===0){if(isFunction(value)){var name=value.name\?\": \"+value.name:\"\";return ctx.stylize(\"[Function\"+name+\"]\",\"special\")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),\"regexp\");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),\"date\");if(isError(value))return formatError(value)}var base=\"\",array=!1,braces=[\"{\",\"}\"];if(@isArray(value))array=!0,braces=[\"[\",\"]\"];if(isFunction(value)){var n=value.name\?\": \"+value.name:\"\";base=\" [Function\"+n+\"]\"}if(isRegExp(value))base=\" \"+RegExp.prototype.toString.call(value);if(isDate(value))base=\" \"+Date.prototype.toUTCString.call(value);if(isError(value))base=\" \"+formatError(value);if(keys.length===0&&(!array||value.length==0))return braces[0]+base+braces[1];if(recurseTimes<0)if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),\"regexp\");else return ctx.stylize(\"[Object]\",\"special\");ctx.seen.push(value);var output;if(array)output=formatArray(ctx,value,recurseTimes,visibleKeys,keys);else output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)});return ctx.seen.pop(),reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize(\"undefined\",\"undefined\");if(isString(value)){var simple=\"'\"+JSON.stringify(value).replace(/^\"|\"$/g,\"\").replace(/'/g,\"\\\\'\").replace(/\\\\\"/g,'\"')+\"'\";return ctx.stylize(simple,\"string\")}if(isNumber(value))return ctx.stylize(\"\"+value,\"number\");if(isBoolean(value))return ctx.stylize(\"\"+value,\"boolean\");if(isNull(value))return ctx.stylize(\"null\",\"null\")}function formatError(value){return\"[\"+Error.prototype.toString.call(value)+\"]\"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1)if(array)str=str.split(\"\\n\").map(function(line){return\" \"+line}).join(\"\\n\").substr(2);else str=\"\\n\"+str.split(\"\\n\").map(function(line){return\" \"+line}).join(\"\\n\")}else str=ctx.stylize(\"[Circular]\",\"special\");if(isUndefined(name)){if(array&&key.match(/^\\d+$/))return str;if(name=JSON.stringify(\"\"+key),name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/))name=name.substr(1,name.length-2),name=ctx.stylize(name,\"name\");else name=name.replace(/'/g,\"\\\\'\").replace(/\\\\\"/g,'\"').replace(/(^\"|\"$)/g,\"'\"),name=ctx.stylize(name,\"string\")}return name+\": \"+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){if(numLinesEst++,cur.indexOf(\"\\n\")>=0)numLinesEst++;return prev+cur.replace(/\\u001b\\[\\d\\d\?m/g,\"\").length+1},0);if(length>60)return braces[0]+(base===\"\"\?\"\":base+\"\\n \")+\" \"+output.join(\",\\n \")+\" \"+braces[1];return braces[0]+base+\" \"+output.join(\", \")+\" \"+braces[1]}function isBoolean(arg){return typeof arg===\"boolean\"}function isNull(arg){return arg===null}function isNullOrUndefined(arg){return arg==null}function isNumber(arg){return typeof arg===\"number\"}function isString(arg){return typeof arg===\"string\"}function isSymbol(arg){return typeof arg===\"symbol\"}function isUndefined(arg){return arg===void 0}var isRegExp=types.isRegExp;function isObject(arg){return typeof arg===\"object\"&&arg!==null}var{isDate,isNativeError:isError}=types;function isPrimitive(arg){return arg===null||typeof arg===\"boolean\"||typeof arg===\"number\"||typeof arg===\"string\"||typeof arg===\"symbol\"||typeof arg===\"undefined\"}function pad(n){return n<10\?\"0\"+n.toString(10):n.toString(10)}var months=[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"];function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(\":\");return[d.getDate(),months[d.getMonth()],time].join(\" \")}var log=function log(){console.log(\"%s - %s\",timestamp(),format.apply(cjs_exports,arguments))},inherits=function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},_extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add),i=keys.length;while(i--)origin[keys[i]]=add[keys[i]];return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var kCustomPromisifiedSymbol=Symbol.for(\"util.promisify.custom\"),promisify=function promisify(original){if(typeof original!==\"function\")@throwTypeError('The \"original\" argument must be of type Function');if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if(typeof fn!==\"function\")@throwTypeError('The \"util.promisify.custom\" argument must be of type Function');return Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),fn}function fn(){var promiseResolve,promiseReject,promise=new Promise(function(resolve,reject){promiseResolve=resolve,promiseReject=reject}),args=[];for(var i=0;i{return(input+\"\").toWellFormed()};return Object.assign(cjs_exports,{format,deprecate,debuglog,_extend,inspect,types,isArray:@isArray,isBoolean,isNull,isNullOrUndefined,isNumber,isString,isSymbol,isUndefined,isRegExp,isObject,isDate,isFunction,isError,isPrimitive,isBuffer,log,inherits,toUSVString,promisify,callbackify,isDeepStrictEqual,TextDecoder,TextEncoder})})\n"_s; +// + +// +static constexpr ASCIILiteral NodeV8Code = "(function (){\"use strict\";var $;const{hideFromStack,throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),jsc=@requireNativeModule(\"bun:jsc\");function notimpl(message){throwNotImplemented(\"node:v8 \"+message)}class Deserializer{constructor(){notimpl(\"Deserializer\")}}class Serializer{constructor(){notimpl(\"Serializer\")}}class DefaultDeserializer extends Deserializer{constructor(){super(...arguments)}}class DefaultSerializer extends Serializer{constructor(){super(...arguments)}}class GCProfiler{constructor(){notimpl(\"GCProfiler\")}}function cachedDataVersionTag(){notimpl(\"cachedDataVersionTag\")}function getHeapSnapshot(){notimpl(\"getHeapSnapshot\")}function getHeapStatistics(){notimpl(\"getHeapStatistics\")}function getHeapSpaceStatistics(){notimpl(\"getHeapSpaceStatistics\")}function getHeapCodeStatistics(){notimpl(\"getHeapCodeStatistics\")}function setFlagsFromString(){notimpl(\"setFlagsFromString\")}function deserialize(value){return jsc.deserialize(value)}function takeCoverage(){notimpl(\"takeCoverage\")}function stopCoverage(){notimpl(\"stopCoverage\")}function serialize(arg1){return jsc.serialize(arg1,{binaryType:\"nodebuffer\"})}function writeHeapSnapshot(){notimpl(\"writeHeapSnapshot\")}function setHeapSnapshotNearHeapLimit(){notimpl(\"setHeapSnapshotNearHeapLimit\")}return $={cachedDataVersionTag,getHeapSnapshot,getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,deserialize,takeCoverage,stopCoverage,serialize,writeHeapSnapshot,setHeapSnapshotNearHeapLimit,promiseHooks:{createHook:()=>{notimpl(\"createHook\")},onInit:()=>{notimpl(\"onInit\")},onBefore:()=>{notimpl(\"onBefore\")},onAfter:()=>{notimpl(\"onAfter\")},onSettled:()=>{notimpl(\"onSettled\")}},startupSnapshot:{addDeserializeCallback:()=>notimpl(\"addDeserializeCallback\"),addSerializeCallback:()=>notimpl(\"addSerializeCallback\"),setDeserializeMainFunction:()=>notimpl(\"setDeserializeMainFunction\"),isBuildingSnapshot:()=>notimpl(\"isBuildingSnapshot\")},Deserializer,Serializer},hideFromStack(notimpl,cachedDataVersionTag,getHeapSnapshot,getHeapStatistics,getHeapSpaceStatistics,getHeapCodeStatistics,setFlagsFromString,deserialize,takeCoverage,stopCoverage,serialize,writeHeapSnapshot,setHeapSnapshotNearHeapLimit,Deserializer,Serializer,DefaultDeserializer,DefaultSerializer,GCProfiler),$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeVMCode = "(function (){\"use strict\";const{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),vm=globalThis[globalThis.Symbol.for('Bun.lazy')](\"vm\"),{createContext,isContext,Script,runInNewContext,runInThisContext}=vm;function runInContext(code,context,options){return new Script(code,options).runInContext(context)}function compileFunction(){throwNotImplemented(\"node:vm compileFunction\")}function measureMemory(){throwNotImplemented(\"node:vm measureMemory\")}class Module{constructor(){throwNotImplemented(\"node:vm Module\")}}class SourceTextModule{constructor(){throwNotImplemented(\"node:vm Module\")}}class SyntheticModule{constructor(){throwNotImplemented(\"node:vm Module\")}}return{createContext,runInContext,runInNewContext,runInThisContext,isContext,compileFunction,measureMemory,Script,Module,SourceTextModule,SyntheticModule}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeWasiCode = "(function (){\"use strict\";const nodeFsConstants=@processBindingConstants.fs;var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require2(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_types=__commonJS({\"node_modules/wasi-js/dist/types.js\"(exports){Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.WASIKillError=exports.WASIExitError=exports.WASIError=void 0;var WASIError=class extends Error{constructor(errno){super();this.errno=errno,Object.setPrototypeOf(this,WASIError.prototype)}};exports.WASIError=WASIError;var WASIExitError=class extends Error{constructor(code){super(`WASI Exit error: ${code}`);this.code=code,Object.setPrototypeOf(this,WASIExitError.prototype)}};exports.WASIExitError=WASIExitError;var WASIKillError=class extends Error{constructor(signal){super(`WASI Kill signal: ${signal}`);this.signal=signal,Object.setPrototypeOf(this,WASIKillError.prototype)}};exports.WASIKillError=WASIKillError}}),require_constants=__commonJS({\"node_modules/wasi-js/dist/constants.js\"(exports){Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.WASI_ENOMSG=exports.WASI_ENOMEM=exports.WASI_ENOLINK=exports.WASI_ENOLCK=exports.WASI_ENOEXEC=exports.WASI_ENOENT=exports.WASI_ENODEV=exports.WASI_ENOBUFS=exports.WASI_ENFILE=exports.WASI_ENETUNREACH=exports.WASI_ENETRESET=exports.WASI_ENETDOWN=exports.WASI_ENAMETOOLONG=exports.WASI_EMULTIHOP=exports.WASI_EMSGSIZE=exports.WASI_EMLINK=exports.WASI_EMFILE=exports.WASI_ELOOP=exports.WASI_EISDIR=exports.WASI_EISCONN=exports.WASI_EIO=exports.WASI_EINVAL=exports.WASI_EINTR=exports.WASI_EINPROGRESS=exports.WASI_EILSEQ=exports.WASI_EIDRM=exports.WASI_EHOSTUNREACH=exports.WASI_EFBIG=exports.WASI_EFAULT=exports.WASI_EEXIST=exports.WASI_EDQUOT=exports.WASI_EDOM=exports.WASI_EDESTADDRREQ=exports.WASI_EDEADLK=exports.WASI_ECONNRESET=exports.WASI_ECONNREFUSED=exports.WASI_ECONNABORTED=exports.WASI_ECHILD=exports.WASI_ECANCELED=exports.WASI_EBUSY=exports.WASI_EBADMSG=exports.WASI_EBADF=exports.WASI_EALREADY=exports.WASI_EAGAIN=exports.WASI_EAFNOSUPPORT=exports.WASI_EADDRNOTAVAIL=exports.WASI_EADDRINUSE=exports.WASI_EACCES=exports.WASI_E2BIG=exports.WASI_ESUCCESS=void 0,exports.WASI_SIGVTALRM=exports.WASI_SIGUSR2=exports.WASI_SIGUSR1=exports.WASI_SIGURG=exports.WASI_SIGTTOU=exports.WASI_SIGTTIN=exports.WASI_SIGTSTP=exports.WASI_SIGTRAP=exports.WASI_SIGTERM=exports.WASI_SIGSTOP=exports.WASI_SIGSEGV=exports.WASI_SIGQUIT=exports.WASI_SIGPIPE=exports.WASI_SIGKILL=exports.WASI_SIGINT=exports.WASI_SIGILL=exports.WASI_SIGHUP=exports.WASI_SIGFPE=exports.WASI_SIGCONT=exports.WASI_SIGCHLD=exports.WASI_SIGBUS=exports.WASI_SIGALRM=exports.WASI_SIGABRT=exports.WASI_ENOTCAPABLE=exports.WASI_EXDEV=exports.WASI_ETXTBSY=exports.WASI_ETIMEDOUT=exports.WASI_ESTALE=exports.WASI_ESRCH=exports.WASI_ESPIPE=exports.WASI_EROFS=exports.WASI_ERANGE=exports.WASI_EPROTOTYPE=exports.WASI_EPROTONOSUPPORT=exports.WASI_EPROTO=exports.WASI_EPIPE=exports.WASI_EPERM=exports.WASI_EOWNERDEAD=exports.WASI_EOVERFLOW=exports.WASI_ENXIO=exports.WASI_ENOTTY=exports.WASI_ENOTSUP=exports.WASI_ENOTSOCK=exports.WASI_ENOTRECOVERABLE=exports.WASI_ENOTEMPTY=exports.WASI_ENOTDIR=exports.WASI_ENOTCONN=exports.WASI_ENOSYS=exports.WASI_ENOSPC=exports.WASI_ENOPROTOOPT=void 0,exports.RIGHTS_REGULAR_FILE_BASE=exports.RIGHTS_CHARACTER_DEVICE_INHERITING=exports.RIGHTS_CHARACTER_DEVICE_BASE=exports.RIGHTS_BLOCK_DEVICE_INHERITING=exports.RIGHTS_BLOCK_DEVICE_BASE=exports.RIGHTS_ALL=exports.WASI_RIGHT_SOCK_SHUTDOWN=exports.WASI_RIGHT_POLL_FD_READWRITE=exports.WASI_RIGHT_PATH_UNLINK_FILE=exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY=exports.WASI_RIGHT_PATH_SYMLINK=exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES=exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE=exports.WASI_RIGHT_FD_FILESTAT_GET=exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES=exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE=exports.WASI_RIGHT_PATH_FILESTAT_GET=exports.WASI_RIGHT_PATH_RENAME_TARGET=exports.WASI_RIGHT_PATH_RENAME_SOURCE=exports.WASI_RIGHT_PATH_READLINK=exports.WASI_RIGHT_FD_READDIR=exports.WASI_RIGHT_PATH_OPEN=exports.WASI_RIGHT_PATH_LINK_TARGET=exports.WASI_RIGHT_PATH_LINK_SOURCE=exports.WASI_RIGHT_PATH_CREATE_FILE=exports.WASI_RIGHT_PATH_CREATE_DIRECTORY=exports.WASI_RIGHT_FD_ALLOCATE=exports.WASI_RIGHT_FD_ADVISE=exports.WASI_RIGHT_FD_WRITE=exports.WASI_RIGHT_FD_TELL=exports.WASI_RIGHT_FD_SYNC=exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS=exports.WASI_RIGHT_FD_SEEK=exports.WASI_RIGHT_FD_READ=exports.WASI_RIGHT_FD_DATASYNC=exports.WASI_FDFLAG_SYNC=exports.WASI_FDFLAG_RSYNC=exports.WASI_FDFLAG_NONBLOCK=exports.WASI_FDFLAG_DSYNC=exports.WASI_FDFLAG_APPEND=exports.WASI_FILETYPE_SYMBOLIC_LINK=exports.WASI_FILETYPE_SOCKET_STREAM=exports.WASI_FILETYPE_SOCKET_DGRAM=exports.WASI_FILETYPE_REGULAR_FILE=exports.WASI_FILETYPE_DIRECTORY=exports.WASI_FILETYPE_CHARACTER_DEVICE=exports.WASI_FILETYPE_BLOCK_DEVICE=exports.WASI_FILETYPE_UNKNOWN=exports.WASI_SIGXFSZ=exports.WASI_SIGXCPU=void 0,exports.SIGNAL_MAP=exports.ERROR_MAP=exports.WASI_WHENCE_END=exports.WASI_WHENCE_CUR=exports.WASI_WHENCE_SET=exports.WASI_STDERR_FILENO=exports.WASI_STDOUT_FILENO=exports.WASI_STDIN_FILENO=exports.WASI_DIRCOOKIE_START=exports.WASI_PREOPENTYPE_DIR=exports.WASI_O_TRUNC=exports.WASI_O_EXCL=exports.WASI_O_DIRECTORY=exports.WASI_O_CREAT=exports.WASI_FILESTAT_SET_MTIM_NOW=exports.WASI_FILESTAT_SET_MTIM=exports.WASI_FILESTAT_SET_ATIM_NOW=exports.WASI_FILESTAT_SET_ATIM=exports.WASI_EVENTTYPE_FD_WRITE=exports.WASI_EVENTTYPE_FD_READ=exports.WASI_EVENTTYPE_CLOCK=exports.WASI_CLOCK_THREAD_CPUTIME_ID=exports.WASI_CLOCK_PROCESS_CPUTIME_ID=exports.WASI_CLOCK_MONOTONIC=exports.WASI_CLOCK_REALTIME=exports.RIGHTS_TTY_INHERITING=exports.RIGHTS_TTY_BASE=exports.RIGHTS_SOCKET_INHERITING=exports.RIGHTS_SOCKET_BASE=exports.RIGHTS_DIRECTORY_INHERITING=exports.RIGHTS_DIRECTORY_BASE=exports.RIGHTS_REGULAR_FILE_INHERITING=void 0,exports.WASI_ESUCCESS=0,exports.WASI_E2BIG=1,exports.WASI_EACCES=2,exports.WASI_EADDRINUSE=3,exports.WASI_EADDRNOTAVAIL=4,exports.WASI_EAFNOSUPPORT=5,exports.WASI_EAGAIN=6,exports.WASI_EALREADY=7,exports.WASI_EBADF=8,exports.WASI_EBADMSG=9,exports.WASI_EBUSY=10,exports.WASI_ECANCELED=11,exports.WASI_ECHILD=12,exports.WASI_ECONNABORTED=13,exports.WASI_ECONNREFUSED=14,exports.WASI_ECONNRESET=15,exports.WASI_EDEADLK=16,exports.WASI_EDESTADDRREQ=17,exports.WASI_EDOM=18,exports.WASI_EDQUOT=19,exports.WASI_EEXIST=20,exports.WASI_EFAULT=21,exports.WASI_EFBIG=22,exports.WASI_EHOSTUNREACH=23,exports.WASI_EIDRM=24,exports.WASI_EILSEQ=25,exports.WASI_EINPROGRESS=26,exports.WASI_EINTR=27,exports.WASI_EINVAL=28,exports.WASI_EIO=29,exports.WASI_EISCONN=30,exports.WASI_EISDIR=31,exports.WASI_ELOOP=32,exports.WASI_EMFILE=33,exports.WASI_EMLINK=34,exports.WASI_EMSGSIZE=35,exports.WASI_EMULTIHOP=36,exports.WASI_ENAMETOOLONG=37,exports.WASI_ENETDOWN=38,exports.WASI_ENETRESET=39,exports.WASI_ENETUNREACH=40,exports.WASI_ENFILE=41,exports.WASI_ENOBUFS=42,exports.WASI_ENODEV=43,exports.WASI_ENOENT=44,exports.WASI_ENOEXEC=45,exports.WASI_ENOLCK=46,exports.WASI_ENOLINK=47,exports.WASI_ENOMEM=48,exports.WASI_ENOMSG=49,exports.WASI_ENOPROTOOPT=50,exports.WASI_ENOSPC=51,exports.WASI_ENOSYS=52,exports.WASI_ENOTCONN=53,exports.WASI_ENOTDIR=54,exports.WASI_ENOTEMPTY=55,exports.WASI_ENOTRECOVERABLE=56,exports.WASI_ENOTSOCK=57,exports.WASI_ENOTSUP=58,exports.WASI_ENOTTY=59,exports.WASI_ENXIO=60,exports.WASI_EOVERFLOW=61,exports.WASI_EOWNERDEAD=62,exports.WASI_EPERM=63,exports.WASI_EPIPE=64,exports.WASI_EPROTO=65,exports.WASI_EPROTONOSUPPORT=66,exports.WASI_EPROTOTYPE=67,exports.WASI_ERANGE=68,exports.WASI_EROFS=69,exports.WASI_ESPIPE=70,exports.WASI_ESRCH=71,exports.WASI_ESTALE=72,exports.WASI_ETIMEDOUT=73,exports.WASI_ETXTBSY=74,exports.WASI_EXDEV=75,exports.WASI_ENOTCAPABLE=76,exports.WASI_SIGABRT=0,exports.WASI_SIGALRM=1,exports.WASI_SIGBUS=2,exports.WASI_SIGCHLD=3,exports.WASI_SIGCONT=4,exports.WASI_SIGFPE=5,exports.WASI_SIGHUP=6,exports.WASI_SIGILL=7,exports.WASI_SIGINT=8,exports.WASI_SIGKILL=9,exports.WASI_SIGPIPE=10,exports.WASI_SIGQUIT=11,exports.WASI_SIGSEGV=12,exports.WASI_SIGSTOP=13,exports.WASI_SIGTERM=14,exports.WASI_SIGTRAP=15,exports.WASI_SIGTSTP=16,exports.WASI_SIGTTIN=17,exports.WASI_SIGTTOU=18,exports.WASI_SIGURG=19,exports.WASI_SIGUSR1=20,exports.WASI_SIGUSR2=21,exports.WASI_SIGVTALRM=22,exports.WASI_SIGXCPU=23,exports.WASI_SIGXFSZ=24,exports.WASI_FILETYPE_UNKNOWN=0,exports.WASI_FILETYPE_BLOCK_DEVICE=1,exports.WASI_FILETYPE_CHARACTER_DEVICE=2,exports.WASI_FILETYPE_DIRECTORY=3,exports.WASI_FILETYPE_REGULAR_FILE=4,exports.WASI_FILETYPE_SOCKET_DGRAM=5,exports.WASI_FILETYPE_SOCKET_STREAM=6,exports.WASI_FILETYPE_SYMBOLIC_LINK=7,exports.WASI_FDFLAG_APPEND=1,exports.WASI_FDFLAG_DSYNC=2,exports.WASI_FDFLAG_NONBLOCK=4,exports.WASI_FDFLAG_RSYNC=8,exports.WASI_FDFLAG_SYNC=16,exports.WASI_RIGHT_FD_DATASYNC=BigInt(1),exports.WASI_RIGHT_FD_READ=BigInt(2),exports.WASI_RIGHT_FD_SEEK=BigInt(4),exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS=BigInt(8),exports.WASI_RIGHT_FD_SYNC=BigInt(16),exports.WASI_RIGHT_FD_TELL=BigInt(32),exports.WASI_RIGHT_FD_WRITE=BigInt(64),exports.WASI_RIGHT_FD_ADVISE=BigInt(128),exports.WASI_RIGHT_FD_ALLOCATE=BigInt(256),exports.WASI_RIGHT_PATH_CREATE_DIRECTORY=BigInt(512),exports.WASI_RIGHT_PATH_CREATE_FILE=BigInt(1024),exports.WASI_RIGHT_PATH_LINK_SOURCE=BigInt(2048),exports.WASI_RIGHT_PATH_LINK_TARGET=BigInt(4096),exports.WASI_RIGHT_PATH_OPEN=BigInt(8192),exports.WASI_RIGHT_FD_READDIR=BigInt(16384),exports.WASI_RIGHT_PATH_READLINK=BigInt(32768),exports.WASI_RIGHT_PATH_RENAME_SOURCE=BigInt(65536),exports.WASI_RIGHT_PATH_RENAME_TARGET=BigInt(131072),exports.WASI_RIGHT_PATH_FILESTAT_GET=BigInt(262144),exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE=BigInt(524288),exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES=BigInt(1048576),exports.WASI_RIGHT_FD_FILESTAT_GET=BigInt(2097152),exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE=BigInt(4194304),exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES=BigInt(8388608),exports.WASI_RIGHT_PATH_SYMLINK=BigInt(16777216),exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY=BigInt(33554432),exports.WASI_RIGHT_PATH_UNLINK_FILE=BigInt(67108864),exports.WASI_RIGHT_POLL_FD_READWRITE=BigInt(134217728),exports.WASI_RIGHT_SOCK_SHUTDOWN=BigInt(268435456),exports.RIGHTS_ALL=exports.WASI_RIGHT_FD_DATASYNC|exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_SEEK|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_TELL|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_FD_ALLOCATE|exports.WASI_RIGHT_PATH_CREATE_DIRECTORY|exports.WASI_RIGHT_PATH_CREATE_FILE|exports.WASI_RIGHT_PATH_LINK_SOURCE|exports.WASI_RIGHT_PATH_LINK_TARGET|exports.WASI_RIGHT_PATH_OPEN|exports.WASI_RIGHT_FD_READDIR|exports.WASI_RIGHT_PATH_READLINK|exports.WASI_RIGHT_PATH_RENAME_SOURCE|exports.WASI_RIGHT_PATH_RENAME_TARGET|exports.WASI_RIGHT_PATH_FILESTAT_GET|exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_SYMLINK|exports.WASI_RIGHT_PATH_UNLINK_FILE|exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY|exports.WASI_RIGHT_POLL_FD_READWRITE|exports.WASI_RIGHT_SOCK_SHUTDOWN,exports.RIGHTS_BLOCK_DEVICE_BASE=exports.RIGHTS_ALL,exports.RIGHTS_BLOCK_DEVICE_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_CHARACTER_DEVICE_BASE=exports.RIGHTS_ALL,exports.RIGHTS_CHARACTER_DEVICE_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_REGULAR_FILE_BASE=exports.WASI_RIGHT_FD_DATASYNC|exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_SEEK|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_TELL|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_FD_ALLOCATE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_REGULAR_FILE_INHERITING=BigInt(0),exports.RIGHTS_DIRECTORY_BASE=exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_SYNC|exports.WASI_RIGHT_FD_ADVISE|exports.WASI_RIGHT_PATH_CREATE_DIRECTORY|exports.WASI_RIGHT_PATH_CREATE_FILE|exports.WASI_RIGHT_PATH_LINK_SOURCE|exports.WASI_RIGHT_PATH_LINK_TARGET|exports.WASI_RIGHT_PATH_OPEN|exports.WASI_RIGHT_FD_READDIR|exports.WASI_RIGHT_PATH_READLINK|exports.WASI_RIGHT_PATH_RENAME_SOURCE|exports.WASI_RIGHT_PATH_RENAME_TARGET|exports.WASI_RIGHT_PATH_FILESTAT_GET|exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE|exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES|exports.WASI_RIGHT_PATH_SYMLINK|exports.WASI_RIGHT_PATH_UNLINK_FILE|exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_DIRECTORY_INHERITING=exports.RIGHTS_DIRECTORY_BASE|exports.RIGHTS_REGULAR_FILE_BASE,exports.RIGHTS_SOCKET_BASE=exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_POLL_FD_READWRITE|exports.WASI_RIGHT_SOCK_SHUTDOWN,exports.RIGHTS_SOCKET_INHERITING=exports.RIGHTS_ALL,exports.RIGHTS_TTY_BASE=exports.WASI_RIGHT_FD_READ|exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS|exports.WASI_RIGHT_FD_WRITE|exports.WASI_RIGHT_FD_FILESTAT_GET|exports.WASI_RIGHT_POLL_FD_READWRITE,exports.RIGHTS_TTY_INHERITING=BigInt(0),exports.WASI_CLOCK_REALTIME=0,exports.WASI_CLOCK_MONOTONIC=1,exports.WASI_CLOCK_PROCESS_CPUTIME_ID=2,exports.WASI_CLOCK_THREAD_CPUTIME_ID=3,exports.WASI_EVENTTYPE_CLOCK=0,exports.WASI_EVENTTYPE_FD_READ=1,exports.WASI_EVENTTYPE_FD_WRITE=2,exports.WASI_FILESTAT_SET_ATIM=1<<0,exports.WASI_FILESTAT_SET_ATIM_NOW=1<<1,exports.WASI_FILESTAT_SET_MTIM=1<<2,exports.WASI_FILESTAT_SET_MTIM_NOW=1<<3,exports.WASI_O_CREAT=1<<0,exports.WASI_O_DIRECTORY=1<<1,exports.WASI_O_EXCL=1<<2,exports.WASI_O_TRUNC=1<<3,exports.WASI_PREOPENTYPE_DIR=0,exports.WASI_DIRCOOKIE_START=0,exports.WASI_STDIN_FILENO=0,exports.WASI_STDOUT_FILENO=1,exports.WASI_STDERR_FILENO=2,exports.WASI_WHENCE_SET=0,exports.WASI_WHENCE_CUR=1,exports.WASI_WHENCE_END=2,exports.ERROR_MAP={E2BIG:exports.WASI_E2BIG,EACCES:exports.WASI_EACCES,EADDRINUSE:exports.WASI_EADDRINUSE,EADDRNOTAVAIL:exports.WASI_EADDRNOTAVAIL,EAFNOSUPPORT:exports.WASI_EAFNOSUPPORT,EALREADY:exports.WASI_EALREADY,EAGAIN:exports.WASI_EAGAIN,EBADF:exports.WASI_EBADF,EBADMSG:exports.WASI_EBADMSG,EBUSY:exports.WASI_EBUSY,ECANCELED:exports.WASI_ECANCELED,ECHILD:exports.WASI_ECHILD,ECONNABORTED:exports.WASI_ECONNABORTED,ECONNREFUSED:exports.WASI_ECONNREFUSED,ECONNRESET:exports.WASI_ECONNRESET,EDEADLOCK:exports.WASI_EDEADLK,EDESTADDRREQ:exports.WASI_EDESTADDRREQ,EDOM:exports.WASI_EDOM,EDQUOT:exports.WASI_EDQUOT,EEXIST:exports.WASI_EEXIST,EFAULT:exports.WASI_EFAULT,EFBIG:exports.WASI_EFBIG,EHOSTDOWN:exports.WASI_EHOSTUNREACH,EHOSTUNREACH:exports.WASI_EHOSTUNREACH,EIDRM:exports.WASI_EIDRM,EILSEQ:exports.WASI_EILSEQ,EINPROGRESS:exports.WASI_EINPROGRESS,EINTR:exports.WASI_EINTR,EINVAL:exports.WASI_EINVAL,EIO:exports.WASI_EIO,EISCONN:exports.WASI_EISCONN,EISDIR:exports.WASI_EISDIR,ELOOP:exports.WASI_ELOOP,EMFILE:exports.WASI_EMFILE,EMLINK:exports.WASI_EMLINK,EMSGSIZE:exports.WASI_EMSGSIZE,EMULTIHOP:exports.WASI_EMULTIHOP,ENAMETOOLONG:exports.WASI_ENAMETOOLONG,ENETDOWN:exports.WASI_ENETDOWN,ENETRESET:exports.WASI_ENETRESET,ENETUNREACH:exports.WASI_ENETUNREACH,ENFILE:exports.WASI_ENFILE,ENOBUFS:exports.WASI_ENOBUFS,ENODEV:exports.WASI_ENODEV,ENOENT:exports.WASI_ENOENT,ENOEXEC:exports.WASI_ENOEXEC,ENOLCK:exports.WASI_ENOLCK,ENOLINK:exports.WASI_ENOLINK,ENOMEM:exports.WASI_ENOMEM,ENOMSG:exports.WASI_ENOMSG,ENOPROTOOPT:exports.WASI_ENOPROTOOPT,ENOSPC:exports.WASI_ENOSPC,ENOSYS:exports.WASI_ENOSYS,ENOTCONN:exports.WASI_ENOTCONN,ENOTDIR:exports.WASI_ENOTDIR,ENOTEMPTY:exports.WASI_ENOTEMPTY,ENOTRECOVERABLE:exports.WASI_ENOTRECOVERABLE,ENOTSOCK:exports.WASI_ENOTSOCK,ENOTTY:exports.WASI_ENOTTY,ENXIO:exports.WASI_ENXIO,EOVERFLOW:exports.WASI_EOVERFLOW,EOWNERDEAD:exports.WASI_EOWNERDEAD,EPERM:exports.WASI_EPERM,EPIPE:exports.WASI_EPIPE,EPROTO:exports.WASI_EPROTO,EPROTONOSUPPORT:exports.WASI_EPROTONOSUPPORT,EPROTOTYPE:exports.WASI_EPROTOTYPE,ERANGE:exports.WASI_ERANGE,EROFS:exports.WASI_EROFS,ESPIPE:exports.WASI_ESPIPE,ESRCH:exports.WASI_ESRCH,ESTALE:exports.WASI_ESTALE,ETIMEDOUT:exports.WASI_ETIMEDOUT,ETXTBSY:exports.WASI_ETXTBSY,EXDEV:exports.WASI_EXDEV},exports.SIGNAL_MAP={[exports.WASI_SIGHUP]:\"SIGHUP\",[exports.WASI_SIGINT]:\"SIGINT\",[exports.WASI_SIGQUIT]:\"SIGQUIT\",[exports.WASI_SIGILL]:\"SIGILL\",[exports.WASI_SIGTRAP]:\"SIGTRAP\",[exports.WASI_SIGABRT]:\"SIGABRT\",[exports.WASI_SIGBUS]:\"SIGBUS\",[exports.WASI_SIGFPE]:\"SIGFPE\",[exports.WASI_SIGKILL]:\"SIGKILL\",[exports.WASI_SIGUSR1]:\"SIGUSR1\",[exports.WASI_SIGSEGV]:\"SIGSEGV\",[exports.WASI_SIGUSR2]:\"SIGUSR2\",[exports.WASI_SIGPIPE]:\"SIGPIPE\",[exports.WASI_SIGALRM]:\"SIGALRM\",[exports.WASI_SIGTERM]:\"SIGTERM\",[exports.WASI_SIGCHLD]:\"SIGCHLD\",[exports.WASI_SIGCONT]:\"SIGCONT\",[exports.WASI_SIGSTOP]:\"SIGSTOP\",[exports.WASI_SIGTSTP]:\"SIGTSTP\",[exports.WASI_SIGTTIN]:\"SIGTTIN\",[exports.WASI_SIGTTOU]:\"SIGTTOU\",[exports.WASI_SIGURG]:\"SIGURG\",[exports.WASI_SIGXCPU]:\"SIGXCPU\",[exports.WASI_SIGXFSZ]:\"SIGXFSZ\",[exports.WASI_SIGVTALRM]:\"SIGVTALRM\"}}}),require_wasi=__commonJS({\"node_modules/wasi-js/dist/wasi.js\"(exports){var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule\?mod:{default:mod}};let fs;Object.defineProperty(exports,\"__esModule\",{value:!0}),exports.SOCKET_DEFAULT_RIGHTS=void 0;var log=()=>{},logOpen=()=>{},SC_OPEN_MAX=32768,types_1=require_types(),constants_1=require_constants(),STDIN_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_SYNC|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE,STDOUT_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_SYNC|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE,STDERR_DEFAULT_RIGHTS=STDOUT_DEFAULT_RIGHTS;exports.SOCKET_DEFAULT_RIGHTS=constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_ADVISE|constants_1.WASI_RIGHT_FD_FILESTAT_GET|constants_1.WASI_RIGHT_POLL_FD_READWRITE|constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS;var msToNs=(ms)=>{const msInt=Math.trunc(ms),decimal=BigInt(Math.round((ms-msInt)*1e6));return BigInt(msInt)*BigInt(1e6)+decimal},nsToMs=(ns)=>{if(typeof ns===\"number\")ns=Math.trunc(ns);const nsInt=BigInt(ns);return Number(nsInt/BigInt(1e6))},wrap=(f)=>(...args)=>{try{return f(...args)}catch(err){let e=err;while(e.prev!=null)e=e.prev;if(e\?.code&&typeof e\?.code===\"string\")return constants_1.ERROR_MAP[e.code]||constants_1.WASI_EINVAL;if(e instanceof types_1.WASIError)return e.errno;throw e}},stat=(wasi,fd)=>{const entry=wasi.FD_MAP.get(fd);if(!entry)throw new types_1.WASIError(constants_1.WASI_EBADF);if(entry.filetype===void 0){const stats=wasi.fstatSync(entry.real),{filetype,rightsBase,rightsInheriting}=translateFileAttributes(wasi,fd,stats);if(entry.filetype=filetype,!entry.rights)entry.rights={base:rightsBase,inheriting:rightsInheriting}}return entry},translateFileAttributes=(wasi,fd,stats)=>{switch(!0){case stats.isBlockDevice():return{filetype:constants_1.WASI_FILETYPE_BLOCK_DEVICE,rightsBase:constants_1.RIGHTS_BLOCK_DEVICE_BASE,rightsInheriting:constants_1.RIGHTS_BLOCK_DEVICE_INHERITING};case stats.isCharacterDevice():{const filetype=constants_1.WASI_FILETYPE_CHARACTER_DEVICE;if(fd!==void 0&&wasi.bindings.isTTY(fd))return{filetype,rightsBase:constants_1.RIGHTS_TTY_BASE,rightsInheriting:constants_1.RIGHTS_TTY_INHERITING};return{filetype,rightsBase:constants_1.RIGHTS_CHARACTER_DEVICE_BASE,rightsInheriting:constants_1.RIGHTS_CHARACTER_DEVICE_INHERITING}}case stats.isDirectory():return{filetype:constants_1.WASI_FILETYPE_DIRECTORY,rightsBase:constants_1.RIGHTS_DIRECTORY_BASE,rightsInheriting:constants_1.RIGHTS_DIRECTORY_INHERITING};case stats.isFIFO():return{filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rightsBase:constants_1.RIGHTS_SOCKET_BASE,rightsInheriting:constants_1.RIGHTS_SOCKET_INHERITING};case stats.isFile():return{filetype:constants_1.WASI_FILETYPE_REGULAR_FILE,rightsBase:constants_1.RIGHTS_REGULAR_FILE_BASE,rightsInheriting:constants_1.RIGHTS_REGULAR_FILE_INHERITING};case stats.isSocket():return{filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rightsBase:constants_1.RIGHTS_SOCKET_BASE,rightsInheriting:constants_1.RIGHTS_SOCKET_INHERITING};case stats.isSymbolicLink():return{filetype:constants_1.WASI_FILETYPE_SYMBOLIC_LINK,rightsBase:BigInt(0),rightsInheriting:BigInt(0)};default:return{filetype:constants_1.WASI_FILETYPE_UNKNOWN,rightsBase:BigInt(0),rightsInheriting:BigInt(0)}}},warnedAboutSleep=!1,defaultConfig;function getDefaults(){if(defaultConfig)return defaultConfig;const defaultBindings={hrtime:()=>process.hrtime.bigint(),exit:(code)=>{process.exit(code)},kill:(signal)=>{process.kill(process.pid,signal)},randomFillSync:(array)=>crypto.getRandomValues(array),isTTY:(fd)=>@requireNativeModule(\"node:tty\").isatty(fd),fs:Bun.fs(),path:@getInternalField(@internalModuleRegistry,25)||@createInternalModuleById(25)};return defaultConfig={args:[],env:{},preopens:{},bindings:defaultBindings,sleep:(ms)=>{Bun.sleepSync(ms)}}}var WASI=class WASI2{constructor(wasiConfig={}){const defaultConfig2=getDefaults();this.lastStdin=0,this.sleep=wasiConfig.sleep||defaultConfig2.sleep,this.getStdin=wasiConfig.getStdin,this.sendStdout=wasiConfig.sendStdout,this.sendStderr=wasiConfig.sendStderr;let preopens=wasiConfig.preopens\?\?defaultConfig2.preopens;this.env=wasiConfig.env\?\?defaultConfig2.env;const args=wasiConfig.args\?\?defaultConfig2.args;this.memory=void 0,this.view=void 0,this.bindings=wasiConfig.bindings||defaultConfig2.bindings;const bindings2=this.bindings;fs=bindings2.fs,this.FD_MAP=new Map([[constants_1.WASI_STDIN_FILENO,{real:0,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDIN_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stdin\"}],[constants_1.WASI_STDOUT_FILENO,{real:1,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDOUT_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stdout\"}],[constants_1.WASI_STDERR_FILENO,{real:2,filetype:constants_1.WASI_FILETYPE_CHARACTER_DEVICE,rights:{base:STDERR_DEFAULT_RIGHTS,inheriting:BigInt(0)},path:\"/dev/stderr\"}]]);const path=bindings2.path;for(let[k,v]of Object.entries(preopens)){const real=fs.openSync(v,nodeFsConstants.O_RDONLY),newfd=this.getUnusedFileDescriptor();this.FD_MAP.set(newfd,{real,filetype:constants_1.WASI_FILETYPE_DIRECTORY,rights:{base:constants_1.RIGHTS_DIRECTORY_BASE,inheriting:constants_1.RIGHTS_DIRECTORY_INHERITING},fakePath:k,path:v})}const getiovs=(iovs,iovsLen)=>{this.refreshMemory();const{view,memory}=this,{buffer}=memory,{byteLength}=buffer;if(iovsLen===1){const ptr=iovs,buf=view.getUint32(ptr,!0);let bufLen=view.getUint32(ptr+4,!0);if(bufLen>byteLength-buf)console.log({buf,bufLen,total_memory:byteLength}),log(\"getiovs: warning -- truncating buffer to fit in memory\"),bufLen=Math.min(bufLen,Math.max(0,byteLength-buf));try{return[new Uint8Array(buffer,buf,bufLen)]}catch(err){throw console.warn(\"WASI.getiovs -- invalid buffer\",err),new types_1.WASIError(constants_1.WASI_EINVAL)}}const buffers=[];buffers.length=iovsLen;for(let i=0,ptr=iovs;ibyteLength-buf)console.log({buf,bufLen,total_memory:byteLength}),log(\"getiovs: warning -- truncating buffer to fit in memory\"),bufLen=Math.min(bufLen,Math.max(0,byteLength-buf));try{buffers[i]=new Uint8Array(buffer,buf,bufLen)}catch(err){throw console.warn(\"WASI.getiovs -- invalid buffer\",err),new types_1.WASIError(constants_1.WASI_EINVAL)}}return buffers},CHECK_FD=(fd,rights)=>{const stats=stat(this,fd);if(rights!==BigInt(0)&&(stats.rights.base&rights)===BigInt(0))throw new types_1.WASIError(constants_1.WASI_EPERM);return stats},CPUTIME_START=Bun.nanoseconds(),timeOrigin=Math.trunc(performance.timeOrigin*1e6),now=(clockId)=>{switch(clockId){case constants_1.WASI_CLOCK_MONOTONIC:return Bun.nanoseconds();case constants_1.WASI_CLOCK_REALTIME:return Bun.nanoseconds()+timeOrigin;case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID:case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID:return Bun.nanoseconds()-CPUTIME_START;default:return null}};if(this.wasiImport={args_get:(argv,argvBuf)=>{this.refreshMemory();let coffset=argv,offset=argvBuf;return args.forEach((a)=>{this.view.setUint32(coffset,offset,!0),coffset+=4,offset+=Buffer.from(this.memory.buffer).write(`${a}\\0`,offset)}),constants_1.WASI_ESUCCESS},args_sizes_get:(argc,argvBufSize)=>{this.refreshMemory(),this.view.setUint32(argc,args.length,!0);const size=args.reduce((acc,a)=>acc+Buffer.byteLength(a)+1,0);return this.view.setUint32(argvBufSize,size,!0),constants_1.WASI_ESUCCESS},environ_get:(environ,environBuf)=>{this.refreshMemory();let coffset=environ,offset=environBuf;return Object.entries(this.env).forEach(([key,value])=>{this.view.setUint32(coffset,offset,!0),coffset+=4,offset+=Buffer.from(this.memory.buffer).write(`${key}=${value}\\0`,offset)}),constants_1.WASI_ESUCCESS},environ_sizes_get:(environCount,environBufSize)=>{this.refreshMemory();const envProcessed=Object.entries(this.env).map(([key,value])=>`${key}=${value}\\0`),size=envProcessed.reduce((acc,e)=>acc+Buffer.byteLength(e),0);return this.view.setUint32(environCount,envProcessed.length,!0),this.view.setUint32(environBufSize,size,!0),constants_1.WASI_ESUCCESS},clock_res_get:(clockId,resolution)=>{let res;switch(clockId){case constants_1.WASI_CLOCK_MONOTONIC:case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID:case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID:{res=BigInt(1);break}case constants_1.WASI_CLOCK_REALTIME:{res=BigInt(1000);break}}if(!res)throw Error(\"invalid clockId\");return this.view.setBigUint64(resolution,res),constants_1.WASI_ESUCCESS},clock_time_get:(clockId,_precision,time)=>{this.refreshMemory();const n=now(clockId);if(n===null)return constants_1.WASI_EINVAL;return this.view.setBigUint64(time,BigInt(n),!0),constants_1.WASI_ESUCCESS},fd_advise:wrap((fd,_offset,_len,_advice)=>{return CHECK_FD(fd,constants_1.WASI_RIGHT_FD_ADVISE),constants_1.WASI_ENOSYS}),fd_allocate:wrap((fd,_offset,_len)=>{return CHECK_FD(fd,constants_1.WASI_RIGHT_FD_ALLOCATE),constants_1.WASI_ENOSYS}),fd_close:wrap((fd)=>{const stats=CHECK_FD(fd,BigInt(0));return fs.closeSync(stats.real),this.FD_MAP.delete(fd),constants_1.WASI_ESUCCESS}),fd_datasync:wrap((fd)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_DATASYNC);return fs.fdatasyncSync(stats.real),constants_1.WASI_ESUCCESS}),fd_fdstat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,BigInt(0));if(this.refreshMemory(),stats.filetype==null)throw Error(\"stats.filetype must be set\");return this.view.setUint8(bufPtr,stats.filetype),this.view.setUint16(bufPtr+2,0,!0),this.view.setUint16(bufPtr+4,0,!0),this.view.setBigUint64(bufPtr+8,BigInt(stats.rights.base),!0),this.view.setBigUint64(bufPtr+8+8,BigInt(stats.rights.inheriting),!0),constants_1.WASI_ESUCCESS}),fd_fdstat_set_flags:wrap((fd,flags)=>{if(CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS),this.wasiImport.sock_fcntlSetFlags(fd,flags)==0)return constants_1.WASI_ESUCCESS;return constants_1.WASI_ENOSYS}),fd_fdstat_set_rights:wrap((fd,fsRightsBase,fsRightsInheriting)=>{const stats=CHECK_FD(fd,BigInt(0));if((stats.rights.base|fsRightsBase)>stats.rights.base)return constants_1.WASI_EPERM;if((stats.rights.inheriting|fsRightsInheriting)>stats.rights.inheriting)return constants_1.WASI_EPERM;return stats.rights.base=fsRightsBase,stats.rights.inheriting=fsRightsInheriting,constants_1.WASI_ESUCCESS}),fd_filestat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_GET),rstats=this.fstatSync(stats.real);if(this.refreshMemory(),this.view.setBigUint64(bufPtr,BigInt(rstats.dev),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,stats.filetype==null)throw Error(\"stats.filetype must be set\");return this.view.setUint8(bufPtr,stats.filetype),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.nlink),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.size),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.atimeMs),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.mtimeMs),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,msToNs(rstats.ctimeMs),!0),constants_1.WASI_ESUCCESS}),fd_filestat_set_size:wrap((fd,stSize)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE);return fs.ftruncateSync(stats.real,Number(stSize)),constants_1.WASI_ESUCCESS}),fd_filestat_set_times:wrap((fd,stAtim,stMtim,fstflags)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_FILESTAT_SET_TIMES),rstats=this.fstatSync(stats.real);let{atime:atim,mtime:mtim}=rstats;const n=nsToMs(now(constants_1.WASI_CLOCK_REALTIME)),atimflags=constants_1.WASI_FILESTAT_SET_ATIM|constants_1.WASI_FILESTAT_SET_ATIM_NOW;if((fstflags&atimflags)===atimflags)return constants_1.WASI_EINVAL;const mtimflags=constants_1.WASI_FILESTAT_SET_MTIM|constants_1.WASI_FILESTAT_SET_MTIM_NOW;if((fstflags&mtimflags)===mtimflags)return constants_1.WASI_EINVAL;if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM)===constants_1.WASI_FILESTAT_SET_ATIM)atim=nsToMs(stAtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM_NOW)===constants_1.WASI_FILESTAT_SET_ATIM_NOW)atim=n;if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM)===constants_1.WASI_FILESTAT_SET_MTIM)mtim=nsToMs(stMtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM_NOW)===constants_1.WASI_FILESTAT_SET_MTIM_NOW)mtim=n;return fs.futimesSync(stats.real,new Date(atim),new Date(mtim)),constants_1.WASI_ESUCCESS}),fd_prestat_get:wrap((fd,bufPtr)=>{const stats=CHECK_FD(fd,BigInt(0));return this.refreshMemory(),this.view.setUint8(bufPtr,constants_1.WASI_PREOPENTYPE_DIR),this.view.setUint32(bufPtr+4,Buffer.byteLength(stats.fakePath\?\?stats.path\?\?\"\"),!0),constants_1.WASI_ESUCCESS}),fd_prestat_dir_name:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,BigInt(0));return this.refreshMemory(),Buffer.from(this.memory.buffer).write(stats.fakePath\?\?stats.path\?\?\"\",pathPtr,pathLen,\"utf8\"),constants_1.WASI_ESUCCESS}),fd_pwrite:wrap((fd,iovs,iovsLen,offset,nwritten)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_SEEK);let written=0;return getiovs(iovs,iovsLen).forEach((iov)=>{let w=0;while(w{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_WRITE),IS_STDOUT=fd==constants_1.WASI_STDOUT_FILENO,IS_STDERR=fd==constants_1.WASI_STDERR_FILENO;let written=0;return getiovs(iovs,iovsLen).forEach((iov)=>{if(iov.byteLength==0)return;if(IS_STDOUT&&this.sendStdout!=null)this.sendStdout(iov),written+=iov.byteLength;else if(IS_STDERR&&this.sendStderr!=null)this.sendStderr(iov),written+=iov.byteLength;else{let w=0;while(w{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_SEEK);let read=0;outer:for(let iov of getiovs(iovs,iovsLen)){let r=0;while(r{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READ),IS_STDIN=fd==constants_1.WASI_STDIN_FILENO;let read=0;outer:for(let iov of getiovs(iovs,iovsLen)){let r=0;while(r0)this.lastStdin=(new Date()).valueOf()}}else{if(this.sleep==null&&!warnedAboutSleep)warnedAboutSleep=!0,console.log(\"(cpu waiting for stdin: please define a way to sleep!) \");try{rr=fs.readSync(stats.real,iov,r,length,position)}catch(_err){}if(rr==0)this.shortPause();else this.lastStdin=(new Date()).valueOf()}else rr=fs.readSync(stats.real,iov,r,length,position);if(stats.filetype==constants_1.WASI_FILETYPE_REGULAR_FILE)stats.offset=(stats.offset\?stats.offset:BigInt(0))+BigInt(rr);if(r+=rr,read+=rr,rr===0||rr{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_READDIR);this.refreshMemory();const entries=fs.readdirSync(stats.path,{withFileTypes:!0}),startPtr=bufPtr;for(let i=Number(cookie);ibufLen)break;if(this.view.setBigUint64(bufPtr,BigInt(i+1),!0),bufPtr+=8,bufPtr-startPtr>bufLen)break;const rstats=fs.lstatSync(path.resolve(stats.path,entry.name));if(this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,bufPtr-startPtr>bufLen)break;if(this.view.setUint32(bufPtr,nameLength,!0),bufPtr+=4,bufPtr-startPtr>bufLen)break;let filetype;switch(!0){case rstats.isBlockDevice():filetype=constants_1.WASI_FILETYPE_BLOCK_DEVICE;break;case rstats.isCharacterDevice():filetype=constants_1.WASI_FILETYPE_CHARACTER_DEVICE;break;case rstats.isDirectory():filetype=constants_1.WASI_FILETYPE_DIRECTORY;break;case rstats.isFIFO():filetype=constants_1.WASI_FILETYPE_SOCKET_STREAM;break;case rstats.isFile():filetype=constants_1.WASI_FILETYPE_REGULAR_FILE;break;case rstats.isSocket():filetype=constants_1.WASI_FILETYPE_SOCKET_STREAM;break;case rstats.isSymbolicLink():filetype=constants_1.WASI_FILETYPE_SYMBOLIC_LINK;break;default:filetype=constants_1.WASI_FILETYPE_UNKNOWN;break}if(this.view.setUint8(bufPtr,filetype),bufPtr+=1,bufPtr+=3,bufPtr+nameLength>=startPtr+bufLen)break;Buffer.from(this.memory.buffer).write(entry.name,bufPtr),bufPtr+=nameLength}const bufused=bufPtr-startPtr;return this.view.setUint32(bufusedPtr,Math.min(bufused,bufLen),!0),constants_1.WASI_ESUCCESS}),fd_renumber:wrap((from,to)=>{return CHECK_FD(from,BigInt(0)),CHECK_FD(to,BigInt(0)),fs.closeSync(this.FD_MAP.get(from).real),this.FD_MAP.set(from,this.FD_MAP.get(to)),this.FD_MAP.delete(to),constants_1.WASI_ESUCCESS}),fd_seek:wrap((fd,offset,whence,newOffsetPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_SEEK);switch(this.refreshMemory(),whence){case constants_1.WASI_WHENCE_CUR:stats.offset=(stats.offset\?stats.offset:BigInt(0))+BigInt(offset);break;case constants_1.WASI_WHENCE_END:const{size}=this.fstatSync(stats.real);stats.offset=BigInt(size)+BigInt(offset);break;case constants_1.WASI_WHENCE_SET:stats.offset=BigInt(offset);break}if(stats.offset==null)throw Error(\"stats.offset must be defined\");return this.view.setBigUint64(newOffsetPtr,stats.offset,!0),constants_1.WASI_ESUCCESS}),fd_tell:wrap((fd,offsetPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_TELL);if(this.refreshMemory(),!stats.offset)stats.offset=BigInt(0);return this.view.setBigUint64(offsetPtr,stats.offset,!0),constants_1.WASI_ESUCCESS}),fd_sync:wrap((fd)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_FD_SYNC);return fs.fsyncSync(stats.real),constants_1.WASI_ESUCCESS}),path_create_directory:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_CREATE_DIRECTORY);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.mkdirSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),path_filestat_get:wrap((fd,flags,pathPtr,pathLen,bufPtr)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_FILESTAT_GET);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();let rstats;if(flags)rstats=fs.statSync(path.resolve(stats.path,p));else rstats=fs.lstatSync(path.resolve(stats.path,p));return this.view.setBigUint64(bufPtr,BigInt(rstats.dev),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ino),!0),bufPtr+=8,this.view.setUint8(bufPtr,translateFileAttributes(this,void 0,rstats).filetype),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.nlink),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.size),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.atime.getTime()*1e6),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.mtime.getTime()*1e6),!0),bufPtr+=8,this.view.setBigUint64(bufPtr,BigInt(rstats.ctime.getTime()*1e6),!0),constants_1.WASI_ESUCCESS}),path_filestat_set_times:wrap((fd,_dirflags,pathPtr,pathLen,stAtim,stMtim,fstflags)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_FILESTAT_SET_TIMES);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const rstats=this.fstatSync(stats.real);let{atime:atim,mtime:mtim}=rstats;const n=nsToMs(now(constants_1.WASI_CLOCK_REALTIME)),atimflags=constants_1.WASI_FILESTAT_SET_ATIM|constants_1.WASI_FILESTAT_SET_ATIM_NOW;if((fstflags&atimflags)===atimflags)return constants_1.WASI_EINVAL;const mtimflags=constants_1.WASI_FILESTAT_SET_MTIM|constants_1.WASI_FILESTAT_SET_MTIM_NOW;if((fstflags&mtimflags)===mtimflags)return constants_1.WASI_EINVAL;if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM)===constants_1.WASI_FILESTAT_SET_ATIM)atim=nsToMs(stAtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_ATIM_NOW)===constants_1.WASI_FILESTAT_SET_ATIM_NOW)atim=n;if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM)===constants_1.WASI_FILESTAT_SET_MTIM)mtim=nsToMs(stMtim);else if((fstflags&constants_1.WASI_FILESTAT_SET_MTIM_NOW)===constants_1.WASI_FILESTAT_SET_MTIM_NOW)mtim=n;const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.utimesSync(path.resolve(stats.path,p),new Date(atim),new Date(mtim)),constants_1.WASI_ESUCCESS}),path_link:wrap((oldFd,_oldFlags,oldPath,oldPathLen,newFd,newPath,newPathLen)=>{const ostats=CHECK_FD(oldFd,constants_1.WASI_RIGHT_PATH_LINK_SOURCE),nstats=CHECK_FD(newFd,constants_1.WASI_RIGHT_PATH_LINK_TARGET);if(!ostats.path||!nstats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.linkSync(path.resolve(ostats.path,op),path.resolve(nstats.path,np)),constants_1.WASI_ESUCCESS}),path_open:wrap((dirfd,_dirflags,pathPtr,pathLen,oflags,fsRightsBase,fsRightsInheriting,fsFlags,fdPtr)=>{try{const stats=CHECK_FD(dirfd,constants_1.WASI_RIGHT_PATH_OPEN);fsRightsBase=BigInt(fsRightsBase),fsRightsInheriting=BigInt(fsRightsInheriting);const read=(fsRightsBase&(constants_1.WASI_RIGHT_FD_READ|constants_1.WASI_RIGHT_FD_READDIR))!==BigInt(0),write=(fsRightsBase&(constants_1.WASI_RIGHT_FD_DATASYNC|constants_1.WASI_RIGHT_FD_WRITE|constants_1.WASI_RIGHT_FD_ALLOCATE|constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE))!==BigInt(0);let noflags;if(write&&read)noflags=nodeFsConstants.O_RDWR;else if(read)noflags=nodeFsConstants.O_RDONLY;else if(write)noflags=nodeFsConstants.O_WRONLY;let neededBase=fsRightsBase|constants_1.WASI_RIGHT_PATH_OPEN,neededInheriting=fsRightsBase|fsRightsInheriting;if((oflags&constants_1.WASI_O_CREAT)!==0)noflags|=nodeFsConstants.O_CREAT,neededBase|=constants_1.WASI_RIGHT_PATH_CREATE_FILE;if((oflags&constants_1.WASI_O_DIRECTORY)!==0)noflags|=nodeFsConstants.O_DIRECTORY;if((oflags&constants_1.WASI_O_EXCL)!==0)noflags|=nodeFsConstants.O_EXCL;if((oflags&constants_1.WASI_O_TRUNC)!==0)noflags|=nodeFsConstants.O_TRUNC,neededBase|=constants_1.WASI_RIGHT_PATH_FILESTAT_SET_SIZE;if((fsFlags&constants_1.WASI_FDFLAG_APPEND)!==0)noflags|=nodeFsConstants.O_APPEND;if((fsFlags&constants_1.WASI_FDFLAG_DSYNC)!==0){if(nodeFsConstants.O_DSYNC)noflags|=nodeFsConstants.O_DSYNC;else noflags|=nodeFsConstants.O_SYNC;neededInheriting|=constants_1.WASI_RIGHT_FD_DATASYNC}if((fsFlags&constants_1.WASI_FDFLAG_NONBLOCK)!==0)noflags|=nodeFsConstants.O_NONBLOCK;if((fsFlags&constants_1.WASI_FDFLAG_RSYNC)!==0){if(nodeFsConstants.O_RSYNC)noflags|=nodeFsConstants.O_RSYNC;else noflags|=nodeFsConstants.O_SYNC;neededInheriting|=constants_1.WASI_RIGHT_FD_SYNC}if((fsFlags&constants_1.WASI_FDFLAG_SYNC)!==0)noflags|=nodeFsConstants.O_SYNC,neededInheriting|=constants_1.WASI_RIGHT_FD_SYNC;if(write&&(noflags&(nodeFsConstants.O_APPEND|nodeFsConstants.O_TRUNC))===0)neededInheriting|=constants_1.WASI_RIGHT_FD_SEEK;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();if(p==\"dev/tty\")return this.view.setUint32(fdPtr,constants_1.WASI_STDIN_FILENO,!0),constants_1.WASI_ESUCCESS;if(logOpen(\"path_open\",p),p.startsWith(\"proc/\"))throw new types_1.WASIError(constants_1.WASI_EBADF);const fullUnresolved=path.resolve(p);let full;try{full=fs.realpathSync(fullUnresolved)}catch(e){if(e\?.code===\"ENOENT\")full=fullUnresolved;else throw e}let isDirectory;if(write)try{isDirectory=fs.statSync(full).isDirectory()}catch(_err){}let realfd;if(!write&&isDirectory)realfd=fs.openSync(full,nodeFsConstants.O_RDONLY);else realfd=fs.openSync(full,noflags);const newfd=this.getUnusedFileDescriptor();this.FD_MAP.set(newfd,{real:realfd,filetype:void 0,rights:{base:neededBase,inheriting:neededInheriting},path:full}),stat(this,newfd),this.view.setUint32(fdPtr,newfd,!0)}catch(e){console.error(e)}return constants_1.WASI_ESUCCESS}),path_readlink:wrap((fd,pathPtr,pathLen,buf,bufLen,bufused)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_READLINK);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString(),full=path.resolve(stats.path,p),r=fs.readlinkSync(full),used=Buffer.from(this.memory.buffer).write(r,buf,bufLen);return this.view.setUint32(bufused,used,!0),constants_1.WASI_ESUCCESS}),path_remove_directory:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_REMOVE_DIRECTORY);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.rmdirSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),path_rename:wrap((oldFd,oldPath,oldPathLen,newFd,newPath,newPathLen)=>{const ostats=CHECK_FD(oldFd,constants_1.WASI_RIGHT_PATH_RENAME_SOURCE),nstats=CHECK_FD(newFd,constants_1.WASI_RIGHT_PATH_RENAME_TARGET);if(!ostats.path||!nstats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.renameSync(path.resolve(ostats.path,op),path.resolve(nstats.path,np)),constants_1.WASI_ESUCCESS}),path_symlink:wrap((oldPath,oldPathLen,fd,newPath,newPathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_SYMLINK);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const op=Buffer.from(this.memory.buffer,oldPath,oldPathLen).toString(),np=Buffer.from(this.memory.buffer,newPath,newPathLen).toString();return fs.symlinkSync(op,path.resolve(stats.path,np)),constants_1.WASI_ESUCCESS}),path_unlink_file:wrap((fd,pathPtr,pathLen)=>{const stats=CHECK_FD(fd,constants_1.WASI_RIGHT_PATH_UNLINK_FILE);if(!stats.path)return constants_1.WASI_EINVAL;this.refreshMemory();const p=Buffer.from(this.memory.buffer,pathPtr,pathLen).toString();return fs.unlinkSync(path.resolve(stats.path,p)),constants_1.WASI_ESUCCESS}),poll_oneoff:(sin,sout,nsubscriptions,neventsPtr)=>{let nevents=0,name=\"\",waitTimeNs=BigInt(0),fd=-1,fd_type=\"read\",fd_timeout_ms=0;const startNs=BigInt(bindings2.hrtime());this.refreshMemory();let last_sin=sin;for(let i=0;iwaitTimeNs)waitTimeNs=waitNs}this.view.setBigUint64(sout,userdata,!0),sout+=8,this.view.setUint16(sout,e,!0),sout+=2,this.view.setUint8(sout,constants_1.WASI_EVENTTYPE_CLOCK),sout+=1,sout+=5,nevents+=1;break}case constants_1.WASI_EVENTTYPE_FD_READ:case constants_1.WASI_EVENTTYPE_FD_WRITE:{if(fd=this.view.getUint32(sin,!0),fd_type=type==constants_1.WASI_EVENTTYPE_FD_READ\?\"read\":\"write\",sin+=4,log(name,\"fd =\",fd),sin+=28,this.view.setBigUint64(sout,userdata,!0),sout+=8,this.view.setUint16(sout,constants_1.WASI_ENOSYS,!0),sout+=2,this.view.setUint8(sout,type),sout+=1,sout+=5,nevents+=1,fd==constants_1.WASI_STDIN_FILENO&&constants_1.WASI_EVENTTYPE_FD_READ==type)this.shortPause();break}default:return constants_1.WASI_EINVAL}if(sin-last_sin!=48)console.warn(\"*** BUG in wasi-js in poll_oneoff \",{i,sin,last_sin,diff:sin-last_sin});last_sin=sin}if(this.view.setUint32(neventsPtr,nevents,!0),nevents==2&&fd>=0){const r=this.wasiImport.sock_pollSocket(fd,fd_type,fd_timeout_ms);if(r!=constants_1.WASI_ENOSYS)return r}if(waitTimeNs>0){if(waitTimeNs-=Bun.nanoseconds()-timeOrigin,waitTimeNs>=1e6){if(this.sleep==null&&!warnedAboutSleep)warnedAboutSleep=!0,console.log(\"(100% cpu burning waiting for stdin: please define a way to sleep!) \");if(this.sleep!=null){const ms=nsToMs(waitTimeNs);this.sleep(ms)}else{const end=BigInt(bindings2.hrtime())+waitTimeNs;while(BigInt(bindings2.hrtime()){return bindings2.exit(rval),constants_1.WASI_ESUCCESS},proc_raise:(sig)=>{if(!(sig in constants_1.SIGNAL_MAP))return constants_1.WASI_EINVAL;return bindings2.kill(constants_1.SIGNAL_MAP[sig]),constants_1.WASI_ESUCCESS},random_get:(bufPtr,bufLen)=>{return this.refreshMemory(),crypto.getRandomValues(this.memory.buffer,bufPtr,bufLen),bufLen},sched_yield(){return constants_1.WASI_ESUCCESS},sock_recv(){return constants_1.WASI_ENOSYS},sock_send(){return constants_1.WASI_ENOSYS},sock_shutdown(){return constants_1.WASI_ENOSYS},sock_fcntlSetFlags(_fd,_flags){return constants_1.WASI_ENOSYS},sock_pollSocket(_fd,_eventtype,_timeout_ms){return constants_1.WASI_ENOSYS}},log.enabled)Object.keys(this.wasiImport).forEach((key)=>{const prevImport=this.wasiImport[key];this.wasiImport[key]=function(...args2){log(key,args2);try{let result=prevImport(...args2);return log(\"result\",result),result}catch(e){throw log(\"error: \",e),e}}})}getState(){return{env:this.env,FD_MAP:this.FD_MAP,bindings}}setState(state){this.env=state.env,this.FD_MAP=state.FD_MAP,bindings=state.bindings}fstatSync(real_fd){if(real_fd<=2)try{return fs.fstatSync(real_fd)}catch(_){const now=new Date;return{dev:0,mode:8592,nlink:1,uid:0,gid:0,rdev:0,blksize:65536,ino:0,size:0,blocks:0,atimeMs:now.valueOf(),mtimeMs:now.valueOf(),ctimeMs:now.valueOf(),birthtimeMs:0,atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date(0)}}return fs.fstatSync(real_fd)}shortPause(){if(this.sleep==null)return;if((new Date()).valueOf()-this.lastStdin>2000)this.sleep(50)}getUnusedFileDescriptor(start=3){let fd=start;while(this.FD_MAP.has(fd))fd+=1;if(fd>SC_OPEN_MAX)throw Error(\"no available file descriptors\");return fd}refreshMemory(){if(!this.view||this.view.buffer.byteLength===0)this.view=new DataView(this.memory.buffer)}setMemory(memory){this.memory=memory}start(instance,memory){const exports2=instance.exports;if(exports2===null||typeof exports2!==\"object\")throw new Error(`instance.exports must be an Object. Received ${exports2}.`);if(memory==null){if(memory=exports2.memory,!(memory instanceof WebAssembly.Memory))throw new Error(`instance.exports.memory must be a WebAssembly.Memory. Recceived ${memory}.`)}if(this.setMemory(memory),exports2._start)exports2._start()}getImports(module2){let namespace=null;const imports=WebAssembly.Module.imports(module2);for(let imp of imports){if(imp.kind!==\"function\")continue;if(!imp.module.startsWith(\"wasi_\"))continue;namespace=imp.module;break}switch(namespace){case\"wasi_unstable\":return{wasi_unstable:this.wasiImport};case\"wasi_snapshot_preview1\":return{wasi_snapshot_preview1:this.wasiImport};default:throw new Error(\"No WASI namespace found. Only wasi_unstable and wasi_snapshot_preview1 are supported.\\n\\nList of imports:\\n\\n\"+imports.map(({name,kind,module})=>`${module}:${name} (${kind})`).join(\"\\n\")+\"\\n\")}}initWasiFdInfo(){if(this.env.WASI_FD_INFO!=null){const fdInfo=JSON.parse(this.env.WASI_FD_INFO);for(let wasi_fd in fdInfo){console.log(wasi_fd);const fd=parseInt(wasi_fd);if(this.FD_MAP.has(fd))continue;const real=fdInfo[wasi_fd];try{this.fstatSync(real)}catch(_err){console.log(\"discarding \",{wasi_fd,real});continue}const file={real,filetype:constants_1.WASI_FILETYPE_SOCKET_STREAM,rights:{base:STDIN_DEFAULT_RIGHTS,inheriting:BigInt(0)}};this.FD_MAP.set(fd,file)}console.log(\"after initWasiFdInfo: \",this.FD_MAP),console.log(\"fdInfo = \",fdInfo)}else console.log(\"no WASI_FD_INFO\")}};exports.default=WASI}});return{WASI:require_wasi().default}})\n"_s; +// + +// +static constexpr ASCIILiteral NodeWorkerThreadsCode = "(function (){\"use strict\";var $;const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),{throwNotImplemented}=@getInternalField(@internalModuleRegistry,2)||@createInternalModuleById(2),{MessageChannel,BroadcastChannel,Worker:WebWorker}=globalThis,SHARE_ENV=Symbol(\"nodejs.worker_threads.SHARE_ENV\"),isMainThread=Bun.isMainThread;let[_workerData,_threadId,_receiveMessageOnPort]=globalThis[globalThis.Symbol.for('Bun.lazy')](\"worker_threads\");const emittedWarnings=new Set;function emitWarning(type,message){if(emittedWarnings.has(type))return;emittedWarnings.add(type),console.warn(\"[bun] Warning:\",message)}function injectFakeEmitter(Class){function messageEventHandler(event){return event.data}function errorEventHandler(event){return event.error}const wrappedListener=Symbol(\"wrappedListener\");function wrapped(run,listener){const callback=function(event){return listener(run(event))};return listener[wrappedListener]=callback,callback}function functionForEventType(event,listener){switch(event){case\"error\":case\"messageerror\":return wrapped(errorEventHandler,listener);default:return wrapped(messageEventHandler,listener)}}Class.prototype.on=function(event,listener){return this.addEventListener(event,functionForEventType(event,listener)),this},Class.prototype.off=function(event,listener){if(listener)this.removeEventListener(event,listener[wrappedListener]||listener);else this.removeEventListener(event);return this},Class.prototype.once=function(event,listener){return this.addEventListener(event,functionForEventType(event,listener),{once:!0}),this};function EventClass(eventName){if(eventName===\"error\"||eventName===\"messageerror\")return ErrorEvent;return MessageEvent}Class.prototype.emit=function(event,...args){return this.dispatchEvent(new(EventClass(event))(event,...args)),this},Class.prototype.prependListener=Class.prototype.on,Class.prototype.prependOnceListener=Class.prototype.once}const _MessagePort=globalThis.MessagePort;injectFakeEmitter(_MessagePort);const MessagePort=_MessagePort;let resourceLimits={},workerData=_workerData,threadId=_threadId;function receiveMessageOnPort(port){let res=_receiveMessageOnPort(port);if(!res)return;return{message:res}}function fakeParentPort(){const fake=Object.create(MessagePort.prototype);return Object.defineProperty(fake,\"onmessage\",{get(){return self.onmessage},set(value){self.onmessage=value}}),Object.defineProperty(fake,\"onmessageerror\",{get(){return self.onmessageerror},set(value){}}),Object.defineProperty(fake,\"postMessage\",{value(...args){return self.postMessage(...args)}}),Object.defineProperty(fake,\"close\",{value(){return process.exit(0)}}),Object.defineProperty(fake,\"start\",{value(){}}),Object.defineProperty(fake,\"unref\",{value(){}}),Object.defineProperty(fake,\"ref\",{value(){}}),Object.defineProperty(fake,\"hasRef\",{value(){return!1}}),Object.defineProperty(fake,\"setEncoding\",{value(){}}),Object.defineProperty(fake,\"addEventListener\",{value:self.addEventListener.bind(self)}),Object.defineProperty(fake,\"removeEventListener\",{value:self.removeEventListener.bind(self)}),fake}let parentPort=isMainThread\?null:fakeParentPort();function getEnvironmentData(){return process.env}function setEnvironmentData(env){process.env=env}function markAsUntransferable(){throwNotImplemented(\"worker_threads.markAsUntransferable\")}function moveMessagePortToContext(){throwNotImplemented(\"worker_threads.moveMessagePortToContext\")}const unsupportedOptions=[\"eval\",\"argv\",\"execArgv\",\"stdin\",\"stdout\",\"stderr\",\"trackedUnmanagedFds\",\"resourceLimits\"];class Worker extends EventEmitter{#worker;#performance;#onExitPromise=void 0;constructor(filename,options={}){super();for(let key of unsupportedOptions)if(key in options)emitWarning(\"option.\"+key,`worker_threads.Worker option \"${key}\" is not implemented.`);this.#worker=new WebWorker(filename,options),this.#worker.addEventListener(\"close\",this.#onClose.bind(this)),this.#worker.addEventListener(\"error\",this.#onError.bind(this)),this.#worker.addEventListener(\"message\",this.#onMessage.bind(this)),this.#worker.addEventListener(\"messageerror\",this.#onMessageError.bind(this)),this.#worker.addEventListener(\"open\",this.#onOpen.bind(this))}ref(){this.#worker.ref()}unref(){this.#worker.unref()}get stdin(){return null}get stdout(){return null}get stderr(){return null}get performance(){return this.#performance\?\?={eventLoopUtilization(){return emitWarning(\"performance\",\"worker_threads.Worker.performance is not implemented.\"),{idle:0,active:0,utilization:0}}}}terminate(){if(this.#onExitPromise)return this.#onExitPromise;const{resolve,promise}=Promise.withResolvers();return this.once(\"exit\",(code)=>{resolve(code)}),this.#worker.terminate(),this.#onExitPromise=promise}postMessage(...args){return this.#worker.postMessage(...args)}#onClose(e){console.log(\"worker closed\",e),this.#onExitPromise=e.code,this.emit(\"exit\",e.code)}#onError(event){this.emit(\"error\",event.error)}#onMessage(event){this.emit(\"message\",event.data)}#onMessageError(event){this.emit(\"messageerror\",event.error\?\?event.data\?\?event)}#onOpen(){this.emit(\"online\")}async getHeapSnapshot(){throwNotImplemented(\"worker_threads.Worker.getHeapSnapshot\")}}return $={Worker,workerData,parentPort,resourceLimits,isMainThread,MessageChannel,BroadcastChannel,MessagePort,getEnvironmentData,setEnvironmentData,getHeapSnapshot(){return{}},markAsUntransferable,moveMessagePortToContext,receiveMessageOnPort,SHARE_ENV,threadId},$})\n"_s; +// + +// +static constexpr ASCIILiteral NodeZlibCode = "(function (){\"use strict\";const assert=@getInternalField(@internalModuleRegistry,3)||@createInternalModuleById(3),BufferModule=@requireNativeModule(\"node:buffer\"),StreamModule=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),Util=@getInternalField(@internalModuleRegistry,42)||@createInternalModuleById(42);var __getOwnPropNames=Object.getOwnPropertyNames,__commonJS=(cb,mod)=>function __require(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports},require_zstream=__commonJS({\"node_modules/pako/lib/zlib/zstream.js\"(exports,module2){function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0}module2.exports=ZStream}}),require_common=__commonJS({\"node_modules/pako/lib/utils/common.js\"(exports){var TYPED_OK=typeof Uint8Array!==\"undefined\"&&typeof Uint16Array!==\"undefined\"&&typeof Int32Array!==\"undefined\";function _has(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}exports.assign=function(obj){var sources=Array.prototype.slice.call(arguments,1);while(sources.length){var source=sources.shift();if(!source)continue;if(typeof source!==\"object\")@throwTypeError(source+\"must be non-object\");for(var p in source)if(_has(source,p))obj[p]=source[p]}return obj},exports.shrinkBuf=function(buf,size){if(buf.length===size)return buf;if(buf.subarray)return buf.subarray(0,size);return buf.length=size,buf};var fnTyped={arraySet:function(dest,src,src_offs,len,dest_offs){if(src.subarray&&dest.subarray){dest.set(src.subarray(src_offs,src_offs+len),dest_offs);return}for(var i=0;i=0)buf[len]=0}var STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH=3,MAX_MATCH=258,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],DIST_CODE_LEN=512,static_ltree=new Array((L_CODES+2)*2);zero(static_ltree);var static_dtree=new Array(D_CODES*2);zero(static_dtree);var _dist_code=new Array(DIST_CODE_LEN);zero(_dist_code);var _length_code=new Array(MAX_MATCH-MIN_MATCH+1);zero(_length_code);var base_length=new Array(LENGTH_CODES);zero(base_length);var base_dist=new Array(D_CODES);zero(base_dist);function StaticTreeDesc(static_tree,extra_bits,extra_base,elems,max_length){this.static_tree=static_tree,this.extra_bits=extra_bits,this.extra_base=extra_base,this.elems=elems,this.max_length=max_length,this.has_stree=static_tree&&static_tree.length}var static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(dyn_tree,stat_desc){this.dyn_tree=dyn_tree,this.max_code=0,this.stat_desc=stat_desc}function d_code(dist){return dist<256\?_dist_code[dist]:_dist_code[256+(dist>>>7)]}function put_short(s,w){s.pending_buf[s.pending++]=w&255,s.pending_buf[s.pending++]=w>>>8&255}function send_bits(s,value,length){if(s.bi_valid>Buf_size-length)s.bi_buf|=value<>Buf_size-s.bi_valid,s.bi_valid+=length-Buf_size;else s.bi_buf|=value<>>=1,res<<=1;while(--len>0);return res>>>1}function bi_flush(s){if(s.bi_valid===16)put_short(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0;else if(s.bi_valid>=8)s.pending_buf[s.pending++]=s.bi_buf&255,s.bi_buf>>=8,s.bi_valid-=8}function gen_bitlen(s,desc){var{dyn_tree:tree,max_code}=desc,stree=desc.stat_desc.static_tree,has_stree=desc.stat_desc.has_stree,extra=desc.stat_desc.extra_bits,base=desc.stat_desc.extra_base,max_length=desc.stat_desc.max_length,h,n,m,bits,xbits,f,overflow=0;for(bits=0;bits<=MAX_BITS;bits++)s.bl_count[bits]=0;tree[s.heap[s.heap_max]*2+1]=0;for(h=s.heap_max+1;hmax_length)bits=max_length,overflow++;if(tree[n*2+1]=bits,n>max_code)continue;if(s.bl_count[bits]++,xbits=0,n>=base)xbits=extra[n-base];if(f=tree[n*2],s.opt_len+=f*(bits+xbits),has_stree)s.static_len+=f*(stree[n*2+1]+xbits)}if(overflow===0)return;do{bits=max_length-1;while(s.bl_count[bits]===0)bits--;s.bl_count[bits]--,s.bl_count[bits+1]+=2,s.bl_count[max_length]--,overflow-=2}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){if(m=s.heap[--h],m>max_code)continue;if(tree[m*2+1]!==bits)s.opt_len+=(bits-tree[m*2+1])*tree[m*2],tree[m*2+1]=bits;n--}}}function gen_codes(tree,max_code,bl_count){var next_code=new Array(MAX_BITS+1),code=0,bits,n;for(bits=1;bits<=MAX_BITS;bits++)next_code[bits]=code=code+bl_count[bits-1]<<1;for(n=0;n<=max_code;n++){var len=tree[n*2+1];if(len===0)continue;tree[n*2]=bi_reverse(next_code[len]++,len)}}function tr_static_init(){var n,bits,length,code,dist,bl_count=new Array(MAX_BITS+1);length=0;for(code=0;code>=7;for(;code8)put_short(s,s.bi_buf);else if(s.bi_valid>0)s.pending_buf[s.pending++]=s.bi_buf;s.bi_buf=0,s.bi_valid=0}function copy_block(s,buf,len,header){if(bi_windup(s),header)put_short(s,len),put_short(s,~len);utils.arraySet(s.pending_buf,s.window,buf,len,s.pending),s.pending+=len}function smaller(tree,n,m,depth){var _n2=n*2,_m2=m*2;return tree[_n2]>1;n>=1;n--)pqdownheap(s,tree,n);node=elems;do n=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pqdownheap(s,tree,1),m=s.heap[1],s.heap[--s.heap_max]=n,s.heap[--s.heap_max]=m,tree[node*2]=tree[n*2]+tree[m*2],s.depth[node]=(s.depth[n]>=s.depth[m]\?s.depth[n]:s.depth[m])+1,tree[n*2+1]=tree[m*2+1]=node,s.heap[1]=node++,pqdownheap(s,tree,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],gen_bitlen(s,desc),gen_codes(tree,max_code,s.bl_count)}function scan_tree(s,tree,max_code){var n,prevlen=-1,curlen,nextlen=tree[1],count=0,max_count=7,min_count=4;if(nextlen===0)max_count=138,min_count=3;tree[(max_code+1)*2+1]=65535;for(n=0;n<=max_code;n++){if(curlen=nextlen,nextlen=tree[(n+1)*2+1],++count=3;max_blindex--)if(s.bl_tree[bl_order[max_blindex]*2+1]!==0)break;return s.opt_len+=3*(max_blindex+1)+5+5+4,max_blindex}function send_all_trees(s,lcodes,dcodes,blcodes){var rank;send_bits(s,lcodes-257,5),send_bits(s,dcodes-1,5),send_bits(s,blcodes-4,4);for(rank=0;rank>>=1)if(black_mask&1&&s.dyn_ltree[n*2]!==0)return Z_BINARY;if(s.dyn_ltree[18]!==0||s.dyn_ltree[20]!==0||s.dyn_ltree[26]!==0)return Z_TEXT;for(n=32;n0){if(s.strm.data_type===Z_UNKNOWN)s.strm.data_type=detect_data_type(s);if(build_tree(s,s.l_desc),build_tree(s,s.d_desc),max_blindex=build_bl_tree(s),opt_lenb=s.opt_len+3+7>>>3,static_lenb=s.static_len+3+7>>>3,static_lenb<=opt_lenb)opt_lenb=static_lenb}else opt_lenb=static_lenb=stored_len+5;if(stored_len+4<=opt_lenb&&buf!==-1)_tr_stored_block(s,buf,stored_len,last);else if(s.strategy===Z_FIXED||static_lenb===opt_lenb)send_bits(s,(STATIC_TREES<<1)+(last\?1:0),3),compress_block(s,static_ltree,static_dtree);else send_bits(s,(DYN_TREES<<1)+(last\?1:0),3),send_all_trees(s,s.l_desc.max_code+1,s.d_desc.max_code+1,max_blindex+1),compress_block(s,s.dyn_ltree,s.dyn_dtree);if(init_block(s),last)bi_windup(s)}function _tr_tally(s,dist,lc){if(s.pending_buf[s.d_buf+s.last_lit*2]=dist>>>8&255,s.pending_buf[s.d_buf+s.last_lit*2+1]=dist&255,s.pending_buf[s.l_buf+s.last_lit]=lc&255,s.last_lit++,dist===0)s.dyn_ltree[lc*2]++;else s.matches++,dist--,s.dyn_ltree[(_length_code[lc]+LITERALS+1)*2]++,s.dyn_dtree[d_code(dist)*2]++;return s.last_lit===s.lit_bufsize-1}exports._tr_init=_tr_init,exports._tr_stored_block=_tr_stored_block,exports._tr_flush_block=_tr_flush_block,exports._tr_tally=_tr_tally,exports._tr_align=_tr_align}}),require_adler32=__commonJS({\"node_modules/pako/lib/zlib/adler32.js\"(exports,module2){function adler32(adler,buf,len,pos){var s1=adler&65535|0,s2=adler>>>16&65535|0,n=0;while(len!==0){n=len>2000\?2000:len,len-=n;do s1=s1+buf[pos++]|0,s2=s2+s1|0;while(--n);s1%=65521,s2%=65521}return s1|s2<<16|0}module2.exports=adler32}}),require_crc32=__commonJS({\"node_modules/pako/lib/zlib/crc32.js\"(exports,module2){function makeTable(){var c,table=[];for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++)c=c&1\?3988292384^c>>>1:c>>>1;table[n]=c}return table}var crcTable=makeTable();function crc32(crc,buf,len,pos){var t=crcTable,end=pos+len;crc^=-1;for(var i=pos;i>>8^t[(crc^buf[i])&255];return crc^-1}module2.exports=crc32}}),require_messages=__commonJS({\"node_modules/pako/lib/zlib/messages.js\"(exports,module2){module2.exports={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"}}}),require_deflate=__commonJS({\"node_modules/pako/lib/zlib/deflate.js\"(exports){var utils=require_common(),trees=require_trees(),adler32=require_adler32(),crc32=require_crc32(),msg=require_messages(),Z_NO_FLUSH=0,Z_PARTIAL_FLUSH=1,Z_FULL_FLUSH=3,Z_FINISH=4,Z_BLOCK=5,Z_OK=0,Z_STREAM_END=1,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_BUF_ERROR=-5,Z_DEFAULT_COMPRESSION=-1,Z_FILTERED=1,Z_HUFFMAN_ONLY=2,Z_RLE=3,Z_FIXED=4,Z_DEFAULT_STRATEGY=0,Z_UNKNOWN=2,Z_DEFLATED=8,MAX_MEM_LEVEL=9,MAX_WBITS=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3;function err(strm,errorCode){return strm.msg=msg[errorCode],errorCode}function rank(f){return(f<<1)-(f>4\?9:0)}function zero(buf){var len=buf.length;while(--len>=0)buf[len]=0}function flush_pending(strm){var s=strm.state,len=s.pending;if(len>strm.avail_out)len=strm.avail_out;if(len===0)return;if(utils.arraySet(strm.output,s.pending_buf,s.pending_out,len,strm.next_out),strm.next_out+=len,s.pending_out+=len,strm.total_out+=len,strm.avail_out-=len,s.pending-=len,s.pending===0)s.pending_out=0}function flush_block_only(s,last){trees._tr_flush_block(s,s.block_start>=0\?s.block_start:-1,s.strstart-s.block_start,last),s.block_start=s.strstart,flush_pending(s.strm)}function put_byte(s,b){s.pending_buf[s.pending++]=b}function putShortMSB(s,b){s.pending_buf[s.pending++]=b>>>8&255,s.pending_buf[s.pending++]=b&255}function read_buf(strm,buf,start,size){var len=strm.avail_in;if(len>size)len=size;if(len===0)return 0;if(strm.avail_in-=len,utils.arraySet(buf,strm.input,strm.next_in,len,start),strm.state.wrap===1)strm.adler=adler32(strm.adler,buf,len,start);else if(strm.state.wrap===2)strm.adler=crc32(strm.adler,buf,len,start);return strm.next_in+=len,strm.total_in+=len,len}function longest_match(s,cur_match){var{max_chain_length:chain_length,strstart:scan}=s,match,len,best_len=s.prev_length,nice_match=s.nice_match,limit=s.strstart>s.w_size-MIN_LOOKAHEAD\?s.strstart-(s.w_size-MIN_LOOKAHEAD):0,_win=s.window,wmask=s.w_mask,prev=s.prev,strend=s.strstart+MAX_MATCH,scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len];if(s.prev_length>=s.good_match)chain_length>>=2;if(nice_match>s.lookahead)nice_match=s.lookahead;do{if(match=cur_match,_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1])continue;scan+=2,match++;do;while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scanbest_len){if(s.match_start=cur_match,best_len=len,len>=nice_match)break;scan_end1=_win[scan+best_len-1],scan_end=_win[scan+best_len]}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead)return best_len;return s.lookahead}function fill_window(s){var _w_size=s.w_size,p,n,m,more,str;do{if(more=s.window_size-s.lookahead-s.strstart,s.strstart>=_w_size+(_w_size-MIN_LOOKAHEAD)){utils.arraySet(s.window,s.window,_w_size,_w_size,0),s.match_start-=_w_size,s.strstart-=_w_size,s.block_start-=_w_size,n=s.hash_size,p=n;do m=s.head[--p],s.head[p]=m>=_w_size\?m-_w_size:0;while(--n);n=_w_size,p=n;do m=s.prev[--p],s.prev[p]=m>=_w_size\?m-_w_size:0;while(--n);more+=_w_size}if(s.strm.avail_in===0)break;if(n=read_buf(s.strm,s.window,s.strstart+s.lookahead,more),s.lookahead+=n,s.lookahead+s.insert>=MIN_MATCH){str=s.strstart-s.insert,s.ins_h=s.window[str],s.ins_h=(s.ins_h<s.pending_buf_size-5)max_block_size=s.pending_buf_size-5;for(;;){if(s.lookahead<=1){if(fill_window(s),s.lookahead===0&&flush===Z_NO_FLUSH)return BS_NEED_MORE;if(s.lookahead===0)break}s.strstart+=s.lookahead,s.lookahead=0;var max_start=s.block_start+max_block_size;if(s.strstart===0||s.strstart>=max_start){if(s.lookahead=s.strstart-max_start,s.strstart=max_start,flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}if(s.strstart-s.block_start>=s.w_size-MIN_LOOKAHEAD){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.strstart>s.block_start){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_NEED_MORE}function deflate_fast(s,flush){var hash_head,bflush;for(;;){if(s.lookahead=MIN_MATCH)s.ins_h=(s.ins_h<=MIN_MATCH)if(bflush=trees._tr_tally(s,s.strstart-s.match_start,s.match_length-MIN_MATCH),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=MIN_MATCH){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=MIN_MATCH)s.ins_h=(s.ins_h<4096))s.match_length=MIN_MATCH-1}if(s.prev_length>=MIN_MATCH&&s.match_length<=s.prev_length){max_insert=s.strstart+s.lookahead-MIN_MATCH,bflush=trees._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-MIN_MATCH),s.lookahead-=s.prev_length-1,s.prev_length-=2;do if(++s.strstart<=max_insert)s.ins_h=(s.ins_h<=MIN_MATCH&&s.strstart>0){if(scan=s.strstart-1,prev=_win[scan],prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]){strend=s.strstart+MAX_MATCH;do;while(prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&prev===_win[++scan]&&scans.lookahead)s.match_length=s.lookahead}}if(s.match_length>=MIN_MATCH)bflush=trees._tr_tally(s,1,s.match_length-MIN_MATCH),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0;else bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(bflush){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.last_lit){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_BLOCK_DONE}function deflate_huff(s,flush){var bflush;for(;;){if(s.lookahead===0){if(fill_window(s),s.lookahead===0){if(flush===Z_NO_FLUSH)return BS_NEED_MORE;break}}if(s.match_length=0,bflush=trees._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,bflush){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}}if(s.insert=0,flush===Z_FINISH){if(flush_block_only(s,!0),s.strm.avail_out===0)return BS_FINISH_STARTED;return BS_FINISH_DONE}if(s.last_lit){if(flush_block_only(s,!1),s.strm.avail_out===0)return BS_NEED_MORE}return BS_BLOCK_DONE}function Config(good_length,max_lazy,nice_length,max_chain,func){this.good_length=good_length,this.max_lazy=max_lazy,this.nice_length=nice_length,this.max_chain=max_chain,this.func=func}var configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)];function lm_init(s){s.window_size=2*s.w_size,zero(s.head),s.max_lazy_match=configuration_table[s.level].max_lazy,s.good_match=configuration_table[s.level].good_length,s.nice_match=configuration_table[s.level].nice_length,s.max_chain_length=configuration_table[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=MIN_MATCH-1,s.match_available=0,s.ins_h=0}function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new utils.Buf16(HEAP_SIZE*2),this.dyn_dtree=new utils.Buf16((2*D_CODES+1)*2),this.bl_tree=new utils.Buf16((2*BL_CODES+1)*2),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new utils.Buf16(MAX_BITS+1),this.heap=new utils.Buf16(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new utils.Buf16(2*L_CODES+1),zero(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function deflateResetKeep(strm){var s;if(!strm||!strm.state)return err(strm,Z_STREAM_ERROR);if(strm.total_in=strm.total_out=0,strm.data_type=Z_UNKNOWN,s=strm.state,s.pending=0,s.pending_out=0,s.wrap<0)s.wrap=-s.wrap;return s.status=s.wrap\?INIT_STATE:BUSY_STATE,strm.adler=s.wrap===2\?0:1,s.last_flush=Z_NO_FLUSH,trees._tr_init(s),Z_OK}function deflateReset(strm){var ret=deflateResetKeep(strm);if(ret===Z_OK)lm_init(strm.state);return ret}function deflateSetHeader(strm,head){if(!strm||!strm.state)return Z_STREAM_ERROR;if(strm.state.wrap!==2)return Z_STREAM_ERROR;return strm.state.gzhead=head,Z_OK}function deflateInit2(strm,level,method,windowBits,memLevel,strategy){if(!strm)return Z_STREAM_ERROR;var wrap=1;if(level===Z_DEFAULT_COMPRESSION)level=6;if(windowBits<0)wrap=0,windowBits=-windowBits;else if(windowBits>15)wrap=2,windowBits-=16;if(memLevel<1||memLevel>MAX_MEM_LEVEL||method!==Z_DEFLATED||windowBits<8||windowBits>15||level<0||level>9||strategy<0||strategy>Z_FIXED)return err(strm,Z_STREAM_ERROR);if(windowBits===8)windowBits=9;var s=new DeflateState;return strm.state=s,s.strm=strm,s.wrap=wrap,s.gzhead=null,s.w_bits=windowBits,s.w_size=1<Z_BLOCK||flush<0)return strm\?err(strm,Z_STREAM_ERROR):Z_STREAM_ERROR;if(s=strm.state,!strm.output||!strm.input&&strm.avail_in!==0||s.status===FINISH_STATE&&flush!==Z_FINISH)return err(strm,strm.avail_out===0\?Z_BUF_ERROR:Z_STREAM_ERROR);if(s.strm=strm,old_flush=s.last_flush,s.last_flush=flush,s.status===INIT_STATE)if(s.wrap===2)if(strm.adler=0,put_byte(s,31),put_byte(s,139),put_byte(s,8),!s.gzhead)put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,0),put_byte(s,s.level===9\?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2\?4:0),put_byte(s,OS_CODE),s.status=BUSY_STATE;else{if(put_byte(s,(s.gzhead.text\?1:0)+(s.gzhead.hcrc\?2:0)+(!s.gzhead.extra\?0:4)+(!s.gzhead.name\?0:8)+(!s.gzhead.comment\?0:16)),put_byte(s,s.gzhead.time&255),put_byte(s,s.gzhead.time>>8&255),put_byte(s,s.gzhead.time>>16&255),put_byte(s,s.gzhead.time>>24&255),put_byte(s,s.level===9\?2:s.strategy>=Z_HUFFMAN_ONLY||s.level<2\?4:0),put_byte(s,s.gzhead.os&255),s.gzhead.extra&&s.gzhead.extra.length)put_byte(s,s.gzhead.extra.length&255),put_byte(s,s.gzhead.extra.length>>8&255);if(s.gzhead.hcrc)strm.adler=crc32(strm.adler,s.pending_buf,s.pending,0);s.gzindex=0,s.status=EXTRA_STATE}else{var header=Z_DEFLATED+(s.w_bits-8<<4)<<8,level_flags=-1;if(s.strategy>=Z_HUFFMAN_ONLY||s.level<2)level_flags=0;else if(s.level<6)level_flags=1;else if(s.level===6)level_flags=2;else level_flags=3;if(header|=level_flags<<6,s.strstart!==0)header|=PRESET_DICT;if(header+=31-header%31,s.status=BUSY_STATE,putShortMSB(s,header),s.strstart!==0)putShortMSB(s,strm.adler>>>16),putShortMSB(s,strm.adler&65535);strm.adler=1}if(s.status===EXTRA_STATE)if(s.gzhead.extra){beg=s.pending;while(s.gzindex<(s.gzhead.extra.length&65535)){if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size)break}put_byte(s,s.gzhead.extra[s.gzindex]&255),s.gzindex++}if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(s.gzindex===s.gzhead.extra.length)s.gzindex=0,s.status=NAME_STATE}else s.status=NAME_STATE;if(s.status===NAME_STATE)if(s.gzhead.name){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size){val=1;break}}if(s.gzindexbeg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(val===0)s.gzindex=0,s.status=COMMENT_STATE}else s.status=COMMENT_STATE;if(s.status===COMMENT_STATE)if(s.gzhead.comment){beg=s.pending;do{if(s.pending===s.pending_buf_size){if(s.gzhead.hcrc&&s.pending>beg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(flush_pending(strm),beg=s.pending,s.pending===s.pending_buf_size){val=1;break}}if(s.gzindexbeg)strm.adler=crc32(strm.adler,s.pending_buf,s.pending-beg,beg);if(val===0)s.status=HCRC_STATE}else s.status=HCRC_STATE;if(s.status===HCRC_STATE)if(s.gzhead.hcrc){if(s.pending+2>s.pending_buf_size)flush_pending(strm);if(s.pending+2<=s.pending_buf_size)put_byte(s,strm.adler&255),put_byte(s,strm.adler>>8&255),strm.adler=0,s.status=BUSY_STATE}else s.status=BUSY_STATE;if(s.pending!==0){if(flush_pending(strm),strm.avail_out===0)return s.last_flush=-1,Z_OK}else if(strm.avail_in===0&&rank(flush)<=rank(old_flush)&&flush!==Z_FINISH)return err(strm,Z_BUF_ERROR);if(s.status===FINISH_STATE&&strm.avail_in!==0)return err(strm,Z_BUF_ERROR);if(strm.avail_in!==0||s.lookahead!==0||flush!==Z_NO_FLUSH&&s.status!==FINISH_STATE){var bstate=s.strategy===Z_HUFFMAN_ONLY\?deflate_huff(s,flush):s.strategy===Z_RLE\?deflate_rle(s,flush):configuration_table[s.level].func(s,flush);if(bstate===BS_FINISH_STARTED||bstate===BS_FINISH_DONE)s.status=FINISH_STATE;if(bstate===BS_NEED_MORE||bstate===BS_FINISH_STARTED){if(strm.avail_out===0)s.last_flush=-1;return Z_OK}if(bstate===BS_BLOCK_DONE){if(flush===Z_PARTIAL_FLUSH)trees._tr_align(s);else if(flush!==Z_BLOCK){if(trees._tr_stored_block(s,0,0,!1),flush===Z_FULL_FLUSH){if(zero(s.head),s.lookahead===0)s.strstart=0,s.block_start=0,s.insert=0}}if(flush_pending(strm),strm.avail_out===0)return s.last_flush=-1,Z_OK}}if(flush!==Z_FINISH)return Z_OK;if(s.wrap<=0)return Z_STREAM_END;if(s.wrap===2)put_byte(s,strm.adler&255),put_byte(s,strm.adler>>8&255),put_byte(s,strm.adler>>16&255),put_byte(s,strm.adler>>24&255),put_byte(s,strm.total_in&255),put_byte(s,strm.total_in>>8&255),put_byte(s,strm.total_in>>16&255),put_byte(s,strm.total_in>>24&255);else putShortMSB(s,strm.adler>>>16),putShortMSB(s,strm.adler&65535);if(flush_pending(strm),s.wrap>0)s.wrap=-s.wrap;return s.pending!==0\?Z_OK:Z_STREAM_END}function deflateEnd(strm){var status;if(!strm||!strm.state)return Z_STREAM_ERROR;if(status=strm.state.status,status!==INIT_STATE&&status!==EXTRA_STATE&&status!==NAME_STATE&&status!==COMMENT_STATE&&status!==HCRC_STATE&&status!==BUSY_STATE&&status!==FINISH_STATE)return err(strm,Z_STREAM_ERROR);return strm.state=null,status===BUSY_STATE\?err(strm,Z_DATA_ERROR):Z_OK}function deflateSetDictionary(strm,dictionary){var dictLength=dictionary.length,s,str,n,wrap,avail,next,input,tmpDict;if(!strm||!strm.state)return Z_STREAM_ERROR;if(s=strm.state,wrap=s.wrap,wrap===2||wrap===1&&s.status!==INIT_STATE||s.lookahead)return Z_STREAM_ERROR;if(wrap===1)strm.adler=adler32(strm.adler,dictionary,dictLength,0);if(s.wrap=0,dictLength>=s.w_size){if(wrap===0)zero(s.head),s.strstart=0,s.block_start=0,s.insert=0;tmpDict=new utils.Buf8(s.w_size),utils.arraySet(tmpDict,dictionary,dictLength-s.w_size,s.w_size,0),dictionary=tmpDict,dictLength=s.w_size}avail=strm.avail_in,next=strm.next_in,input=strm.input,strm.avail_in=dictLength,strm.next_in=0,strm.input=dictionary,fill_window(s);while(s.lookahead>=MIN_MATCH){str=s.strstart,n=s.lookahead-(MIN_MATCH-1);do s.ins_h=(s.ins_h<>>24,hold>>>=op,bits-=op,op=here>>>16&255,op===0)output[_out++]=here&65535;else if(op&16){if(len=here&65535,op&=15,op){if(bits>>=op,bits-=op}if(bits<15)hold+=input[_in++]<>>24,hold>>>=op,bits-=op,op=here>>>16&255,op&16){if(dist=here&65535,op&=15,bitsdmax){strm.msg=\"invalid distance too far back\",state.mode=BAD;break top}if(hold>>>=op,bits-=op,op=_out-beg,dist>op){if(op=dist-op,op>whave){if(state.sane){strm.msg=\"invalid distance too far back\",state.mode=BAD;break top}}if(from=0,from_source=s_window,wnext===0){if(from+=wsize-op,op2)output[_out++]=from_source[from++],output[_out++]=from_source[from++],output[_out++]=from_source[from++],len-=3;if(len){if(output[_out++]=from_source[from++],len>1)output[_out++]=from_source[from++]}}else{from=_out-dist;do output[_out++]=output[from++],output[_out++]=output[from++],output[_out++]=output[from++],len-=3;while(len>2);if(len){if(output[_out++]=output[from++],len>1)output[_out++]=output[from++]}}}else if((op&64)===0){here=dcode[(here&65535)+(hold&(1<>3,_in-=len,bits-=len<<3,hold&=(1<=1;max--)if(count[max]!==0)break;if(root>max)root=max;if(max===0)return table[table_index++]=1<<24|64<<16|0,table[table_index++]=1<<24|64<<16|0,opts.bits=1,0;for(min=1;min0&&(type===CODES||max!==1))return-1;offs[1]=0;for(len=1;lenENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS)return 1;for(;;){if(here_bits=len-drop,work[sym]end)here_op=extra[extra_index+work[sym]],here_val=base[base_index+work[sym]];else here_op=96,here_val=0;incr=1<>drop)+fill]=here_bits<<24|here_op<<16|here_val|0;while(fill!==0);incr=1<>=1;if(incr!==0)huff&=incr-1,huff+=incr;else huff=0;if(sym++,--count[len]===0){if(len===max)break;len=lens[lens_index+work[sym]]}if(len>root&&(huff&mask)!==low){if(drop===0)drop=root;next+=min,curr=len-drop,left=1<ENOUGH_LENS||type===DISTS&&used>ENOUGH_DISTS)return 1;low=huff&mask,table[low]=root<<24|curr<<16|next-table_index|0}}if(huff!==0)table[next+huff]=len-drop<<24|64<<16|0;return opts.bits=root,0}}}),require_inflate=__commonJS({\"node_modules/pako/lib/zlib/inflate.js\"(exports){var utils=require_common(),adler32=require_adler32(),crc32=require_crc32(),inflate_fast=require_inffast(),inflate_table=require_inftrees(),CODES=0,LENS=1,DISTS=2,Z_FINISH=4,Z_BLOCK=5,Z_TREES=6,Z_OK=0,Z_STREAM_END=1,Z_NEED_DICT=2,Z_STREAM_ERROR=-2,Z_DATA_ERROR=-3,Z_MEM_ERROR=-4,Z_BUF_ERROR=-5,Z_DEFLATED=8,HEAD=1,FLAGS=2,TIME=3,OS=4,EXLEN=5,EXTRA=6,NAME=7,COMMENT=8,HCRC=9,DICTID=10,DICT=11,TYPE=12,TYPEDO=13,STORED=14,COPY_=15,COPY=16,TABLE=17,LENLENS=18,CODELENS=19,LEN_=20,LEN=21,LENEXT=22,DIST=23,DISTEXT=24,MATCH=25,LIT=26,CHECK=27,LENGTH=28,DONE=29,BAD=30,MEM=31,SYNC=32,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS;function zswap32(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function InflateState(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new utils.Buf16(320),this.work=new utils.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function inflateResetKeep(strm){var state;if(!strm||!strm.state)return Z_STREAM_ERROR;if(state=strm.state,strm.total_in=strm.total_out=state.total=0,strm.msg=\"\",state.wrap)strm.adler=state.wrap&1;return state.mode=HEAD,state.last=0,state.havedict=0,state.dmax=32768,state.head=null,state.hold=0,state.bits=0,state.lencode=state.lendyn=new utils.Buf32(ENOUGH_LENS),state.distcode=state.distdyn=new utils.Buf32(ENOUGH_DISTS),state.sane=1,state.back=-1,Z_OK}function inflateReset(strm){var state;if(!strm||!strm.state)return Z_STREAM_ERROR;return state=strm.state,state.wsize=0,state.whave=0,state.wnext=0,inflateResetKeep(strm)}function inflateReset2(strm,windowBits){var wrap,state;if(!strm||!strm.state)return Z_STREAM_ERROR;if(state=strm.state,windowBits<0)wrap=0,windowBits=-windowBits;else if(wrap=(windowBits>>4)+1,windowBits<48)windowBits&=15;if(windowBits&&(windowBits<8||windowBits>15))return Z_STREAM_ERROR;if(state.window!==null&&state.wbits!==windowBits)state.window=null;return state.wrap=wrap,state.wbits=windowBits,inflateReset(strm)}function inflateInit2(strm,windowBits){var ret,state;if(!strm)return Z_STREAM_ERROR;if(state=new InflateState,strm.state=state,state.window=null,ret=inflateReset2(strm,windowBits),ret!==Z_OK)strm.state=null;return ret}function inflateInit(strm){return inflateInit2(strm,DEF_WBITS)}var virgin=!0,lenfix,distfix;function fixedtables(state){if(virgin){var sym;lenfix=new utils.Buf32(512),distfix=new utils.Buf32(32),sym=0;while(sym<144)state.lens[sym++]=8;while(sym<256)state.lens[sym++]=9;while(sym<280)state.lens[sym++]=7;while(sym<288)state.lens[sym++]=8;inflate_table(LENS,state.lens,0,288,lenfix,0,state.work,{bits:9}),sym=0;while(sym<32)state.lens[sym++]=5;inflate_table(DISTS,state.lens,0,32,distfix,0,state.work,{bits:5}),virgin=!1}state.lencode=lenfix,state.lenbits=9,state.distcode=distfix,state.distbits=5}function updatewindow(strm,src,end,copy){var dist,state=strm.state;if(state.window===null)state.wsize=1<=state.wsize)utils.arraySet(state.window,src,end-state.wsize,state.wsize,0),state.wnext=0,state.whave=state.wsize;else{if(dist=state.wsize-state.wnext,dist>copy)dist=copy;if(utils.arraySet(state.window,src,end-copy,dist,state.wnext),copy-=dist,copy)utils.arraySet(state.window,src,end-copy,copy,0),state.wnext=copy,state.whave=state.wsize;else{if(state.wnext+=dist,state.wnext===state.wsize)state.wnext=0;if(state.whave>>8&255,state.check=crc32(state.check,hbuf,2,0),hold=0,bits=0,state.mode=FLAGS;break}if(state.flags=0,state.head)state.head.done=!1;if(!(state.wrap&1)||(((hold&255)<<8)+(hold>>8))%31){strm.msg=\"incorrect header check\",state.mode=BAD;break}if((hold&15)!==Z_DEFLATED){strm.msg=\"unknown compression method\",state.mode=BAD;break}if(hold>>>=4,bits-=4,len=(hold&15)+8,state.wbits===0)state.wbits=len;else if(len>state.wbits){strm.msg=\"invalid window size\",state.mode=BAD;break}state.dmax=1<>8&1;if(state.flags&512)hbuf[0]=hold&255,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0,state.mode=TIME;case TIME:while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>8&255,hbuf[2]=hold>>>16&255,hbuf[3]=hold>>>24&255,state.check=crc32(state.check,hbuf,4,0);hold=0,bits=0,state.mode=OS;case OS:while(bits<16){if(have===0)break inf_leave;have--,hold+=input[next++]<>8;if(state.flags&512)hbuf[0]=hold&255,hbuf[1]=hold>>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0,state.mode=EXLEN;case EXLEN:if(state.flags&1024){while(bits<16){if(have===0)break inf_leave;have--,hold+=input[next++]<>>8&255,state.check=crc32(state.check,hbuf,2,0);hold=0,bits=0}else if(state.head)state.head.extra=null;state.mode=EXTRA;case EXTRA:if(state.flags&1024){if(copy=state.length,copy>have)copy=have;if(copy){if(state.head){if(len=state.head.extra_len-state.length,!state.head.extra)state.head.extra=new Array(state.head.extra_len);utils.arraySet(state.head.extra,input,next,copy,len)}if(state.flags&512)state.check=crc32(state.check,input,copy,next);have-=copy,next+=copy,state.length-=copy}if(state.length)break inf_leave}state.length=0,state.mode=NAME;case NAME:if(state.flags&2048){if(have===0)break inf_leave;copy=0;do if(len=input[next+copy++],state.head&&len&&state.length<65536)state.head.name+=String.fromCharCode(len);while(len&©>9&1,state.head.done=!0;strm.adler=state.check=0,state.mode=TYPE;break;case DICTID:while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=bits&7,bits-=bits&7,state.mode=CHECK;break}while(bits<3){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=1,bits-=1,hold&3){case 0:state.mode=STORED;break;case 1:if(fixedtables(state),state.mode=LEN_,flush===Z_TREES){hold>>>=2,bits-=2;break inf_leave}break;case 2:state.mode=TABLE;break;case 3:strm.msg=\"invalid block type\",state.mode=BAD}hold>>>=2,bits-=2;break;case STORED:hold>>>=bits&7,bits-=bits&7;while(bits<32){if(have===0)break inf_leave;have--,hold+=input[next++]<>>16^65535)){strm.msg=\"invalid stored block lengths\",state.mode=BAD;break}if(state.length=hold&65535,hold=0,bits=0,state.mode=COPY_,flush===Z_TREES)break inf_leave;case COPY_:state.mode=COPY;case COPY:if(copy=state.length,copy){if(copy>have)copy=have;if(copy>left)copy=left;if(copy===0)break inf_leave;utils.arraySet(output,input,next,copy,put),have-=copy,next+=copy,left-=copy,put+=copy,state.length-=copy;break}state.mode=TYPE;break;case TABLE:while(bits<14){if(have===0)break inf_leave;have--,hold+=input[next++]<>>=5,bits-=5,state.ndist=(hold&31)+1,hold>>>=5,bits-=5,state.ncode=(hold&15)+4,hold>>>=4,bits-=4,state.nlen>286||state.ndist>30){strm.msg=\"too many length or distance symbols\",state.mode=BAD;break}state.have=0,state.mode=LENLENS;case LENLENS:while(state.have>>=3,bits-=3}while(state.have<19)state.lens[order[state.have++]]=0;if(state.lencode=state.lendyn,state.lenbits=7,opts={bits:state.lenbits},ret=inflate_table(CODES,state.lens,0,19,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg=\"invalid code lengths set\",state.mode=BAD;break}state.have=0,state.mode=CODELENS;case CODELENS:while(state.have>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=here_bits,bits-=here_bits,state.lens[state.have++]=here_val;else{if(here_val===16){n=here_bits+2;while(bits>>=here_bits,bits-=here_bits,state.have===0){strm.msg=\"invalid bit length repeat\",state.mode=BAD;break}len=state.lens[state.have-1],copy=3+(hold&3),hold>>>=2,bits-=2}else if(here_val===17){n=here_bits+3;while(bits>>=here_bits,bits-=here_bits,len=0,copy=3+(hold&7),hold>>>=3,bits-=3}else{n=here_bits+7;while(bits>>=here_bits,bits-=here_bits,len=0,copy=11+(hold&127),hold>>>=7,bits-=7}if(state.have+copy>state.nlen+state.ndist){strm.msg=\"invalid bit length repeat\",state.mode=BAD;break}while(copy--)state.lens[state.have++]=len}}if(state.mode===BAD)break;if(state.lens[256]===0){strm.msg=\"invalid code -- missing end-of-block\",state.mode=BAD;break}if(state.lenbits=9,opts={bits:state.lenbits},ret=inflate_table(LENS,state.lens,0,state.nlen,state.lencode,0,state.work,opts),state.lenbits=opts.bits,ret){strm.msg=\"invalid literal/lengths set\",state.mode=BAD;break}if(state.distbits=6,state.distcode=state.distdyn,opts={bits:state.distbits},ret=inflate_table(DISTS,state.lens,state.nlen,state.ndist,state.distcode,0,state.work,opts),state.distbits=opts.bits,ret){strm.msg=\"invalid distances set\",state.mode=BAD;break}if(state.mode=LEN_,flush===Z_TREES)break inf_leave;case LEN_:state.mode=LEN;case LEN:if(have>=6&&left>=258){if(strm.next_out=put,strm.avail_out=left,strm.next_in=next,strm.avail_in=have,state.hold=hold,state.bits=bits,inflate_fast(strm,_out),put=strm.next_out,output=strm.output,left=strm.avail_out,next=strm.next_in,input=strm.input,have=strm.avail_in,hold=state.hold,bits=state.bits,state.mode===TYPE)state.back=-1;break}state.back=0;for(;;){if(here=state.lencode[hold&(1<>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=here&65535,last_bits+here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,state.length=here_val,here_op===0){state.mode=LIT;break}if(here_op&32){state.back=-1,state.mode=TYPE;break}if(here_op&64){strm.msg=\"invalid literal/length code\",state.mode=BAD;break}state.extra=here_op&15,state.mode=LENEXT;case LENEXT:if(state.extra){n=state.extra;while(bits>>=state.extra,bits-=state.extra,state.back+=state.extra}state.was=state.length,state.mode=DIST;case DIST:for(;;){if(here=state.distcode[hold&(1<>>24,here_op=here>>>16&255,here_val=here&65535,here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>last_bits)],here_bits=here>>>24,here_op=here>>>16&255,here_val=here&65535,last_bits+here_bits<=bits)break;if(have===0)break inf_leave;have--,hold+=input[next++]<>>=last_bits,bits-=last_bits,state.back+=last_bits}if(hold>>>=here_bits,bits-=here_bits,state.back+=here_bits,here_op&64){strm.msg=\"invalid distance code\",state.mode=BAD;break}state.offset=here_val,state.extra=here_op&15,state.mode=DISTEXT;case DISTEXT:if(state.extra){n=state.extra;while(bits>>=state.extra,bits-=state.extra,state.back+=state.extra}if(state.offset>state.dmax){strm.msg=\"invalid distance too far back\",state.mode=BAD;break}state.mode=MATCH;case MATCH:if(left===0)break inf_leave;if(copy=_out-left,state.offset>copy){if(copy=state.offset-copy,copy>state.whave){if(state.sane){strm.msg=\"invalid distance too far back\",state.mode=BAD;break}}if(copy>state.wnext)copy-=state.wnext,from=state.wsize-copy;else from=state.wnext-copy;if(copy>state.length)copy=state.length;from_source=state.window}else from_source=output,from=put-state.offset,copy=state.length;if(copy>left)copy=left;left-=copy,state.length-=copy;do output[put++]=from_source[from++];while(--copy);if(state.length===0)state.mode=LEN;break;case LIT:if(left===0)break inf_leave;output[put++]=state.length,left--,state.mode=LEN;break;case CHECK:if(state.wrap){while(bits<32){if(have===0)break inf_leave;have--,hold|=input[next++]<exports.UNZIP)@throwTypeError(\"Bad argument\");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=mode,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}Zlib.prototype={},Zlib.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}if(this.pending_close=!1,assert(this.init_done,\"close before init\"),assert(this.mode<=exports.UNZIP),this.mode===exports.DEFLATE||this.mode===exports.GZIP||this.mode===exports.DEFLATERAW)zlib_deflate.deflateEnd(this.strm);else if(this.mode===exports.INFLATE||this.mode===exports.GUNZIP||this.mode===exports.INFLATERAW||this.mode===exports.UNZIP)zlib_inflate.inflateEnd(this.strm);this.mode=exports.NONE,this.dictionary=null},Zlib.prototype.write=function(flush,input,in_off,in_len,out,out_off,out_len){return this._write(!0,flush,input,in_off,in_len,out,out_off,out_len)},Zlib.prototype.writeSync=function(flush,input,in_off,in_len,out,out_off,out_len){return this._write(!1,flush,input,in_off,in_len,out,out_off,out_len)},Zlib.prototype._write=function(async,flush,input,in_off,in_len,out,out_off,out_len){if(assert.equal(arguments.length,8),assert(this.init_done,\"write before init\"),assert(this.mode!==exports.NONE,\"already finalized\"),assert.equal(!1,this.write_in_progress,\"write already in progress\"),assert.equal(!1,this.pending_close,\"close is pending\"),this.write_in_progress=!0,assert.equal(!1,flush===void 0,\"must provide flush value\"),this.write_in_progress=!0,flush!==exports.Z_NO_FLUSH&&flush!==exports.Z_PARTIAL_FLUSH&&flush!==exports.Z_SYNC_FLUSH&&flush!==exports.Z_FULL_FLUSH&&flush!==exports.Z_FINISH&&flush!==exports.Z_BLOCK)throw new Error(\"Invalid flush value\");if(input==null)input=Buffer.alloc(0),in_len=0,in_off=0;if(this.strm.avail_in=in_len,this.strm.input=input,this.strm.next_in=in_off,this.strm.avail_out=out_len,this.strm.output=out,this.strm.next_out=out_off,this.flush=flush,!async){if(this._process(),this._checkError())return this._afterSync();return}var self=this;return process.nextTick(function(){self._process(),self._after()}),this},Zlib.prototype._afterSync=function(){var avail_out=this.strm.avail_out,avail_in=this.strm.avail_in;return this.write_in_progress=!1,[avail_in,avail_out]},Zlib.prototype._process=function(){var next_expected_header_byte=null;switch(this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:this.err=zlib_deflate.deflate(this.strm,this.flush);break;case exports.UNZIP:if(this.strm.avail_in>0)next_expected_header_byte=this.strm.next_in;switch(this.gzip_id_bytes_read){case 0:if(next_expected_header_byte===null)break;if(this.strm.input[next_expected_header_byte]===GZIP_HEADER_ID1){if(this.gzip_id_bytes_read=1,next_expected_header_byte++,this.strm.avail_in===1)break}else{this.mode=exports.INFLATE;break}case 1:if(next_expected_header_byte===null)break;if(this.strm.input[next_expected_header_byte]===GZIP_HEADER_ID2)this.gzip_id_bytes_read=2,this.mode=exports.GUNZIP;else this.mode=exports.INFLATE;break;default:throw new Error(\"invalid number of gzip magic number bytes read\")}case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:if(this.err=zlib_inflate.inflate(this.strm,this.flush),this.err===exports.Z_NEED_DICT&&this.dictionary){if(this.err=zlib_inflate.inflateSetDictionary(this.strm,this.dictionary),this.err===exports.Z_OK)this.err=zlib_inflate.inflate(this.strm,this.flush);else if(this.err===exports.Z_DATA_ERROR)this.err=exports.Z_NEED_DICT}while(this.strm.avail_in>0&&this.mode===exports.GUNZIP&&this.err===exports.Z_STREAM_END&&this.strm.next_in[0]!==0)this.reset(),this.err=zlib_inflate.inflate(this.strm,this.flush);break;default:throw new Error(\"Unknown mode \"+this.mode)}},Zlib.prototype._checkError=function(){switch(this.err){case exports.Z_OK:case exports.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===exports.Z_FINISH)return this._error(\"unexpected end of file\"),!1;break;case exports.Z_STREAM_END:break;case exports.Z_NEED_DICT:if(this.dictionary==null)this._error(\"Missing dictionary\");else this._error(\"Bad dictionary\");return!1;default:return this._error(\"Zlib error\"),!1}return!0},Zlib.prototype._after=function(){if(!this._checkError())return;var avail_out=this.strm.avail_out,avail_in=this.strm.avail_in;if(this.write_in_progress=!1,this.callback(avail_in,avail_out),this.pending_close)this.close()},Zlib.prototype._error=function(message){if(this.strm.msg)message=this.strm.msg;if(this.onerror(message,this.err),this.write_in_progress=!1,this.pending_close)this.close()},Zlib.prototype.init=function(windowBits,level,memLevel,strategy,dictionary){assert(arguments.length===4||arguments.length===5,\"init(windowBits, level, memLevel, strategy, [dictionary])\"),assert(windowBits>=8&&windowBits<=15,\"invalid windowBits\"),assert(level>=-1&&level<=9,\"invalid compression level\"),assert(memLevel>=1&&memLevel<=9,\"invalid memlevel\"),assert(strategy===exports.Z_FILTERED||strategy===exports.Z_HUFFMAN_ONLY||strategy===exports.Z_RLE||strategy===exports.Z_FIXED||strategy===exports.Z_DEFAULT_STRATEGY,\"invalid strategy\"),this._init(level,windowBits,memLevel,strategy,dictionary),this._setDictionary()},Zlib.prototype.params=function(){throw new Error(\"deflateParams Not supported\")},Zlib.prototype.reset=function(){this._reset(),this._setDictionary()},Zlib.prototype._init=function(level,windowBits,memLevel,strategy,dictionary){if(this.level=level,this.windowBits=windowBits,this.memLevel=memLevel,this.strategy=strategy,this.flush=exports.Z_NO_FLUSH,this.err=exports.Z_OK,this.mode===exports.GZIP||this.mode===exports.GUNZIP)this.windowBits+=16;if(this.mode===exports.UNZIP)this.windowBits+=32;if(this.mode===exports.DEFLATERAW||this.mode===exports.INFLATERAW)this.windowBits=-1*this.windowBits;switch(this.strm=new Zstream,this.mode){case exports.DEFLATE:case exports.GZIP:case exports.DEFLATERAW:this.err=zlib_deflate.deflateInit2(this.strm,this.level,exports.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case exports.INFLATE:case exports.GUNZIP:case exports.INFLATERAW:case exports.UNZIP:this.err=zlib_inflate.inflateInit2(this.strm,this.windowBits);break;default:throw new Error(\"Unknown mode \"+this.mode)}if(this.err!==exports.Z_OK)this._error(\"Init error\");this.dictionary=dictionary,this.write_in_progress=!1,this.init_done=!0},Zlib.prototype._setDictionary=function(){if(this.dictionary==null)return;switch(this.err=exports.Z_OK,this.mode){case exports.DEFLATE:case exports.DEFLATERAW:this.err=zlib_deflate.deflateSetDictionary(this.strm,this.dictionary);break;default:break}if(this.err!==exports.Z_OK)this._error(\"Failed to set dictionary\")},Zlib.prototype._reset=function(){switch(this.err=exports.Z_OK,this.mode){case exports.DEFLATE:case exports.DEFLATERAW:case exports.GZIP:this.err=zlib_deflate.deflateReset(this.strm);break;case exports.INFLATE:case exports.INFLATERAW:case exports.GUNZIP:this.err=zlib_inflate.inflateReset(this.strm);break;default:break}if(this.err!==exports.Z_OK)this._error(\"Failed to reset stream\")},exports.Zlib=Zlib}}),require_lib=__commonJS({\"node_modules/browserify-zlib/lib/index.js\"(exports){var Buffer2=BufferModule.Buffer,Transform=StreamModule.Transform,binding=require_binding(),util=Util,kMaxLength=BufferModule.kMaxLength,kRangeErrorMessage=\"Cannot create final Buffer. It would be larger than 0x\"+kMaxLength.toString(16)+\" bytes\";binding.Z_MIN_WINDOWBITS=8,binding.Z_MAX_WINDOWBITS=15,binding.Z_DEFAULT_WINDOWBITS=15,binding.Z_MIN_CHUNK=64,binding.Z_MAX_CHUNK=Infinity,binding.Z_DEFAULT_CHUNK=16384,binding.Z_MIN_MEMLEVEL=1,binding.Z_MAX_MEMLEVEL=9,binding.Z_DEFAULT_MEMLEVEL=8,binding.Z_MIN_LEVEL=-1,binding.Z_MAX_LEVEL=9,binding.Z_DEFAULT_LEVEL=binding.Z_DEFAULT_COMPRESSION;var bkeys=Object.keys(binding);for(bk=0;bk=kMaxLength)err=new RangeError(kRangeErrorMessage);else buf=Buffer2.concat(buffers,nread);buffers=[],engine.close(),callback(err,buf)}}function zlibBufferSync(engine,buffer){if(typeof buffer===\"string\")buffer=Buffer2.from(buffer);if(!Buffer2.isBuffer(buffer))@throwTypeError(\"Not a string or buffer\");var flushFlag=engine._finishFlushFlag;return engine._processChunk(buffer,flushFlag)}function Deflate(opts){if(!(this instanceof Deflate))return new Deflate(opts);Zlib.call(this,opts,binding.DEFLATE)}function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);Zlib.call(this,opts,binding.INFLATE)}function Gzip(opts){if(!(this instanceof Gzip))return new Gzip(opts);Zlib.call(this,opts,binding.GZIP)}function Gunzip(opts){if(!(this instanceof Gunzip))return new Gunzip(opts);Zlib.call(this,opts,binding.GUNZIP)}function DeflateRaw(opts){if(!(this instanceof DeflateRaw))return new DeflateRaw(opts);Zlib.call(this,opts,binding.DEFLATERAW)}function InflateRaw(opts){if(!(this instanceof InflateRaw))return new InflateRaw(opts);Zlib.call(this,opts,binding.INFLATERAW)}function Unzip(opts){if(!(this instanceof Unzip))return new Unzip(opts);Zlib.call(this,opts,binding.UNZIP)}function isValidFlushFlag(flag){return flag===binding.Z_NO_FLUSH||flag===binding.Z_PARTIAL_FLUSH||flag===binding.Z_SYNC_FLUSH||flag===binding.Z_FULL_FLUSH||flag===binding.Z_FINISH||flag===binding.Z_BLOCK}function Zlib(opts,mode){var _this=this;if(this._opts=opts=opts||{},this._chunkSize=opts.chunkSize||exports.Z_DEFAULT_CHUNK,Transform.call(this,opts),opts.flush&&!isValidFlushFlag(opts.flush))throw new Error(\"Invalid flush flag: \"+opts.flush);if(opts.finishFlush&&!isValidFlushFlag(opts.finishFlush))throw new Error(\"Invalid flush flag: \"+opts.finishFlush);if(this._flushFlag=opts.flush||binding.Z_NO_FLUSH,this._finishFlushFlag=typeof opts.finishFlush!==\"undefined\"\?opts.finishFlush:binding.Z_FINISH,opts.chunkSize){if(opts.chunkSizeexports.Z_MAX_CHUNK)throw new Error(\"Invalid chunk size: \"+opts.chunkSize)}if(opts.windowBits){if(opts.windowBitsexports.Z_MAX_WINDOWBITS)throw new Error(\"Invalid windowBits: \"+opts.windowBits)}if(opts.level){if(opts.levelexports.Z_MAX_LEVEL)throw new Error(\"Invalid compression level: \"+opts.level)}if(opts.memLevel){if(opts.memLevelexports.Z_MAX_MEMLEVEL)throw new Error(\"Invalid memLevel: \"+opts.memLevel)}if(opts.strategy){if(opts.strategy!=exports.Z_FILTERED&&opts.strategy!=exports.Z_HUFFMAN_ONLY&&opts.strategy!=exports.Z_RLE&&opts.strategy!=exports.Z_FIXED&&opts.strategy!=exports.Z_DEFAULT_STRATEGY)throw new Error(\"Invalid strategy: \"+opts.strategy)}if(opts.dictionary){if(!Buffer2.isBuffer(opts.dictionary))throw new Error(\"Invalid dictionary: it should be a Buffer instance\")}this._handle=new binding.Zlib(mode);var self=this;this._hadError=!1,this._handle.onerror=function(message,errno){_close(self),self._hadError=!0;var error=new Error(message);error.errno=errno,error.code=exports.codes[errno],self.emit(\"error\",error)};var level=exports.Z_DEFAULT_COMPRESSION;if(typeof opts.level===\"number\")level=opts.level;var strategy=exports.Z_DEFAULT_STRATEGY;if(typeof opts.strategy===\"number\")strategy=opts.strategy;this._handle.init(opts.windowBits||exports.Z_DEFAULT_WINDOWBITS,level,opts.memLevel||exports.Z_DEFAULT_MEMLEVEL,strategy,opts.dictionary),this._buffer=Buffer2.allocUnsafe(this._chunkSize),this._offset=0,this._level=level,this._strategy=strategy,this.once(\"end\",this.close),Object.defineProperty(this,\"_closed\",{get:function(){return!_this._handle},configurable:!0,enumerable:!0})}util.inherits(Zlib,Transform),Zlib.prototype.params=function(level,strategy,callback){if(levelexports.Z_MAX_LEVEL)@throwRangeError(\"Invalid compression level: \"+level);if(strategy!=exports.Z_FILTERED&&strategy!=exports.Z_HUFFMAN_ONLY&&strategy!=exports.Z_RLE&&strategy!=exports.Z_FIXED&&strategy!=exports.Z_DEFAULT_STRATEGY)@throwTypeError(\"Invalid strategy: \"+strategy);if(this._level!==level||this._strategy!==strategy){var self=this;this.flush(binding.Z_SYNC_FLUSH,function(){if(assert(self._handle,\"zlib binding closed\"),self._handle.params(level,strategy),!self._hadError){if(self._level=level,self._strategy=strategy,callback)callback()}})}else process.nextTick(callback)},Zlib.prototype.reset=function(){return assert(this._handle,\"zlib binding closed\"),this._handle.reset()},Zlib.prototype._flush=function(callback){this._transform(Buffer2.alloc(0),\"\",callback)},Zlib.prototype.flush=function(kind,callback){var _this2=this,ws=this._writableState;if(typeof kind===\"function\"||kind===void 0&&!callback)callback=kind,kind=binding.Z_FULL_FLUSH;if(ws.ended){if(callback)process.nextTick(callback)}else if(ws.ending){if(callback)this.once(\"end\",callback)}else if(ws.needDrain){if(callback)this.once(\"drain\",function(){return _this2.flush(kind,callback)})}else this._flushFlag=kind,this.write(Buffer2.alloc(0),\"\",callback)},Zlib.prototype.close=function(callback){_close(this,callback),process.nextTick(emitCloseNT,this)};function _close(engine,callback){if(callback)process.nextTick(callback);if(!engine._handle)return;engine._handle.close(),engine._handle=null}function emitCloseNT(self){self.emit(\"close\")}Zlib.prototype._transform=function(chunk,encoding,cb){var flushFlag,ws=this._writableState,ending=ws.ending||ws.ended,last=ending&&(!chunk||ws.length===chunk.length);if(chunk!==null&&!Buffer2.isBuffer(chunk))return cb(new Error(\"invalid input\"));if(!this._handle)return cb(new Error(\"zlib binding closed\"));if(last)flushFlag=this._finishFlushFlag;else if(flushFlag=this._flushFlag,chunk.length>=ws.length)this._flushFlag=this._opts.flush||binding.Z_NO_FLUSH;this._processChunk(chunk,flushFlag,cb)},Zlib.prototype._processChunk=function(chunk,flushFlag,cb){var availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,inOff=0,self=this,async=typeof cb===\"function\";if(!async){var buffers=[],nread=0,error;this.on(\"error\",function(er){error=er}),assert(this._handle,\"zlib binding closed\");do var res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);while(!this._hadError&&callback(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)_close(this),@throwRangeError(kRangeErrorMessage);var buf=Buffer2.concat(buffers,nread);return _close(this),buf}assert(this._handle,\"zlib binding closed\");var req=this._handle.write(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore);req.buffer=chunk,req.callback=callback;function callback(availInAfter,availOutAfter){if(this)this.buffer=null,this.callback=null;if(self._hadError)return;var have=availOutBefore-availOutAfter;if(assert(have>=0,\"have should not go down\"),have>0){var out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,async)self.push(out);else buffers.push(out),nread+=out.length}if(availOutAfter===0||self._offset>=self._chunkSize)availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer2.allocUnsafe(self._chunkSize);if(availOutAfter===0){if(inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!async)return!0;var newReq=self._handle.write(flushFlag,chunk,inOff,availInBefore,self._buffer,self._offset,self._chunkSize);newReq.callback=callback,newReq.buffer=chunk;return}if(!async)return!1;cb()}},util.inherits(Deflate,Zlib),util.inherits(Inflate,Zlib),util.inherits(Gzip,Zlib),util.inherits(Gunzip,Zlib),util.inherits(DeflateRaw,Zlib),util.inherits(InflateRaw,Zlib),util.inherits(Unzip,Zlib)}});return require_lib()})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDepdCode = "(function (){\"use strict\";var $=function depd(namespace){if(!namespace)@throwTypeError(\"argument namespace is required\");function deprecate(message){}return deprecate._file=void 0,deprecate._ignored=!0,deprecate._namespace=namespace,deprecate._traced=!1,deprecate._warned=Object.create(null),deprecate.function=wrapfunction,deprecate.property=wrapproperty,deprecate};function wrapfunction(fn,message){if(typeof fn!==\"function\")@throwTypeError(\"argument fn must be a function\");return fn}function wrapproperty(obj,prop,message){if(!obj||typeof obj!==\"object\"&&typeof obj!==\"function\")@throwTypeError(\"argument obj must be object\");var descriptor=Object.getOwnPropertyDescriptor(obj,prop);if(!descriptor)@throwTypeError(\"must call property on owner object\");if(!descriptor.configurable)@throwTypeError(\"property must be configurable\")}return $})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDetectLibcCode = "(function (){\"use strict\";function family(){return Promise.resolve(familySync())}function familySync(){return null}const GLIBC=\"glibc\",MUSL=\"musl\";function versionAsync(){return Promise.resolve(version())}function version(){return null}function isNonGlibcLinuxSync(){return!1}function isNonGlibcLinux(){return Promise.resolve(isNonGlibcLinuxSync())}return{GLIBC,MUSL,family,familySync,isNonGlibcLinux,isNonGlibcLinuxSync,version,versionAsync}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyDetectLibcLinuxCode = "(function (){\"use strict\";function family(){return Promise.resolve(familySync())}function familySync(){return GLIBC}const GLIBC=\"glibc\",MUSL=\"musl\";function versionAsync(){return Promise.resolve(version())}function version(){return\"2.29\"}function isNonGlibcLinuxSync(){return!1}function isNonGlibcLinux(){return Promise.resolve(isNonGlibcLinuxSync())}return{GLIBC,MUSL,family,familySync,isNonGlibcLinux,isNonGlibcLinuxSync,version,versionAsync}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyIsomorphicFetchCode = "(function (){\"use strict\";const bunFetch=Bun.fetch,fetch=(...args)=>bunFetch(...args);return fetch.default=fetch,fetch.fetch=fetch,fetch})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyNodeFetchCode = "(function (){\"use strict\";const{Headers,Request,Response,Blob,File=Blob,FormData}=globalThis,realFetch=Bun.fetch;function fetch(...args){return realFetch(...args)}class AbortError extends DOMException{constructor(message){super(message,\"AbortError\")}}class FetchBaseError extends Error{constructor(message,type){super(message);this.type=type}}class FetchError extends FetchBaseError{constructor(message,type,systemError){super(message,type);this.code=systemError\?.code}}function blobFrom(path,options){return Promise.resolve(Bun.file(data))}function blobFromSync(path,options){return Bun.file(data)}var fileFrom=blobFrom,fileFromSync=blobFromSync;function isRedirect(code){return code===301||code===302||code===303||code===307||code===308}return Object.assign(fetch,{AbortError,Blob,FetchBaseError,FetchError,File,FormData,Headers,Request,Response,blobFrom,blobFromSync,fileFrom,fileFromSync,isRedirect,fetch,default:fetch})})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyUndiciCode = "(function (){\"use strict\";const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),StreamModule=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),{Readable}=StreamModule,{_ReadableFromWebForUndici:ReadableFromWeb}=StreamModule[Symbol.for(\"::bunternal::\")],ObjectCreate=Object.create,kEmptyObject=ObjectCreate(null);var fetch=Bun.fetch,Response=globalThis.Response,Headers=globalThis.Headers,Request=globalThis.Request,URLSearchParams=globalThis.URLSearchParams,URL=globalThis.URL;class File extends Blob{constructor(){super(...arguments)}}class FileReader extends EventTarget{constructor(){throw new Error(\"Not implemented yet!\")}}var FormData=globalThis.FormData;function notImplemented(){throw new Error(\"Not implemented in bun\")}class BodyReadable extends ReadableFromWeb{#response;#bodyUsed;constructor(response,options={}){var{body}=response;if(!body)throw new Error(\"Response body is null\");super(options,body);this.#response=response,this.#bodyUsed=response.bodyUsed}get bodyUsed(){return this.#bodyUsed}#consume(){if(this.#bodyUsed)@throwTypeError(\"unusable\");this.#bodyUsed=!0}async arrayBuffer(){return this.#consume(),await this.#response.arrayBuffer()}async blob(){return this.#consume(),await this.#response.blob()}async formData(){return this.#consume(),await this.#response.formData()}async json(){return this.#consume(),await this.#response.json()}async text(){return this.#consume(),await this.#response.text()}}async function request(url,options={method:\"GET\",signal:null,headers:null,query:null,reset:!1,throwOnError:!1,body:null}){let{method=\"GET\",headers:inputHeaders,query,signal,reset=!1,throwOnError=!1,body:inputBody,maxRedirections}=options;if(typeof url===\"string\"){if(query)url=new URL(url)}else if(typeof url===\"object\"&&url!==null){if(!(url instanceof URL))throw new Error(\"not implemented\")}else @throwTypeError(\"url must be a string, URL, or UrlObject\");if(typeof url===\"string\"&&query)url=new URL(url);if(typeof url===\"object\"&&url!==null&&query){if(query)url.search=new URLSearchParams(query).toString()}if(method=method&&typeof method===\"string\"\?method.toUpperCase():null,inputBody&&(method===\"GET\"||method===\"HEAD\"))throw new Error(\"Body not allowed for GET or HEAD requests\");if(inputBody&&inputBody.read&&inputBody instanceof Readable){let data=\"\";inputBody.setEncoding(\"utf8\");for await(let chunk of stream)data+=chunk;inputBody=(new TextEncoder()).encode(data)}if(maxRedirections!==void 0&&Number.isNaN(maxRedirections))throw new Error(\"maxRedirections must be a number if defined\");if(signal&&!(signal instanceof AbortSignal))throw new Error(\"signal must be an instance of AbortSignal\");let resp;const{status:statusCode,headers,trailers}=resp=await fetch(url,{signal,mode:\"cors\",method,headers:inputHeaders||kEmptyObject,body:inputBody,redirect:maxRedirections===\"undefined\"||maxRedirections>0\?\"follow\":\"manual\",keepalive:!reset});if(throwOnError&&statusCode>=400&&statusCode<600)throw new Error(`Request failed with status code ${statusCode}`);const body=resp.body\?new BodyReadable(resp):null;return{statusCode,headers:headers.toJSON(),body,trailers,opaque:kEmptyObject,context:kEmptyObject}}function stream(){throw new Error(\"Not implemented in bun\")}function pipeline(){throw new Error(\"Not implemented in bun\")}function connect(){throw new Error(\"Not implemented in bun\")}function upgrade(){throw new Error(\"Not implemented in bun\")}class MockClient{constructor(){throw new Error(\"Not implemented in bun\")}}class MockPool{constructor(){throw new Error(\"Not implemented in bun\")}}class MockAgent{constructor(){throw new Error(\"Not implemented in bun\")}}function mockErrors(){throw new Error(\"Not implemented in bun\")}function Undici(){throw new Error(\"Not implemented in bun\")}class Dispatcher extends EventEmitter{constructor(){super(...arguments)}}class Agent extends Dispatcher{constructor(){super(...arguments)}}class Pool extends Dispatcher{constructor(){super(...arguments)}request(){throw new Error(\"Not implemented in bun\")}}class BalancedPool extends Dispatcher{constructor(){super(...arguments)}}class Client extends Dispatcher{constructor(){super(...arguments)}request(){throw new Error(\"Not implemented in bun\")}}return Undici.Dispatcher=Dispatcher,Undici.Pool=Pool,Undici.BalancedPool=BalancedPool,Undici.Client=Client,Undici.Agent=Agent,Undici.buildConnector=Undici.errors=Undici.setGlobalDispatcher=Undici.getGlobalDispatcher=Undici.request=Undici.stream=Undici.pipeline=Undici.connect=Undici.upgrade=Undici.MockClient=Undici.MockPool=Undici.MockAgent=Undici.mockErrors=notImplemented,Undici.fetch=fetch,{fetch,Response,Headers,Request,URLSearchParams,URL,File,FileReader,FormData,request,stream,pipeline,connect,upgrade,MockClient,MockPool,MockAgent,mockErrors,Dispatcher,Pool,BalancedPool,Client,Agent,Undici}})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyVercelFetchCode = "(function (){\"use strict\";var $=(wrapper=Bun.fetch)=>{async function vercelFetch(url,opts={}){if(opts.body&&typeof opts.body===\"object\"&&(!(\"buffer\"in opts.body)||typeof opts.body.buffer!==\"object\"||!(opts.body.buffer instanceof ArrayBuffer))){if(opts.body=JSON.stringify(opts.body),!opts.headers)opts.headers=new Headers;opts.headers.set(\"Content-Type\",\"application/json\")}try{return await wrapper(url,opts)}catch(err){if(typeof err===\"string\")err=new Error(err);throw err.url=url,err.opts=opts,err}}return vercelFetch.default=vercelFetch,vercelFetch};return $})\n"_s; +// + +// +static constexpr ASCIILiteral ThirdpartyWSCode = "(function (){\"use strict\";const EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),http=@getInternalField(@internalModuleRegistry,18)||@createInternalModuleById(18),kBunInternals=Symbol.for(\"::bunternal::\"),readyStates=[\"CONNECTING\",\"OPEN\",\"CLOSING\",\"CLOSED\"],encoder=new TextEncoder,eventIds={open:1,close:2,message:3,error:4,ping:5,pong:6},emittedWarnings=new Set;function emitWarning(type,message){if(emittedWarnings.has(type))return;emittedWarnings.add(type),console.warn(\"[bun] Warning:\",message)}class BunWebSocket extends EventEmitter{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;#ws;#paused=!1;#fragments=!1;#binaryType=\"nodebuffer\";#eventId=0;constructor(url,protocols,options){super();let ws=this.#ws=new WebSocket(url,protocols);ws.binaryType=\"nodebuffer\"}on(event,listener){if(event===\"unexpected-response\"||event===\"upgrade\"||event===\"redirect\")emitWarning(event,\"ws.WebSocket '\"+event+\"' event is not implemented in bun\");const mask=1<{this.emit(\"open\")});else if(event===\"close\")this.#ws.addEventListener(\"close\",({code,reason,wasClean})=>{this.emit(\"close\",code,reason,wasClean)});else if(event===\"message\")this.#ws.addEventListener(\"message\",({data})=>{const isBinary=typeof data!==\"string\";if(isBinary)this.emit(\"message\",this.#fragments\?[data]:data,isBinary);else{let encoded=encoder.encode(data);if(this.#binaryType!==\"arraybuffer\")encoded=Buffer.from(encoded.buffer,encoded.byteOffset,encoded.byteLength);this.emit(\"message\",this.#fragments\?[encoded]:encoded,isBinary)}});else if(event===\"error\")this.#ws.addEventListener(\"error\",(err)=>{this.emit(\"error\",err)});else if(event===\"ping\")this.#ws.addEventListener(\"ping\",({data})=>{this.emit(\"ping\",data)});else if(event===\"pong\")this.#ws.addEventListener(\"pong\",({data})=>{this.emit(\"pong\",data)})}return super.on(event,listener)}send(data,opts,cb){try{this.#ws.send(data,opts\?.compress)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}close(code,reason){this.#ws.close(code,reason)}terminate(){this.#ws.terminate()}get url(){return this.#ws.url}get readyState(){return this.#ws.readyState}get binaryType(){return this.#binaryType}set binaryType(value){if(value===\"nodebuffer\"||value===\"arraybuffer\")this.#ws.binaryType=this.#binaryType=value,this.#fragments=!1;else if(value===\"fragments\")this.#ws.binaryType=\"nodebuffer\",this.#binaryType=\"fragments\",this.#fragments=!0;else throw new Error(`Invalid binaryType: ${value}`)}get protocol(){return this.#ws.protocol}get extensions(){return this.#ws.extensions}addEventListener(type,listener,options){this.#ws.addEventListener(type,listener,options)}removeEventListener(type,listener){this.#ws.removeEventListener(type,listener)}get onopen(){return this.#ws.onopen}set onopen(value){this.#ws.onopen=value}get onerror(){return this.#ws.onerror}set onerror(value){this.#ws.onerror=value}get onclose(){return this.#ws.onclose}set onclose(value){this.#ws.onclose=value}get onmessage(){return this.#ws.onmessage}set onmessage(value){this.#ws.onmessage=value}get bufferedAmount(){return this.#ws.bufferedAmount}get isPaused(){return this.#paused}ping(data,mask,cb){if(typeof data===\"function\")cb=data,data=mask=void 0;else if(typeof mask===\"function\")cb=mask,mask=void 0;if(typeof data===\"number\")data=data.toString();try{this.#ws.ping(data)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}pong(data,mask,cb){if(typeof data===\"function\")cb=data,data=mask=void 0;else if(typeof mask===\"function\")cb=mask,mask=void 0;if(typeof data===\"number\")data=data.toString();try{this.#ws.pong(data)}catch(error){typeof cb===\"function\"&&cb(error);return}typeof cb===\"function\"&&cb()}pause(){switch(this.readyState){case WebSocket.CONNECTING:case WebSocket.CLOSED:return}this.#paused=!0,emitWarning(\"pause()\",\"ws.WebSocket.pause() is not implemented in bun\")}resume(){switch(this.readyState){case WebSocket.CONNECTING:case WebSocket.CLOSED:return}this.#paused=!1,emitWarning(\"resume()\",\"ws.WebSocket.resume() is not implemented in bun\")}}Object.defineProperty(BunWebSocket,\"name\",{value:\"WebSocket\"});const wsKeyRegex=/^[+/0-9A-Za-z]{22}==$/,wsTokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,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,0,0,0,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,0,1,0,1,0];function subprotocolParse(header){const protocols=new Set;let start=-1,end=-1,i=0;for(i;i{const body=http.STATUS_CODES[426];res.writeHead(426,{\"Content-Length\":body.length,\"Content-Type\":\"text/plain\"}),res.end(body)}),this._server.listen(options.port,options.host,options.backlog,callback);else if(options.server)this._server=options.server;if(this._server){const emitConnection=this.emit.bind(this,\"connection\"),emitListening=this.emit.bind(this,\"listening\"),emitError=this.emit.bind(this,\"error\"),doUpgrade=(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)};this._server.on(\"listening\",emitListening),this._server.on(\"error\",emitError),this._server.on(\"upgrade\",doUpgrade),this._removeListeners=()=>{this._server.removeListener(\"upgrade\",doUpgrade),this._server.removeListener(\"listening\",emitListening),this._server.removeListener(\"error\",emitError)}}if(options.perMessageDeflate===!0)options.perMessageDeflate={};if(options.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=options,this._state=RUNNING}address(){if(this.options.noServer)throw new Error('The server is operating in \"noServer\" mode');if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb)this.once(\"close\",()=>{cb(new Error(\"The server is not running\"))});process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this);return}if(cb)this.once(\"close\",cb);if(this._state===CLOSING)return;if(this._state=CLOSING,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this);else this._shouldEmitClose=!0;else process.nextTick((server)=>{server._state=CLOSED,server.emit(\"close\")},this)}else{const server=this._server;this._removeListeners(),this._removeListeners=this._server=null,server.close(()=>{this._state=CLOSED,this.emit(\"close\")})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf(\"\?\");if((index!==-1\?req.url.slice(0,index):req.url)!==this.options.path)return!1}return!0}completeUpgrade(extensions,key,protocols,request,socket,head,cb){const[server,response,req]=socket[kBunInternals];if(this._state>RUNNING)return abortHandshake(response,503);let protocol=\"\";if(protocols.size)protocol=this.options.handleProtocols\?this.options.handleProtocols(protocols,request):protocols.values().next().value;const ws=new BunWebSocketMocked(request.url,protocol,extensions,\"nodebuffer\"),headers=[\"HTTP/1.1 101 Switching Protocols\",\"Upgrade: websocket\",\"Connection: Upgrade\"];if(this.emit(\"headers\",headers,request),server.upgrade(req,{data:ws[kBunInternals]})){if(response._reply(void 0),this.clients)this.clients.add(ws),ws.on(\"close\",()=>{if(this.clients.delete(ws),this._shouldEmitClose&&!this.clients.size)process.nextTick(wsEmitClose,this)});cb(ws,request)}else abortHandshake(response,500)}handleUpgrade(req,socket,head,cb){const[_,response]=socket[kBunInternals],key=req.headers[\"sec-websocket-key\"],version=+req.headers[\"sec-websocket-version\"];if(req.method!==\"GET\"){abortHandshakeOrEmitwsClientError(this,req,response,socket,405,\"Invalid HTTP method\");return}if(req.headers.upgrade.toLowerCase()!==\"websocket\"){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Invalid Upgrade header\");return}if(!key||!wsKeyRegex.test(key)){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Missing or invalid Sec-WebSocket-Key header\");return}if(version!==8&&version!==13){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Missing or invalid Sec-WebSocket-Version header\");return}if(!this.shouldHandle(req)){abortHandshake(response,400);return}const secWebSocketProtocol=req.headers[\"sec-websocket-protocol\"];let protocols=new Set;if(secWebSocketProtocol!==void 0)try{protocols=subprotocolParse(secWebSocketProtocol)}catch(err){abortHandshakeOrEmitwsClientError(this,req,response,socket,400,\"Invalid Sec-WebSocket-Protocol header\");return}const extensions={};if(this.options.verifyClient){const info={origin:req.headers[`${version===8\?\"sec-websocket-origin\":\"origin\"}`],secure:!!(req.socket.authorized||req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified)return abortHandshake(response,code||401,message,headers);this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(response,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}}Object.defineProperty(BunWebSocket,\"CONNECTING\",{enumerable:!0,value:readyStates.indexOf(\"CONNECTING\")}),Object.defineProperty(BunWebSocket.prototype,\"CONNECTING\",{enumerable:!0,value:readyStates.indexOf(\"CONNECTING\")}),Object.defineProperty(BunWebSocket,\"OPEN\",{enumerable:!0,value:readyStates.indexOf(\"OPEN\")}),Object.defineProperty(BunWebSocket.prototype,\"OPEN\",{enumerable:!0,value:readyStates.indexOf(\"OPEN\")}),Object.defineProperty(BunWebSocket,\"CLOSING\",{enumerable:!0,value:readyStates.indexOf(\"CLOSING\")}),Object.defineProperty(BunWebSocket.prototype,\"CLOSING\",{enumerable:!0,value:readyStates.indexOf(\"CLOSING\")}),Object.defineProperty(BunWebSocket,\"CLOSED\",{enumerable:!0,value:readyStates.indexOf(\"CLOSED\")}),Object.defineProperty(BunWebSocket.prototype,\"CLOSED\",{enumerable:!0,value:readyStates.indexOf(\"CLOSED\")});class Sender{constructor(){throw new Error(\"Not supported yet in Bun\")}}class Receiver{constructor(){throw new Error(\"Not supported yet in Bun\")}}var createWebSocketStream=(ws)=>{throw new Error(\"Not supported yet in Bun\")};return Object.assign(BunWebSocket,{createWebSocketStream,Receiver,Sender,WebSocket:BunWebSocket,Server:WebSocketServer,WebSocketServer})})\n"_s; +// + + #endif + + } + } \ No newline at end of file diff --git a/src/js/out/NativeModuleImpl.h b/src/js/out/NativeModuleImpl.h new file mode 100644 index 00000000000000..5a6881b7f845d8 --- /dev/null +++ b/src/js/out/NativeModuleImpl.h @@ -0,0 +1,10 @@ +#include "../../bun.js/modules/BunObjectModule.h" +#include "../../bun.js/modules/BunJSCModule.h" +#include "../../bun.js/modules/NodeBufferModule.h" +#include "../../bun.js/modules/NodeConstantsModule.h" +#include "../../bun.js/modules/NodeModuleModule.h" +#include "../../bun.js/modules/NodeProcessModule.h" +#include "../../bun.js/modules/NodeStringDecoderModule.h" +#include "../../bun.js/modules/NodeTTYModule.h" +#include "../../bun.js/modules/NodeUtilTypesModule.h" +#include "../../bun.js/modules/UTF8ValidateModule.h" diff --git a/src/js/out/ResolvedSourceTag.zig b/src/js/out/ResolvedSourceTag.zig new file mode 100644 index 00000000000000..43dc24689a4a67 --- /dev/null +++ b/src/js/out/ResolvedSourceTag.zig @@ -0,0 +1,79 @@ +pub const ResolvedSourceTag = enum(u32) { + // Predefined + javascript = 0, + package_json_type_module = 1, + wasm = 2, + object = 3, + file = 4, + esm = 5, + + // Built in modules are loaded through InternalModuleRegistry by numerical ID. + // In this enum are represented as `(1 << 9) & id` + @"bun:ffi" = 512, + @"bun:sqlite" = 513, + @"internal:shared" = 514, + @"node:assert" = 515, + @"node:assert/strict" = 516, + @"node:async_hooks" = 517, + @"node:child_process" = 518, + @"node:cluster" = 519, + @"node:console" = 520, + @"node:crypto" = 521, + @"node:dgram" = 522, + @"node:diagnostics_channel" = 523, + @"node:dns" = 524, + @"node:dns/promises" = 525, + @"node:domain" = 526, + @"node:events" = 527, + @"node:fs" = 528, + @"node:fs/promises" = 529, + @"node:http" = 530, + @"node:http2" = 531, + @"node:https" = 532, + @"node:inspector" = 533, + @"node:net" = 534, + @"node:os" = 535, + @"node:path/posix" = 536, + @"node:path" = 537, + @"node:path/win32" = 538, + @"node:perf_hooks" = 539, + @"node:punycode" = 540, + @"node:querystring" = 541, + @"node:readline" = 542, + @"node:readline/promises" = 543, + @"node:repl" = 544, + @"node:stream/consumers" = 545, + @"node:stream" = 546, + @"node:stream/promises" = 547, + @"node:stream/web" = 548, + @"node:timers" = 549, + @"node:timers/promises" = 550, + @"node:tls" = 551, + @"node:trace_events" = 552, + @"node:url" = 553, + @"node:util" = 554, + @"node:v8" = 555, + @"node:vm" = 556, + @"node:wasi" = 557, + @"node:worker_threads" = 558, + @"node:zlib" = 559, + @"depd" = 560, + @"detect-libc" = 561, + @"detect-libc/linux" = 562, + @"isomorphic-fetch" = 563, + @"node-fetch" = 564, + @"undici" = 565, + @"vercel_fetch" = 566, + @"ws" = 567, + // Native modules run through a different system using ESM registry. + @"bun" = 1024, + @"bun:jsc" = 1025, + @"node:buffer" = 1026, + @"node:constants" = 1027, + @"node:module" = 1028, + @"node:process" = 1029, + @"node:string_decoder" = 1030, + @"node:tty" = 1031, + @"node:util/types" = 1032, + @"utf-8-validate" = 1033, +}; diff --git a/src/js/out/SyntheticModuleType.h b/src/js/out/SyntheticModuleType.h new file mode 100644 index 00000000000000..26704a71d140e4 --- /dev/null +++ b/src/js/out/SyntheticModuleType.h @@ -0,0 +1,83 @@ +enum SyntheticModuleType : uint32_t { + JavaScript = 0, + PackageJSONTypeModule = 1, + Wasm = 2, + ObjectModule = 3, + File = 4, + ESM = 5, + + // Built in modules are loaded through InternalModuleRegistry by numerical ID. + // In this enum are represented as `(1 << 9) & id` + InternalModuleRegistryFlag = 1 << 9, + BunFFI = 512, + BunSqlite = 513, + InternalShared = 514, + NodeAssert = 515, + NodeAssertStrict = 516, + NodeAsyncHooks = 517, + NodeChildProcess = 518, + NodeCluster = 519, + NodeConsole = 520, + NodeCrypto = 521, + NodeDgram = 522, + NodeDiagnosticsChannel = 523, + NodeDNS = 524, + NodeDNSPromises = 525, + NodeDomain = 526, + NodeEvents = 527, + NodeFS = 528, + NodeFSPromises = 529, + NodeHttp = 530, + NodeHttp2 = 531, + NodeHttps = 532, + NodeInspector = 533, + NodeNet = 534, + NodeOS = 535, + NodePathPosix = 536, + NodePath = 537, + NodePathWin32 = 538, + NodePerfHooks = 539, + NodePunycode = 540, + NodeQuerystring = 541, + NodeReadline = 542, + NodeReadlinePromises = 543, + NodeRepl = 544, + NodeStreamConsumers = 545, + NodeStream = 546, + NodeStreamPromises = 547, + NodeStreamWeb = 548, + NodeTimers = 549, + NodeTimersPromises = 550, + NodeTLS = 551, + NodeTraceEvents = 552, + NodeUrl = 553, + NodeUtil = 554, + NodeV8 = 555, + NodeVM = 556, + NodeWasi = 557, + NodeWorkerThreads = 558, + NodeZlib = 559, + ThirdpartyDepd = 560, + ThirdpartyDetectLibc = 561, + ThirdpartyDetectLibcLinux = 562, + ThirdpartyIsomorphicFetch = 563, + ThirdpartyNodeFetch = 564, + ThirdpartyUndici = 565, + ThirdpartyVercelFetch = 566, + ThirdpartyWS = 567, + + // Native modules run through the same system, but with different underlying initializers. + // They also have bit 10 set to differentiate them from JS builtins. + NativeModuleFlag = (1 << 10) | (1 << 9), + BunObject = 1024, + BunJSC = 1025, + NodeBuffer = 1026, + NodeConstants = 1027, + NodeModule = 1028, + NodeProcess = 1029, + NodeStringDecoder = 1030, + NodeTTY = 1031, + NodeUtilTypes = 1032, + UTF8Validate = 1033, +}; + diff --git a/src/js/out/WebCoreJSBuiltins.cpp b/src/js/out/WebCoreJSBuiltins.cpp index 9ae90e82a6eb35..f3568455b6a82f 100644 --- a/src/js/out/WebCoreJSBuiltins.cpp +++ b/src/js/out/WebCoreJSBuiltins.cpp @@ -14,25 +14,25 @@ namespace WebCore { const JSC::ConstructAbility s_bundlerPluginRunSetupFunctionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_bundlerPluginRunSetupFunctionCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_bundlerPluginRunSetupFunctionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_bundlerPluginRunSetupFunctionCodeLength = 2165; +const int s_bundlerPluginRunSetupFunctionCodeLength = 3224; static const JSC::Intrinsic s_bundlerPluginRunSetupFunctionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_bundlerPluginRunSetupFunctionCode = "(function (J,_){\"use strict\";var D=new Map,F=new Map;function H(q,h,E){if(!q||!@isObject(q))@throwTypeError('Expected an object with \"filter\" RegExp');if(!h||!@isCallable(h))@throwTypeError(\"callback must be a function\");var{filter:w,namespace:z=\"file\"}=q;if(!w)@throwTypeError('Expected an object with \"filter\" RegExp');if(!@isRegExpObject(w))@throwTypeError(\"filter must be a RegExp\");if(z&&typeof z!==\"string\")@throwTypeError(\"namespace must be a string\");if((z\?.length\?\?0)===0)z=\"file\";if(!/^([/@a-zA-Z0-9_\\\\-]+)$/.test(z))@throwTypeError(\"namespace can only contain $a-zA-Z0-9_\\\\-\");var A=E.@get(z);if(!A)E.@set(z,[[w,h]]);else @arrayPush(A,[w,h])}function K(q,h){H(q,h,D)}function M(q,h){H(q,h,F)}const I=()=>{var q=!1,h=!1;for(var[E,w]of D.entries())for(var[z]of w)this.addFilter(z,E,1),q=!0;for(var[E,w]of F.entries())for(var[z]of w)this.addFilter(z,E,0),h=!0;if(h){var A=this.onResolve;if(!A)this.onResolve=F;else for(var[E,w]of F.entries()){var C=A.@get(E);if(!C)A.@set(E,w);else A.@set(E,C.concat(w))}}if(q){var G=this.onLoad;if(!G)this.onLoad=D;else for(var[E,w]of D.entries()){var C=G.@get(E);if(!C)G.@set(E,w);else G.@set(E,C.concat(w))}}return q||h};var B=J({config:_,onDispose:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),onEnd:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),onLoad:K,onResolve:M,onStart:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),resolve:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),initialOptions:{..._,bundle:!0,entryPoints:_.entrypoints\?\?_.entryPoints\?\?[],minify:typeof _.minify===\"boolean\"\?_.minify:!1,minifyIdentifiers:_.minify===!0||_.minify\?.identifiers,minifyWhitespace:_.minify===!0||_.minify\?.whitespace,minifySyntax:_.minify===!0||_.minify\?.syntax,outbase:_.root,platform:_.target===\"bun\"\?\"node\":_.target},esbuild:{}});if(B&&@isPromise(B))if(@getPromiseInternalField(B,@promiseFieldFlags)&@promiseStateFulfilled)B=@getPromiseInternalField(B,@promiseFieldReactionsOrResult);else return B.@then(I);return I()})\n"; +const char* const s_bundlerPluginRunSetupFunctionCode = "(function (setup,config){\"use strict\";var onLoadPlugins=new Map,onResolvePlugins=new Map;function validate(filterObject,callback,map){if(!filterObject||!@isObject(filterObject))@throwTypeError('Expected an object with \"filter\" RegExp');if(!callback||!@isCallable(callback))@throwTypeError(\"callback must be a function\");var{filter,namespace=\"file\"}=filterObject;if(!filter)@throwTypeError('Expected an object with \"filter\" RegExp');if(!@isRegExpObject(filter))@throwTypeError(\"filter must be a RegExp\");if(namespace&&typeof namespace!==\"string\")@throwTypeError(\"namespace must be a string\");if((namespace\?.length\?\?0)===0)namespace=\"file\";if(!/^([/@a-zA-Z0-9_\\\\-]+)$/.test(namespace))@throwTypeError(\"namespace can only contain $a-zA-Z0-9_\\\\-\");var callbacks=map.@get(namespace);if(!callbacks)map.@set(namespace,[[filter,callback]]);else @arrayPush(callbacks,[filter,callback])}function onLoad(filterObject,callback){validate(filterObject,callback,onLoadPlugins)}function onResolve(filterObject,callback){validate(filterObject,callback,onResolvePlugins)}const processSetupResult=()=>{var anyOnLoad=!1,anyOnResolve=!1;for(var[namespace,callbacks]of onLoadPlugins.entries())for(var[filter]of callbacks)this.addFilter(filter,namespace,1),anyOnLoad=!0;for(var[namespace,callbacks]of onResolvePlugins.entries())for(var[filter]of callbacks)this.addFilter(filter,namespace,0),anyOnResolve=!0;if(anyOnResolve){var onResolveObject=this.onResolve;if(!onResolveObject)this.onResolve=onResolvePlugins;else for(var[namespace,callbacks]of onResolvePlugins.entries()){var existing=onResolveObject.@get(namespace);if(!existing)onResolveObject.@set(namespace,callbacks);else onResolveObject.@set(namespace,existing.concat(callbacks))}}if(anyOnLoad){var onLoadObject=this.onLoad;if(!onLoadObject)this.onLoad=onLoadPlugins;else for(var[namespace,callbacks]of onLoadPlugins.entries()){var existing=onLoadObject.@get(namespace);if(!existing)onLoadObject.@set(namespace,callbacks);else onLoadObject.@set(namespace,existing.concat(callbacks))}}return anyOnLoad||anyOnResolve};var setupResult=setup({config,onDispose:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),onEnd:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),onLoad,onResolve,onStart:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),resolve:()=>@throwTypeError(\"@{@2} is not implemented yet. See https://github.com/oven-sh/bun/issues/@1\"),initialOptions:{...config,bundle:!0,entryPoints:config.entrypoints\?\?config.entryPoints\?\?[],minify:typeof config.minify===\"boolean\"\?config.minify:!1,minifyIdentifiers:config.minify===!0||config.minify\?.identifiers,minifyWhitespace:config.minify===!0||config.minify\?.whitespace,minifySyntax:config.minify===!0||config.minify\?.syntax,outbase:config.root,platform:config.target===\"bun\"\?\"node\":config.target},esbuild:{}});if(setupResult&&@isPromise(setupResult))if(@getPromiseInternalField(setupResult,@promiseFieldFlags)&@promiseStateFulfilled)setupResult=@getPromiseInternalField(setupResult,@promiseFieldReactionsOrResult);else return setupResult.@then(processSetupResult);return processSetupResult()})\n"; // runOnResolvePlugins const JSC::ConstructAbility s_bundlerPluginRunOnResolvePluginsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_bundlerPluginRunOnResolvePluginsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_bundlerPluginRunOnResolvePluginsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_bundlerPluginRunOnResolvePluginsCodeLength = 1711; +const int s_bundlerPluginRunOnResolvePluginsCodeLength = 2359; static const JSC::Intrinsic s_bundlerPluginRunOnResolvePluginsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_bundlerPluginRunOnResolvePluginsCode = "(function (C,E,F,b,G){\"use strict\";const H=[\"entry-point\",\"import-statement\",\"require-call\",\"dynamic-import\",\"require-resolve\",\"import-rule\",\"url-token\",\"internal\"][G];var g=(async(j,q,J,K)=>{var{onResolve:M,onLoad:A}=this,B=M.@get(q);if(!B)return this.onResolveAsync(b,null,null,null),null;for(let[O,Q]of B)if(O.test(j)){var _=Q({path:j,importer:J,namespace:q,kind:K});while(_&&@isPromise(_)&&(@getPromiseInternalField(_,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)_=@getPromiseInternalField(_,@promiseFieldReactionsOrResult);if(_&&@isPromise(_))_=await _;if(!_||!@isObject(_))continue;var{path:y,namespace:w=q,external:z}=_;if(typeof y!==\"string\"||typeof w!==\"string\")@throwTypeError(\"onResolve plugins must return an object with a string 'path' and string 'loader' field\");if(!y)continue;if(!w)w=q;if(typeof z!==\"boolean\"&&!@isUndefinedOrNull(z))@throwTypeError('onResolve plugins \"external\" field must be boolean or unspecified');if(!z){if(w===\"file\"){if(darwin!==\"win32\"){if(y[0]!==\"/\"||y.includes(\"..\"))@throwTypeError('onResolve plugin \"path\" must be absolute when the namespace is \"file\"')}}if(w===\"dataurl\"){if(!y.startsWith(\"data:\"))@throwTypeError('onResolve plugin \"path\" must start with \"data:\" when the namespace is \"dataurl\"')}if(w&&w!==\"file\"&&(!A||!A.@has(w)))@throwTypeError(`Expected onLoad plugin for namespace ${w} to exist`)}return this.onResolveAsync(b,y,w,z),null}return this.onResolveAsync(b,null,null,null),null})(C,E,F,H);while(g&&@isPromise(g)&&(@getPromiseInternalField(g,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)g=@getPromiseInternalField(g,@promiseFieldReactionsOrResult);if(g&&@isPromise(g))g.then(()=>{},(j)=>{this.addError(b,j,0)})})\n"; +const char* const s_bundlerPluginRunOnResolvePluginsCode = "(function (specifier,inputNamespace,importer,internalID,kindId){\"use strict\";const kind=[\"entry-point\",\"import-statement\",\"require-call\",\"dynamic-import\",\"require-resolve\",\"import-rule\",\"url-token\",\"internal\"][kindId];var promiseResult=(async(inputPath,inputNamespace2,importer2,kind2)=>{var{onResolve,onLoad}=this,results=onResolve.@get(inputNamespace2);if(!results)return this.onResolveAsync(internalID,null,null,null),null;for(let[filter,callback]of results)if(filter.test(inputPath)){var result=callback({path:inputPath,importer:importer2,namespace:inputNamespace2,kind:kind2});while(result&&@isPromise(result)&&(@getPromiseInternalField(result,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)result=@getPromiseInternalField(result,@promiseFieldReactionsOrResult);if(result&&@isPromise(result))result=await result;if(!result||!@isObject(result))continue;var{path,namespace:userNamespace=inputNamespace2,external}=result;if(typeof path!==\"string\"||typeof userNamespace!==\"string\")@throwTypeError(\"onResolve plugins must return an object with a string 'path' and string 'loader' field\");if(!path)continue;if(!userNamespace)userNamespace=inputNamespace2;if(typeof external!==\"boolean\"&&!@isUndefinedOrNull(external))@throwTypeError('onResolve plugins \"external\" field must be boolean or unspecified');if(!external){if(userNamespace===\"file\"){if(process.platform!==\"win32\"){if(path[0]!==\"/\"||path.includes(\"..\"))@throwTypeError('onResolve plugin \"path\" must be absolute when the namespace is \"file\"')}}if(userNamespace===\"dataurl\"){if(!path.startsWith(\"data:\"))@throwTypeError('onResolve plugin \"path\" must start with \"data:\" when the namespace is \"dataurl\"')}if(userNamespace&&userNamespace!==\"file\"&&(!onLoad||!onLoad.@has(userNamespace)))@throwTypeError(`Expected onLoad plugin for namespace ${userNamespace} to exist`)}return this.onResolveAsync(internalID,path,userNamespace,external),null}return this.onResolveAsync(internalID,null,null,null),null})(specifier,inputNamespace,importer,kind);while(promiseResult&&@isPromise(promiseResult)&&(@getPromiseInternalField(promiseResult,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)promiseResult=@getPromiseInternalField(promiseResult,@promiseFieldReactionsOrResult);if(promiseResult&&@isPromise(promiseResult))promiseResult.then(()=>{},(e)=>{this.addError(internalID,e,0)})})\n"; // runOnLoadPlugins const JSC::ConstructAbility s_bundlerPluginRunOnLoadPluginsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_bundlerPluginRunOnLoadPluginsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_bundlerPluginRunOnLoadPluginsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_bundlerPluginRunOnLoadPluginsCodeLength = 1325; +const int s_bundlerPluginRunOnLoadPluginsCodeLength = 1835; static const JSC::Intrinsic s_bundlerPluginRunOnLoadPluginsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_bundlerPluginRunOnLoadPluginsCode = "(function (w,F,G,H){\"use strict\";const J={jsx:0,js:1,ts:2,tsx:3,css:4,file:5,json:6,toml:7,wasm:8,napi:9,base64:10,dataurl:11,text:12},K=[\"jsx\",\"js\",\"ts\",\"tsx\",\"css\",\"file\",\"json\",\"toml\",\"wasm\",\"napi\",\"base64\",\"dataurl\",\"text\"][H];var g=(async(j,x,y,z)=>{var B=this.onLoad.@get(y);if(!B)return this.onLoadAsync(j,null,null),null;for(let[Q,T]of B)if(Q.test(x)){var b=T({path:x,namespace:y,loader:z});while(b&&@isPromise(b)&&(@getPromiseInternalField(b,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)b=@getPromiseInternalField(b,@promiseFieldReactionsOrResult);if(b&&@isPromise(b))b=await b;if(!b||!@isObject(b))continue;var{contents:q,loader:v=z}=b;if(typeof q!==\"string\"&&!@isTypedArrayView(q))@throwTypeError('onLoad plugins must return an object with \"contents\" as a string or Uint8Array');if(typeof v!==\"string\")@throwTypeError('onLoad plugins must return an object with \"loader\" as a string');const C=J[v];if(C===@undefined)@throwTypeError(`Loader ${v} is not supported.`);return this.onLoadAsync(j,q,C),null}return this.onLoadAsync(j,null,null),null})(w,F,G,K);while(g&&@isPromise(g)&&(@getPromiseInternalField(g,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)g=@getPromiseInternalField(g,@promiseFieldReactionsOrResult);if(g&&@isPromise(g))g.then(()=>{},(j)=>{this.addError(w,j,1)})})\n"; +const char* const s_bundlerPluginRunOnLoadPluginsCode = "(function (internalID,path,namespace,defaultLoaderId){\"use strict\";const LOADERS_MAP={jsx:0,js:1,ts:2,tsx:3,css:4,file:5,json:6,toml:7,wasm:8,napi:9,base64:10,dataurl:11,text:12},loaderName=[\"jsx\",\"js\",\"ts\",\"tsx\",\"css\",\"file\",\"json\",\"toml\",\"wasm\",\"napi\",\"base64\",\"dataurl\",\"text\"][defaultLoaderId];var promiseResult=(async(internalID2,path2,namespace2,defaultLoader)=>{var results=this.onLoad.@get(namespace2);if(!results)return this.onLoadAsync(internalID2,null,null),null;for(let[filter,callback]of results)if(filter.test(path2)){var result=callback({path:path2,namespace:namespace2,loader:defaultLoader});while(result&&@isPromise(result)&&(@getPromiseInternalField(result,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)result=@getPromiseInternalField(result,@promiseFieldReactionsOrResult);if(result&&@isPromise(result))result=await result;if(!result||!@isObject(result))continue;var{contents,loader=defaultLoader}=result;if(typeof contents!==\"string\"&&!@isTypedArrayView(contents))@throwTypeError('onLoad plugins must return an object with \"contents\" as a string or Uint8Array');if(typeof loader!==\"string\")@throwTypeError('onLoad plugins must return an object with \"loader\" as a string');const chosenLoader=LOADERS_MAP[loader];if(chosenLoader===@undefined)@throwTypeError(`Loader ${loader} is not supported.`);return this.onLoadAsync(internalID2,contents,chosenLoader),null}return this.onLoadAsync(internalID2,null,null),null})(internalID,path,namespace,loaderName);while(promiseResult&&@isPromise(promiseResult)&&(@getPromiseInternalField(promiseResult,@promiseFieldFlags)&@promiseStateMask)===@promiseStateFulfilled)promiseResult=@getPromiseInternalField(promiseResult,@promiseFieldReactionsOrResult);if(promiseResult&&@isPromise(promiseResult))promiseResult.then(()=>{},(e)=>{this.addError(internalID,e,1)})})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -48,25 +48,25 @@ WEBCORE_FOREACH_BUNDLERPLUGIN_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_byteLengthQueuingStrategyHighWaterMarkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_byteLengthQueuingStrategyHighWaterMarkCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_byteLengthQueuingStrategyHighWaterMarkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_byteLengthQueuingStrategyHighWaterMarkCodeLength = 210; +const int s_byteLengthQueuingStrategyHighWaterMarkCodeLength = 246; static const JSC::Intrinsic s_byteLengthQueuingStrategyHighWaterMarkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_byteLengthQueuingStrategyHighWaterMarkCode = "(function (){\"use strict\";const c=@getByIdDirectPrivate(this,\"highWaterMark\");if(c===@undefined)@throwTypeError(\"ByteLengthQueuingStrategy.highWaterMark getter called on incompatible |this| value.\");return c})\n"; +const char* const s_byteLengthQueuingStrategyHighWaterMarkCode = "(function (){\"use strict\";const highWaterMark=@getByIdDirectPrivate(this,\"highWaterMark\");if(highWaterMark===@undefined)@throwTypeError(\"ByteLengthQueuingStrategy.highWaterMark getter called on incompatible |this| value.\");return highWaterMark})\n"; // size const JSC::ConstructAbility s_byteLengthQueuingStrategySizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_byteLengthQueuingStrategySizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_byteLengthQueuingStrategySizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_byteLengthQueuingStrategySizeCodeLength = 49; +const int s_byteLengthQueuingStrategySizeCodeLength = 57; static const JSC::Intrinsic s_byteLengthQueuingStrategySizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_byteLengthQueuingStrategySizeCode = "(function (e){\"use strict\";return e.byteLength})\n"; +const char* const s_byteLengthQueuingStrategySizeCode = "(function (chunk){\"use strict\";return chunk.byteLength})\n"; // initializeByteLengthQueuingStrategy const JSC::ConstructAbility s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCodeLength = 121; +const int s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCodeLength = 139; static const JSC::Intrinsic s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCode = "(function (c){\"use strict\";@putByIdDirectPrivate(this,\"highWaterMark\",@extractHighWaterMarkFromQueuingStrategyInit(c))})\n"; +const char* const s_byteLengthQueuingStrategyInitializeByteLengthQueuingStrategyCode = "(function (parameters){\"use strict\";@putByIdDirectPrivate(this,\"highWaterMark\",@extractHighWaterMarkFromQueuingStrategyInit(parameters))})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -82,305 +82,305 @@ WEBCORE_FOREACH_BYTELENGTHQUEUINGSTRATEGY_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_writableStreamInternalsIsWritableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsIsWritableStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsIsWritableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsIsWritableStreamCodeLength = 94; +const int s_writableStreamInternalsIsWritableStreamCodeLength = 109; static const JSC::Intrinsic s_writableStreamInternalsIsWritableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsIsWritableStreamCode = "(function (i){\"use strict\";return @isObject(i)&&!!@getByIdDirectPrivate(i,\"underlyingSink\")})\n"; +const char* const s_writableStreamInternalsIsWritableStreamCode = "(function (stream){\"use strict\";return @isObject(stream)&&!!@getByIdDirectPrivate(stream,\"underlyingSink\")})\n"; // isWritableStreamDefaultWriter const JSC::ConstructAbility s_writableStreamInternalsIsWritableStreamDefaultWriterCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsIsWritableStreamDefaultWriterCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsIsWritableStreamDefaultWriterCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsIsWritableStreamDefaultWriterCodeLength = 93; +const int s_writableStreamInternalsIsWritableStreamDefaultWriterCodeLength = 108; static const JSC::Intrinsic s_writableStreamInternalsIsWritableStreamDefaultWriterCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsIsWritableStreamDefaultWriterCode = "(function (d){\"use strict\";return @isObject(d)&&!!@getByIdDirectPrivate(d,\"closedPromise\")})\n"; +const char* const s_writableStreamInternalsIsWritableStreamDefaultWriterCode = "(function (writer){\"use strict\";return @isObject(writer)&&!!@getByIdDirectPrivate(writer,\"closedPromise\")})\n"; // acquireWritableStreamDefaultWriter const JSC::ConstructAbility s_writableStreamInternalsAcquireWritableStreamDefaultWriterCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsAcquireWritableStreamDefaultWriterCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsAcquireWritableStreamDefaultWriterCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsAcquireWritableStreamDefaultWriterCodeLength = 72; +const int s_writableStreamInternalsAcquireWritableStreamDefaultWriterCodeLength = 82; static const JSC::Intrinsic s_writableStreamInternalsAcquireWritableStreamDefaultWriterCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsAcquireWritableStreamDefaultWriterCode = "(function (b){\"use strict\";return new @WritableStreamDefaultWriter(b)})\n"; +const char* const s_writableStreamInternalsAcquireWritableStreamDefaultWriterCode = "(function (stream){\"use strict\";return new @WritableStreamDefaultWriter(stream)})\n"; // createWritableStream const JSC::ConstructAbility s_writableStreamInternalsCreateWritableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsCreateWritableStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsCreateWritableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsCreateWritableStreamCodeLength = 273; +const int s_writableStreamInternalsCreateWritableStreamCodeLength = 453; static const JSC::Intrinsic s_writableStreamInternalsCreateWritableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsCreateWritableStreamCode = "(function (j,p,q,u,d,v){\"use strict\";@assert(typeof d===\"number\"&&d===d&&d>=0);const f={};@initializeWritableStreamSlots(f,{});const x=new @WritableStreamDefaultController;return @setUpWritableStreamDefaultController(f,x,j,p,q,u,d,v),@createWritableStreamFromInternal(f)})\n"; +const char* const s_writableStreamInternalsCreateWritableStreamCode = "(function (startAlgorithm,writeAlgorithm,closeAlgorithm,abortAlgorithm,highWaterMark,sizeAlgorithm){\"use strict\";const internalStream={};@initializeWritableStreamSlots(internalStream,{});const controller=new @WritableStreamDefaultController;return @setUpWritableStreamDefaultController(internalStream,controller,startAlgorithm,writeAlgorithm,closeAlgorithm,abortAlgorithm,highWaterMark,sizeAlgorithm),@createWritableStreamFromInternal(internalStream)})\n"; // createInternalWritableStreamFromUnderlyingSink const JSC::ConstructAbility s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeLength = 920; +const int s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeLength = 1388; static const JSC::Intrinsic s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCode = "(function (f,w){\"use strict\";const C={};if(f===@undefined)f={};if(w===@undefined)w={};if(!@isObject(f))@throwTypeError(\"WritableStream constructor takes an object as first argument\");if(\"type\"in f)@throwRangeError(\"Invalid type is specified\");const E=@extractSizeAlgorithm(w),_=@extractHighWaterMark(w,1),o={};if(\"start\"in f){if(o.start=f.start,typeof o.start!==\"function\")@throwTypeError(\"underlyingSink.start should be a function\")}if(\"write\"in f){if(o.write=f.write,typeof o.write!==\"function\")@throwTypeError(\"underlyingSink.write should be a function\")}if(\"close\"in f){if(o.close=f.close,typeof o.close!==\"function\")@throwTypeError(\"underlyingSink.close should be a function\")}if(\"abort\"in f){if(o.abort=f.abort,typeof o.abort!==\"function\")@throwTypeError(\"underlyingSink.abort should be a function\")}return @initializeWritableStreamSlots(C,f),@setUpWritableStreamDefaultControllerFromUnderlyingSink(C,f,o,_,E),C})\n"; +const char* const s_writableStreamInternalsCreateInternalWritableStreamFromUnderlyingSinkCode = "(function (underlyingSink,strategy){\"use strict\";const stream={};if(underlyingSink===@undefined)underlyingSink={};if(strategy===@undefined)strategy={};if(!@isObject(underlyingSink))@throwTypeError(\"WritableStream constructor takes an object as first argument\");if(\"type\"in underlyingSink)@throwRangeError(\"Invalid type is specified\");const sizeAlgorithm=@extractSizeAlgorithm(strategy),highWaterMark=@extractHighWaterMark(strategy,1),underlyingSinkDict={};if(\"start\"in underlyingSink){if(underlyingSinkDict.start=underlyingSink.start,typeof underlyingSinkDict.start!==\"function\")@throwTypeError(\"underlyingSink.start should be a function\")}if(\"write\"in underlyingSink){if(underlyingSinkDict.write=underlyingSink.write,typeof underlyingSinkDict.write!==\"function\")@throwTypeError(\"underlyingSink.write should be a function\")}if(\"close\"in underlyingSink){if(underlyingSinkDict.close=underlyingSink.close,typeof underlyingSinkDict.close!==\"function\")@throwTypeError(\"underlyingSink.close should be a function\")}if(\"abort\"in underlyingSink){if(underlyingSinkDict.abort=underlyingSink.abort,typeof underlyingSinkDict.abort!==\"function\")@throwTypeError(\"underlyingSink.abort should be a function\")}return @initializeWritableStreamSlots(stream,underlyingSink),@setUpWritableStreamDefaultControllerFromUnderlyingSink(stream,underlyingSink,underlyingSinkDict,highWaterMark,sizeAlgorithm),stream})\n"; // initializeWritableStreamSlots const JSC::ConstructAbility s_writableStreamInternalsInitializeWritableStreamSlotsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsInitializeWritableStreamSlotsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsInitializeWritableStreamSlotsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsInitializeWritableStreamSlotsCodeLength = 588; +const int s_writableStreamInternalsInitializeWritableStreamSlotsCodeLength = 674; static const JSC::Intrinsic s_writableStreamInternalsInitializeWritableStreamSlotsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsInitializeWritableStreamSlotsCode = "(function (_,c){\"use strict\";@putByIdDirectPrivate(_,\"state\",\"writable\"),@putByIdDirectPrivate(_,\"storedError\",@undefined),@putByIdDirectPrivate(_,\"writer\",@undefined),@putByIdDirectPrivate(_,\"controller\",@undefined),@putByIdDirectPrivate(_,\"inFlightWriteRequest\",@undefined),@putByIdDirectPrivate(_,\"closeRequest\",@undefined),@putByIdDirectPrivate(_,\"inFlightCloseRequest\",@undefined),@putByIdDirectPrivate(_,\"pendingAbortRequest\",@undefined),@putByIdDirectPrivate(_,\"writeRequests\",@createFIFO()),@putByIdDirectPrivate(_,\"backpressure\",!1),@putByIdDirectPrivate(_,\"underlyingSink\",c)})\n"; +const char* const s_writableStreamInternalsInitializeWritableStreamSlotsCode = "(function (stream,underlyingSink){\"use strict\";@putByIdDirectPrivate(stream,\"state\",\"writable\"),@putByIdDirectPrivate(stream,\"storedError\",@undefined),@putByIdDirectPrivate(stream,\"writer\",@undefined),@putByIdDirectPrivate(stream,\"controller\",@undefined),@putByIdDirectPrivate(stream,\"inFlightWriteRequest\",@undefined),@putByIdDirectPrivate(stream,\"closeRequest\",@undefined),@putByIdDirectPrivate(stream,\"inFlightCloseRequest\",@undefined),@putByIdDirectPrivate(stream,\"pendingAbortRequest\",@undefined),@putByIdDirectPrivate(stream,\"writeRequests\",@createFIFO()),@putByIdDirectPrivate(stream,\"backpressure\",!1),@putByIdDirectPrivate(stream,\"underlyingSink\",underlyingSink)})\n"; // writableStreamCloseForBindings const JSC::ConstructAbility s_writableStreamInternalsWritableStreamCloseForBindingsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamCloseForBindingsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamCloseForBindingsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamCloseForBindingsCodeLength = 370; +const int s_writableStreamInternalsWritableStreamCloseForBindingsCodeLength = 390; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamCloseForBindingsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamCloseForBindingsCode = "(function (_){\"use strict\";if(@isWritableStreamLocked(_))return @Promise.@reject(@makeTypeError(\"WritableStream.close method can only be used on non locked WritableStream\"));if(@writableStreamCloseQueuedOrInFlight(_))return @Promise.@reject(@makeTypeError(\"WritableStream.close method can only be used on a being close WritableStream\"));return @writableStreamClose(_)})\n"; +const char* const s_writableStreamInternalsWritableStreamCloseForBindingsCode = "(function (stream){\"use strict\";if(@isWritableStreamLocked(stream))return @Promise.@reject(@makeTypeError(\"WritableStream.close method can only be used on non locked WritableStream\"));if(@writableStreamCloseQueuedOrInFlight(stream))return @Promise.@reject(@makeTypeError(\"WritableStream.close method can only be used on a being close WritableStream\"));return @writableStreamClose(stream)})\n"; // writableStreamAbortForBindings const JSC::ConstructAbility s_writableStreamInternalsWritableStreamAbortForBindingsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamAbortForBindingsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamAbortForBindingsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamAbortForBindingsCodeLength = 211; +const int s_writableStreamInternalsWritableStreamAbortForBindingsCodeLength = 236; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamAbortForBindingsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamAbortForBindingsCode = "(function (d,h){\"use strict\";if(@isWritableStreamLocked(d))return @Promise.@reject(@makeTypeError(\"WritableStream.abort method can only be used on non locked WritableStream\"));return @writableStreamAbort(d,h)})\n"; +const char* const s_writableStreamInternalsWritableStreamAbortForBindingsCode = "(function (stream,reason){\"use strict\";if(@isWritableStreamLocked(stream))return @Promise.@reject(@makeTypeError(\"WritableStream.abort method can only be used on non locked WritableStream\"));return @writableStreamAbort(stream,reason)})\n"; // isWritableStreamLocked const JSC::ConstructAbility s_writableStreamInternalsIsWritableStreamLockedCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsIsWritableStreamLockedCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsIsWritableStreamLockedCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsIsWritableStreamLockedCodeLength = 83; +const int s_writableStreamInternalsIsWritableStreamLockedCodeLength = 93; static const JSC::Intrinsic s_writableStreamInternalsIsWritableStreamLockedCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsIsWritableStreamLockedCode = "(function (i){\"use strict\";return @getByIdDirectPrivate(i,\"writer\")!==@undefined})\n"; +const char* const s_writableStreamInternalsIsWritableStreamLockedCode = "(function (stream){\"use strict\";return @getByIdDirectPrivate(stream,\"writer\")!==@undefined})\n"; // setUpWritableStreamDefaultWriter const JSC::ConstructAbility s_writableStreamInternalsSetUpWritableStreamDefaultWriterCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsSetUpWritableStreamDefaultWriterCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsSetUpWritableStreamDefaultWriterCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsSetUpWritableStreamDefaultWriterCodeLength = 878; +const int s_writableStreamInternalsSetUpWritableStreamDefaultWriterCodeLength = 1249; static const JSC::Intrinsic s_writableStreamInternalsSetUpWritableStreamDefaultWriterCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsSetUpWritableStreamDefaultWriterCode = "(function (g,n){\"use strict\";if(@isWritableStreamLocked(n))@throwTypeError(\"WritableStream is locked\");@putByIdDirectPrivate(g,\"stream\",n),@putByIdDirectPrivate(n,\"writer\",g);const B=@newPromiseCapability(@Promise),h=@newPromiseCapability(@Promise);@putByIdDirectPrivate(g,\"readyPromise\",B),@putByIdDirectPrivate(g,\"closedPromise\",h);const k=@getByIdDirectPrivate(n,\"state\");if(k===\"writable\"){if(@writableStreamCloseQueuedOrInFlight(n)||!@getByIdDirectPrivate(n,\"backpressure\"))B.resolve.@call()}else if(k===\"erroring\")B.reject.@call(@undefined,@getByIdDirectPrivate(n,\"storedError\")),@markPromiseAsHandled(B.promise);else if(k===\"closed\")B.resolve.@call(),h.resolve.@call();else{@assert(k===\"errored\");const u=@getByIdDirectPrivate(n,\"storedError\");B.reject.@call(@undefined,u),@markPromiseAsHandled(B.promise),h.reject.@call(@undefined,u),@markPromiseAsHandled(h.promise)}})\n"; +const char* const s_writableStreamInternalsSetUpWritableStreamDefaultWriterCode = "(function (writer,stream){\"use strict\";if(@isWritableStreamLocked(stream))@throwTypeError(\"WritableStream is locked\");@putByIdDirectPrivate(writer,\"stream\",stream),@putByIdDirectPrivate(stream,\"writer\",writer);const readyPromiseCapability=@newPromiseCapability(@Promise),closedPromiseCapability=@newPromiseCapability(@Promise);@putByIdDirectPrivate(writer,\"readyPromise\",readyPromiseCapability),@putByIdDirectPrivate(writer,\"closedPromise\",closedPromiseCapability);const state=@getByIdDirectPrivate(stream,\"state\");if(state===\"writable\"){if(@writableStreamCloseQueuedOrInFlight(stream)||!@getByIdDirectPrivate(stream,\"backpressure\"))readyPromiseCapability.resolve.@call()}else if(state===\"erroring\")readyPromiseCapability.reject.@call(@undefined,@getByIdDirectPrivate(stream,\"storedError\")),@markPromiseAsHandled(readyPromiseCapability.promise);else if(state===\"closed\")readyPromiseCapability.resolve.@call(),closedPromiseCapability.resolve.@call();else{const storedError=@getByIdDirectPrivate(stream,\"storedError\");readyPromiseCapability.reject.@call(@undefined,storedError),@markPromiseAsHandled(readyPromiseCapability.promise),closedPromiseCapability.reject.@call(@undefined,storedError),@markPromiseAsHandled(closedPromiseCapability.promise)}})\n"; // writableStreamAbort const JSC::ConstructAbility s_writableStreamInternalsWritableStreamAbortCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamAbortCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamAbortCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamAbortCodeLength = 499; +const int s_writableStreamInternalsWritableStreamAbortCodeLength = 679; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamAbortCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamAbortCode = "(function (h,B){\"use strict\";const c=@getByIdDirectPrivate(h,\"state\");if(c===\"closed\"||c===\"errored\")return @Promise.@resolve();const f=@getByIdDirectPrivate(h,\"pendingAbortRequest\");if(f!==@undefined)return f.promise.promise;@assert(c===\"writable\"||c===\"erroring\");let _=!1;if(c===\"erroring\")_=!0,B=@undefined;const j=@newPromiseCapability(@Promise);if(@putByIdDirectPrivate(h,\"pendingAbortRequest\",{promise:j,reason:B,wasAlreadyErroring:_}),!_)@writableStreamStartErroring(h,B);return j.promise})\n"; +const char* const s_writableStreamInternalsWritableStreamAbortCode = "(function (stream,reason){\"use strict\";const state=@getByIdDirectPrivate(stream,\"state\");if(state===\"closed\"||state===\"errored\")return @Promise.@resolve();const pendingAbortRequest=@getByIdDirectPrivate(stream,\"pendingAbortRequest\");if(pendingAbortRequest!==@undefined)return pendingAbortRequest.promise.promise;let wasAlreadyErroring=!1;if(state===\"erroring\")wasAlreadyErroring=!0,reason=@undefined;const abortPromiseCapability=@newPromiseCapability(@Promise);if(@putByIdDirectPrivate(stream,\"pendingAbortRequest\",{promise:abortPromiseCapability,reason,wasAlreadyErroring}),!wasAlreadyErroring)@writableStreamStartErroring(stream,reason);return abortPromiseCapability.promise})\n"; // writableStreamClose const JSC::ConstructAbility s_writableStreamInternalsWritableStreamCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamCloseCodeLength = 640; +const int s_writableStreamInternalsWritableStreamCloseCodeLength = 674; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamCloseCode = "(function (n){\"use strict\";const _=@getByIdDirectPrivate(n,\"state\");if(_===\"closed\"||_===\"errored\")return @Promise.@reject(@makeTypeError(\"Cannot close a writable stream that is closed or errored\"));@assert(_===\"writable\"||_===\"erroring\"),@assert(!@writableStreamCloseQueuedOrInFlight(n));const d=@newPromiseCapability(@Promise);@putByIdDirectPrivate(n,\"closeRequest\",d);const h=@getByIdDirectPrivate(n,\"writer\");if(h!==@undefined&&@getByIdDirectPrivate(n,\"backpressure\")&&_===\"writable\")@getByIdDirectPrivate(h,\"readyPromise\").resolve.@call();return @writableStreamDefaultControllerClose(@getByIdDirectPrivate(n,\"controller\")),d.promise})\n"; +const char* const s_writableStreamInternalsWritableStreamCloseCode = "(function (stream){\"use strict\";const state=@getByIdDirectPrivate(stream,\"state\");if(state===\"closed\"||state===\"errored\")return @Promise.@reject(@makeTypeError(\"Cannot close a writable stream that is closed or errored\"));const closePromiseCapability=@newPromiseCapability(@Promise);@putByIdDirectPrivate(stream,\"closeRequest\",closePromiseCapability);const writer=@getByIdDirectPrivate(stream,\"writer\");if(writer!==@undefined&&@getByIdDirectPrivate(stream,\"backpressure\")&&state===\"writable\")@getByIdDirectPrivate(writer,\"readyPromise\").resolve.@call();return @writableStreamDefaultControllerClose(@getByIdDirectPrivate(stream,\"controller\")),closePromiseCapability.promise})\n"; // writableStreamAddWriteRequest const JSC::ConstructAbility s_writableStreamInternalsWritableStreamAddWriteRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamAddWriteRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamAddWriteRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamAddWriteRequestCodeLength = 226; +const int s_writableStreamInternalsWritableStreamAddWriteRequestCodeLength = 208; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamAddWriteRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamAddWriteRequestCode = "(function (c){\"use strict\";@assert(@isWritableStreamLocked(c)),@assert(@getByIdDirectPrivate(c,\"state\")===\"writable\");const _=@newPromiseCapability(@Promise);return @getByIdDirectPrivate(c,\"writeRequests\").push(_),_.promise})\n"; +const char* const s_writableStreamInternalsWritableStreamAddWriteRequestCode = "(function (stream){\"use strict\";const writePromiseCapability=@newPromiseCapability(@Promise);return @getByIdDirectPrivate(stream,\"writeRequests\").push(writePromiseCapability),writePromiseCapability.promise})\n"; // writableStreamCloseQueuedOrInFlight const JSC::ConstructAbility s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCodeLength = 151; +const int s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCodeLength = 166; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCode = "(function (i){\"use strict\";return @getByIdDirectPrivate(i,\"closeRequest\")!==@undefined||@getByIdDirectPrivate(i,\"inFlightCloseRequest\")!==@undefined})\n"; +const char* const s_writableStreamInternalsWritableStreamCloseQueuedOrInFlightCode = "(function (stream){\"use strict\";return @getByIdDirectPrivate(stream,\"closeRequest\")!==@undefined||@getByIdDirectPrivate(stream,\"inFlightCloseRequest\")!==@undefined})\n"; // writableStreamDealWithRejection const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDealWithRejectionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDealWithRejectionCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDealWithRejectionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDealWithRejectionCodeLength = 189; +const int s_writableStreamInternalsWritableStreamDealWithRejectionCodeLength = 183; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDealWithRejectionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDealWithRejectionCode = "(function (i,c){\"use strict\";const n=@getByIdDirectPrivate(i,\"state\");if(n===\"writable\"){@writableStreamStartErroring(i,c);return}@assert(n===\"erroring\"),@writableStreamFinishErroring(i)})\n"; +const char* const s_writableStreamInternalsWritableStreamDealWithRejectionCode = "(function (stream,error){\"use strict\";if(@getByIdDirectPrivate(stream,\"state\")===\"writable\"){@writableStreamStartErroring(stream,error);return}@writableStreamFinishErroring(stream)})\n"; // writableStreamFinishErroring const JSC::ConstructAbility s_writableStreamInternalsWritableStreamFinishErroringCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamFinishErroringCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamFinishErroringCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamFinishErroringCodeLength = 1054; +const int s_writableStreamInternalsWritableStreamFinishErroringCodeLength = 1193; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamFinishErroringCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamFinishErroringCode = "(function (i){\"use strict\";@assert(@getByIdDirectPrivate(i,\"state\")===\"erroring\"),@assert(!@writableStreamHasOperationMarkedInFlight(i)),@putByIdDirectPrivate(i,\"state\",\"errored\");const d=@getByIdDirectPrivate(i,\"controller\");@getByIdDirectPrivate(d,\"errorSteps\").@call();const h=@getByIdDirectPrivate(i,\"storedError\"),j=@getByIdDirectPrivate(i,\"writeRequests\");for(var f=j.shift();f;f=j.shift())f.reject.@call(@undefined,h);@putByIdDirectPrivate(i,\"writeRequests\",@createFIFO());const _=@getByIdDirectPrivate(i,\"pendingAbortRequest\");if(_===@undefined){@writableStreamRejectCloseAndClosedPromiseIfNeeded(i);return}if(@putByIdDirectPrivate(i,\"pendingAbortRequest\",@undefined),_.wasAlreadyErroring){_.promise.reject.@call(@undefined,h),@writableStreamRejectCloseAndClosedPromiseIfNeeded(i);return}@getByIdDirectPrivate(d,\"abortSteps\").@call(@undefined,_.reason).@then(()=>{_.promise.resolve.@call(),@writableStreamRejectCloseAndClosedPromiseIfNeeded(i)},(v)=>{_.promise.reject.@call(@undefined,v),@writableStreamRejectCloseAndClosedPromiseIfNeeded(i)})})\n"; +const char* const s_writableStreamInternalsWritableStreamFinishErroringCode = "(function (stream){\"use strict\";@putByIdDirectPrivate(stream,\"state\",\"errored\");const controller=@getByIdDirectPrivate(stream,\"controller\");@getByIdDirectPrivate(controller,\"errorSteps\").@call();const storedError=@getByIdDirectPrivate(stream,\"storedError\"),requests=@getByIdDirectPrivate(stream,\"writeRequests\");for(var request=requests.shift();request;request=requests.shift())request.reject.@call(@undefined,storedError);@putByIdDirectPrivate(stream,\"writeRequests\",@createFIFO());const abortRequest=@getByIdDirectPrivate(stream,\"pendingAbortRequest\");if(abortRequest===@undefined){@writableStreamRejectCloseAndClosedPromiseIfNeeded(stream);return}if(@putByIdDirectPrivate(stream,\"pendingAbortRequest\",@undefined),abortRequest.wasAlreadyErroring){abortRequest.promise.reject.@call(@undefined,storedError),@writableStreamRejectCloseAndClosedPromiseIfNeeded(stream);return}@getByIdDirectPrivate(controller,\"abortSteps\").@call(@undefined,abortRequest.reason).@then(()=>{abortRequest.promise.resolve.@call(),@writableStreamRejectCloseAndClosedPromiseIfNeeded(stream)},(reason)=>{abortRequest.promise.reject.@call(@undefined,reason),@writableStreamRejectCloseAndClosedPromiseIfNeeded(stream)})})\n"; // writableStreamFinishInFlightClose const JSC::ConstructAbility s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeLength = 748; +const int s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeLength = 661; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamFinishInFlightCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamFinishInFlightCloseCode = "(function (_){\"use strict\";@getByIdDirectPrivate(_,\"inFlightCloseRequest\").resolve.@call(),@putByIdDirectPrivate(_,\"inFlightCloseRequest\",@undefined);const d=@getByIdDirectPrivate(_,\"state\");if(@assert(d===\"writable\"||d===\"erroring\"),d===\"erroring\"){@putByIdDirectPrivate(_,\"storedError\",@undefined);const n=@getByIdDirectPrivate(_,\"pendingAbortRequest\");if(n!==@undefined)n.promise.resolve.@call(),@putByIdDirectPrivate(_,\"pendingAbortRequest\",@undefined)}@putByIdDirectPrivate(_,\"state\",\"closed\");const i=@getByIdDirectPrivate(_,\"writer\");if(i!==@undefined)@getByIdDirectPrivate(i,\"closedPromise\").resolve.@call();@assert(@getByIdDirectPrivate(_,\"pendingAbortRequest\")===@undefined),@assert(@getByIdDirectPrivate(_,\"storedError\")===@undefined)})\n"; +const char* const s_writableStreamInternalsWritableStreamFinishInFlightCloseCode = "(function (stream){\"use strict\";if(@getByIdDirectPrivate(stream,\"inFlightCloseRequest\").resolve.@call(),@putByIdDirectPrivate(stream,\"inFlightCloseRequest\",@undefined),@getByIdDirectPrivate(stream,\"state\")===\"erroring\"){@putByIdDirectPrivate(stream,\"storedError\",@undefined);const abortRequest=@getByIdDirectPrivate(stream,\"pendingAbortRequest\");if(abortRequest!==@undefined)abortRequest.promise.resolve.@call(),@putByIdDirectPrivate(stream,\"pendingAbortRequest\",@undefined)}@putByIdDirectPrivate(stream,\"state\",\"closed\");const writer=@getByIdDirectPrivate(stream,\"writer\");if(writer!==@undefined)@getByIdDirectPrivate(writer,\"closedPromise\").resolve.@call()})\n"; // writableStreamFinishInFlightCloseWithError const JSC::ConstructAbility s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCodeLength = 486; +const int s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCodeLength = 494; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCode = "(function (c,d){\"use strict\";const p=@getByIdDirectPrivate(c,\"inFlightCloseRequest\");@assert(p!==@undefined),p.reject.@call(@undefined,d),@putByIdDirectPrivate(c,\"inFlightCloseRequest\",@undefined);const _=@getByIdDirectPrivate(c,\"state\");@assert(_===\"writable\"||_===\"erroring\");const f=@getByIdDirectPrivate(c,\"pendingAbortRequest\");if(f!==@undefined)f.promise.reject.@call(@undefined,d),@putByIdDirectPrivate(c,\"pendingAbortRequest\",@undefined);@writableStreamDealWithRejection(c,d)})\n"; +const char* const s_writableStreamInternalsWritableStreamFinishInFlightCloseWithErrorCode = "(function (stream,error){\"use strict\";@getByIdDirectPrivate(stream,\"inFlightCloseRequest\").reject.@call(@undefined,error),@putByIdDirectPrivate(stream,\"inFlightCloseRequest\",@undefined);const state=@getByIdDirectPrivate(stream,\"state\"),abortRequest=@getByIdDirectPrivate(stream,\"pendingAbortRequest\");if(abortRequest!==@undefined)abortRequest.promise.reject.@call(@undefined,error),@putByIdDirectPrivate(stream,\"pendingAbortRequest\",@undefined);@writableStreamDealWithRejection(stream,error)})\n"; // writableStreamFinishInFlightWrite const JSC::ConstructAbility s_writableStreamInternalsWritableStreamFinishInFlightWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamFinishInFlightWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamFinishInFlightWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamFinishInFlightWriteCodeLength = 186; +const int s_writableStreamInternalsWritableStreamFinishInFlightWriteCodeLength = 167; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamFinishInFlightWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamFinishInFlightWriteCode = "(function (d){\"use strict\";const b=@getByIdDirectPrivate(d,\"inFlightWriteRequest\");@assert(b!==@undefined),b.resolve.@call(),@putByIdDirectPrivate(d,\"inFlightWriteRequest\",@undefined)})\n"; +const char* const s_writableStreamInternalsWritableStreamFinishInFlightWriteCode = "(function (stream){\"use strict\";@getByIdDirectPrivate(stream,\"inFlightWriteRequest\").resolve.@call(),@putByIdDirectPrivate(stream,\"inFlightWriteRequest\",@undefined)})\n"; // writableStreamFinishInFlightWriteWithError const JSC::ConstructAbility s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCodeLength = 318; +const int s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCodeLength = 285; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCode = "(function (c,b){\"use strict\";const d=@getByIdDirectPrivate(c,\"inFlightWriteRequest\");@assert(d!==@undefined),d.reject.@call(@undefined,b),@putByIdDirectPrivate(c,\"inFlightWriteRequest\",@undefined);const f=@getByIdDirectPrivate(c,\"state\");@assert(f===\"writable\"||f===\"erroring\"),@writableStreamDealWithRejection(c,b)})\n"; +const char* const s_writableStreamInternalsWritableStreamFinishInFlightWriteWithErrorCode = "(function (stream,error){\"use strict\";@getByIdDirectPrivate(stream,\"inFlightWriteRequest\").reject.@call(@undefined,error),@putByIdDirectPrivate(stream,\"inFlightWriteRequest\",@undefined);const state=@getByIdDirectPrivate(stream,\"state\");@writableStreamDealWithRejection(stream,error)})\n"; // writableStreamHasOperationMarkedInFlight const JSC::ConstructAbility s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCodeLength = 159; +const int s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCodeLength = 174; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCode = "(function (n){\"use strict\";return @getByIdDirectPrivate(n,\"inFlightWriteRequest\")!==@undefined||@getByIdDirectPrivate(n,\"inFlightCloseRequest\")!==@undefined})\n"; +const char* const s_writableStreamInternalsWritableStreamHasOperationMarkedInFlightCode = "(function (stream){\"use strict\";return @getByIdDirectPrivate(stream,\"inFlightWriteRequest\")!==@undefined||@getByIdDirectPrivate(stream,\"inFlightCloseRequest\")!==@undefined})\n"; // writableStreamMarkCloseRequestInFlight const JSC::ConstructAbility s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCodeLength = 272; +const int s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCodeLength = 220; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCode = "(function (i){\"use strict\";const d=@getByIdDirectPrivate(i,\"closeRequest\");@assert(@getByIdDirectPrivate(i,\"inFlightCloseRequest\")===@undefined),@assert(d!==@undefined),@putByIdDirectPrivate(i,\"inFlightCloseRequest\",d),@putByIdDirectPrivate(i,\"closeRequest\",@undefined)})\n"; +const char* const s_writableStreamInternalsWritableStreamMarkCloseRequestInFlightCode = "(function (stream){\"use strict\";const closeRequest=@getByIdDirectPrivate(stream,\"closeRequest\");@putByIdDirectPrivate(stream,\"inFlightCloseRequest\",closeRequest),@putByIdDirectPrivate(stream,\"closeRequest\",@undefined)})\n"; // writableStreamMarkFirstWriteRequestInFlight const JSC::ConstructAbility s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCodeLength = 240; +const int s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCodeLength = 173; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCode = "(function (c){\"use strict\";const d=@getByIdDirectPrivate(c,\"writeRequests\");@assert(@getByIdDirectPrivate(c,\"inFlightWriteRequest\")===@undefined),@assert(d.isNotEmpty());const h=d.shift();@putByIdDirectPrivate(c,\"inFlightWriteRequest\",h)})\n"; +const char* const s_writableStreamInternalsWritableStreamMarkFirstWriteRequestInFlightCode = "(function (stream){\"use strict\";const writeRequest=@getByIdDirectPrivate(stream,\"writeRequests\").shift();@putByIdDirectPrivate(stream,\"inFlightWriteRequest\",writeRequest)})\n"; // writableStreamRejectCloseAndClosedPromiseIfNeeded const JSC::ConstructAbility s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCodeLength = 513; +const int s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCodeLength = 528; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCode = "(function (n){\"use strict\";@assert(@getByIdDirectPrivate(n,\"state\")===\"errored\");const _=@getByIdDirectPrivate(n,\"storedError\"),h=@getByIdDirectPrivate(n,\"closeRequest\");if(h!==@undefined)@assert(@getByIdDirectPrivate(n,\"inFlightCloseRequest\")===@undefined),h.reject.@call(@undefined,_),@putByIdDirectPrivate(n,\"closeRequest\",@undefined);const i=@getByIdDirectPrivate(n,\"writer\");if(i!==@undefined){const p=@getByIdDirectPrivate(i,\"closedPromise\");p.reject.@call(@undefined,_),@markPromiseAsHandled(p.promise)}})\n"; +const char* const s_writableStreamInternalsWritableStreamRejectCloseAndClosedPromiseIfNeededCode = "(function (stream){\"use strict\";const storedError=@getByIdDirectPrivate(stream,\"storedError\"),closeRequest=@getByIdDirectPrivate(stream,\"closeRequest\");if(closeRequest!==@undefined)closeRequest.reject.@call(@undefined,storedError),@putByIdDirectPrivate(stream,\"closeRequest\",@undefined);const writer=@getByIdDirectPrivate(stream,\"writer\");if(writer!==@undefined){const closedPromise=@getByIdDirectPrivate(writer,\"closedPromise\");closedPromise.reject.@call(@undefined,storedError),@markPromiseAsHandled(closedPromise.promise)}})\n"; // writableStreamStartErroring const JSC::ConstructAbility s_writableStreamInternalsWritableStreamStartErroringCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamStartErroringCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamStartErroringCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamStartErroringCodeLength = 544; +const int s_writableStreamInternalsWritableStreamStartErroringCodeLength = 487; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamStartErroringCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamStartErroringCode = "(function (i,_){\"use strict\";@assert(@getByIdDirectPrivate(i,\"storedError\")===@undefined),@assert(@getByIdDirectPrivate(i,\"state\")===\"writable\");const d=@getByIdDirectPrivate(i,\"controller\");@assert(d!==@undefined),@putByIdDirectPrivate(i,\"state\",\"erroring\"),@putByIdDirectPrivate(i,\"storedError\",_);const h=@getByIdDirectPrivate(i,\"writer\");if(h!==@undefined)@writableStreamDefaultWriterEnsureReadyPromiseRejected(h,_);if(!@writableStreamHasOperationMarkedInFlight(i)&&@getByIdDirectPrivate(d,\"started\")===1)@writableStreamFinishErroring(i)})\n"; +const char* const s_writableStreamInternalsWritableStreamStartErroringCode = "(function (stream,reason){\"use strict\";const controller=@getByIdDirectPrivate(stream,\"controller\");@putByIdDirectPrivate(stream,\"state\",\"erroring\"),@putByIdDirectPrivate(stream,\"storedError\",reason);const writer=@getByIdDirectPrivate(stream,\"writer\");if(writer!==@undefined)@writableStreamDefaultWriterEnsureReadyPromiseRejected(writer,reason);if(!@writableStreamHasOperationMarkedInFlight(stream)&&@getByIdDirectPrivate(controller,\"started\")===1)@writableStreamFinishErroring(stream)})\n"; // writableStreamUpdateBackpressure const JSC::ConstructAbility s_writableStreamInternalsWritableStreamUpdateBackpressureCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamUpdateBackpressureCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamUpdateBackpressureCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamUpdateBackpressureCodeLength = 421; +const int s_writableStreamInternalsWritableStreamUpdateBackpressureCodeLength = 400; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamUpdateBackpressureCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamUpdateBackpressureCode = "(function (n,_){\"use strict\";@assert(@getByIdDirectPrivate(n,\"state\")===\"writable\"),@assert(!@writableStreamCloseQueuedOrInFlight(n));const d=@getByIdDirectPrivate(n,\"writer\");if(d!==@undefined&&_!==@getByIdDirectPrivate(n,\"backpressure\"))if(_)@putByIdDirectPrivate(d,\"readyPromise\",@newPromiseCapability(@Promise));else @getByIdDirectPrivate(d,\"readyPromise\").resolve.@call();@putByIdDirectPrivate(n,\"backpressure\",_)})\n"; +const char* const s_writableStreamInternalsWritableStreamUpdateBackpressureCode = "(function (stream,backpressure){\"use strict\";const writer=@getByIdDirectPrivate(stream,\"writer\");if(writer!==@undefined&&backpressure!==@getByIdDirectPrivate(stream,\"backpressure\"))if(backpressure)@putByIdDirectPrivate(writer,\"readyPromise\",@newPromiseCapability(@Promise));else @getByIdDirectPrivate(writer,\"readyPromise\").resolve.@call();@putByIdDirectPrivate(stream,\"backpressure\",backpressure)})\n"; // writableStreamDefaultWriterAbort const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterAbortCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterAbortCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterAbortCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterAbortCodeLength = 130; +const int s_writableStreamInternalsWritableStreamDefaultWriterAbortCodeLength = 136; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterAbortCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterAbortCode = "(function (d,f){\"use strict\";const c=@getByIdDirectPrivate(d,\"stream\");return @assert(c!==@undefined),@writableStreamAbort(c,f)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterAbortCode = "(function (writer,reason){\"use strict\";const stream=@getByIdDirectPrivate(writer,\"stream\");return @writableStreamAbort(stream,reason)})\n"; // writableStreamDefaultWriterClose const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterCloseCodeLength = 126; +const int s_writableStreamInternalsWritableStreamDefaultWriterCloseCodeLength = 122; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterCloseCode = "(function (c){\"use strict\";const _=@getByIdDirectPrivate(c,\"stream\");return @assert(_!==@undefined),@writableStreamClose(_)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterCloseCode = "(function (writer){\"use strict\";const stream=@getByIdDirectPrivate(writer,\"stream\");return @writableStreamClose(stream)})\n"; // writableStreamDefaultWriterCloseWithErrorPropagation const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCodeLength = 385; +const int s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCodeLength = 362; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCode = "(function (u){\"use strict\";const c=@getByIdDirectPrivate(u,\"stream\");@assert(c!==@undefined);const l=@getByIdDirectPrivate(c,\"state\");if(@writableStreamCloseQueuedOrInFlight(c)||l===\"closed\")return @Promise.@resolve();if(l===\"errored\")return @Promise.@reject(@getByIdDirectPrivate(c,\"storedError\"));return @assert(l===\"writable\"||l===\"erroring\"),@writableStreamDefaultWriterClose(u)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterCloseWithErrorPropagationCode = "(function (writer){\"use strict\";const stream=@getByIdDirectPrivate(writer,\"stream\"),state=@getByIdDirectPrivate(stream,\"state\");if(@writableStreamCloseQueuedOrInFlight(stream)||state===\"closed\")return @Promise.@resolve();if(state===\"errored\")return @Promise.@reject(@getByIdDirectPrivate(stream,\"storedError\"));return @writableStreamDefaultWriterClose(writer)})\n"; // writableStreamDefaultWriterEnsureClosedPromiseRejected const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCodeLength = 326; +const int s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCodeLength = 529; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCode = "(function (h,n){\"use strict\";let _=@getByIdDirectPrivate(h,\"closedPromise\"),f=_.promise;if((@getPromiseInternalField(f,@promiseFieldFlags)&@promiseStateMask)!==@promiseStatePending)_=@newPromiseCapability(@Promise),f=_.promise,@putByIdDirectPrivate(h,\"closedPromise\",_);_.reject.@call(@undefined,n),@markPromiseAsHandled(f)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterEnsureClosedPromiseRejectedCode = "(function (writer,error){\"use strict\";let closedPromiseCapability=@getByIdDirectPrivate(writer,\"closedPromise\"),closedPromise=closedPromiseCapability.promise;if((@getPromiseInternalField(closedPromise,@promiseFieldFlags)&@promiseStateMask)!==@promiseStatePending)closedPromiseCapability=@newPromiseCapability(@Promise),closedPromise=closedPromiseCapability.promise,@putByIdDirectPrivate(writer,\"closedPromise\",closedPromiseCapability);closedPromiseCapability.reject.@call(@undefined,error),@markPromiseAsHandled(closedPromise)})\n"; // writableStreamDefaultWriterEnsureReadyPromiseRejected const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCodeLength = 324; +const int s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCodeLength = 517; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCode = "(function (h,n){\"use strict\";let _=@getByIdDirectPrivate(h,\"readyPromise\"),g=_.promise;if((@getPromiseInternalField(g,@promiseFieldFlags)&@promiseStateMask)!==@promiseStatePending)_=@newPromiseCapability(@Promise),g=_.promise,@putByIdDirectPrivate(h,\"readyPromise\",_);_.reject.@call(@undefined,n),@markPromiseAsHandled(g)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterEnsureReadyPromiseRejectedCode = "(function (writer,error){\"use strict\";let readyPromiseCapability=@getByIdDirectPrivate(writer,\"readyPromise\"),readyPromise=readyPromiseCapability.promise;if((@getPromiseInternalField(readyPromise,@promiseFieldFlags)&@promiseStateMask)!==@promiseStatePending)readyPromiseCapability=@newPromiseCapability(@Promise),readyPromise=readyPromiseCapability.promise,@putByIdDirectPrivate(writer,\"readyPromise\",readyPromiseCapability);readyPromiseCapability.reject.@call(@undefined,error),@markPromiseAsHandled(readyPromise)})\n"; // writableStreamDefaultWriterGetDesiredSize const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCodeLength = 299; +const int s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCodeLength = 310; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCode = "(function (_){\"use strict\";const c=@getByIdDirectPrivate(_,\"stream\");@assert(c!==@undefined);const l=@getByIdDirectPrivate(c,\"state\");if(l===\"errored\"||l===\"erroring\")return null;if(l===\"closed\")return 0;return @writableStreamDefaultControllerGetDesiredSize(@getByIdDirectPrivate(c,\"controller\"))})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterGetDesiredSizeCode = "(function (writer){\"use strict\";const stream=@getByIdDirectPrivate(writer,\"stream\"),state=@getByIdDirectPrivate(stream,\"state\");if(state===\"errored\"||state===\"erroring\")return null;if(state===\"closed\")return 0;return @writableStreamDefaultControllerGetDesiredSize(@getByIdDirectPrivate(stream,\"controller\"))})\n"; // writableStreamDefaultWriterRelease const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterReleaseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterReleaseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterReleaseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterReleaseCodeLength = 414; +const int s_writableStreamInternalsWritableStreamDefaultWriterReleaseCodeLength = 408; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterReleaseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterReleaseCode = "(function (_){\"use strict\";const c=@getByIdDirectPrivate(_,\"stream\");@assert(c!==@undefined),@assert(@getByIdDirectPrivate(c,\"writer\")===_);const h=@makeTypeError(\"writableStreamDefaultWriterRelease\");@writableStreamDefaultWriterEnsureReadyPromiseRejected(_,h),@writableStreamDefaultWriterEnsureClosedPromiseRejected(_,h),@putByIdDirectPrivate(c,\"writer\",@undefined),@putByIdDirectPrivate(_,\"stream\",@undefined)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterReleaseCode = "(function (writer){\"use strict\";const stream=@getByIdDirectPrivate(writer,\"stream\"),releasedError=@makeTypeError(\"writableStreamDefaultWriterRelease\");@writableStreamDefaultWriterEnsureReadyPromiseRejected(writer,releasedError),@writableStreamDefaultWriterEnsureClosedPromiseRejected(writer,releasedError),@putByIdDirectPrivate(stream,\"writer\",@undefined),@putByIdDirectPrivate(writer,\"stream\",@undefined)})\n"; // writableStreamDefaultWriterWrite const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeLength = 919; +const int s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeLength = 982; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultWriterWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultWriterWriteCode = "(function (W,_){\"use strict\";const d=@getByIdDirectPrivate(W,\"stream\");@assert(d!==@undefined);const P=@getByIdDirectPrivate(d,\"controller\");@assert(P!==@undefined);const b=@writableStreamDefaultControllerGetChunkSize(P,_);if(d!==@getByIdDirectPrivate(W,\"stream\"))return @Promise.@reject(@makeTypeError(\"writer is not stream's writer\"));const g=@getByIdDirectPrivate(d,\"state\");if(g===\"errored\")return @Promise.@reject(@getByIdDirectPrivate(d,\"storedError\"));if(@writableStreamCloseQueuedOrInFlight(d)||g===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(@writableStreamCloseQueuedOrInFlight(d)||g===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(g===\"erroring\")return @Promise.@reject(@getByIdDirectPrivate(d,\"storedError\"));@assert(g===\"writable\");const f=@writableStreamAddWriteRequest(d);return @writableStreamDefaultControllerWrite(P,_,b),f})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultWriterWriteCode = "(function (writer,chunk){\"use strict\";const stream=@getByIdDirectPrivate(writer,\"stream\"),controller=@getByIdDirectPrivate(stream,\"controller\"),chunkSize=@writableStreamDefaultControllerGetChunkSize(controller,chunk);if(stream!==@getByIdDirectPrivate(writer,\"stream\"))return @Promise.@reject(@makeTypeError(\"writer is not stream's writer\"));const state=@getByIdDirectPrivate(stream,\"state\");if(state===\"errored\")return @Promise.@reject(@getByIdDirectPrivate(stream,\"storedError\"));if(@writableStreamCloseQueuedOrInFlight(stream)||state===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(@writableStreamCloseQueuedOrInFlight(stream)||state===\"closed\")return @Promise.@reject(@makeTypeError(\"stream is closing or closed\"));if(state===\"erroring\")return @Promise.@reject(@getByIdDirectPrivate(stream,\"storedError\"));const promise=@writableStreamAddWriteRequest(stream);return @writableStreamDefaultControllerWrite(controller,chunk,chunkSize),promise})\n"; // setUpWritableStreamDefaultController const JSC::ConstructAbility s_writableStreamInternalsSetUpWritableStreamDefaultControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsSetUpWritableStreamDefaultControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsSetUpWritableStreamDefaultControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsSetUpWritableStreamDefaultControllerCodeLength = 700; +const int s_writableStreamInternalsSetUpWritableStreamDefaultControllerCodeLength = 921; static const JSC::Intrinsic s_writableStreamInternalsSetUpWritableStreamDefaultControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsSetUpWritableStreamDefaultControllerCode = "(function (B,_,v,P,U,d,f,j){\"use strict\";@assert(@isWritableStream(B)),@assert(@getByIdDirectPrivate(B,\"controller\")===@undefined),@putByIdDirectPrivate(_,\"stream\",B),@putByIdDirectPrivate(B,\"controller\",_),@resetQueue(@getByIdDirectPrivate(_,\"queue\")),@putByIdDirectPrivate(_,\"started\",-1),@putByIdDirectPrivate(_,\"startAlgorithm\",v),@putByIdDirectPrivate(_,\"strategySizeAlgorithm\",j),@putByIdDirectPrivate(_,\"strategyHWM\",f),@putByIdDirectPrivate(_,\"writeAlgorithm\",P),@putByIdDirectPrivate(_,\"closeAlgorithm\",U),@putByIdDirectPrivate(_,\"abortAlgorithm\",d);const q=@writableStreamDefaultControllerGetBackpressure(_);@writableStreamUpdateBackpressure(B,q),@writableStreamDefaultControllerStart(_)})\n"; +const char* const s_writableStreamInternalsSetUpWritableStreamDefaultControllerCode = "(function (stream,controller,startAlgorithm,writeAlgorithm,closeAlgorithm,abortAlgorithm,highWaterMark,sizeAlgorithm){\"use strict\";@putByIdDirectPrivate(controller,\"stream\",stream),@putByIdDirectPrivate(stream,\"controller\",controller),@resetQueue(@getByIdDirectPrivate(controller,\"queue\")),@putByIdDirectPrivate(controller,\"started\",-1),@putByIdDirectPrivate(controller,\"startAlgorithm\",startAlgorithm),@putByIdDirectPrivate(controller,\"strategySizeAlgorithm\",sizeAlgorithm),@putByIdDirectPrivate(controller,\"strategyHWM\",highWaterMark),@putByIdDirectPrivate(controller,\"writeAlgorithm\",writeAlgorithm),@putByIdDirectPrivate(controller,\"closeAlgorithm\",closeAlgorithm),@putByIdDirectPrivate(controller,\"abortAlgorithm\",abortAlgorithm);const backpressure=@writableStreamDefaultControllerGetBackpressure(controller);@writableStreamUpdateBackpressure(stream,backpressure),@writableStreamDefaultControllerStart(controller)})\n"; // writableStreamDefaultControllerStart const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerStartCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerStartCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerStartCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerStartCodeLength = 647; +const int s_writableStreamInternalsWritableStreamDefaultControllerStartCodeLength = 710; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerStartCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerStartCode = "(function (i){\"use strict\";if(@getByIdDirectPrivate(i,\"started\")!==-1)return;@putByIdDirectPrivate(i,\"started\",0);const p=@getByIdDirectPrivate(i,\"startAlgorithm\");@putByIdDirectPrivate(i,\"startAlgorithm\",@undefined);const d=@getByIdDirectPrivate(i,\"stream\");return @Promise.@resolve(p.@call()).@then(()=>{const _=@getByIdDirectPrivate(d,\"state\");@assert(_===\"writable\"||_===\"erroring\"),@putByIdDirectPrivate(i,\"started\",1),@writableStreamDefaultControllerAdvanceQueueIfNeeded(i)},(_)=>{const u=@getByIdDirectPrivate(d,\"state\");@assert(u===\"writable\"||u===\"erroring\"),@putByIdDirectPrivate(i,\"started\",1),@writableStreamDealWithRejection(d,_)})})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerStartCode = "(function (controller){\"use strict\";if(@getByIdDirectPrivate(controller,\"started\")!==-1)return;@putByIdDirectPrivate(controller,\"started\",0);const startAlgorithm=@getByIdDirectPrivate(controller,\"startAlgorithm\");@putByIdDirectPrivate(controller,\"startAlgorithm\",@undefined);const stream=@getByIdDirectPrivate(controller,\"stream\");return @Promise.@resolve(startAlgorithm.@call()).@then(()=>{const state=@getByIdDirectPrivate(stream,\"state\");@putByIdDirectPrivate(controller,\"started\",1),@writableStreamDefaultControllerAdvanceQueueIfNeeded(controller)},(error)=>{const state=@getByIdDirectPrivate(stream,\"state\");@putByIdDirectPrivate(controller,\"started\",1),@writableStreamDealWithRejection(stream,error)})})\n"; // setUpWritableStreamDefaultControllerFromUnderlyingSink const JSC::ConstructAbility s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeLength = 561; +const int s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeLength = 1127; static const JSC::Intrinsic s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCodeIntrinsic = JSC::NoIntrinsic; -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"; +const char* const s_writableStreamInternalsSetUpWritableStreamDefaultControllerFromUnderlyingSinkCode = "(function (stream,underlyingSink,underlyingSinkDict,highWaterMark,sizeAlgorithm){\"use strict\";const controller=new @WritableStreamDefaultController;let startAlgorithm=()=>{},writeAlgorithm=()=>{return @Promise.@resolve()},closeAlgorithm=()=>{return @Promise.@resolve()},abortAlgorithm=()=>{return @Promise.@resolve()};if(\"start\"in underlyingSinkDict){const startMethod=underlyingSinkDict.start;startAlgorithm=()=>@promiseInvokeOrNoopMethodNoCatch(underlyingSink,startMethod,[controller])}if(\"write\"in underlyingSinkDict){const writeMethod=underlyingSinkDict.write;writeAlgorithm=(chunk)=>@promiseInvokeOrNoopMethod(underlyingSink,writeMethod,[chunk,controller])}if(\"close\"in underlyingSinkDict){const closeMethod=underlyingSinkDict.close;closeAlgorithm=()=>@promiseInvokeOrNoopMethod(underlyingSink,closeMethod,[])}if(\"abort\"in underlyingSinkDict){const abortMethod=underlyingSinkDict.abort;abortAlgorithm=(reason)=>@promiseInvokeOrNoopMethod(underlyingSink,abortMethod,[reason])}@setUpWritableStreamDefaultController(stream,controller,startAlgorithm,writeAlgorithm,closeAlgorithm,abortAlgorithm,highWaterMark,sizeAlgorithm)})\n"; // writableStreamDefaultControllerAdvanceQueueIfNeeded const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCodeLength = 582; +const int s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCodeLength = 609; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCode = "(function (_){\"use strict\";const d=@getByIdDirectPrivate(_,\"stream\");if(@getByIdDirectPrivate(_,\"started\")!==1)return;if(@assert(d!==@undefined),@getByIdDirectPrivate(d,\"inFlightWriteRequest\")!==@undefined)return;const f=@getByIdDirectPrivate(d,\"state\");if(@assert(f!==\"closed\"||f!==\"errored\"),f===\"erroring\"){@writableStreamFinishErroring(d);return}const h=@getByIdDirectPrivate(_,\"queue\");if(h.content\?.isEmpty()\?\?!1)return;const i=@peekQueueValue(h);if(i===@isCloseSentinel)@writableStreamDefaultControllerProcessClose(_);else @writableStreamDefaultControllerProcessWrite(_,i)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerAdvanceQueueIfNeededCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"stream\");if(@getByIdDirectPrivate(controller,\"started\")!==1)return;if(@getByIdDirectPrivate(stream,\"inFlightWriteRequest\")!==@undefined)return;if(@getByIdDirectPrivate(stream,\"state\")===\"erroring\"){@writableStreamFinishErroring(stream);return}const queue=@getByIdDirectPrivate(controller,\"queue\");if(queue.content\?.isEmpty()\?\?!1)return;const value=@peekQueueValue(queue);if(value===@isCloseSentinel)@writableStreamDefaultControllerProcessClose(controller);else @writableStreamDefaultControllerProcessWrite(controller,value)})\n"; // isCloseSentinel const JSC::ConstructAbility s_writableStreamInternalsIsCloseSentinelCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -394,81 +394,81 @@ const char* const s_writableStreamInternalsIsCloseSentinelCode = "(function (){\ const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCodeLength = 248; +const int s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCodeLength = 293; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCode = "(function (h){\"use strict\";@putByIdDirectPrivate(h,\"writeAlgorithm\",@undefined),@putByIdDirectPrivate(h,\"closeAlgorithm\",@undefined),@putByIdDirectPrivate(h,\"abortAlgorithm\",@undefined),@putByIdDirectPrivate(h,\"strategySizeAlgorithm\",@undefined)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerClearAlgorithmsCode = "(function (controller){\"use strict\";@putByIdDirectPrivate(controller,\"writeAlgorithm\",@undefined),@putByIdDirectPrivate(controller,\"closeAlgorithm\",@undefined),@putByIdDirectPrivate(controller,\"abortAlgorithm\",@undefined),@putByIdDirectPrivate(controller,\"strategySizeAlgorithm\",@undefined)})\n"; // writableStreamDefaultControllerClose const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerCloseCodeLength = 160; +const int s_writableStreamInternalsWritableStreamDefaultControllerCloseCodeLength = 187; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerCloseCode = "(function (_){\"use strict\";@enqueueValueWithSize(@getByIdDirectPrivate(_,\"queue\"),@isCloseSentinel,0),@writableStreamDefaultControllerAdvanceQueueIfNeeded(_)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerCloseCode = "(function (controller){\"use strict\";@enqueueValueWithSize(@getByIdDirectPrivate(controller,\"queue\"),@isCloseSentinel,0),@writableStreamDefaultControllerAdvanceQueueIfNeeded(controller)})\n"; // writableStreamDefaultControllerError const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerErrorCodeLength = 237; +const int s_writableStreamInternalsWritableStreamDefaultControllerErrorCodeLength = 203; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerErrorCode = "(function (h,b){\"use strict\";const i=@getByIdDirectPrivate(h,\"stream\");@assert(i!==@undefined),@assert(@getByIdDirectPrivate(i,\"state\")===\"writable\"),@writableStreamDefaultControllerClearAlgorithms(h),@writableStreamStartErroring(i,b)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerErrorCode = "(function (controller,error){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"stream\");@writableStreamDefaultControllerClearAlgorithms(controller),@writableStreamStartErroring(stream,error)})\n"; // writableStreamDefaultControllerErrorIfNeeded const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCodeLength = 165; +const int s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCodeLength = 210; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCode = "(function (d,h){\"use strict\";const i=@getByIdDirectPrivate(d,\"stream\");if(@getByIdDirectPrivate(i,\"state\")===\"writable\")@writableStreamDefaultControllerError(d,h)})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerErrorIfNeededCode = "(function (controller,error){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"stream\");if(@getByIdDirectPrivate(stream,\"state\")===\"writable\")@writableStreamDefaultControllerError(controller,error)})\n"; // writableStreamDefaultControllerGetBackpressure const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCodeLength = 89; +const int s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCodeLength = 107; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCode = "(function (d){\"use strict\";return @writableStreamDefaultControllerGetDesiredSize(d)<=0})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerGetBackpressureCode = "(function (controller){\"use strict\";return @writableStreamDefaultControllerGetDesiredSize(controller)<=0})\n"; // writableStreamDefaultControllerGetChunkSize const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCodeLength = 181; +const int s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCodeLength = 216; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCode = "(function (a,i){\"use strict\";try{return @getByIdDirectPrivate(a,\"strategySizeAlgorithm\").@call(@undefined,i)}catch(d){return @writableStreamDefaultControllerErrorIfNeeded(a,d),1}})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerGetChunkSizeCode = "(function (controller,chunk){\"use strict\";try{return @getByIdDirectPrivate(controller,\"strategySizeAlgorithm\").@call(@undefined,chunk)}catch(e){return @writableStreamDefaultControllerErrorIfNeeded(controller,e),1}})\n"; // writableStreamDefaultControllerGetDesiredSize const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCodeLength = 113; +const int s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCodeLength = 140; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCode = "(function (i){\"use strict\";return @getByIdDirectPrivate(i,\"strategyHWM\")-@getByIdDirectPrivate(i,\"queue\").size})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerGetDesiredSizeCode = "(function (controller){\"use strict\";return @getByIdDirectPrivate(controller,\"strategyHWM\")-@getByIdDirectPrivate(controller,\"queue\").size})\n"; // writableStreamDefaultControllerProcessClose const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCodeLength = 441; +const int s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCodeLength = 485; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCode = "(function (i){\"use strict\";const _=@getByIdDirectPrivate(i,\"stream\");@writableStreamMarkCloseRequestInFlight(_),@dequeueValue(@getByIdDirectPrivate(i,\"queue\")),@assert(@getByIdDirectPrivate(i,\"queue\").content\?.isEmpty());const d=@getByIdDirectPrivate(i,\"closeAlgorithm\").@call();@writableStreamDefaultControllerClearAlgorithms(i),d.@then(()=>{@writableStreamFinishInFlightClose(_)},(h)=>{@writableStreamFinishInFlightCloseWithError(_,h)})})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerProcessCloseCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"stream\");@writableStreamMarkCloseRequestInFlight(stream),@dequeueValue(@getByIdDirectPrivate(controller,\"queue\"));const sinkClosePromise=@getByIdDirectPrivate(controller,\"closeAlgorithm\").@call();@writableStreamDefaultControllerClearAlgorithms(controller),sinkClosePromise.@then(()=>{@writableStreamFinishInFlightClose(stream)},(reason)=>{@writableStreamFinishInFlightCloseWithError(stream,reason)})})\n"; // writableStreamDefaultControllerProcessWrite const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCodeLength = 734; +const int s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCodeLength = 845; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCode = "(function (d,v){\"use strict\";const i=@getByIdDirectPrivate(d,\"stream\");@writableStreamMarkFirstWriteRequestInFlight(i),@getByIdDirectPrivate(d,\"writeAlgorithm\").@call(@undefined,v).@then(()=>{@writableStreamFinishInFlightWrite(i);const _=@getByIdDirectPrivate(i,\"state\");if(@assert(_===\"writable\"||_===\"erroring\"),@dequeueValue(@getByIdDirectPrivate(d,\"queue\")),!@writableStreamCloseQueuedOrInFlight(i)&&_===\"writable\"){const q=@writableStreamDefaultControllerGetBackpressure(d);@writableStreamUpdateBackpressure(i,q)}@writableStreamDefaultControllerAdvanceQueueIfNeeded(d)},(_)=>{if(@getByIdDirectPrivate(i,\"state\")===\"writable\")@writableStreamDefaultControllerClearAlgorithms(d);@writableStreamFinishInFlightWriteWithError(i,_)})})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerProcessWriteCode = "(function (controller,chunk){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"stream\");@writableStreamMarkFirstWriteRequestInFlight(stream),@getByIdDirectPrivate(controller,\"writeAlgorithm\").@call(@undefined,chunk).@then(()=>{@writableStreamFinishInFlightWrite(stream);const state=@getByIdDirectPrivate(stream,\"state\");if(@dequeueValue(@getByIdDirectPrivate(controller,\"queue\")),!@writableStreamCloseQueuedOrInFlight(stream)&&state===\"writable\"){const backpressure=@writableStreamDefaultControllerGetBackpressure(controller);@writableStreamUpdateBackpressure(stream,backpressure)}@writableStreamDefaultControllerAdvanceQueueIfNeeded(controller)},(reason)=>{if(@getByIdDirectPrivate(stream,\"state\")===\"writable\")@writableStreamDefaultControllerClearAlgorithms(controller);@writableStreamFinishInFlightWriteWithError(stream,reason)})})\n"; // writableStreamDefaultControllerWrite const JSC::ConstructAbility s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeLength = 450; +const int s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeLength = 578; static const JSC::Intrinsic s_writableStreamInternalsWritableStreamDefaultControllerWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamInternalsWritableStreamDefaultControllerWriteCode = "(function (d,B,D){\"use strict\";try{@enqueueValueWithSize(@getByIdDirectPrivate(d,\"queue\"),B,D);const y=@getByIdDirectPrivate(d,\"stream\"),I=@getByIdDirectPrivate(y,\"state\");if(!@writableStreamCloseQueuedOrInFlight(y)&&I===\"writable\"){const _=@writableStreamDefaultControllerGetBackpressure(d);@writableStreamUpdateBackpressure(y,_)}@writableStreamDefaultControllerAdvanceQueueIfNeeded(d)}catch(y){@writableStreamDefaultControllerErrorIfNeeded(d,y)}})\n"; +const char* const s_writableStreamInternalsWritableStreamDefaultControllerWriteCode = "(function (controller,chunk,chunkSize){\"use strict\";try{@enqueueValueWithSize(@getByIdDirectPrivate(controller,\"queue\"),chunk,chunkSize);const stream=@getByIdDirectPrivate(controller,\"stream\"),state=@getByIdDirectPrivate(stream,\"state\");if(!@writableStreamCloseQueuedOrInFlight(stream)&&state===\"writable\"){const backpressure=@writableStreamDefaultControllerGetBackpressure(controller);@writableStreamUpdateBackpressure(stream,backpressure)}@writableStreamDefaultControllerAdvanceQueueIfNeeded(controller)}catch(e){@writableStreamDefaultControllerErrorIfNeeded(controller,e)}})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -484,145 +484,145 @@ WEBCORE_FOREACH_WRITABLESTREAMINTERNALS_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_transformStreamInternalsIsTransformStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsIsTransformStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsIsTransformStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsIsTransformStreamCodeLength = 88; +const int s_transformStreamInternalsIsTransformStreamCodeLength = 103; static const JSC::Intrinsic s_transformStreamInternalsIsTransformStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsIsTransformStreamCode = "(function (d){\"use strict\";return @isObject(d)&&!!@getByIdDirectPrivate(d,\"readable\")})\n"; +const char* const s_transformStreamInternalsIsTransformStreamCode = "(function (stream){\"use strict\";return @isObject(stream)&&!!@getByIdDirectPrivate(stream,\"readable\")})\n"; // isTransformStreamDefaultController const JSC::ConstructAbility s_transformStreamInternalsIsTransformStreamDefaultControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsIsTransformStreamDefaultControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsIsTransformStreamDefaultControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsIsTransformStreamDefaultControllerCodeLength = 98; +const int s_transformStreamInternalsIsTransformStreamDefaultControllerCodeLength = 125; static const JSC::Intrinsic s_transformStreamInternalsIsTransformStreamDefaultControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsIsTransformStreamDefaultControllerCode = "(function (a){\"use strict\";return @isObject(a)&&!!@getByIdDirectPrivate(a,\"transformAlgorithm\")})\n"; +const char* const s_transformStreamInternalsIsTransformStreamDefaultControllerCode = "(function (controller){\"use strict\";return @isObject(controller)&&!!@getByIdDirectPrivate(controller,\"transformAlgorithm\")})\n"; // createTransformStream const JSC::ConstructAbility s_transformStreamInternalsCreateTransformStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsCreateTransformStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsCreateTransformStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsCreateTransformStreamCodeLength = 510; +const int s_transformStreamInternalsCreateTransformStreamCodeLength = 1042; static const JSC::Intrinsic s_transformStreamInternalsCreateTransformStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsCreateTransformStreamCode = "(function (D,E,F,_,j,c,q){\"use strict\";if(_===@undefined)_=1;if(j===@undefined)j=()=>1;if(c===@undefined)c=0;if(q===@undefined)q=()=>1;@assert(_>=0),@assert(c>=0);const B={};@putByIdDirectPrivate(B,\"TransformStream\",!0);const v=new @TransformStream(B),x=@newPromiseCapability(@Promise);@initializeTransformStream(v,x.promise,_,j,c,q);const G=new @TransformStreamDefaultController;return @setUpTransformStreamDefaultController(v,G,E,F),D().@then(()=>{x.resolve.@call()},(I)=>{x.reject.@call(@undefined,I)}),v})\n"; +const char* const s_transformStreamInternalsCreateTransformStreamCode = "(function (startAlgorithm,transformAlgorithm,flushAlgorithm,writableHighWaterMark,writableSizeAlgorithm,readableHighWaterMark,readableSizeAlgorithm){\"use strict\";if(writableHighWaterMark===@undefined)writableHighWaterMark=1;if(writableSizeAlgorithm===@undefined)writableSizeAlgorithm=()=>1;if(readableHighWaterMark===@undefined)readableHighWaterMark=0;if(readableSizeAlgorithm===@undefined)readableSizeAlgorithm=()=>1;const transform={};@putByIdDirectPrivate(transform,\"TransformStream\",!0);const stream=new @TransformStream(transform),startPromiseCapability=@newPromiseCapability(@Promise);@initializeTransformStream(stream,startPromiseCapability.promise,writableHighWaterMark,writableSizeAlgorithm,readableHighWaterMark,readableSizeAlgorithm);const controller=new @TransformStreamDefaultController;return @setUpTransformStreamDefaultController(stream,controller,transformAlgorithm,flushAlgorithm),startAlgorithm().@then(()=>{startPromiseCapability.resolve.@call()},(error)=>{startPromiseCapability.reject.@call(@undefined,error)}),stream})\n"; // initializeTransformStream const JSC::ConstructAbility s_transformStreamInternalsInitializeTransformStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsInitializeTransformStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsInitializeTransformStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsInitializeTransformStreamCodeLength = 1015; +const int s_transformStreamInternalsInitializeTransformStreamCodeLength = 1593; static const JSC::Intrinsic s_transformStreamInternalsInitializeTransformStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsInitializeTransformStreamCode = "(function (f,x,C,D,E,F){\"use strict\";const q=()=>{return x},G=(B)=>{return @transformStreamDefaultSinkWriteAlgorithm(f,B)},I=(B)=>{return @transformStreamDefaultSinkAbortAlgorithm(f,B)},J=()=>{return @transformStreamDefaultSinkCloseAlgorithm(f)},v=@createWritableStream(q,G,J,I,C,D),K=()=>{return @transformStreamDefaultSourcePullAlgorithm(f)},L=(B)=>{return @transformStreamErrorWritableAndUnblockWrite(f,B),@Promise.@resolve()},T={};@putByIdDirectPrivate(T,\"start\",q),@putByIdDirectPrivate(T,\"pull\",K),@putByIdDirectPrivate(T,\"cancel\",L);const j={};@putByIdDirectPrivate(j,\"size\",F),@putByIdDirectPrivate(j,\"highWaterMark\",E);const N=new @ReadableStream(T,j);@putByIdDirectPrivate(f,\"writable\",v),@putByIdDirectPrivate(f,\"internalWritable\",@getInternalWritableStream(v)),@putByIdDirectPrivate(f,\"readable\",N),@putByIdDirectPrivate(f,\"backpressure\",@undefined),@putByIdDirectPrivate(f,\"backpressureChangePromise\",@undefined),@transformStreamSetBackpressure(f,!0),@putByIdDirectPrivate(f,\"controller\",@undefined)})\n"; +const char* const s_transformStreamInternalsInitializeTransformStreamCode = "(function (stream,startPromise,writableHighWaterMark,writableSizeAlgorithm,readableHighWaterMark,readableSizeAlgorithm){\"use strict\";const startAlgorithm=()=>{return startPromise},writeAlgorithm=(chunk)=>{return @transformStreamDefaultSinkWriteAlgorithm(stream,chunk)},abortAlgorithm=(reason)=>{return @transformStreamDefaultSinkAbortAlgorithm(stream,reason)},closeAlgorithm=()=>{return @transformStreamDefaultSinkCloseAlgorithm(stream)},writable=@createWritableStream(startAlgorithm,writeAlgorithm,closeAlgorithm,abortAlgorithm,writableHighWaterMark,writableSizeAlgorithm),pullAlgorithm=()=>{return @transformStreamDefaultSourcePullAlgorithm(stream)},cancelAlgorithm=(reason)=>{return @transformStreamErrorWritableAndUnblockWrite(stream,reason),@Promise.@resolve()},underlyingSource={};@putByIdDirectPrivate(underlyingSource,\"start\",startAlgorithm),@putByIdDirectPrivate(underlyingSource,\"pull\",pullAlgorithm),@putByIdDirectPrivate(underlyingSource,\"cancel\",cancelAlgorithm);const options={};@putByIdDirectPrivate(options,\"size\",readableSizeAlgorithm),@putByIdDirectPrivate(options,\"highWaterMark\",readableHighWaterMark);const readable=new @ReadableStream(underlyingSource,options);@putByIdDirectPrivate(stream,\"writable\",writable),@putByIdDirectPrivate(stream,\"internalWritable\",@getInternalWritableStream(writable)),@putByIdDirectPrivate(stream,\"readable\",readable),@putByIdDirectPrivate(stream,\"backpressure\",@undefined),@putByIdDirectPrivate(stream,\"backpressureChangePromise\",@undefined),@transformStreamSetBackpressure(stream,!0),@putByIdDirectPrivate(stream,\"controller\",@undefined)})\n"; // transformStreamError const JSC::ConstructAbility s_transformStreamInternalsTransformStreamErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamErrorCodeLength = 222; +const int s_transformStreamInternalsTransformStreamErrorCodeLength = 285; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamErrorCode = "(function (f,i){\"use strict\";const n=@getByIdDirectPrivate(f,\"readable\"),_=@getByIdDirectPrivate(n,\"readableStreamController\");@readableStreamDefaultControllerError(_,i),@transformStreamErrorWritableAndUnblockWrite(f,i)})\n"; +const char* const s_transformStreamInternalsTransformStreamErrorCode = "(function (stream,e){\"use strict\";const readable=@getByIdDirectPrivate(stream,\"readable\"),readableController=@getByIdDirectPrivate(readable,\"readableStreamController\");@readableStreamDefaultControllerError(readableController,e),@transformStreamErrorWritableAndUnblockWrite(stream,e)})\n"; // transformStreamErrorWritableAndUnblockWrite const JSC::ConstructAbility s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCodeLength = 339; +const int s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCodeLength = 378; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCode = "(function (_,n){\"use strict\";@transformStreamDefaultControllerClearAlgorithms(@getByIdDirectPrivate(_,\"controller\"));const o=@getByIdDirectPrivate(_,\"internalWritable\");if(@writableStreamDefaultControllerErrorIfNeeded(@getByIdDirectPrivate(o,\"controller\"),n),@getByIdDirectPrivate(_,\"backpressure\"))@transformStreamSetBackpressure(_,!1)})\n"; +const char* const s_transformStreamInternalsTransformStreamErrorWritableAndUnblockWriteCode = "(function (stream,e){\"use strict\";@transformStreamDefaultControllerClearAlgorithms(@getByIdDirectPrivate(stream,\"controller\"));const writable=@getByIdDirectPrivate(stream,\"internalWritable\");if(@writableStreamDefaultControllerErrorIfNeeded(@getByIdDirectPrivate(writable,\"controller\"),e),@getByIdDirectPrivate(stream,\"backpressure\"))@transformStreamSetBackpressure(stream,!1)})\n"; // transformStreamSetBackpressure const JSC::ConstructAbility s_transformStreamInternalsTransformStreamSetBackpressureCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamSetBackpressureCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamSetBackpressureCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamSetBackpressureCodeLength = 308; +const int s_transformStreamInternalsTransformStreamSetBackpressureCodeLength = 369; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamSetBackpressureCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamSetBackpressureCode = "(function (_,d){\"use strict\";@assert(@getByIdDirectPrivate(_,\"backpressure\")!==d);const i=@getByIdDirectPrivate(_,\"backpressureChangePromise\");if(i!==@undefined)i.resolve.@call();@putByIdDirectPrivate(_,\"backpressureChangePromise\",@newPromiseCapability(@Promise)),@putByIdDirectPrivate(_,\"backpressure\",d)})\n"; +const char* const s_transformStreamInternalsTransformStreamSetBackpressureCode = "(function (stream,backpressure){\"use strict\";const backpressureChangePromise=@getByIdDirectPrivate(stream,\"backpressureChangePromise\");if(backpressureChangePromise!==@undefined)backpressureChangePromise.resolve.@call();@putByIdDirectPrivate(stream,\"backpressureChangePromise\",@newPromiseCapability(@Promise)),@putByIdDirectPrivate(stream,\"backpressure\",backpressure)})\n"; // setUpTransformStreamDefaultController const JSC::ConstructAbility s_transformStreamInternalsSetUpTransformStreamDefaultControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsSetUpTransformStreamDefaultControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsSetUpTransformStreamDefaultControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsSetUpTransformStreamDefaultControllerCodeLength = 294; +const int s_transformStreamInternalsSetUpTransformStreamDefaultControllerCodeLength = 323; static const JSC::Intrinsic s_transformStreamInternalsSetUpTransformStreamDefaultControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsSetUpTransformStreamDefaultControllerCode = "(function (d,P,_,b){\"use strict\";@assert(@isTransformStream(d)),@assert(@getByIdDirectPrivate(d,\"controller\")===@undefined),@putByIdDirectPrivate(P,\"stream\",d),@putByIdDirectPrivate(d,\"controller\",P),@putByIdDirectPrivate(P,\"transformAlgorithm\",_),@putByIdDirectPrivate(P,\"flushAlgorithm\",b)})\n"; +const char* const s_transformStreamInternalsSetUpTransformStreamDefaultControllerCode = "(function (stream,controller,transformAlgorithm,flushAlgorithm){\"use strict\";@putByIdDirectPrivate(controller,\"stream\",stream),@putByIdDirectPrivate(stream,\"controller\",controller),@putByIdDirectPrivate(controller,\"transformAlgorithm\",transformAlgorithm),@putByIdDirectPrivate(controller,\"flushAlgorithm\",flushAlgorithm)})\n"; // setUpTransformStreamDefaultControllerFromTransformer const JSC::ConstructAbility s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCodeLength = 443; +const int s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCodeLength = 704; static const JSC::Intrinsic s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCode = "(function (q,v,_){\"use strict\";const d=new @TransformStreamDefaultController;let b=(p)=>{try{@transformStreamDefaultControllerEnqueue(d,p)}catch(w){return @Promise.@reject(w)}return @Promise.@resolve()},j=()=>{return @Promise.@resolve()};if(\"transform\"in _)b=(p)=>{return @promiseInvokeOrNoopMethod(v,_.transform,[p,d])};if(\"flush\"in _)j=()=>{return @promiseInvokeOrNoopMethod(v,_.flush,[d])};@setUpTransformStreamDefaultController(q,d,b,j)})\n"; +const char* const s_transformStreamInternalsSetUpTransformStreamDefaultControllerFromTransformerCode = "(function (stream,transformer,transformerDict){\"use strict\";const controller=new @TransformStreamDefaultController;let transformAlgorithm=(chunk)=>{try{@transformStreamDefaultControllerEnqueue(controller,chunk)}catch(e){return @Promise.@reject(e)}return @Promise.@resolve()},flushAlgorithm=()=>{return @Promise.@resolve()};if(\"transform\"in transformerDict)transformAlgorithm=(chunk)=>{return @promiseInvokeOrNoopMethod(transformer,transformerDict.transform,[chunk,controller])};if(\"flush\"in transformerDict)flushAlgorithm=()=>{return @promiseInvokeOrNoopMethod(transformer,transformerDict.flush,[controller])};@setUpTransformStreamDefaultController(stream,controller,transformAlgorithm,flushAlgorithm)})\n"; // transformStreamDefaultControllerClearAlgorithms const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCodeLength = 131; +const int s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCodeLength = 158; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCode = "(function (_){\"use strict\";@putByIdDirectPrivate(_,\"transformAlgorithm\",!0),@putByIdDirectPrivate(_,\"flushAlgorithm\",@undefined)})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultControllerClearAlgorithmsCode = "(function (controller){\"use strict\";@putByIdDirectPrivate(controller,\"transformAlgorithm\",!0),@putByIdDirectPrivate(controller,\"flushAlgorithm\",@undefined)})\n"; // transformStreamDefaultControllerEnqueue const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCodeLength = 622; +const int s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCodeLength = 717; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCode = "(function (g,i){\"use strict\";const _=@getByIdDirectPrivate(g,\"stream\"),W=@getByIdDirectPrivate(_,\"readable\"),S=@getByIdDirectPrivate(W,\"readableStreamController\");if(@assert(S!==@undefined),!@readableStreamDefaultControllerCanCloseOrEnqueue(S))@throwTypeError(\"TransformStream.readable cannot close or enqueue\");try{@readableStreamDefaultControllerEnqueue(S,i)}catch(j){throw @transformStreamErrorWritableAndUnblockWrite(_,j),@getByIdDirectPrivate(W,\"storedError\")}const f=!@readableStreamDefaultControllerShouldCallPull(S);if(f!==@getByIdDirectPrivate(_,\"backpressure\"))@assert(f),@transformStreamSetBackpressure(_,!0)})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultControllerEnqueueCode = "(function (controller,chunk){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"stream\"),readable=@getByIdDirectPrivate(stream,\"readable\"),readableController=@getByIdDirectPrivate(readable,\"readableStreamController\");if(!@readableStreamDefaultControllerCanCloseOrEnqueue(readableController))@throwTypeError(\"TransformStream.readable cannot close or enqueue\");try{@readableStreamDefaultControllerEnqueue(readableController,chunk)}catch(e){throw @transformStreamErrorWritableAndUnblockWrite(stream,e),@getByIdDirectPrivate(readable,\"storedError\")}if(!@readableStreamDefaultControllerShouldCallPull(readableController)!==@getByIdDirectPrivate(stream,\"backpressure\"))@transformStreamSetBackpressure(stream,!0)})\n"; // transformStreamDefaultControllerError const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultControllerErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultControllerErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultControllerErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultControllerErrorCodeLength = 90; +const int s_transformStreamInternalsTransformStreamDefaultControllerErrorCodeLength = 108; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultControllerErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultControllerErrorCode = "(function (a,d){\"use strict\";@transformStreamError(@getByIdDirectPrivate(a,\"stream\"),d)})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultControllerErrorCode = "(function (controller,e){\"use strict\";@transformStreamError(@getByIdDirectPrivate(controller,\"stream\"),e)})\n"; // transformStreamDefaultControllerPerformTransform const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCodeLength = 275; +const int s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCodeLength = 373; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCode = "(function (d,g){\"use strict\";const _=@newPromiseCapability(@Promise);return @getByIdDirectPrivate(d,\"transformAlgorithm\").@call(@undefined,g).@then(()=>{_.@resolve()},(f)=>{@transformStreamError(@getByIdDirectPrivate(d,\"stream\"),f),_.reject.@call(@undefined,f)}),_.promise})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultControllerPerformTransformCode = "(function (controller,chunk){\"use strict\";const promiseCapability=@newPromiseCapability(@Promise);return @getByIdDirectPrivate(controller,\"transformAlgorithm\").@call(@undefined,chunk).@then(()=>{promiseCapability.resolve()},(r)=>{@transformStreamError(@getByIdDirectPrivate(controller,\"stream\"),r),promiseCapability.reject.@call(@undefined,r)}),promiseCapability.promise})\n"; // transformStreamDefaultControllerTerminate const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultControllerTerminateCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultControllerTerminateCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultControllerTerminateCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultControllerTerminateCodeLength = 367; +const int s_transformStreamInternalsTransformStreamDefaultControllerTerminateCodeLength = 473; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultControllerTerminateCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultControllerTerminateCode = "(function (f){\"use strict\";const i=@getByIdDirectPrivate(f,\"stream\"),k=@getByIdDirectPrivate(i,\"readable\"),_=@getByIdDirectPrivate(k,\"readableStreamController\");if(@readableStreamDefaultControllerCanCloseOrEnqueue(_))@readableStreamDefaultControllerClose(_);const u=@makeTypeError(\"the stream has been terminated\");@transformStreamErrorWritableAndUnblockWrite(i,u)})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultControllerTerminateCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"stream\"),readable=@getByIdDirectPrivate(stream,\"readable\"),readableController=@getByIdDirectPrivate(readable,\"readableStreamController\");if(@readableStreamDefaultControllerCanCloseOrEnqueue(readableController))@readableStreamDefaultControllerClose(readableController);const error=@makeTypeError(\"the stream has been terminated\");@transformStreamErrorWritableAndUnblockWrite(stream,error)})\n"; // transformStreamDefaultSinkWriteAlgorithm const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeLength = 759; +const int s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeLength = 816; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCode = "(function (d,q){\"use strict\";const j=@getByIdDirectPrivate(d,\"internalWritable\");@assert(@getByIdDirectPrivate(j,\"state\")===\"writable\");const v=@getByIdDirectPrivate(d,\"controller\");if(@getByIdDirectPrivate(d,\"backpressure\")){const _=@newPromiseCapability(@Promise),x=@getByIdDirectPrivate(d,\"backpressureChangePromise\");return @assert(x!==@undefined),x.promise.@then(()=>{const f=@getByIdDirectPrivate(j,\"state\");if(f===\"erroring\"){_.reject.@call(@undefined,@getByIdDirectPrivate(j,\"storedError\"));return}@assert(f===\"writable\"),@transformStreamDefaultControllerPerformTransform(v,q).@then(()=>{_.@resolve()},(z)=>{_.reject.@call(@undefined,z)})},(f)=>{_.reject.@call(@undefined,f)}),_.promise}return @transformStreamDefaultControllerPerformTransform(v,q)})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultSinkWriteAlgorithmCode = "(function (stream,chunk){\"use strict\";const writable=@getByIdDirectPrivate(stream,\"internalWritable\"),controller=@getByIdDirectPrivate(stream,\"controller\");if(@getByIdDirectPrivate(stream,\"backpressure\")){const promiseCapability=@newPromiseCapability(@Promise);return @getByIdDirectPrivate(stream,\"backpressureChangePromise\").promise.@then(()=>{if(@getByIdDirectPrivate(writable,\"state\")===\"erroring\"){promiseCapability.reject.@call(@undefined,@getByIdDirectPrivate(writable,\"storedError\"));return}@transformStreamDefaultControllerPerformTransform(controller,chunk).@then(()=>{promiseCapability.resolve()},(e)=>{promiseCapability.reject.@call(@undefined,e)})},(e)=>{promiseCapability.reject.@call(@undefined,e)}),promiseCapability.promise}return @transformStreamDefaultControllerPerformTransform(controller,chunk)})\n"; // transformStreamDefaultSinkAbortAlgorithm const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCodeLength = 85; +const int s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCodeLength = 105; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCode = "(function (d,t){\"use strict\";return @transformStreamError(d,t),@Promise.@resolve()})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultSinkAbortAlgorithmCode = "(function (stream,reason){\"use strict\";return @transformStreamError(stream,reason),@Promise.@resolve()})\n"; // transformStreamDefaultSinkCloseAlgorithm const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCodeLength = 786; +const int s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCodeLength = 1016; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCode = "(function (j){\"use strict\";const _=@getByIdDirectPrivate(j,\"readable\"),I=@getByIdDirectPrivate(j,\"controller\"),k=@getByIdDirectPrivate(_,\"readableStreamController\"),q=@getByIdDirectPrivate(I,\"flushAlgorithm\");@assert(q!==@undefined);const u=@getByIdDirectPrivate(I,\"flushAlgorithm\").@call();@transformStreamDefaultControllerClearAlgorithms(I);const S=@newPromiseCapability(@Promise);return u.@then(()=>{if(@getByIdDirectPrivate(_,\"state\")===@streamErrored){S.reject.@call(@undefined,@getByIdDirectPrivate(_,\"storedError\"));return}if(@readableStreamDefaultControllerCanCloseOrEnqueue(k))@readableStreamDefaultControllerClose(k);S.@resolve()},(v)=>{@transformStreamError(@getByIdDirectPrivate(I,\"stream\"),v),S.reject.@call(@undefined,@getByIdDirectPrivate(_,\"storedError\"))}),S.promise})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultSinkCloseAlgorithmCode = "(function (stream){\"use strict\";const readable=@getByIdDirectPrivate(stream,\"readable\"),controller=@getByIdDirectPrivate(stream,\"controller\"),readableController=@getByIdDirectPrivate(readable,\"readableStreamController\"),flushAlgorithm=@getByIdDirectPrivate(controller,\"flushAlgorithm\"),flushPromise=@getByIdDirectPrivate(controller,\"flushAlgorithm\").@call();@transformStreamDefaultControllerClearAlgorithms(controller);const promiseCapability=@newPromiseCapability(@Promise);return flushPromise.@then(()=>{if(@getByIdDirectPrivate(readable,\"state\")===@streamErrored){promiseCapability.reject.@call(@undefined,@getByIdDirectPrivate(readable,\"storedError\"));return}if(@readableStreamDefaultControllerCanCloseOrEnqueue(readableController))@readableStreamDefaultControllerClose(readableController);promiseCapability.resolve()},(r)=>{@transformStreamError(@getByIdDirectPrivate(controller,\"stream\"),r),promiseCapability.reject.@call(@undefined,@getByIdDirectPrivate(readable,\"storedError\"))}),promiseCapability.promise})\n"; // transformStreamDefaultSourcePullAlgorithm const JSC::ConstructAbility s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCodeLength = 259; +const int s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCodeLength = 150; static const JSC::Intrinsic s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCode = "(function (i){\"use strict\";return @assert(@getByIdDirectPrivate(i,\"backpressure\")),@assert(@getByIdDirectPrivate(i,\"backpressureChangePromise\")!==@undefined),@transformStreamSetBackpressure(i,!1),@getByIdDirectPrivate(i,\"backpressureChangePromise\").promise})\n"; +const char* const s_transformStreamInternalsTransformStreamDefaultSourcePullAlgorithmCode = "(function (stream){\"use strict\";return @transformStreamSetBackpressure(stream,!1),@getByIdDirectPrivate(stream,\"backpressureChangePromise\").promise})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -638,25 +638,25 @@ WEBCORE_FOREACH_TRANSFORMSTREAMINTERNALS_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_processObjectInternalsBindingCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_processObjectInternalsBindingCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_processObjectInternalsBindingCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_processObjectInternalsBindingCodeLength = 473; +const int s_processObjectInternalsBindingCodeLength = 511; static const JSC::Intrinsic s_processObjectInternalsBindingCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_processObjectInternalsBindingCode = "(function (u){\"use strict\";if(u!==\"constants\")@throwTypeError(\"process.binding() is not supported in Bun. If that breaks something, please file an issue and include a reproducible code sample.\");var p=globalThis.Symbol.for(\"process.bindings.constants\"),r=globalThis[p];if(!r){const{constants:I}=globalThis[globalThis.Symbol.for('Bun.lazy')](\"createImportMeta\",\"node:process\").require(\"node:fs\");r={fs:I,zlib:{},crypto:{},os:@Bun._Os().constants},globalThis[p]=r}return r})\n"; +const char* const s_processObjectInternalsBindingCode = "(function (bindingName){\"use strict\";if(bindingName===\"constants\")return @processBindingConstants;const issue={fs:3546,buffer:2020,natives:2254,uv:2891}[bindingName];if(issue)throw new Error(`process.binding(\"${bindingName}\") is not implemented in Bun. Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/${issue}`);@throwTypeError(`process.binding(\"${bindingName}\") is not implemented in Bun. If that breaks something, please file an issue and include a reproducible code sample.`)})\n"; // getStdioWriteStream 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 = 4505; +const int s_processObjectInternalsGetStdioWriteStreamCodeLength = 7529; static const JSC::Intrinsic s_processObjectInternalsGetStdioWriteStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_processObjectInternalsGetStdioWriteStreamCode = "(function (X,Z){\"use strict\";var N=(J)=>{var L=@requireMap.get(J);if(L)return L.exports;return @internalRequire(J)},I={path:\"node:process\",require:N};function q(J){var{Duplex:L,eos:j,destroy:B}=N(\"node:stream\"),K=class Q extends L{#j;#$;#N=!0;#O=!0;#J;#B;#L;#G;#H;#K;get isTTY(){return this.#K\?\?=N(\"node:tty\").isatty(J)}get fd(){return J}constructor(G){super({readable:!0,writable:!0});this.#J=`/dev/fd/${G}`}#M(G){const H=this.#B;if(this.#B=null,H)H(G);else if(G)this.destroy(G);else if(!this.#N&&!this.#O)this.destroy()}_destroy(G,H){if(!G&&this.#B!==null){var O=class P extends Error{code;name;constructor(V=\"The operation was aborted\",M=void 0){if(M!==void 0&&typeof M!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(M,null,2)}`);super(V,M);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};G=new O}if(this.#L=null,this.#G=null,this.#B===null)H(G);else{if(this.#B=H,this.#j)B(this.#j,G);if(this.#$)B(this.#$,G)}}_write(G,H,O){if(!this.#j){var{createWriteStream:P}=N(\"node:fs\"),V=this.#j=P(this.#J);V.on(\"finish\",()=>{if(this.#G){const M=this.#G;this.#G=null,M()}}),V.on(\"drain\",()=>{if(this.#L){const M=this.#L;this.#L=null,M()}}),j(V,(M)=>{if(this.#O=!1,M)B(V,M);this.#M(M)})}if(V.write(G,H))O();else this.#L=O}_final(G){this.#j&&this.#j.end(),this.#G=G}#Q(){var{createReadStream:G}=N(\"node:fs\"),H=this.#$=G(this.#J);return H.on(\"readable\",()=>{if(this.#H){const O=this.#H;this.#H=null,O()}else this.read()}),H.on(\"end\",()=>{this.push(null)}),j(H,(O)=>{if(this.#N=!1,O)B(H,O);this.#M(O)}),H}_read(){var G=this.#$;if(!G)G=this.#Q();while(!0){const H=G.read();if(H===null||!this.push(H))return}}};return new K(J)}var{EventEmitter:x}=N(\"node:events\");function Y(J){if(!J)return!0;var L=J.toLowerCase();return L===\"utf8\"||L===\"utf-8\"||L===\"buffer\"||L===\"binary\"}var T,U=[0,0],D=class J extends x{#j;#$;#N;#O;bytesWritten=0;setDefaultEncoding(L){if(this.#$||!Y(L))return this.#L(),this.#$.setDefaultEncoding(L)}#J(){switch(this.#j){case 1:{var L=@Bun.stdout.writer({highWaterMark:0});return L.unref(),L}case 2:{var L=@Bun.stderr.writer({highWaterMark:0});return L.unref(),L}default:throw new Error(\"Unsupported writer\")}}#B(){return this.#N\?\?=this.#J()}constructor(L){super();this.#j=L}get fd(){return this.#j}ref(){this.#B().ref()}unref(){this.#B().unref()}on(L,j){if(L===\"close\"||L===\"finish\")return this.#L(),this.#$.on(L,j);if(L===\"drain\")return super.on(\"drain\",j);if(L===\"error\")return super.on(\"error\",j);return super.on(L,j)}get _writableState(){return this.#L(),this.#$._writableState}get _readableState(){return this.#L(),this.#$._readableState}pipe(L){return this.#L(),this.#$.pipe(L)}unpipe(L){return this.#L(),this.#$.unpipe(L)}#L(){if(this.#$)return;this.#$=q(this.#j);const L=this.eventNames();for(let j of L)this.#$.on(j,(...B)=>{this.emit(j,...B)})}#G(L){var j=this.#B();const B=j.write(L);this.bytesWritten+=B;const K=j.flush(!1);return!!(B||K)}#H(L,j){if(!Y(j))return this.#L(),this.#$.write(L,j);return this.#G(L)}#K(L,j){if(j)this.emit(\"error\",j);try{L(j\?j:null)}catch(B){this.emit(\"error\",B)}}#M(L,j,B){if(!Y(j))return this.#L(),this.#$.write(L,j,B);var K=this.#B();const Q=K.write(L),G=K.flush(!0);if(G\?.then)return G.then(()=>{this.#K(B),this.emit(\"drain\")},(H)=>this.#K(B,H)),!1;return queueMicrotask(()=>{this.#K(B)}),!!(Q||G)}get isTTY(){return!1}write(L,j,B){const K=this._write(L,j,B);if(K)this.emit(\"drain\");return K}get hasColors(){return @Bun.tty[this.#j].hasColors}_write(L,j,B){var K=this.#$;if(K)return K.write(L,j,B);switch(arguments.length){case 0:{var Q=new Error(\"Invalid arguments\");throw Q.code=\"ERR_INVALID_ARG_TYPE\",Q}case 1:return this.#G(L);case 2:if(typeof j===\"function\")return this.#M(L,\"\",j);else if(typeof j===\"string\")return this.#H(L,j);default:{if(typeof j!==\"undefined\"&&typeof j!==\"string\"||typeof B!==\"undefined\"&&typeof B!==\"function\"){var Q=new Error(\"Invalid arguments\");throw Q.code=\"ERR_INVALID_ARG_TYPE\",Q}if(typeof B===\"undefined\")return this.#H(L,j);return this.#M(L,j,B)}}}destroy(){return this}end(){return this}};if(Z(X,U)){var C=class J extends D{get isTTY(){return!0}cursorTo(L,j,B){return(T\?\?=N(\"node:readline\")).cursorTo(this,L,j,B)}moveCursor(L,j,B){return(T\?\?=N(\"node:readline\")).moveCursor(this,L,j,B)}clearLine(L,j){return(T\?\?=N(\"node:readline\")).clearLine(this,L,j)}clearScreenDown(L){return(T\?\?=N(\"node:readline\")).clearScreenDown(this,L)}getWindowSize(){if(Z(X,U)===!0)return[U[0],U[1]]}get columns(){if(Z(X,U)===!0)return U[0]}get rows(){if(Z(X,U)===!0)return U[1]}};return new C(X)}return new D(X)})\n"; +const char* const s_processObjectInternalsGetStdioWriteStreamCode = "(function (fd_,getWindowSize){\"use strict\";var EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15);function createStdioWriteStream(fd_2){var{Duplex,eos,destroy}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),StdioWriteStream=class StdioWriteStream2 extends Duplex{#writeStream;#readStream;#readable=!0;#writable=!0;#fdPath;#onClose;#onDrain;#onFinish;#onReadable;#isTTY;get isTTY(){return this.#isTTY\?\?=@requireNativeModule(\"node:tty\").isatty(fd_2)}get fd(){return fd_2}constructor(fd){super({readable:!0,writable:!0});this.#fdPath=`/dev/fd/${fd}`}#onFinished(err){const cb=this.#onClose;if(this.#onClose=null,cb)cb(err);else if(err)this.destroy(err);else if(!this.#readable&&!this.#writable)this.destroy()}_destroy(err,callback){if(!err&&this.#onClose!==null){var AbortError=class AbortError2 extends Error{code;name;constructor(message=\"The operation was aborted\",options=void 0){if(options!==void 0&&typeof options!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(options,null,2)}`);super(message,options);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};err=new AbortError}if(this.#onDrain=null,this.#onFinish=null,this.#onClose===null)callback(err);else{if(this.#onClose=callback,this.#writeStream)destroy(this.#writeStream,err);if(this.#readStream)destroy(this.#readStream,err)}}_write(chunk,encoding,callback){if(!this.#writeStream){var{createWriteStream}=@getInternalField(@internalModuleRegistry,16)||@createInternalModuleById(16),stream=this.#writeStream=createWriteStream(this.#fdPath);stream.on(\"finish\",()=>{if(this.#onFinish){const cb=this.#onFinish;this.#onFinish=null,cb()}}),stream.on(\"drain\",()=>{if(this.#onDrain){const cb=this.#onDrain;this.#onDrain=null,cb()}}),eos(stream,(err)=>{if(this.#writable=!1,err)destroy(stream,err);this.#onFinished(err)})}if(stream.write(chunk,encoding))callback();else this.#onDrain=callback}_final(callback){this.#writeStream&&this.#writeStream.end(),this.#onFinish=callback}#loadReadStream(){var{createReadStream}=@getInternalField(@internalModuleRegistry,16)||@createInternalModuleById(16),readStream=this.#readStream=createReadStream(this.#fdPath);return readStream.on(\"readable\",()=>{if(this.#onReadable){const cb=this.#onReadable;this.#onReadable=null,cb()}else this.read()}),readStream.on(\"end\",()=>{this.push(null)}),eos(readStream,(err)=>{if(this.#readable=!1,err)destroy(readStream,err);this.#onFinished(err)}),readStream}_read(){var stream=this.#readStream;if(!stream)stream=this.#loadReadStream();while(!0){const buf=stream.read();if(buf===null||!this.push(buf))return}}};return new StdioWriteStream(fd_2)}function isFastEncoding(encoding){if(!encoding)return!0;var normalied=encoding.toLowerCase();return normalied===\"utf8\"||normalied===\"utf-8\"||normalied===\"buffer\"||normalied===\"binary\"}var readline,windowSizeArray=[0,0],FastStdioWriteStreamInternal=class StdioWriteStream extends EventEmitter{#fd;#innerStream;#writer;#isTTY;bytesWritten=0;setDefaultEncoding(encoding){if(this.#innerStream||!isFastEncoding(encoding))return this.#ensureInnerStream(),this.#innerStream.setDefaultEncoding(encoding)}#createWriter(){switch(this.#fd){case 1:{var writer=@Bun.stdout.writer({highWaterMark:0});return writer.unref(),writer}case 2:{var writer=@Bun.stderr.writer({highWaterMark:0});return writer.unref(),writer}default:throw new Error(\"Unsupported writer\")}}#getWriter(){return this.#writer\?\?=this.#createWriter()}constructor(fd_2){super();this.#fd=fd_2}get fd(){return this.#fd}ref(){this.#getWriter().ref()}unref(){this.#getWriter().unref()}on(event,listener){if(event===\"close\"||event===\"finish\")return this.#ensureInnerStream(),this.#innerStream.on(event,listener);if(event===\"drain\")return super.on(\"drain\",listener);if(event===\"error\")return super.on(\"error\",listener);return super.on(event,listener)}get _writableState(){return this.#ensureInnerStream(),this.#innerStream._writableState}get _readableState(){return this.#ensureInnerStream(),this.#innerStream._readableState}pipe(destination){return this.#ensureInnerStream(),this.#innerStream.pipe(destination)}unpipe(destination){return this.#ensureInnerStream(),this.#innerStream.unpipe(destination)}#ensureInnerStream(){if(this.#innerStream)return;this.#innerStream=createStdioWriteStream(this.#fd);const events=this.eventNames();for(let event of events)this.#innerStream.on(event,(...args)=>{this.emit(event,...args)})}#write1(chunk){var writer=this.#getWriter();const writeResult=writer.write(chunk);this.bytesWritten+=writeResult;const flushResult=writer.flush(!1);return!!(writeResult||flushResult)}#writeWithEncoding(chunk,encoding){if(!isFastEncoding(encoding))return this.#ensureInnerStream(),this.#innerStream.write(chunk,encoding);return this.#write1(chunk)}#performCallback(cb,err){if(err)this.emit(\"error\",err);try{cb(err\?err:null)}catch(err2){this.emit(\"error\",err2)}}#writeWithCallbackAndEncoding(chunk,encoding,callback){if(!isFastEncoding(encoding))return this.#ensureInnerStream(),this.#innerStream.write(chunk,encoding,callback);var writer=this.#getWriter();const writeResult=writer.write(chunk),flushResult=writer.flush(!0);if(flushResult\?.then)return flushResult.then(()=>{this.#performCallback(callback),this.emit(\"drain\")},(err)=>this.#performCallback(callback,err)),!1;return queueMicrotask(()=>{this.#performCallback(callback)}),!!(writeResult||flushResult)}get isTTY(){return!1}write(chunk,encoding,callback){const result=this._write(chunk,encoding,callback);if(result)this.emit(\"drain\");return result}get hasColors(){return @Bun.tty[this.#fd].hasColors}_write(chunk,encoding,callback){var inner=this.#innerStream;if(inner)return inner.write(chunk,encoding,callback);switch(arguments.length){case 0:{var error=new Error(\"Invalid arguments\");throw error.code=\"ERR_INVALID_ARG_TYPE\",error}case 1:return this.#write1(chunk);case 2:if(typeof encoding===\"function\")return this.#writeWithCallbackAndEncoding(chunk,\"\",encoding);else if(typeof encoding===\"string\")return this.#writeWithEncoding(chunk,encoding);default:{if(typeof encoding!==\"undefined\"&&typeof encoding!==\"string\"||typeof callback!==\"undefined\"&&typeof callback!==\"function\"){var error=new Error(\"Invalid arguments\");throw error.code=\"ERR_INVALID_ARG_TYPE\",error}if(typeof callback===\"undefined\")return this.#writeWithEncoding(chunk,encoding);return this.#writeWithCallbackAndEncoding(chunk,encoding,callback)}}}destroy(){return this}end(){return this}};if(getWindowSize(fd_,windowSizeArray)){var WriteStream=class WriteStream2 extends FastStdioWriteStreamInternal{get isTTY(){return!0}cursorTo(x,y,callback){return(readline\?\?=@getInternalField(@internalModuleRegistry,30)||@createInternalModuleById(30)).cursorTo(this,x,y,callback)}moveCursor(dx,dy,callback){return(readline\?\?=@getInternalField(@internalModuleRegistry,30)||@createInternalModuleById(30)).moveCursor(this,dx,dy,callback)}clearLine(dir,callback){return(readline\?\?=@getInternalField(@internalModuleRegistry,30)||@createInternalModuleById(30)).clearLine(this,dir,callback)}clearScreenDown(callback){return(readline\?\?=@getInternalField(@internalModuleRegistry,30)||@createInternalModuleById(30)).clearScreenDown(this,callback)}getWindowSize(){if(getWindowSize(fd_,windowSizeArray)===!0)return[windowSizeArray[0],windowSizeArray[1]]}get columns(){if(getWindowSize(fd_,windowSizeArray)===!0)return windowSizeArray[0]}get rows(){if(getWindowSize(fd_,windowSizeArray)===!0)return windowSizeArray[1]}};return new WriteStream(fd_)}return new FastStdioWriteStreamInternal(fd_)})\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 = 1866; +const int s_processObjectInternalsGetStdinStreamCodeLength = 2702; static const JSC::Intrinsic s_processObjectInternalsGetStdinStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_processObjectInternalsGetStdinStreamCode = "(function (L){\"use strict\";var H=(J)=>{var j=@requireMap.get(J);if(j)return j.exports;return @internalRequire(J)},T={path:\"node:process\",require:H},{Duplex:N,eos:P,destroy:M}=H(\"node:stream\"),Q=class J extends N{#K;#I;#$;#G=!0;#H=!1;#L=!0;#z;#j;#B;get isTTY(){return H(\"node:tty\").isatty(L)}get fd(){return L}constructor(){super({readable:!0,writable:!0})}#J(j){const I=this.#j;if(this.#j=null,I)I(j);else if(j)this.destroy(j);else if(!this.#G&&!this.#L)this.destroy()}_destroy(j,I){if(!j&&this.#j!==null){var z=class B extends Error{constructor(G=\"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(G,K);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};j=new z}if(this.#j===null)I(j);else if(this.#j=I,this.#$)M(this.#$,j)}setRawMode(j){}on(j,I){if(j===\"readable\")this.ref(),this.#H=!0;return super.on(j,I)}pause(){return this.unref(),super.pause()}resume(){return this.ref(),super.resume()}ref(){this.#K\?\?=@Bun.stdin.stream().getReader(),this.#I\?\?=setInterval(()=>{},1<<30)}unref(){if(this.#I)clearInterval(this.#I),this.#I=null}async#M(){try{var j,I;const z=this.#K.readMany();if(!z\?.then)({done:j,value:I}=z);else({done:j,value:I}=await z);if(!j){this.push(I[0]);const B=I.length;for(let G=1;G{if(this.#z){const z=this.#z;this.#z=null,z()}}),I.on(\"drain\",()=>{if(this.#B){const z=this.#B;this.#B=null,z()}}),P(I,(z)=>{if(this.#L=!1,z)M(I,z);this.#J(z)}),I}_write(j,I,z){var B=this.#$;if(!B)B=this.#N();if(B.write(j,I))z();else this.#B=z}_final(j){this.#$.end(),this.#z=(...I)=>j(...I)}};return new Q})\n"; +const char* const s_processObjectInternalsGetStdinStreamCode = "(function (fd_){\"use strict\";var{Duplex,eos,destroy}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),StdinStream=class StdinStream2 extends Duplex{#reader;#readRef;#writeStream;#readable=!0;#unrefOnRead=!1;#writable=!0;#onFinish;#onClose;#onDrain;get isTTY(){return @requireNativeModule(\"node:tty\").isatty(fd_)}get fd(){return fd_}constructor(){super({readable:!0,writable:!0})}#onFinished(err){const cb=this.#onClose;if(this.#onClose=null,cb)cb(err);else if(err)this.destroy(err);else if(!this.#readable&&!this.#writable)this.destroy()}_destroy(err,callback){if(!err&&this.#onClose!==null){var AbortError=class AbortError2 extends Error{constructor(message=\"The operation was aborted\",options=void 0){if(options!==void 0&&typeof options!==\"object\")throw new Error(`Invalid AbortError options:\\n\\n${JSON.stringify(options,null,2)}`);super(message,options);this.code=\"ABORT_ERR\",this.name=\"AbortError\"}};err=new AbortError}if(this.#onClose===null)callback(err);else if(this.#onClose=callback,this.#writeStream)destroy(this.#writeStream,err)}setRawMode(mode){}on(name,callback){if(name===\"readable\")this.ref(),this.#unrefOnRead=!0;return super.on(name,callback)}pause(){return this.unref(),super.pause()}resume(){return this.ref(),super.resume()}ref(){this.#reader\?\?=@Bun.stdin.stream().getReader(),this.#readRef\?\?=setInterval(()=>{},1<<30)}unref(){if(this.#readRef)clearInterval(this.#readRef),this.#readRef=null}async#readInternal(){try{var done,value;const read=this.#reader.readMany();if(!read\?.then)({done,value}=read);else({done,value}=await read);if(!done){this.push(value[0]);const length=value.length;for(let i=1;i{if(this.#onFinish){const cb=this.#onFinish;this.#onFinish=null,cb()}}),writeStream.on(\"drain\",()=>{if(this.#onDrain){const cb=this.#onDrain;this.#onDrain=null,cb()}}),eos(writeStream,(err)=>{if(this.#writable=!1,err)destroy(writeStream,err);this.#onFinished(err)}),writeStream}_write(chunk,encoding,callback){var writeStream=this.#writeStream;if(!writeStream)writeStream=this.#constructWriteStream();if(writeStream.write(chunk,encoding))callback();else this.#onDrain=callback}_final(callback){this.#writeStream.end(),this.#onFinish=(...args)=>callback(...args)}};return new StdinStream})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -672,9 +672,9 @@ WEBCORE_FOREACH_PROCESSOBJECTINTERNALS_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_transformStreamInitializeTransformStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamInitializeTransformStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamInitializeTransformStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamInitializeTransformStreamCodeLength = 1300; +const int s_transformStreamInitializeTransformStreamCodeLength = 2041; static const JSC::Intrinsic s_transformStreamInitializeTransformStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamInitializeTransformStreamCode = "(function (){\"use strict\";let _=arguments[0];if(@isObject(_)&&@getByIdDirectPrivate(_,\"TransformStream\"))return this;let u=arguments[1],U=arguments[2];if(_===@undefined)_=null;if(U===@undefined)U={};if(u===@undefined)u={};let j={};if(_!==null){if(\"start\"in _){if(j.start=_.start,typeof j.start!==\"function\")@throwTypeError(\"transformer.start should be a function\")}if(\"transform\"in _){if(j.transform=_.transform,typeof j.transform!==\"function\")@throwTypeError(\"transformer.transform should be a function\")}if(\"flush\"in _){if(j.flush=_.flush,typeof j.flush!==\"function\")@throwTypeError(\"transformer.flush should be a function\")}if(\"readableType\"in _)@throwRangeError(\"TransformStream transformer has a readableType\");if(\"writableType\"in _)@throwRangeError(\"TransformStream transformer has a writableType\")}const v=@extractHighWaterMark(U,0),x=@extractSizeAlgorithm(U),B=@extractHighWaterMark(u,1),E=@extractSizeAlgorithm(u),q=@newPromiseCapability(@Promise);if(@initializeTransformStream(this,q.promise,B,E,v,x),@setUpTransformStreamDefaultControllerFromTransformer(this,_,j),(\"start\"in j)){const F=@getByIdDirectPrivate(this,\"controller\");(()=>@promiseInvokeOrNoopMethodNoCatch(_,j.start,[F]))().@then(()=>{q.resolve.@call()},(G)=>{q.reject.@call(@undefined,G)})}else q.resolve.@call();return this})\n"; +const char* const s_transformStreamInitializeTransformStreamCode = "(function (){\"use strict\";let transformer=arguments[0];if(@isObject(transformer)&&@getByIdDirectPrivate(transformer,\"TransformStream\"))return this;let writableStrategy=arguments[1],readableStrategy=arguments[2];if(transformer===@undefined)transformer=null;if(readableStrategy===@undefined)readableStrategy={};if(writableStrategy===@undefined)writableStrategy={};let transformerDict={};if(transformer!==null){if(\"start\"in transformer){if(transformerDict.start=transformer.start,typeof transformerDict.start!==\"function\")@throwTypeError(\"transformer.start should be a function\")}if(\"transform\"in transformer){if(transformerDict.transform=transformer.transform,typeof transformerDict.transform!==\"function\")@throwTypeError(\"transformer.transform should be a function\")}if(\"flush\"in transformer){if(transformerDict.flush=transformer.flush,typeof transformerDict.flush!==\"function\")@throwTypeError(\"transformer.flush should be a function\")}if(\"readableType\"in transformer)@throwRangeError(\"TransformStream transformer has a readableType\");if(\"writableType\"in transformer)@throwRangeError(\"TransformStream transformer has a writableType\")}const readableHighWaterMark=@extractHighWaterMark(readableStrategy,0),readableSizeAlgorithm=@extractSizeAlgorithm(readableStrategy),writableHighWaterMark=@extractHighWaterMark(writableStrategy,1),writableSizeAlgorithm=@extractSizeAlgorithm(writableStrategy),startPromiseCapability=@newPromiseCapability(@Promise);if(@initializeTransformStream(this,startPromiseCapability.promise,writableHighWaterMark,writableSizeAlgorithm,readableHighWaterMark,readableSizeAlgorithm),@setUpTransformStreamDefaultControllerFromTransformer(this,transformer,transformerDict),(\"start\"in transformerDict)){const controller=@getByIdDirectPrivate(this,\"controller\");(()=>@promiseInvokeOrNoopMethodNoCatch(transformer,transformerDict.start,[controller]))().@then(()=>{startPromiseCapability.resolve.@call()},(error)=>{startPromiseCapability.reject.@call(@undefined,error)})}else startPromiseCapability.resolve.@call();return this})\n"; // readable const JSC::ConstructAbility s_transformStreamReadableCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -714,17 +714,25 @@ const char* const s_moduleMainCode = "(function (){\"use strict\";return @requir const JSC::ConstructAbility s_moduleRequireCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_moduleRequireCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_moduleRequireCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_moduleRequireCodeLength = 1035; +const int s_moduleRequireCodeLength = 769; static const JSC::Intrinsic s_moduleRequireCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_moduleRequireCode = "(function (_){\"use strict\";const b=@requireMap.@get(_)||@requireMap.@get(_=@resolveSync(_,this.path,!1));if(b)return @evaluateCommonJSModule(b),b.exports;if(_.endsWith(\".json\")||_.endsWith(\".toml\")||_.endsWith(\".node\"))return @internalRequire(_);let S=@Loader.registry.@get(_);if(S\?.evaluated&&(S.state\?\?0)>=@ModuleReady){const M=S.module,f=@Loader.getModuleNamespaceObject(M),r=f\?.[@commonJSSymbol]===0||f\?.default\?.[@commonJSSymbol]===0\?f.default:f.__esModule\?f:Object.create(f,{__esModule:{value:!0}});return @requireMap.@set(_,@createCommonJSModule(_,r,!0)),r}const L=@createCommonJSModule(_,{},!1);@requireMap.@set(_,L);var h=this.@require(_,L);if(h===-1){try{h=@requireESM(_)}catch(M){throw @requireMap.@delete(_),M}if(S=@Loader.registry.@get(_),S\?.evaluated&&(S.state\?\?0)>=@ModuleReady){const M=@Loader.getModuleNamespaceObject(S.module);return L.exports=M\?.[@commonJSSymbol]===0||M\?.default\?.[@commonJSSymbol]===0\?M.default:M.__esModule\?M:Object.create(M,{__esModule:{value:!0}})}}return @evaluateCommonJSModule(L),L.exports})\n"; +const char* const s_moduleRequireCode = "(function (id){\"use strict\";const existing=@requireMap.@get(id)||@requireMap.@get(id=@resolveSync(id,this.path,!1));if(existing)return @evaluateCommonJSModule(existing),existing.exports;if(id.endsWith(\".json\")||id.endsWith(\".toml\")||id.endsWith(\".node\"))return @internalRequire(id);const mod=@createCommonJSModule(id,{},!1);@requireMap.@set(id,mod);var out=this.@require(id,mod);if(out===-1){try{out=@requireESM(id)}catch(exception){throw @requireMap.@delete(id),exception}const esm=@Loader.registry.@get(id);if(esm\?.evaluated&&(esm.state\?\?0)>=@ModuleReady){const namespace=@Loader.getModuleNamespaceObject(esm.module);return mod.exports=namespace.__esModule\?namespace:Object.create(namespace,{__esModule:{value:!0}})}}return @evaluateCommonJSModule(mod),mod.exports})\n"; // requireResolve const JSC::ConstructAbility s_moduleRequireResolveCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_moduleRequireResolveCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_moduleRequireResolveCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_moduleRequireResolveCodeLength = 65; +const int s_moduleRequireResolveCodeLength = 96; static const JSC::Intrinsic s_moduleRequireResolveCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_moduleRequireResolveCode = "(function (n){\"use strict\";return @resolveSync(n,this.path,!1)})\n"; +const char* const s_moduleRequireResolveCode = "(function (id){\"use strict\";return @resolveSync(id,typeof this===\"string\"\?this:this\?.path,!1)})\n"; + +// requireNativeModule +const JSC::ConstructAbility s_moduleRequireNativeModuleCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; +const JSC::ConstructorKind s_moduleRequireNativeModuleCodeConstructorKind = JSC::ConstructorKind::None; +const JSC::ImplementationVisibility s_moduleRequireNativeModuleCodeImplementationVisibility = JSC::ImplementationVisibility::Public; +const int s_moduleRequireNativeModuleCodeLength = 203; +static const JSC::Intrinsic s_moduleRequireNativeModuleCodeIntrinsic = JSC::NoIntrinsic; +const char* const s_moduleRequireNativeModuleCode = "(function (id){\"use strict\";let esm=@Loader.registry.@get(id);if(esm\?.evaluated&&(esm.state\?\?0)>=@ModuleReady)return @Loader.getModuleNamespaceObject(esm.module).default;return @requireESM(id).default})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -740,489 +748,489 @@ WEBCORE_FOREACH_MODULE_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_jsBufferPrototypeSetBigUint64CodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeSetBigUint64CodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeSetBigUint64CodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeSetBigUint64CodeLength = 136; +const int s_jsBufferPrototypeSetBigUint64CodeLength = 156; static const JSC::Intrinsic s_jsBufferPrototypeSetBigUint64CodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeSetBigUint64Code = "(function (d,r,t){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigUint64(d,r,t)})\n"; +const char* const s_jsBufferPrototypeSetBigUint64Code = "(function (offset,value,le){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigUint64(offset,value,le)})\n"; // readInt8 const JSC::ConstructAbility s_jsBufferPrototypeReadInt8CodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadInt8CodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadInt8CodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadInt8CodeLength = 123; +const int s_jsBufferPrototypeReadInt8CodeLength = 133; static const JSC::Intrinsic s_jsBufferPrototypeReadInt8CodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadInt8Code = "(function (d){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt8(d)})\n"; +const char* const s_jsBufferPrototypeReadInt8Code = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt8(offset)})\n"; // readUInt8 const JSC::ConstructAbility s_jsBufferPrototypeReadUInt8CodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadUInt8CodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadUInt8CodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadUInt8CodeLength = 124; +const int s_jsBufferPrototypeReadUInt8CodeLength = 134; static const JSC::Intrinsic s_jsBufferPrototypeReadUInt8CodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadUInt8Code = "(function (d){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint8(d)})\n"; +const char* const s_jsBufferPrototypeReadUInt8Code = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint8(offset)})\n"; // readInt16LE const JSC::ConstructAbility s_jsBufferPrototypeReadInt16LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadInt16LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadInt16LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadInt16LECodeLength = 127; +const int s_jsBufferPrototypeReadInt16LECodeLength = 137; static const JSC::Intrinsic s_jsBufferPrototypeReadInt16LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadInt16LECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt16(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadInt16LECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt16(offset,!0)})\n"; // readInt16BE const JSC::ConstructAbility s_jsBufferPrototypeReadInt16BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadInt16BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadInt16BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadInt16BECodeLength = 127; +const int s_jsBufferPrototypeReadInt16BECodeLength = 137; static const JSC::Intrinsic s_jsBufferPrototypeReadInt16BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadInt16BECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt16(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadInt16BECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt16(offset,!1)})\n"; // readUInt16LE const JSC::ConstructAbility s_jsBufferPrototypeReadUInt16LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadUInt16LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadUInt16LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadUInt16LECodeLength = 128; +const int s_jsBufferPrototypeReadUInt16LECodeLength = 138; static const JSC::Intrinsic s_jsBufferPrototypeReadUInt16LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadUInt16LECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint16(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadUInt16LECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint16(offset,!0)})\n"; // readUInt16BE const JSC::ConstructAbility s_jsBufferPrototypeReadUInt16BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadUInt16BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadUInt16BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadUInt16BECodeLength = 128; +const int s_jsBufferPrototypeReadUInt16BECodeLength = 138; static const JSC::Intrinsic s_jsBufferPrototypeReadUInt16BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadUInt16BECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint16(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadUInt16BECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint16(offset,!1)})\n"; // readInt32LE const JSC::ConstructAbility s_jsBufferPrototypeReadInt32LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadInt32LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadInt32LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadInt32LECodeLength = 127; +const int s_jsBufferPrototypeReadInt32LECodeLength = 137; static const JSC::Intrinsic s_jsBufferPrototypeReadInt32LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadInt32LECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt32(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadInt32LECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt32(offset,!0)})\n"; // readInt32BE const JSC::ConstructAbility s_jsBufferPrototypeReadInt32BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadInt32BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadInt32BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadInt32BECodeLength = 127; +const int s_jsBufferPrototypeReadInt32BECodeLength = 137; static const JSC::Intrinsic s_jsBufferPrototypeReadInt32BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadInt32BECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt32(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadInt32BECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getInt32(offset,!1)})\n"; // readUInt32LE const JSC::ConstructAbility s_jsBufferPrototypeReadUInt32LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadUInt32LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadUInt32LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadUInt32LECodeLength = 128; +const int s_jsBufferPrototypeReadUInt32LECodeLength = 138; static const JSC::Intrinsic s_jsBufferPrototypeReadUInt32LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadUInt32LECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint32(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadUInt32LECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint32(offset,!0)})\n"; // readUInt32BE const JSC::ConstructAbility s_jsBufferPrototypeReadUInt32BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadUInt32BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadUInt32BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadUInt32BECodeLength = 128; +const int s_jsBufferPrototypeReadUInt32BECodeLength = 138; static const JSC::Intrinsic s_jsBufferPrototypeReadUInt32BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadUInt32BECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint32(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadUInt32BECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getUint32(offset,!1)})\n"; // readIntLE const JSC::ConstructAbility s_jsBufferPrototypeReadIntLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadIntLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadIntLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadIntLECodeLength = 528; +const int s_jsBufferPrototypeReadIntLECodeLength = 650; static const JSC::Intrinsic s_jsBufferPrototypeReadIntLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadIntLECode = "(function (d,u){\"use strict\";const r=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(u){case 1:return r.getInt8(d);case 2:return r.getInt16(d,!0);case 3:{const _=r.getUint16(d,!0)+r.getUint8(d+2)*65536;return _|(_&8388608)*510}case 4:return r.getInt32(d,!0);case 5:{const _=r.getUint8(d+4);return(_|(_&128)*33554430)*4294967296+r.getUint32(d,!0)}case 6:{const _=r.getUint16(d+4,!0);return(_|(_&32768)*131070)*4294967296+r.getUint32(d,!0)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; +const char* const s_jsBufferPrototypeReadIntLECode = "(function (offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:return view.getInt8(offset);case 2:return view.getInt16(offset,!0);case 3:{const val=view.getUint16(offset,!0)+view.getUint8(offset+2)*65536;return val|(val&8388608)*510}case 4:return view.getInt32(offset,!0);case 5:{const last=view.getUint8(offset+4);return(last|(last&128)*33554430)*4294967296+view.getUint32(offset,!0)}case 6:{const last=view.getUint16(offset+4,!0);return(last|(last&32768)*131070)*4294967296+view.getUint32(offset,!0)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; // readIntBE const JSC::ConstructAbility s_jsBufferPrototypeReadIntBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadIntBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadIntBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadIntBECodeLength = 528; +const int s_jsBufferPrototypeReadIntBECodeLength = 650; static const JSC::Intrinsic s_jsBufferPrototypeReadIntBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadIntBECode = "(function (r,c){\"use strict\";const d=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(c){case 1:return d.getInt8(r);case 2:return d.getInt16(r,!1);case 3:{const u=d.getUint16(r+1,!1)+d.getUint8(r)*65536;return u|(u&8388608)*510}case 4:return d.getInt32(r,!1);case 5:{const u=d.getUint8(r);return(u|(u&128)*33554430)*4294967296+d.getUint32(r+1,!1)}case 6:{const u=d.getUint16(r,!1);return(u|(u&32768)*131070)*4294967296+d.getUint32(r+2,!1)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; +const char* const s_jsBufferPrototypeReadIntBECode = "(function (offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:return view.getInt8(offset);case 2:return view.getInt16(offset,!1);case 3:{const val=view.getUint16(offset+1,!1)+view.getUint8(offset)*65536;return val|(val&8388608)*510}case 4:return view.getInt32(offset,!1);case 5:{const last=view.getUint8(offset);return(last|(last&128)*33554430)*4294967296+view.getUint32(offset+1,!1)}case 6:{const last=view.getUint16(offset,!1);return(last|(last&32768)*131070)*4294967296+view.getUint32(offset+2,!1)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; // readUIntLE const JSC::ConstructAbility s_jsBufferPrototypeReadUIntLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadUIntLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadUIntLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadUIntLECodeLength = 445; +const int s_jsBufferPrototypeReadUIntLECodeLength = 543; static const JSC::Intrinsic s_jsBufferPrototypeReadUIntLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadUIntLECode = "(function (a,r){\"use strict\";const d=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(r){case 1:return d.getUint8(a);case 2:return d.getUint16(a,!0);case 3:return d.getUint16(a,!0)+d.getUint8(a+2)*65536;case 4:return d.getUint32(a,!0);case 5:return d.getUint8(a+4)*4294967296+d.getUint32(a,!0);case 6:return d.getUint16(a+4,!0)*4294967296+d.getUint32(a,!0)}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; +const char* const s_jsBufferPrototypeReadUIntLECode = "(function (offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:return view.getUint8(offset);case 2:return view.getUint16(offset,!0);case 3:return view.getUint16(offset,!0)+view.getUint8(offset+2)*65536;case 4:return view.getUint32(offset,!0);case 5:return view.getUint8(offset+4)*4294967296+view.getUint32(offset,!0);case 6:return view.getUint16(offset+4,!0)*4294967296+view.getUint32(offset,!0)}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; // readUIntBE const JSC::ConstructAbility s_jsBufferPrototypeReadUIntBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadUIntBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadUIntBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadUIntBECodeLength = 504; +const int s_jsBufferPrototypeReadUIntBECodeLength = 620; static const JSC::Intrinsic s_jsBufferPrototypeReadUIntBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadUIntBECode = "(function (d,p){\"use strict\";const r=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(p){case 1:return r.getUint8(d);case 2:return r.getUint16(d,!1);case 3:return r.getUint16(d+1,!1)+r.getUint8(d)*65536;case 4:return r.getUint32(d,!1);case 5:{const c=r.getUint8(d);return(c|(c&128)*33554430)*4294967296+r.getUint32(d+1,!1)}case 6:{const c=r.getUint16(d,!1);return(c|(c&32768)*131070)*4294967296+r.getUint32(d+2,!1)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; +const char* const s_jsBufferPrototypeReadUIntBECode = "(function (offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:return view.getUint8(offset);case 2:return view.getUint16(offset,!1);case 3:return view.getUint16(offset+1,!1)+view.getUint8(offset)*65536;case 4:return view.getUint32(offset,!1);case 5:{const last=view.getUint8(offset);return(last|(last&128)*33554430)*4294967296+view.getUint32(offset+1,!1)}case 6:{const last=view.getUint16(offset,!1);return(last|(last&32768)*131070)*4294967296+view.getUint32(offset+2,!1)}}@throwRangeError(\"byteLength must be >= 1 and <= 6\")})\n"; // readFloatLE const JSC::ConstructAbility s_jsBufferPrototypeReadFloatLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadFloatLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadFloatLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadFloatLECodeLength = 129; +const int s_jsBufferPrototypeReadFloatLECodeLength = 139; static const JSC::Intrinsic s_jsBufferPrototypeReadFloatLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadFloatLECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat32(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadFloatLECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat32(offset,!0)})\n"; // readFloatBE const JSC::ConstructAbility s_jsBufferPrototypeReadFloatBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadFloatBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadFloatBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadFloatBECodeLength = 129; +const int s_jsBufferPrototypeReadFloatBECodeLength = 139; static const JSC::Intrinsic s_jsBufferPrototypeReadFloatBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadFloatBECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat32(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadFloatBECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat32(offset,!1)})\n"; // readDoubleLE const JSC::ConstructAbility s_jsBufferPrototypeReadDoubleLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadDoubleLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadDoubleLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadDoubleLECodeLength = 129; +const int s_jsBufferPrototypeReadDoubleLECodeLength = 139; static const JSC::Intrinsic s_jsBufferPrototypeReadDoubleLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadDoubleLECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat64(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadDoubleLECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat64(offset,!0)})\n"; // readDoubleBE const JSC::ConstructAbility s_jsBufferPrototypeReadDoubleBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadDoubleBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadDoubleBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadDoubleBECodeLength = 129; +const int s_jsBufferPrototypeReadDoubleBECodeLength = 139; static const JSC::Intrinsic s_jsBufferPrototypeReadDoubleBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadDoubleBECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat64(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadDoubleBECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getFloat64(offset,!1)})\n"; // readBigInt64LE const JSC::ConstructAbility s_jsBufferPrototypeReadBigInt64LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadBigInt64LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadBigInt64LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadBigInt64LECodeLength = 130; +const int s_jsBufferPrototypeReadBigInt64LECodeLength = 140; static const JSC::Intrinsic s_jsBufferPrototypeReadBigInt64LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadBigInt64LECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigInt64(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadBigInt64LECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigInt64(offset,!0)})\n"; // readBigInt64BE const JSC::ConstructAbility s_jsBufferPrototypeReadBigInt64BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadBigInt64BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadBigInt64BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadBigInt64BECodeLength = 130; +const int s_jsBufferPrototypeReadBigInt64BECodeLength = 140; static const JSC::Intrinsic s_jsBufferPrototypeReadBigInt64BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadBigInt64BECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigInt64(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadBigInt64BECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigInt64(offset,!1)})\n"; // readBigUInt64LE const JSC::ConstructAbility s_jsBufferPrototypeReadBigUInt64LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadBigUInt64LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadBigUInt64LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadBigUInt64LECodeLength = 131; +const int s_jsBufferPrototypeReadBigUInt64LECodeLength = 141; static const JSC::Intrinsic s_jsBufferPrototypeReadBigUInt64LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadBigUInt64LECode = "(function (r){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigUint64(r,!0)})\n"; +const char* const s_jsBufferPrototypeReadBigUInt64LECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigUint64(offset,!0)})\n"; // readBigUInt64BE const JSC::ConstructAbility s_jsBufferPrototypeReadBigUInt64BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeReadBigUInt64BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeReadBigUInt64BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeReadBigUInt64BECodeLength = 131; +const int s_jsBufferPrototypeReadBigUInt64BECodeLength = 141; static const JSC::Intrinsic s_jsBufferPrototypeReadBigUInt64BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeReadBigUInt64BECode = "(function (a){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigUint64(a,!1)})\n"; +const char* const s_jsBufferPrototypeReadBigUInt64BECode = "(function (offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).getBigUint64(offset,!1)})\n"; // writeInt8 const JSC::ConstructAbility s_jsBufferPrototypeWriteInt8CodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteInt8CodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteInt8CodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteInt8CodeLength = 131; +const int s_jsBufferPrototypeWriteInt8CodeLength = 154; static const JSC::Intrinsic s_jsBufferPrototypeWriteInt8CodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteInt8Code = "(function (r,d){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt8(d,r),d+1})\n"; +const char* const s_jsBufferPrototypeWriteInt8Code = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt8(offset,value),offset+1})\n"; // writeUInt8 const JSC::ConstructAbility s_jsBufferPrototypeWriteUInt8CodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteUInt8CodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteUInt8CodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteUInt8CodeLength = 132; +const int s_jsBufferPrototypeWriteUInt8CodeLength = 155; static const JSC::Intrinsic s_jsBufferPrototypeWriteUInt8CodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteUInt8Code = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint8(c,d),c+1})\n"; +const char* const s_jsBufferPrototypeWriteUInt8Code = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint8(offset,value),offset+1})\n"; // writeInt16LE const JSC::ConstructAbility s_jsBufferPrototypeWriteInt16LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteInt16LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteInt16LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteInt16LECodeLength = 135; +const int s_jsBufferPrototypeWriteInt16LECodeLength = 158; static const JSC::Intrinsic s_jsBufferPrototypeWriteInt16LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteInt16LECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt16(c,d,!0),c+2})\n"; +const char* const s_jsBufferPrototypeWriteInt16LECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt16(offset,value,!0),offset+2})\n"; // writeInt16BE const JSC::ConstructAbility s_jsBufferPrototypeWriteInt16BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteInt16BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteInt16BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteInt16BECodeLength = 135; +const int s_jsBufferPrototypeWriteInt16BECodeLength = 158; static const JSC::Intrinsic s_jsBufferPrototypeWriteInt16BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteInt16BECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt16(c,d,!1),c+2})\n"; +const char* const s_jsBufferPrototypeWriteInt16BECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt16(offset,value,!1),offset+2})\n"; // writeUInt16LE const JSC::ConstructAbility s_jsBufferPrototypeWriteUInt16LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteUInt16LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteUInt16LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteUInt16LECodeLength = 136; +const int s_jsBufferPrototypeWriteUInt16LECodeLength = 159; static const JSC::Intrinsic s_jsBufferPrototypeWriteUInt16LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteUInt16LECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint16(c,d,!0),c+2})\n"; +const char* const s_jsBufferPrototypeWriteUInt16LECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint16(offset,value,!0),offset+2})\n"; // writeUInt16BE const JSC::ConstructAbility s_jsBufferPrototypeWriteUInt16BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteUInt16BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteUInt16BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteUInt16BECodeLength = 136; +const int s_jsBufferPrototypeWriteUInt16BECodeLength = 159; static const JSC::Intrinsic s_jsBufferPrototypeWriteUInt16BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteUInt16BECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint16(c,d,!1),c+2})\n"; +const char* const s_jsBufferPrototypeWriteUInt16BECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint16(offset,value,!1),offset+2})\n"; // writeInt32LE const JSC::ConstructAbility s_jsBufferPrototypeWriteInt32LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteInt32LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteInt32LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteInt32LECodeLength = 135; +const int s_jsBufferPrototypeWriteInt32LECodeLength = 158; static const JSC::Intrinsic s_jsBufferPrototypeWriteInt32LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteInt32LECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt32(c,d,!0),c+4})\n"; +const char* const s_jsBufferPrototypeWriteInt32LECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt32(offset,value,!0),offset+4})\n"; // writeInt32BE const JSC::ConstructAbility s_jsBufferPrototypeWriteInt32BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteInt32BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteInt32BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteInt32BECodeLength = 135; +const int s_jsBufferPrototypeWriteInt32BECodeLength = 158; static const JSC::Intrinsic s_jsBufferPrototypeWriteInt32BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteInt32BECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt32(c,d,!1),c+4})\n"; +const char* const s_jsBufferPrototypeWriteInt32BECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setInt32(offset,value,!1),offset+4})\n"; // writeUInt32LE const JSC::ConstructAbility s_jsBufferPrototypeWriteUInt32LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteUInt32LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteUInt32LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteUInt32LECodeLength = 136; +const int s_jsBufferPrototypeWriteUInt32LECodeLength = 159; static const JSC::Intrinsic s_jsBufferPrototypeWriteUInt32LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteUInt32LECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint32(c,d,!0),c+4})\n"; +const char* const s_jsBufferPrototypeWriteUInt32LECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint32(offset,value,!0),offset+4})\n"; // writeUInt32BE const JSC::ConstructAbility s_jsBufferPrototypeWriteUInt32BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteUInt32BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteUInt32BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteUInt32BECodeLength = 136; +const int s_jsBufferPrototypeWriteUInt32BECodeLength = 159; static const JSC::Intrinsic s_jsBufferPrototypeWriteUInt32BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteUInt32BECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint32(c,d,!1),c+4})\n"; +const char* const s_jsBufferPrototypeWriteUInt32BECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setUint32(offset,value,!1),offset+4})\n"; // writeIntLE const JSC::ConstructAbility s_jsBufferPrototypeWriteIntLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteIntLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteIntLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteIntLECodeLength = 573; +const int s_jsBufferPrototypeWriteIntLECodeLength = 725; static const JSC::Intrinsic s_jsBufferPrototypeWriteIntLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteIntLECode = "(function (r,d,j){\"use strict\";const c=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(j){case 1:{c.setInt8(d,r);break}case 2:{c.setInt16(d,r,!0);break}case 3:{c.setUint16(d,r&65535,!0),c.setInt8(d+2,Math.floor(r*0.0000152587890625));break}case 4:{c.setInt32(d,r,!0);break}case 5:{c.setUint32(d,r|0,!0),c.setInt8(d+4,Math.floor(r*0.00000000023283064365386964));break}case 6:{c.setUint32(d,r|0,!0),c.setInt16(d+4,Math.floor(r*0.00000000023283064365386964),!0);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return d+j})\n"; +const char* const s_jsBufferPrototypeWriteIntLECode = "(function (value,offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:{view.setInt8(offset,value);break}case 2:{view.setInt16(offset,value,!0);break}case 3:{view.setUint16(offset,value&65535,!0),view.setInt8(offset+2,Math.floor(value*0.0000152587890625));break}case 4:{view.setInt32(offset,value,!0);break}case 5:{view.setUint32(offset,value|0,!0),view.setInt8(offset+4,Math.floor(value*0.00000000023283064365386964));break}case 6:{view.setUint32(offset,value|0,!0),view.setInt16(offset+4,Math.floor(value*0.00000000023283064365386964),!0);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return offset+byteLength})\n"; // writeIntBE const JSC::ConstructAbility s_jsBufferPrototypeWriteIntBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteIntBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteIntBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteIntBECodeLength = 573; +const int s_jsBufferPrototypeWriteIntBECodeLength = 725; static const JSC::Intrinsic s_jsBufferPrototypeWriteIntBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteIntBECode = "(function (r,d,c){\"use strict\";const E=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(c){case 1:{E.setInt8(d,r);break}case 2:{E.setInt16(d,r,!1);break}case 3:{E.setUint16(d+1,r&65535,!1),E.setInt8(d,Math.floor(r*0.0000152587890625));break}case 4:{E.setInt32(d,r,!1);break}case 5:{E.setUint32(d+1,r|0,!1),E.setInt8(d,Math.floor(r*0.00000000023283064365386964));break}case 6:{E.setUint32(d+2,r|0,!1),E.setInt16(d,Math.floor(r*0.00000000023283064365386964),!1);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return d+c})\n"; +const char* const s_jsBufferPrototypeWriteIntBECode = "(function (value,offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:{view.setInt8(offset,value);break}case 2:{view.setInt16(offset,value,!1);break}case 3:{view.setUint16(offset+1,value&65535,!1),view.setInt8(offset,Math.floor(value*0.0000152587890625));break}case 4:{view.setInt32(offset,value,!1);break}case 5:{view.setUint32(offset+1,value|0,!1),view.setInt8(offset,Math.floor(value*0.00000000023283064365386964));break}case 6:{view.setUint32(offset+2,value|0,!1),view.setInt16(offset,Math.floor(value*0.00000000023283064365386964),!1);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return offset+byteLength})\n"; // writeUIntLE const JSC::ConstructAbility s_jsBufferPrototypeWriteUIntLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteUIntLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteUIntLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteUIntLECodeLength = 579; +const int s_jsBufferPrototypeWriteUIntLECodeLength = 731; static const JSC::Intrinsic s_jsBufferPrototypeWriteUIntLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteUIntLECode = "(function (r,d,c){\"use strict\";const E=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(c){case 1:{E.setUint8(d,r);break}case 2:{E.setUint16(d,r,!0);break}case 3:{E.setUint16(d,r&65535,!0),E.setUint8(d+2,Math.floor(r*0.0000152587890625));break}case 4:{E.setUint32(d,r,!0);break}case 5:{E.setUint32(d,r|0,!0),E.setUint8(d+4,Math.floor(r*0.00000000023283064365386964));break}case 6:{E.setUint32(d,r|0,!0),E.setUint16(d+4,Math.floor(r*0.00000000023283064365386964),!0);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return d+c})\n"; +const char* const s_jsBufferPrototypeWriteUIntLECode = "(function (value,offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:{view.setUint8(offset,value);break}case 2:{view.setUint16(offset,value,!0);break}case 3:{view.setUint16(offset,value&65535,!0),view.setUint8(offset+2,Math.floor(value*0.0000152587890625));break}case 4:{view.setUint32(offset,value,!0);break}case 5:{view.setUint32(offset,value|0,!0),view.setUint8(offset+4,Math.floor(value*0.00000000023283064365386964));break}case 6:{view.setUint32(offset,value|0,!0),view.setUint16(offset+4,Math.floor(value*0.00000000023283064365386964),!0);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return offset+byteLength})\n"; // writeUIntBE const JSC::ConstructAbility s_jsBufferPrototypeWriteUIntBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteUIntBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteUIntBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteUIntBECodeLength = 579; +const int s_jsBufferPrototypeWriteUIntBECodeLength = 731; static const JSC::Intrinsic s_jsBufferPrototypeWriteUIntBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteUIntBECode = "(function (r,d,_){\"use strict\";const p=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(_){case 1:{p.setUint8(d,r);break}case 2:{p.setUint16(d,r,!1);break}case 3:{p.setUint16(d+1,r&65535,!1),p.setUint8(d,Math.floor(r*0.0000152587890625));break}case 4:{p.setUint32(d,r,!1);break}case 5:{p.setUint32(d+1,r|0,!1),p.setUint8(d,Math.floor(r*0.00000000023283064365386964));break}case 6:{p.setUint32(d+2,r|0,!1),p.setUint16(d,Math.floor(r*0.00000000023283064365386964),!1);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return d+_})\n"; +const char* const s_jsBufferPrototypeWriteUIntBECode = "(function (value,offset,byteLength){\"use strict\";const view=this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength);switch(byteLength){case 1:{view.setUint8(offset,value);break}case 2:{view.setUint16(offset,value,!1);break}case 3:{view.setUint16(offset+1,value&65535,!1),view.setUint8(offset,Math.floor(value*0.0000152587890625));break}case 4:{view.setUint32(offset,value,!1);break}case 5:{view.setUint32(offset+1,value|0,!1),view.setUint8(offset,Math.floor(value*0.00000000023283064365386964));break}case 6:{view.setUint32(offset+2,value|0,!1),view.setUint16(offset,Math.floor(value*0.00000000023283064365386964),!1);break}default:@throwRangeError(\"byteLength must be >= 1 and <= 6\")}return offset+byteLength})\n"; // writeFloatLE const JSC::ConstructAbility s_jsBufferPrototypeWriteFloatLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteFloatLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteFloatLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteFloatLECodeLength = 137; +const int s_jsBufferPrototypeWriteFloatLECodeLength = 160; static const JSC::Intrinsic s_jsBufferPrototypeWriteFloatLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteFloatLECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(c,d,!0),c+4})\n"; +const char* const s_jsBufferPrototypeWriteFloatLECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(offset,value,!0),offset+4})\n"; // writeFloatBE const JSC::ConstructAbility s_jsBufferPrototypeWriteFloatBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteFloatBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteFloatBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteFloatBECodeLength = 137; +const int s_jsBufferPrototypeWriteFloatBECodeLength = 160; static const JSC::Intrinsic s_jsBufferPrototypeWriteFloatBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteFloatBECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(c,d,!1),c+4})\n"; +const char* const s_jsBufferPrototypeWriteFloatBECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat32(offset,value,!1),offset+4})\n"; // writeDoubleLE const JSC::ConstructAbility s_jsBufferPrototypeWriteDoubleLECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteDoubleLECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteDoubleLECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteDoubleLECodeLength = 137; +const int s_jsBufferPrototypeWriteDoubleLECodeLength = 160; static const JSC::Intrinsic s_jsBufferPrototypeWriteDoubleLECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteDoubleLECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat64(c,d,!0),c+8})\n"; +const char* const s_jsBufferPrototypeWriteDoubleLECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat64(offset,value,!0),offset+8})\n"; // writeDoubleBE const JSC::ConstructAbility s_jsBufferPrototypeWriteDoubleBECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteDoubleBECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteDoubleBECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteDoubleBECodeLength = 137; +const int s_jsBufferPrototypeWriteDoubleBECodeLength = 160; static const JSC::Intrinsic s_jsBufferPrototypeWriteDoubleBECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteDoubleBECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat64(c,d,!1),c+8})\n"; +const char* const s_jsBufferPrototypeWriteDoubleBECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setFloat64(offset,value,!1),offset+8})\n"; // writeBigInt64LE const JSC::ConstructAbility s_jsBufferPrototypeWriteBigInt64LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteBigInt64LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteBigInt64LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteBigInt64LECodeLength = 138; +const int s_jsBufferPrototypeWriteBigInt64LECodeLength = 161; static const JSC::Intrinsic s_jsBufferPrototypeWriteBigInt64LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteBigInt64LECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigInt64(c,d,!0),c+8})\n"; +const char* const s_jsBufferPrototypeWriteBigInt64LECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigInt64(offset,value,!0),offset+8})\n"; // writeBigInt64BE const JSC::ConstructAbility s_jsBufferPrototypeWriteBigInt64BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteBigInt64BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteBigInt64BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteBigInt64BECodeLength = 138; +const int s_jsBufferPrototypeWriteBigInt64BECodeLength = 161; static const JSC::Intrinsic s_jsBufferPrototypeWriteBigInt64BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteBigInt64BECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigInt64(c,d,!1),c+8})\n"; +const char* const s_jsBufferPrototypeWriteBigInt64BECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigInt64(offset,value,!1),offset+8})\n"; // writeBigUInt64LE const JSC::ConstructAbility s_jsBufferPrototypeWriteBigUInt64LECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteBigUInt64LECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteBigUInt64LECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteBigUInt64LECodeLength = 139; +const int s_jsBufferPrototypeWriteBigUInt64LECodeLength = 162; static const JSC::Intrinsic s_jsBufferPrototypeWriteBigUInt64LECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteBigUInt64LECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigUint64(c,d,!0),c+8})\n"; +const char* const s_jsBufferPrototypeWriteBigUInt64LECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigUint64(offset,value,!0),offset+8})\n"; // writeBigUInt64BE const JSC::ConstructAbility s_jsBufferPrototypeWriteBigUInt64BECodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeWriteBigUInt64BECodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeWriteBigUInt64BECodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeWriteBigUInt64BECodeLength = 139; +const int s_jsBufferPrototypeWriteBigUInt64BECodeLength = 162; static const JSC::Intrinsic s_jsBufferPrototypeWriteBigUInt64BECodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeWriteBigUInt64BECode = "(function (d,c){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigUint64(c,d,!1),c+8})\n"; +const char* const s_jsBufferPrototypeWriteBigUInt64BECode = "(function (value,offset){\"use strict\";return(this.@dataView||=new DataView(this.buffer,this.byteOffset,this.byteLength)).setBigUint64(offset,value,!1),offset+8})\n"; // utf8Write const JSC::ConstructAbility s_jsBufferPrototypeUtf8WriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeUtf8WriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeUtf8WriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeUtf8WriteCodeLength = 65; +const int s_jsBufferPrototypeUtf8WriteCodeLength = 91; static const JSC::Intrinsic s_jsBufferPrototypeUtf8WriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeUtf8WriteCode = "(function (d,r,a){\"use strict\";return this.write(d,r,a,\"utf8\")})\n"; +const char* const s_jsBufferPrototypeUtf8WriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"utf8\")})\n"; // ucs2Write const JSC::ConstructAbility s_jsBufferPrototypeUcs2WriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeUcs2WriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeUcs2WriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeUcs2WriteCodeLength = 65; +const int s_jsBufferPrototypeUcs2WriteCodeLength = 91; static const JSC::Intrinsic s_jsBufferPrototypeUcs2WriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeUcs2WriteCode = "(function (c,d,r){\"use strict\";return this.write(c,d,r,\"ucs2\")})\n"; +const char* const s_jsBufferPrototypeUcs2WriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"ucs2\")})\n"; // utf16leWrite const JSC::ConstructAbility s_jsBufferPrototypeUtf16leWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeUtf16leWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeUtf16leWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeUtf16leWriteCodeLength = 68; +const int s_jsBufferPrototypeUtf16leWriteCodeLength = 94; static const JSC::Intrinsic s_jsBufferPrototypeUtf16leWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeUtf16leWriteCode = "(function (d,r,a){\"use strict\";return this.write(d,r,a,\"utf16le\")})\n"; +const char* const s_jsBufferPrototypeUtf16leWriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"utf16le\")})\n"; // latin1Write const JSC::ConstructAbility s_jsBufferPrototypeLatin1WriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeLatin1WriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeLatin1WriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeLatin1WriteCodeLength = 67; +const int s_jsBufferPrototypeLatin1WriteCodeLength = 93; static const JSC::Intrinsic s_jsBufferPrototypeLatin1WriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeLatin1WriteCode = "(function (a,d,r){\"use strict\";return this.write(a,d,r,\"latin1\")})\n"; +const char* const s_jsBufferPrototypeLatin1WriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"latin1\")})\n"; // asciiWrite const JSC::ConstructAbility s_jsBufferPrototypeAsciiWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeAsciiWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeAsciiWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeAsciiWriteCodeLength = 66; +const int s_jsBufferPrototypeAsciiWriteCodeLength = 92; static const JSC::Intrinsic s_jsBufferPrototypeAsciiWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeAsciiWriteCode = "(function (c,d,i){\"use strict\";return this.write(c,d,i,\"ascii\")})\n"; +const char* const s_jsBufferPrototypeAsciiWriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"ascii\")})\n"; // base64Write const JSC::ConstructAbility s_jsBufferPrototypeBase64WriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeBase64WriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeBase64WriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeBase64WriteCodeLength = 67; +const int s_jsBufferPrototypeBase64WriteCodeLength = 93; static const JSC::Intrinsic s_jsBufferPrototypeBase64WriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeBase64WriteCode = "(function (a,d,r){\"use strict\";return this.write(a,d,r,\"base64\")})\n"; +const char* const s_jsBufferPrototypeBase64WriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"base64\")})\n"; // base64urlWrite const JSC::ConstructAbility s_jsBufferPrototypeBase64urlWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeBase64urlWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeBase64urlWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeBase64urlWriteCodeLength = 70; +const int s_jsBufferPrototypeBase64urlWriteCodeLength = 96; static const JSC::Intrinsic s_jsBufferPrototypeBase64urlWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeBase64urlWriteCode = "(function (a,d,r){\"use strict\";return this.write(a,d,r,\"base64url\")})\n"; +const char* const s_jsBufferPrototypeBase64urlWriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"base64url\")})\n"; // hexWrite const JSC::ConstructAbility s_jsBufferPrototypeHexWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeHexWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeHexWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeHexWriteCodeLength = 64; +const int s_jsBufferPrototypeHexWriteCodeLength = 90; static const JSC::Intrinsic s_jsBufferPrototypeHexWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeHexWriteCode = "(function (d,r,a){\"use strict\";return this.write(d,r,a,\"hex\")})\n"; +const char* const s_jsBufferPrototypeHexWriteCode = "(function (text,offset,length){\"use strict\";return this.write(text,offset,length,\"hex\")})\n"; // utf8Slice const JSC::ConstructAbility s_jsBufferPrototypeUtf8SliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeUtf8SliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeUtf8SliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeUtf8SliceCodeLength = 64; +const int s_jsBufferPrototypeUtf8SliceCodeLength = 76; static const JSC::Intrinsic s_jsBufferPrototypeUtf8SliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeUtf8SliceCode = "(function (g,u){\"use strict\";return this.toString(\"utf8\",g,u)})\n"; +const char* const s_jsBufferPrototypeUtf8SliceCode = "(function (start,end){\"use strict\";return this.toString(\"utf8\",start,end)})\n"; // ucs2Slice const JSC::ConstructAbility s_jsBufferPrototypeUcs2SliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeUcs2SliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeUcs2SliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeUcs2SliceCodeLength = 64; +const int s_jsBufferPrototypeUcs2SliceCodeLength = 76; static const JSC::Intrinsic s_jsBufferPrototypeUcs2SliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeUcs2SliceCode = "(function (g,u){\"use strict\";return this.toString(\"ucs2\",g,u)})\n"; +const char* const s_jsBufferPrototypeUcs2SliceCode = "(function (start,end){\"use strict\";return this.toString(\"ucs2\",start,end)})\n"; // utf16leSlice const JSC::ConstructAbility s_jsBufferPrototypeUtf16leSliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeUtf16leSliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeUtf16leSliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeUtf16leSliceCodeLength = 67; +const int s_jsBufferPrototypeUtf16leSliceCodeLength = 79; static const JSC::Intrinsic s_jsBufferPrototypeUtf16leSliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeUtf16leSliceCode = "(function (g,p){\"use strict\";return this.toString(\"utf16le\",g,p)})\n"; +const char* const s_jsBufferPrototypeUtf16leSliceCode = "(function (start,end){\"use strict\";return this.toString(\"utf16le\",start,end)})\n"; // latin1Slice const JSC::ConstructAbility s_jsBufferPrototypeLatin1SliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeLatin1SliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeLatin1SliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeLatin1SliceCodeLength = 66; +const int s_jsBufferPrototypeLatin1SliceCodeLength = 78; static const JSC::Intrinsic s_jsBufferPrototypeLatin1SliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeLatin1SliceCode = "(function (g,p){\"use strict\";return this.toString(\"latin1\",g,p)})\n"; +const char* const s_jsBufferPrototypeLatin1SliceCode = "(function (start,end){\"use strict\";return this.toString(\"latin1\",start,end)})\n"; // asciiSlice const JSC::ConstructAbility s_jsBufferPrototypeAsciiSliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeAsciiSliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeAsciiSliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeAsciiSliceCodeLength = 65; +const int s_jsBufferPrototypeAsciiSliceCodeLength = 77; static const JSC::Intrinsic s_jsBufferPrototypeAsciiSliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeAsciiSliceCode = "(function (g,u){\"use strict\";return this.toString(\"ascii\",g,u)})\n"; +const char* const s_jsBufferPrototypeAsciiSliceCode = "(function (start,end){\"use strict\";return this.toString(\"ascii\",start,end)})\n"; // base64Slice const JSC::ConstructAbility s_jsBufferPrototypeBase64SliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeBase64SliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeBase64SliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeBase64SliceCodeLength = 66; +const int s_jsBufferPrototypeBase64SliceCodeLength = 78; static const JSC::Intrinsic s_jsBufferPrototypeBase64SliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeBase64SliceCode = "(function (g,p){\"use strict\";return this.toString(\"base64\",g,p)})\n"; +const char* const s_jsBufferPrototypeBase64SliceCode = "(function (start,end){\"use strict\";return this.toString(\"base64\",start,end)})\n"; // base64urlSlice const JSC::ConstructAbility s_jsBufferPrototypeBase64urlSliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeBase64urlSliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeBase64urlSliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeBase64urlSliceCodeLength = 69; +const int s_jsBufferPrototypeBase64urlSliceCodeLength = 81; static const JSC::Intrinsic s_jsBufferPrototypeBase64urlSliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeBase64urlSliceCode = "(function (c,g){\"use strict\";return this.toString(\"base64url\",c,g)})\n"; +const char* const s_jsBufferPrototypeBase64urlSliceCode = "(function (start,end){\"use strict\";return this.toString(\"base64url\",start,end)})\n"; // hexSlice const JSC::ConstructAbility s_jsBufferPrototypeHexSliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeHexSliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeHexSliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeHexSliceCodeLength = 63; +const int s_jsBufferPrototypeHexSliceCodeLength = 75; static const JSC::Intrinsic s_jsBufferPrototypeHexSliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeHexSliceCode = "(function (g,_){\"use strict\";return this.toString(\"hex\",g,_)})\n"; +const char* const s_jsBufferPrototypeHexSliceCode = "(function (start,end){\"use strict\";return this.toString(\"hex\",start,end)})\n"; // toJSON const JSC::ConstructAbility s_jsBufferPrototypeToJSONCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1236,9 +1244,9 @@ const char* const s_jsBufferPrototypeToJSONCode = "(function (){\"use strict\";r const JSC::ConstructAbility s_jsBufferPrototypeSliceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeSliceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeSliceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeSliceCodeLength = 256; +const int s_jsBufferPrototypeSliceCodeLength = 447; static const JSC::Intrinsic s_jsBufferPrototypeSliceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeSliceCode = "(function (v,m){\"use strict\";var{buffer:w,byteOffset:x,byteLength:p}=this;function q(c,k){if(c=@trunc(c),c===0||c!==c)return 0;else if(c<0)return c+=k,c>0\?c:0;else return ci\?u-i:0)})\n"; +const char* const s_jsBufferPrototypeSliceCode = "(function (start,end){\"use strict\";var{buffer,byteOffset,byteLength}=this;function adjustOffset(offset,length){if(offset=@trunc(offset),offset===0||offset!==offset)return 0;else if(offset<0)return offset+=length,offset>0\?offset:0;else return offsetstart_\?end_-start_:0)})\n"; // parent const JSC::ConstructAbility s_jsBufferPrototypeParentCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1260,9 +1268,9 @@ const char* const s_jsBufferPrototypeOffsetCode = "(function (){\"use strict\";r const JSC::ConstructAbility s_jsBufferPrototypeInspectCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferPrototypeInspectCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferPrototypeInspectCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferPrototypeInspectCodeLength = 57; +const int s_jsBufferPrototypeInspectCodeLength = 70; static const JSC::Intrinsic s_jsBufferPrototypeInspectCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferPrototypeInspectCode = "(function (c,d){\"use strict\";return @Bun.inspect(this)})\n"; +const char* const s_jsBufferPrototypeInspectCode = "(function (recurseTimes,ctx){\"use strict\";return @Bun.inspect(this)})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -1278,25 +1286,25 @@ WEBCORE_FOREACH_JSBUFFERPROTOTYPE_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_readableByteStreamControllerInitializeReadableByteStreamControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamControllerInitializeReadableByteStreamControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamControllerInitializeReadableByteStreamControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamControllerInitializeReadableByteStreamControllerCodeLength = 253; +const int s_readableByteStreamControllerInitializeReadableByteStreamControllerCodeLength = 325; static const JSC::Intrinsic s_readableByteStreamControllerInitializeReadableByteStreamControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamControllerInitializeReadableByteStreamControllerCode = "(function (f,l,p){\"use strict\";if(arguments.length!==4&&arguments[3]!==@isReadableStream)@throwTypeError(\"ReadableByteStreamController constructor should not be called directly\");return @privateInitializeReadableByteStreamController.@call(this,f,l,p)})\n"; +const char* const s_readableByteStreamControllerInitializeReadableByteStreamControllerCode = "(function (stream,underlyingByteSource,highWaterMark){\"use strict\";if(arguments.length!==4&&arguments[3]!==@isReadableStream)@throwTypeError(\"ReadableByteStreamController constructor should not be called directly\");return @privateInitializeReadableByteStreamController.@call(this,stream,underlyingByteSource,highWaterMark)})\n"; // enqueue const JSC::ConstructAbility s_readableByteStreamControllerEnqueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamControllerEnqueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamControllerEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamControllerEnqueueCodeLength = 562; +const int s_readableByteStreamControllerEnqueueCodeLength = 578; static const JSC::Intrinsic s_readableByteStreamControllerEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamControllerEnqueueCode = "(function (r){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeThisTypeError(\"ReadableByteStreamController\",\"enqueue\");if(@getByIdDirectPrivate(this,\"closeRequested\"))@throwTypeError(\"ReadableByteStreamController is requested to close\");if(@getByIdDirectPrivate(@getByIdDirectPrivate(this,\"controlledReadableStream\"),\"state\")!==@streamReadable)@throwTypeError(\"ReadableStream is not readable\");if(!@isObject(r)||!@ArrayBuffer.@isView(r))@throwTypeError(\"Provided chunk is not a TypedArray\");return @readableByteStreamControllerEnqueue(this,r)})\n"; +const char* const s_readableByteStreamControllerEnqueueCode = "(function (chunk){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeThisTypeError(\"ReadableByteStreamController\",\"enqueue\");if(@getByIdDirectPrivate(this,\"closeRequested\"))@throwTypeError(\"ReadableByteStreamController is requested to close\");if(@getByIdDirectPrivate(@getByIdDirectPrivate(this,\"controlledReadableStream\"),\"state\")!==@streamReadable)@throwTypeError(\"ReadableStream is not readable\");if(!@isObject(chunk)||!@ArrayBuffer.@isView(chunk))@throwTypeError(\"Provided chunk is not a TypedArray\");return @readableByteStreamControllerEnqueue(this,chunk)})\n"; // error const JSC::ConstructAbility s_readableByteStreamControllerErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamControllerErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamControllerErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamControllerErrorCodeLength = 336; +const int s_readableByteStreamControllerErrorCodeLength = 344; static const JSC::Intrinsic s_readableByteStreamControllerErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamControllerErrorCode = "(function (a){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeThisTypeError(\"ReadableByteStreamController\",\"error\");if(@getByIdDirectPrivate(@getByIdDirectPrivate(this,\"controlledReadableStream\"),\"state\")!==@streamReadable)@throwTypeError(\"ReadableStream is not readable\");@readableByteStreamControllerError(this,a)})\n"; +const char* const s_readableByteStreamControllerErrorCode = "(function (error){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeThisTypeError(\"ReadableByteStreamController\",\"error\");if(@getByIdDirectPrivate(@getByIdDirectPrivate(this,\"controlledReadableStream\"),\"state\")!==@streamReadable)@throwTypeError(\"ReadableStream is not readable\");@readableByteStreamControllerError(this,error)})\n"; // close const JSC::ConstructAbility s_readableByteStreamControllerCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1310,9 +1318,9 @@ const char* const s_readableByteStreamControllerCloseCode = "(function (){\"use const JSC::ConstructAbility s_readableByteStreamControllerByobRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamControllerByobRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamControllerByobRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamControllerByobRequestCodeLength = 523; +const int s_readableByteStreamControllerByobRequestCodeLength = 651; static const JSC::Intrinsic s_readableByteStreamControllerByobRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamControllerByobRequestCode = "(function (){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeGetterTypeError(\"ReadableByteStreamController\",\"byobRequest\");var a=@getByIdDirectPrivate(this,\"byobRequest\");if(a===@undefined){var l=@getByIdDirectPrivate(this,\"pendingPullIntos\");const _=l.peek();if(_){const m=new @Uint8Array(_.buffer,_.byteOffset+_.bytesFilled,_.byteLength-_.bytesFilled);@putByIdDirectPrivate(this,\"byobRequest\",new @ReadableStreamBYOBRequest(this,m,@isReadableStream))}}return @getByIdDirectPrivate(this,\"byobRequest\")})\n"; +const char* const s_readableByteStreamControllerByobRequestCode = "(function (){\"use strict\";if(!@isReadableByteStreamController(this))throw @makeGetterTypeError(\"ReadableByteStreamController\",\"byobRequest\");var request=@getByIdDirectPrivate(this,\"byobRequest\");if(request===@undefined){var pending=@getByIdDirectPrivate(this,\"pendingPullIntos\");const firstDescriptor=pending.peek();if(firstDescriptor){const view=new @Uint8Array(firstDescriptor.buffer,firstDescriptor.byteOffset+firstDescriptor.bytesFilled,firstDescriptor.byteLength-firstDescriptor.bytesFilled);@putByIdDirectPrivate(this,\"byobRequest\",new @ReadableStreamBYOBRequest(this,view,@isReadableStream))}}return @getByIdDirectPrivate(this,\"byobRequest\")})\n"; // desiredSize const JSC::ConstructAbility s_readableByteStreamControllerDesiredSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1336,17 +1344,17 @@ WEBCORE_FOREACH_READABLEBYTESTREAMCONTROLLER_BUILTIN_CODE(DEFINE_BUILTIN_GENERAT const JSC::ConstructAbility s_consoleObjectAsyncIteratorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_consoleObjectAsyncIteratorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_consoleObjectAsyncIteratorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_consoleObjectAsyncIteratorCodeLength = 577; +const int s_consoleObjectAsyncIteratorCodeLength = 949; static const JSC::Intrinsic s_consoleObjectAsyncIteratorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_consoleObjectAsyncIteratorCode = "(function (){\"use strict\";const D=async function*L(){var F=@Bun.stdin.stream().getReader(),G=new globalThis.TextDecoder(\"utf-8\",{fatal:!1}),z,H=@Bun.indexOfLine;try{while(!0){var A,B,w;const m=F.readMany();if(@isPromise(m))({done:A,value:B}=await m);else({done:A,value:B}=m);if(A){if(w)yield G.decode(w);return}var _;for(let J of B){if(_=J,w)_=@Buffer.concat([w,J]),w=null;var j=0,q=H(_,j);while(q!==-1)yield G.decode(_.subarray(j,q)),j=q+1,q=H(_,j);w=_.subarray(j)}}}catch(m){z=m}finally{if(F.releaseLock(),z)throw z}},K=globalThis.Symbol.asyncIterator;return this[K]=D,D()})\n"; +const char* const s_consoleObjectAsyncIteratorCode = "(function (){\"use strict\";const Iterator=async function*ConsoleAsyncIterator(){var reader=@Bun.stdin.stream().getReader(),decoder=new globalThis.TextDecoder(\"utf-8\",{fatal:!1}),deferredError,indexOf=@Bun.indexOfLine;try{while(!0){var done,value,pendingChunk;const firstResult=reader.readMany();if(@isPromise(firstResult))({done,value}=await firstResult);else({done,value}=firstResult);if(done){if(pendingChunk)yield decoder.decode(pendingChunk);return}var actualChunk;for(let chunk of value){if(actualChunk=chunk,pendingChunk)actualChunk=@Buffer.concat([pendingChunk,chunk]),pendingChunk=null;var last=0,i=indexOf(actualChunk,last);while(i!==-1)yield decoder.decode(actualChunk.subarray(last,i)),last=i+1,i=indexOf(actualChunk,last);pendingChunk=actualChunk.subarray(last)}}}catch(e){deferredError=e}finally{if(reader.releaseLock(),deferredError)throw deferredError}},symbol=globalThis.Symbol.asyncIterator;return this[symbol]=Iterator,Iterator()})\n"; // write const JSC::ConstructAbility s_consoleObjectWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_consoleObjectWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_consoleObjectWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_consoleObjectWriteCodeLength = 310; +const int s_consoleObjectWriteCodeLength = 392; static const JSC::Intrinsic s_consoleObjectWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_consoleObjectWriteCode = "(function (_){\"use strict\";var a=@getByIdDirectPrivate(this,\"writer\");if(!a){var b=@toLength(_\?.length\?\?0);a=@Bun.stdout.writer({highWaterMark:b>65536\?b:65536}),@putByIdDirectPrivate(this,\"writer\",a)}var c=a.write(_);const f=@argumentCount();for(var d=1;d65536\?length:65536}),@putByIdDirectPrivate(this,\"writer\",writer)}var wrote=writer.write(input);const count=@argumentCount();for(var i=1;i{},(h)=>{y.error(h)});function b(){@readableStreamDefaultReaderRead(_).@then(function(h){if(h.done){y.close();return}try{y.enqueue(h.value)}catch(c){y.error(\"ReadableStream chunk enqueueing in the sink failed\");return}b()},function(h){y.error(h)})}b()})\n"; +const char* const s_readableStreamInternalsReadableStreamPipeToCode = "(function (stream,sink){\"use strict\";const reader=new @ReadableStreamDefaultReader(stream);@getByIdDirectPrivate(reader,\"closedPromiseCapability\").promise.@then(()=>{},(e)=>{sink.error(e)});function doPipe(){@readableStreamDefaultReaderRead(reader).@then(function(result){if(result.done){sink.close();return}try{sink.enqueue(result.value)}catch(e){sink.error(\"ReadableStream chunk enqueueing in the sink failed\");return}doPipe()},function(e){sink.error(e)})}doPipe()})\n"; // acquireReadableStreamDefaultReader const JSC::ConstructAbility s_readableStreamInternalsAcquireReadableStreamDefaultReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsAcquireReadableStreamDefaultReaderCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsAcquireReadableStreamDefaultReaderCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsAcquireReadableStreamDefaultReaderCodeLength = 127; +const int s_readableStreamInternalsAcquireReadableStreamDefaultReaderCodeLength = 159; static const JSC::Intrinsic s_readableStreamInternalsAcquireReadableStreamDefaultReaderCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsAcquireReadableStreamDefaultReaderCode = "(function (c){\"use strict\";var d=@getByIdDirectPrivate(c,\"start\");if(d)d.@call(c);return new @ReadableStreamDefaultReader(c)})\n"; +const char* const s_readableStreamInternalsAcquireReadableStreamDefaultReaderCode = "(function (stream){\"use strict\";var start=@getByIdDirectPrivate(stream,\"start\");if(start)start.@call(stream);return new @ReadableStreamDefaultReader(stream)})\n"; // setupReadableStreamDefaultController const JSC::ConstructAbility s_readableStreamInternalsSetupReadableStreamDefaultControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsSetupReadableStreamDefaultControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsSetupReadableStreamDefaultControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsSetupReadableStreamDefaultControllerCodeLength = 726; +const int s_readableStreamInternalsSetupReadableStreamDefaultControllerCodeLength = 1105; static const JSC::Intrinsic s_readableStreamInternalsSetupReadableStreamDefaultControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsSetupReadableStreamDefaultControllerCode = "(function (I,f,w,B,J,D,j){\"use strict\";const _=new @ReadableStreamDefaultController(I,f,w,B,@isReadableStream);var q=I.@asyncContext;const E=()=>@promiseInvokeOrNoopMethod(f,D,[_]),F=q\?(b)=>{var G=@getInternalField(@asyncContext,0);@putInternalField(@asyncContext,0,q);var H=@promiseInvokeOrNoopMethod(f,j,[b]);return @putInternalField(@asyncContext,0,G),H}:(b)=>@promiseInvokeOrNoopMethod(f,j,[b]);@putByIdDirectPrivate(_,\"pullAlgorithm\",E),@putByIdDirectPrivate(_,\"cancelAlgorithm\",F),@putByIdDirectPrivate(_,\"pull\",@readableStreamDefaultControllerPull),@putByIdDirectPrivate(_,\"cancel\",@readableStreamDefaultControllerCancel),@putByIdDirectPrivate(I,\"readableStreamController\",_),@readableStreamDefaultControllerStart(_)})\n"; +const char* const s_readableStreamInternalsSetupReadableStreamDefaultControllerCode = "(function (stream,underlyingSource,size,highWaterMark,startMethod,pullMethod,cancelMethod){\"use strict\";const controller=new @ReadableStreamDefaultController(stream,underlyingSource,size,highWaterMark,@isReadableStream);var asyncContext=stream.@asyncContext;const pullAlgorithm=()=>@promiseInvokeOrNoopMethod(underlyingSource,pullMethod,[controller]),cancelAlgorithm=asyncContext\?(reason)=>{var prev=@getInternalField(@asyncContext,0);@putInternalField(@asyncContext,0,asyncContext);var result=@promiseInvokeOrNoopMethod(underlyingSource,cancelMethod,[reason]);return @putInternalField(@asyncContext,0,prev),result}:(reason)=>@promiseInvokeOrNoopMethod(underlyingSource,cancelMethod,[reason]);@putByIdDirectPrivate(controller,\"pullAlgorithm\",pullAlgorithm),@putByIdDirectPrivate(controller,\"cancelAlgorithm\",cancelAlgorithm),@putByIdDirectPrivate(controller,\"pull\",@readableStreamDefaultControllerPull),@putByIdDirectPrivate(controller,\"cancel\",@readableStreamDefaultControllerCancel),@putByIdDirectPrivate(stream,\"readableStreamController\",controller),@readableStreamDefaultControllerStart(controller)})\n"; // createReadableStreamController const JSC::ConstructAbility s_readableStreamInternalsCreateReadableStreamControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsCreateReadableStreamControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsCreateReadableStreamControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsCreateReadableStreamControllerCodeLength = 671; +const int s_readableStreamInternalsCreateReadableStreamControllerCodeLength = 946; static const JSC::Intrinsic s_readableStreamInternalsCreateReadableStreamControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsCreateReadableStreamControllerCode = "(function (w,v,f){\"use strict\";const A=v.type,C=@toString(A);if(C===\"bytes\"){if(f.highWaterMark===@undefined)f.highWaterMark=0;if(f.size!==@undefined)@throwRangeError(\"Strategy for a ReadableByteStreamController cannot have a size\");@putByIdDirectPrivate(w,\"readableStreamController\",new @ReadableByteStreamController(w,v,f.highWaterMark,@isReadableStream))}else if(C===\"direct\"){var b=f\?.highWaterMark;@initializeArrayBufferStream.@call(w,v,b)}else if(A===@undefined){if(f.highWaterMark===@undefined)f.highWaterMark=1;@setupReadableStreamDefaultController(w,v,f.size,f.highWaterMark,v.start,v.pull,v.cancel)}else @throwRangeError(\"Invalid type for underlying source\")})\n"; +const char* const s_readableStreamInternalsCreateReadableStreamControllerCode = "(function (stream,underlyingSource,strategy){\"use strict\";const type=underlyingSource.type,typeString=@toString(type);if(typeString===\"bytes\"){if(strategy.highWaterMark===@undefined)strategy.highWaterMark=0;if(strategy.size!==@undefined)@throwRangeError(\"Strategy for a ReadableByteStreamController cannot have a size\");@putByIdDirectPrivate(stream,\"readableStreamController\",new @ReadableByteStreamController(stream,underlyingSource,strategy.highWaterMark,@isReadableStream))}else if(typeString===\"direct\"){var highWaterMark=strategy\?.highWaterMark;@initializeArrayBufferStream.@call(stream,underlyingSource,highWaterMark)}else if(type===@undefined){if(strategy.highWaterMark===@undefined)strategy.highWaterMark=1;@setupReadableStreamDefaultController(stream,underlyingSource,strategy.size,strategy.highWaterMark,underlyingSource.start,underlyingSource.pull,underlyingSource.cancel)}else @throwRangeError(\"Invalid type for underlying source\")})\n"; // readableStreamDefaultControllerStart const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerStartCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerStartCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerStartCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerStartCodeLength = 465; +const int s_readableStreamInternalsReadableStreamDefaultControllerStartCodeLength = 518; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerStartCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerStartCode = "(function (m){\"use strict\";if(@getByIdDirectPrivate(m,\"started\")!==-1)return;const B=@getByIdDirectPrivate(m,\"underlyingSource\"),a=B.start;@putByIdDirectPrivate(m,\"started\",0),@promiseInvokeOrNoopMethodNoCatch(B,a,[m]).@then(()=>{@putByIdDirectPrivate(m,\"started\",1),@assert(!@getByIdDirectPrivate(m,\"pulling\")),@assert(!@getByIdDirectPrivate(m,\"pullAgain\")),@readableStreamDefaultControllerCallPullIfNeeded(m)},(p)=>{@readableStreamDefaultControllerError(m,p)})})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerStartCode = "(function (controller){\"use strict\";if(@getByIdDirectPrivate(controller,\"started\")!==-1)return;const underlyingSource=@getByIdDirectPrivate(controller,\"underlyingSource\"),startMethod=underlyingSource.start;@putByIdDirectPrivate(controller,\"started\",0),@promiseInvokeOrNoopMethodNoCatch(underlyingSource,startMethod,[controller]).@then(()=>{@putByIdDirectPrivate(controller,\"started\",1),@readableStreamDefaultControllerCallPullIfNeeded(controller)},(error)=>{@readableStreamDefaultControllerError(controller,error)})})\n"; // readableStreamPipeToWritableStream const JSC::ConstructAbility s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeLength = 1625; +const int s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeLength = 2022; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamPipeToWritableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamPipeToWritableStreamCode = "(function (E,k,F,G,H,f){\"use strict\";if(@assert(@isReadableStream(E)),@assert(@isWritableStream(k)),@assert(!@isReadableStreamLocked(E)),@assert(!@isWritableStreamLocked(k)),@assert(f===@undefined||@isAbortSignal(f)),@getByIdDirectPrivate(E,\"underlyingByteSource\")!==@undefined)return @Promise.@reject(\"Piping to a readable bytestream is not supported\");let _={source:E,destination:k,preventAbort:G,preventCancel:H,preventClose:F,signal:f};if(_.reader=@acquireReadableStreamDefaultReader(E),_.writer=@acquireWritableStreamDefaultWriter(k),@putByIdDirectPrivate(E,\"disturbed\",!0),_.finalized=!1,_.shuttingDown=!1,_.promiseCapability=@newPromiseCapability(@Promise),_.pendingReadPromiseCapability=@newPromiseCapability(@Promise),_.pendingReadPromiseCapability.resolve.@call(),_.pendingWritePromise=@Promise.@resolve(),f!==@undefined){const I=(q)=>{if(_.finalized)return;@pipeToShutdownWithAction(_,()=>{const J=!_.preventAbort&&@getByIdDirectPrivate(_.destination,\"state\")===\"writable\"\?@writableStreamAbort(_.destination,q):@Promise.@resolve(),K=!_.preventCancel&&@getByIdDirectPrivate(_.source,\"state\")===@streamReadable\?@readableStreamCancel(_.source,q):@Promise.@resolve();let w=@newPromiseCapability(@Promise),x=!0,z=()=>{if(x){x=!1;return}w.resolve.@call()},B=(L)=>{w.reject.@call(@undefined,L)};return J.@then(z,B),K.@then(z,B),w.promise},q)};if(@whenSignalAborted(f,I))return _.promiseCapability.promise}return @pipeToErrorsMustBePropagatedForward(_),@pipeToErrorsMustBePropagatedBackward(_),@pipeToClosingMustBePropagatedForward(_),@pipeToClosingMustBePropagatedBackward(_),@pipeToLoop(_),_.promiseCapability.promise})\n"; +const char* const s_readableStreamInternalsReadableStreamPipeToWritableStreamCode = "(function (source,destination,preventClose,preventAbort,preventCancel,signal){\"use strict\";if(@getByIdDirectPrivate(source,\"underlyingByteSource\")!==@undefined)return @Promise.@reject(\"Piping to a readable bytestream is not supported\");let pipeState={source,destination,preventAbort,preventCancel,preventClose,signal};if(pipeState.reader=@acquireReadableStreamDefaultReader(source),pipeState.writer=@acquireWritableStreamDefaultWriter(destination),@putByIdDirectPrivate(source,\"disturbed\",!0),pipeState.finalized=!1,pipeState.shuttingDown=!1,pipeState.promiseCapability=@newPromiseCapability(@Promise),pipeState.pendingReadPromiseCapability=@newPromiseCapability(@Promise),pipeState.pendingReadPromiseCapability.resolve.@call(),pipeState.pendingWritePromise=@Promise.@resolve(),signal!==@undefined){const algorithm=(reason)=>{if(pipeState.finalized)return;@pipeToShutdownWithAction(pipeState,()=>{const promiseDestination=!pipeState.preventAbort&&@getByIdDirectPrivate(pipeState.destination,\"state\")===\"writable\"\?@writableStreamAbort(pipeState.destination,reason):@Promise.@resolve(),promiseSource=!pipeState.preventCancel&&@getByIdDirectPrivate(pipeState.source,\"state\")===@streamReadable\?@readableStreamCancel(pipeState.source,reason):@Promise.@resolve();let promiseCapability=@newPromiseCapability(@Promise),shouldWait=!0,handleResolvedPromise=()=>{if(shouldWait){shouldWait=!1;return}promiseCapability.resolve.@call()},handleRejectedPromise=(e)=>{promiseCapability.reject.@call(@undefined,e)};return promiseDestination.@then(handleResolvedPromise,handleRejectedPromise),promiseSource.@then(handleResolvedPromise,handleRejectedPromise),promiseCapability.promise},reason)};if(@whenSignalAborted(signal,algorithm))return pipeState.promiseCapability.promise}return @pipeToErrorsMustBePropagatedForward(pipeState),@pipeToErrorsMustBePropagatedBackward(pipeState),@pipeToClosingMustBePropagatedForward(pipeState),@pipeToClosingMustBePropagatedBackward(pipeState),@pipeToLoop(pipeState),pipeState.promiseCapability.promise})\n"; // pipeToLoop const JSC::ConstructAbility s_readableStreamInternalsPipeToLoopCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToLoopCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToLoopCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToLoopCodeLength = 110; +const int s_readableStreamInternalsPipeToLoopCodeLength = 152; static const JSC::Intrinsic s_readableStreamInternalsPipeToLoopCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToLoopCode = "(function (c){\"use strict\";if(c.shuttingDown)return;@pipeToDoReadWrite(c).@then((d)=>{if(d)@pipeToLoop(c)})})\n"; +const char* const s_readableStreamInternalsPipeToLoopCode = "(function (pipeState){\"use strict\";if(pipeState.shuttingDown)return;@pipeToDoReadWrite(pipeState).@then((result)=>{if(result)@pipeToLoop(pipeState)})})\n"; // pipeToDoReadWrite const JSC::ConstructAbility s_readableStreamInternalsPipeToDoReadWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToDoReadWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToDoReadWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToDoReadWriteCodeLength = 725; +const int s_readableStreamInternalsPipeToDoReadWriteCodeLength = 840; static const JSC::Intrinsic s_readableStreamInternalsPipeToDoReadWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToDoReadWriteCode = "(function (d){\"use strict\";return @assert(!d.shuttingDown),d.pendingReadPromiseCapability=@newPromiseCapability(@Promise),@getByIdDirectPrivate(d.writer,\"readyPromise\").promise.@then(()=>{if(d.shuttingDown){d.pendingReadPromiseCapability.resolve.@call(@undefined,!1);return}@readableStreamDefaultReaderRead(d.reader).@then((m)=>{const g=!m.done&&@getByIdDirectPrivate(d.writer,\"stream\")!==@undefined;if(d.pendingReadPromiseCapability.resolve.@call(@undefined,g),!g)return;d.pendingWritePromise=@writableStreamDefaultWriterWrite(d.writer,m.value)},(m)=>{d.pendingReadPromiseCapability.resolve.@call(@undefined,!1)})},(m)=>{d.pendingReadPromiseCapability.resolve.@call(@undefined,!1)}),d.pendingReadPromiseCapability.promise})\n"; +const char* const s_readableStreamInternalsPipeToDoReadWriteCode = "(function (pipeState){\"use strict\";return pipeState.pendingReadPromiseCapability=@newPromiseCapability(@Promise),@getByIdDirectPrivate(pipeState.writer,\"readyPromise\").promise.@then(()=>{if(pipeState.shuttingDown){pipeState.pendingReadPromiseCapability.resolve.@call(@undefined,!1);return}@readableStreamDefaultReaderRead(pipeState.reader).@then((result)=>{const canWrite=!result.done&&@getByIdDirectPrivate(pipeState.writer,\"stream\")!==@undefined;if(pipeState.pendingReadPromiseCapability.resolve.@call(@undefined,canWrite),!canWrite)return;pipeState.pendingWritePromise=@writableStreamDefaultWriterWrite(pipeState.writer,result.value)},(e)=>{pipeState.pendingReadPromiseCapability.resolve.@call(@undefined,!1)})},(e)=>{pipeState.pendingReadPromiseCapability.resolve.@call(@undefined,!1)}),pipeState.pendingReadPromiseCapability.promise})\n"; // pipeToErrorsMustBePropagatedForward const JSC::ConstructAbility s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCodeLength = 436; +const int s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCodeLength = 539; static const JSC::Intrinsic s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCode = "(function (s){\"use strict\";const _=()=>{s.pendingReadPromiseCapability.resolve.@call(@undefined,!1);const g=@getByIdDirectPrivate(s.source,\"storedError\");if(!s.preventAbort){@pipeToShutdownWithAction(s,()=>@writableStreamAbort(s.destination,g),g);return}@pipeToShutdown(s,g)};if(@getByIdDirectPrivate(s.source,\"state\")===@streamErrored){_();return}@getByIdDirectPrivate(s.reader,\"closedPromiseCapability\").promise.@then(@undefined,_)})\n"; +const char* const s_readableStreamInternalsPipeToErrorsMustBePropagatedForwardCode = "(function (pipeState){\"use strict\";const action=()=>{pipeState.pendingReadPromiseCapability.resolve.@call(@undefined,!1);const error=@getByIdDirectPrivate(pipeState.source,\"storedError\");if(!pipeState.preventAbort){@pipeToShutdownWithAction(pipeState,()=>@writableStreamAbort(pipeState.destination,error),error);return}@pipeToShutdown(pipeState,error)};if(@getByIdDirectPrivate(pipeState.source,\"state\")===@streamErrored){action();return}@getByIdDirectPrivate(pipeState.reader,\"closedPromiseCapability\").promise.@then(@undefined,action)})\n"; // pipeToErrorsMustBePropagatedBackward const JSC::ConstructAbility s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCodeLength = 368; +const int s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCodeLength = 463; static const JSC::Intrinsic s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCode = "(function (m){\"use strict\";const h=()=>{const d=@getByIdDirectPrivate(m.destination,\"storedError\");if(!m.preventCancel){@pipeToShutdownWithAction(m,()=>@readableStreamCancel(m.source,d),d);return}@pipeToShutdown(m,d)};if(@getByIdDirectPrivate(m.destination,\"state\")===\"errored\"){h();return}@getByIdDirectPrivate(m.writer,\"closedPromise\").promise.@then(@undefined,h)})\n"; +const char* const s_readableStreamInternalsPipeToErrorsMustBePropagatedBackwardCode = "(function (pipeState){\"use strict\";const action=()=>{const error=@getByIdDirectPrivate(pipeState.destination,\"storedError\");if(!pipeState.preventCancel){@pipeToShutdownWithAction(pipeState,()=>@readableStreamCancel(pipeState.source,error),error);return}@pipeToShutdown(pipeState,error)};if(@getByIdDirectPrivate(pipeState.destination,\"state\")===\"errored\"){action();return}@getByIdDirectPrivate(pipeState.writer,\"closedPromise\").promise.@then(@undefined,action)})\n"; // pipeToClosingMustBePropagatedForward const JSC::ConstructAbility s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCodeLength = 403; +const int s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCodeLength = 482; static const JSC::Intrinsic s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCode = "(function (_){\"use strict\";const r=()=>{if(_.pendingReadPromiseCapability.resolve.@call(@undefined,!1),!_.preventClose){@pipeToShutdownWithAction(_,()=>@writableStreamDefaultWriterCloseWithErrorPropagation(_.writer));return}@pipeToShutdown(_)};if(@getByIdDirectPrivate(_.source,\"state\")===@streamClosed){r();return}@getByIdDirectPrivate(_.reader,\"closedPromiseCapability\").promise.@then(r,@undefined)})\n"; +const char* const s_readableStreamInternalsPipeToClosingMustBePropagatedForwardCode = "(function (pipeState){\"use strict\";const action=()=>{if(pipeState.pendingReadPromiseCapability.resolve.@call(@undefined,!1),!pipeState.preventClose){@pipeToShutdownWithAction(pipeState,()=>@writableStreamDefaultWriterCloseWithErrorPropagation(pipeState.writer));return}@pipeToShutdown(pipeState)};if(@getByIdDirectPrivate(pipeState.source,\"state\")===@streamClosed){action();return}@getByIdDirectPrivate(pipeState.reader,\"closedPromiseCapability\").promise.@then(action,@undefined)})\n"; // pipeToClosingMustBePropagatedBackward const JSC::ConstructAbility s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCodeLength = 324; +const int s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCodeLength = 396; static const JSC::Intrinsic s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCode = "(function (k){\"use strict\";if(!@writableStreamCloseQueuedOrInFlight(k.destination)&&@getByIdDirectPrivate(k.destination,\"state\")!==\"closed\")return;const m=@makeTypeError(\"closing is propagated backward\");if(!k.preventCancel){@pipeToShutdownWithAction(k,()=>@readableStreamCancel(k.source,m),m);return}@pipeToShutdown(k,m)})\n"; +const char* const s_readableStreamInternalsPipeToClosingMustBePropagatedBackwardCode = "(function (pipeState){\"use strict\";if(!@writableStreamCloseQueuedOrInFlight(pipeState.destination)&&@getByIdDirectPrivate(pipeState.destination,\"state\")!==\"closed\")return;const error=@makeTypeError(\"closing is propagated backward\");if(!pipeState.preventCancel){@pipeToShutdownWithAction(pipeState,()=>@readableStreamCancel(pipeState.source,error),error);return}@pipeToShutdown(pipeState,error)})\n"; // pipeToShutdownWithAction const JSC::ConstructAbility s_readableStreamInternalsPipeToShutdownWithActionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToShutdownWithActionCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToShutdownWithActionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToShutdownWithActionCodeLength = 457; +const int s_readableStreamInternalsPipeToShutdownWithActionCodeLength = 605; static const JSC::Intrinsic s_readableStreamInternalsPipeToShutdownWithActionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToShutdownWithActionCode = "(function (_,u){\"use strict\";if(_.shuttingDown)return;_.shuttingDown=!0;const b=arguments.length>2,g=arguments[2],d=()=>{u().@then(()=>{if(b)@pipeToFinalize(_,g);else @pipeToFinalize(_)},(h)=>{@pipeToFinalize(_,h)})};if(@getByIdDirectPrivate(_.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(_.destination)){_.pendingReadPromiseCapability.promise.@then(()=>{_.pendingWritePromise.@then(d,d)},(m)=>@pipeToFinalize(_,m));return}d()})\n"; +const char* const s_readableStreamInternalsPipeToShutdownWithActionCode = "(function (pipeState,action){\"use strict\";if(pipeState.shuttingDown)return;pipeState.shuttingDown=!0;const hasError=arguments.length>2,error=arguments[2],finalize=()=>{action().@then(()=>{if(hasError)@pipeToFinalize(pipeState,error);else @pipeToFinalize(pipeState)},(e)=>{@pipeToFinalize(pipeState,e)})};if(@getByIdDirectPrivate(pipeState.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(pipeState.destination)){pipeState.pendingReadPromiseCapability.promise.@then(()=>{pipeState.pendingWritePromise.@then(finalize,finalize)},(e)=>@pipeToFinalize(pipeState,e));return}finalize()})\n"; // pipeToShutdown const JSC::ConstructAbility s_readableStreamInternalsPipeToShutdownCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToShutdownCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToShutdownCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToShutdownCodeLength = 410; +const int s_readableStreamInternalsPipeToShutdownCodeLength = 540; static const JSC::Intrinsic s_readableStreamInternalsPipeToShutdownCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToShutdownCode = "(function (_){\"use strict\";if(_.shuttingDown)return;_.shuttingDown=!0;const d=arguments.length>1,m=arguments[1],c=()=>{if(d)@pipeToFinalize(_,m);else @pipeToFinalize(_)};if(@getByIdDirectPrivate(_.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(_.destination)){_.pendingReadPromiseCapability.promise.@then(()=>{_.pendingWritePromise.@then(c,c)},(u)=>@pipeToFinalize(_,u));return}c()})\n"; +const char* const s_readableStreamInternalsPipeToShutdownCode = "(function (pipeState){\"use strict\";if(pipeState.shuttingDown)return;pipeState.shuttingDown=!0;const hasError=arguments.length>1,error=arguments[1],finalize=()=>{if(hasError)@pipeToFinalize(pipeState,error);else @pipeToFinalize(pipeState)};if(@getByIdDirectPrivate(pipeState.destination,\"state\")===\"writable\"&&!@writableStreamCloseQueuedOrInFlight(pipeState.destination)){pipeState.pendingReadPromiseCapability.promise.@then(()=>{pipeState.pendingWritePromise.@then(finalize,finalize)},(e)=>@pipeToFinalize(pipeState,e));return}finalize()})\n"; // pipeToFinalize const JSC::ConstructAbility s_readableStreamInternalsPipeToFinalizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsPipeToFinalizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsPipeToFinalizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsPipeToFinalizeCodeLength = 257; +const int s_readableStreamInternalsPipeToFinalizeCodeLength = 305; static const JSC::Intrinsic s_readableStreamInternalsPipeToFinalizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsPipeToFinalizeCode = "(function (l){\"use strict\";if(@writableStreamDefaultWriterRelease(l.writer),@readableStreamReaderGenericRelease(l.reader),l.finalized=!0,arguments.length>1)l.promiseCapability.reject.@call(@undefined,arguments[1]);else l.promiseCapability.resolve.@call()})\n"; +const char* const s_readableStreamInternalsPipeToFinalizeCode = "(function (pipeState){\"use strict\";if(@writableStreamDefaultWriterRelease(pipeState.writer),@readableStreamReaderGenericRelease(pipeState.reader),pipeState.finalized=!0,arguments.length>1)pipeState.promiseCapability.reject.@call(@undefined,arguments[1]);else pipeState.promiseCapability.resolve.@call()})\n"; // readableStreamTee const JSC::ConstructAbility s_readableStreamInternalsReadableStreamTeeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamTeeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamTeeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamTeeCodeLength = 1102; +const int s_readableStreamInternalsReadableStreamTeeCodeLength = 1383; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamTeeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamTeeCode = "(function (i,q){\"use strict\";@assert(@isReadableStream(i)),@assert(typeof q===\"boolean\");var v=@getByIdDirectPrivate(i,\"start\");if(v)@putByIdDirectPrivate(i,\"start\",@undefined),v();const w=new @ReadableStreamDefaultReader(i),_={closedOrErrored:!1,canceled1:!1,canceled2:!1,reason1:@undefined,reason2:@undefined};_.cancelPromiseCapability=@newPromiseCapability(@Promise);const x=@readableStreamTeePullFunction(_,w,q),f={};@putByIdDirectPrivate(f,\"pull\",x),@putByIdDirectPrivate(f,\"cancel\",@readableStreamTeeBranch1CancelFunction(_,i));const g={};@putByIdDirectPrivate(g,\"pull\",x),@putByIdDirectPrivate(g,\"cancel\",@readableStreamTeeBranch2CancelFunction(_,i));const j=new @ReadableStream(f),k=new @ReadableStream(g);return @getByIdDirectPrivate(w,\"closedPromiseCapability\").promise.@then(@undefined,function(y){if(_.closedOrErrored)return;if(@readableStreamDefaultControllerError(j.@readableStreamController,y),@readableStreamDefaultControllerError(k.@readableStreamController,y),_.closedOrErrored=!0,!_.canceled1||!_.canceled2)_.cancelPromiseCapability.resolve.@call()}),_.branch1=j,_.branch2=k,[j,k]})\n"; +const char* const s_readableStreamInternalsReadableStreamTeeCode = "(function (stream,shouldClone){\"use strict\";var start_=@getByIdDirectPrivate(stream,\"start\");if(start_)@putByIdDirectPrivate(stream,\"start\",@undefined),start_();const reader=new @ReadableStreamDefaultReader(stream),teeState={closedOrErrored:!1,canceled1:!1,canceled2:!1,reason1:@undefined,reason2:@undefined};teeState.cancelPromiseCapability=@newPromiseCapability(@Promise);const pullFunction=@readableStreamTeePullFunction(teeState,reader,shouldClone),branch1Source={};@putByIdDirectPrivate(branch1Source,\"pull\",pullFunction),@putByIdDirectPrivate(branch1Source,\"cancel\",@readableStreamTeeBranch1CancelFunction(teeState,stream));const branch2Source={};@putByIdDirectPrivate(branch2Source,\"pull\",pullFunction),@putByIdDirectPrivate(branch2Source,\"cancel\",@readableStreamTeeBranch2CancelFunction(teeState,stream));const branch1=new @ReadableStream(branch1Source),branch2=new @ReadableStream(branch2Source);return @getByIdDirectPrivate(reader,\"closedPromiseCapability\").promise.@then(@undefined,function(e){if(teeState.closedOrErrored)return;if(@readableStreamDefaultControllerError(branch1.@readableStreamController,e),@readableStreamDefaultControllerError(branch2.@readableStreamController,e),teeState.closedOrErrored=!0,!teeState.canceled1||!teeState.canceled2)teeState.cancelPromiseCapability.resolve.@call()}),teeState.branch1=branch1,teeState.branch2=branch2,[branch1,branch2]})\n"; // readableStreamTeePullFunction const JSC::ConstructAbility s_readableStreamInternalsReadableStreamTeePullFunctionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamTeePullFunctionCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamTeePullFunctionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamTeePullFunctionCodeLength = 763; +const int s_readableStreamInternalsReadableStreamTeePullFunctionCodeLength = 866; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamTeePullFunctionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamTeePullFunctionCode = "(function (_,c,f){\"use strict\";return function(){@Promise.prototype.@then.@call(@readableStreamDefaultReaderRead(c),function(i){if(@assert(@isObject(i)),@assert(typeof i.done===\"boolean\"),i.done&&!_.closedOrErrored){if(!_.canceled1)@readableStreamDefaultControllerClose(_.branch1.@readableStreamController);if(!_.canceled2)@readableStreamDefaultControllerClose(_.branch2.@readableStreamController);if(_.closedOrErrored=!0,!_.canceled1||!_.canceled2)_.cancelPromiseCapability.resolve.@call()}if(_.closedOrErrored)return;if(!_.canceled1)@readableStreamDefaultControllerEnqueue(_.branch1.@readableStreamController,i.value);if(!_.canceled2)@readableStreamDefaultControllerEnqueue(_.branch2.@readableStreamController,f\?@structuredCloneForStream(i.value):i.value)})}})\n"; +const char* const s_readableStreamInternalsReadableStreamTeePullFunctionCode = "(function (teeState,reader,shouldClone){\"use strict\";return function(){@Promise.prototype.@then.@call(@readableStreamDefaultReaderRead(reader),function(result){if(result.done&&!teeState.closedOrErrored){if(!teeState.canceled1)@readableStreamDefaultControllerClose(teeState.branch1.@readableStreamController);if(!teeState.canceled2)@readableStreamDefaultControllerClose(teeState.branch2.@readableStreamController);if(teeState.closedOrErrored=!0,!teeState.canceled1||!teeState.canceled2)teeState.cancelPromiseCapability.resolve.@call()}if(teeState.closedOrErrored)return;if(!teeState.canceled1)@readableStreamDefaultControllerEnqueue(teeState.branch1.@readableStreamController,result.value);if(!teeState.canceled2)@readableStreamDefaultControllerEnqueue(teeState.branch2.@readableStreamController,shouldClone\?@structuredCloneForStream(result.value):result.value)})}})\n"; // readableStreamTeeBranch1CancelFunction const JSC::ConstructAbility s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeLength = 257; +const int s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeLength = 330; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCode = "(function (d,i){\"use strict\";return function(n){if(d.canceled1=!0,d.reason1=n,d.canceled2)@readableStreamCancel(i,[d.reason1,d.reason2]).@then(d.cancelPromiseCapability.@resolve,d.cancelPromiseCapability.@reject);return d.cancelPromiseCapability.promise}})\n"; +const char* const s_readableStreamInternalsReadableStreamTeeBranch1CancelFunctionCode = "(function (teeState,stream){\"use strict\";return function(r){if(teeState.canceled1=!0,teeState.reason1=r,teeState.canceled2)@readableStreamCancel(stream,[teeState.reason1,teeState.reason2]).@then(teeState.cancelPromiseCapability.@resolve,teeState.cancelPromiseCapability.@reject);return teeState.cancelPromiseCapability.promise}})\n"; // readableStreamTeeBranch2CancelFunction const JSC::ConstructAbility s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCodeLength = 257; +const int s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCodeLength = 330; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCode = "(function (d,i){\"use strict\";return function(n){if(d.canceled2=!0,d.reason2=n,d.canceled1)@readableStreamCancel(i,[d.reason1,d.reason2]).@then(d.cancelPromiseCapability.@resolve,d.cancelPromiseCapability.@reject);return d.cancelPromiseCapability.promise}})\n"; +const char* const s_readableStreamInternalsReadableStreamTeeBranch2CancelFunctionCode = "(function (teeState,stream){\"use strict\";return function(r){if(teeState.canceled2=!0,teeState.reason2=r,teeState.canceled1)@readableStreamCancel(stream,[teeState.reason1,teeState.reason2]).@then(teeState.cancelPromiseCapability.@resolve,teeState.cancelPromiseCapability.@reject);return teeState.cancelPromiseCapability.promise}})\n"; // isReadableStream const JSC::ConstructAbility s_readableStreamInternalsIsReadableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsIsReadableStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsIsReadableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsIsReadableStreamCodeLength = 115; +const int s_readableStreamInternalsIsReadableStreamCodeLength = 130; static const JSC::Intrinsic s_readableStreamInternalsIsReadableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsIsReadableStreamCode = "(function (d){\"use strict\";return @isObject(d)&&@getByIdDirectPrivate(d,\"readableStreamController\")!==@undefined})\n"; +const char* const s_readableStreamInternalsIsReadableStreamCode = "(function (stream){\"use strict\";return @isObject(stream)&&@getByIdDirectPrivate(stream,\"readableStreamController\")!==@undefined})\n"; // isReadableStreamDefaultReader const JSC::ConstructAbility s_readableStreamInternalsIsReadableStreamDefaultReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsIsReadableStreamDefaultReaderCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsIsReadableStreamDefaultReaderCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsIsReadableStreamDefaultReaderCodeLength = 92; +const int s_readableStreamInternalsIsReadableStreamDefaultReaderCodeLength = 107; static const JSC::Intrinsic s_readableStreamInternalsIsReadableStreamDefaultReaderCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsIsReadableStreamDefaultReaderCode = "(function (i){\"use strict\";return @isObject(i)&&!!@getByIdDirectPrivate(i,\"readRequests\")})\n"; +const char* const s_readableStreamInternalsIsReadableStreamDefaultReaderCode = "(function (reader){\"use strict\";return @isObject(reader)&&!!@getByIdDirectPrivate(reader,\"readRequests\")})\n"; // isReadableStreamDefaultController const JSC::ConstructAbility s_readableStreamInternalsIsReadableStreamDefaultControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsIsReadableStreamDefaultControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsIsReadableStreamDefaultControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsIsReadableStreamDefaultControllerCodeLength = 96; +const int s_readableStreamInternalsIsReadableStreamDefaultControllerCodeLength = 123; static const JSC::Intrinsic s_readableStreamInternalsIsReadableStreamDefaultControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsIsReadableStreamDefaultControllerCode = "(function (i){\"use strict\";return @isObject(i)&&!!@getByIdDirectPrivate(i,\"underlyingSource\")})\n"; +const char* const s_readableStreamInternalsIsReadableStreamDefaultControllerCode = "(function (controller){\"use strict\";return @isObject(controller)&&!!@getByIdDirectPrivate(controller,\"underlyingSource\")})\n"; // readDirectStream const JSC::ConstructAbility s_readableStreamInternalsReadDirectStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadDirectStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadDirectStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadDirectStreamCodeLength = 916; +const int s_readableStreamInternalsReadDirectStreamCodeLength = 1281; static const JSC::Intrinsic s_readableStreamInternalsReadDirectStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadDirectStreamCode = "(function (_,q,f){\"use strict\";@putByIdDirectPrivate(_,\"underlyingSource\",@undefined),@putByIdDirectPrivate(_,\"start\",@undefined);function w(j,v){if(v&&f\?.cancel){try{var A=f.cancel(v);@markPromiseAsHandled(A)}catch(B){}f=@undefined}if(j){if(@putByIdDirectPrivate(j,\"readableStreamController\",@undefined),@putByIdDirectPrivate(j,\"reader\",@undefined),v)@putByIdDirectPrivate(j,\"state\",@streamErrored),@putByIdDirectPrivate(j,\"storedError\",v);else @putByIdDirectPrivate(j,\"state\",@streamClosed);j=@undefined}}if(!f.pull){w();return}if(!@isCallable(f.pull)){w(),@throwTypeError(\"pull is not a function\");return}@putByIdDirectPrivate(_,\"readableStreamController\",q);const x=@getByIdDirectPrivate(_,\"highWaterMark\");q.start({highWaterMark:!x||x<64\?64:x}),@startDirectStream.@call(q,_,f.pull,w,_.@asyncContext),@putByIdDirectPrivate(_,\"reader\",{});var z=f.pull(q);if(q=@undefined,z&&@isPromise(z))return z.@then(()=>{})})\n"; +const char* const s_readableStreamInternalsReadDirectStreamCode = "(function (stream,sink,underlyingSource){\"use strict\";@putByIdDirectPrivate(stream,\"underlyingSource\",@undefined),@putByIdDirectPrivate(stream,\"start\",@undefined);function close(stream2,reason){if(reason&&underlyingSource\?.cancel){try{var prom=underlyingSource.cancel(reason);@markPromiseAsHandled(prom)}catch(e){}underlyingSource=@undefined}if(stream2){if(@putByIdDirectPrivate(stream2,\"readableStreamController\",@undefined),@putByIdDirectPrivate(stream2,\"reader\",@undefined),reason)@putByIdDirectPrivate(stream2,\"state\",@streamErrored),@putByIdDirectPrivate(stream2,\"storedError\",reason);else @putByIdDirectPrivate(stream2,\"state\",@streamClosed);stream2=@undefined}}if(!underlyingSource.pull){close();return}if(!@isCallable(underlyingSource.pull)){close(),@throwTypeError(\"pull is not a function\");return}@putByIdDirectPrivate(stream,\"readableStreamController\",sink);const highWaterMark=@getByIdDirectPrivate(stream,\"highWaterMark\");sink.start({highWaterMark:!highWaterMark||highWaterMark<64\?64:highWaterMark}),@startDirectStream.@call(sink,stream,underlyingSource.pull,close,stream.@asyncContext),@putByIdDirectPrivate(stream,\"reader\",{});var maybePromise=underlyingSource.pull(sink);if(sink=@undefined,maybePromise&&@isPromise(maybePromise))return maybePromise.@then(()=>{})})\n"; // assignToStream const JSC::ConstructAbility s_readableStreamInternalsAssignToStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsAssignToStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsAssignToStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamInternalsAssignToStreamCodeLength = 221; +const int s_readableStreamInternalsAssignToStreamCodeLength = 318; static const JSC::Intrinsic s_readableStreamInternalsAssignToStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsAssignToStreamCode = "(function (h,_){\"use strict\";var b=@getByIdDirectPrivate(h,\"underlyingSource\");if(b)try{return @readDirectStream(h,_,b)}catch(f){throw f}finally{b=@undefined,h=@undefined,_=@undefined}return @readStreamIntoSink(h,_,!0)})\n"; +const char* const s_readableStreamInternalsAssignToStreamCode = "(function (stream,sink){\"use strict\";var underlyingSource=@getByIdDirectPrivate(stream,\"underlyingSource\");if(underlyingSource)try{return @readDirectStream(stream,sink,underlyingSource)}catch(e){throw e}finally{underlyingSource=@undefined,stream=@undefined,sink=@undefined}return @readStreamIntoSink(stream,sink,!0)})\n"; // readStreamIntoSink const JSC::ConstructAbility s_readableStreamInternalsReadStreamIntoSinkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadStreamIntoSinkCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadStreamIntoSinkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadStreamIntoSinkCodeLength = 1411; +const int s_readableStreamInternalsReadStreamIntoSinkCodeLength = 1943; static const JSC::Intrinsic s_readableStreamInternalsReadStreamIntoSinkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadStreamIntoSinkCode = "(async function (_,c,B){\"use strict\";var j=!1,x=!1;try{var P=_.getReader(),D=P.readMany();if(D&&@isPromise(D))D=await D;if(D.done)return j=!0,c.end();var I=D.value.length;const f=@getByIdDirectPrivate(_,\"highWaterMark\");if(B)@startDirectStream.@call(c,_,@undefined,()=>!x&&@markPromiseAsHandled(_.cancel()),_.@asyncContext);c.start({highWaterMark:f||0});for(var z=0,E=D.value,F=D.value.length;z!didThrow&&@markPromiseAsHandled(stream.cancel()),stream.@asyncContext);sink.start({highWaterMark:highWaterMark||0});for(var i=0,values=many.value,length=many.value.length;i{var b=@createFulfilledPromise({value:v,done:!1});return v=@undefined,@readableStreamClose(c),c=@undefined,b}}else if(this._pendingRead){var y=this._pendingRead;this._pendingRead=@undefined,@putByIdDirectPrivate(this,\"pull\",@noopDoneFunction),@fulfillPromise(y,{value:@undefined,done:!0})}@readableStreamClose(c)})\n"; +const char* const s_readableStreamInternalsOnCloseDirectStreamCode = "(function (reason){\"use strict\";var stream=this.@controlledReadableStream;if(!stream||@getByIdDirectPrivate(stream,\"state\")!==@streamReadable)return;if(this._deferClose!==0){this._deferClose=1,this._deferCloseReason=reason;return}if(@putByIdDirectPrivate(stream,\"state\",@streamClosing),typeof this.@underlyingSource.close===\"function\")try{this.@underlyingSource.close.@call(this.@underlyingSource,reason)}catch(e){}var flushed;try{flushed=this.@sink.end(),@putByIdDirectPrivate(this,\"sink\",@undefined)}catch(e){if(this._pendingRead){var read=this._pendingRead;this._pendingRead=@undefined,@rejectPromise(read,e)}@readableStreamError(stream,e);return}this.error=this.flush=this.write=this.close=this.end=@onReadableStreamDirectControllerClosed;var reader=@getByIdDirectPrivate(stream,\"reader\");if(reader&&@isReadableStreamDefaultReader(reader)){var _pendingRead=this._pendingRead;if(_pendingRead&&@isPromise(_pendingRead)&&flushed\?.byteLength){this._pendingRead=@undefined,@fulfillPromise(_pendingRead,{value:flushed,done:!1}),@readableStreamClose(stream);return}}if(flushed\?.byteLength){var requests=@getByIdDirectPrivate(reader,\"readRequests\");if(requests\?.isNotEmpty()){@readableStreamFulfillReadRequest(stream,flushed,!1),@readableStreamClose(stream);return}@putByIdDirectPrivate(stream,\"state\",@streamReadable),this.@pull=()=>{var thisResult=@createFulfilledPromise({value:flushed,done:!1});return flushed=@undefined,@readableStreamClose(stream),stream=@undefined,thisResult}}else if(this._pendingRead){var read=this._pendingRead;this._pendingRead=@undefined,@putByIdDirectPrivate(this,\"pull\",@noopDoneFunction),@fulfillPromise(read,{value:@undefined,done:!0})}@readableStreamClose(stream)})\n"; // onFlushDirectStream const JSC::ConstructAbility s_readableStreamInternalsOnFlushDirectStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsOnFlushDirectStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsOnFlushDirectStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsOnFlushDirectStreamCodeLength = 591; +const int s_readableStreamInternalsOnFlushDirectStreamCodeLength = 722; static const JSC::Intrinsic s_readableStreamInternalsOnFlushDirectStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsOnFlushDirectStreamCode = "(function (){\"use strict\";var B=this.@controlledReadableStream,i=@getByIdDirectPrivate(B,\"reader\");if(!i||!@isReadableStreamDefaultReader(i))return;var b=this._pendingRead;if(this._pendingRead=@undefined,b&&@isPromise(b)){var c=this.@sink.flush();if(c\?.byteLength)this._pendingRead=@getByIdDirectPrivate(B,\"readRequests\")\?.shift(),@fulfillPromise(b,{value:c,done:!1});else this._pendingRead=b}else if(@getByIdDirectPrivate(B,\"readRequests\")\?.isNotEmpty()){var c=this.@sink.flush();if(c\?.byteLength)@readableStreamFulfillReadRequest(B,c,!1)}else if(this._deferFlush===-1)this._deferFlush=1})\n"; +const char* const s_readableStreamInternalsOnFlushDirectStreamCode = "(function (){\"use strict\";var stream=this.@controlledReadableStream,reader=@getByIdDirectPrivate(stream,\"reader\");if(!reader||!@isReadableStreamDefaultReader(reader))return;var _pendingRead=this._pendingRead;if(this._pendingRead=@undefined,_pendingRead&&@isPromise(_pendingRead)){var flushed=this.@sink.flush();if(flushed\?.byteLength)this._pendingRead=@getByIdDirectPrivate(stream,\"readRequests\")\?.shift(),@fulfillPromise(_pendingRead,{value:flushed,done:!1});else this._pendingRead=_pendingRead}else if(@getByIdDirectPrivate(stream,\"readRequests\")\?.isNotEmpty()){var flushed=this.@sink.flush();if(flushed\?.byteLength)@readableStreamFulfillReadRequest(stream,flushed,!1)}else if(this._deferFlush===-1)this._deferFlush=1})\n"; // createTextStream const JSC::ConstructAbility s_readableStreamInternalsCreateTextStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsCreateTextStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsCreateTextStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsCreateTextStreamCodeLength = 983; +const int s_readableStreamInternalsCreateTextStreamCodeLength = 1479; static const JSC::Intrinsic s_readableStreamInternalsCreateTextStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsCreateTextStreamCode = "(function (G){\"use strict\";var q,v=[],x=!1,z=!1,j=\"\",C=@toLength(0),F=@newPromiseCapability(@Promise),A=!1;return q={start(){},write(_){if(typeof _===\"string\"){var w=@toLength(_.length);if(w>0)j+=_,x=!0,C+=w;return w}if(!_||!(@ArrayBuffer.@isView(_)||_ instanceof @ArrayBuffer))@throwTypeError(\"Expected text, ArrayBuffer or ArrayBufferView\");const E=@toLength(_.byteLength);if(E>0)if(z=!0,j.length>0)@arrayPush(v,j,_),j=\"\";else @arrayPush(v,_);return C+=E,E},flush(){return 0},end(){if(A)return\"\";return q.fulfill()},fulfill(){A=!0;const _=q.finishInternal();return @fulfillPromise(F.promise,_),_},finishInternal(){if(!x&&!z)return\"\";if(x&&!z)return j;if(z&&!x)return new globalThis.TextDecoder().decode(@Bun.concatArrayBuffers(v));var _=new @Bun.ArrayBufferSink;_.start({highWaterMark:C,asUint8Array:!0});for(let w of v)_.write(w);if(v.length=0,j.length>0)_.write(j),j=\"\";return new globalThis.TextDecoder().decode(_.end())},close(){try{if(!A)A=!0,q.fulfill()}catch(_){}}},[q,F]})\n"; +const char* const s_readableStreamInternalsCreateTextStreamCode = "(function (highWaterMark){\"use strict\";var sink,array=[],hasString=!1,hasBuffer=!1,rope=\"\",estimatedLength=@toLength(0),capability=@newPromiseCapability(@Promise),calledDone=!1;return sink={start(){},write(chunk){if(typeof chunk===\"string\"){var chunkLength=@toLength(chunk.length);if(chunkLength>0)rope+=chunk,hasString=!0,estimatedLength+=chunkLength;return chunkLength}if(!chunk||!(@ArrayBuffer.@isView(chunk)||chunk instanceof @ArrayBuffer))@throwTypeError(\"Expected text, ArrayBuffer or ArrayBufferView\");const byteLength=@toLength(chunk.byteLength);if(byteLength>0)if(hasBuffer=!0,rope.length>0)@arrayPush(array,rope,chunk),rope=\"\";else @arrayPush(array,chunk);return estimatedLength+=byteLength,byteLength},flush(){return 0},end(){if(calledDone)return\"\";return sink.fulfill()},fulfill(){calledDone=!0;const result=sink.finishInternal();return @fulfillPromise(capability.promise,result),result},finishInternal(){if(!hasString&&!hasBuffer)return\"\";if(hasString&&!hasBuffer)return rope;if(hasBuffer&&!hasString)return new globalThis.TextDecoder().decode(@Bun.concatArrayBuffers(array));var arrayBufferSink=new @Bun.ArrayBufferSink;arrayBufferSink.start({highWaterMark:estimatedLength,asUint8Array:!0});for(let item of array)arrayBufferSink.write(item);if(array.length=0,rope.length>0)arrayBufferSink.write(rope),rope=\"\";return new globalThis.TextDecoder().decode(arrayBufferSink.end())},close(){try{if(!calledDone)calledDone=!0,sink.fulfill()}catch(e){}}},[sink,capability]})\n"; // initializeTextStream const JSC::ConstructAbility s_readableStreamInternalsInitializeTextStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsInitializeTextStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsInitializeTextStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsInitializeTextStreamCodeLength = 578; +const int s_readableStreamInternalsInitializeTextStreamCodeLength = 685; static const JSC::Intrinsic s_readableStreamInternalsInitializeTextStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsInitializeTextStreamCode = "(function (m,p){\"use strict\";var[_,b]=@createTextStream(p),f={@underlyingSource:m,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:_,close:@onCloseDirectStream,write:_.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",f),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),b})\n"; +const char* const s_readableStreamInternalsInitializeTextStreamCode = "(function (underlyingSource,highWaterMark){\"use strict\";var[sink,closingPromise]=@createTextStream(highWaterMark),controller={@underlyingSource:underlyingSource,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:sink,close:@onCloseDirectStream,write:sink.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",controller),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),closingPromise})\n"; // initializeArrayStream const JSC::ConstructAbility s_readableStreamInternalsInitializeArrayStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsInitializeArrayStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsInitializeArrayStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsInitializeArrayStreamCodeLength = 796; +const int s_readableStreamInternalsInitializeArrayStreamCodeLength = 990; static const JSC::Intrinsic s_readableStreamInternalsInitializeArrayStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsInitializeArrayStreamCode = "(function (v,x){\"use strict\";var _=[],b=@newPromiseCapability(@Promise),p=!1;function j(){return p=!0,b.resolve.@call(@undefined,_),_}var q={start(){},write(t){return @arrayPush(_,t),t.byteLength||t.length},flush(){return 0},end(){if(p)return[];return j()},close(){if(!p)j()}},w={@underlyingSource:v,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:q,close:@onCloseDirectStream,write:q.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",w),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),b})\n"; +const char* const s_readableStreamInternalsInitializeArrayStreamCode = "(function (underlyingSource,highWaterMark){\"use strict\";var array=[],closingPromise=@newPromiseCapability(@Promise),calledDone=!1;function fulfill(){return calledDone=!0,closingPromise.resolve.@call(@undefined,array),array}var sink={start(){},write(chunk){return @arrayPush(array,chunk),chunk.byteLength||chunk.length},flush(){return 0},end(){if(calledDone)return[];return fulfill()},close(){if(!calledDone)fulfill()}},controller={@underlyingSource:underlyingSource,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:sink,close:@onCloseDirectStream,write:sink.write,error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};return @putByIdDirectPrivate(this,\"readableStreamController\",controller),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined),closingPromise})\n"; // initializeArrayBufferStream const JSC::ConstructAbility s_readableStreamInternalsInitializeArrayBufferStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsInitializeArrayBufferStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsInitializeArrayBufferStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsInitializeArrayBufferStreamCodeLength = 690; +const int s_readableStreamInternalsInitializeArrayBufferStreamCodeLength = 793; static const JSC::Intrinsic s_readableStreamInternalsInitializeArrayBufferStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsInitializeArrayBufferStreamCode = "(function (w,m){\"use strict\";var D=m&&typeof m===\"number\"\?{highWaterMark:m,stream:!0,asUint8Array:!0}:{stream:!0,asUint8Array:!0},_=new @Bun.ArrayBufferSink;_.start(D);var b={@underlyingSource:w,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:_,close:@onCloseDirectStream,write:_.write.bind(_),error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};@putByIdDirectPrivate(this,\"readableStreamController\",b),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined)})\n"; +const char* const s_readableStreamInternalsInitializeArrayBufferStreamCode = "(function (underlyingSource,highWaterMark){\"use strict\";var opts=highWaterMark&&typeof highWaterMark===\"number\"\?{highWaterMark,stream:!0,asUint8Array:!0}:{stream:!0,asUint8Array:!0},sink=new @Bun.ArrayBufferSink;sink.start(opts);var controller={@underlyingSource:underlyingSource,@pull:@onPullDirectStream,@controlledReadableStream:this,@sink:sink,close:@onCloseDirectStream,write:sink.write.bind(sink),error:@handleDirectStreamError,end:@onCloseDirectStream,@close:@onCloseDirectStream,flush:@onFlushDirectStream,_pendingRead:@undefined,_deferClose:0,_deferFlush:0,_deferCloseReason:@undefined,_handleError:@undefined};@putByIdDirectPrivate(this,\"readableStreamController\",controller),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"start\",@undefined)})\n"; // readableStreamError const JSC::ConstructAbility s_readableStreamInternalsReadableStreamErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamErrorCodeLength = 838; +const int s_readableStreamInternalsReadableStreamErrorCodeLength = 895; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamErrorCode = "(function (n,f){\"use strict\";@assert(@isReadableStream(n)),@assert(@getByIdDirectPrivate(n,\"state\")===@streamReadable),@putByIdDirectPrivate(n,\"state\",@streamErrored),@putByIdDirectPrivate(n,\"storedError\",f);const _=@getByIdDirectPrivate(n,\"reader\");if(!_)return;if(@isReadableStreamDefaultReader(_)){const c=@getByIdDirectPrivate(_,\"readRequests\");@putByIdDirectPrivate(_,\"readRequests\",@createFIFO());for(var i=c.shift();i;i=c.shift())@rejectPromise(i,f)}else{@assert(@isReadableStreamBYOBReader(_));const c=@getByIdDirectPrivate(_,\"readIntoRequests\");@putByIdDirectPrivate(_,\"readIntoRequests\",@createFIFO());for(var i=c.shift();i;i=c.shift())@rejectPromise(i,f)}@getByIdDirectPrivate(_,\"closedPromiseCapability\").reject.@call(@undefined,f);const h=@getByIdDirectPrivate(_,\"closedPromiseCapability\").promise;@markPromiseAsHandled(h)})\n"; +const char* const s_readableStreamInternalsReadableStreamErrorCode = "(function (stream,error){\"use strict\";@putByIdDirectPrivate(stream,\"state\",@streamErrored),@putByIdDirectPrivate(stream,\"storedError\",error);const reader=@getByIdDirectPrivate(stream,\"reader\");if(!reader)return;if(@isReadableStreamDefaultReader(reader)){const requests=@getByIdDirectPrivate(reader,\"readRequests\");@putByIdDirectPrivate(reader,\"readRequests\",@createFIFO());for(var request=requests.shift();request;request=requests.shift())@rejectPromise(request,error)}else{const requests=@getByIdDirectPrivate(reader,\"readIntoRequests\");@putByIdDirectPrivate(reader,\"readIntoRequests\",@createFIFO());for(var request=requests.shift();request;request=requests.shift())@rejectPromise(request,error)}@getByIdDirectPrivate(reader,\"closedPromiseCapability\").reject.@call(@undefined,error);const promise=@getByIdDirectPrivate(reader,\"closedPromiseCapability\").promise;@markPromiseAsHandled(promise)})\n"; // readableStreamDefaultControllerShouldCallPull const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCodeLength = 477; +const int s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCodeLength = 518; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCode = "(function (h){\"use strict\";const i=@getByIdDirectPrivate(h,\"controlledReadableStream\");if(!@readableStreamDefaultControllerCanCloseOrEnqueue(h))return!1;if(@getByIdDirectPrivate(h,\"started\")!==1)return!1;if((!@isReadableStreamLocked(i)||!@getByIdDirectPrivate(@getByIdDirectPrivate(i,\"reader\"),\"readRequests\")\?.isNotEmpty())&&@readableStreamDefaultControllerGetDesiredSize(h)<=0)return!1;const v=@readableStreamDefaultControllerGetDesiredSize(h);return @assert(v!==null),v>0})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerShouldCallPullCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");if(!@readableStreamDefaultControllerCanCloseOrEnqueue(controller))return!1;if(@getByIdDirectPrivate(controller,\"started\")!==1)return!1;if((!@isReadableStreamLocked(stream)||!@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\")\?.isNotEmpty())&&@readableStreamDefaultControllerGetDesiredSize(controller)<=0)return!1;return @readableStreamDefaultControllerGetDesiredSize(controller)>0})\n"; // readableStreamDefaultControllerCallPullIfNeeded const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCodeLength = 859; +const int s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCodeLength = 961; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCode = "(function (i){\"use strict\";const _=@getByIdDirectPrivate(i,\"controlledReadableStream\");if(!@readableStreamDefaultControllerCanCloseOrEnqueue(i))return;if(@getByIdDirectPrivate(i,\"started\")!==1)return;if((!@isReadableStreamLocked(_)||!@getByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"readRequests\")\?.isNotEmpty())&&@readableStreamDefaultControllerGetDesiredSize(i)<=0)return;if(@getByIdDirectPrivate(i,\"pulling\")){@putByIdDirectPrivate(i,\"pullAgain\",!0);return}@assert(!@getByIdDirectPrivate(i,\"pullAgain\")),@putByIdDirectPrivate(i,\"pulling\",!0),@getByIdDirectPrivate(i,\"pullAlgorithm\").@call(@undefined).@then(function(){if(@putByIdDirectPrivate(i,\"pulling\",!1),@getByIdDirectPrivate(i,\"pullAgain\"))@putByIdDirectPrivate(i,\"pullAgain\",!1),@readableStreamDefaultControllerCallPullIfNeeded(i)},function(d){@readableStreamDefaultControllerError(i,d)})})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerCallPullIfNeededCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");if(!@readableStreamDefaultControllerCanCloseOrEnqueue(controller))return;if(@getByIdDirectPrivate(controller,\"started\")!==1)return;if((!@isReadableStreamLocked(stream)||!@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\")\?.isNotEmpty())&&@readableStreamDefaultControllerGetDesiredSize(controller)<=0)return;if(@getByIdDirectPrivate(controller,\"pulling\")){@putByIdDirectPrivate(controller,\"pullAgain\",!0);return}@putByIdDirectPrivate(controller,\"pulling\",!0),@getByIdDirectPrivate(controller,\"pullAlgorithm\").@call(@undefined).@then(function(){if(@putByIdDirectPrivate(controller,\"pulling\",!1),@getByIdDirectPrivate(controller,\"pullAgain\"))@putByIdDirectPrivate(controller,\"pullAgain\",!1),@readableStreamDefaultControllerCallPullIfNeeded(controller)},function(error){@readableStreamDefaultControllerError(controller,error)})})\n"; // isReadableStreamLocked const JSC::ConstructAbility s_readableStreamInternalsIsReadableStreamLockedCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsIsReadableStreamLockedCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsIsReadableStreamLockedCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsIsReadableStreamLockedCodeLength = 102; +const int s_readableStreamInternalsIsReadableStreamLockedCodeLength = 81; static const JSC::Intrinsic s_readableStreamInternalsIsReadableStreamLockedCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsIsReadableStreamLockedCode = "(function (i){\"use strict\";return @assert(@isReadableStream(i)),!!@getByIdDirectPrivate(i,\"reader\")})\n"; +const char* const s_readableStreamInternalsIsReadableStreamLockedCode = "(function (stream){\"use strict\";return!!@getByIdDirectPrivate(stream,\"reader\")})\n"; // readableStreamDefaultControllerGetDesiredSize const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCodeLength = 283; +const int s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCodeLength = 341; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCode = "(function (i){\"use strict\";const g=@getByIdDirectPrivate(i,\"controlledReadableStream\"),d=@getByIdDirectPrivate(g,\"state\");if(d===@streamErrored)return null;if(d===@streamClosed)return 0;return @getByIdDirectPrivate(i,\"strategy\").highWaterMark-@getByIdDirectPrivate(i,\"queue\").size})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerGetDesiredSizeCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\"),state=@getByIdDirectPrivate(stream,\"state\");if(state===@streamErrored)return null;if(state===@streamClosed)return 0;return @getByIdDirectPrivate(controller,\"strategy\").highWaterMark-@getByIdDirectPrivate(controller,\"queue\").size})\n"; // readableStreamReaderGenericCancel const JSC::ConstructAbility s_readableStreamInternalsReadableStreamReaderGenericCancelCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamReaderGenericCancelCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamReaderGenericCancelCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamReaderGenericCancelCodeLength = 133; +const int s_readableStreamInternalsReadableStreamReaderGenericCancelCodeLength = 150; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamReaderGenericCancelCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamReaderGenericCancelCode = "(function (h,i){\"use strict\";const c=@getByIdDirectPrivate(h,\"ownerReadableStream\");return @assert(!!c),@readableStreamCancel(c,i)})\n"; +const char* const s_readableStreamInternalsReadableStreamReaderGenericCancelCode = "(function (reader,reason){\"use strict\";const stream=@getByIdDirectPrivate(reader,\"ownerReadableStream\");return @readableStreamCancel(stream,reason)})\n"; // readableStreamCancel const JSC::ConstructAbility s_readableStreamInternalsReadableStreamCancelCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamCancelCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamCancelCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamCancelCodeLength = 509; +const int s_readableStreamInternalsReadableStreamCancelCodeLength = 634; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamCancelCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamCancelCode = "(function (i,d){\"use strict\";@putByIdDirectPrivate(i,\"disturbed\",!0);const h=@getByIdDirectPrivate(i,\"state\");if(h===@streamClosed)return @Promise.@resolve();if(h===@streamErrored)return @Promise.@reject(@getByIdDirectPrivate(i,\"storedError\"));@readableStreamClose(i);var _=@getByIdDirectPrivate(i,\"readableStreamController\"),p=_.@cancel;if(p)return p(_,d).@then(function(){});var u=_.close;if(u)return @Promise.@resolve(_.close(d));@throwTypeError(\"ReadableStreamController has no cancel or close method\")})\n"; +const char* const s_readableStreamInternalsReadableStreamCancelCode = "(function (stream,reason){\"use strict\";@putByIdDirectPrivate(stream,\"disturbed\",!0);const state=@getByIdDirectPrivate(stream,\"state\");if(state===@streamClosed)return @Promise.@resolve();if(state===@streamErrored)return @Promise.@reject(@getByIdDirectPrivate(stream,\"storedError\"));@readableStreamClose(stream);var controller=@getByIdDirectPrivate(stream,\"readableStreamController\"),cancel=controller.@cancel;if(cancel)return cancel(controller,reason).@then(function(){});var close=controller.close;if(close)return @Promise.@resolve(controller.close(reason));@throwTypeError(\"ReadableStreamController has no cancel or close method\")})\n"; // readableStreamDefaultControllerCancel const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerCancelCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerCancelCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerCancelCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerCancelCodeLength = 146; +const int s_readableStreamInternalsReadableStreamDefaultControllerCancelCodeLength = 183; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerCancelCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerCancelCode = "(function (_,d){\"use strict\";return @putByIdDirectPrivate(_,\"queue\",@newQueue()),@getByIdDirectPrivate(_,\"cancelAlgorithm\").@call(@undefined,d)})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerCancelCode = "(function (controller,reason){\"use strict\";return @putByIdDirectPrivate(controller,\"queue\",@newQueue()),@getByIdDirectPrivate(controller,\"cancelAlgorithm\").@call(@undefined,reason)})\n"; // readableStreamDefaultControllerPull const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerPullCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerPullCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerPullCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerPullCodeLength = 519; +const int s_readableStreamInternalsReadableStreamDefaultControllerPullCodeLength = 632; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerPullCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerPullCode = "(function (a){\"use strict\";var _=@getByIdDirectPrivate(a,\"queue\");if(_.content.isNotEmpty()){const f=@dequeueValue(_);if(@getByIdDirectPrivate(a,\"closeRequested\")&&_.content.isEmpty())@readableStreamClose(@getByIdDirectPrivate(a,\"controlledReadableStream\"));else @readableStreamDefaultControllerCallPullIfNeeded(a);return @createFulfilledPromise({value:f,done:!1})}const d=@readableStreamAddReadRequest(@getByIdDirectPrivate(a,\"controlledReadableStream\"));return @readableStreamDefaultControllerCallPullIfNeeded(a),d})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerPullCode = "(function (controller){\"use strict\";var queue=@getByIdDirectPrivate(controller,\"queue\");if(queue.content.isNotEmpty()){const chunk=@dequeueValue(queue);if(@getByIdDirectPrivate(controller,\"closeRequested\")&&queue.content.isEmpty())@readableStreamClose(@getByIdDirectPrivate(controller,\"controlledReadableStream\"));else @readableStreamDefaultControllerCallPullIfNeeded(controller);return @createFulfilledPromise({value:chunk,done:!1})}const pendingPromise=@readableStreamAddReadRequest(@getByIdDirectPrivate(controller,\"controlledReadableStream\"));return @readableStreamDefaultControllerCallPullIfNeeded(controller),pendingPromise})\n"; // readableStreamDefaultControllerClose const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerCloseCodeLength = 266; +const int s_readableStreamInternalsReadableStreamDefaultControllerCloseCodeLength = 240; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerCloseCode = "(function (_){\"use strict\";if(@assert(@readableStreamDefaultControllerCanCloseOrEnqueue(_)),@putByIdDirectPrivate(_,\"closeRequested\",!0),@getByIdDirectPrivate(_,\"queue\")\?.content\?.isEmpty())@readableStreamClose(@getByIdDirectPrivate(_,\"controlledReadableStream\"))})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerCloseCode = "(function (controller){\"use strict\";if(@putByIdDirectPrivate(controller,\"closeRequested\",!0),@getByIdDirectPrivate(controller,\"queue\")\?.content\?.isEmpty())@readableStreamClose(@getByIdDirectPrivate(controller,\"controlledReadableStream\"))})\n"; // readableStreamClose const JSC::ConstructAbility s_readableStreamInternalsReadableStreamCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamCloseCodeLength = 616; +const int s_readableStreamInternalsReadableStreamCloseCodeLength = 643; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamCloseCode = "(function (d){\"use strict\";if(@assert(@getByIdDirectPrivate(d,\"state\")===@streamReadable),@putByIdDirectPrivate(d,\"state\",@streamClosed),!@getByIdDirectPrivate(d,\"reader\"))return;if(@isReadableStreamDefaultReader(@getByIdDirectPrivate(d,\"reader\"))){const _=@getByIdDirectPrivate(@getByIdDirectPrivate(d,\"reader\"),\"readRequests\");if(_.isNotEmpty()){@putByIdDirectPrivate(@getByIdDirectPrivate(d,\"reader\"),\"readRequests\",@createFIFO());for(var i=_.shift();i;i=_.shift())@fulfillPromise(i,{value:@undefined,done:!0})}}@getByIdDirectPrivate(@getByIdDirectPrivate(d,\"reader\"),\"closedPromiseCapability\").resolve.@call()})\n"; +const char* const s_readableStreamInternalsReadableStreamCloseCode = "(function (stream){\"use strict\";if(@putByIdDirectPrivate(stream,\"state\",@streamClosed),!@getByIdDirectPrivate(stream,\"reader\"))return;if(@isReadableStreamDefaultReader(@getByIdDirectPrivate(stream,\"reader\"))){const requests=@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\");if(requests.isNotEmpty()){@putByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\",@createFIFO());for(var request=requests.shift();request;request=requests.shift())@fulfillPromise(request,{value:@undefined,done:!0})}}@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"closedPromiseCapability\").resolve.@call()})\n"; // readableStreamFulfillReadRequest const JSC::ConstructAbility s_readableStreamInternalsReadableStreamFulfillReadRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamFulfillReadRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamFulfillReadRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamFulfillReadRequestCodeLength = 157; +const int s_readableStreamInternalsReadableStreamFulfillReadRequestCodeLength = 196; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamFulfillReadRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamFulfillReadRequestCode = "(function (i,p,y){\"use strict\";const _=@getByIdDirectPrivate(@getByIdDirectPrivate(i,\"reader\"),\"readRequests\").shift();@fulfillPromise(_,{value:p,done:y})})\n"; +const char* const s_readableStreamInternalsReadableStreamFulfillReadRequestCode = "(function (stream,chunk,done){\"use strict\";const readRequest=@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\").shift();@fulfillPromise(readRequest,{value:chunk,done})})\n"; // readableStreamDefaultControllerEnqueue const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeLength = 659; +const int s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeLength = 741; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCode = "(function (_,D){\"use strict\";const E=@getByIdDirectPrivate(_,\"controlledReadableStream\");if(@assert(@readableStreamDefaultControllerCanCloseOrEnqueue(_)),@isReadableStreamLocked(E)&&@getByIdDirectPrivate(@getByIdDirectPrivate(E,\"reader\"),\"readRequests\")\?.isNotEmpty()){@readableStreamFulfillReadRequest(E,D,!1),@readableStreamDefaultControllerCallPullIfNeeded(_);return}try{let d=1;if(@getByIdDirectPrivate(_,\"strategy\").size!==@undefined)d=@getByIdDirectPrivate(_,\"strategy\").size(D);@enqueueValueWithSize(@getByIdDirectPrivate(_,\"queue\"),D,d)}catch(d){throw @readableStreamDefaultControllerError(_,d),d}@readableStreamDefaultControllerCallPullIfNeeded(_)})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerEnqueueCode = "(function (controller,chunk){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");if(@isReadableStreamLocked(stream)&&@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\")\?.isNotEmpty()){@readableStreamFulfillReadRequest(stream,chunk,!1),@readableStreamDefaultControllerCallPullIfNeeded(controller);return}try{let chunkSize=1;if(@getByIdDirectPrivate(controller,\"strategy\").size!==@undefined)chunkSize=@getByIdDirectPrivate(controller,\"strategy\").size(chunk);@enqueueValueWithSize(@getByIdDirectPrivate(controller,\"queue\"),chunk,chunkSize)}catch(error){throw @readableStreamDefaultControllerError(controller,error),error}@readableStreamDefaultControllerCallPullIfNeeded(controller)})\n"; // readableStreamDefaultReaderRead const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultReaderReadCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultReaderReadCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultReaderReadCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultReaderReadCodeLength = 491; +const int s_readableStreamInternalsReadableStreamDefaultReaderReadCodeLength = 495; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultReaderReadCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultReaderReadCode = "(function (y){\"use strict\";const i=@getByIdDirectPrivate(y,\"ownerReadableStream\");@assert(!!i);const n=@getByIdDirectPrivate(i,\"state\");if(@putByIdDirectPrivate(i,\"disturbed\",!0),n===@streamClosed)return @createFulfilledPromise({value:@undefined,done:!0});if(n===@streamErrored)return @Promise.@reject(@getByIdDirectPrivate(i,\"storedError\"));return @assert(n===@streamReadable),@getByIdDirectPrivate(i,\"readableStreamController\").@pull(@getByIdDirectPrivate(i,\"readableStreamController\"))})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultReaderReadCode = "(function (reader){\"use strict\";const stream=@getByIdDirectPrivate(reader,\"ownerReadableStream\"),state=@getByIdDirectPrivate(stream,\"state\");if(@putByIdDirectPrivate(stream,\"disturbed\",!0),state===@streamClosed)return @createFulfilledPromise({value:@undefined,done:!0});if(state===@streamErrored)return @Promise.@reject(@getByIdDirectPrivate(stream,\"storedError\"));return @getByIdDirectPrivate(stream,\"readableStreamController\").@pull(@getByIdDirectPrivate(stream,\"readableStreamController\"))})\n"; // readableStreamAddReadRequest const JSC::ConstructAbility s_readableStreamInternalsReadableStreamAddReadRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamAddReadRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamAddReadRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamAddReadRequestCodeLength = 274; +const int s_readableStreamInternalsReadableStreamAddReadRequestCodeLength = 180; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamAddReadRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamAddReadRequestCode = "(function (h){\"use strict\";@assert(@isReadableStreamDefaultReader(@getByIdDirectPrivate(h,\"reader\"))),@assert(@getByIdDirectPrivate(h,\"state\")==@streamReadable);const i=@newPromise();return @getByIdDirectPrivate(@getByIdDirectPrivate(h,\"reader\"),\"readRequests\").push(i),i})\n"; +const char* const s_readableStreamInternalsReadableStreamAddReadRequestCode = "(function (stream){\"use strict\";const readRequest=@newPromise();return @getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\").push(readRequest),readRequest})\n"; // isReadableStreamDisturbed const JSC::ConstructAbility s_readableStreamInternalsIsReadableStreamDisturbedCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsIsReadableStreamDisturbedCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsIsReadableStreamDisturbedCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsIsReadableStreamDisturbedCodeLength = 103; +const int s_readableStreamInternalsIsReadableStreamDisturbedCodeLength = 83; static const JSC::Intrinsic s_readableStreamInternalsIsReadableStreamDisturbedCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsIsReadableStreamDisturbedCode = "(function (d){\"use strict\";return @assert(@isReadableStream(d)),@getByIdDirectPrivate(d,\"disturbed\")})\n"; +const char* const s_readableStreamInternalsIsReadableStreamDisturbedCode = "(function (stream){\"use strict\";return @getByIdDirectPrivate(stream,\"disturbed\")})\n"; // readableStreamReaderGenericRelease const JSC::ConstructAbility s_readableStreamInternalsReadableStreamReaderGenericReleaseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamReaderGenericReleaseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamReaderGenericReleaseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamReaderGenericReleaseCodeLength = 810; +const int s_readableStreamInternalsReadableStreamReaderGenericReleaseCodeLength = 707; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamReaderGenericReleaseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamReaderGenericReleaseCode = "(function (s){\"use strict\";if(@assert(!!@getByIdDirectPrivate(s,\"ownerReadableStream\")),@assert(@getByIdDirectPrivate(@getByIdDirectPrivate(s,\"ownerReadableStream\"),\"reader\")===s),@getByIdDirectPrivate(@getByIdDirectPrivate(s,\"ownerReadableStream\"),\"state\")===@streamReadable)@getByIdDirectPrivate(s,\"closedPromiseCapability\").reject.@call(@undefined,@makeTypeError(\"releasing lock of reader whose stream is still in readable state\"));else @putByIdDirectPrivate(s,\"closedPromiseCapability\",{promise:@newHandledRejectedPromise(@makeTypeError(\"reader released lock\"))});const t=@getByIdDirectPrivate(s,\"closedPromiseCapability\").promise;@markPromiseAsHandled(t),@putByIdDirectPrivate(@getByIdDirectPrivate(s,\"ownerReadableStream\"),\"reader\",@undefined),@putByIdDirectPrivate(s,\"ownerReadableStream\",@undefined)})\n"; +const char* const s_readableStreamInternalsReadableStreamReaderGenericReleaseCode = "(function (reader){\"use strict\";if(@getByIdDirectPrivate(@getByIdDirectPrivate(reader,\"ownerReadableStream\"),\"state\")===@streamReadable)@getByIdDirectPrivate(reader,\"closedPromiseCapability\").reject.@call(@undefined,@makeTypeError(\"releasing lock of reader whose stream is still in readable state\"));else @putByIdDirectPrivate(reader,\"closedPromiseCapability\",{promise:@newHandledRejectedPromise(@makeTypeError(\"reader released lock\"))});const promise=@getByIdDirectPrivate(reader,\"closedPromiseCapability\").promise;@markPromiseAsHandled(promise),@putByIdDirectPrivate(@getByIdDirectPrivate(reader,\"ownerReadableStream\"),\"reader\",@undefined),@putByIdDirectPrivate(reader,\"ownerReadableStream\",@undefined)})\n"; // readableStreamDefaultControllerCanCloseOrEnqueue const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCodeLength = 180; +const int s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCodeLength = 207; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCode = "(function (a){\"use strict\";return!@getByIdDirectPrivate(a,\"closeRequested\")&&@getByIdDirectPrivate(@getByIdDirectPrivate(a,\"controlledReadableStream\"),\"state\")===@streamReadable})\n"; +const char* const s_readableStreamInternalsReadableStreamDefaultControllerCanCloseOrEnqueueCode = "(function (controller){\"use strict\";return!@getByIdDirectPrivate(controller,\"closeRequested\")&&@getByIdDirectPrivate(@getByIdDirectPrivate(controller,\"controlledReadableStream\"),\"state\")===@streamReadable})\n"; // lazyLoadStream const JSC::ConstructAbility s_readableStreamInternalsLazyLoadStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsLazyLoadStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsLazyLoadStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsLazyLoadStreamCodeLength = 1589; +const int s_readableStreamInternalsLazyLoadStreamCodeLength = 2881; static const JSC::Intrinsic s_readableStreamInternalsLazyLoadStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsLazyLoadStreamCode = "(function (J,P){\"use strict\";var G=@getByIdDirectPrivate(J,\"bunNativeType\"),B=@getByIdDirectPrivate(J,\"bunNativePtr\"),x=@lazyStreamPrototypeMap.@get(G);if(x===@undefined){let q=function(m){var{c:b,v:f}=this;this.c=@undefined,this.v=@undefined,I(m,b,f)},N=function(m){try{m.close()}catch(b){globalThis.reportError(b)}},O=function(m,b,f,j){j[0]=!1;var y;try{y=Q(m,f,j)}catch(Y){return b.error(Y)}return I(y,b,f)};var z=q,A=N,p=O,[Q,U,W,Z,D,K,X]=@lazyLoad(G),H=[!1],I;I=function m(b,f,j){if(b&&@isPromise(b))return b.then(q.bind({c:f,v:j}),(y)=>f.error(y));else if(typeof b===\"number\")if(j&&j.byteLength===b&&j.buffer===f.byobRequest\?.view\?.buffer)f.byobRequest.respondWithNewView(j);else f.byobRequest.respond(b);else if(b.constructor===@Uint8Array)f.enqueue(b);if(H[0]||b===!1)@enqueueJob(N,f),H[0]=!1};const F=D\?new FinalizationRegistry(D):null;x=class m{constructor(b,f,j){if(this.#f=b,this.#b={},this.pull=this.#j.bind(this),this.cancel=this.#m.bind(this),this.autoAllocateChunkSize=f,j!==@undefined)this.start=(y)=>{y.enqueue(j)};if(F)F.register(this,b,this.#b)}#b;pull;cancel;start;#f;type=\"bytes\";autoAllocateChunkSize=0;static startSync=U;#j(b){var f=this.#f;if(!f){b.close();return}O(f,b,b.byobRequest.view,H)}#m(b){var f=this.#f;F&&F.unregister(this.#b),K&&K(f,!1),W(f,b)}static deinit=D;static drain=X},@lazyStreamPrototypeMap.@set(G,x)}const L=x.startSync(B,P);var E;const{drain:M,deinit:_}=x;if(M)E=M(B);if(L===0){if(D&&B&&@enqueueJob(D,B),(E\?.byteLength\?\?0)>0)return{start(q){q.enqueue(E),q.close()},type:\"bytes\"};return{start(q){q.close()},type:\"bytes\"}}return new x(B,L,E)})\n"; +const char* const s_readableStreamInternalsLazyLoadStreamCode = "(function (stream,autoAllocateChunkSize){\"use strict\";var nativeType=@getByIdDirectPrivate(stream,\"bunNativeType\"),nativePtr=@getByIdDirectPrivate(stream,\"bunNativePtr\"),Prototype=@lazyStreamPrototypeMap.@get(nativeType);if(Prototype===@undefined){let handleNativeReadableStreamPromiseResult2=function(val){var{c,v}=this;this.c=@undefined,this.v=@undefined,handleResult(val,c,v)},callClose2=function(controller){try{controller.close()}catch(e){globalThis.reportError(e)}},createResult2=function(tag,controller,view,closer2){closer2[0]=!1;var result;try{result=pull(tag,view,closer2)}catch(err){return controller.error(err)}return handleResult(result,controller,view)};var handleNativeReadableStreamPromiseResult=handleNativeReadableStreamPromiseResult2,callClose=callClose2,createResult=createResult2,[pull,start,cancel,setClose,deinit,setRefOrUnref,drain]=@lazyLoad(nativeType),closer=[!1],handleResult;handleResult=function handleResult(result,controller,view){if(result&&@isPromise(result))return result.then(handleNativeReadableStreamPromiseResult2.bind({c:controller,v:view}),(err)=>controller.error(err));else if(typeof result===\"number\")if(view&&view.byteLength===result&&view.buffer===controller.byobRequest\?.view\?.buffer)controller.byobRequest.respondWithNewView(view);else controller.byobRequest.respond(result);else if(result.constructor===@Uint8Array)controller.enqueue(result);if(closer[0]||result===!1)@enqueueJob(callClose2,controller),closer[0]=!1};const registry=deinit\?new FinalizationRegistry(deinit):null;Prototype=class NativeReadableStreamSource{constructor(tag,autoAllocateChunkSize2,drainValue2){if(this.#tag=tag,this.#cancellationToken={},this.pull=this.#pull.bind(this),this.cancel=this.#cancel.bind(this),this.autoAllocateChunkSize=autoAllocateChunkSize2,drainValue2!==@undefined)this.start=(controller)=>{controller.enqueue(drainValue2)};if(registry)registry.register(this,tag,this.#cancellationToken)}#cancellationToken;pull;cancel;start;#tag;type=\"bytes\";autoAllocateChunkSize=0;static startSync=start;#pull(controller){var tag=this.#tag;if(!tag){controller.close();return}createResult2(tag,controller,controller.byobRequest.view,closer)}#cancel(reason){var tag=this.#tag;registry&®istry.unregister(this.#cancellationToken),setRefOrUnref&&setRefOrUnref(tag,!1),cancel(tag,reason)}static deinit=deinit;static drain=drain},@lazyStreamPrototypeMap.@set(nativeType,Prototype)}const chunkSize=Prototype.startSync(nativePtr,autoAllocateChunkSize);var drainValue;const{drain:drainFn,deinit:deinitFn}=Prototype;if(drainFn)drainValue=drainFn(nativePtr);if(chunkSize===0){if(deinit&&nativePtr&&@enqueueJob(deinit,nativePtr),(drainValue\?.byteLength\?\?0)>0)return{start(controller){controller.enqueue(drainValue),controller.close()},type:\"bytes\"};return{start(controller){controller.close()},type:\"bytes\"}}return new Prototype(nativePtr,chunkSize,drainValue)})\n"; // readableStreamIntoArray const JSC::ConstructAbility s_readableStreamInternalsReadableStreamIntoArrayCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamIntoArrayCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamIntoArrayCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamIntoArrayCodeLength = 247; +const int s_readableStreamInternalsReadableStreamIntoArrayCodeLength = 427; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamIntoArrayCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamIntoArrayCode = "(function (q){\"use strict\";var b=q.getReader(),f=b.readMany();async function g(j){if(j.done)return[];var _=j.value||[];while(!0){var p=await b.read();if(p.done)break;_=_.concat(p.value)}return _}if(f&&@isPromise(f))return f.@then(g);return g(f)})\n"; +const char* const s_readableStreamInternalsReadableStreamIntoArrayCode = "(function (stream){\"use strict\";var reader=stream.getReader(),manyResult=reader.readMany();async function processManyResult(result){if(result.done)return[];var chunks=result.value||[];while(!0){var thisResult=await reader.read();if(thisResult.done)break;chunks=chunks.concat(thisResult.value)}return chunks}if(manyResult&&@isPromise(manyResult))return manyResult.@then(processManyResult);return processManyResult(manyResult)})\n"; // readableStreamIntoText const JSC::ConstructAbility s_readableStreamInternalsReadableStreamIntoTextCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamIntoTextCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamIntoTextCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamIntoTextCodeLength = 212; +const int s_readableStreamInternalsReadableStreamIntoTextCodeLength = 272; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamIntoTextCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamIntoTextCode = "(function (h){\"use strict\";const[_,T]=@createTextStream(@getByIdDirectPrivate(h,\"highWaterMark\")),i=@readStreamIntoSink(h,_,!1);if(i&&@isPromise(i))return @Promise.@resolve(i).@then(T.promise);return T.promise})\n"; +const char* const s_readableStreamInternalsReadableStreamIntoTextCode = "(function (stream){\"use strict\";const[textStream,closer]=@createTextStream(@getByIdDirectPrivate(stream,\"highWaterMark\")),prom=@readStreamIntoSink(stream,textStream,!1);if(prom&&@isPromise(prom))return @Promise.@resolve(prom).@then(closer.promise);return closer.promise})\n"; // readableStreamToArrayBufferDirect const JSC::ConstructAbility s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeLength = 724; +const int s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeLength = 1079; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamToArrayBufferDirectCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamToArrayBufferDirectCode = "(function (j,B){\"use strict\";var q=new @Bun.ArrayBufferSink;@putByIdDirectPrivate(j,\"underlyingSource\",@undefined);var C=@getByIdDirectPrivate(j,\"highWaterMark\");q.start(C\?{highWaterMark:C}:{});var x=@newPromiseCapability(@Promise),v=!1,z=B.pull,w=B.close,A={start(){},close(_){if(!v){if(v=!0,w)w();@fulfillPromise(x.promise,q.end())}},end(){if(!v){if(v=!0,w)w();@fulfillPromise(x.promise,q.end())}},flush(){return 0},write:q.write.bind(q)},D=!1;try{const _=z(A);if(_&&@isObject(_)&&@isPromise(_))return async function(F,G,H){while(!v)await H(F);return await G}(A,promise,z);return x.promise}catch(_){return D=!0,@readableStreamError(j,_),@Promise.@reject(_)}finally{if(!D&&j)@readableStreamClose(j);A=w=q=z=j=@undefined}})\n"; +const char* const s_readableStreamInternalsReadableStreamToArrayBufferDirectCode = "(function (stream,underlyingSource){\"use strict\";var sink=new @Bun.ArrayBufferSink;@putByIdDirectPrivate(stream,\"underlyingSource\",@undefined);var highWaterMark=@getByIdDirectPrivate(stream,\"highWaterMark\");sink.start(highWaterMark\?{highWaterMark}:{});var capability=@newPromiseCapability(@Promise),ended=!1,pull=underlyingSource.pull,close=underlyingSource.close,controller={start(){},close(reason){if(!ended){if(ended=!0,close)close();@fulfillPromise(capability.promise,sink.end())}},end(){if(!ended){if(ended=!0,close)close();@fulfillPromise(capability.promise,sink.end())}},flush(){return 0},write:sink.write.bind(sink)},didError=!1;try{const firstPull=pull(controller);if(firstPull&&@isObject(firstPull)&&@isPromise(firstPull))return async function(controller2,promise2,pull2){while(!ended)await pull2(controller2);return await promise2}(controller,promise,pull);return capability.promise}catch(e){return didError=!0,@readableStreamError(stream,e),@Promise.@reject(e)}finally{if(!didError&&stream)@readableStreamClose(stream);controller=close=sink=pull=stream=@undefined}})\n"; // readableStreamToTextDirect const JSC::ConstructAbility s_readableStreamInternalsReadableStreamToTextDirectCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamToTextDirectCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamToTextDirectCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamToTextDirectCodeLength = 277; +const int s_readableStreamInternalsReadableStreamToTextDirectCodeLength = 388; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamToTextDirectCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamToTextDirectCode = "(async function (f,j){\"use strict\";const k=@initializeTextStream.@call(f,j,@undefined);var h=f.getReader();while(@getByIdDirectPrivate(f,\"state\")===@streamReadable){var q=await h.read();if(q.done)break}try{h.releaseLock()}catch(v){}return h=@undefined,f=@undefined,k.promise})\n"; +const char* const s_readableStreamInternalsReadableStreamToTextDirectCode = "(async function (stream,underlyingSource){\"use strict\";const capability=@initializeTextStream.@call(stream,underlyingSource,@undefined);var reader=stream.getReader();while(@getByIdDirectPrivate(stream,\"state\")===@streamReadable){var thisResult=await reader.read();if(thisResult.done)break}try{reader.releaseLock()}catch(e){}return reader=@undefined,stream=@undefined,capability.promise})\n"; // readableStreamToArrayDirect const JSC::ConstructAbility s_readableStreamInternalsReadableStreamToArrayDirectCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamToArrayDirectCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamToArrayDirectCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamToArrayDirectCodeLength = 353; +const int s_readableStreamInternalsReadableStreamToArrayDirectCodeLength = 484; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamToArrayDirectCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamToArrayDirectCode = "(async function (_,j){\"use strict\";const q=@initializeArrayStream.@call(_,j,@undefined);j=@undefined;var f=_.getReader();try{while(@getByIdDirectPrivate(_,\"state\")===@streamReadable){var v=await f.read();if(v.done)break}try{f.releaseLock()}catch(k){}return f=@undefined,@Promise.@resolve(q.promise)}catch(k){throw k}finally{_=@undefined,f=@undefined}})\n"; +const char* const s_readableStreamInternalsReadableStreamToArrayDirectCode = "(async function (stream,underlyingSource){\"use strict\";const capability=@initializeArrayStream.@call(stream,underlyingSource,@undefined);underlyingSource=@undefined;var reader=stream.getReader();try{while(@getByIdDirectPrivate(stream,\"state\")===@streamReadable){var thisResult=await reader.read();if(thisResult.done)break}try{reader.releaseLock()}catch(e){}return reader=@undefined,@Promise.@resolve(capability.promise)}catch(e){throw e}finally{stream=@undefined,reader=@undefined}})\n"; // readableStreamDefineLazyIterators const JSC::ConstructAbility s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeLength = 516; +const int s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeLength = 921; static const JSC::Intrinsic s_readableStreamInternalsReadableStreamDefineLazyIteratorsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInternalsReadableStreamDefineLazyIteratorsCode = "(function (i){\"use strict\";var B=globalThis.Symbol.asyncIterator,w=async function*x(k,G){var z=k.getReader(),g;try{while(!0){var j,q;const h=z.readMany();if(@isPromise(h))({done:j,value:q}=await h);else({done:j,value:q}=h);if(j)return;yield*q}}catch(h){g=h}finally{if(z.releaseLock(),!G)k.cancel(g);if(g)throw g}},D=function x(){return w(this,!1)},F=function x({preventCancel:k=!1}={preventCancel:!1}){return w(this,k)};return @Object.@defineProperty(i,B,{value:D}),@Object.@defineProperty(i,\"values\",{value:F}),i})\n"; +const char* const s_readableStreamInternalsReadableStreamDefineLazyIteratorsCode = "(function (prototype){\"use strict\";var asyncIterator=globalThis.Symbol.asyncIterator,ReadableStreamAsyncIterator=async function*ReadableStreamAsyncIterator(stream,preventCancel){var reader=stream.getReader(),deferredError;try{while(!0){var done,value;const firstResult=reader.readMany();if(@isPromise(firstResult))({done,value}=await firstResult);else({done,value}=firstResult);if(done)return;yield*value}}catch(e){deferredError=e}finally{if(reader.releaseLock(),!preventCancel)stream.cancel(deferredError);if(deferredError)throw deferredError}},createAsyncIterator=function asyncIterator(){return ReadableStreamAsyncIterator(this,!1)},createValues=function values({preventCancel=!1}={preventCancel:!1}){return ReadableStreamAsyncIterator(this,preventCancel)};return @Object.@defineProperty(prototype,asyncIterator,{value:createAsyncIterator}),@Object.@defineProperty(prototype,\"values\",{value:createValues}),prototype})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -1892,17 +1900,17 @@ const char* const s_transformStreamDefaultControllerInitializeTransformStreamDef const JSC::ConstructAbility s_transformStreamDefaultControllerDesiredSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamDefaultControllerDesiredSizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamDefaultControllerDesiredSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamDefaultControllerDesiredSizeCodeLength = 339; +const int s_transformStreamDefaultControllerDesiredSizeCodeLength = 397; static const JSC::Intrinsic s_transformStreamDefaultControllerDesiredSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamDefaultControllerDesiredSizeCode = "(function (){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"enqueue\");const _=@getByIdDirectPrivate(this,\"stream\"),u=@getByIdDirectPrivate(_,\"readable\"),i=@getByIdDirectPrivate(u,\"readableStreamController\");return @readableStreamDefaultControllerGetDesiredSize(i)})\n"; +const char* const s_transformStreamDefaultControllerDesiredSizeCode = "(function (){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"enqueue\");const stream=@getByIdDirectPrivate(this,\"stream\"),readable=@getByIdDirectPrivate(stream,\"readable\"),readableController=@getByIdDirectPrivate(readable,\"readableStreamController\");return @readableStreamDefaultControllerGetDesiredSize(readableController)})\n"; // enqueue const JSC::ConstructAbility s_transformStreamDefaultControllerEnqueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_transformStreamDefaultControllerEnqueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_transformStreamDefaultControllerEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_transformStreamDefaultControllerEnqueueCodeLength = 195; +const int s_transformStreamDefaultControllerEnqueueCodeLength = 203; static const JSC::Intrinsic s_transformStreamDefaultControllerEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamDefaultControllerEnqueueCode = "(function (a){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"enqueue\");@transformStreamDefaultControllerEnqueue(this,a)})\n"; +const char* const s_transformStreamDefaultControllerEnqueueCode = "(function (chunk){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"enqueue\");@transformStreamDefaultControllerEnqueue(this,chunk)})\n"; // error const JSC::ConstructAbility s_transformStreamDefaultControllerErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1910,7 +1918,7 @@ const JSC::ConstructorKind s_transformStreamDefaultControllerErrorCodeConstructo const JSC::ImplementationVisibility s_transformStreamDefaultControllerErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; const int s_transformStreamDefaultControllerErrorCodeLength = 191; static const JSC::Intrinsic s_transformStreamDefaultControllerErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_transformStreamDefaultControllerErrorCode = "(function (t){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"error\");@transformStreamDefaultControllerError(this,t)})\n"; +const char* const s_transformStreamDefaultControllerErrorCode = "(function (e){\"use strict\";if(!@isTransformStreamDefaultController(this))throw @makeThisTypeError(\"TransformStreamDefaultController\",\"error\");@transformStreamDefaultControllerError(this,e)})\n"; // terminate const JSC::ConstructAbility s_transformStreamDefaultControllerTerminateCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -1929,56 +1937,30 @@ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ WEBCORE_FOREACH_TRANSFORMSTREAMDEFAULTCONTROLLER_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) #undef DEFINE_BUILTIN_GENERATOR -/* AsyncContext.ts */ -// getAsyncContext -const JSC::ConstructAbility s_asyncContextGetAsyncContextCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; -const JSC::ConstructorKind s_asyncContextGetAsyncContextCodeConstructorKind = JSC::ConstructorKind::None; -const JSC::ImplementationVisibility s_asyncContextGetAsyncContextCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_asyncContextGetAsyncContextCodeLength = 70; -static const JSC::Intrinsic s_asyncContextGetAsyncContextCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_asyncContextGetAsyncContextCode = "(function (){\"use strict\";return @getInternalField(@asyncContext,0)})\n"; - -// setAsyncContext -const JSC::ConstructAbility s_asyncContextSetAsyncContextCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; -const JSC::ConstructorKind s_asyncContextSetAsyncContextCodeConstructorKind = JSC::ConstructorKind::None; -const JSC::ImplementationVisibility s_asyncContextSetAsyncContextCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_asyncContextSetAsyncContextCodeLength = 73; -static const JSC::Intrinsic s_asyncContextSetAsyncContextCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_asyncContextSetAsyncContextCode = "(function (r){\"use strict\";return @putInternalField(@asyncContext,0,r)})\n"; - -#define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ -JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ -{\ - JSVMClientData* clientData = static_cast(vm.clientData); \ - return clientData->builtinFunctions().asyncContextBuiltins().codeName##Executable()->link(vm, nullptr, clientData->builtinFunctions().asyncContextBuiltins().codeName##Source(), std::nullopt, s_##codeName##Intrinsic); \ -} -WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) -#undef DEFINE_BUILTIN_GENERATOR - /* ReadableStreamBYOBReader.ts */ // initializeReadableStreamBYOBReader const JSC::ConstructAbility s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCodeLength = 485; +const int s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCodeLength = 510; static const JSC::Intrinsic s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCode = "(function (n){\"use strict\";if(!@isReadableStream(n))@throwTypeError(\"ReadableStreamBYOBReader needs a ReadableStream\");if(!@isReadableByteStreamController(@getByIdDirectPrivate(n,\"readableStreamController\")))@throwTypeError(\"ReadableStreamBYOBReader needs a ReadableByteStreamController\");if(@isReadableStreamLocked(n))@throwTypeError(\"ReadableStream is locked\");return @readableStreamReaderGenericInitialize(this,n),@putByIdDirectPrivate(this,\"readIntoRequests\",@createFIFO()),this})\n"; +const char* const s_readableStreamBYOBReaderInitializeReadableStreamBYOBReaderCode = "(function (stream){\"use strict\";if(!@isReadableStream(stream))@throwTypeError(\"ReadableStreamBYOBReader needs a ReadableStream\");if(!@isReadableByteStreamController(@getByIdDirectPrivate(stream,\"readableStreamController\")))@throwTypeError(\"ReadableStreamBYOBReader needs a ReadableByteStreamController\");if(@isReadableStreamLocked(stream))@throwTypeError(\"ReadableStream is locked\");return @readableStreamReaderGenericInitialize(this,stream),@putByIdDirectPrivate(this,\"readIntoRequests\",@createFIFO()),this})\n"; // cancel const JSC::ConstructAbility s_readableStreamBYOBReaderCancelCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamBYOBReaderCancelCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamBYOBReaderCancelCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamBYOBReaderCancelCodeLength = 351; +const int s_readableStreamBYOBReaderCancelCodeLength = 361; static const JSC::Intrinsic s_readableStreamBYOBReaderCancelCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamBYOBReaderCancelCode = "(function (t){\"use strict\";if(!@isReadableStreamBYOBReader(this))return @Promise.@reject(@makeThisTypeError(\"ReadableStreamBYOBReader\",\"cancel\"));if(!@getByIdDirectPrivate(this,\"ownerReadableStream\"))return @Promise.@reject(@makeTypeError(\"cancel() called on a reader owned by no readable stream\"));return @readableStreamReaderGenericCancel(this,t)})\n"; +const char* const s_readableStreamBYOBReaderCancelCode = "(function (reason){\"use strict\";if(!@isReadableStreamBYOBReader(this))return @Promise.@reject(@makeThisTypeError(\"ReadableStreamBYOBReader\",\"cancel\"));if(!@getByIdDirectPrivate(this,\"ownerReadableStream\"))return @Promise.@reject(@makeTypeError(\"cancel() called on a reader owned by no readable stream\"));return @readableStreamReaderGenericCancel(this,reason)})\n"; // read const JSC::ConstructAbility s_readableStreamBYOBReaderReadCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamBYOBReaderReadCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamBYOBReaderReadCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamBYOBReaderReadCodeLength = 648; +const int s_readableStreamBYOBReaderReadCodeLength = 663; static const JSC::Intrinsic s_readableStreamBYOBReaderReadCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamBYOBReaderReadCode = "(function (t){\"use strict\";if(!@isReadableStreamBYOBReader(this))return @Promise.@reject(@makeThisTypeError(\"ReadableStreamBYOBReader\",\"read\"));if(!@getByIdDirectPrivate(this,\"ownerReadableStream\"))return @Promise.@reject(@makeTypeError(\"read() called on a reader owned by no readable stream\"));if(!@isObject(t))return @Promise.@reject(@makeTypeError(\"Provided view is not an object\"));if(!@ArrayBuffer.@isView(t))return @Promise.@reject(@makeTypeError(\"Provided view is not an ArrayBufferView\"));if(t.byteLength===0)return @Promise.@reject(@makeTypeError(\"Provided view cannot have a 0 byteLength\"));return @readableStreamBYOBReaderRead(this,t)})\n"; +const char* const s_readableStreamBYOBReaderReadCode = "(function (view){\"use strict\";if(!@isReadableStreamBYOBReader(this))return @Promise.@reject(@makeThisTypeError(\"ReadableStreamBYOBReader\",\"read\"));if(!@getByIdDirectPrivate(this,\"ownerReadableStream\"))return @Promise.@reject(@makeTypeError(\"read() called on a reader owned by no readable stream\"));if(!@isObject(view))return @Promise.@reject(@makeTypeError(\"Provided view is not an object\"));if(!@ArrayBuffer.@isView(view))return @Promise.@reject(@makeTypeError(\"Provided view is not an ArrayBufferView\"));if(view.byteLength===0)return @Promise.@reject(@makeTypeError(\"Provided view cannot have a 0 byteLength\"));return @readableStreamBYOBReaderRead(this,view)})\n"; // releaseLock const JSC::ConstructAbility s_readableStreamBYOBReaderReleaseLockCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2010,17 +1992,17 @@ WEBCORE_FOREACH_READABLESTREAMBYOBREADER_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_jsBufferConstructorFromCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferConstructorFromCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferConstructorFromCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferConstructorFromCodeLength = 1107; +const int s_jsBufferConstructorFromCodeLength = 1274; static const JSC::Intrinsic s_jsBufferConstructorFromCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferConstructorFromCode = "(function (n){\"use strict\";if(@isUndefinedOrNull(n))@throwTypeError(\"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.\");if(typeof n===\"string\"||typeof n===\"object\"&&(@isTypedArrayView(n)||n instanceof @ArrayBuffer||n instanceof SharedArrayBuffer||n instanceof String))switch(@argumentCount()){case 1:return new @Buffer(n);case 2:return new @Buffer(n,@argument(1));default:return new @Buffer(n,@argument(1),@argument(2))}var d=@toObject(n,\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\");if(!@isJSArray(d)){const u=@tryGetByIdWithWellKnownSymbol(n,\"toPrimitive\");if(u){const f=u.@call(n,\"string\");if(typeof f===\"string\")switch(@argumentCount()){case 1:return new @Buffer(f);case 2:return new @Buffer(f,@argument(1));default:return new @Buffer(f,@argument(1),@argument(2))}}if(!(\"length\"in d)||@isCallable(d))@throwTypeError(\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\")}return new @Buffer(@Uint8Array.from(d).buffer)})\n"; +const char* const s_jsBufferConstructorFromCode = "(function (items){\"use strict\";if(@isUndefinedOrNull(items))@throwTypeError(\"The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.\");if(typeof items===\"string\"||typeof items===\"object\"&&(@isTypedArrayView(items)||items instanceof @ArrayBuffer||items instanceof SharedArrayBuffer||items instanceof @String))switch(@argumentCount()){case 1:return new @Buffer(items);case 2:return new @Buffer(items,@argument(1));default:return new @Buffer(items,@argument(1),@argument(2))}var arrayLike=@toObject(items,\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\");if(!@isJSArray(arrayLike)){const toPrimitive=@tryGetByIdWithWellKnownSymbol(items,\"toPrimitive\");if(toPrimitive){const primitive=toPrimitive.@call(items,\"string\");if(typeof primitive===\"string\")switch(@argumentCount()){case 1:return new @Buffer(primitive);case 2:return new @Buffer(primitive,@argument(1));default:return new @Buffer(primitive,@argument(1),@argument(2))}}if(!(\"length\"in arrayLike)||@isCallable(arrayLike))@throwTypeError(\"The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\")}return new @Buffer(@Uint8Array.from(arrayLike).buffer)})\n"; // isBuffer const JSC::ConstructAbility s_jsBufferConstructorIsBufferCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_jsBufferConstructorIsBufferCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_jsBufferConstructorIsBufferCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_jsBufferConstructorIsBufferCodeLength = 57; +const int s_jsBufferConstructorIsBufferCodeLength = 75; static const JSC::Intrinsic s_jsBufferConstructorIsBufferCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_jsBufferConstructorIsBufferCode = "(function (a){\"use strict\";return a instanceof @Buffer})\n"; +const char* const s_jsBufferConstructorIsBufferCode = "(function (bufferlike){\"use strict\";return bufferlike instanceof @Buffer})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2036,25 +2018,25 @@ WEBCORE_FOREACH_JSBUFFERCONSTRUCTOR_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCodeLength = 314; +const int s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCodeLength = 334; static const JSC::Intrinsic s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCode = "(function (n){\"use strict\";if(!@isReadableStream(n))@throwTypeError(\"ReadableStreamDefaultReader needs a ReadableStream\");if(@isReadableStreamLocked(n))@throwTypeError(\"ReadableStream is locked\");return @readableStreamReaderGenericInitialize(this,n),@putByIdDirectPrivate(this,\"readRequests\",@createFIFO()),this})\n"; +const char* const s_readableStreamDefaultReaderInitializeReadableStreamDefaultReaderCode = "(function (stream){\"use strict\";if(!@isReadableStream(stream))@throwTypeError(\"ReadableStreamDefaultReader needs a ReadableStream\");if(@isReadableStreamLocked(stream))@throwTypeError(\"ReadableStream is locked\");return @readableStreamReaderGenericInitialize(this,stream),@putByIdDirectPrivate(this,\"readRequests\",@createFIFO()),this})\n"; // cancel const JSC::ConstructAbility s_readableStreamDefaultReaderCancelCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamDefaultReaderCancelCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamDefaultReaderCancelCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamDefaultReaderCancelCodeLength = 357; +const int s_readableStreamDefaultReaderCancelCodeLength = 367; static const JSC::Intrinsic s_readableStreamDefaultReaderCancelCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamDefaultReaderCancelCode = "(function (i){\"use strict\";if(!@isReadableStreamDefaultReader(this))return @Promise.@reject(@makeThisTypeError(\"ReadableStreamDefaultReader\",\"cancel\"));if(!@getByIdDirectPrivate(this,\"ownerReadableStream\"))return @Promise.@reject(@makeTypeError(\"cancel() called on a reader owned by no readable stream\"));return @readableStreamReaderGenericCancel(this,i)})\n"; +const char* const s_readableStreamDefaultReaderCancelCode = "(function (reason){\"use strict\";if(!@isReadableStreamDefaultReader(this))return @Promise.@reject(@makeThisTypeError(\"ReadableStreamDefaultReader\",\"cancel\"));if(!@getByIdDirectPrivate(this,\"ownerReadableStream\"))return @Promise.@reject(@makeTypeError(\"cancel() called on a reader owned by no readable stream\"));return @readableStreamReaderGenericCancel(this,reason)})\n"; // readMany const JSC::ConstructAbility s_readableStreamDefaultReaderReadManyCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamDefaultReaderReadManyCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamDefaultReaderReadManyCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamDefaultReaderReadManyCodeLength = 2598; +const int s_readableStreamDefaultReaderReadManyCodeLength = 3230; 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 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{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;A0){var outValues=@newArrayWithSize(length);if(@isReadableByteStreamController(controller)){{const buf=values[0];if(!(@ArrayBuffer.@isView(buf)||buf instanceof @ArrayBuffer))@putByValDirect(outValues,0,new @Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength));else @putByValDirect(outValues,0,buf)}for(var i=1;i{if(result.done)return{value:[],size:0,done:!0};var controller2=@getByIdDirectPrivate(stream,\"readableStreamController\"),queue2=@getByIdDirectPrivate(controller2,\"queue\"),value=[result.value].concat(queue2.content.toArray(!1)),length2=value.length;if(@isReadableByteStreamController(controller2))for(var i2=0;i20}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>>=1,this._capacityMask>>>=1}}return new A})\n"; +const char* const s_streamInternalsCreateFIFOCode = "(function (){\"use strict\";var slice=@Array.prototype.slice;class Denqueue{constructor(){this._head=0,this._tail=0,this._capacityMask=3,this._list=@newArrayWithSize(4)}_head;_tail;_capacityMask;_list;size(){if(this._head===this._tail)return 0;if(this._head0}shift(){var{_head:head,_tail,_list,_capacityMask}=this;if(head===_tail)return @undefined;var item=_list[head];if(@putByValDirect(_list,head,@undefined),head=this._head=head+1&_capacityMask,head<2&&_tail>1e4&&_tail<=_list.length>>>2)this._shrinkArray();return item}peek(){if(this._head===this._tail)return @undefined;return this._list[this._head]}push(item){var tail=this._tail;if(@putByValDirect(this._list,tail,item),this._tail=tail+1&this._capacityMask,this._tail===this._head)this._growArray()}toArray(fullCopy){var list=this._list,len=@toLength(list.length);if(fullCopy||this._head>this._tail){var _head=@toLength(this._head),_tail=@toLength(this._tail),total=@toLength(len-_head+_tail),array=@newArrayWithSize(total),j=0;for(var i=_head;i>>=1,this._capacityMask>>>=1}}return new Denqueue})\n"; // newQueue const JSC::ConstructAbility s_streamInternalsNewQueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2174,73 +2156,73 @@ const char* const s_streamInternalsNewQueueCode = "(function (){\"use strict\";r const JSC::ConstructAbility s_streamInternalsDequeueValueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsDequeueValueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsDequeueValueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsDequeueValueCodeLength = 106; +const int s_streamInternalsDequeueValueCodeLength = 141; static const JSC::Intrinsic s_streamInternalsDequeueValueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsDequeueValueCode = "(function (l){\"use strict\";const p=l.content.shift();if(l.size-=p.size,l.size<0)l.size=0;return p.value})\n"; +const char* const s_streamInternalsDequeueValueCode = "(function (queue){\"use strict\";const record=queue.content.shift();if(queue.size-=record.size,queue.size<0)queue.size=0;return record.value})\n"; // enqueueValueWithSize const JSC::ConstructAbility s_streamInternalsEnqueueValueWithSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsEnqueueValueWithSizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsEnqueueValueWithSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsEnqueueValueWithSizeCodeLength = 161; +const int s_streamInternalsEnqueueValueWithSizeCodeLength = 191; static const JSC::Intrinsic s_streamInternalsEnqueueValueWithSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsEnqueueValueWithSizeCode = "(function (d,o,n){\"use strict\";if(n=@toNumber(n),!@isFinite(n)||n<0)@throwRangeError(\"size has an incorrect value\");d.content.push({value:o,size:n}),d.size+=n})\n"; +const char* const s_streamInternalsEnqueueValueWithSizeCode = "(function (queue,value,size){\"use strict\";if(size=@toNumber(size),!@isFinite(size)||size<0)@throwRangeError(\"size has an incorrect value\");queue.content.push({value,size}),queue.size+=size})\n"; // peekQueueValue const JSC::ConstructAbility s_streamInternalsPeekQueueValueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsPeekQueueValueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsPeekQueueValueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsPeekQueueValueCodeLength = 60; +const int s_streamInternalsPeekQueueValueCodeLength = 68; static const JSC::Intrinsic s_streamInternalsPeekQueueValueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsPeekQueueValueCode = "(function (a){\"use strict\";return a.content.peek()\?.value})\n"; +const char* const s_streamInternalsPeekQueueValueCode = "(function (queue){\"use strict\";return queue.content.peek()\?.value})\n"; // resetQueue const JSC::ConstructAbility s_streamInternalsResetQueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsResetQueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsResetQueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsResetQueueCodeLength = 99; +const int s_streamInternalsResetQueueCodeLength = 68; static const JSC::Intrinsic s_streamInternalsResetQueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsResetQueueCode = "(function (c){\"use strict\";@assert(\"content\"in c),@assert(\"size\"in c),c.content.clear(),c.size=0})\n"; +const char* const s_streamInternalsResetQueueCode = "(function (queue){\"use strict\";queue.content.clear(),queue.size=0})\n"; // extractSizeAlgorithm const JSC::ConstructAbility s_streamInternalsExtractSizeAlgorithmCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsExtractSizeAlgorithmCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsExtractSizeAlgorithmCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsExtractSizeAlgorithmCodeLength = 176; +const int s_streamInternalsExtractSizeAlgorithmCodeLength = 246; static const JSC::Intrinsic s_streamInternalsExtractSizeAlgorithmCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsExtractSizeAlgorithmCode = "(function (p){\"use strict\";const d=p.size;if(d===@undefined)return()=>1;if(typeof d!==\"function\")@throwTypeError(\"strategy.size must be a function\");return(w)=>{return d(w)}})\n"; +const char* const s_streamInternalsExtractSizeAlgorithmCode = "(function (strategy){\"use strict\";const sizeAlgorithm=strategy.size;if(sizeAlgorithm===@undefined)return()=>1;if(typeof sizeAlgorithm!==\"function\")@throwTypeError(\"strategy.size must be a function\");return(chunk)=>{return sizeAlgorithm(chunk)}})\n"; // extractHighWaterMark const JSC::ConstructAbility s_streamInternalsExtractHighWaterMarkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsExtractHighWaterMarkCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsExtractHighWaterMarkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsExtractHighWaterMarkCodeLength = 184; +const int s_streamInternalsExtractHighWaterMarkCodeLength = 288; static const JSC::Intrinsic s_streamInternalsExtractHighWaterMarkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsExtractHighWaterMarkCode = "(function (n,p){\"use strict\";const c=n.highWaterMark;if(c===@undefined)return p;if(c!==c||c<0)@throwRangeError(\"highWaterMark value is negative or not a number\");return @toNumber(c)})\n"; +const char* const s_streamInternalsExtractHighWaterMarkCode = "(function (strategy,defaultHWM){\"use strict\";const highWaterMark=strategy.highWaterMark;if(highWaterMark===@undefined)return defaultHWM;if(highWaterMark!==highWaterMark||highWaterMark<0)@throwRangeError(\"highWaterMark value is negative or not a number\");return @toNumber(highWaterMark)})\n"; // extractHighWaterMarkFromQueuingStrategyInit const JSC::ConstructAbility s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCodeLength = 249; +const int s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCodeLength = 280; static const JSC::Intrinsic s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCode = "(function (e){\"use strict\";if(!@isObject(e))@throwTypeError(\"QueuingStrategyInit argument must be an object.\");const{highWaterMark:c}=e;if(c===@undefined)@throwTypeError(\"QueuingStrategyInit.highWaterMark member is required.\");return @toNumber(c)})\n"; +const char* const s_streamInternalsExtractHighWaterMarkFromQueuingStrategyInitCode = "(function (init){\"use strict\";if(!@isObject(init))@throwTypeError(\"QueuingStrategyInit argument must be an object.\");const{highWaterMark}=init;if(highWaterMark===@undefined)@throwTypeError(\"QueuingStrategyInit.highWaterMark member is required.\");return @toNumber(highWaterMark)})\n"; // createFulfilledPromise const JSC::ConstructAbility s_streamInternalsCreateFulfilledPromiseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsCreateFulfilledPromiseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsCreateFulfilledPromiseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsCreateFulfilledPromiseCodeLength = 81; +const int s_streamInternalsCreateFulfilledPromiseCodeLength = 107; static const JSC::Intrinsic s_streamInternalsCreateFulfilledPromiseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsCreateFulfilledPromiseCode = "(function (n){\"use strict\";const d=@newPromise();return @fulfillPromise(d,n),d})\n"; +const char* const s_streamInternalsCreateFulfilledPromiseCode = "(function (value){\"use strict\";const promise=@newPromise();return @fulfillPromise(promise,value),promise})\n"; // toDictionary const JSC::ConstructAbility s_streamInternalsToDictionaryCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_streamInternalsToDictionaryCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_streamInternalsToDictionaryCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_streamInternalsToDictionaryCodeLength = 115; +const int s_streamInternalsToDictionaryCodeLength = 179; static const JSC::Intrinsic s_streamInternalsToDictionaryCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_streamInternalsToDictionaryCode = "(function (c,n,p){\"use strict\";if(c===@undefined||c===null)return n;if(!@isObject(c))@throwTypeError(p);return c})\n"; +const char* const s_streamInternalsToDictionaryCode = "(function (value,defaultValue,errorMessage){\"use strict\";if(value===@undefined||value===null)return defaultValue;if(!@isObject(value))@throwTypeError(errorMessage);return value})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2256,41 +2238,41 @@ WEBCORE_FOREACH_STREAMINTERNALS_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_importMetaObjectLoadCJS2ESMCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_importMetaObjectLoadCJS2ESMCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_importMetaObjectLoadCJS2ESMCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_importMetaObjectLoadCJS2ESMCodeLength = 1406; +const int s_importMetaObjectLoadCJS2ESMCodeLength = 2214; static const JSC::Intrinsic s_importMetaObjectLoadCJS2ESMCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_importMetaObjectLoadCJS2ESMCode = "(function (z){\"use strict\";var J=@Loader,G=@createFIFO(),D=z;while(D){var _=J.registry.@get(D);if((_\?.state\?\?0)<=@ModuleFetch)@fulfillModuleSync(D),_=J.registry.@get(D);var V=@getPromiseInternalField(_.fetch,@promiseFieldReactionsOrResult),w=J.parseModule(D,V),x=_.module;if(w&&@isPromise(w)){var h=@getPromiseInternalField(w,@promiseFieldReactionsOrResult),W=@getPromiseInternalField(w,@promiseFieldFlags),L=W&@promiseStateMask;if(L===@promiseStatePending||h&&@isPromise(h))@throwTypeError(`require() async module \"${D}\" is unsupported. use \"await import()\" instead.`);else if(L===@promiseStateRejected){if(!h\?.message)@throwTypeError(`${h+\"\"\?h:\"An error occurred\"} occurred while parsing module \\\"${D}\\\"`);throw h}_.module=x=h}else if(w&&!x)_.module=x=w;@setStateToMax(_,@ModuleLink);var X=x.dependenciesMap,H=J.requestedModules(x),Q=@newArrayWithSize(H.length);for(var B=0,Y=H.length;B=@ModuleLink)D=G.shift()}var U=J.linkAndEvaluateModule(z,@undefined);if(U&&@isPromise(U))@throwTypeError(`require() async module \\\"${z}\\\" is unsupported. use \"await import()\" instead.`);return J.registry.@get(z)})\n"; +const char* const s_importMetaObjectLoadCJS2ESMCode = "(function (resolvedSpecifier){\"use strict\";var loader=@Loader,queue=@createFIFO(),key=resolvedSpecifier;while(key){var entry=loader.registry.@get(key);if((entry\?.state\?\?0)<=@ModuleFetch)@fulfillModuleSync(key),entry=loader.registry.@get(key);var sourceCodeObject=@getPromiseInternalField(entry.fetch,@promiseFieldReactionsOrResult),moduleRecordPromise=loader.parseModule(key,sourceCodeObject),mod=entry.module;if(moduleRecordPromise&&@isPromise(moduleRecordPromise)){var reactionsOrResult=@getPromiseInternalField(moduleRecordPromise,@promiseFieldReactionsOrResult),flags=@getPromiseInternalField(moduleRecordPromise,@promiseFieldFlags),state=flags&@promiseStateMask;if(state===@promiseStatePending||reactionsOrResult&&@isPromise(reactionsOrResult))@throwTypeError(`require() async module \"${key}\" is unsupported. use \"await import()\" instead.`);else if(state===@promiseStateRejected){if(!reactionsOrResult\?.message)@throwTypeError(`${reactionsOrResult+\"\"\?reactionsOrResult:\"An error occurred\"} occurred while parsing module \\\"${key}\\\"`);throw reactionsOrResult}entry.module=mod=reactionsOrResult}else if(moduleRecordPromise&&!mod)entry.module=mod=moduleRecordPromise;@setStateToMax(entry,@ModuleLink);var dependenciesMap=mod.dependenciesMap,requestedModules=loader.requestedModules(mod),dependencies=@newArrayWithSize(requestedModules.length);for(var i=0,length=requestedModules.length;i=@ModuleLink)key=queue.shift()}var linkAndEvaluateResult=loader.linkAndEvaluateModule(resolvedSpecifier,@undefined);if(linkAndEvaluateResult&&@isPromise(linkAndEvaluateResult))@throwTypeError(`require() async module \\\"${resolvedSpecifier}\\\" is unsupported. use \"await import()\" instead.`);return loader.registry.@get(resolvedSpecifier)})\n"; // requireESM const JSC::ConstructAbility s_importMetaObjectRequireESMCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_importMetaObjectRequireESMCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_importMetaObjectRequireESMCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_importMetaObjectRequireESMCodeLength = 325; +const int s_importMetaObjectRequireESMCodeLength = 364; static const JSC::Intrinsic s_importMetaObjectRequireESMCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_importMetaObjectRequireESMCode = "(function (c){\"use strict\";var a=@Loader.registry.@get(c);if(!a||!a.evaluated)a=@loadCJS2ESM(c);if(!a||!a.evaluated||!a.module)@throwTypeError(`require() failed to evaluate module \"${c}\". This is an internal consistentency error.`);var _=@Loader.getModuleNamespaceObject(a.module);if(_[@commonJSSymbol]===0)return;return _})\n"; +const char* const s_importMetaObjectRequireESMCode = "(function (resolved){\"use strict\";var entry=@Loader.registry.@get(resolved);if(!entry||!entry.evaluated)entry=@loadCJS2ESM(resolved);if(!entry||!entry.evaluated||!entry.module)@throwTypeError(`require() failed to evaluate module \"${resolved}\". This is an internal consistentency error.`);var exports=@Loader.getModuleNamespaceObject(entry.module);return exports})\n"; // internalRequire const JSC::ConstructAbility s_importMetaObjectInternalRequireCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_importMetaObjectInternalRequireCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_importMetaObjectInternalRequireCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_importMetaObjectInternalRequireCodeLength = 747; +const int s_importMetaObjectInternalRequireCodeLength = 857; static const JSC::Intrinsic s_importMetaObjectInternalRequireCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_importMetaObjectInternalRequireCode = "(function (_){\"use strict\";var n=@requireMap.@get(_);const g=_.substring(_.length-5);if(n)return n.exports;if(g===\".json\"){var j=globalThis[Symbol.for(\"_fs\")]||=@Bun.fs(),b=JSON.parse(j.readFileSync(_,\"utf8\"));return @requireMap.@set(_,@createCommonJSModule(_,b,!0)),b}else if(g===\".node\"){const k=@createCommonJSModule(_,{},!0);return process.dlopen(k,_),@requireMap.@set(_,k),k.exports}else if(g===\".toml\"){var j=globalThis[Symbol.for(\"_fs\")]||=@Bun.fs(),b=@Bun.TOML.parse(j.readFileSync(_,\"utf8\"));return @requireMap.@set(_,@createCommonJSModule(_,b,!0)),b}else{var b=@requireESM(_);const v=@requireMap.@get(_);if(v)return v.exports;var q=b\?.default;if(q\?.[@commonJSSymbol]===0)b=q;return @requireMap.@set(_,@createCommonJSModule(_,b,!0)),b}})\n"; +const char* const s_importMetaObjectInternalRequireCode = "(function (id){\"use strict\";var cached=@requireMap.@get(id);const last5=id.substring(id.length-5);if(cached)return cached.exports;if(last5===\".json\"){var fs=globalThis[Symbol.for(\"_fs\")]||=@Bun.fs(),exports=JSON.parse(fs.readFileSync(id,\"utf8\"));return @requireMap.@set(id,@createCommonJSModule(id,exports,!0)),exports}else if(last5===\".node\"){const module=@createCommonJSModule(id,{},!0);return process.dlopen(module,id),@requireMap.@set(id,module),module.exports}else if(last5===\".toml\"){var fs=globalThis[Symbol.for(\"_fs\")]||=@Bun.fs(),exports=@Bun.TOML.parse(fs.readFileSync(id,\"utf8\"));return @requireMap.@set(id,@createCommonJSModule(id,exports,!0)),exports}else{var exports=@requireESM(id);const cachedModule=@requireMap.@get(id);if(cachedModule)return cachedModule.exports;return @requireMap.@set(id,@createCommonJSModule(id,exports,!0)),exports}})\n"; // createRequireCache const JSC::ConstructAbility s_importMetaObjectCreateRequireCacheCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_importMetaObjectCreateRequireCacheCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_importMetaObjectCreateRequireCacheCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_importMetaObjectCreateRequireCacheCodeLength = 854; +const int s_importMetaObjectCreateRequireCacheCodeLength = 978; static const JSC::Intrinsic s_importMetaObjectCreateRequireCacheCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_importMetaObjectCreateRequireCacheCode = "(function (){\"use strict\";var c=new Map,L={};return new Proxy(L,{get(f,_){const h=@requireMap.@get(_);if(h)return h;const t=@Loader.registry.@get(_);if(t\?.evaluated){const u=@Loader.getModuleNamespaceObject(t.module),g=u[@commonJSSymbol]===0||u.default\?.[@commonJSSymbol]\?u.default:u,b=@createCommonJSModule(_,g,!0);return @requireMap.@set(_,b),b}return L[_]},set(f,_,h){return @requireMap.@set(_,h),!0},has(f,_){return @requireMap.@has(_)||@Loader.registry.@has(_)},deleteProperty(f,_){return c.@delete(_),@requireMap.@delete(_),@Loader.registry.@delete(_),!0},ownKeys(f){var _=[...@requireMap.@keys()];const h=[...@Loader.registry.@keys()];for(let t of h)if(!_.includes(t))@arrayPush(_,t);return _},getPrototypeOf(f){return null},getOwnPropertyDescriptor(f,_){if(@requireMap.@has(_)||@Loader.registry.@has(_))return{configurable:!0,enumerable:!0}}})})\n"; +const char* const s_importMetaObjectCreateRequireCacheCode = "(function (){\"use strict\";var moduleMap=new Map,inner={};return new Proxy(inner,{get(target,key){const entry=@requireMap.@get(key);if(entry)return entry;const esm=@Loader.registry.@get(key);if(esm\?.evaluated){const namespace=@Loader.getModuleNamespaceObject(esm.module),mod=@createCommonJSModule(key,namespace,!0);return @requireMap.@set(key,mod),mod}return inner[key]},set(target,key,value){return @requireMap.@set(key,value),!0},has(target,key){return @requireMap.@has(key)||@Loader.registry.@has(key)},deleteProperty(target,key){return moduleMap.@delete(key),@requireMap.@delete(key),@Loader.registry.@delete(key),!0},ownKeys(target){var array=[...@requireMap.@keys()];const registryKeys=[...@Loader.registry.@keys()];for(let key of registryKeys)if(!array.includes(key))@arrayPush(array,key);return array},getPrototypeOf(target){return null},getOwnPropertyDescriptor(target,key){if(@requireMap.@has(key)||@Loader.registry.@has(key))return{configurable:!0,enumerable:!0}}})})\n"; // main const JSC::ConstructAbility s_importMetaObjectMainCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_importMetaObjectMainCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_importMetaObjectMainCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_importMetaObjectMainCodeLength = 57; +const int s_importMetaObjectMainCodeLength = 76; static const JSC::Intrinsic s_importMetaObjectMainCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_importMetaObjectMainCode = "(function (){\"use strict\";return this.path===@Bun.main})\n"; +const char* const s_importMetaObjectMainCode = "(function (){\"use strict\";return this.path===@Bun.main&&@Bun.isMainThread})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2306,9 +2288,9 @@ WEBCORE_FOREACH_IMPORTMETAOBJECT_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_countQueuingStrategyHighWaterMarkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_countQueuingStrategyHighWaterMarkCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_countQueuingStrategyHighWaterMarkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_countQueuingStrategyHighWaterMarkCodeLength = 205; +const int s_countQueuingStrategyHighWaterMarkCodeLength = 241; static const JSC::Intrinsic s_countQueuingStrategyHighWaterMarkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_countQueuingStrategyHighWaterMarkCode = "(function (){\"use strict\";const n=@getByIdDirectPrivate(this,\"highWaterMark\");if(n===@undefined)@throwTypeError(\"CountQueuingStrategy.highWaterMark getter called on incompatible |this| value.\");return n})\n"; +const char* const s_countQueuingStrategyHighWaterMarkCode = "(function (){\"use strict\";const highWaterMark=@getByIdDirectPrivate(this,\"highWaterMark\");if(highWaterMark===@undefined)@throwTypeError(\"CountQueuingStrategy.highWaterMark getter called on incompatible |this| value.\");return highWaterMark})\n"; // size const JSC::ConstructAbility s_countQueuingStrategySizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2322,9 +2304,9 @@ const char* const s_countQueuingStrategySizeCode = "(function (){\"use strict\"; const JSC::ConstructAbility s_countQueuingStrategyInitializeCountQueuingStrategyCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_countQueuingStrategyInitializeCountQueuingStrategyCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_countQueuingStrategyInitializeCountQueuingStrategyCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_countQueuingStrategyInitializeCountQueuingStrategyCodeLength = 121; +const int s_countQueuingStrategyInitializeCountQueuingStrategyCodeLength = 139; static const JSC::Intrinsic s_countQueuingStrategyInitializeCountQueuingStrategyCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_countQueuingStrategyInitializeCountQueuingStrategyCode = "(function (b){\"use strict\";@putByIdDirectPrivate(this,\"highWaterMark\",@extractHighWaterMarkFromQueuingStrategyInit(b))})\n"; +const char* const s_countQueuingStrategyInitializeCountQueuingStrategyCode = "(function (parameters){\"use strict\";@putByIdDirectPrivate(this,\"highWaterMark\",@extractHighWaterMarkFromQueuingStrategyInit(parameters))})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2340,25 +2322,25 @@ WEBCORE_FOREACH_COUNTQUEUINGSTRATEGY_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCodeLength = 243; +const int s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCodeLength = 267; static const JSC::Intrinsic s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCode = "(function (a,c){\"use strict\";if(arguments.length!==3&&arguments[2]!==@isReadableStream)@throwTypeError(\"ReadableStreamBYOBRequest constructor should not be called directly\");return @privateInitializeReadableStreamBYOBRequest.@call(this,a,c)})\n"; +const char* const s_readableStreamBYOBRequestInitializeReadableStreamBYOBRequestCode = "(function (controller,view){\"use strict\";if(arguments.length!==3&&arguments[2]!==@isReadableStream)@throwTypeError(\"ReadableStreamBYOBRequest constructor should not be called directly\");return @privateInitializeReadableStreamBYOBRequest.@call(this,controller,view)})\n"; // respond const JSC::ConstructAbility s_readableStreamBYOBRequestRespondCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamBYOBRequestRespondCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamBYOBRequestRespondCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamBYOBRequestRespondCodeLength = 430; +const int s_readableStreamBYOBRequestRespondCodeLength = 452; static const JSC::Intrinsic s_readableStreamBYOBRequestRespondCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamBYOBRequestRespondCode = "(function (m){\"use strict\";if(!@isReadableStreamBYOBRequest(this))throw @makeThisTypeError(\"ReadableStreamBYOBRequest\",\"respond\");if(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\")===@undefined)@throwTypeError(\"ReadableStreamBYOBRequest.associatedReadableByteStreamController is undefined\");return @readableByteStreamControllerRespond(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\"),m)})\n"; +const char* const s_readableStreamBYOBRequestRespondCode = "(function (bytesWritten){\"use strict\";if(!@isReadableStreamBYOBRequest(this))throw @makeThisTypeError(\"ReadableStreamBYOBRequest\",\"respond\");if(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\")===@undefined)@throwTypeError(\"ReadableStreamBYOBRequest.associatedReadableByteStreamController is undefined\");return @readableByteStreamControllerRespond(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\"),bytesWritten)})\n"; // respondWithNewView const JSC::ConstructAbility s_readableStreamBYOBRequestRespondWithNewViewCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamBYOBRequestRespondWithNewViewCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamBYOBRequestRespondWithNewViewCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamBYOBRequestRespondWithNewViewCodeLength = 595; +const int s_readableStreamBYOBRequestRespondWithNewViewCodeLength = 607; static const JSC::Intrinsic s_readableStreamBYOBRequestRespondWithNewViewCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamBYOBRequestRespondWithNewViewCode = "(function (_){\"use strict\";if(!@isReadableStreamBYOBRequest(this))throw @makeThisTypeError(\"ReadableStreamBYOBRequest\",\"respond\");if(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\")===@undefined)@throwTypeError(\"ReadableStreamBYOBRequest.associatedReadableByteStreamController is undefined\");if(!@isObject(_))@throwTypeError(\"Provided view is not an object\");if(!@ArrayBuffer.@isView(_))@throwTypeError(\"Provided view is not an ArrayBufferView\");return @readableByteStreamControllerRespondWithNewView(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\"),_)})\n"; +const char* const s_readableStreamBYOBRequestRespondWithNewViewCode = "(function (view){\"use strict\";if(!@isReadableStreamBYOBRequest(this))throw @makeThisTypeError(\"ReadableStreamBYOBRequest\",\"respond\");if(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\")===@undefined)@throwTypeError(\"ReadableStreamBYOBRequest.associatedReadableByteStreamController is undefined\");if(!@isObject(view))@throwTypeError(\"Provided view is not an object\");if(!@ArrayBuffer.@isView(view))@throwTypeError(\"Provided view is not an ArrayBufferView\");return @readableByteStreamControllerRespondWithNewView(@getByIdDirectPrivate(this,\"associatedReadableByteStreamController\"),view)})\n"; // view const JSC::ConstructAbility s_readableStreamBYOBRequestViewCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2382,9 +2364,9 @@ WEBCORE_FOREACH_READABLESTREAMBYOBREQUEST_BUILTIN_CODE(DEFINE_BUILTIN_GENERATOR) const JSC::ConstructAbility s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCodeLength = 237; +const int s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCodeLength = 301; static const JSC::Intrinsic s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCode = "(function (u){\"use strict\";const c=@getInternalWritableStream(u);if(c)u=c;if(!@isWritableStream(u))@throwTypeError(\"WritableStreamDefaultWriter constructor takes a WritableStream\");return @setUpWritableStreamDefaultWriter(this,u),this})\n"; +const char* const s_writableStreamDefaultWriterInitializeWritableStreamDefaultWriterCode = "(function (stream){\"use strict\";const internalStream=@getInternalWritableStream(stream);if(internalStream)stream=internalStream;if(!@isWritableStream(stream))@throwTypeError(\"WritableStreamDefaultWriter constructor takes a WritableStream\");return @setUpWritableStreamDefaultWriter(this,stream),this})\n"; // closed const JSC::ConstructAbility s_writableStreamDefaultWriterClosedCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; @@ -2414,33 +2396,33 @@ const char* const s_writableStreamDefaultWriterReadyCode = "(function (){\"use s const JSC::ConstructAbility s_writableStreamDefaultWriterAbortCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamDefaultWriterAbortCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamDefaultWriterAbortCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamDefaultWriterAbortCodeLength = 340; +const int s_writableStreamDefaultWriterAbortCodeLength = 350; static const JSC::Intrinsic s_writableStreamDefaultWriterAbortCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamDefaultWriterAbortCode = "(function (c){\"use strict\";if(!@isWritableStreamDefaultWriter(this))return @Promise.@reject(@makeThisTypeError(\"WritableStreamDefaultWriter\",\"abort\"));if(@getByIdDirectPrivate(this,\"stream\")===@undefined)return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter has no stream\"));return @writableStreamDefaultWriterAbort(this,c)})\n"; +const char* const s_writableStreamDefaultWriterAbortCode = "(function (reason){\"use strict\";if(!@isWritableStreamDefaultWriter(this))return @Promise.@reject(@makeThisTypeError(\"WritableStreamDefaultWriter\",\"abort\"));if(@getByIdDirectPrivate(this,\"stream\")===@undefined)return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter has no stream\"));return @writableStreamDefaultWriterAbort(this,reason)})\n"; // close const JSC::ConstructAbility s_writableStreamDefaultWriterCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamDefaultWriterCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamDefaultWriterCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamDefaultWriterCloseCodeLength = 477; +const int s_writableStreamDefaultWriterCloseCodeLength = 492; static const JSC::Intrinsic s_writableStreamDefaultWriterCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamDefaultWriterCloseCode = "(function (){\"use strict\";if(!@isWritableStreamDefaultWriter(this))return @Promise.@reject(@makeThisTypeError(\"WritableStreamDefaultWriter\",\"close\"));const i=@getByIdDirectPrivate(this,\"stream\");if(i===@undefined)return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter has no stream\"));if(@writableStreamCloseQueuedOrInFlight(i))return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter is being closed\"));return @writableStreamDefaultWriterClose(this)})\n"; +const char* const s_writableStreamDefaultWriterCloseCode = "(function (){\"use strict\";if(!@isWritableStreamDefaultWriter(this))return @Promise.@reject(@makeThisTypeError(\"WritableStreamDefaultWriter\",\"close\"));const stream=@getByIdDirectPrivate(this,\"stream\");if(stream===@undefined)return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter has no stream\"));if(@writableStreamCloseQueuedOrInFlight(stream))return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter is being closed\"));return @writableStreamDefaultWriterClose(this)})\n"; // releaseLock const JSC::ConstructAbility s_writableStreamDefaultWriterReleaseLockCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamDefaultWriterReleaseLockCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamDefaultWriterReleaseLockCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamDefaultWriterReleaseLockCodeLength = 307; +const int s_writableStreamDefaultWriterReleaseLockCodeLength = 241; static const JSC::Intrinsic s_writableStreamDefaultWriterReleaseLockCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamDefaultWriterReleaseLockCode = "(function (){\"use strict\";if(!@isWritableStreamDefaultWriter(this))throw @makeThisTypeError(\"WritableStreamDefaultWriter\",\"releaseLock\");const i=@getByIdDirectPrivate(this,\"stream\");if(i===@undefined)return;@assert(@getByIdDirectPrivate(i,\"writer\")!==@undefined),@writableStreamDefaultWriterRelease(this)})\n"; +const char* const s_writableStreamDefaultWriterReleaseLockCode = "(function (){\"use strict\";if(!@isWritableStreamDefaultWriter(this))throw @makeThisTypeError(\"WritableStreamDefaultWriter\",\"releaseLock\");if(@getByIdDirectPrivate(this,\"stream\")===@undefined)return;@writableStreamDefaultWriterRelease(this)})\n"; // write const JSC::ConstructAbility s_writableStreamDefaultWriterWriteCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamDefaultWriterWriteCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamDefaultWriterWriteCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamDefaultWriterWriteCodeLength = 340; +const int s_writableStreamDefaultWriterWriteCodeLength = 348; static const JSC::Intrinsic s_writableStreamDefaultWriterWriteCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamDefaultWriterWriteCode = "(function (e){\"use strict\";if(!@isWritableStreamDefaultWriter(this))return @Promise.@reject(@makeThisTypeError(\"WritableStreamDefaultWriter\",\"write\"));if(@getByIdDirectPrivate(this,\"stream\")===@undefined)return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter has no stream\"));return @writableStreamDefaultWriterWrite(this,e)})\n"; +const char* const s_writableStreamDefaultWriterWriteCode = "(function (chunk){\"use strict\";if(!@isWritableStreamDefaultWriter(this))return @Promise.@reject(@makeThisTypeError(\"WritableStreamDefaultWriter\",\"write\"));if(@getByIdDirectPrivate(this,\"stream\")===@undefined)return @Promise.@reject(@makeTypeError(\"WritableStreamDefaultWriter has no stream\"));return @writableStreamDefaultWriterWrite(this,chunk)})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2456,113 +2438,113 @@ WEBCORE_FOREACH_WRITABLESTREAMDEFAULTWRITER_BUILTIN_CODE(DEFINE_BUILTIN_GENERATO const JSC::ConstructAbility s_readableStreamInitializeReadableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamInitializeReadableStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamInitializeReadableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableStreamInitializeReadableStreamCodeLength = 2143; +const int s_readableStreamInitializeReadableStreamCodeLength = 2702; static const JSC::Intrinsic s_readableStreamInitializeReadableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamInitializeReadableStreamCode = "(function (_,v){\"use strict\";if(_===@undefined)_={@bunNativeType:0,@bunNativePtr:0,@lazy:!1};if(v===@undefined)v={};if(!@isObject(_))@throwTypeError(\"ReadableStream constructor takes an object as first argument\");if(v!==@undefined&&!@isObject(v))@throwTypeError(\"ReadableStream constructor takes an object as second argument, if any\");@putByIdDirectPrivate(this,\"state\",@streamReadable),@putByIdDirectPrivate(this,\"reader\",@undefined),@putByIdDirectPrivate(this,\"storedError\",@undefined),@putByIdDirectPrivate(this,\"disturbed\",!1),@putByIdDirectPrivate(this,\"readableStreamController\",null),@putByIdDirectPrivate(this,\"bunNativeType\",@getByIdDirectPrivate(_,\"bunNativeType\")\?\?0),@putByIdDirectPrivate(this,\"bunNativePtr\",@getByIdDirectPrivate(_,\"bunNativePtr\")\?\?0),@putByIdDirectPrivate(this,\"asyncContext\",@getInternalField(@asyncContext,0));const B=_.type===\"direct\",R=!!_.@lazy,P=B||R;if(@getByIdDirectPrivate(_,\"pull\")!==@undefined&&!P){const m=@getByIdDirectPrivate(v,\"size\"),f=@getByIdDirectPrivate(v,\"highWaterMark\");return @putByIdDirectPrivate(this,\"highWaterMark\",f),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@setupReadableStreamDefaultController(this,_,m,f!==@undefined\?f:1,@getByIdDirectPrivate(_,\"start\"),@getByIdDirectPrivate(_,\"pull\"),@getByIdDirectPrivate(_,\"cancel\")),this}if(B)@putByIdDirectPrivate(this,\"underlyingSource\",_),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(v,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>@createReadableStreamController(this,_,v));else if(P){const m=_.autoAllocateChunkSize;@putByIdDirectPrivate(this,\"highWaterMark\",@undefined),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",m||@getByIdDirectPrivate(v,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>{const f=@lazyLoadStream(this,m);if(f)@createReadableStreamController(this,f,v)})}else @putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(v,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",@undefined),@createReadableStreamController(this,_,v);return this})\n"; +const char* const s_readableStreamInitializeReadableStreamCode = "(function (underlyingSource,strategy){\"use strict\";if(underlyingSource===@undefined)underlyingSource={@bunNativeType:0,@bunNativePtr:0,@lazy:!1};if(strategy===@undefined)strategy={};if(!@isObject(underlyingSource))@throwTypeError(\"ReadableStream constructor takes an object as first argument\");if(strategy!==@undefined&&!@isObject(strategy))@throwTypeError(\"ReadableStream constructor takes an object as second argument, if any\");@putByIdDirectPrivate(this,\"state\",@streamReadable),@putByIdDirectPrivate(this,\"reader\",@undefined),@putByIdDirectPrivate(this,\"storedError\",@undefined),@putByIdDirectPrivate(this,\"disturbed\",!1),@putByIdDirectPrivate(this,\"readableStreamController\",null),@putByIdDirectPrivate(this,\"bunNativeType\",@getByIdDirectPrivate(underlyingSource,\"bunNativeType\")\?\?0),@putByIdDirectPrivate(this,\"bunNativePtr\",@getByIdDirectPrivate(underlyingSource,\"bunNativePtr\")\?\?0),@putByIdDirectPrivate(this,\"asyncContext\",@getInternalField(@asyncContext,0));const isDirect=underlyingSource.type===\"direct\",isUnderlyingSourceLazy=!!underlyingSource.@lazy,isLazy=isDirect||isUnderlyingSourceLazy;if(@getByIdDirectPrivate(underlyingSource,\"pull\")!==@undefined&&!isLazy){const size=@getByIdDirectPrivate(strategy,\"size\"),highWaterMark=@getByIdDirectPrivate(strategy,\"highWaterMark\");return @putByIdDirectPrivate(this,\"highWaterMark\",highWaterMark),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@setupReadableStreamDefaultController(this,underlyingSource,size,highWaterMark!==@undefined\?highWaterMark:1,@getByIdDirectPrivate(underlyingSource,\"start\"),@getByIdDirectPrivate(underlyingSource,\"pull\"),@getByIdDirectPrivate(underlyingSource,\"cancel\")),this}if(isDirect)@putByIdDirectPrivate(this,\"underlyingSource\",underlyingSource),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(strategy,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>@createReadableStreamController(this,underlyingSource,strategy));else if(isLazy){const autoAllocateChunkSize=underlyingSource.autoAllocateChunkSize;@putByIdDirectPrivate(this,\"highWaterMark\",@undefined),@putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",autoAllocateChunkSize||@getByIdDirectPrivate(strategy,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",()=>{const instance=@lazyLoadStream(this,autoAllocateChunkSize);if(instance)@createReadableStreamController(this,instance,strategy)})}else @putByIdDirectPrivate(this,\"underlyingSource\",@undefined),@putByIdDirectPrivate(this,\"highWaterMark\",@getByIdDirectPrivate(strategy,\"highWaterMark\")),@putByIdDirectPrivate(this,\"start\",@undefined),@createReadableStreamController(this,underlyingSource,strategy);return this})\n"; // readableStreamToArray const JSC::ConstructAbility s_readableStreamReadableStreamToArrayCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamReadableStreamToArrayCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamReadableStreamToArrayCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamReadableStreamToArrayCodeLength = 173; +const int s_readableStreamReadableStreamToArrayCodeLength = 238; static const JSC::Intrinsic s_readableStreamReadableStreamToArrayCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToArrayCode = "(function (_){\"use strict\";var b=@getByIdDirectPrivate(_,\"underlyingSource\");if(b!==@undefined)return @readableStreamToArrayDirect(_,b);return @readableStreamIntoArray(_)})\n"; +const char* const s_readableStreamReadableStreamToArrayCode = "(function (stream){\"use strict\";var underlyingSource=@getByIdDirectPrivate(stream,\"underlyingSource\");if(underlyingSource!==@undefined)return @readableStreamToArrayDirect(stream,underlyingSource);return @readableStreamIntoArray(stream)})\n"; // readableStreamToText const JSC::ConstructAbility s_readableStreamReadableStreamToTextCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamReadableStreamToTextCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamReadableStreamToTextCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamReadableStreamToTextCodeLength = 171; +const int s_readableStreamReadableStreamToTextCodeLength = 236; static const JSC::Intrinsic s_readableStreamReadableStreamToTextCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToTextCode = "(function (p){\"use strict\";var _=@getByIdDirectPrivate(p,\"underlyingSource\");if(_!==@undefined)return @readableStreamToTextDirect(p,_);return @readableStreamIntoText(p)})\n"; +const char* const s_readableStreamReadableStreamToTextCode = "(function (stream){\"use strict\";var underlyingSource=@getByIdDirectPrivate(stream,\"underlyingSource\");if(underlyingSource!==@undefined)return @readableStreamToTextDirect(stream,underlyingSource);return @readableStreamIntoText(stream)})\n"; // readableStreamToArrayBuffer const JSC::ConstructAbility s_readableStreamReadableStreamToArrayBufferCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamReadableStreamToArrayBufferCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamReadableStreamToArrayBufferCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamReadableStreamToArrayBufferCodeLength = 270; +const int s_readableStreamReadableStreamToArrayBufferCodeLength = 355; static const JSC::Intrinsic s_readableStreamReadableStreamToArrayBufferCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToArrayBufferCode = "(function (_){\"use strict\";var p=@getByIdDirectPrivate(_,\"underlyingSource\");if(p!==@undefined)return @readableStreamToArrayBufferDirect(_,p);var b=@Bun.readableStreamToArray(_);if(@isPromise(b))return b.then(@Bun.concatArrayBuffers);return @Bun.concatArrayBuffers(b)})\n"; +const char* const s_readableStreamReadableStreamToArrayBufferCode = "(function (stream){\"use strict\";var underlyingSource=@getByIdDirectPrivate(stream,\"underlyingSource\");if(underlyingSource!==@undefined)return @readableStreamToArrayBufferDirect(stream,underlyingSource);var result=@Bun.readableStreamToArray(stream);if(@isPromise(result))return result.then(@Bun.concatArrayBuffers);return @Bun.concatArrayBuffers(result)})\n"; // readableStreamToFormData const JSC::ConstructAbility s_readableStreamReadableStreamToFormDataCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamReadableStreamToFormDataCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamReadableStreamToFormDataCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamReadableStreamToFormDataCodeLength = 106; +const int s_readableStreamReadableStreamToFormDataCodeLength = 142; static const JSC::Intrinsic s_readableStreamReadableStreamToFormDataCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToFormDataCode = "(function (r,d){\"use strict\";return @Bun.readableStreamToBlob(r).then((u)=>{return FormData.from(u,d)})})\n"; +const char* const s_readableStreamReadableStreamToFormDataCode = "(function (stream,contentType){\"use strict\";return @Bun.readableStreamToBlob(stream).then((blob)=>{return FormData.from(blob,contentType)})})\n"; // readableStreamToJSON const JSC::ConstructAbility s_readableStreamReadableStreamToJSONCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamReadableStreamToJSONCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamReadableStreamToJSONCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamReadableStreamToJSONCodeLength = 94; +const int s_readableStreamReadableStreamToJSONCodeLength = 104; static const JSC::Intrinsic s_readableStreamReadableStreamToJSONCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToJSONCode = "(function (d){\"use strict\";return @Bun.readableStreamToText(d).@then(globalThis.JSON.parse)})\n"; +const char* const s_readableStreamReadableStreamToJSONCode = "(function (stream){\"use strict\";return @Bun.readableStreamToText(stream).@then(globalThis.JSON.parse)})\n"; // readableStreamToBlob const JSC::ConstructAbility s_readableStreamReadableStreamToBlobCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamReadableStreamToBlobCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamReadableStreamToBlobCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamReadableStreamToBlobCodeLength = 108; +const int s_readableStreamReadableStreamToBlobCodeLength = 126; static const JSC::Intrinsic s_readableStreamReadableStreamToBlobCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamReadableStreamToBlobCode = "(function (n){\"use strict\";return @Promise.resolve(@Bun.readableStreamToArray(n)).@then((B)=>new Blob(B))})\n"; +const char* const s_readableStreamReadableStreamToBlobCode = "(function (stream){\"use strict\";return @Promise.resolve(@Bun.readableStreamToArray(stream)).@then((array)=>new Blob(array))})\n"; // consumeReadableStream const JSC::ConstructAbility s_readableStreamConsumeReadableStreamCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableStreamConsumeReadableStreamCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableStreamConsumeReadableStreamCodeImplementationVisibility = JSC::ImplementationVisibility::Private; -const int s_readableStreamConsumeReadableStreamCodeLength = 1603; +const int s_readableStreamConsumeReadableStreamCodeLength = 2131; static const JSC::Intrinsic s_readableStreamConsumeReadableStreamCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableStreamConsumeReadableStreamCode = "(function (G,q,A){\"use strict\";const B=globalThis.Symbol.for(\"Bun.consumeReadableStreamPrototype\");var k=globalThis[B];if(!k)k=globalThis[B]=[];var w=k[q];if(w===@undefined){var[L,H,I,J,N,D]=globalThis[globalThis.Symbol.for('Bun.lazy')](q);w=class K{handleError;handleClosed;processResult;constructor(_,j){this.#$=j,this.#j=_,this.#_=!1,this.handleError=this._handleError.bind(this),this.handleClosed=this._handleClosed.bind(this),this.processResult=this._processResult.bind(this),_.closed.then(this.handleClosed,this.handleError)}_handleClosed(){if(this.#_)return;this.#_=!0;var _=this.#$;this.#$=0,J(_),D(_)}_handleError(_){if(this.#_)return;this.#_=!0;var j=this.#$;this.#$=0,H(j,_),D(j)}#$;#_=!1;#j;_handleReadMany({value:_,done:j,size:x}){if(j){this.handleClosed();return}if(this.#_)return;I(this.#$,_,j,x)}read(){if(!this.#$)return @throwTypeError(\"ReadableStreamSink is already closed\");return this.processResult(this.#j.read())}_processResult(_){if(_&&@isPromise(_)){if(@getPromiseInternalField(_,@promiseFieldFlags)&@promiseStateFulfilled){const x=@getPromiseInternalField(_,@promiseFieldReactionsOrResult);if(x)_=x}}if(_&&@isPromise(_))return _.then(this.processResult,this.handleError),null;if(_.done)return this.handleClosed(),0;else if(_.value)return _.value;else return-1}readMany(){if(!this.#$)return @throwTypeError(\"ReadableStreamSink is already closed\");return this.processResult(this.#j.readMany())}};const F=q+1;if(k.length{@putByIdDirectPrivate(p,\"started\",1),@assert(!@getByIdDirectPrivate(p,\"pulling\")),@assert(!@getByIdDirectPrivate(p,\"pullAgain\")),@readableByteStreamControllerCallPullIfNeeded(p)},(I)=>{if(@getByIdDirectPrivate(R,\"state\")===@streamReadable)@readableByteStreamControllerError(p,I)}),@putByIdDirectPrivate(this,\"cancel\",@readableByteStreamControllerCancel),@putByIdDirectPrivate(this,\"pull\",@readableByteStreamControllerPull),this})\n"; +const char* const s_readableByteStreamInternalsPrivateInitializeReadableByteStreamControllerCode = "(function (stream,underlyingByteSource,highWaterMark){\"use strict\";if(!@isReadableStream(stream))@throwTypeError(\"ReadableByteStreamController needs a ReadableStream\");if(@getByIdDirectPrivate(stream,\"readableStreamController\")!==null)@throwTypeError(\"ReadableStream already has a controller\");@putByIdDirectPrivate(this,\"controlledReadableStream\",stream),@putByIdDirectPrivate(this,\"underlyingByteSource\",underlyingByteSource),@putByIdDirectPrivate(this,\"pullAgain\",!1),@putByIdDirectPrivate(this,\"pulling\",!1),@readableByteStreamControllerClearPendingPullIntos(this),@putByIdDirectPrivate(this,\"queue\",@newQueue()),@putByIdDirectPrivate(this,\"started\",0),@putByIdDirectPrivate(this,\"closeRequested\",!1);let hwm=@toNumber(highWaterMark);if(hwm!==hwm||hwm<0)@throwRangeError(\"highWaterMark value is negative or not a number\");@putByIdDirectPrivate(this,\"strategyHWM\",hwm);let autoAllocateChunkSize=underlyingByteSource.autoAllocateChunkSize;if(autoAllocateChunkSize!==@undefined){if(autoAllocateChunkSize=@toNumber(autoAllocateChunkSize),autoAllocateChunkSize<=0||autoAllocateChunkSize===@Infinity||autoAllocateChunkSize===-@Infinity)@throwRangeError(\"autoAllocateChunkSize value is negative or equal to positive or negative infinity\")}@putByIdDirectPrivate(this,\"autoAllocateChunkSize\",autoAllocateChunkSize),@putByIdDirectPrivate(this,\"pendingPullIntos\",@createFIFO());const controller=this;return @promiseInvokeOrNoopNoCatch(@getByIdDirectPrivate(controller,\"underlyingByteSource\"),\"start\",[controller]).@then(()=>{@putByIdDirectPrivate(controller,\"started\",1),@readableByteStreamControllerCallPullIfNeeded(controller)},(error)=>{if(@getByIdDirectPrivate(stream,\"state\")===@streamReadable)@readableByteStreamControllerError(controller,error)}),@putByIdDirectPrivate(this,\"cancel\",@readableByteStreamControllerCancel),@putByIdDirectPrivate(this,\"pull\",@readableByteStreamControllerPull),this})\n"; // readableStreamByteStreamControllerStart const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCodeLength = 73; +const int s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCodeLength = 91; static const JSC::Intrinsic s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCode = "(function (u){\"use strict\";@putByIdDirectPrivate(u,\"start\",@undefined)})\n"; +const char* const s_readableByteStreamInternalsReadableStreamByteStreamControllerStartCode = "(function (controller){\"use strict\";@putByIdDirectPrivate(controller,\"start\",@undefined)})\n"; // privateInitializeReadableStreamBYOBRequest const JSC::ConstructAbility s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeLength = 139; +const int s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeLength = 163; static const JSC::Intrinsic s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCode = "(function (a,d){\"use strict\";@putByIdDirectPrivate(this,\"associatedReadableByteStreamController\",a),@putByIdDirectPrivate(this,\"view\",d)})\n"; +const char* const s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCode = "(function (controller,view){\"use strict\";@putByIdDirectPrivate(this,\"associatedReadableByteStreamController\",controller),@putByIdDirectPrivate(this,\"view\",view)})\n"; // isReadableByteStreamController const JSC::ConstructAbility s_readableByteStreamInternalsIsReadableByteStreamControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsIsReadableByteStreamControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsIsReadableByteStreamControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsIsReadableByteStreamControllerCodeLength = 100; +const int s_readableByteStreamInternalsIsReadableByteStreamControllerCodeLength = 127; static const JSC::Intrinsic s_readableByteStreamInternalsIsReadableByteStreamControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsIsReadableByteStreamControllerCode = "(function (u){\"use strict\";return @isObject(u)&&!!@getByIdDirectPrivate(u,\"underlyingByteSource\")})\n"; +const char* const s_readableByteStreamInternalsIsReadableByteStreamControllerCode = "(function (controller){\"use strict\";return @isObject(controller)&&!!@getByIdDirectPrivate(controller,\"underlyingByteSource\")})\n"; // isReadableStreamBYOBRequest const JSC::ConstructAbility s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeLength = 118; +const int s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeLength = 148; static const JSC::Intrinsic s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsIsReadableStreamBYOBRequestCode = "(function (n){\"use strict\";return @isObject(n)&&!!@getByIdDirectPrivate(n,\"associatedReadableByteStreamController\")})\n"; +const char* const s_readableByteStreamInternalsIsReadableStreamBYOBRequestCode = "(function (byobRequest){\"use strict\";return @isObject(byobRequest)&&!!@getByIdDirectPrivate(byobRequest,\"associatedReadableByteStreamController\")})\n"; // isReadableStreamBYOBReader const JSC::ConstructAbility s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeLength = 96; +const int s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeLength = 111; static const JSC::Intrinsic s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsIsReadableStreamBYOBReaderCode = "(function (c){\"use strict\";return @isObject(c)&&!!@getByIdDirectPrivate(c,\"readIntoRequests\")})\n"; +const char* const s_readableByteStreamInternalsIsReadableStreamBYOBReaderCode = "(function (reader){\"use strict\";return @isObject(reader)&&!!@getByIdDirectPrivate(reader,\"readIntoRequests\")})\n"; // readableByteStreamControllerCancel const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeLength = 248; +const int s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeLength = 336; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerCancelCode = "(function (a,u){\"use strict\";var _=@getByIdDirectPrivate(a,\"pendingPullIntos\"),p=_.peek();if(p)p.bytesFilled=0;return @putByIdDirectPrivate(a,\"queue\",@newQueue()),@promiseInvokeOrNoop(@getByIdDirectPrivate(a,\"underlyingByteSource\"),\"cancel\",[u])})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerCancelCode = "(function (controller,reason){\"use strict\";var pendingPullIntos=@getByIdDirectPrivate(controller,\"pendingPullIntos\"),first=pendingPullIntos.peek();if(first)first.bytesFilled=0;return @putByIdDirectPrivate(controller,\"queue\",@newQueue()),@promiseInvokeOrNoop(@getByIdDirectPrivate(controller,\"underlyingByteSource\"),\"cancel\",[reason])})\n"; // readableByteStreamControllerError const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeLength = 316; +const int s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeLength = 242; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerErrorCode = "(function (_,a){\"use strict\";@assert(@getByIdDirectPrivate(@getByIdDirectPrivate(_,\"controlledReadableStream\"),\"state\")===@streamReadable),@readableByteStreamControllerClearPendingPullIntos(_),@putByIdDirectPrivate(_,\"queue\",@newQueue()),@readableStreamError(@getByIdDirectPrivate(_,\"controlledReadableStream\"),a)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerErrorCode = "(function (controller,e){\"use strict\";@readableByteStreamControllerClearPendingPullIntos(controller),@putByIdDirectPrivate(controller,\"queue\",@newQueue()),@readableStreamError(@getByIdDirectPrivate(controller,\"controlledReadableStream\"),e)})\n"; // readableByteStreamControllerClose const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeLength = 569; +const int s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeLength = 473; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerCloseCode = "(function (d){\"use strict\";if(@assert(!@getByIdDirectPrivate(d,\"closeRequested\")),@assert(@getByIdDirectPrivate(@getByIdDirectPrivate(d,\"controlledReadableStream\"),\"state\")===@streamReadable),@getByIdDirectPrivate(d,\"queue\").size>0){@putByIdDirectPrivate(d,\"closeRequested\",!0);return}var a=@getByIdDirectPrivate(d,\"pendingPullIntos\")\?.peek();if(a){if(a.bytesFilled>0){const u=@makeTypeError(\"Close requested while there remain pending bytes\");throw @readableByteStreamControllerError(d,u),u}}@readableStreamClose(@getByIdDirectPrivate(d,\"controlledReadableStream\"))})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerCloseCode = "(function (controller){\"use strict\";if(@getByIdDirectPrivate(controller,\"queue\").size>0){@putByIdDirectPrivate(controller,\"closeRequested\",!0);return}var first=@getByIdDirectPrivate(controller,\"pendingPullIntos\")\?.peek();if(first){if(first.bytesFilled>0){const e=@makeTypeError(\"Close requested while there remain pending bytes\");throw @readableByteStreamControllerError(controller,e),e}}@readableStreamClose(@getByIdDirectPrivate(controller,\"controlledReadableStream\"))})\n"; // readableByteStreamControllerClearPendingPullIntos const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeLength = 224; +const int s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeLength = 281; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCode = "(function (_){\"use strict\";@readableByteStreamControllerInvalidateBYOBRequest(_);var u=@getByIdDirectPrivate(_,\"pendingPullIntos\");if(u!==@undefined)u.clear();else @putByIdDirectPrivate(_,\"pendingPullIntos\",@createFIFO())})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCode = "(function (controller){\"use strict\";@readableByteStreamControllerInvalidateBYOBRequest(controller);var existing=@getByIdDirectPrivate(controller,\"pendingPullIntos\");if(existing!==@undefined)existing.clear();else @putByIdDirectPrivate(controller,\"pendingPullIntos\",@createFIFO())})\n"; // readableByteStreamControllerGetDesiredSize const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeLength = 272; +const int s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeLength = 330; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCode = "(function (u){\"use strict\";const _=@getByIdDirectPrivate(u,\"controlledReadableStream\"),d=@getByIdDirectPrivate(_,\"state\");if(d===@streamErrored)return null;if(d===@streamClosed)return 0;return @getByIdDirectPrivate(u,\"strategyHWM\")-@getByIdDirectPrivate(u,\"queue\").size})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\"),state=@getByIdDirectPrivate(stream,\"state\");if(state===@streamErrored)return null;if(state===@streamClosed)return 0;return @getByIdDirectPrivate(controller,\"strategyHWM\")-@getByIdDirectPrivate(controller,\"queue\").size})\n"; // readableStreamHasBYOBReader const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeLength = 125; +const int s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeLength = 150; static const JSC::Intrinsic s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableStreamHasBYOBReaderCode = "(function (u){\"use strict\";const n=@getByIdDirectPrivate(u,\"reader\");return n!==@undefined&&@isReadableStreamBYOBReader(n)})\n"; +const char* const s_readableByteStreamInternalsReadableStreamHasBYOBReaderCode = "(function (stream){\"use strict\";const reader=@getByIdDirectPrivate(stream,\"reader\");return reader!==@undefined&&@isReadableStreamBYOBReader(reader)})\n"; // readableStreamHasDefaultReader const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeLength = 128; +const int s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeLength = 153; static const JSC::Intrinsic s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableStreamHasDefaultReaderCode = "(function (n){\"use strict\";const l=@getByIdDirectPrivate(n,\"reader\");return l!==@undefined&&@isReadableStreamDefaultReader(l)})\n"; +const char* const s_readableByteStreamInternalsReadableStreamHasDefaultReaderCode = "(function (stream){\"use strict\";const reader=@getByIdDirectPrivate(stream,\"reader\");return reader!==@undefined&&@isReadableStreamDefaultReader(reader)})\n"; // readableByteStreamControllerHandleQueueDrain const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeLength = 352; +const int s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeLength = 287; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCode = "(function (g){\"use strict\";if(@assert(@getByIdDirectPrivate(@getByIdDirectPrivate(g,\"controlledReadableStream\"),\"state\")===@streamReadable),!@getByIdDirectPrivate(g,\"queue\").size&&@getByIdDirectPrivate(g,\"closeRequested\"))@readableStreamClose(@getByIdDirectPrivate(g,\"controlledReadableStream\"));else @readableByteStreamControllerCallPullIfNeeded(g)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCode = "(function (controller){\"use strict\";if(!@getByIdDirectPrivate(controller,\"queue\").size&&@getByIdDirectPrivate(controller,\"closeRequested\"))@readableStreamClose(@getByIdDirectPrivate(controller,\"controlledReadableStream\"));else @readableByteStreamControllerCallPullIfNeeded(controller)})\n"; // readableByteStreamControllerPull const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerPullCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerPullCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerPullCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerPullCodeLength = 1005; +const int s_readableByteStreamInternalsReadableByteStreamControllerPullCodeLength = 1169; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerPullCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerPullCode = "(function (_){\"use strict\";const P=@getByIdDirectPrivate(_,\"controlledReadableStream\");if(@assert(@readableStreamHasDefaultReader(P)),@getByIdDirectPrivate(_,\"queue\").content\?.isNotEmpty()){const d=@getByIdDirectPrivate(_,\"queue\").content.shift();@getByIdDirectPrivate(_,\"queue\").size-=d.byteLength,@readableByteStreamControllerHandleQueueDrain(_);let h;try{h=new @Uint8Array(d.buffer,d.byteOffset,d.byteLength)}catch(F){return @Promise.@reject(F)}return @createFulfilledPromise({value:h,done:!1})}if(@getByIdDirectPrivate(_,\"autoAllocateChunkSize\")!==@undefined){let d;try{d=@createUninitializedArrayBuffer(@getByIdDirectPrivate(_,\"autoAllocateChunkSize\"))}catch(F){return @Promise.@reject(F)}const h={buffer:d,byteOffset:0,byteLength:@getByIdDirectPrivate(_,\"autoAllocateChunkSize\"),bytesFilled:0,elementSize:1,ctor:@Uint8Array,readerType:\"default\"};@getByIdDirectPrivate(_,\"pendingPullIntos\").push(h)}const R=@readableStreamAddReadRequest(P);return @readableByteStreamControllerCallPullIfNeeded(_),R})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerPullCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");if(@getByIdDirectPrivate(controller,\"queue\").content\?.isNotEmpty()){const entry=@getByIdDirectPrivate(controller,\"queue\").content.shift();@getByIdDirectPrivate(controller,\"queue\").size-=entry.byteLength,@readableByteStreamControllerHandleQueueDrain(controller);let view;try{view=new @Uint8Array(entry.buffer,entry.byteOffset,entry.byteLength)}catch(error){return @Promise.@reject(error)}return @createFulfilledPromise({value:view,done:!1})}if(@getByIdDirectPrivate(controller,\"autoAllocateChunkSize\")!==@undefined){let buffer;try{buffer=@createUninitializedArrayBuffer(@getByIdDirectPrivate(controller,\"autoAllocateChunkSize\"))}catch(error){return @Promise.@reject(error)}const pullIntoDescriptor={buffer,byteOffset:0,byteLength:@getByIdDirectPrivate(controller,\"autoAllocateChunkSize\"),bytesFilled:0,elementSize:1,ctor:@Uint8Array,readerType:\"default\"};@getByIdDirectPrivate(controller,\"pendingPullIntos\").push(pullIntoDescriptor)}const promise=@readableStreamAddReadRequest(stream);return @readableByteStreamControllerCallPullIfNeeded(controller),promise})\n"; // readableByteStreamControllerShouldCallPull const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeLength = 619; +const int s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeLength = 709; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCode = "(function (u){\"use strict\";const P=@getByIdDirectPrivate(u,\"controlledReadableStream\");if(@getByIdDirectPrivate(P,\"state\")!==@streamReadable)return!1;if(@getByIdDirectPrivate(u,\"closeRequested\"))return!1;if(!(@getByIdDirectPrivate(u,\"started\")>0))return!1;const b=@getByIdDirectPrivate(P,\"reader\");if(b&&(@getByIdDirectPrivate(b,\"readRequests\")\?.isNotEmpty()||!!@getByIdDirectPrivate(b,\"bunNativePtr\")))return!0;if(@readableStreamHasBYOBReader(P)&&@getByIdDirectPrivate(@getByIdDirectPrivate(P,\"reader\"),\"readIntoRequests\")\?.isNotEmpty())return!0;if(@readableByteStreamControllerGetDesiredSize(u)>0)return!0;return!1})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCode = "(function (controller){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");if(@getByIdDirectPrivate(stream,\"state\")!==@streamReadable)return!1;if(@getByIdDirectPrivate(controller,\"closeRequested\"))return!1;if(!(@getByIdDirectPrivate(controller,\"started\")>0))return!1;const reader=@getByIdDirectPrivate(stream,\"reader\");if(reader&&(@getByIdDirectPrivate(reader,\"readRequests\")\?.isNotEmpty()||!!@getByIdDirectPrivate(reader,\"bunNativePtr\")))return!0;if(@readableStreamHasBYOBReader(stream)&&@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readIntoRequests\")\?.isNotEmpty())return!0;if(@readableByteStreamControllerGetDesiredSize(controller)>0)return!0;return!1})\n"; // readableByteStreamControllerCallPullIfNeeded const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeLength = 670; +const int s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeLength = 748; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCode = "(function (i){\"use strict\";if(!@readableByteStreamControllerShouldCallPull(i))return;if(@getByIdDirectPrivate(i,\"pulling\")){@putByIdDirectPrivate(i,\"pullAgain\",!0);return}@assert(!@getByIdDirectPrivate(i,\"pullAgain\")),@putByIdDirectPrivate(i,\"pulling\",!0),@promiseInvokeOrNoop(@getByIdDirectPrivate(i,\"underlyingByteSource\"),\"pull\",[i]).@then(()=>{if(@putByIdDirectPrivate(i,\"pulling\",!1),@getByIdDirectPrivate(i,\"pullAgain\"))@putByIdDirectPrivate(i,\"pullAgain\",!1),@readableByteStreamControllerCallPullIfNeeded(i)},(_)=>{if(@getByIdDirectPrivate(@getByIdDirectPrivate(i,\"controlledReadableStream\"),\"state\")===@streamReadable)@readableByteStreamControllerError(i,_)})})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCode = "(function (controller){\"use strict\";if(!@readableByteStreamControllerShouldCallPull(controller))return;if(@getByIdDirectPrivate(controller,\"pulling\")){@putByIdDirectPrivate(controller,\"pullAgain\",!0);return}@putByIdDirectPrivate(controller,\"pulling\",!0),@promiseInvokeOrNoop(@getByIdDirectPrivate(controller,\"underlyingByteSource\"),\"pull\",[controller]).@then(()=>{if(@putByIdDirectPrivate(controller,\"pulling\",!1),@getByIdDirectPrivate(controller,\"pullAgain\"))@putByIdDirectPrivate(controller,\"pullAgain\",!1),@readableByteStreamControllerCallPullIfNeeded(controller)},(error)=>{if(@getByIdDirectPrivate(@getByIdDirectPrivate(controller,\"controlledReadableStream\"),\"state\")===@streamReadable)@readableByteStreamControllerError(controller,error)})})\n"; // transferBufferToCurrentRealm const JSC::ConstructAbility s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeLength = 38; +const int s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeLength = 48; static const JSC::Intrinsic s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsTransferBufferToCurrentRealmCode = "(function (n){\"use strict\";return n})\n"; +const char* const s_readableByteStreamInternalsTransferBufferToCurrentRealmCode = "(function (buffer){\"use strict\";return buffer})\n"; // readableStreamReaderKind const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamReaderKindCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableStreamReaderKindCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableStreamReaderKindCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableStreamReaderKindCodeLength = 188; +const int s_readableByteStreamInternalsReadableStreamReaderKindCodeLength = 208; static const JSC::Intrinsic s_readableByteStreamInternalsReadableStreamReaderKindCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableStreamReaderKindCode = "(function (t){\"use strict\";if(@getByIdDirectPrivate(t,\"readRequests\"))return @getByIdDirectPrivate(t,\"bunNativePtr\")\?3:1;if(@getByIdDirectPrivate(t,\"readIntoRequests\"))return 2;return 0})\n"; +const char* const s_readableByteStreamInternalsReadableStreamReaderKindCode = "(function (reader){\"use strict\";if(@getByIdDirectPrivate(reader,\"readRequests\"))return @getByIdDirectPrivate(reader,\"bunNativePtr\")\?3:1;if(@getByIdDirectPrivate(reader,\"readIntoRequests\"))return 2;return 0})\n"; // readableByteStreamControllerEnqueue const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeLength = 1076; +const int s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeLength = 1036; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCode = "(function (d,i){\"use strict\";const _=@getByIdDirectPrivate(d,\"controlledReadableStream\");switch(@assert(!@getByIdDirectPrivate(d,\"closeRequested\")),@assert(@getByIdDirectPrivate(_,\"state\")===@streamReadable),@getByIdDirectPrivate(_,\"reader\")\?@readableStreamReaderKind(@getByIdDirectPrivate(_,\"reader\")):0){case 1:{if(!@getByIdDirectPrivate(@getByIdDirectPrivate(_,\"reader\"),\"readRequests\")\?.isNotEmpty())@readableByteStreamControllerEnqueueChunk(d,@transferBufferToCurrentRealm(i.buffer),i.byteOffset,i.byteLength);else{@assert(!@getByIdDirectPrivate(d,\"queue\").content.size());const f=i.constructor===@Uint8Array\?i:new @Uint8Array(i.buffer,i.byteOffset,i.byteLength);@readableStreamFulfillReadRequest(_,f,!1)}break}case 2:{@readableByteStreamControllerEnqueueChunk(d,@transferBufferToCurrentRealm(i.buffer),i.byteOffset,i.byteLength),@readableByteStreamControllerProcessPullDescriptors(d);break}case 3:break;default:{@assert(!@isReadableStreamLocked(_)),@readableByteStreamControllerEnqueueChunk(d,@transferBufferToCurrentRealm(i.buffer),i.byteOffset,i.byteLength);break}}})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCode = "(function (controller,chunk){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");switch(@getByIdDirectPrivate(stream,\"reader\")\?@readableStreamReaderKind(@getByIdDirectPrivate(stream,\"reader\")):0){case 1:{if(!@getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readRequests\")\?.isNotEmpty())@readableByteStreamControllerEnqueueChunk(controller,@transferBufferToCurrentRealm(chunk.buffer),chunk.byteOffset,chunk.byteLength);else{const transferredView=chunk.constructor===@Uint8Array\?chunk:new @Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength);@readableStreamFulfillReadRequest(stream,transferredView,!1)}break}case 2:{@readableByteStreamControllerEnqueueChunk(controller,@transferBufferToCurrentRealm(chunk.buffer),chunk.byteOffset,chunk.byteLength),@readableByteStreamControllerProcessPullDescriptors(controller);break}case 3:break;default:{@readableByteStreamControllerEnqueueChunk(controller,@transferBufferToCurrentRealm(chunk.buffer),chunk.byteOffset,chunk.byteLength);break}}})\n"; // readableByteStreamControllerEnqueueChunk const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeLength = 160; +const int s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeLength = 213; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCode = "(function (_,d,p,a){\"use strict\";@getByIdDirectPrivate(_,\"queue\").content.push({buffer:d,byteOffset:p,byteLength:a}),@getByIdDirectPrivate(_,\"queue\").size+=a})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCode = "(function (controller,buffer,byteOffset,byteLength){\"use strict\";@getByIdDirectPrivate(controller,\"queue\").content.push({buffer,byteOffset,byteLength}),@getByIdDirectPrivate(controller,\"queue\").size+=byteLength})\n"; // readableByteStreamControllerRespondWithNewView const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeLength = 417; +const int s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeLength = 463; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCode = "(function (d,u){\"use strict\";@assert(@getByIdDirectPrivate(d,\"pendingPullIntos\").isNotEmpty());let a=@getByIdDirectPrivate(d,\"pendingPullIntos\").peek();if(a.byteOffset+a.bytesFilled!==u.byteOffset)@throwRangeError(\"Invalid value for view.byteOffset\");if(a.byteLength!==u.byteLength)@throwRangeError(\"Invalid value for view.byteLength\");a.buffer=u.buffer,@readableByteStreamControllerRespondInternal(d,u.byteLength)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCode = "(function (controller,view){\"use strict\";let firstDescriptor=@getByIdDirectPrivate(controller,\"pendingPullIntos\").peek();if(firstDescriptor.byteOffset+firstDescriptor.bytesFilled!==view.byteOffset)@throwRangeError(\"Invalid value for view.byteOffset\");if(firstDescriptor.byteLength!==view.byteLength)@throwRangeError(\"Invalid value for view.byteLength\");firstDescriptor.buffer=view.buffer,@readableByteStreamControllerRespondInternal(controller,view.byteLength)})\n"; // readableByteStreamControllerRespond const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeLength = 247; +const int s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeLength = 287; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondCode = "(function (u,_){\"use strict\";if(_=@toNumber(_),_!==_||_===@Infinity||_<0)@throwRangeError(\"bytesWritten has an incorrect value\");@assert(@getByIdDirectPrivate(u,\"pendingPullIntos\").isNotEmpty()),@readableByteStreamControllerRespondInternal(u,_)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondCode = "(function (controller,bytesWritten){\"use strict\";if(bytesWritten=@toNumber(bytesWritten),bytesWritten!==bytesWritten||bytesWritten===@Infinity||bytesWritten<0)@throwRangeError(\"bytesWritten has an incorrect value\");@readableByteStreamControllerRespondInternal(controller,bytesWritten)})\n"; // readableByteStreamControllerRespondInternal const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeLength = 464; +const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeLength = 534; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCode = "(function (d,u){\"use strict\";let _=@getByIdDirectPrivate(d,\"pendingPullIntos\").peek(),k=@getByIdDirectPrivate(d,\"controlledReadableStream\");if(@getByIdDirectPrivate(k,\"state\")===@streamClosed){if(u!==0)@throwTypeError(\"bytesWritten is different from 0 even though stream is closed\");@readableByteStreamControllerRespondInClosedState(d,_)}else @assert(@getByIdDirectPrivate(k,\"state\")===@streamReadable),@readableByteStreamControllerRespondInReadableState(d,u,_)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCode = "(function (controller,bytesWritten){\"use strict\";let firstDescriptor=@getByIdDirectPrivate(controller,\"pendingPullIntos\").peek(),stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");if(@getByIdDirectPrivate(stream,\"state\")===@streamClosed){if(bytesWritten!==0)@throwTypeError(\"bytesWritten is different from 0 even though stream is closed\");@readableByteStreamControllerRespondInClosedState(controller,firstDescriptor)}else @readableByteStreamControllerRespondInReadableState(controller,bytesWritten,firstDescriptor)})\n"; // readableByteStreamControllerRespondInReadableState const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeLength = 799; +const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeLength = 1110; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCode = "(function (w,_,f){\"use strict\";if(f.bytesFilled+_>f.byteLength)@throwRangeError(\"bytesWritten value is too great\");if(@assert(@getByIdDirectPrivate(w,\"pendingPullIntos\").isEmpty()||@getByIdDirectPrivate(w,\"pendingPullIntos\").peek()===f),@readableByteStreamControllerInvalidateBYOBRequest(w),f.bytesFilled+=_,f.bytesFilled0){const h=f.byteOffset+f.bytesFilled,g=@cloneArrayBuffer(f.buffer,h-R,R);@readableByteStreamControllerEnqueueChunk(w,g,0,g.byteLength)}f.buffer=@transferBufferToCurrentRealm(f.buffer),f.bytesFilled-=R,@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(w,\"controlledReadableStream\"),f),@readableByteStreamControllerProcessPullDescriptors(w)})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCode = "(function (controller,bytesWritten,pullIntoDescriptor){\"use strict\";if(pullIntoDescriptor.bytesFilled+bytesWritten>pullIntoDescriptor.byteLength)@throwRangeError(\"bytesWritten value is too great\");if(@readableByteStreamControllerInvalidateBYOBRequest(controller),pullIntoDescriptor.bytesFilled+=bytesWritten,pullIntoDescriptor.bytesFilled0){const end=pullIntoDescriptor.byteOffset+pullIntoDescriptor.bytesFilled,remainder=@cloneArrayBuffer(pullIntoDescriptor.buffer,end-remainderSize,remainderSize);@readableByteStreamControllerEnqueueChunk(controller,remainder,0,remainder.byteLength)}pullIntoDescriptor.buffer=@transferBufferToCurrentRealm(pullIntoDescriptor.buffer),pullIntoDescriptor.bytesFilled-=remainderSize,@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(controller,\"controlledReadableStream\"),pullIntoDescriptor),@readableByteStreamControllerProcessPullDescriptors(controller)})\n"; // readableByteStreamControllerRespondInClosedState const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeLength = 502; +const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeLength = 596; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCode = "(function (a,_){\"use strict\";if(_.buffer=@transferBufferToCurrentRealm(_.buffer),@assert(_.bytesFilled===0),@readableStreamHasBYOBReader(@getByIdDirectPrivate(a,\"controlledReadableStream\")))while(@getByIdDirectPrivate(@getByIdDirectPrivate(@getByIdDirectPrivate(a,\"controlledReadableStream\"),\"reader\"),\"readIntoRequests\")\?.isNotEmpty()){let d=@readableByteStreamControllerShiftPendingDescriptor(a);@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(a,\"controlledReadableStream\"),d)}})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCode = "(function (controller,firstDescriptor){\"use strict\";if(firstDescriptor.buffer=@transferBufferToCurrentRealm(firstDescriptor.buffer),@readableStreamHasBYOBReader(@getByIdDirectPrivate(controller,\"controlledReadableStream\")))while(@getByIdDirectPrivate(@getByIdDirectPrivate(@getByIdDirectPrivate(controller,\"controlledReadableStream\"),\"reader\"),\"readIntoRequests\")\?.isNotEmpty()){let pullIntoDescriptor=@readableByteStreamControllerShiftPendingDescriptor(controller);@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(controller,\"controlledReadableStream\"),pullIntoDescriptor)}})\n"; // readableByteStreamControllerProcessPullDescriptors const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeLength = 472; +const int s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeLength = 534; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCode = "(function (d){\"use strict\";@assert(!@getByIdDirectPrivate(d,\"closeRequested\"));while(@getByIdDirectPrivate(d,\"pendingPullIntos\").isNotEmpty()){if(@getByIdDirectPrivate(d,\"queue\").size===0)return;let a=@getByIdDirectPrivate(d,\"pendingPullIntos\").peek();if(@readableByteStreamControllerFillDescriptorFromQueue(d,a))@readableByteStreamControllerShiftPendingDescriptor(d),@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(d,\"controlledReadableStream\"),a)}})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCode = "(function (controller){\"use strict\";while(@getByIdDirectPrivate(controller,\"pendingPullIntos\").isNotEmpty()){if(@getByIdDirectPrivate(controller,\"queue\").size===0)return;let pullIntoDescriptor=@getByIdDirectPrivate(controller,\"pendingPullIntos\").peek();if(@readableByteStreamControllerFillDescriptorFromQueue(controller,pullIntoDescriptor))@readableByteStreamControllerShiftPendingDescriptor(controller),@readableByteStreamControllerCommitDescriptor(@getByIdDirectPrivate(controller,\"controlledReadableStream\"),pullIntoDescriptor)}})\n"; // readableByteStreamControllerFillDescriptorFromQueue const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeLength = 970; +const int s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeLength = 1538; static const JSC::Intrinsic s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCode = "(function (q,_){\"use strict\";const H=_.bytesFilled-_.bytesFilled%_.elementSize,z=@getByIdDirectPrivate(q,\"queue\").size<_.byteLength-_.bytesFilled\?@getByIdDirectPrivate(q,\"queue\").size:_.byteLength-_.bytesFilled,E=_.bytesFilled+z,G=E-E%_.elementSize;let v=z,w=!1;if(G>H)v=G-_.bytesFilled,w=!0;while(v>0){let j=@getByIdDirectPrivate(q,\"queue\").content.peek();const k=v0),@assert(_.bytesFilled<_.elementSize);return w})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCode = "(function (controller,pullIntoDescriptor){\"use strict\";const currentAlignedBytes=pullIntoDescriptor.bytesFilled-pullIntoDescriptor.bytesFilled%pullIntoDescriptor.elementSize,maxBytesToCopy=@getByIdDirectPrivate(controller,\"queue\").sizecurrentAlignedBytes)totalBytesToCopyRemaining=maxAlignedBytes-pullIntoDescriptor.bytesFilled,ready=!0;while(totalBytesToCopyRemaining>0){let headOfQueue=@getByIdDirectPrivate(controller,\"queue\").content.peek();const bytesToCopy=totalBytesToCopyRemaining0){if(@readableByteStreamControllerFillDescriptorFromQueue(b,_)){const k=@readableByteStreamControllerConvertDescriptor(_);return @readableByteStreamControllerHandleQueueDrain(b),@createFulfilledPromise({value:k,done:!1})}if(@getByIdDirectPrivate(b,\"closeRequested\")){const k=@makeTypeError(\"Closing stream has been requested\");return @readableByteStreamControllerError(b,k),@Promise.@reject(k)}}_.buffer=@transferBufferToCurrentRealm(_.buffer),@getByIdDirectPrivate(b,\"pendingPullIntos\").push(_);const R=@readableStreamAddReadIntoRequest(A);return @readableByteStreamControllerCallPullIfNeeded(b),R})\n"; +const char* const s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCode = "(function (controller,view){\"use strict\";const stream=@getByIdDirectPrivate(controller,\"controlledReadableStream\");let elementSize=1;if(view.BYTES_PER_ELEMENT!==@undefined)elementSize=view.BYTES_PER_ELEMENT;const ctor=view.constructor,pullIntoDescriptor={buffer:view.buffer,byteOffset:view.byteOffset,byteLength:view.byteLength,bytesFilled:0,elementSize,ctor,readerType:\"byob\"};var pending=@getByIdDirectPrivate(controller,\"pendingPullIntos\");if(pending\?.isNotEmpty())return pullIntoDescriptor.buffer=@transferBufferToCurrentRealm(pullIntoDescriptor.buffer),pending.push(pullIntoDescriptor),@readableStreamAddReadIntoRequest(stream);if(@getByIdDirectPrivate(stream,\"state\")===@streamClosed){const emptyView=new ctor(pullIntoDescriptor.buffer,pullIntoDescriptor.byteOffset,0);return @createFulfilledPromise({value:emptyView,done:!0})}if(@getByIdDirectPrivate(controller,\"queue\").size>0){if(@readableByteStreamControllerFillDescriptorFromQueue(controller,pullIntoDescriptor)){const filledView=@readableByteStreamControllerConvertDescriptor(pullIntoDescriptor);return @readableByteStreamControllerHandleQueueDrain(controller),@createFulfilledPromise({value:filledView,done:!1})}if(@getByIdDirectPrivate(controller,\"closeRequested\")){const e=@makeTypeError(\"Closing stream has been requested\");return @readableByteStreamControllerError(controller,e),@Promise.@reject(e)}}pullIntoDescriptor.buffer=@transferBufferToCurrentRealm(pullIntoDescriptor.buffer),@getByIdDirectPrivate(controller,\"pendingPullIntos\").push(pullIntoDescriptor);const promise=@readableStreamAddReadIntoRequest(stream);return @readableByteStreamControllerCallPullIfNeeded(controller),promise})\n"; // readableStreamAddReadIntoRequest const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeLength = 326; +const int s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeLength = 184; static const JSC::Intrinsic s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCode = "(function (i){\"use strict\";@assert(@isReadableStreamBYOBReader(@getByIdDirectPrivate(i,\"reader\"))),@assert(@getByIdDirectPrivate(i,\"state\")===@streamReadable||@getByIdDirectPrivate(i,\"state\")===@streamClosed);const _=@newPromise();return @getByIdDirectPrivate(@getByIdDirectPrivate(i,\"reader\"),\"readIntoRequests\").push(_),_})\n"; +const char* const s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCode = "(function (stream){\"use strict\";const readRequest=@newPromise();return @getByIdDirectPrivate(@getByIdDirectPrivate(stream,\"reader\"),\"readIntoRequests\").push(readRequest),readRequest})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2958,17 +2940,17 @@ WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(DEFINE_BUILTIN_GENERATO const JSC::ConstructAbility s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCodeLength = 368; +const int s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCodeLength = 388; static const JSC::Intrinsic s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCode = "(function (){\"use strict\";return @putByIdDirectPrivate(this,\"queue\",@newQueue()),@putByIdDirectPrivate(this,\"abortSteps\",(_)=>{const u=@getByIdDirectPrivate(this,\"abortAlgorithm\").@call(@undefined,_);return @writableStreamDefaultControllerClearAlgorithms(this),u}),@putByIdDirectPrivate(this,\"errorSteps\",()=>{@resetQueue(@getByIdDirectPrivate(this,\"queue\"))}),this})\n"; +const char* const s_writableStreamDefaultControllerInitializeWritableStreamDefaultControllerCode = "(function (){\"use strict\";return @putByIdDirectPrivate(this,\"queue\",@newQueue()),@putByIdDirectPrivate(this,\"abortSteps\",(reason)=>{const result=@getByIdDirectPrivate(this,\"abortAlgorithm\").@call(@undefined,reason);return @writableStreamDefaultControllerClearAlgorithms(this),result}),@putByIdDirectPrivate(this,\"errorSteps\",()=>{@resetQueue(@getByIdDirectPrivate(this,\"queue\"))}),this})\n"; // error const JSC::ConstructAbility s_writableStreamDefaultControllerErrorCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_writableStreamDefaultControllerErrorCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_writableStreamDefaultControllerErrorCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_writableStreamDefaultControllerErrorCodeLength = 301; +const int s_writableStreamDefaultControllerErrorCodeLength = 311; static const JSC::Intrinsic s_writableStreamDefaultControllerErrorCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_writableStreamDefaultControllerErrorCode = "(function (r){\"use strict\";if(@getByIdDirectPrivate(this,\"abortSteps\")===@undefined)throw @makeThisTypeError(\"WritableStreamDefaultController\",\"error\");const t=@getByIdDirectPrivate(this,\"stream\");if(@getByIdDirectPrivate(t,\"state\")!==\"writable\")return;@writableStreamDefaultControllerError(this,r)})\n"; +const char* const s_writableStreamDefaultControllerErrorCode = "(function (e){\"use strict\";if(@getByIdDirectPrivate(this,\"abortSteps\")===@undefined)throw @makeThisTypeError(\"WritableStreamDefaultController\",\"error\");const stream=@getByIdDirectPrivate(this,\"stream\");if(@getByIdDirectPrivate(stream,\"state\")!==\"writable\")return;@writableStreamDefaultControllerError(this,e)})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ @@ -2984,9 +2966,9 @@ WEBCORE_FOREACH_WRITABLESTREAMDEFAULTCONTROLLER_BUILTIN_CODE(DEFINE_BUILTIN_GENE const JSC::ConstructAbility s_eventSourceGetEventSourceCodeConstructAbility = JSC::ConstructAbility::CannotConstruct; const JSC::ConstructorKind s_eventSourceGetEventSourceCodeConstructorKind = JSC::ConstructorKind::None; const JSC::ImplementationVisibility s_eventSourceGetEventSourceCodeImplementationVisibility = JSC::ImplementationVisibility::Public; -const int s_eventSourceGetEventSourceCodeLength = 5469; +const int s_eventSourceGetEventSourceCodeLength = 8458; static const JSC::Intrinsic s_eventSourceGetEventSourceCodeIntrinsic = JSC::NoIntrinsic; -const char* const s_eventSourceGetEventSourceCode = "(function (){\"use strict\";class A extends EventTarget{#j;#$;#F;#G;#J;#K=!1;#U=null;#w=\"\";#M=\"\";#O=\"\";#Q=!0;#A=0;#B=0;#X=0;#L=null;static#V(w){w.#H()}static#Y(w,U){const L=w.data,j=L.#O\?`Last-Event-ID: ${L.#O}\\r\\n`:\"\",G=`GET ${U.pathname}${U.search} HTTP/1.1\\r\\nHost: bun\\r\\nContent-type: text/event-stream\\r\\nContent-length: 0\\r\\n${j}\\r\\n`,F=w.write(G);if(F!==G.length)L.#M=G.substring(F)}static#Z(w,U,L){for(;;){if(L>=U.length)return;let j=-1,G=U.indexOf(\"\\r\\n\",L);const F=G+2;if(G>0)if(w.#A===0){const B=parseInt(U.substring(L,G),16);if(B===0){w.#$=2,w.#U\?.end();return}j=F+B}else j=U.length;else{if(w.#w.length===0){w.#w+=U.substring(L);return}j=U.length}let K=U.substring(F,j);L=j+2;let Z=0,J=K.indexOf(\"\\n\\n\");if(J==-1){w.#w+=U.substring(F);return}if(w.#w.length)w.#w+=K,K=w.#w,w.#w=\"\";let X=!0;while(X){const B=K.substring(Z,J);let Y,M=\"\",O,W=0,Q=-1;for(;;){let z=B.indexOf(\"\\n\",W);if(z===-1){if(W>=B.length)break;z=B.length}const V=B.substring(W,z);if(V.startsWith(\"data:\"))if(M.length)M+=`\\n${V.substring(5).trim()}`;else M=V.substring(5).trim();else if(V.startsWith(\"event:\"))Y=V.substring(6).trim();else if(V.startsWith(\"id:\"))O=V.substring(3).trim();else if(V.startsWith(\"retry:\")){if(Q=parseInt(V.substring(6).trim(),10),Q!==Q)Q=-1}W=z+1}if(w.#O=O||\"\",Q>=0)w.#X=Q;if(M||O||Y)w.dispatchEvent(new MessageEvent(Y||\"message\",{data:M||\"\",origin:w.#j.origin,source:w,lastEventId:O}));if(K.length===J+2){X=!1;break}const H=K.indexOf(\"\\n\\n\",J+1);if(H===-1)break;Z=J,J=H}}}static#z={open(w){const U=w.data;if(U.#U=w,!U.#K)A.#Y(w,U.#j)},handshake(w,U,L){const j=w.data;if(U)A.#Y(w,j.#j);else j.#$=2,j.dispatchEvent(new ErrorEvent(\"error\",{error:L})),w.end()},data(w,U){const L=w.data;switch(L.#$){case 0:{let j=U.toString();const G=j.indexOf(\"\\r\\n\\r\\n\");if(G===-1){L.#w+=j;return}if(L.#w.length)L.#w+=j,j=L.#w,L.#w=\"\";const F=j.substring(0,G),K=F.indexOf(\"\\r\\n\");if(K===-1){L.#$=2,L.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Invalid HTTP request\")})),w.end();return}const Z=F.substring(0,K);if(Z!==\"HTTP/1.1 200 OK\"){L.#$=2,L.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(Z)})),w.end();return}let J=K+1,X=!1,B=-1;for(;;){let M=F.indexOf(\"\\r\\n\",J);if(M===-1){if(J>=F.length){if(!X)L.#$=2,L.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has no MIME type and \"text/event-stream\" is required. Aborting the connection.`)})),w.end();return}M=F.length}const O=F.substring(J+1,M),W=O.indexOf(\":\"),Q=O.substring(0,W),H=Q.localeCompare(\"content-type\",@undefined,{sensitivity:\"accent\"})===0;if(J=M+1,H)if(O.endsWith(\" text/event-stream\"))X=!0;else{L.#$=2,L.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has a MIME type that is not \"text/event-stream\". Aborting the connection.`)})),w.end();return}else if(Q.localeCompare(\"content-length\",@undefined,{sensitivity:\"accent\"})===0){if(B=parseInt(O.substring(W+1).trim(),10),B!==B||B<=0){L.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"EventSource's Content-Length is invalid. Aborting the connection.\")})),w.end();return}if(X)break}else if(Q.localeCompare(\"transfer-encoding\",@undefined,{sensitivity:\"accent\"})===0){if(O.substring(W+1).trim()!==\"chunked\"){L.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"EventSource's Transfer-Encoding is invalid. Aborting the connection.\")})),w.end();return}if(B=0,X)break}}L.#A=B,L.#$=1,L.dispatchEvent(new Event(\"open\"));const Y=j.substring(G+4);if(A.#Z(L,Y,0),L.#A>0){if(L.#B+=Y.length,L.#B>=L.#A)L.#$=2,w.end()}return}case 1:if(A.#Z(L,U.toString(),2),L.#A>0){if(L.#B+=U.byteLength,L.#B>=L.#A)L.#$=2,w.end()}return;default:break}},drain(w){const U=w.data;if(U.#$===0){const L=U.#w;if(L.length){const j=w.write(L);if(j!==L.length)w.data.#M=L.substring(j);else w.data.#M=\"\"}}},close:A.#W,end(w){A.#W(w).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Connection closed by server\")}))},timeout(w){A.#W(w).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Timeout\")}))},binaryType:\"buffer\"};static#W(w){const U=w.data;if(U.#U=null,U.#B=0,U.#$=2,U.#Q){if(U.#L)clearTimeout(U.#L);U.#L=setTimeout(A.#V,U.#X,U)}return U}constructor(w,U=@undefined){super();const L=new URL(w);this.#K=L.protocol===\"https:\",this.#j=L,this.#$=2,process.nextTick(A.#V,this)}ref(){this.#L\?.ref(),this.#U\?.ref()}unref(){this.#L\?.unref(),this.#U\?.unref()}#H(){if(this.#$!==2)return;const w=this.#j,U=this.#K;this.#$=0,@Bun.connect({data:this,socket:A.#z,hostname:w.hostname,port:parseInt(w.port||(U\?\"443\":\"80\"),10),tls:U\?{requestCert:!0,rejectUnauthorized:!1}:!1}).catch((L)=>{if(super.dispatchEvent(new ErrorEvent(\"error\",{error:L})),this.#Q){if(this.#L)this.#L.unref\?.();this.#L=setTimeout(A.#V,1000,this)}})}get url(){return this.#j.href}get readyState(){return this.#$}close(){this.#Q=!1,this.#$=2,this.#U\?.unref(),this.#U\?.end()}get onopen(){return this.#J}get onerror(){return this.#F}get onmessage(){return this.#G}set onopen(w){if(this.#J)super.removeEventListener(\"close\",this.#J);super.addEventListener(\"open\",w),this.#J=w}set onerror(w){if(this.#F)super.removeEventListener(\"error\",this.#F);super.addEventListener(\"error\",w),this.#F=w}set onmessage(w){if(this.#G)super.removeEventListener(\"message\",this.#G);super.addEventListener(\"message\",w),this.#G=w}}return Object.defineProperty(A.prototype,\"CONNECTING\",{enumerable:!0,value:0}),Object.defineProperty(A.prototype,\"OPEN\",{enumerable:!0,value:1}),Object.defineProperty(A.prototype,\"CLOSED\",{enumerable:!0,value:2}),A[Symbol.for(\"CommonJS\")]=0,A})\n"; +const char* const s_eventSourceGetEventSourceCode = "(function (){\"use strict\";class EventSource extends EventTarget{#url;#state;#onerror;#onmessage;#onopen;#is_tls=!1;#socket=null;#data_buffer=\"\";#send_buffer=\"\";#lastEventID=\"\";#reconnect=!0;#content_length=0;#received_length=0;#reconnection_time=0;#reconnection_timer=null;static#ConnectNextTick(self){self.#connect()}static#SendRequest(socket,url){const self=socket.data,last_event_header=self.#lastEventID\?`Last-Event-ID: ${self.#lastEventID}\\r\\n`:\"\",request=`GET ${url.pathname}${url.search} HTTP/1.1\\r\\nHost: bun\\r\\nContent-type: text/event-stream\\r\\nContent-length: 0\\r\\n${last_event_header}\\r\\n`,sended=socket.write(request);if(sended!==request.length)self.#send_buffer=request.substring(sended)}static#ProcessChunk(self,chunks,offset){for(;;){if(offset>=chunks.length)return;let chunk_end_idx=-1,start_idx=chunks.indexOf(\"\\r\\n\",offset);const chunk_start_idx=start_idx+2;if(start_idx>0)if(self.#content_length===0){const chunk_size=parseInt(chunks.substring(offset,start_idx),16);if(chunk_size===0){self.#state=2,self.#socket\?.end();return}chunk_end_idx=chunk_start_idx+chunk_size}else chunk_end_idx=chunks.length;else{if(self.#data_buffer.length===0){self.#data_buffer+=chunks.substring(offset);return}chunk_end_idx=chunks.length}let chunk=chunks.substring(chunk_start_idx,chunk_end_idx);offset=chunk_end_idx+2;let chunk_offset=0,event_idx=chunk.indexOf(\"\\n\\n\");if(event_idx==-1){self.#data_buffer+=chunks.substring(chunk_start_idx);return}if(self.#data_buffer.length)self.#data_buffer+=chunk,chunk=self.#data_buffer,self.#data_buffer=\"\";let more_events=!0;while(more_events){const event_data=chunk.substring(chunk_offset,event_idx);let type,data=\"\",id,event_line_idx=0,retry=-1;for(;;){let idx=event_data.indexOf(\"\\n\",event_line_idx);if(idx===-1){if(event_line_idx>=event_data.length)break;idx=event_data.length}const line=event_data.substring(event_line_idx,idx);if(line.startsWith(\"data:\"))if(data.length)data+=`\\n${line.substring(5).trim()}`;else data=line.substring(5).trim();else if(line.startsWith(\"event:\"))type=line.substring(6).trim();else if(line.startsWith(\"id:\"))id=line.substring(3).trim();else if(line.startsWith(\"retry:\")){if(retry=parseInt(line.substring(6).trim(),10),retry!==retry)retry=-1}event_line_idx=idx+1}if(self.#lastEventID=id||\"\",retry>=0)self.#reconnection_time=retry;if(data||id||type)self.dispatchEvent(new MessageEvent(type||\"message\",{data:data||\"\",origin:self.#url.origin,source:self,lastEventId:id}));if(chunk.length===event_idx+2){more_events=!1;break}const next_event_idx=chunk.indexOf(\"\\n\\n\",event_idx+1);if(next_event_idx===-1)break;chunk_offset=event_idx,event_idx=next_event_idx}}}static#Handlers={open(socket){const self=socket.data;if(self.#socket=socket,!self.#is_tls)EventSource.#SendRequest(socket,self.#url)},handshake(socket,success,verifyError){const self=socket.data;if(success)EventSource.#SendRequest(socket,self.#url);else self.#state=2,self.dispatchEvent(new ErrorEvent(\"error\",{error:verifyError})),socket.end()},data(socket,buffer){const self=socket.data;switch(self.#state){case 0:{let text=buffer.toString();const headers_idx=text.indexOf(\"\\r\\n\\r\\n\");if(headers_idx===-1){self.#data_buffer+=text;return}if(self.#data_buffer.length)self.#data_buffer+=text,text=self.#data_buffer,self.#data_buffer=\"\";const headers=text.substring(0,headers_idx),status_idx=headers.indexOf(\"\\r\\n\");if(status_idx===-1){self.#state=2,self.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Invalid HTTP request\")})),socket.end();return}const status=headers.substring(0,status_idx);if(status!==\"HTTP/1.1 200 OK\"){self.#state=2,self.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(status)})),socket.end();return}let start_idx=status_idx+1,mime_type_ok=!1,content_length=-1;for(;;){let header_idx=headers.indexOf(\"\\r\\n\",start_idx);if(header_idx===-1){if(start_idx>=headers.length){if(!mime_type_ok)self.#state=2,self.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has no MIME type and \"text/event-stream\" is required. Aborting the connection.`)})),socket.end();return}header_idx=headers.length}const header=headers.substring(start_idx+1,header_idx),header_name_idx=header.indexOf(\":\"),header_name=header.substring(0,header_name_idx),is_content_type=header_name.localeCompare(\"content-type\",@undefined,{sensitivity:\"accent\"})===0;if(start_idx=header_idx+1,is_content_type)if(header.endsWith(\" text/event-stream\"))mime_type_ok=!0;else{self.#state=2,self.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(`EventSource's response has a MIME type that is not \"text/event-stream\". Aborting the connection.`)})),socket.end();return}else if(header_name.localeCompare(\"content-length\",@undefined,{sensitivity:\"accent\"})===0){if(content_length=parseInt(header.substring(header_name_idx+1).trim(),10),content_length!==content_length||content_length<=0){self.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"EventSource's Content-Length is invalid. Aborting the connection.\")})),socket.end();return}if(mime_type_ok)break}else if(header_name.localeCompare(\"transfer-encoding\",@undefined,{sensitivity:\"accent\"})===0){if(header.substring(header_name_idx+1).trim()!==\"chunked\"){self.dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"EventSource's Transfer-Encoding is invalid. Aborting the connection.\")})),socket.end();return}if(content_length=0,mime_type_ok)break}}self.#content_length=content_length,self.#state=1,self.dispatchEvent(new Event(\"open\"));const chunks=text.substring(headers_idx+4);if(EventSource.#ProcessChunk(self,chunks,0),self.#content_length>0){if(self.#received_length+=chunks.length,self.#received_length>=self.#content_length)self.#state=2,socket.end()}return}case 1:if(EventSource.#ProcessChunk(self,buffer.toString(),2),self.#content_length>0){if(self.#received_length+=buffer.byteLength,self.#received_length>=self.#content_length)self.#state=2,socket.end()}return;default:break}},drain(socket){const self=socket.data;if(self.#state===0){const request=self.#data_buffer;if(request.length){const sended=socket.write(request);if(sended!==request.length)socket.data.#send_buffer=request.substring(sended);else socket.data.#send_buffer=\"\"}}},close:EventSource.#Close,end(socket){EventSource.#Close(socket).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Connection closed by server\")}))},timeout(socket){EventSource.#Close(socket).dispatchEvent(new ErrorEvent(\"error\",{error:new Error(\"Timeout\")}))},binaryType:\"buffer\"};static#Close(socket){const self=socket.data;if(self.#socket=null,self.#received_length=0,self.#state=2,self.#reconnect){if(self.#reconnection_timer)clearTimeout(self.#reconnection_timer);self.#reconnection_timer=setTimeout(EventSource.#ConnectNextTick,self.#reconnection_time,self)}return self}constructor(url,options=@undefined){super();const uri=new URL(url);this.#is_tls=uri.protocol===\"https:\",this.#url=uri,this.#state=2,process.nextTick(EventSource.#ConnectNextTick,this)}ref(){this.#reconnection_timer\?.ref(),this.#socket\?.ref()}unref(){this.#reconnection_timer\?.unref(),this.#socket\?.unref()}#connect(){if(this.#state!==2)return;const uri=this.#url,is_tls=this.#is_tls;this.#state=0,@Bun.connect({data:this,socket:EventSource.#Handlers,hostname:uri.hostname,port:parseInt(uri.port||(is_tls\?\"443\":\"80\"),10),tls:is_tls\?{requestCert:!0,rejectUnauthorized:!1}:!1}).catch((err)=>{if(super.dispatchEvent(new ErrorEvent(\"error\",{error:err})),this.#reconnect){if(this.#reconnection_timer)this.#reconnection_timer.unref\?.();this.#reconnection_timer=setTimeout(EventSource.#ConnectNextTick,1000,this)}})}get url(){return this.#url.href}get readyState(){return this.#state}close(){this.#reconnect=!1,this.#state=2,this.#socket\?.unref(),this.#socket\?.end()}get onopen(){return this.#onopen}get onerror(){return this.#onerror}get onmessage(){return this.#onmessage}set onopen(cb){if(this.#onopen)super.removeEventListener(\"close\",this.#onopen);super.addEventListener(\"open\",cb),this.#onopen=cb}set onerror(cb){if(this.#onerror)super.removeEventListener(\"error\",this.#onerror);super.addEventListener(\"error\",cb),this.#onerror=cb}set onmessage(cb){if(this.#onmessage)super.removeEventListener(\"message\",this.#onmessage);super.addEventListener(\"message\",cb),this.#onmessage=cb}}return Object.defineProperty(EventSource.prototype,\"CONNECTING\",{enumerable:!0,value:0}),Object.defineProperty(EventSource.prototype,\"OPEN\",{enumerable:!0,value:1}),Object.defineProperty(EventSource.prototype,\"CLOSED\",{enumerable:!0,value:2}),EventSource})\n"; #define DEFINE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM& vm) \ diff --git a/src/js/out/WebCoreJSBuiltins.h b/src/js/out/WebCoreJSBuiltins.h index 44e7023af8bebf..e540facb9f637a 100644 --- a/src/js/out/WebCoreJSBuiltins.h +++ b/src/js/out/WebCoreJSBuiltins.h @@ -1379,20 +1379,31 @@ extern const JSC::ConstructAbility s_moduleRequireResolveCodeConstructAbility; extern const JSC::ConstructorKind s_moduleRequireResolveCodeConstructorKind; extern const JSC::ImplementationVisibility s_moduleRequireResolveCodeImplementationVisibility; +// requireNativeModule +#define WEBCORE_BUILTIN_MODULE_REQUIRENATIVEMODULE 1 +extern const char* const s_moduleRequireNativeModuleCode; +extern const int s_moduleRequireNativeModuleCodeLength; +extern const JSC::ConstructAbility s_moduleRequireNativeModuleCodeConstructAbility; +extern const JSC::ConstructorKind s_moduleRequireNativeModuleCodeConstructorKind; +extern const JSC::ImplementationVisibility s_moduleRequireNativeModuleCodeImplementationVisibility; + #define WEBCORE_FOREACH_MODULE_BUILTIN_DATA(macro) \ macro(main, moduleMain, 0) \ macro(require, moduleRequire, 1) \ macro(requireResolve, moduleRequireResolve, 1) \ + macro(requireNativeModule, moduleRequireNativeModule, 1) \ #define WEBCORE_FOREACH_MODULE_BUILTIN_CODE(macro) \ macro(moduleMainCode, main, "get main"_s, s_moduleMainCodeLength) \ macro(moduleRequireCode, require, ASCIILiteral(), s_moduleRequireCodeLength) \ macro(moduleRequireResolveCode, requireResolve, ASCIILiteral(), s_moduleRequireResolveCodeLength) \ + macro(moduleRequireNativeModuleCode, requireNativeModule, ASCIILiteral(), s_moduleRequireNativeModuleCodeLength) \ #define WEBCORE_FOREACH_MODULE_BUILTIN_FUNCTION_NAME(macro) \ macro(main) \ macro(require) \ macro(requireResolve) \ + macro(requireNativeModule) \ #define DECLARE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM&); @@ -3396,95 +3407,6 @@ inline void TransformStreamDefaultControllerBuiltinsWrapper::exportNames() WEBCORE_FOREACH_TRANSFORMSTREAMDEFAULTCONTROLLER_BUILTIN_FUNCTION_NAME(EXPORT_FUNCTION_NAME) #undef EXPORT_FUNCTION_NAME } -/* AsyncContext.ts */ -// getAsyncContext -#define WEBCORE_BUILTIN_ASYNCCONTEXT_GETASYNCCONTEXT 1 -extern const char* const s_asyncContextGetAsyncContextCode; -extern const int s_asyncContextGetAsyncContextCodeLength; -extern const JSC::ConstructAbility s_asyncContextGetAsyncContextCodeConstructAbility; -extern const JSC::ConstructorKind s_asyncContextGetAsyncContextCodeConstructorKind; -extern const JSC::ImplementationVisibility s_asyncContextGetAsyncContextCodeImplementationVisibility; - -// setAsyncContext -#define WEBCORE_BUILTIN_ASYNCCONTEXT_SETASYNCCONTEXT 1 -extern const char* const s_asyncContextSetAsyncContextCode; -extern const int s_asyncContextSetAsyncContextCodeLength; -extern const JSC::ConstructAbility s_asyncContextSetAsyncContextCodeConstructAbility; -extern const JSC::ConstructorKind s_asyncContextSetAsyncContextCodeConstructorKind; -extern const JSC::ImplementationVisibility s_asyncContextSetAsyncContextCodeImplementationVisibility; - -#define WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_DATA(macro) \ - macro(getAsyncContext, asyncContextGetAsyncContext, 0) \ - macro(setAsyncContext, asyncContextSetAsyncContext, 1) \ - -#define WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_CODE(macro) \ - macro(asyncContextGetAsyncContextCode, getAsyncContext, ASCIILiteral(), s_asyncContextGetAsyncContextCodeLength) \ - macro(asyncContextSetAsyncContextCode, setAsyncContext, ASCIILiteral(), s_asyncContextSetAsyncContextCodeLength) \ - -#define WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_FUNCTION_NAME(macro) \ - macro(getAsyncContext) \ - macro(setAsyncContext) \ - -#define DECLARE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ - JSC::FunctionExecutable* codeName##Generator(JSC::VM&); - -WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_CODE(DECLARE_BUILTIN_GENERATOR) -#undef DECLARE_BUILTIN_GENERATOR - -class AsyncContextBuiltinsWrapper : private JSC::WeakHandleOwner { -public: - explicit AsyncContextBuiltinsWrapper(JSC::VM& vm) - : m_vm(vm) - WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_FUNCTION_NAME(INITIALIZE_BUILTIN_NAMES) -#define INITIALIZE_BUILTIN_SOURCE_MEMBERS(name, functionName, overriddenName, length) , m_##name##Source(JSC::makeSource(StringImpl::createWithoutCopying(s_##name, length), { })) - WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_CODE(INITIALIZE_BUILTIN_SOURCE_MEMBERS) -#undef INITIALIZE_BUILTIN_SOURCE_MEMBERS - { - } - -#define EXPOSE_BUILTIN_EXECUTABLES(name, functionName, overriddenName, length) \ - JSC::UnlinkedFunctionExecutable* name##Executable(); \ - const JSC::SourceCode& name##Source() const { return m_##name##Source; } - WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_CODE(EXPOSE_BUILTIN_EXECUTABLES) -#undef EXPOSE_BUILTIN_EXECUTABLES - - WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_FUNCTION_NAME(DECLARE_BUILTIN_IDENTIFIER_ACCESSOR) - - void exportNames(); - -private: - JSC::VM& m_vm; - - WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_FUNCTION_NAME(DECLARE_BUILTIN_NAMES) - -#define DECLARE_BUILTIN_SOURCE_MEMBERS(name, functionName, overriddenName, length) \ - JSC::SourceCode m_##name##Source;\ - JSC::Weak m_##name##Executable; - WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_CODE(DECLARE_BUILTIN_SOURCE_MEMBERS) -#undef DECLARE_BUILTIN_SOURCE_MEMBERS - -}; - -#define DEFINE_BUILTIN_EXECUTABLES(name, functionName, overriddenName, length) \ -inline JSC::UnlinkedFunctionExecutable* AsyncContextBuiltinsWrapper::name##Executable() \ -{\ - if (!m_##name##Executable) {\ - JSC::Identifier executableName = functionName##PublicName();\ - if (overriddenName)\ - executableName = JSC::Identifier::fromString(m_vm, overriddenName);\ - m_##name##Executable = JSC::Weak(JSC::createBuiltinExecutable(m_vm, m_##name##Source, executableName, s_##name##ImplementationVisibility, s_##name##ConstructorKind, s_##name##ConstructAbility), this, &m_##name##Executable);\ - }\ - return m_##name##Executable.get();\ -} -WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_CODE(DEFINE_BUILTIN_EXECUTABLES) -#undef DEFINE_BUILTIN_EXECUTABLES - -inline void AsyncContextBuiltinsWrapper::exportNames() -{ -#define EXPORT_FUNCTION_NAME(name) m_vm.propertyNames->appendExternalName(name##PublicName(), name##PrivateName()); - WEBCORE_FOREACH_ASYNCCONTEXT_BUILTIN_FUNCTION_NAME(EXPORT_FUNCTION_NAME) -#undef EXPORT_FUNCTION_NAME -} /* ReadableStreamBYOBReader.ts */ // initializeReadableStreamBYOBReader #define WEBCORE_BUILTIN_READABLESTREAMBYOBREADER_INITIALIZEREADABLESTREAMBYOBREADER 1 @@ -5694,7 +5616,6 @@ class JSBuiltinFunctions { , m_consoleObjectBuiltins(m_vm) , m_readableStreamInternalsBuiltins(m_vm) , m_transformStreamDefaultControllerBuiltins(m_vm) - , m_asyncContextBuiltins(m_vm) , m_readableStreamBYOBReaderBuiltins(m_vm) , m_jsBufferConstructorBuiltins(m_vm) , m_readableStreamDefaultReaderBuiltins(m_vm) @@ -5728,7 +5649,6 @@ class JSBuiltinFunctions { ConsoleObjectBuiltinsWrapper& consoleObjectBuiltins() { return m_consoleObjectBuiltins; } ReadableStreamInternalsBuiltinsWrapper& readableStreamInternalsBuiltins() { return m_readableStreamInternalsBuiltins; } TransformStreamDefaultControllerBuiltinsWrapper& transformStreamDefaultControllerBuiltins() { return m_transformStreamDefaultControllerBuiltins; } - AsyncContextBuiltinsWrapper& asyncContextBuiltins() { return m_asyncContextBuiltins; } ReadableStreamBYOBReaderBuiltinsWrapper& readableStreamBYOBReaderBuiltins() { return m_readableStreamBYOBReaderBuiltins; } JSBufferConstructorBuiltinsWrapper& jsBufferConstructorBuiltins() { return m_jsBufferConstructorBuiltins; } ReadableStreamDefaultReaderBuiltinsWrapper& readableStreamDefaultReaderBuiltins() { return m_readableStreamDefaultReaderBuiltins; } @@ -5757,7 +5677,6 @@ class JSBuiltinFunctions { ConsoleObjectBuiltinsWrapper m_consoleObjectBuiltins; ReadableStreamInternalsBuiltinsWrapper m_readableStreamInternalsBuiltins; TransformStreamDefaultControllerBuiltinsWrapper m_transformStreamDefaultControllerBuiltins; - AsyncContextBuiltinsWrapper m_asyncContextBuiltins; ReadableStreamBYOBReaderBuiltinsWrapper m_readableStreamBYOBReaderBuiltins; JSBufferConstructorBuiltinsWrapper m_jsBufferConstructorBuiltins; ReadableStreamDefaultReaderBuiltinsWrapper m_readableStreamDefaultReaderBuiltins; diff --git a/src/js/out/modules/bun/ffi.js b/src/js/out/modules/bun/ffi.js deleted file mode 100644 index c2c02ecb34e111..00000000000000 --- a/src/js/out/modules/bun/ffi.js +++ /dev/null @@ -1,268 +0,0 @@ -var cstringReturnType = function(val) { - return new __GlobalBunCString(val); -}, FFIBuilder = function(params, returnType, functionToCall, name) { - const hasReturnType = typeof FFIType[returnType] === "number" && FFIType[returnType] !== FFIType.void; - var paramNames = new Array(params.length), args = new Array(params.length); - for (let i = 0;i < params.length; i++) { - paramNames[i] = `p${i}`; - const wrapper = ffiWrappers[FFIType[params[i]]]; - if (wrapper) - args[i] = `(${wrapper.toString()})(p${i})`; - else - throw new TypeError(`Unsupported type ${params[i]}. Must be one of: ${Object.keys(FFIType).sort().join(", ")}`); - } - var code = `functionToCall(${args.join(", ")})`; - if (hasReturnType) - if (FFIType[returnType] === FFIType.cstring) - code = `return (${cstringReturnType.toString()})(${code})`; - else - code = `return ${code}`; - var func = new Function("functionToCall", ...paramNames, code); - Object.defineProperty(func, "name", { - value: name - }); - var wrap; - switch (paramNames.length) { - case 0: - wrap = () => func(functionToCall); - break; - case 1: - wrap = (arg1) => func(functionToCall, arg1); - break; - case 2: - wrap = (arg1, arg2) => func(functionToCall, arg1, arg2); - break; - case 3: - wrap = (arg1, arg2, arg3) => func(functionToCall, arg1, arg2, arg3); - break; - case 4: - wrap = (arg1, arg2, arg3, arg4) => func(functionToCall, arg1, arg2, arg3, arg4); - break; - case 5: - wrap = (arg1, arg2, arg3, arg4, arg5) => func(functionToCall, arg1, arg2, arg3, arg4, arg5); - break; - case 6: - wrap = (arg1, arg2, arg3, arg4, arg5, arg6) => func(functionToCall, arg1, arg2, arg3, arg4, arg5, arg6); - break; - case 7: - wrap = (arg1, arg2, arg3, arg4, arg5, arg6, arg7) => func(functionToCall, arg1, arg2, arg3, arg4, arg5, arg6, arg7); - break; - case 8: - wrap = (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) => func(functionToCall, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); - break; - case 9: - wrap = (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) => func(functionToCall, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); - break; - default: { - wrap = (...args2) => func(functionToCall, ...args2); - break; - } - } - return wrap.native = functionToCall, wrap.ptr = functionToCall.ptr, wrap; -}; -function dlopen(path, options) { - const result = nativeDLOpen(path, options); - for (let key in result.symbols) { - var symbol = result.symbols[key]; - if (options[key]?.args?.length || FFIType[options[key]?.returns] === FFIType.cstring) - result.symbols[key] = FFIBuilder(options[key].args ?? [], options[key].returns ?? FFIType.void, symbol, path.includes("/") ? `${key} (${path.split("/").pop()})` : `${key} (${path})`); - else - result.symbols[key].native = result.symbols[key]; - } - return result; -} -function linkSymbols(options) { - const result = nativeLinkSymbols(options); - for (let key in result.symbols) { - var symbol = result.symbols[key]; - if (options[key]?.args?.length || FFIType[options[key]?.returns] === FFIType.cstring) - result.symbols[key] = FFIBuilder(options[key].args ?? [], options[key].returns ?? FFIType.void, symbol, key); - else - result.symbols[key].native = result.symbols[key]; - } - return result; -} -var onCloseCFunction = function(close) { - close(); -}; -function CFunction(options) { - const identifier = `CFunction${cFunctionI++}`; - var result = linkSymbols({ - [identifier]: options - }), hasClosed = !1, close = result.close; - return result.symbols[identifier].close = () => { - if (hasClosed || !close) - return; - hasClosed = !0, close(), close = void 0; - }, cFunctionRegistry ||= new FinalizationRegistry(onCloseCFunction), cFunctionRegistry.register(result.symbols[identifier], result.symbols[identifier].close), result.symbols[identifier]; -} -var ffi = globalThis.Bun.FFI, ptr = (arg1, arg2) => typeof arg2 === "undefined" ? ffi.ptr(arg1) : ffi.ptr(arg1, arg2), toBuffer = ffi.toBuffer, toArrayBuffer = ffi.toArrayBuffer, viewSource = ffi.viewSource, BunCString = ffi.CString, nativeLinkSymbols = ffi.linkSymbols, nativeDLOpen = ffi.dlopen, nativeCallback = ffi.callback, closeCallback = ffi.closeCallback; -delete ffi.callback; -delete ffi.closeCallback; - -class JSCallback { - constructor(cb, options) { - const { ctx, ptr: ptr2 } = nativeCallback(options, cb); - this.#ctx = ctx, this.ptr = ptr2, this.#threadsafe = !!options?.threadsafe; - } - ptr; - #ctx; - #threadsafe; - get threadsafe() { - return this.#threadsafe; - } - [Symbol.toPrimitive]() { - const { ptr: ptr2 } = this; - return typeof ptr2 === "number" ? ptr2 : 0; - } - close() { - const ctx = this.#ctx; - if (this.ptr = null, this.#ctx = null, ctx) - closeCallback(ctx); - } -} - -class CString extends String { - constructor(ptr2, byteOffset, byteLength) { - super(ptr2 ? typeof byteLength === "number" && Number.isSafeInteger(byteLength) ? new BunCString(ptr2, byteOffset || 0, byteLength) : new BunCString(ptr2) : ""); - if (this.ptr = typeof ptr2 === "number" ? ptr2 : 0, typeof byteOffset !== "undefined") - this.byteOffset = byteOffset; - if (typeof byteLength !== "undefined") - this.byteLength = byteLength; - } - ptr; - byteOffset; - byteLength; - #cachedArrayBuffer; - get arrayBuffer() { - if (this.#cachedArrayBuffer) - return this.#cachedArrayBuffer; - if (!this.ptr) - return this.#cachedArrayBuffer = new ArrayBuffer(0); - return this.#cachedArrayBuffer = toArrayBuffer(this.ptr, this.byteOffset, this.byteLength); - } -} -Object.defineProperty(globalThis, "__GlobalBunCString", { - value: CString, - enumerable: !1, - configurable: !1 -}); -var ffiWrappers = new Array(18), char = (val) => val | 0; -ffiWrappers.fill(char); -ffiWrappers[FFIType.uint8_t] = function uint8(val) { - return val < 0 ? 0 : val >= 255 ? 255 : val | 0; -}; -ffiWrappers[FFIType.int16_t] = function int16(val) { - return val <= -32768 ? -32768 : val >= 32768 ? 32768 : val | 0; -}; -ffiWrappers[FFIType.uint16_t] = function uint16(val) { - return val <= 0 ? 0 : val >= 65536 ? 65536 : val | 0; -}; -ffiWrappers[FFIType.int32_t] = function int32(val) { - return val | 0; -}; -ffiWrappers[FFIType.uint32_t] = function uint32(val) { - return val <= 0 ? 0 : val >= 4294967295 ? 4294967295 : +val || 0; -}; -ffiWrappers[FFIType.i64_fast] = function int64(val) { - if (typeof val === "bigint") { - if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(-Number.MAX_SAFE_INTEGER)) - return Number(val).valueOf() || 0; - return val; - } - return !val ? 0 : +val || 0; -}; -ffiWrappers[FFIType.u64_fast] = function u64_fast(val) { - if (typeof val === "bigint") { - if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= 0) - return Number(val).valueOf() || 0; - return val; - } - return !val ? 0 : +val || 0; -}; -ffiWrappers[FFIType.int64_t] = function int642(val) { - if (typeof val === "bigint") - return val; - if (typeof val === "number") - return BigInt(val || 0); - return BigInt(+val || 0); -}; -ffiWrappers[FFIType.uint64_t] = function uint64(val) { - if (typeof val === "bigint") - return val; - if (typeof val === "number") - return val <= 0 ? BigInt(0) : BigInt(val || 0); - return BigInt(+val || 0); -}; -ffiWrappers[FFIType.u64_fast] = function u64_fast2(val) { - if (typeof val === "bigint") { - if (val <= BigInt(Number.MAX_SAFE_INTEGER) && val >= BigInt(0)) - return Number(val); - return val; - } - return typeof val === "number" ? val <= 0 ? 0 : +val || 0 : +val || 0; -}; -ffiWrappers[FFIType.uint16_t] = function uint162(val) { - const ret = (typeof val === "bigint" ? Number(val) : val) | 0; - return ret <= 0 ? 0 : ret > 65535 ? 65535 : ret; -}; -ffiWrappers[FFIType.double] = function double(val) { - if (typeof val === "bigint") { - if (val.valueOf() < BigInt(Number.MAX_VALUE)) - return Math.abs(Number(val).valueOf()) + 0.00000000000001 - 0.00000000000001; - } - if (!val) - return 0; - return val + 0.00000000000001 - 0.00000000000001; -}; -ffiWrappers[FFIType.float] = ffiWrappers[10] = function float(val) { - return Math.fround(val); -}; -ffiWrappers[FFIType.bool] = function bool(val) { - return !!val; -}; -Object.defineProperty(globalThis, "__GlobalBunFFIPtrFunctionForWrapper", { - value: ptr, - enumerable: !1, - configurable: !0 -}); -ffiWrappers[FFIType.cstring] = ffiWrappers[FFIType.pointer] = function pointer(val) { - if (typeof val === "number") - return val; - if (!val) - return null; - if (ArrayBuffer.isView(val) || val instanceof ArrayBuffer) - return __GlobalBunFFIPtrFunctionForWrapper(val); - if (typeof val === "string") - throw new TypeError("To convert a string to a pointer, encode it as a buffer"); - throw new TypeError(`Unable to convert ${val} to a pointer`); -}; -ffiWrappers[FFIType.function] = function functionType(val) { - if (typeof val === "number") - return val; - if (typeof val === "bigint") - return Number(val); - var ptr2 = val && val.ptr; - if (!ptr2) - throw new TypeError("Expected function to be a JSCallback or a number"); - return ptr2; -}; -var native = { - dlopen: nativeDLOpen, - callback: () => { - throw new Error("Deprecated. Use new JSCallback(options, fn) instead"); - } -}, cFunctionI = 0, cFunctionRegistry, read = ffi.read; -export { - viewSource, - toBuffer, - toArrayBuffer, - read, - ptr, - native, - linkSymbols, - dlopen, - JSCallback, - CString, - CFunction -}; diff --git a/src/js/out/modules/bun/jsc.js b/src/js/out/modules/bun/jsc.js deleted file mode 100644 index 45fb51bddfe35d..00000000000000 --- a/src/js/out/modules/bun/jsc.js +++ /dev/null @@ -1,37 +0,0 @@ -var jsc = globalThis[Symbol.for("Bun.lazy")]("bun:jsc"), callerSourceOrigin = jsc.callerSourceOrigin, jscDescribe = jsc.describe, jscDescribeArray = jsc.describeArray, describe = jscDescribe, describeArray = jscDescribeArray, drainMicrotasks = jsc.drainMicrotasks, edenGC = jsc.edenGC, fullGC = jsc.fullGC, gcAndSweep = jsc.gcAndSweep, getRandomSeed = jsc.getRandomSeed, heapSize = jsc.heapSize, heapStats = jsc.heapStats, startSamplingProfiler = jsc.startSamplingProfiler, samplingProfilerStackTraces = jsc.samplingProfilerStackTraces, isRope = jsc.isRope, memoryUsage = jsc.memoryUsage, noInline = jsc.noInline, noFTL = jsc.noFTL, noOSRExitFuzzing = jsc.noOSRExitFuzzing, numberOfDFGCompiles = jsc.numberOfDFGCompiles, optimizeNextInvocation = jsc.optimizeNextInvocation, releaseWeakRefs = jsc.releaseWeakRefs, reoptimizationRetryCount = jsc.reoptimizationRetryCount, setRandomSeed = jsc.setRandomSeed, startRemoteDebugger = jsc.startRemoteDebugger, totalCompileTime = jsc.totalCompileTime, getProtectedObjects = jsc.getProtectedObjects, generateHeapSnapshotForDebugging = jsc.generateHeapSnapshotForDebugging, profile = jsc.profile, jsc_default = jsc, setTimeZone = jsc.setTimeZone, setTimezone = setTimeZone, serialize = jsc.serialize, deserialize = jsc.deserialize; -export { - totalCompileTime, - startSamplingProfiler, - startRemoteDebugger, - setTimezone, - setTimeZone, - setRandomSeed, - serialize, - samplingProfilerStackTraces, - reoptimizationRetryCount, - releaseWeakRefs, - profile, - optimizeNextInvocation, - numberOfDFGCompiles, - noOSRExitFuzzing, - noInline, - noFTL, - memoryUsage, - jscDescribeArray, - jscDescribe, - isRope, - heapStats, - heapSize, - getRandomSeed, - getProtectedObjects, - generateHeapSnapshotForDebugging, - gcAndSweep, - fullGC, - edenGC, - drainMicrotasks, - deserialize, - describeArray, - describe, - jsc_default as default, - callerSourceOrigin -}; diff --git a/src/js/out/modules/bun/sqlite.js b/src/js/out/modules/bun/sqlite.js deleted file mode 100644 index d0eace29017291..00000000000000 --- a/src/js/out/modules/bun/sqlite.js +++ /dev/null @@ -1,278 +0,0 @@ -var lazy = globalThis[Symbol.for("Bun.lazy")], defineProperties = Object.defineProperties, toStringTag = Symbol.toStringTag, apply = Function.prototype.apply, isArray = Array.isArray, isTypedArray = ArrayBuffer.isView, constants = { - SQLITE_OPEN_READONLY: 1, - SQLITE_OPEN_READWRITE: 2, - SQLITE_OPEN_CREATE: 4, - SQLITE_OPEN_DELETEONCLOSE: 8, - SQLITE_OPEN_EXCLUSIVE: 16, - SQLITE_OPEN_AUTOPROXY: 32, - SQLITE_OPEN_URI: 64, - SQLITE_OPEN_MEMORY: 128, - SQLITE_OPEN_MAIN_DB: 256, - SQLITE_OPEN_TEMP_DB: 512, - SQLITE_OPEN_TRANSIENT_DB: 1024, - SQLITE_OPEN_MAIN_JOURNAL: 2048, - SQLITE_OPEN_TEMP_JOURNAL: 4096, - SQLITE_OPEN_SUBJOURNAL: 8192, - SQLITE_OPEN_SUPER_JOURNAL: 16384, - SQLITE_OPEN_NOMUTEX: 32768, - SQLITE_OPEN_FULLMUTEX: 65536, - SQLITE_OPEN_SHAREDCACHE: 131072, - SQLITE_OPEN_PRIVATECACHE: 262144, - SQLITE_OPEN_WAL: 524288, - SQLITE_OPEN_NOFOLLOW: 16777216, - SQLITE_OPEN_EXRESCODE: 33554432, - SQLITE_PREPARE_PERSISTENT: 1, - SQLITE_PREPARE_NORMALIZE: 2, - SQLITE_PREPARE_NO_VTAB: 4 -}, SQL, _SQL, controllers; - -class Statement { - constructor(raw) { - switch (this.#raw = raw, raw.paramsCount) { - case 0: { - this.get = this.#getNoArgs, this.all = this.#allNoArgs, this.values = this.#valuesNoArgs, this.run = this.#runNoArgs; - break; - } - default: { - this.get = this.#get, this.all = this.#all, this.values = this.#values, this.run = this.#run; - break; - } - } - } - #raw; - get; - all; - values; - run; - isFinalized = !1; - toJSON() { - return { - sql: this.native.toString(), - isFinalized: this.isFinalized, - paramsCount: this.paramsCount, - columnNames: this.columnNames - }; - } - get [toStringTag]() { - return `"${this.native.toString()}"`; - } - toString() { - return this.native.toString(); - } - get native() { - return this.#raw; - } - #getNoArgs() { - return this.#raw.get(); - } - #allNoArgs() { - return this.#raw.all(); - } - #valuesNoArgs() { - return this.#raw.values(); - } - #runNoArgs() { - this.#raw.run(); - } - #get(...args) { - if (args.length === 0) - return this.#getNoArgs(); - var arg0 = args[0]; - return !isArray(arg0) && (!arg0 || typeof arg0 !== "object" || isTypedArray(arg0)) ? this.#raw.get(args) : this.#raw.get(...args); - } - #all(...args) { - if (args.length === 0) - return this.#allNoArgs(); - var arg0 = args[0]; - return !isArray(arg0) && (!arg0 || typeof arg0 !== "object" || isTypedArray(arg0)) ? this.#raw.all(args) : this.#raw.all(...args); - } - #values(...args) { - if (args.length === 0) - return this.#valuesNoArgs(); - var arg0 = args[0]; - return !isArray(arg0) && (!arg0 || typeof arg0 !== "object" || isTypedArray(arg0)) ? this.#raw.values(args) : this.#raw.values(...args); - } - #run(...args) { - if (args.length === 0) - return this.#runNoArgs(); - var arg0 = args[0]; - !isArray(arg0) && (!arg0 || typeof arg0 !== "object" || isTypedArray(arg0)) ? this.#raw.run(args) : this.#raw.run(...args); - } - get columnNames() { - return this.#raw.columns; - } - get paramsCount() { - return this.#raw.paramsCount; - } - finalize(...args) { - return this.isFinalized = !0, this.#raw.finalize(...args); - } -} -var cachedCount = Symbol.for("Bun.Database.cache.count"); - -class Database { - constructor(filenameGiven, options) { - if (typeof filenameGiven === "undefined") - ; - else if (typeof filenameGiven !== "string") { - if (isTypedArray(filenameGiven)) { - this.#handle = Database.deserialize(filenameGiven, typeof options === "object" && options ? !!options.readonly : ((options | 0) & constants.SQLITE_OPEN_READONLY) != 0), this.filename = ":memory:"; - return; - } - throw new TypeError(`Expected 'filename' to be a string, got '${typeof filenameGiven}'`); - } - var filename = typeof filenameGiven === "string" ? filenameGiven.trim() : ":memory:", flags = constants.SQLITE_OPEN_READWRITE | constants.SQLITE_OPEN_CREATE; - if (typeof options === "object" && options) { - if (flags = 0, options.readonly) - flags = constants.SQLITE_OPEN_READONLY; - if ("readOnly" in options) - throw new TypeError('Misspelled option "readOnly" should be "readonly"'); - if (options.create) - flags = constants.SQLITE_OPEN_READWRITE | constants.SQLITE_OPEN_CREATE; - if (options.readwrite) - flags |= constants.SQLITE_OPEN_READWRITE; - } else if (typeof options === "number") - flags = options; - const anonymous = filename === "" || filename === ":memory:"; - if (anonymous && (flags & constants.SQLITE_OPEN_READONLY) !== 0) - throw new Error("Cannot open an anonymous database in read-only mode."); - if (!SQL) - _SQL = SQL = lazy("sqlite"); - this.#handle = SQL.open(anonymous ? ":memory:" : filename, flags), this.filename = filename; - } - #handle; - #cachedQueriesKeys = []; - #cachedQueriesLengths = []; - #cachedQueriesValues = []; - filename; - get handle() { - return this.#handle; - } - get inTransaction() { - return SQL.isInTransaction(this.#handle); - } - static open(filename, options) { - return new Database(filename, options); - } - loadExtension(name, entryPoint) { - return SQL.loadExtension(this.#handle, name, entryPoint); - } - serialize(optionalName) { - return SQL.serialize(this.#handle, optionalName || "main"); - } - static deserialize(serialized, isReadOnly = !1) { - if (!SQL) - _SQL = SQL = lazy("sqlite"); - return SQL.deserialize(serialized, isReadOnly); - } - static setCustomSQLite(path) { - if (!SQL) - _SQL = SQL = lazy("sqlite"); - return SQL.setCustomSQLite(path); - } - close() { - return this.clearQueryCache(), SQL.close(this.#handle); - } - clearQueryCache() { - for (let item of this.#cachedQueriesValues) - item.finalize(); - this.#cachedQueriesKeys.length = 0, this.#cachedQueriesValues.length = 0, this.#cachedQueriesLengths.length = 0; - } - run(query, ...params) { - if (params.length === 0) { - SQL.run(this.#handle, query); - return; - } - var arg0 = params[0]; - return !isArray(arg0) && (!arg0 || typeof arg0 !== "object" || isTypedArray(arg0)) ? SQL.run(this.#handle, query, params) : SQL.run(this.#handle, query, ...params); - } - prepare(query, params, flags) { - return new Statement(SQL.prepare(this.#handle, query, params, flags || 0)); - } - static MAX_QUERY_CACHE_SIZE = 20; - get [cachedCount]() { - return this.#cachedQueriesKeys.length; - } - query(query) { - if (typeof query !== "string") - throw new TypeError(`Expected 'query' to be a string, got '${typeof query}'`); - if (query.length === 0) - throw new Error("SQL query cannot be empty."); - var index = this.#cachedQueriesLengths.indexOf(query.length); - while (index !== -1) { - if (this.#cachedQueriesKeys[index] !== query) { - index = this.#cachedQueriesLengths.indexOf(query.length, index + 1); - continue; - } - var stmt = this.#cachedQueriesValues[index]; - if (stmt.isFinalized) - return this.#cachedQueriesValues[index] = this.prepare(query, void 0, willCache ? constants.SQLITE_PREPARE_PERSISTENT : 0); - return stmt; - } - const willCache = this.#cachedQueriesKeys.length < Database.MAX_QUERY_CACHE_SIZE; - var stmt = this.prepare(query, void 0, willCache ? constants.SQLITE_PREPARE_PERSISTENT : 0); - if (willCache) - this.#cachedQueriesKeys.push(query), this.#cachedQueriesLengths.push(query.length), this.#cachedQueriesValues.push(stmt); - return stmt; - } - transaction(fn, self) { - if (typeof fn !== "function") - throw new TypeError("Expected first argument to be a function"); - const db = this, controller = getController(db, self), properties = { - default: { value: wrapTransaction(fn, db, controller.default) }, - deferred: { value: wrapTransaction(fn, db, controller.deferred) }, - immediate: { - value: wrapTransaction(fn, db, controller.immediate) - }, - exclusive: { - value: wrapTransaction(fn, db, controller.exclusive) - }, - database: { value: this, enumerable: !0 } - }; - return defineProperties(properties.default.value, properties), defineProperties(properties.deferred.value, properties), defineProperties(properties.immediate.value, properties), defineProperties(properties.exclusive.value, properties), properties.default.value; - } -} -Database.prototype.exec = Database.prototype.run; -var getController = (db, self) => { - let controller = (controllers ||= new WeakMap).get(db); - if (!controller) { - const shared = { - commit: db.prepare("COMMIT", void 0, 0), - rollback: db.prepare("ROLLBACK", void 0, 0), - savepoint: db.prepare("SAVEPOINT `\t_bs3.\t`", void 0, 0), - release: db.prepare("RELEASE `\t_bs3.\t`", void 0, 0), - rollbackTo: db.prepare("ROLLBACK TO `\t_bs3.\t`", void 0, 0) - }; - controllers.set(db, controller = { - default: Object.assign({ begin: db.prepare("BEGIN", void 0, 0) }, shared), - deferred: Object.assign({ begin: db.prepare("BEGIN DEFERRED", void 0, 0) }, shared), - immediate: Object.assign({ begin: db.prepare("BEGIN IMMEDIATE", void 0, 0) }, shared), - exclusive: Object.assign({ begin: db.prepare("BEGIN EXCLUSIVE", void 0, 0) }, shared) - }); - } - return controller; -}, wrapTransaction = (fn, db, { begin, commit, rollback, savepoint, release, rollbackTo }) => function transaction(...args) { - let before, after, undo; - if (db.inTransaction) - before = savepoint, after = release, undo = rollbackTo; - else - before = begin, after = commit, undo = rollback; - try { - before.run(); - const result = fn.apply(this, args); - return after.run(), result; - } catch (ex) { - if (db.inTransaction) { - if (undo.run(), undo !== rollback) - after.run(); - } - throw ex; - } -}; -export { - _SQL as native, - Database as default, - constants, - Statement, - Database -}; diff --git a/src/js/out/modules/bun/wasi-runner.js b/src/js/out/modules/bun/wasi-runner.js deleted file mode 100644 index 47c5ade3c2eda9..00000000000000 --- a/src/js/out/modules/bun/wasi-runner.js +++ /dev/null @@ -1,26 +0,0 @@ -var filePath = process.argv.at(1); -if (!filePath) - throw err = new Error("To run a wasm file with Bun, the first argument must be a path to a .wasm file"), err.name = "WasmFileNotFound", err; -var err, { - WASM_CWD = process.cwd(), - WASM_ROOT_DIR = "/", - WASM_ENV_STR = void 0, - WASM_USE_ASYNC_INIT = "1" -} = process.env, env = process.env; -if (WASM_ENV_STR?.length) - env = JSON.parse(WASM_ENV_STR); -var wasi = new WASI({ - args: process.argv.slice(1), - env, - preopens: { - ".": WASM_CWD || process.cwd(), - "/": WASM_ROOT_DIR || "/" - } -}), source = globalThis.wasmSourceBytes; -if (!source) { - const fs = Bun.fs(), file = import.meta.path; - source = fs.readFileSync(file); -} -var wasm = await WebAssembly.compile(source), instance = !Number(WASM_USE_ASYNC_INIT) ? new WebAssembly.Instance(wasm, wasi.getImports(wasm)) : await WebAssembly.instantiate(wasm, wasi.getImports(wasm)); -wasi.start(instance); -process.reallyExit(0); diff --git a/src/js/out/modules/node/assert.js b/src/js/out/modules/node/assert.js deleted file mode 100644 index 3067445ce96877..00000000000000 --- a/src/js/out/modules/node/assert.js +++ /dev/null @@ -1,53 +0,0 @@ -var D0=(g)=>{return import.meta.require(g)};import J0 from"node:util";var V0=function(){throw new Error("CallTracker is not supported yet")},{Bun:U0}=globalThis[Symbol.for("Bun.lazy")]("primordials"),t=U0.deepEquals,X0=(g,L)=>function(){return L||(0,g[Object.keys(g)[0]])((L={exports:{}}).exports,L),L.exports},$0=X0({"assert/build/internal/errors.js"(g,L){function A(U){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?A=function(X){return typeof X}:A=function(X){return X&&typeof Symbol=="function"&&X.constructor===Symbol&&X!==Symbol.prototype?"symbol":typeof X},A(U)}function i(U,X){if(!(U instanceof X))throw new TypeError("Cannot call a class as a function")}function l(U,X){return X&&(A(X)==="object"||typeof X=="function")?X:b(U)}function b(U){if(U===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return U}function x(U){return x=Object.setPrototypeOf?Object.getPrototypeOf:function(X){return X.__proto__||Object.getPrototypeOf(X)},x(U)}function I(U,X){if(typeof X!="function"&&X!==null)throw new TypeError("Super expression must either be null or a function");U.prototype=Object.create(X&&X.prototype,{constructor:{value:U,writable:!0,configurable:!0}}),X&&m(U,X)}function m(U,X){return m=Object.setPrototypeOf||function(D,v){return D.__proto__=v,D},m(U,X)}var n={},N,C;function j(U,X,D){D||(D=Error);function v(T,G,f){return typeof X=="string"?X:X(T,G,f)}var M=function(T){I(G,T);function G(f,O,S){var y;return i(this,G),y=l(this,x(G).call(this,v(f,O,S))),y.code=U,y}return G}(D);n[U]=M}function p(U,X){if(Array.isArray(U)){var D=U.length;return U=U.map(function(v){return String(v)}),D>2?"one of ".concat(X," ").concat(U.slice(0,D-1).join(", "),", or ")+U[D-1]:D===2?"one of ".concat(X," ").concat(U[0]," or ").concat(U[1]):"of ".concat(X," ").concat(U[0])}else return"of ".concat(X," ").concat(String(U))}function h(U,X,D){return U.substr(!D||D<0?0:+D,X.length)===X}function R(U,X,D){return(D===void 0||D>U.length)&&(D=U.length),U.substring(D-X.length,D)===X}function P(U,X,D){return typeof D!="number"&&(D=0),D+X.length>U.length?!1:U.indexOf(X,D)!==-1}j("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),j("ERR_INVALID_ARG_TYPE",function(U,X,D){N===void 0&&(N=z0()),N(typeof U=="string","'name' must be a string");var v;typeof X=="string"&&h(X,"not ")?(v="must not be",X=X.replace(/^not /,"")):v="must be";var M;if(R(U," argument"))M="The ".concat(U," ").concat(v," ").concat(p(X,"type"));else{var T=P(U,".")?"property":"argument";M='The "'.concat(U,'" ').concat(T," ").concat(v," ").concat(p(X,"type"))}return M+=". Received type ".concat(A(D)),M},TypeError),j("ERR_INVALID_ARG_VALUE",function(U,X){var D=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"is invalid",v=C.inspect(X);return v.length>128&&(v="".concat(v.slice(0,128),"...")),"The argument '".concat(U,"' ").concat(D,". Received ").concat(v)},TypeError,RangeError),j("ERR_INVALID_RETURN_VALUE",function(U,X,D){var v;return D&&D.constructor&&D.constructor.name?v="instance of ".concat(D.constructor.name):v="type ".concat(A(D)),"Expected ".concat(U,' to be returned from the "').concat(X,'"')+" function but got ".concat(v,".")},TypeError),j("ERR_MISSING_ARGS",function(){for(var U=arguments.length,X=new Array(U),D=0;D0,"At least one arg needs to be specified");var v="The ",M=X.length;switch(X=X.map(function(T){return'"'.concat(T,'"')}),M){case 1:v+="".concat(X[0]," argument");break;case 2:v+="".concat(X[0]," and ").concat(X[1]," arguments");break;default:v+=X.slice(0,M-1).join(", "),v+=", and ".concat(X[M-1]," arguments");break}return"".concat(v," must be specified")},TypeError),L.exports.codes=n}}),B0=X0({"assert/build/internal/assert/assertion_error.js"(g,L){function A(Y){for(var J=1;JY.length)&&($=Y.length),Y.substring($-J.length,$)===J}function M(Y,J){if(J=Math.floor(J),Y.length==0||J==0)return"";var $=Y.length*J;for(J=Math.floor(Math.log(J)/Math.log(2));J;)Y+=Y,J--;return Y+=Y.substring(0,$-Y.length),Y}var T="",G="",f="",O="",S={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"},y=10;function c(Y){var J=Object.keys(Y),$=Object.create(Object.getPrototypeOf(Y));return J.forEach(function(V){$[V]=Y[V]}),Object.defineProperty($,"message",{value:Y.message}),$}function d(Y){return U(Y,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:Infinity,showHidden:!1,breakLength:Infinity,showProxy:!1,sorted:!0,getters:!0})}function s(Y,J,$){var V="",q="",Z=0,H="",Q=!1,z=d(Y),K=z.split(` -`),W=d(J).split(` -`),B=0,w="";if($==="strictEqual"&&P(Y)==="object"&&P(J)==="object"&&Y!==null&&J!==null&&($="strictEqualObject"),K.length===1&&W.length===1&&K[0]!==W[0]){var F=K[0].length+W[0].length;if(F<=y){if((P(Y)!=="object"||Y===null)&&(P(J)!=="object"||J===null)&&(Y!==0||J!==0))return"".concat(S[$],` - -`)+"".concat(K[0]," !== ").concat(W[0],` -`)}else if($!=="strictEqualObject"){var _=process.stderr&&process.stderr.isTTY?process.stderr.columns:80;if(F<_){for(;K[0][B]===W[0][B];)B++;B>2&&(w=` - `.concat(M(" ",B),"^"),B=0)}}}for(var e=K[K.length-1],Y0=W[W.length-1];e===Y0&&(B++<2?H=` - `.concat(e).concat(H):V=e,K.pop(),W.pop(),!(K.length===0||W.length===0));)e=K[K.length-1],Y0=W[W.length-1];var Q0=Math.max(K.length,W.length);if(Q0===0){var o=z.split(` -`);if(o.length>30)for(o[26]="".concat(T,"...").concat(O);o.length>27;)o.pop();return"".concat(S.notIdentical,` - -`).concat(o.join(` -`),` -`)}B>3&&(H=` -`.concat(T,"...").concat(O).concat(H),Q=!0),V!==""&&(H=` - `.concat(V).concat(H),V="");var E=0,K0=S[$]+` -`.concat(G,"+ actual").concat(O," ").concat(f,"- expected").concat(O),W0=" ".concat(T,"...").concat(O," Lines skipped");for(B=0;B1&&B>2&&(k>4?(q+=` -`.concat(T,"...").concat(O),Q=!0):k>3&&(q+=` - `.concat(W[B-2]),E++),q+=` - `.concat(W[B-1]),E++),Z=B,V+=` -`.concat(f,"-").concat(O," ").concat(W[B]),E++;else if(W.length1&&B>2&&(k>4?(q+=` -`.concat(T,"...").concat(O),Q=!0):k>3&&(q+=` - `.concat(K[B-2]),E++),q+=` - `.concat(K[B-1]),E++),Z=B,q+=` -`.concat(G,"+").concat(O," ").concat(K[B]),E++;else{var a=W[B],u=K[B],Z0=u!==a&&(!v(u,",")||u.slice(0,-1)!==a);Z0&&v(a,",")&&a.slice(0,-1)===u&&(Z0=!1,u+=","),Z0?(k>1&&B>2&&(k>4?(q+=` -`.concat(T,"...").concat(O),Q=!0):k>3&&(q+=` - `.concat(K[B-2]),E++),q+=` - `.concat(K[B-1]),E++),Z=B,q+=` -`.concat(G,"+").concat(O," ").concat(u),V+=` -`.concat(f,"-").concat(O," ").concat(a),E+=2):(q+=V,V="",(k===1||B===0)&&(q+=` - `.concat(u),E++))}if(E>20&&B30)for(B[26]="".concat(T,"...").concat(O);B.length>27;)B.pop();B.length===1?V=I(this,R(J).call(this,"".concat(W," ").concat(B[0]))):V=I(this,R(J).call(this,"".concat(W,` - -`).concat(B.join(` -`),` -`)))}else{var w=d(Q),F="",_=S[Z];Z==="notDeepEqual"||Z==="notEqual"?(w="".concat(S[Z],` - -`).concat(w),w.length>1024&&(w="".concat(w.slice(0,1021),"..."))):(F="".concat(d(z)),w.length>512&&(w="".concat(w.slice(0,509),"...")),F.length>512&&(F="".concat(F.slice(0,509),"...")),Z==="deepEqual"||Z==="equal"?w="".concat(_,` - -`).concat(w,` - -should equal - -`):F=" ".concat(Z," ").concat(F)),V=I(this,R(J).call(this,"".concat(w).concat(F)))}return Error.stackTraceLimit=K,V.generatedMessage=!q,Object.defineProperty(m(V),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),V.code="ERR_ASSERTION",V.actual=Q,V.expected=z,V.operator=Z,Error.captureStackTrace&&Error.captureStackTrace(m(V),H),V.stack,V.name="AssertionError",I(V)}return x(J,[{key:"toString",value:function(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:U.custom,value:function($,V){return U(this,A({},V,{customInspect:!1,depth:0}))}}]),J}(N(Error));L.exports=r}}),z0=X0({"assert/build/assert.js"(g,L){function A(Z){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?A=function(H){return typeof H}:A=function(H){return H&&typeof Symbol=="function"&&H.constructor===Symbol&&H!==Symbol.prototype?"symbol":typeof H},A(Z)}function i(Z,H){if(!(Z instanceof H))throw new TypeError("Cannot call a class as a function")}var l=$0(),b=l.codes,x=b.ERR_AMBIGUOUS_ARGUMENT,I=b.ERR_INVALID_ARG_TYPE,m=b.ERR_INVALID_ARG_VALUE,n=b.ERR_INVALID_RETURN_VALUE,N=b.ERR_MISSING_ARGS,C=B0(),j=J0,p=j.inspect,h=J0.types,R=h.isPromise,P=h.isRegExp,U=Object.assign,X=Object.is,D=new Map,v=!1,M=L.exports=S,T={};function G(Z){throw Z.message instanceof Error?Z.message:new C(Z)}function f(Z,H,Q,z,K){var W=arguments.length,B;if(W===0)B="Failed";else if(W===1)Q=Z,Z=void 0;else{if(v===!1){v=!0;var w=process.emitWarning?process.emitWarning:console.warn.bind(console);w("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.","DeprecationWarning","DEP0094")}W===2&&(z="!=")}if(Q instanceof Error)throw Q;var F={actual:Z,expected:H,operator:z===void 0?"fail":z,stackStartFn:K||f};Q!==void 0&&(F.message=Q);var _=new C(F);throw B&&(_.message=B,_.generatedMessage=!0),_}M.fail=f,M.AssertionError=C;function O(Z,H,Q,z){if(!Q){var K=!1;if(H===0)K=!0,z="No value argument passed to `assert.ok()`";else if(z instanceof Error)throw z;var W=new C({actual:Q,expected:!0,message:z,operator:"==",stackStartFn:Z});throw W.generatedMessage=K,W}}function S(){for(var Z=arguments.length,H=new Array(Z),Q=0;Q1?Q-1:0),K=1;K1?Q-1:0),K=1;K1?Q-1:0),K=1;K1?Q-1:0),K=1;K { - var prev = get(); - set(context); - try { - return fn(...args); - } catch (error) { - throw error; - } finally { - set(prev); - } - }; - } - enterWith(store) { - cleanupLater(); - var context = get(); - if (!context) { - set([this, store]); - return; - } - var { length } = context; - for (var i = 0;i < length; i += 2) - if (context[i] === this) { - const clone = context.slice(); - clone[i + 1] = store, set(clone); - return; - } - set(context.concat(this, store)); - } - exit(cb, ...args) { - return this.run(void 0, cb, ...args); - } - run(store, callback, ...args) { - var context = get(), hasPrevious = !1, previous, i = 0, contextWasInit = !context; - if (contextWasInit) - set(context = [this, store]); - else { - if (context = context.slice(), i = context.indexOf(this), i > -1) - hasPrevious = !0, previous = context[i + 1], context[i + 1] = store; - else - context.push(this, store); - set(context); - } - try { - return callback(...args); - } catch (e) { - throw e; - } finally { - if (!this.#disableCalled) { - var context2 = get(); - if (context2 === context && contextWasInit) - set(void 0); - else if (context2 = context2.slice(), hasPrevious) - context2[i + 1] = previous, set(context2); - else - context2.splice(i, 2), set(context2.length ? context2 : void 0); - } - } - } - disable() { - if (!this.#disableCalled) { - var context = get(); - if (context) { - var { length } = context; - for (var i = 0;i < length; i += 2) - if (context[i] === this) { - context.splice(i, 2), set(context.length ? context : void 0); - break; - } - } - this.#disableCalled = !0; - } - } - getStore() { - var context = get(); - if (!context) - return; - var { length } = context; - for (var i = 0;i < length; i += 2) - if (context[i] === this) - return context[i + 1]; - } -} - -class AsyncResource { - type; - #snapshot; - constructor(type, options) { - if (typeof type !== "string") - throw new TypeError('The "type" argument must be of type string. Received type ' + typeof type); - this.type = type, this.#snapshot = get(); - } - emitBefore() { - return !0; - } - emitAfter() { - return !0; - } - asyncId() { - return 0; - } - triggerAsyncId() { - return 0; - } - emitDestroy() { - } - runInAsyncScope(fn, thisArg, ...args) { - var prev = get(); - set(this.#snapshot); - try { - return fn.apply(thisArg, args); - } catch (error) { - throw error; - } finally { - set(prev); - } - } -} -var createHookNotImpl = createWarning("async_hooks.createHook is not implemented in Bun. Hooks can still be created but will never be called."), executionAsyncIdNotImpl = createWarning("async_hooks.executionAsyncId/triggerAsyncId are not implemented in Bun. It will return 0 every time."), executionAsyncResourceWarning = createWarning("async_hooks.executionAsyncResource is not implemented in Bun. It returns a reference to process.stdin every time."), asyncWrapProviders = { - NONE: 0, - DIRHANDLE: 1, - DNSCHANNEL: 2, - ELDHISTOGRAM: 3, - FILEHANDLE: 4, - FILEHANDLECLOSEREQ: 5, - FIXEDSIZEBLOBCOPY: 6, - FSEVENTWRAP: 7, - FSREQCALLBACK: 8, - FSREQPROMISE: 9, - GETADDRINFOREQWRAP: 10, - GETNAMEINFOREQWRAP: 11, - HEAPSNAPSHOT: 12, - HTTP2SESSION: 13, - HTTP2STREAM: 14, - HTTP2PING: 15, - HTTP2SETTINGS: 16, - HTTPINCOMINGMESSAGE: 17, - HTTPCLIENTREQUEST: 18, - JSSTREAM: 19, - JSUDPWRAP: 20, - MESSAGEPORT: 21, - PIPECONNECTWRAP: 22, - PIPESERVERWRAP: 23, - PIPEWRAP: 24, - PROCESSWRAP: 25, - PROMISE: 26, - QUERYWRAP: 27, - SHUTDOWNWRAP: 28, - SIGNALWRAP: 29, - STATWATCHER: 30, - STREAMPIPE: 31, - TCPCONNECTWRAP: 32, - TCPSERVERWRAP: 33, - TCPWRAP: 34, - TTYWRAP: 35, - UDPSENDWRAP: 36, - UDPWRAP: 37, - SIGINTWATCHDOG: 38, - WORKER: 39, - WORKERHEAPSNAPSHOT: 40, - WRITEWRAP: 41, - ZLIB: 42, - CHECKPRIMEREQUEST: 43, - PBKDF2REQUEST: 44, - KEYPAIRGENREQUEST: 45, - KEYGENREQUEST: 46, - KEYEXPORTREQUEST: 47, - CIPHERREQUEST: 48, - DERIVEBITSREQUEST: 49, - HASHREQUEST: 50, - RANDOMBYTESREQUEST: 51, - RANDOMPRIMEREQUEST: 52, - SCRYPTREQUEST: 53, - SIGNREQUEST: 54, - TLSWRAP: 55, - VERIFYREQUEST: 56, - INSPECTORJSBINDING: 57 -}; -var async_hooks_default = { - AsyncLocalStorage, - createHook, - executionAsyncId, - triggerAsyncId, - executionAsyncResource, - asyncWrapProviders, - AsyncResource, - [Symbol.for("CommonJS")]: 0 -}; -export { - triggerAsyncId, - executionAsyncResource, - executionAsyncId, - async_hooks_default as default, - createHook, - asyncWrapProviders, - AsyncResource, - AsyncLocalStorage -}; diff --git a/src/js/out/modules/node/child_process.js b/src/js/out/modules/node/child_process.js deleted file mode 100644 index 042fb7753c37c2..00000000000000 --- a/src/js/out/modules/node/child_process.js +++ /dev/null @@ -1,715 +0,0 @@ -import {EventEmitter} from "node:events"; -import * as StreamModule from "node:stream"; -import {constants} from "node:os"; -import {promisify} from "node:util"; -function spawn(file, args, options) { - options = normalizeSpawnArguments(file, args, options), validateTimeout(options.timeout), validateAbortSignal(options.signal, "options.signal"); - const killSignal2 = sanitizeKillSignal(options.killSignal), child = new ChildProcess; - if (debug("spawn", options), child.spawn(options), options.timeout > 0) { - let timeoutId = setTimeout(() => { - if (timeoutId) { - try { - child.kill(killSignal2); - } catch (err) { - child.emit("error", err); - } - timeoutId = null; - } - }); - child.once("exit", () => { - if (timeoutId) - clearTimeout(timeoutId), timeoutId = null; - }); - } - if (options.signal) { - let onAbortListener = function() { - abortChildProcess(child, killSignal2); - }; - const signal = options.signal; - if (signal.aborted) - process.nextTick(onAbortListener); - else - signal.addEventListener("abort", onAbortListener, { once: !0 }), child.once("exit", () => signal.removeEventListener("abort", onAbortListener)); - } - return child; -} -function execFile(file, args, options, callback) { - ({ file, args, options, callback } = normalizeExecFileArgs(file, args, options, callback)), options = { - encoding: "utf8", - timeout: 0, - maxBuffer: MAX_BUFFER, - killSignal: "SIGTERM", - cwd: null, - env: null, - shell: !1, - ...options - }; - const maxBuffer = options.maxBuffer; - validateTimeout(options.timeout), validateMaxBuffer(maxBuffer), options.killSignal = sanitizeKillSignal(options.killSignal); - const child = spawn(file, args, { - cwd: options.cwd, - env: options.env, - shell: options.shell, - signal: options.signal - }); - let encoding; - const _stdout = [], _stderr = []; - if (options.encoding !== "buffer" && BufferIsEncoding(options.encoding)) - encoding = options.encoding; - else - encoding = null; - let stdoutLen = 0, stderrLen = 0, killed = !1, exited = !1, timeoutId, encodedStdoutLen, encodedStderrLen, ex = null, cmd = file; - function exitHandler(code, signal) { - if (exited) - return; - if (exited = !0, timeoutId) - clearTimeout(timeoutId), timeoutId = null; - if (!callback) - return; - const readableEncoding = child?.stdout?.readableEncoding; - let stdout, stderr; - if (encoding || child.stdout && readableEncoding) - stdout = ArrayPrototypeJoin.call(_stdout, ""); - else - stdout = BufferConcat(_stdout); - if (encoding || child.stderr && readableEncoding) - stderr = ArrayPrototypeJoin.call(_stderr, ""); - else - stderr = BufferConcat(_stderr); - if (!ex && code === 0 && signal === null) { - callback(null, stdout, stderr); - return; - } - if (args?.length) - cmd += ` ${ArrayPrototypeJoin.call(args, " ")}`; - if (!ex) { - let message = `Command failed: ${cmd}`; - if (stderr) - message += `\n${stderr}`; - ex = genericNodeError(message, { - code, - killed: child.killed || killed, - signal - }); - } - ex.cmd = cmd, callback(ex, stdout, stderr); - } - function errorHandler(e) { - if (ex = e, child.stdout) - child.stdout.destroy(); - if (child.stderr) - child.stderr.destroy(); - exitHandler(); - } - function kill() { - if (child.stdout) - child.stdout.destroy(); - if (child.stderr) - child.stderr.destroy(); - killed = !0; - try { - child.kill(options.killSignal); - } catch (e) { - ex = e, exitHandler(); - } - } - if (options.timeout > 0) - timeoutId = setTimeout(function delayedKill() { - kill(), timeoutId = null; - }, options.timeout); - if (child.stdout) { - if (encoding) - child.stdout.setEncoding(encoding); - child.stdout.on("data", maxBuffer === Infinity ? function onUnlimitedSizeBufferedData(chunk) { - ArrayPrototypePush.call(_stdout, chunk); - } : encoding ? function onChildStdoutEncoded(chunk) { - if (stdoutLen += chunk.length, stdoutLen * 4 > maxBuffer) { - const encoding2 = child.stdout.readableEncoding, actualLen = Buffer.byteLength(chunk, encoding2); - if (encodedStdoutLen === void 0) - for (let i = 0;i < _stdout.length; i++) - encodedStdoutLen += Buffer.byteLength(_stdout[i], encoding2); - else - encodedStdoutLen += actualLen; - const truncatedLen = maxBuffer - (encodedStdoutLen - actualLen); - ArrayPrototypePush.call(_stdout, StringPrototypeSlice.apply(chunk, 0, truncatedLen)), ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER("stdout"), kill(); - } else - ArrayPrototypePush.call(_stdout, chunk); - } : function onChildStdoutRaw(chunk) { - if (stdoutLen += chunk.length, stdoutLen > maxBuffer) { - const truncatedLen = maxBuffer - (stdoutLen - chunk.length); - ArrayPrototypePush.call(_stdout, chunk.slice(0, truncatedLen)), ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER("stdout"), kill(); - } else - ArrayPrototypePush.call(_stdout, chunk); - }); - } - if (child.stderr) { - if (encoding) - child.stderr.setEncoding(encoding); - child.stderr.on("data", maxBuffer === Infinity ? function onUnlimitedSizeBufferedData(chunk) { - ArrayPrototypePush.call(_stderr, chunk); - } : encoding ? function onChildStderrEncoded(chunk) { - if (stderrLen += chunk.length, stderrLen * 4 > maxBuffer) { - const encoding2 = child.stderr.readableEncoding, actualLen = Buffer.byteLength(chunk, encoding2); - if (encodedStderrLen === void 0) - for (let i = 0;i < _stderr.length; i++) - encodedStderrLen += Buffer.byteLength(_stderr[i], encoding2); - else - encodedStderrLen += actualLen; - const truncatedLen = maxBuffer - (encodedStderrLen - actualLen); - ArrayPrototypePush.call(_stderr, StringPrototypeSlice.call(chunk, 0, truncatedLen)), ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER("stderr"), kill(); - } else - ArrayPrototypePush.call(_stderr, chunk); - } : function onChildStderrRaw(chunk) { - if (stderrLen += chunk.length, stderrLen > maxBuffer) { - const truncatedLen = maxBuffer - (stderrLen - chunk.length); - ArrayPrototypePush.call(_stderr, StringPrototypeSlice.call(chunk, 0, truncatedLen)), ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER("stderr"), kill(); - } else - ArrayPrototypePush.call(_stderr, chunk); - }); - } - return child.addListener("close", exitHandler), child.addListener("error", errorHandler), child; -} -function exec(command, options, callback) { - const opts = normalizeExecArgs(command, options, callback); - return execFile(opts.file, opts.options, opts.callback); -} -function spawnSync(file, args, options) { - options = { - maxBuffer: MAX_BUFFER, - ...normalizeSpawnArguments(file, args, options) - }; - const { maxBuffer, encoding } = options; - debug("spawnSync", options), validateTimeout(options.timeout), validateMaxBuffer(maxBuffer), options.killSignal = sanitizeKillSignal(options.killSignal); - const stdio = options.stdio || "pipe", bunStdio = getBunStdioFromOptions(stdio); - var { input } = options; - if (input) - if (ArrayBufferIsView(input)) - bunStdio[0] = input; - else if (typeof input === "string") - bunStdio[0] = Buffer.from(input, encoding || "utf8"); - else - throw new ERR_INVALID_ARG_TYPE("options.stdio[0]", ["Buffer", "TypedArray", "DataView", "string"], input); - const { stdout, stderr, success, exitCode } = Bun.spawnSync({ - cmd: options.args, - env: options.env || void 0, - cwd: options.cwd || void 0, - stdin: bunStdio[0], - stdout: bunStdio[1], - stderr: bunStdio[2] - }), result = { - signal: null, - status: exitCode, - output: [null, stdout, stderr] - }; - if (stdout && encoding && encoding !== "buffer") - result.output[1] = result.output[1]?.toString(encoding); - if (stderr && encoding && encoding !== "buffer") - result.output[2] = result.output[2]?.toString(encoding); - if (result.stdout = result.output[1], result.stderr = result.output[2], !success) - result.error = new SystemError(result.output[2], options.file, "spawnSync", -1, result.status), result.error.spawnargs = ArrayPrototypeSlice.call(options.args, 1); - return result; -} -function execFileSync(file, args, options) { - ({ file, args, options } = normalizeExecFileArgs(file, args, options)); - const ret = spawnSync(file, args, options), errArgs = [options.argv0 || file]; - ArrayPrototypePush.apply(errArgs, args); - const err = checkExecSyncError(ret, errArgs); - if (err) - throw err; - return ret.stdout; -} -function execSync(command, options) { - const opts = normalizeExecArgs(command, options, null), ret = spawnSync(opts.file, opts.options), err = checkExecSyncError(ret, void 0, command); - if (err) - throw err; - return ret.stdout; -} -function fork() { - throw new Error("Not implemented"); -} -var convertToValidSignal = function(signal) { - if (typeof signal === "number" && getSignalsToNamesMapping()[signal]) - return signal; - if (typeof signal === "string") { - const signalName = signals[StringPrototypeToUpperCase.call(signal)]; - if (signalName) - return signalName; - } - throw new ERR_UNKNOWN_SIGNAL(signal); -}, sanitizeKillSignal = function(killSignal2) { - if (typeof killSignal2 === "string" || typeof killSignal2 === "number") - return convertToValidSignal(killSignal2); - else if (killSignal2 != null) - throw new ERR_INVALID_ARG_TYPE("options.killSignal", ["string", "number"], killSignal2); -}, getSignalsToNamesMapping = function() { - if (signalsToNamesMapping !== void 0) - return signalsToNamesMapping; - signalsToNamesMapping = ObjectCreate(null); - for (let key in signals) - signalsToNamesMapping[signals[key]] = key; - return signalsToNamesMapping; -}, normalizeExecFileArgs = function(file, args, options, callback) { - if (ArrayIsArray(args)) - args = ArrayPrototypeSlice.call(args); - else if (args != null && typeof args === "object") - callback = options, options = args, args = null; - else if (typeof args === "function") - callback = args, options = null, args = null; - if (args == null) - args = []; - if (typeof options === "function") - callback = options; - else if (options != null) - validateObject(options, "options"); - if (options == null) - options = kEmptyObject; - if (callback != null) - validateFunction(callback, "callback"); - if (options.argv0 != null) - validateString(options.argv0, "options.argv0"), validateArgumentNullCheck(options.argv0, "options.argv0"); - return { file, args, options, callback }; -}, normalizeExecArgs = function(command, options, callback) { - if (validateString(command, "command"), validateArgumentNullCheck(command, "command"), typeof options === "function") - callback = options, options = void 0; - return options = { ...options }, options.shell = typeof options.shell === "string" ? options.shell : !0, { - file: command, - options, - callback - }; -}, normalizeSpawnArguments = function(file, args, options) { - if (validateString(file, "file"), validateArgumentNullCheck(file, "file"), file.length === 0) - throw new ERR_INVALID_ARG_VALUE("file", file, "cannot be empty"); - if (ArrayIsArray(args)) - args = ArrayPrototypeSlice.call(args); - else if (args == null) - args = []; - else if (typeof args !== "object") - throw new ERR_INVALID_ARG_TYPE("args", "object", args); - else - options = args, args = []; - if (validateArgumentsNullCheck(args, "args"), options === void 0) - options = {}; - else - validateObject(options, "options"); - let cwd = options.cwd; - if (cwd != null) - cwd = getValidatedPath(cwd, "options.cwd"); - if (options.shell != null && typeof options.shell !== "boolean" && typeof options.shell !== "string") - throw new ERR_INVALID_ARG_TYPE("options.shell", ["boolean", "string"], options.shell); - if (options.argv0 != null) - validateString(options.argv0, "options.argv0"), validateArgumentNullCheck(options.argv0, "options.argv0"); - if (options.shell) { - validateArgumentNullCheck(options.shell, "options.shell"); - const command = ArrayPrototypeJoin.call([file, ...args], " "); - if (typeof options.shell === "string") - file = options.shell; - else - file = "sh"; - args = ["-c", command]; - } - if (typeof options.argv0 === "string") - ArrayPrototypeUnshift.call(args, options.argv0); - else - ArrayPrototypeUnshift.call(args, file); - const envPairs = options.env || process.env; - return { ...options, file, args, cwd, envPairs }; -}, checkExecSyncError = function(ret, args, cmd) { - let err; - if (ret.error) - err = ret.error, ObjectAssign(err, ret); - else if (ret.status !== 0) { - let msg = "Command failed: "; - if (msg += cmd || ArrayPrototypeJoin.call(args, " "), ret.stderr && ret.stderr.length > 0) - msg += `\n${ret.stderr.toString()}`; - err = genericNodeError(msg, ret); - } - return err; -}, nodeToBun = function(item) { - if (typeof item === "number") - return item; - else { - const result = nodeToBunLookup[item]; - if (result === void 0) - throw new Error("Invalid stdio option"); - return result; - } -}, fdToStdioName = function(fd) { - switch (fd) { - case 0: - return "stdin"; - case 1: - return "stdout"; - case 2: - return "stderr"; - default: - return null; - } -}, getBunStdioFromOptions = function(stdio) { - return normalizeStdio(stdio).map((item) => nodeToBun(item)); -}, normalizeStdio = function(stdio) { - if (typeof stdio === "string") - switch (stdio) { - case "ignore": - return ["ignore", "ignore", "ignore"]; - case "pipe": - return ["pipe", "pipe", "pipe"]; - case "inherit": - return ["inherit", "inherit", "inherit"]; - default: - throw new ERR_INVALID_OPT_VALUE("stdio", stdio); - } - else if (ArrayIsArray(stdio)) { - let processedStdio; - if (stdio.length === 0) - processedStdio = ["pipe", "pipe", "pipe"]; - else if (stdio.length === 1) - processedStdio = [stdio[0], "pipe", "pipe"]; - else if (stdio.length === 2) - processedStdio = [stdio[0], stdio[1], "pipe"]; - else if (stdio.length >= 3) - processedStdio = [stdio[0], stdio[1], stdio[2]]; - return processedStdio.map((item) => !item ? "pipe" : item); - } else - throw new ERR_INVALID_OPT_VALUE("stdio", stdio); -}, flushStdio = function(subprocess) { - const stdio = subprocess.stdio; - if (stdio == null) - return; - for (let i = 0;i < stdio.length; i++) { - const stream = stdio[i]; - if (!stream || !stream.readable) - continue; - stream.resume(); - } -}, onSpawnNT = function(self) { - self.emit("spawn"); -}, abortChildProcess = function(child, killSignal2) { - if (!child) - return; - try { - if (child.kill(killSignal2)) - child.emit("error", new AbortError); - } catch (err) { - child.emit("error", err); - } -}, validateMaxBuffer = function(maxBuffer) { - if (maxBuffer != null && !(typeof maxBuffer === "number" && maxBuffer >= 0)) - throw new ERR_OUT_OF_RANGE("options.maxBuffer", "a positive number", maxBuffer); -}, validateArgumentNullCheck = function(arg, propName) { - if (typeof arg === "string" && StringPrototypeIncludes.call(arg, "\0")) - throw new ERR_INVALID_ARG_VALUE(propName, arg, "must be a string without null bytes"); -}, validateArgumentsNullCheck = function(args, propName) { - for (let i = 0;i < args.length; ++i) - validateArgumentNullCheck(args[i], `${propName}[${i}]`); -}, validateTimeout = function(timeout) { - if (timeout != null && !(NumberIsInteger(timeout) && timeout >= 0)) - throw new ERR_OUT_OF_RANGE("timeout", "an unsigned integer", timeout); -}; -var validateFunction = function(value, name) { - if (typeof value !== "function") - throw new ERR_INVALID_ARG_TYPE(name, "Function", value); -}, validateString = function(value, name) { - if (typeof value !== "string") - throw new ERR_INVALID_ARG_TYPE(name, "string", value); -}, nullCheck = function(path, propName, throwError = !0) { - const pathIsString = typeof path === "string", pathIsUint8Array = isUint8Array(path); - if (!pathIsString && !pathIsUint8Array || pathIsString && !StringPrototypeIncludes.call(path, "\0") || pathIsUint8Array && !Uint8ArrayPrototypeIncludes.call(path, 0)) - return; - const err = new ERR_INVALID_ARG_VALUE(propName, path, "must be a string or Uint8Array without null bytes"); - if (throwError) - throw err; - return err; -}, validatePath = function(path, propName = "path") { - if (typeof path !== "string" && !isUint8Array(path)) - throw new ERR_INVALID_ARG_TYPE(propName, ["string", "Buffer", "URL"], path); - const err = nullCheck(path, propName, !1); - if (err !== void 0) - throw err; -}, getValidatedPath = function(fileURLOrPath, propName = "path") { - const path = toPathIfFileURL(fileURLOrPath); - return validatePath(path, propName), path; -}, isUint8Array = function(value) { - return typeof value === "object" && value !== null && value instanceof Uint8Array; -}, isURLInstance = function(fileURLOrPath) { - return fileURLOrPath != null && fileURLOrPath.href && fileURLOrPath.origin; -}, toPathIfFileURL = function(fileURLOrPath) { - if (!isURLInstance(fileURLOrPath)) - return fileURLOrPath; - return Bun.fileURLToPath(fileURLOrPath); -}, genericNodeError = function(message, options) { - const err = new Error(message); - return err.code = options.code, err.killed = options.killed, err.signal = options.signal, err; -}, ERR_OUT_OF_RANGE = function(str, range, input, replaceDefaultBoolean = !1) { - return new RangeError(`The value of ${str} is out of range. It must be ${range}. Received ${input}`); -}, ERR_CHILD_PROCESS_STDIO_MAXBUFFER = function(stdio) { - return Error(`${stdio} maxBuffer length exceeded`); -}, ERR_UNKNOWN_SIGNAL = function(name) { - const err = new TypeError(`Unknown signal: ${name}`); - return err.code = "ERR_UNKNOWN_SIGNAL", err; -}, ERR_INVALID_ARG_TYPE = function(name, type, value) { - const err = new TypeError(`The "${name}" argument must be of type ${type}. Received ${value}`); - return err.code = "ERR_INVALID_ARG_TYPE", err; -}, ERR_INVALID_OPT_VALUE = function(name, value) { - return new TypeError(`The value "${value}" is invalid for option "${name}"`); -}, ERR_INVALID_ARG_VALUE = function(name, value, reason) { - return new Error(`The value "${value}" is invalid for argument '${name}'. Reason: ${reason}`); -}, signals = constants.signals, { ArrayBuffer, Uint8Array, String, Object, Buffer, Promise: Promise2 } = globalThis[Symbol.for("Bun.lazy")]("primordials"), ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty, ObjectCreate = Object.create, ObjectAssign = Object.assign, ObjectDefineProperty = Object.defineProperty, BufferConcat = Buffer.concat, BufferIsEncoding = Buffer.isEncoding, kEmptyObject = ObjectCreate(null), ArrayPrototypePush = Array.prototype.push, ArrayPrototypeJoin = Array.prototype.join, ArrayPrototypeMap = Array.prototype.map, ArrayPrototypeIncludes = Array.prototype.includes, ArrayPrototypeSlice = Array.prototype.slice, ArrayPrototypeUnshift = Array.prototype.unshift, ArrayIsArray = Array.isArray, ArrayBufferIsView = ArrayBuffer.isView, NumberIsInteger = Number.isInteger; -var StringPrototypeToUpperCase = String.prototype.toUpperCase, StringPrototypeIncludes = String.prototype.includes, StringPrototypeSlice = String.prototype.slice, Uint8ArrayPrototypeIncludes = Uint8Array.prototype.includes, MAX_BUFFER = 1048576, __DEBUG__ = process.env.DEBUG || !1, __TRACK_STDIO__ = process.env.DEBUG_STDIO, debug = __DEBUG__ ? console.log : () => { -}; -if (__TRACK_STDIO__) - debug("child_process: debug mode on"), globalThis.__lastId = null, globalThis.__getId = () => { - return globalThis.__lastId !== null ? globalThis.__lastId++ : 0; - }; -var NativeWritable2, ReadableFromWeb, customPromiseExecFunction = (orig) => { - return (...args) => { - let resolve, reject; - const promise = new Promise2((res, rej) => { - resolve = res, reject = rej; - }); - return promise.child = orig(...args, (err, stdout, stderr) => { - if (err !== null) - err.stdout = stdout, err.stderr = stderr, reject(err); - else - resolve({ stdout, stderr }); - }), promise; - }; -}; -ObjectDefineProperty(exec, promisify.custom, { - __proto__: null, - enumerable: !1, - value: customPromiseExecFunction(exec) -}); -var signalsToNamesMapping; - -class ChildProcess extends EventEmitter { - #handle; - #exited = !1; - #closesNeeded = 1; - #closesGot = 0; - connected = !1; - signalCode = null; - exitCode = null; - spawnfile; - spawnargs; - pid; - channel; - get killed() { - if (this.#handle == null) - return !1; - } - #handleOnExit(exitCode, signalCode, err) { - if (this.#exited) - return; - if (this.exitCode = this.#handle.exitCode, this.signalCode = exitCode > 0 ? signalCode : null, this.#stdin) - this.#stdin.destroy(); - if (this.#handle) - this.#handle = null; - if (exitCode < 0) { - const err2 = new SystemError(`Spawned process exited with error code: ${exitCode}`, void 0, "spawn", "EUNKNOWN", "ERR_CHILD_PROCESS_UNKNOWN_ERROR"); - if (this.spawnfile) - err2.path = this.spawnfile; - err2.spawnargs = ArrayPrototypeSlice.call(this.spawnargs, 1), this.emit("error", err2); - } else - this.emit("exit", this.exitCode, this.signalCode); - process.nextTick(flushStdio, this), this.#maybeClose(), this.#exited = !0, this.#stdioOptions = ["destroyed", "destroyed", "destroyed"]; - } - #getBunSpawnIo(i, encoding) { - if (__DEBUG__ && !this.#handle) - if (this.#handle === null) - debug("ChildProcess: getBunSpawnIo: this.#handle is null. This means the subprocess already exited"); - else - debug("ChildProcess: getBunSpawnIo: this.#handle is undefined"); - NativeWritable2 ||= StreamModule.NativeWritable, ReadableFromWeb ||= StreamModule.Readable.fromWeb; - const io = this.#stdioOptions[i]; - switch (i) { - case 0: - switch (io) { - case "pipe": - return new NativeWritable2(this.#handle.stdin); - case "inherit": - return process.stdin || null; - case "destroyed": - return new ShimmedStdin; - default: - return null; - } - case 2: - case 1: - switch (io) { - case "pipe": - return ReadableFromWeb(this.#handle[fdToStdioName(i)], { encoding }); - case "inherit": - return process[fdToStdioName(i)] || null; - case "destroyed": - return new ShimmedStdioOutStream; - default: - return null; - } - } - } - #stdin; - #stdout; - #stderr; - #stdioObject; - #encoding; - #stdioOptions; - #createStdioObject() { - return Object.create(null, { - 0: { - get: () => this.stdin - }, - 1: { - get: () => this.stdout - }, - 2: { - get: () => this.stderr - } - }); - } - get stdin() { - return this.#stdin ??= this.#getBunSpawnIo(0, this.#encoding); - } - get stdout() { - return this.#stdout ??= this.#getBunSpawnIo(1, this.#encoding); - } - get stderr() { - return this.#stderr ??= this.#getBunSpawnIo(2, this.#encoding); - } - get stdio() { - return this.#stdioObject ??= this.#createStdioObject(); - } - spawn(options) { - validateObject(options, "options"), validateString(options.file, "options.file"); - var file = this.spawnfile = options.file, spawnargs; - if (options.args == null) - spawnargs = this.spawnargs = []; - else - validateArray(options.args, "options.args"), spawnargs = this.spawnargs = options.args; - const stdio = options.stdio || ["pipe", "pipe", "pipe"], bunStdio = getBunStdioFromOptions(stdio); - var env = options.envPairs || void 0; - this.#encoding = options.encoding || void 0, this.#stdioOptions = bunStdio, this.#handle = Bun.spawn({ - cmd: spawnargs, - stdin: bunStdio[0], - stdout: bunStdio[1], - stderr: bunStdio[2], - cwd: options.cwd || void 0, - env: env || process.env, - onExit: (handle, exitCode, signalCode, err) => { - this.#handle = handle, this.pid = this.#handle.pid, process.nextTick((exitCode2, signalCode2, err2) => this.#handleOnExit(exitCode2, signalCode2, err2), exitCode, signalCode, err); - }, - lazy: !0 - }), this.pid = this.#handle.pid, onSpawnNT(this); - } - send() { - console.log("ChildProcess.prototype.send() - Sorry! Not implemented yet"); - } - disconnect() { - console.log("ChildProcess.prototype.disconnect() - Sorry! Not implemented yet"); - } - kill(sig) { - const signal = sig === 0 ? sig : convertToValidSignal(sig === void 0 ? "SIGTERM" : sig); - if (this.#handle) - this.#handle.kill(signal); - return this.#maybeClose(), !0; - } - #maybeClose() { - if (debug("Attempting to maybe close..."), this.#closesGot++, this.#closesGot === this.#closesNeeded) - this.emit("close", this.exitCode, this.signalCode); - } - ref() { - if (this.#handle) - this.#handle.ref(); - } - unref() { - if (this.#handle) - this.#handle.unref(); - } -} -var nodeToBunLookup = { - ignore: null, - pipe: "pipe", - overlapped: "pipe", - inherit: "inherit" -}; - -class ShimmedStdin extends EventEmitter { - constructor() { - super(); - } - write() { - return !1; - } - destroy() { - } - end() { - } - pipe() { - } -} - -class ShimmedStdioOutStream extends EventEmitter { - pipe() { - } -} -var validateAbortSignal = (signal, name) => { - if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) - throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal); -}; -var validateObject = (value, name, options = null) => { - const allowArray = options?.allowArray ?? !1, allowFunction = options?.allowFunction ?? !1; - if (!(options?.nullable ?? !1) && value === null || !allowArray && ArrayIsArray.call(value) || typeof value !== "object" && (!allowFunction || typeof value !== "function")) - throw new ERR_INVALID_ARG_TYPE(name, "object", value); -}, validateArray = (value, name, minLength = 0) => { - if (!ArrayIsArray(value)) - throw new ERR_INVALID_ARG_TYPE(name, "Array", value); - if (value.length < minLength) { - const reason = `must be longer than ${minLength}`; - throw new ERR_INVALID_ARG_VALUE(name, value, reason); - } -}, Error = globalThis.Error, TypeError = globalThis.TypeError, RangeError = globalThis.RangeError; - -class AbortError extends Error { - code = "ABORT_ERR"; - name = "AbortError"; - constructor(message = "The operation was aborted", options = void 0) { - if (options !== void 0 && typeof options !== "object") - throw new ERR_INVALID_ARG_TYPE("options", "Object", options); - super(message, options); - } -} - -class SystemError extends Error { - path; - syscall; - errno; - code; - constructor(message, path, syscall, errno, code) { - super(message); - this.path = path, this.syscall = syscall, this.errno = errno, this.code = code; - } - get name() { - return "SystemError"; - } -} -var child_process_default = { - ChildProcess, - spawn, - execFile, - exec, - fork, - spawnSync, - execFileSync, - execSync, - [Symbol.for("CommonJS")]: 0 -}; -export { - spawnSync, - spawn, - fork, - execSync, - execFileSync, - execFile, - exec, - child_process_default as default, - ChildProcess -}; diff --git a/src/js/out/modules/node/cluster.js b/src/js/out/modules/node/cluster.js deleted file mode 100644 index 036e80380fbde3..00000000000000 --- a/src/js/out/modules/node/cluster.js +++ /dev/null @@ -1,63 +0,0 @@ -import EventEmitter from "node:events"; - -// src/js/shared.ts -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/cluster.ts -var SCHED_NONE = 0, SCHED_RR = 1, Worker, schedulingPolicy = 2, isWorker = !1, isPrimary = !0, isMaster = !0, cluster; -Worker = function Worker2() { - throwNotImplemented("node:cluster Worker", 2428); -}; - -class Cluster extends EventEmitter { - constructor() { - super(...arguments); - } - static isWorker = !1; - static isPrimary = !0; - static isMaster = !0; - static Worker = Worker; - fork() { - throwNotImplemented("node:cluster", 2428); - } - disconnect() { - throwNotImplemented("node:cluster", 2428); - } - setupMaster() { - throwNotImplemented("node:cluster", 2428); - } - settings = {}; - workers = {}; - SCHED_NONE = 0; - SCHED_RR = 1; - schedulingPolicy = 2; - [Symbol.for("CommonJS")] = 0; -} -cluster = new Cluster; -export { - schedulingPolicy, - isWorker, - isPrimary, - isMaster, - cluster as default, - cluster, - Worker, - SCHED_RR, - SCHED_NONE -}; diff --git a/src/js/out/modules/node/crypto.js b/src/js/out/modules/node/crypto.js deleted file mode 100644 index 81adf061842b0e..00000000000000 --- a/src/js/out/modules/node/crypto.js +++ /dev/null @@ -1,4 +0,0 @@ -var bQ=(N)=>{return import.meta.require(N)};import{StringDecoder as uQ} from"node:string_decoder";import*as i$ from"node:buffer";import*as A$ from"node:stream";var q$=function(N,_,j){if(sQ(N))return N;if(typeof N==="string"){if(j==="buffer")j="utf8";return j0.from(N,j)}if(!tQ(N)){var k=new TypeError(`ERR_INVALID_ARG_TYPE: The "${_}" argument must be of type string or an instance of ArrayBuffer, Buffer, TypedArray, or DataView. Received `+N);throw k.code="ERR_INVALID_ARG_TYPE",k}return N},OZ=function(){return IZ};var lQ=Object.defineProperty;var oQ=Object.getOwnPropertyNames;var nQ=536870888,j0=globalThis.Buffer,$Q=j0.alloc(0),{isAnyArrayBuffer:sQ,isArrayBufferView:tQ}=import.meta.require("node:util/types"),W$=globalThis.crypto,QQ=W$;var S0=(N,_)=>function(){return _||(0,N[oQ(N)[0]])((_={exports:{}}).exports,_),_.exports},mQ=(N,_)=>{for(var j in _)lQ(N,j,{get:_[j],enumerable:!0})};var N0=S0({"node_modules/safe-buffer/index.js"(N,_){var j=i$,k=j.Buffer;function F(X,C){for(var z in X)C[z]=X[z]}k.from&&k.alloc&&k.allocUnsafe&&k.allocUnsafeSlow?_.exports=j:(F(j,N),N.Buffer=P);function P(X,C,z){return k(X,C,z)}P.prototype=Object.create(k.prototype),F(k,P),P.from=function(X,C,z){if(typeof X=="number")throw new TypeError("Argument must not be a number");return k(X,C,z)},P.alloc=function(X,C,z){if(typeof X!="number")throw new TypeError("Argument must be a number");var T=k(X);return C!==void 0?typeof z=="string"?T.fill(C,z):T.fill(C):T.fill(0),T},P.allocUnsafe=function(X){if(typeof X!="number")throw new TypeError("Argument must be a number");return k(X)},P.allocUnsafeSlow=function(X){if(typeof X!="number")throw new TypeError("Argument must be a number");return j.SlowBuffer(X)}}}),L$=S0({"node_modules/randombytes/browser.js"(N,_){var j=65536,k=4294967295;function F(){throw new Error(`Secure random number generation is not supported by this browser. -Use Chrome, Firefox or Internet Explorer 11`)}var P=N0().Buffer,X=QQ;X&&X.getRandomValues?_.exports=C:_.exports=F;function C(z,T){if(z>k)throw new RangeError("requested too many random bytes");var H=P.allocUnsafe(z);if(z>0)if(z>j)for(var J=0;J=this._blockSize;){for(var H=this._blockOffset;H0;++J)this._length[J]+=W,W=this._length[J]/4294967296|0,W>0&&(this._length[J]-=4294967296*W);return this},P.prototype._update=function(){throw new Error("_update is not implemented")},P.prototype.digest=function(X){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var C=this._digest();X!==void 0&&(C=C.toString(X)),this._block.fill(0),this._blockOffset=0;for(var z=0;z<4;++z)this._length[z]=0;return C},P.prototype._digest=function(){throw new Error("_digest is not implemented")},_.exports=P}}),ZQ=S0({"node_modules/md5.js/index.js"(N,_){var j=B0(),k=YQ(),F=N0().Buffer,P=new Array(16);function X(){k.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}j(X,k),X.prototype._update=function(){for(var W=P,D=0;D<16;++D)W[D]=this._block.readInt32LE(D*4);var E=this._a,R=this._b,M=this._c,v=this._d;E=z(E,R,M,v,W[0],3614090360,7),v=z(v,E,R,M,W[1],3905402710,12),M=z(M,v,E,R,W[2],606105819,17),R=z(R,M,v,E,W[3],3250441966,22),E=z(E,R,M,v,W[4],4118548399,7),v=z(v,E,R,M,W[5],1200080426,12),M=z(M,v,E,R,W[6],2821735955,17),R=z(R,M,v,E,W[7],4249261313,22),E=z(E,R,M,v,W[8],1770035416,7),v=z(v,E,R,M,W[9],2336552879,12),M=z(M,v,E,R,W[10],4294925233,17),R=z(R,M,v,E,W[11],2304563134,22),E=z(E,R,M,v,W[12],1804603682,7),v=z(v,E,R,M,W[13],4254626195,12),M=z(M,v,E,R,W[14],2792965006,17),R=z(R,M,v,E,W[15],1236535329,22),E=T(E,R,M,v,W[1],4129170786,5),v=T(v,E,R,M,W[6],3225465664,9),M=T(M,v,E,R,W[11],643717713,14),R=T(R,M,v,E,W[0],3921069994,20),E=T(E,R,M,v,W[5],3593408605,5),v=T(v,E,R,M,W[10],38016083,9),M=T(M,v,E,R,W[15],3634488961,14),R=T(R,M,v,E,W[4],3889429448,20),E=T(E,R,M,v,W[9],568446438,5),v=T(v,E,R,M,W[14],3275163606,9),M=T(M,v,E,R,W[3],4107603335,14),R=T(R,M,v,E,W[8],1163531501,20),E=T(E,R,M,v,W[13],2850285829,5),v=T(v,E,R,M,W[2],4243563512,9),M=T(M,v,E,R,W[7],1735328473,14),R=T(R,M,v,E,W[12],2368359562,20),E=H(E,R,M,v,W[5],4294588738,4),v=H(v,E,R,M,W[8],2272392833,11),M=H(M,v,E,R,W[11],1839030562,16),R=H(R,M,v,E,W[14],4259657740,23),E=H(E,R,M,v,W[1],2763975236,4),v=H(v,E,R,M,W[4],1272893353,11),M=H(M,v,E,R,W[7],4139469664,16),R=H(R,M,v,E,W[10],3200236656,23),E=H(E,R,M,v,W[13],681279174,4),v=H(v,E,R,M,W[0],3936430074,11),M=H(M,v,E,R,W[3],3572445317,16),R=H(R,M,v,E,W[6],76029189,23),E=H(E,R,M,v,W[9],3654602809,4),v=H(v,E,R,M,W[12],3873151461,11),M=H(M,v,E,R,W[15],530742520,16),R=H(R,M,v,E,W[2],3299628645,23),E=J(E,R,M,v,W[0],4096336452,6),v=J(v,E,R,M,W[7],1126891415,10),M=J(M,v,E,R,W[14],2878612391,15),R=J(R,M,v,E,W[5],4237533241,21),E=J(E,R,M,v,W[12],1700485571,6),v=J(v,E,R,M,W[3],2399980690,10),M=J(M,v,E,R,W[10],4293915773,15),R=J(R,M,v,E,W[1],2240044497,21),E=J(E,R,M,v,W[8],1873313359,6),v=J(v,E,R,M,W[15],4264355552,10),M=J(M,v,E,R,W[6],2734768916,15),R=J(R,M,v,E,W[13],1309151649,21),E=J(E,R,M,v,W[4],4149444226,6),v=J(v,E,R,M,W[11],3174756917,10),M=J(M,v,E,R,W[2],718787259,15),R=J(R,M,v,E,W[9],3951481745,21),this._a=this._a+E|0,this._b=this._b+R|0,this._c=this._c+M|0,this._d=this._d+v|0},X.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var W=F.allocUnsafe(16);return W.writeInt32LE(this._a,0),W.writeInt32LE(this._b,4),W.writeInt32LE(this._c,8),W.writeInt32LE(this._d,12),W};function C(W,D){return W<>>32-D}function z(W,D,E,R,M,v,q){return C(W+(D&E|~D&R)+M+v|0,q)+D|0}function T(W,D,E,R,M,v,q){return C(W+(D&R|E&~R)+M+v|0,q)+D|0}function H(W,D,E,R,M,v,q){return C(W+(D^E^R)+M+v|0,q)+D|0}function J(W,D,E,R,M,v,q){return C(W+(E^(D|~R))+M+v|0,q)+D|0}_.exports=X}}),GQ=S0({"node_modules/ripemd160/index.js"(N,_){var j=j0,k=B0(),F=YQ(),P=new Array(16),X=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],C=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],z=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],T=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],H=[0,1518500249,1859775393,2400959708,2840853838],J=[1352829926,1548603684,1836072691,2053994217,0];function W(){F.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}k(W,F),W.prototype._update=function(){for(var g=P,B=0;B<16;++B)g[B]=this._block.readInt32LE(B*4);for(var w=this._a|0,f=this._b|0,b=this._c|0,u=this._d|0,Y0=this._e|0,p=this._a|0,v0=this._b|0,$=this._c|0,Y=this._d|0,G=this._e|0,Z=0;Z<80;Z+=1){var V,I;Z<16?(V=E(w,f,b,u,Y0,g[X[Z]],H[0],z[Z]),I=q(p,v0,$,Y,G,g[C[Z]],J[0],T[Z])):Z<32?(V=R(w,f,b,u,Y0,g[X[Z]],H[1],z[Z]),I=v(p,v0,$,Y,G,g[C[Z]],J[1],T[Z])):Z<48?(V=M(w,f,b,u,Y0,g[X[Z]],H[2],z[Z]),I=M(p,v0,$,Y,G,g[C[Z]],J[2],T[Z])):Z<64?(V=v(w,f,b,u,Y0,g[X[Z]],H[3],z[Z]),I=R(p,v0,$,Y,G,g[C[Z]],J[3],T[Z])):(V=q(w,f,b,u,Y0,g[X[Z]],H[4],z[Z]),I=E(p,v0,$,Y,G,g[C[Z]],J[4],T[Z])),w=Y0,Y0=u,u=D(b,10),b=f,f=V,p=G,G=Y,Y=D($,10),$=v0,v0=I}var O=this._b+b+Y|0;this._b=this._c+u+G|0,this._c=this._d+Y0+p|0,this._d=this._e+w+v0|0,this._e=this._a+f+$|0,this._a=O},W.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var g=j.alloc?j.alloc(20):new j(20);return g.writeInt32LE(this._a,0),g.writeInt32LE(this._b,4),g.writeInt32LE(this._c,8),g.writeInt32LE(this._d,12),g.writeInt32LE(this._e,16),g};function D(g,B){return g<>>32-B}function E(g,B,w,f,b,u,Y0,p){return D(g+(B^w^f)+u+Y0|0,p)+b|0}function R(g,B,w,f,b,u,Y0,p){return D(g+(B&w|~B&f)+u+Y0|0,p)+b|0}function M(g,B,w,f,b,u,Y0,p){return D(g+((B|~w)^f)+u+Y0|0,p)+b|0}function v(g,B,w,f,b,u,Y0,p){return D(g+(B&f|w&~f)+u+Y0|0,p)+b|0}function q(g,B,w,f,b,u,Y0,p){return D(g+(B^(w|~f))+u+Y0|0,p)+b|0}_.exports=W}}),R$=S0({"node_modules/sha.js/hash.js"(N,_){var j=N0().Buffer;function k(F,P){this._block=j.alloc(F),this._finalSize=P,this._blockSize=F,this._len=0}k.prototype.update=function(F,P){typeof F=="string"&&(P=P||"utf8",F=j.from(F,P));for(var X=this._block,C=this._blockSize,z=F.length,T=this._len,H=0;H=this._finalSize&&(this._update(this._block),this._block.fill(0));var X=this._len*8;if(X<=4294967295)this._block.writeUInt32BE(X,this._blockSize-4);else{var C=(X&4294967295)>>>0,z=(X-C)/4294967296;this._block.writeUInt32BE(z,this._blockSize-8),this._block.writeUInt32BE(C,this._blockSize-4)}this._update(this._block);var T=this._hash();return F?T.toString(F):T},k.prototype._update=function(){throw new Error("_update must be implemented by subclass")},_.exports=k}}),aQ=S0({"node_modules/sha.js/sha.js"(N,_){var j=B0(),k=R$(),F=N0().Buffer,P=[1518500249,1859775393,-1894007588,-899497514],X=new Array(80);function C(){this.init(),this._w=X,k.call(this,64,56)}j(C,k),C.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function z(J){return J<<5|J>>>27}function T(J){return J<<30|J>>>2}function H(J,W,D,E){return J===0?W&D|~W&E:J===2?W&D|W&E|D&E:W^D^E}C.prototype._update=function(J){for(var W=this._w,D=this._a|0,E=this._b|0,R=this._c|0,M=this._d|0,v=this._e|0,q=0;q<16;++q)W[q]=J.readInt32BE(q*4);for(;q<80;++q)W[q]=W[q-3]^W[q-8]^W[q-14]^W[q-16];for(var g=0;g<80;++g){var B=~~(g/20),w=z(D)+H(B,E,R,M)+v+W[g]+P[B]|0;v=M,M=R,R=T(E),E=D,D=w}this._a=D+this._a|0,this._b=E+this._b|0,this._c=R+this._c|0,this._d=M+this._d|0,this._e=v+this._e|0},C.prototype._hash=function(){var J=F.allocUnsafe(20);return J.writeInt32BE(this._a|0,0),J.writeInt32BE(this._b|0,4),J.writeInt32BE(this._c|0,8),J.writeInt32BE(this._d|0,12),J.writeInt32BE(this._e|0,16),J},_.exports=C}}),eQ=S0({"node_modules/sha.js/sha1.js"(N,_){var j=B0(),k=R$(),F=N0().Buffer,P=[1518500249,1859775393,-1894007588,-899497514],X=new Array(80);function C(){this.init(),this._w=X,k.call(this,64,56)}j(C,k),C.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function z(W){return W<<1|W>>>31}function T(W){return W<<5|W>>>27}function H(W){return W<<30|W>>>2}function J(W,D,E,R){return W===0?D&E|~D&R:W===2?D&E|D&R|E&R:D^E^R}C.prototype._update=function(W){for(var D=this._w,E=this._a|0,R=this._b|0,M=this._c|0,v=this._d|0,q=this._e|0,g=0;g<16;++g)D[g]=W.readInt32BE(g*4);for(;g<80;++g)D[g]=z(D[g-3]^D[g-8]^D[g-14]^D[g-16]);for(var B=0;B<80;++B){var w=~~(B/20),f=T(E)+J(w,R,M,v)+q+D[B]+P[w]|0;q=v,v=M,M=H(R),R=E,E=f}this._a=E+this._a|0,this._b=R+this._b|0,this._c=M+this._c|0,this._d=v+this._d|0,this._e=q+this._e|0},C.prototype._hash=function(){var W=F.allocUnsafe(20);return W.writeInt32BE(this._a|0,0),W.writeInt32BE(this._b|0,4),W.writeInt32BE(this._c|0,8),W.writeInt32BE(this._d|0,12),W.writeInt32BE(this._e|0,16),W},_.exports=C}}),VQ=S0({"node_modules/sha.js/sha256.js"(N,_){var j=B0(),k=R$(),F=N0().Buffer,P=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],X=new Array(64);function C(){this.init(),this._w=X,k.call(this,64,56)}j(C,k),C.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function z(E,R,M){return M^E&(R^M)}function T(E,R,M){return E&R|M&(E|R)}function H(E){return(E>>>2|E<<30)^(E>>>13|E<<19)^(E>>>22|E<<10)}function J(E){return(E>>>6|E<<26)^(E>>>11|E<<21)^(E>>>25|E<<7)}function W(E){return(E>>>7|E<<25)^(E>>>18|E<<14)^E>>>3}function D(E){return(E>>>17|E<<15)^(E>>>19|E<<13)^E>>>10}C.prototype._update=function(E){for(var R=this._w,M=this._a|0,v=this._b|0,q=this._c|0,g=this._d|0,B=this._e|0,w=this._f|0,f=this._g|0,b=this._h|0,u=0;u<16;++u)R[u]=E.readInt32BE(u*4);for(;u<64;++u)R[u]=D(R[u-2])+R[u-7]+W(R[u-15])+R[u-16]|0;for(var Y0=0;Y0<64;++Y0){var p=b+J(B)+z(B,w,f)+P[Y0]+R[Y0]|0,v0=H(M)+T(M,v,q)|0;b=f,f=w,w=B,B=g+p|0,g=q,q=v,v=M,M=p+v0|0}this._a=M+this._a|0,this._b=v+this._b|0,this._c=q+this._c|0,this._d=g+this._d|0,this._e=B+this._e|0,this._f=w+this._f|0,this._g=f+this._g|0,this._h=b+this._h|0},C.prototype._hash=function(){var E=F.allocUnsafe(32);return E.writeInt32BE(this._a,0),E.writeInt32BE(this._b,4),E.writeInt32BE(this._c,8),E.writeInt32BE(this._d,12),E.writeInt32BE(this._e,16),E.writeInt32BE(this._f,20),E.writeInt32BE(this._g,24),E.writeInt32BE(this._h,28),E},_.exports=C}}),rQ=S0({"node_modules/sha.js/sha224.js"(N,_){var j=B0(),k=VQ(),F=R$(),P=N0().Buffer,X=new Array(64);function C(){this.init(),this._w=X,F.call(this,64,56)}j(C,k),C.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},C.prototype._hash=function(){var z=P.allocUnsafe(28);return z.writeInt32BE(this._a,0),z.writeInt32BE(this._b,4),z.writeInt32BE(this._c,8),z.writeInt32BE(this._d,12),z.writeInt32BE(this._e,16),z.writeInt32BE(this._f,20),z.writeInt32BE(this._g,24),z},_.exports=C}}),UQ=S0({"node_modules/sha.js/sha512.js"(N,_){var j=B0(),k=R$(),F=N0().Buffer,P=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],X=new Array(160);function C(){this.init(),this._w=X,k.call(this,128,112)}j(C,k),C.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function z(v,q,g){return g^v&(q^g)}function T(v,q,g){return v&q|g&(v|q)}function H(v,q){return(v>>>28|q<<4)^(q>>>2|v<<30)^(q>>>7|v<<25)}function J(v,q){return(v>>>14|q<<18)^(v>>>18|q<<14)^(q>>>9|v<<23)}function W(v,q){return(v>>>1|q<<31)^(v>>>8|q<<24)^v>>>7}function D(v,q){return(v>>>1|q<<31)^(v>>>8|q<<24)^(v>>>7|q<<25)}function E(v,q){return(v>>>19|q<<13)^(q>>>29|v<<3)^v>>>6}function R(v,q){return(v>>>19|q<<13)^(q>>>29|v<<3)^(v>>>6|q<<26)}function M(v,q){return v>>>0>>0?1:0}C.prototype._update=function(v){for(var q=this._w,g=this._ah|0,B=this._bh|0,w=this._ch|0,f=this._dh|0,b=this._eh|0,u=this._fh|0,Y0=this._gh|0,p=this._hh|0,v0=this._al|0,$=this._bl|0,Y=this._cl|0,G=this._dl|0,Z=this._el|0,V=this._fl|0,I=this._gl|0,O=this._hl|0,U=0;U<32;U+=2)q[U]=v.readInt32BE(U*4),q[U+1]=v.readInt32BE(U*4+4);for(;U<160;U+=2){var Q=q[U-30],K=q[U-30+1],L=W(Q,K),A=D(K,Q);Q=q[U-4],K=q[U-4+1];var S=E(Q,K),x=R(K,Q),y=q[U-14],c=q[U-14+1],q0=q[U-32],h=q[U-32+1],d=A+c|0,_0=L+y+M(d,A)|0;d=d+x|0,_0=_0+S+M(d,x)|0,d=d+h|0,_0=_0+q0+M(d,h)|0,q[U]=_0,q[U+1]=d}for(var l=0;l<160;l+=2){_0=q[l],d=q[l+1];var n=T(g,B,w),y0=T(v0,$,Y),t=H(g,v0),s=H(v0,g),w0=J(b,Z),m=J(Z,b),r=P[l],$$=P[l+1],i=z(b,u,Y0),e=z(Z,V,I),x0=O+m|0,o=p+w0+M(x0,O)|0;x0=x0+e|0,o=o+i+M(x0,e)|0,x0=x0+$$|0,o=o+r+M(x0,$$)|0,x0=x0+d|0,o=o+_0+M(x0,d)|0;var a=s+y0|0,p0=t+n+M(a,s)|0;p=Y0,O=I,Y0=u,I=V,u=b,V=Z,Z=G+x0|0,b=f+o+M(Z,G)|0,f=w,G=Y,w=B,Y=$,B=g,$=v0,v0=x0+a|0,g=o+p0+M(v0,x0)|0}this._al=this._al+v0|0,this._bl=this._bl+$|0,this._cl=this._cl+Y|0,this._dl=this._dl+G|0,this._el=this._el+Z|0,this._fl=this._fl+V|0,this._gl=this._gl+I|0,this._hl=this._hl+O|0,this._ah=this._ah+g+M(this._al,v0)|0,this._bh=this._bh+B+M(this._bl,$)|0,this._ch=this._ch+w+M(this._cl,Y)|0,this._dh=this._dh+f+M(this._dl,G)|0,this._eh=this._eh+b+M(this._el,Z)|0,this._fh=this._fh+u+M(this._fl,V)|0,this._gh=this._gh+Y0+M(this._gl,I)|0,this._hh=this._hh+p+M(this._hl,O)|0},C.prototype._hash=function(){var v=F.allocUnsafe(64);function q(g,B,w){v.writeInt32BE(g,w),v.writeInt32BE(B,w+4)}return q(this._ah,this._al,0),q(this._bh,this._bl,8),q(this._ch,this._cl,16),q(this._dh,this._dl,24),q(this._eh,this._el,32),q(this._fh,this._fl,40),q(this._gh,this._gl,48),q(this._hh,this._hl,56),v},_.exports=C}}),iQ=S0({"node_modules/sha.js/sha384.js"(N,_){var j=B0(),k=UQ(),F=R$(),P=N0().Buffer,X=new Array(160);function C(){this.init(),this._w=X,F.call(this,128,112)}j(C,k),C.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},C.prototype._hash=function(){var z=P.allocUnsafe(48);function T(H,J,W){z.writeInt32BE(H,W),z.writeInt32BE(J,W+4)}return T(this._ah,this._al,0),T(this._bh,this._bl,8),T(this._ch,this._cl,16),T(this._dh,this._dl,24),T(this._eh,this._el,32),T(this._fh,this._fl,40),z},_.exports=C}}),XQ=S0({"node_modules/sha.js/index.js"(j,_){var j=_.exports=function(k){k=k.toLowerCase();var F=j[k];if(!F)throw new Error(k+" is not supported (we accept pull requests)");return new F};j.sha=aQ(),j.sha1=eQ(),j.sha224=rQ(),j.sha256=VQ(),j.sha384=iQ(),j.sha512=UQ()}}),C$=S0({"node_modules/cipher-base/index.js"(N,_){var j=N0().Buffer,k=B0();function F(P){A$.Transform.call(this),this.hashMode=typeof P=="string",this.hashMode?this[P]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}k(F,A$.Transform),F.prototype.update=function(P,X,C){typeof P=="string"&&(P=j.from(P,X));var z=this._update(P);return this.hashMode?this:(C&&(z=this._toString(z,C)),z)},F.prototype.setAutoPadding=function(){},F.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},F.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},F.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},F.prototype._transform=function(P,X,C){var z;try{this.hashMode?this._update(P):this.push(this._update(P))}catch(T){z=T}finally{C(z)}},F.prototype._flush=function(P){var X;try{this.push(this.__final())}catch(C){X=C}P(X)},F.prototype._finalOrDigest=function(P){var X=this.__final()||j.alloc(0);return P&&(X=this._toString(X,P,!0)),X},F.prototype._toString=function(P,X,C){if(this._decoder||(this._decoder=new uQ(X),this._encoding=X),this._encoding!==X)throw new Error("can't switch encodings");var z=this._decoder.write(P);return C&&(z+=this._decoder.end()),z},_.exports=F}}),M$=S0({"node_modules/create-hash/browser.js"(N,_){const j=function P(X,C){this._options=C,this._hasher=new $Z(X,C),this._finalized=!1};j.prototype=Object.create(A$.Transform.prototype),j.prototype.update=function P(X,C){return this._checkFinalized(),this._hasher.update(X,C),this},j.prototype.digest=function P(X,C){return this._checkFinalized(),this._finalized=!0,this._hasher.digest(X,C)},j.prototype._checkFinalized=function P(){if(this._finalized){var X=new Error("Digest already called");throw X.code="ERR_CRYPTO_HASH_FINALIZED",X}},j.prototype.copy=function P(){const X=Object.create(j.prototype);return X._options=this._options,X._hasher=this._hasher.copy(),X._finalized=this._finalized,X};const k={__proto__:A$.Transform.prototype,...j.prototype,_transform(P,X,C){this.update(P,X),C&&C()},_flush(P){this.push(this.digest()),P()}},F=["_events","_eventsCount","_final","_maxListeners","_maxListeners","_read","_undestroy","_writableState","_write","_writev","addListener","asIndexedPairs","closed","compose","constructor","cork","destroy","destroyed","drop","emit","end","errored","eventNames","every","filter","find","flatMap","forEach","getMaxListeners","hasOwnProperty","isPaused","isPrototypeOf","iterator","listenerCount","listeners","map","off","on","once","pause","pipe","prependListener","prependOnceListener","propertyIsEnumerable","push","rawListeners","read","readable","readableAborted","readableBuffer","readableDidRead","readableEncoding","readableEnded","readableFlowing","readableHighWaterMark","readableLength","readableObjectMode","reduce","removeAllListeners","removeListener","resume","setDefaultEncoding","setEncoding","setMaxListeners","some","take","toArray","toLocaleString","toString","uncork","unpipe","unshift","valueOf","wrap","writable","writableBuffer","writableCorked","writableEnded","writableFinished","writableHighWaterMark","writableLength","writableNeedDrain","writableObjectMode","write"];for(let P of F)Object.defineProperty(j.prototype,P,{get(){return Object.setPrototypeOf(this,k),A$.Transform.call(this,this._options),this[P]},enumerable:!1,configurable:!0});_.exports=function P(X){return new j(X)},_.exports.createHash=_.exports,_.exports.Hash=j}}),$Y=S0({"node_modules/create-hmac/legacy.js"(N,_){var j=B0(),k=N0().Buffer,F=C$(),P=k.alloc(128),X=64;function C(z,T){F.call(this,"digest"),typeof T=="string"&&(T=k.from(T)),this._alg=z,this._key=T,T.length>X?T=z(T):T.lengthD){var E=J==="rmd160"?new C:z(J);W=E.update(W).digest()}else W.lengthj||F!==F)throw new TypeError("Bad key length")}}}),FQ=S0({"node_modules/pbkdf2/lib/default-encoding.js"(N,_){var j;global.process&&global.process.browser?j="utf-8":global.process&&global.process.version?(k=parseInt(process.version.split(".")[0].slice(1),10),j=k>=6?"utf-8":"binary"):j="utf-8";var k;_.exports=j}}),AQ=S0({"node_modules/pbkdf2/lib/to-buffer.js"(N,_){var j=N0().Buffer;_.exports=function(k,F,P){if(j.isBuffer(k))return k;if(typeof k=="string")return j.from(k,F);if(ArrayBuffer.isView(k))return j.from(k.buffer);throw new TypeError(P+" must be a string, a Buffer, a typed array or a DataView")}}}),WQ=S0({"node_modules/pbkdf2/lib/sync-browser.js"(N,_){var j=KQ(),k=GQ(),F=XQ(),P=N0().Buffer,X=JQ(),C=FQ(),z=AQ(),T=P.alloc(128),H={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function J(E,R,M){var v=W(E),q=E==="sha512"||E==="sha384"?128:64;R.length>q?R=v(R):R.length>>0},N.writeUInt32BE=function(F,P,X){F[0+X]=P>>>24,F[1+X]=P>>>16&255,F[2+X]=P>>>8&255,F[3+X]=P&255},N.ip=function(F,P,X,C){for(var z=0,T=0,H=6;H>=0;H-=2){for(var J=0;J<=24;J+=8)z<<=1,z|=P>>>J+H&1;for(var J=0;J<=24;J+=8)z<<=1,z|=F>>>J+H&1}for(var H=6;H>=0;H-=2){for(var J=1;J<=25;J+=8)T<<=1,T|=P>>>J+H&1;for(var J=1;J<=25;J+=8)T<<=1,T|=F>>>J+H&1}X[C+0]=z>>>0,X[C+1]=T>>>0},N.rip=function(F,P,X,C){for(var z=0,T=0,H=0;H<4;H++)for(var J=24;J>=0;J-=8)z<<=1,z|=P>>>J+H&1,z<<=1,z|=F>>>J+H&1;for(var H=4;H<8;H++)for(var J=24;J>=0;J-=8)T<<=1,T|=P>>>J+H&1,T<<=1,T|=F>>>J+H&1;X[C+0]=z>>>0,X[C+1]=T>>>0},N.pc1=function(F,P,X,C){for(var z=0,T=0,H=7;H>=5;H--){for(var J=0;J<=24;J+=8)z<<=1,z|=P>>J+H&1;for(var J=0;J<=24;J+=8)z<<=1,z|=F>>J+H&1}for(var J=0;J<=24;J+=8)z<<=1,z|=P>>J+H&1;for(var H=1;H<=3;H++){for(var J=0;J<=24;J+=8)T<<=1,T|=P>>J+H&1;for(var J=0;J<=24;J+=8)T<<=1,T|=F>>J+H&1}for(var J=0;J<=24;J+=8)T<<=1,T|=F>>J+H&1;X[C+0]=z>>>0,X[C+1]=T>>>0},N.r28shl=function(F,P){return F<>>28-P};var _=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];N.pc2=function(F,P,X,C){for(var z=0,T=0,H=_.length>>>1,J=0;J>>_[J]&1;for(var J=H;J<_.length;J++)T<<=1,T|=P>>>_[J]&1;X[C+0]=z>>>0,X[C+1]=T>>>0},N.expand=function(F,P,X){var C=0,z=0;C=(F&1)<<5|F>>>27;for(var T=23;T>=15;T-=4)C<<=6,C|=F>>>T&63;for(var T=11;T>=3;T-=4)z|=F>>>T&63,z<<=6;z|=(F&31)<<1|F>>>31,P[X+0]=C>>>0,P[X+1]=z>>>0};var j=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];N.substitute=function(F,P){for(var X=0,C=0;C<4;C++){var z=F>>>18-C*6&63,T=j[C*64+z];X<<=4,X|=T}for(var C=0;C<4;C++){var z=P>>>18-C*6&63,T=j[256+C*64+z];X<<=4,X|=T}return X>>>0};var k=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];N.permute=function(F){for(var P=0,X=0;X>>k[X]&1;return P>>>0},N.padSplit=function(F,P,X){for(var C=F.toString(2);C.length0;C--)P+=this._buffer(F,P),X+=this._flushBuffer(z,X);return P+=this._buffer(F,P),z},k.prototype.final=function(F){var P;F&&(P=this.update(F));var X;return this.type==="encrypt"?X=this._finalEncrypt():X=this._finalDecrypt(),P?P.concat(X):X},k.prototype._pad=function(F,P){if(P===0)return!1;for(;P>>1];J=F.r28shl(J,E),W=F.r28shl(W,E),F.pc2(J,W,T.keys,D)}},C.prototype._update=function(T,H,J,W){var D=this._desState,E=F.readUInt32BE(T,H),R=F.readUInt32BE(T,H+4);F.ip(E,R,D.tmp,0),E=D.tmp[0],R=D.tmp[1],this.type==="encrypt"?this._encrypt(D,E,R,D.tmp,0):this._decrypt(D,E,R,D.tmp,0),E=D.tmp[0],R=D.tmp[1],F.writeUInt32BE(J,E,W),F.writeUInt32BE(J,R,W+4)},C.prototype._pad=function(T,H){for(var J=T.length-H,W=H;W>>0,E=w}F.rip(R,E,W,D)},C.prototype._decrypt=function(T,H,J,W,D){for(var E=J,R=H,M=T.keys.length-2;M>=0;M-=2){var v=T.keys[M],q=T.keys[M+1];F.expand(E,T.tmp,0),v^=T.tmp[0],q^=T.tmp[1];var g=F.substitute(v,q),B=F.permute(g),w=E;E=(R^B)>>>0,R=w}F.rip(E,R,W,D)}}}),ZY=S0({"node_modules/des.js/lib/des/cbc.js"(N){var _=H$(),j=B0(),k={};function F(X){_.equal(X.length,8,"Invalid IV length"),this.iv=new Array(8);for(var C=0;C>z%8,F._prev=k(F._prev,X?J:W);return H}function k(F,P){var X=F.length,C=-1,z=_.allocUnsafe(F.length);for(F=_.concat([F,_.from([P])]);++C>7;return z}N.encrypt=function(F,P,X){for(var C=P.length,z=_.allocUnsafe(C),T=-1;++T>>24]^R[g>>>16&255]^M[B>>>8&255]^v[w&255]^H[p++],b=E[g>>>24]^R[B>>>16&255]^M[w>>>8&255]^v[q&255]^H[p++],u=E[B>>>24]^R[w>>>16&255]^M[q>>>8&255]^v[g&255]^H[p++],Y0=E[w>>>24]^R[q>>>16&255]^M[g>>>8&255]^v[B&255]^H[p++],q=f,g=b,B=u,w=Y0;return f=(W[q>>>24]<<24|W[g>>>16&255]<<16|W[B>>>8&255]<<8|W[w&255])^H[p++],b=(W[g>>>24]<<24|W[B>>>16&255]<<16|W[w>>>8&255]<<8|W[q&255])^H[p++],u=(W[B>>>24]<<24|W[w>>>16&255]<<16|W[q>>>8&255]<<8|W[g&255])^H[p++],Y0=(W[w>>>24]<<24|W[q>>>16&255]<<16|W[g>>>8&255]<<8|W[B&255])^H[p++],f=f>>>0,b=b>>>0,u=u>>>0,Y0=Y0>>>0,[f,b,u,Y0]}var X=[0,1,2,4,8,16,32,64,128,27,54],C=function(){for(var T=new Array(256),H=0;H<256;H++)H<128?T[H]=H<<1:T[H]=H<<1^283;for(var J=[],W=[],D=[[],[],[],[]],E=[[],[],[],[]],R=0,M=0,v=0;v<256;++v){var q=M^M<<1^M<<2^M<<3^M<<4;q=q>>>8^q&255^99,J[R]=q,W[q]=R;var g=T[R],B=T[g],w=T[B],f=T[q]*257^q*16843008;D[0][R]=f<<24|f>>>8,D[1][R]=f<<16|f>>>16,D[2][R]=f<<8|f>>>24,D[3][R]=f,f=w*16843009^B*65537^g*257^R*16843008,E[0][q]=f<<24|f>>>8,E[1][q]=f<<16|f>>>16,E[2][q]=f<<8|f>>>24,E[3][q]=f,R===0?R=M=1:(R=g^T[T[T[w^g]]],M^=T[T[M]])}return{SBOX:J,INV_SBOX:W,SUB_MIX:D,INV_SUB_MIX:E}}();function z(T){this._key=k(T),this._reset()}z.blockSize=16,z.keySize=32,z.prototype.blockSize=z.blockSize,z.prototype.keySize=z.keySize,z.prototype._reset=function(){for(var T=this._key,H=T.length,J=H+6,W=(J+1)*4,D=[],E=0;E>>24,R=C.SBOX[R>>>24]<<24|C.SBOX[R>>>16&255]<<16|C.SBOX[R>>>8&255]<<8|C.SBOX[R&255],R^=X[E/H|0]<<24):H>6&&E%H===4&&(R=C.SBOX[R>>>24]<<24|C.SBOX[R>>>16&255]<<16|C.SBOX[R>>>8&255]<<8|C.SBOX[R&255]),D[E]=D[E-H]^R}for(var M=[],v=0;v>>24]]^C.INV_SUB_MIX[1][C.SBOX[g>>>16&255]]^C.INV_SUB_MIX[2][C.SBOX[g>>>8&255]]^C.INV_SUB_MIX[3][C.SBOX[g&255]]}this._nRounds=J,this._keySchedule=D,this._invKeySchedule=M},z.prototype.encryptBlockRaw=function(T){return T=k(T),P(T,this._keySchedule,C.SUB_MIX,C.SBOX,this._nRounds)},z.prototype.encryptBlock=function(T){var H=this.encryptBlockRaw(T),J=j.allocUnsafe(16);return J.writeUInt32BE(H[0],0),J.writeUInt32BE(H[1],4),J.writeUInt32BE(H[2],8),J.writeUInt32BE(H[3],12),J},z.prototype.decryptBlock=function(T){T=k(T);var H=T[1];T[1]=T[3],T[3]=H;var J=P(T,this._invKeySchedule,C.INV_SUB_MIX,C.INV_SBOX,this._nRounds),W=j.allocUnsafe(16);return W.writeUInt32BE(J[0],0),W.writeUInt32BE(J[3],4),W.writeUInt32BE(J[2],8),W.writeUInt32BE(J[1],12),W},z.prototype.scrub=function(){F(this._keySchedule),F(this._invKeySchedule),F(this._key)},_.exports.AES=z}}),AY=S0({"node_modules/browserify-aes/ghash.js"(N,_){var j=N0().Buffer,k=j.alloc(16,0);function F(C){return[C.readUInt32BE(0),C.readUInt32BE(4),C.readUInt32BE(8),C.readUInt32BE(12)]}function P(C){var z=j.allocUnsafe(16);return z.writeUInt32BE(C[0]>>>0,0),z.writeUInt32BE(C[1]>>>0,4),z.writeUInt32BE(C[2]>>>0,8),z.writeUInt32BE(C[3]>>>0,12),z}function X(C){this.h=C,this.state=j.alloc(16,0),this.cache=j.allocUnsafe(0)}X.prototype.ghash=function(C){for(var z=-1;++z0;T--)C[T]=C[T]>>>1|(C[T-1]&1)<<31;C[0]=C[0]>>>1,J&&(C[0]=C[0]^225<<24)}this.state=P(z)},X.prototype.update=function(C){this.cache=j.concat([this.cache,C]);for(var z;this.cache.length>=16;)z=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(z)},X.prototype.final=function(C,z){return this.cache.length&&this.ghash(j.concat([this.cache,k],16)),this.ghash(P([0,C,0,z])),this.state},_.exports=X}}),LQ=S0({"node_modules/browserify-aes/authCipher.js"(N,_){var j=j$(),k=N0().Buffer,F=C$(),P=B0(),X=AY(),C=S$(),z=DQ();function T(W,D){var E=0;W.length!==D.length&&E++;for(var R=Math.min(W.length,D.length),M=0;M0||z>0;){var D=new k;D.update(W),D.update(P),X&&D.update(X),W=D.digest();var E=0;if(T>0){var R=H.length-T;E=Math.min(T,W.length),W.copy(H,R,0,E),T-=E}if(E0){var M=J.length-z,v=Math.min(z,W.length-E);W.copy(J,M,E,E+v),z-=v}}return W.fill(0),{key:H,iv:J}}_.exports=F}}),WY=S0({"node_modules/browserify-aes/encrypter.js"(N){var _=p$(),j=LQ(),k=N0().Buffer,F=RQ(),P=C$(),X=j$(),C=k$(),z=B0();function T(E,R,M){P.call(this),this._cache=new J,this._cipher=new X.AES(R),this._prev=k.from(M),this._mode=E,this._autopadding=!0}z(T,P),T.prototype._update=function(E){this._cache.add(E);for(var R,M,v=[];R=this._cache.get();)M=this._mode.encrypt(this,R),v.push(M);return k.concat(v)};var H=k.alloc(16,16);T.prototype._final=function(){var E=this._cache.flush();if(this._autopadding)return E=this._mode.encrypt(this,E),this._cipher.scrub(),E;if(!E.equals(H))throw this._cipher.scrub(),new Error("data not multiple of block length")},T.prototype.setAutoPadding=function(E){return this._autopadding=!!E,this};function J(){this.cache=k.allocUnsafe(0)}J.prototype.add=function(E){this.cache=k.concat([this.cache,E])},J.prototype.get=function(){if(this.cache.length>15){var E=this.cache.slice(0,16);return this.cache=this.cache.slice(16),E}return null},J.prototype.flush=function(){for(var E=16-this.cache.length,R=k.allocUnsafe(E),M=-1;++M16)return R=this.cache.slice(0,16),this.cache=this.cache.slice(16),R}else if(this.cache.length>=16)return R=this.cache.slice(0,16),this.cache=this.cache.slice(16),R;return null},H.prototype.flush=function(){if(this.cache.length)return this.cache};function J(E){var R=E[15];if(R<1||R>16)throw new Error("unable to decrypt data");for(var M=-1;++M0?$:Y},X.min=function($,Y){return $.cmp(Y)<0?$:Y},X.prototype._init=function($,Y,G){if(typeof $=="number")return this._initNumber($,Y,G);if(typeof $=="object")return this._initArray($,Y,G);Y==="hex"&&(Y=16),F(Y===(Y|0)&&Y>=2&&Y<=36),$=$.toString().replace(/\s+/g,"");var Z=0;$[0]==="-"&&(Z++,this.negative=1),Z<$.length&&(Y===16?this._parseHex($,Z,G):(this._parseBase($,Y,Z),G==="le"&&this._initArray(this.toArray(),Y,G)))},X.prototype._initNumber=function($,Y,G){$<0&&(this.negative=1,$=-$),$<67108864?(this.words=[$&67108863],this.length=1):$<4503599627370496?(this.words=[$&67108863,$/67108864&67108863],this.length=2):(F($<9007199254740992),this.words=[$&67108863,$/67108864&67108863,1],this.length=3),G==="le"&&this._initArray(this.toArray(),Y,G)},X.prototype._initArray=function($,Y,G){if(F(typeof $.length=="number"),$.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil($.length/3),this.words=new Array(this.length);for(var Z=0;Z=0;Z-=3)I=$[Z]|$[Z-1]<<8|$[Z-2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);else if(G==="le")for(Z=0,V=0;Z<$.length;Z+=3)I=$[Z]|$[Z+1]<<8|$[Z+2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);return this.strip()};function z($,Y){var G=$.charCodeAt(Y);return G>=65&&G<=70?G-55:G>=97&&G<=102?G-87:G-48&15}function T($,Y,G){var Z=z($,G);return G-1>=Y&&(Z|=z($,G-1)<<4),Z}X.prototype._parseHex=function($,Y,G){this.length=Math.ceil(($.length-Y)/6),this.words=new Array(this.length);for(var Z=0;Z=Y;Z-=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8;else{var U=$.length-Y;for(Z=U%2===0?Y+1:Y;Z<$.length;Z+=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8}this.strip()};function H($,Y,G,Z){for(var V=0,I=Math.min($.length,G),O=Y;O=49?V+=U-49+10:U>=17?V+=U-17+10:V+=U}return V}X.prototype._parseBase=function($,Y,G){this.words=[0],this.length=1;for(var Z=0,V=1;V<=67108863;V*=Y)Z++;Z--,V=V/Y|0;for(var I=$.length-G,O=I%Z,U=Math.min(I,I-O)+G,Q=0,K=G;K1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},X.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},X.prototype.inspect=function(){return(this.red?""};var J=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],W=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],D=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];X.prototype.toString=function($,Y){$=$||10,Y=Y|0||1;var G;if($===16||$==="hex"){G="";for(var Z=0,V=0,I=0;I>>24-Z&16777215,V!==0||I!==this.length-1?G=J[6-U.length]+U+G:G=U+G,Z+=2,Z>=26&&(Z-=26,I--)}for(V!==0&&(G=V.toString(16)+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}if($===($|0)&&$>=2&&$<=36){var Q=W[$],K=D[$];G="";var L=this.clone();for(L.negative=0;!L.isZero();){var A=L.modn(K).toString($);L=L.idivn(K),L.isZero()?G=A+G:G=J[Q-A.length]+A+G}for(this.isZero()&&(G="0"+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}F(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var $=this.words[0];return this.length===2?$+=this.words[1]*67108864:this.length===3&&this.words[2]===1?$+=4503599627370496+this.words[1]*67108864:this.length>2&&F(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-$:$},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function($,Y){return F(typeof C<"u"),this.toArrayLike(C,$,Y)},X.prototype.toArray=function($,Y){return this.toArrayLike(Array,$,Y)},X.prototype.toArrayLike=function($,Y,G){var Z=this.byteLength(),V=G||Math.max(1,Z);F(Z<=V,"byte array longer than desired length"),F(V>0,"Requested array length <= 0"),this.strip();var I=Y==="le",O=new $(V),U,Q,K=this.clone();if(I){for(Q=0;!K.isZero();Q++)U=K.andln(255),K.iushrn(8),O[Q]=U;for(;Q=4096&&(G+=13,Y>>>=13),Y>=64&&(G+=7,Y>>>=7),Y>=8&&(G+=4,Y>>>=4),Y>=2&&(G+=2,Y>>>=2),G+Y},X.prototype._zeroBits=function($){if($===0)return 26;var Y=$,G=0;return(Y&8191)===0&&(G+=13,Y>>>=13),(Y&127)===0&&(G+=7,Y>>>=7),(Y&15)===0&&(G+=4,Y>>>=4),(Y&3)===0&&(G+=2,Y>>>=2),(Y&1)===0&&G++,G},X.prototype.bitLength=function(){var $=this.words[this.length-1],Y=this._countBits($);return(this.length-1)*26+Y};function E($){for(var Y=new Array($.bitLength()),G=0;G>>V}return Y}X.prototype.zeroBits=function(){if(this.isZero())return 0;for(var $=0,Y=0;Y$.length?this.clone().ior($):$.clone().ior(this)},X.prototype.uor=function($){return this.length>$.length?this.clone().iuor($):$.clone().iuor(this)},X.prototype.iuand=function($){var Y;this.length>$.length?Y=$:Y=this;for(var G=0;G$.length?this.clone().iand($):$.clone().iand(this)},X.prototype.uand=function($){return this.length>$.length?this.clone().iuand($):$.clone().iuand(this)},X.prototype.iuxor=function($){var Y,G;this.length>$.length?(Y=this,G=$):(Y=$,G=this);for(var Z=0;Z$.length?this.clone().ixor($):$.clone().ixor(this)},X.prototype.uxor=function($){return this.length>$.length?this.clone().iuxor($):$.clone().iuxor(this)},X.prototype.inotn=function($){F(typeof $=="number"&&$>=0);var Y=Math.ceil($/26)|0,G=$%26;this._expand(Y),G>0&&Y--;for(var Z=0;Z0&&(this.words[Z]=~this.words[Z]&67108863>>26-G),this.strip()},X.prototype.notn=function($){return this.clone().inotn($)},X.prototype.setn=function($,Y){F(typeof $=="number"&&$>=0);var G=$/26|0,Z=$%26;return this._expand(G+1),Y?this.words[G]=this.words[G]|1<$.length?(G=this,Z=$):(G=$,Z=this);for(var V=0,I=0;I>>26;for(;V!==0&&I>>26;if(this.length=G.length,V!==0)this.words[this.length]=V,this.length++;else if(G!==this)for(;I$.length?this.clone().iadd($):$.clone().iadd(this)},X.prototype.isub=function($){if($.negative!==0){$.negative=0;var Y=this.iadd($);return $.negative=1,Y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd($),this.negative=1,this._normSign();var G=this.cmp($);if(G===0)return this.negative=0,this.length=1,this.words[0]=0,this;var Z,V;G>0?(Z=this,V=$):(Z=$,V=this);for(var I=0,O=0;O>26,this.words[O]=Y&67108863;for(;I!==0&&O>26,this.words[O]=Y&67108863;if(I===0&&O>>26,A=Q&67108863,S=Math.min(K,Y.length-1),x=Math.max(0,K-$.length+1);x<=S;x++){var y=K-x|0;V=$.words[y]|0,I=Y.words[x]|0,O=V*I+A,L+=O/67108864|0,A=O&67108863}G.words[K]=A|0,Q=L|0}return Q!==0?G.words[K]=Q|0:G.length--,G.strip()}var M=function($,Y,G){var Z=$.words,V=Y.words,I=G.words,O=0,U,Q,K,L=Z[0]|0,A=L&8191,S=L>>>13,x=Z[1]|0,y=x&8191,c=x>>>13,q0=Z[2]|0,h=q0&8191,d=q0>>>13,_0=Z[3]|0,l=_0&8191,n=_0>>>13,y0=Z[4]|0,t=y0&8191,s=y0>>>13,w0=Z[5]|0,m=w0&8191,r=w0>>>13,$$=Z[6]|0,i=$$&8191,e=$$>>>13,x0=Z[7]|0,o=x0&8191,a=x0>>>13,p0=Z[8]|0,$0=p0&8191,Q0=p0>>>13,Y$=Z[9]|0,Z0=Y$&8191,G0=Y$>>>13,Z$=V[0]|0,V0=Z$&8191,U0=Z$>>>13,G$=V[1]|0,X0=G$&8191,K0=G$>>>13,V$=V[2]|0,I0=V$&8191,O0=V$>>>13,U$=V[3]|0,J0=U$&8191,F0=U$>>>13,X$=V[4]|0,A0=X$&8191,W0=X$>>>13,K$=V[5]|0,H0=K$&8191,E0=K$>>>13,I$=V[6]|0,T0=I$&8191,D0=I$>>>13,O$=V[7]|0,C0=O$&8191,L0=O$>>>13,J$=V[8]|0,R0=J$&8191,z0=J$>>>13,F$=V[9]|0,P0=F$&8191,M0=F$>>>13;G.negative=$.negative^Y.negative,G.length=19,U=Math.imul(A,V0),Q=Math.imul(A,U0),Q=Q+Math.imul(S,V0)|0,K=Math.imul(S,U0);var Q$=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(Q$>>>26)|0,Q$&=67108863,U=Math.imul(y,V0),Q=Math.imul(y,U0),Q=Q+Math.imul(c,V0)|0,K=Math.imul(c,U0),U=U+Math.imul(A,X0)|0,Q=Q+Math.imul(A,K0)|0,Q=Q+Math.imul(S,X0)|0,K=K+Math.imul(S,K0)|0;var k0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(k0>>>26)|0,k0&=67108863,U=Math.imul(h,V0),Q=Math.imul(h,U0),Q=Q+Math.imul(d,V0)|0,K=Math.imul(d,U0),U=U+Math.imul(y,X0)|0,Q=Q+Math.imul(y,K0)|0,Q=Q+Math.imul(c,X0)|0,K=K+Math.imul(c,K0)|0,U=U+Math.imul(A,I0)|0,Q=Q+Math.imul(A,O0)|0,Q=Q+Math.imul(S,I0)|0,K=K+Math.imul(S,O0)|0;var g0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(g0>>>26)|0,g0&=67108863,U=Math.imul(l,V0),Q=Math.imul(l,U0),Q=Q+Math.imul(n,V0)|0,K=Math.imul(n,U0),U=U+Math.imul(h,X0)|0,Q=Q+Math.imul(h,K0)|0,Q=Q+Math.imul(d,X0)|0,K=K+Math.imul(d,K0)|0,U=U+Math.imul(y,I0)|0,Q=Q+Math.imul(y,O0)|0,Q=Q+Math.imul(c,I0)|0,K=K+Math.imul(c,O0)|0,U=U+Math.imul(A,J0)|0,Q=Q+Math.imul(A,F0)|0,Q=Q+Math.imul(S,J0)|0,K=K+Math.imul(S,F0)|0;var f0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(f0>>>26)|0,f0&=67108863,U=Math.imul(t,V0),Q=Math.imul(t,U0),Q=Q+Math.imul(s,V0)|0,K=Math.imul(s,U0),U=U+Math.imul(l,X0)|0,Q=Q+Math.imul(l,K0)|0,Q=Q+Math.imul(n,X0)|0,K=K+Math.imul(n,K0)|0,U=U+Math.imul(h,I0)|0,Q=Q+Math.imul(h,O0)|0,Q=Q+Math.imul(d,I0)|0,K=K+Math.imul(d,O0)|0,U=U+Math.imul(y,J0)|0,Q=Q+Math.imul(y,F0)|0,Q=Q+Math.imul(c,J0)|0,K=K+Math.imul(c,F0)|0,U=U+Math.imul(A,A0)|0,Q=Q+Math.imul(A,W0)|0,Q=Q+Math.imul(S,A0)|0,K=K+Math.imul(S,W0)|0;var c0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(c0>>>26)|0,c0&=67108863,U=Math.imul(m,V0),Q=Math.imul(m,U0),Q=Q+Math.imul(r,V0)|0,K=Math.imul(r,U0),U=U+Math.imul(t,X0)|0,Q=Q+Math.imul(t,K0)|0,Q=Q+Math.imul(s,X0)|0,K=K+Math.imul(s,K0)|0,U=U+Math.imul(l,I0)|0,Q=Q+Math.imul(l,O0)|0,Q=Q+Math.imul(n,I0)|0,K=K+Math.imul(n,O0)|0,U=U+Math.imul(h,J0)|0,Q=Q+Math.imul(h,F0)|0,Q=Q+Math.imul(d,J0)|0,K=K+Math.imul(d,F0)|0,U=U+Math.imul(y,A0)|0,Q=Q+Math.imul(y,W0)|0,Q=Q+Math.imul(c,A0)|0,K=K+Math.imul(c,W0)|0,U=U+Math.imul(A,H0)|0,Q=Q+Math.imul(A,E0)|0,Q=Q+Math.imul(S,H0)|0,K=K+Math.imul(S,E0)|0;var h0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(h0>>>26)|0,h0&=67108863,U=Math.imul(i,V0),Q=Math.imul(i,U0),Q=Q+Math.imul(e,V0)|0,K=Math.imul(e,U0),U=U+Math.imul(m,X0)|0,Q=Q+Math.imul(m,K0)|0,Q=Q+Math.imul(r,X0)|0,K=K+Math.imul(r,K0)|0,U=U+Math.imul(t,I0)|0,Q=Q+Math.imul(t,O0)|0,Q=Q+Math.imul(s,I0)|0,K=K+Math.imul(s,O0)|0,U=U+Math.imul(l,J0)|0,Q=Q+Math.imul(l,F0)|0,Q=Q+Math.imul(n,J0)|0,K=K+Math.imul(n,F0)|0,U=U+Math.imul(h,A0)|0,Q=Q+Math.imul(h,W0)|0,Q=Q+Math.imul(d,A0)|0,K=K+Math.imul(d,W0)|0,U=U+Math.imul(y,H0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(c,H0)|0,K=K+Math.imul(c,E0)|0,U=U+Math.imul(A,T0)|0,Q=Q+Math.imul(A,D0)|0,Q=Q+Math.imul(S,T0)|0,K=K+Math.imul(S,D0)|0;var d0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(d0>>>26)|0,d0&=67108863,U=Math.imul(o,V0),Q=Math.imul(o,U0),Q=Q+Math.imul(a,V0)|0,K=Math.imul(a,U0),U=U+Math.imul(i,X0)|0,Q=Q+Math.imul(i,K0)|0,Q=Q+Math.imul(e,X0)|0,K=K+Math.imul(e,K0)|0,U=U+Math.imul(m,I0)|0,Q=Q+Math.imul(m,O0)|0,Q=Q+Math.imul(r,I0)|0,K=K+Math.imul(r,O0)|0,U=U+Math.imul(t,J0)|0,Q=Q+Math.imul(t,F0)|0,Q=Q+Math.imul(s,J0)|0,K=K+Math.imul(s,F0)|0,U=U+Math.imul(l,A0)|0,Q=Q+Math.imul(l,W0)|0,Q=Q+Math.imul(n,A0)|0,K=K+Math.imul(n,W0)|0,U=U+Math.imul(h,H0)|0,Q=Q+Math.imul(h,E0)|0,Q=Q+Math.imul(d,H0)|0,K=K+Math.imul(d,E0)|0,U=U+Math.imul(y,T0)|0,Q=Q+Math.imul(y,D0)|0,Q=Q+Math.imul(c,T0)|0,K=K+Math.imul(c,D0)|0,U=U+Math.imul(A,C0)|0,Q=Q+Math.imul(A,L0)|0,Q=Q+Math.imul(S,C0)|0,K=K+Math.imul(S,L0)|0;var b0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(b0>>>26)|0,b0&=67108863,U=Math.imul($0,V0),Q=Math.imul($0,U0),Q=Q+Math.imul(Q0,V0)|0,K=Math.imul(Q0,U0),U=U+Math.imul(o,X0)|0,Q=Q+Math.imul(o,K0)|0,Q=Q+Math.imul(a,X0)|0,K=K+Math.imul(a,K0)|0,U=U+Math.imul(i,I0)|0,Q=Q+Math.imul(i,O0)|0,Q=Q+Math.imul(e,I0)|0,K=K+Math.imul(e,O0)|0,U=U+Math.imul(m,J0)|0,Q=Q+Math.imul(m,F0)|0,Q=Q+Math.imul(r,J0)|0,K=K+Math.imul(r,F0)|0,U=U+Math.imul(t,A0)|0,Q=Q+Math.imul(t,W0)|0,Q=Q+Math.imul(s,A0)|0,K=K+Math.imul(s,W0)|0,U=U+Math.imul(l,H0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(n,H0)|0,K=K+Math.imul(n,E0)|0,U=U+Math.imul(h,T0)|0,Q=Q+Math.imul(h,D0)|0,Q=Q+Math.imul(d,T0)|0,K=K+Math.imul(d,D0)|0,U=U+Math.imul(y,C0)|0,Q=Q+Math.imul(y,L0)|0,Q=Q+Math.imul(c,C0)|0,K=K+Math.imul(c,L0)|0,U=U+Math.imul(A,R0)|0,Q=Q+Math.imul(A,z0)|0,Q=Q+Math.imul(S,R0)|0,K=K+Math.imul(S,z0)|0;var l0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(l0>>>26)|0,l0&=67108863,U=Math.imul(Z0,V0),Q=Math.imul(Z0,U0),Q=Q+Math.imul(G0,V0)|0,K=Math.imul(G0,U0),U=U+Math.imul($0,X0)|0,Q=Q+Math.imul($0,K0)|0,Q=Q+Math.imul(Q0,X0)|0,K=K+Math.imul(Q0,K0)|0,U=U+Math.imul(o,I0)|0,Q=Q+Math.imul(o,O0)|0,Q=Q+Math.imul(a,I0)|0,K=K+Math.imul(a,O0)|0,U=U+Math.imul(i,J0)|0,Q=Q+Math.imul(i,F0)|0,Q=Q+Math.imul(e,J0)|0,K=K+Math.imul(e,F0)|0,U=U+Math.imul(m,A0)|0,Q=Q+Math.imul(m,W0)|0,Q=Q+Math.imul(r,A0)|0,K=K+Math.imul(r,W0)|0,U=U+Math.imul(t,H0)|0,Q=Q+Math.imul(t,E0)|0,Q=Q+Math.imul(s,H0)|0,K=K+Math.imul(s,E0)|0,U=U+Math.imul(l,T0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(n,T0)|0,K=K+Math.imul(n,D0)|0,U=U+Math.imul(h,C0)|0,Q=Q+Math.imul(h,L0)|0,Q=Q+Math.imul(d,C0)|0,K=K+Math.imul(d,L0)|0,U=U+Math.imul(y,R0)|0,Q=Q+Math.imul(y,z0)|0,Q=Q+Math.imul(c,R0)|0,K=K+Math.imul(c,z0)|0,U=U+Math.imul(A,P0)|0,Q=Q+Math.imul(A,M0)|0,Q=Q+Math.imul(S,P0)|0,K=K+Math.imul(S,M0)|0;var o0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(o0>>>26)|0,o0&=67108863,U=Math.imul(Z0,X0),Q=Math.imul(Z0,K0),Q=Q+Math.imul(G0,X0)|0,K=Math.imul(G0,K0),U=U+Math.imul($0,I0)|0,Q=Q+Math.imul($0,O0)|0,Q=Q+Math.imul(Q0,I0)|0,K=K+Math.imul(Q0,O0)|0,U=U+Math.imul(o,J0)|0,Q=Q+Math.imul(o,F0)|0,Q=Q+Math.imul(a,J0)|0,K=K+Math.imul(a,F0)|0,U=U+Math.imul(i,A0)|0,Q=Q+Math.imul(i,W0)|0,Q=Q+Math.imul(e,A0)|0,K=K+Math.imul(e,W0)|0,U=U+Math.imul(m,H0)|0,Q=Q+Math.imul(m,E0)|0,Q=Q+Math.imul(r,H0)|0,K=K+Math.imul(r,E0)|0,U=U+Math.imul(t,T0)|0,Q=Q+Math.imul(t,D0)|0,Q=Q+Math.imul(s,T0)|0,K=K+Math.imul(s,D0)|0,U=U+Math.imul(l,C0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(n,C0)|0,K=K+Math.imul(n,L0)|0,U=U+Math.imul(h,R0)|0,Q=Q+Math.imul(h,z0)|0,Q=Q+Math.imul(d,R0)|0,K=K+Math.imul(d,z0)|0,U=U+Math.imul(y,P0)|0,Q=Q+Math.imul(y,M0)|0,Q=Q+Math.imul(c,P0)|0,K=K+Math.imul(c,M0)|0;var u0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(u0>>>26)|0,u0&=67108863,U=Math.imul(Z0,I0),Q=Math.imul(Z0,O0),Q=Q+Math.imul(G0,I0)|0,K=Math.imul(G0,O0),U=U+Math.imul($0,J0)|0,Q=Q+Math.imul($0,F0)|0,Q=Q+Math.imul(Q0,J0)|0,K=K+Math.imul(Q0,F0)|0,U=U+Math.imul(o,A0)|0,Q=Q+Math.imul(o,W0)|0,Q=Q+Math.imul(a,A0)|0,K=K+Math.imul(a,W0)|0,U=U+Math.imul(i,H0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,H0)|0,K=K+Math.imul(e,E0)|0,U=U+Math.imul(m,T0)|0,Q=Q+Math.imul(m,D0)|0,Q=Q+Math.imul(r,T0)|0,K=K+Math.imul(r,D0)|0,U=U+Math.imul(t,C0)|0,Q=Q+Math.imul(t,L0)|0,Q=Q+Math.imul(s,C0)|0,K=K+Math.imul(s,L0)|0,U=U+Math.imul(l,R0)|0,Q=Q+Math.imul(l,z0)|0,Q=Q+Math.imul(n,R0)|0,K=K+Math.imul(n,z0)|0,U=U+Math.imul(h,P0)|0,Q=Q+Math.imul(h,M0)|0,Q=Q+Math.imul(d,P0)|0,K=K+Math.imul(d,M0)|0;var n0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(n0>>>26)|0,n0&=67108863,U=Math.imul(Z0,J0),Q=Math.imul(Z0,F0),Q=Q+Math.imul(G0,J0)|0,K=Math.imul(G0,F0),U=U+Math.imul($0,A0)|0,Q=Q+Math.imul($0,W0)|0,Q=Q+Math.imul(Q0,A0)|0,K=K+Math.imul(Q0,W0)|0,U=U+Math.imul(o,H0)|0,Q=Q+Math.imul(o,E0)|0,Q=Q+Math.imul(a,H0)|0,K=K+Math.imul(a,E0)|0,U=U+Math.imul(i,T0)|0,Q=Q+Math.imul(i,D0)|0,Q=Q+Math.imul(e,T0)|0,K=K+Math.imul(e,D0)|0,U=U+Math.imul(m,C0)|0,Q=Q+Math.imul(m,L0)|0,Q=Q+Math.imul(r,C0)|0,K=K+Math.imul(r,L0)|0,U=U+Math.imul(t,R0)|0,Q=Q+Math.imul(t,z0)|0,Q=Q+Math.imul(s,R0)|0,K=K+Math.imul(s,z0)|0,U=U+Math.imul(l,P0)|0,Q=Q+Math.imul(l,M0)|0,Q=Q+Math.imul(n,P0)|0,K=K+Math.imul(n,M0)|0;var s0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(s0>>>26)|0,s0&=67108863,U=Math.imul(Z0,A0),Q=Math.imul(Z0,W0),Q=Q+Math.imul(G0,A0)|0,K=Math.imul(G0,W0),U=U+Math.imul($0,H0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Q0,H0)|0,K=K+Math.imul(Q0,E0)|0,U=U+Math.imul(o,T0)|0,Q=Q+Math.imul(o,D0)|0,Q=Q+Math.imul(a,T0)|0,K=K+Math.imul(a,D0)|0,U=U+Math.imul(i,C0)|0,Q=Q+Math.imul(i,L0)|0,Q=Q+Math.imul(e,C0)|0,K=K+Math.imul(e,L0)|0,U=U+Math.imul(m,R0)|0,Q=Q+Math.imul(m,z0)|0,Q=Q+Math.imul(r,R0)|0,K=K+Math.imul(r,z0)|0,U=U+Math.imul(t,P0)|0,Q=Q+Math.imul(t,M0)|0,Q=Q+Math.imul(s,P0)|0,K=K+Math.imul(s,M0)|0;var t0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(t0>>>26)|0,t0&=67108863,U=Math.imul(Z0,H0),Q=Math.imul(Z0,E0),Q=Q+Math.imul(G0,H0)|0,K=Math.imul(G0,E0),U=U+Math.imul($0,T0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Q0,T0)|0,K=K+Math.imul(Q0,D0)|0,U=U+Math.imul(o,C0)|0,Q=Q+Math.imul(o,L0)|0,Q=Q+Math.imul(a,C0)|0,K=K+Math.imul(a,L0)|0,U=U+Math.imul(i,R0)|0,Q=Q+Math.imul(i,z0)|0,Q=Q+Math.imul(e,R0)|0,K=K+Math.imul(e,z0)|0,U=U+Math.imul(m,P0)|0,Q=Q+Math.imul(m,M0)|0,Q=Q+Math.imul(r,P0)|0,K=K+Math.imul(r,M0)|0;var m0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(m0>>>26)|0,m0&=67108863,U=Math.imul(Z0,T0),Q=Math.imul(Z0,D0),Q=Q+Math.imul(G0,T0)|0,K=Math.imul(G0,D0),U=U+Math.imul($0,C0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Q0,C0)|0,K=K+Math.imul(Q0,L0)|0,U=U+Math.imul(o,R0)|0,Q=Q+Math.imul(o,z0)|0,Q=Q+Math.imul(a,R0)|0,K=K+Math.imul(a,z0)|0,U=U+Math.imul(i,P0)|0,Q=Q+Math.imul(i,M0)|0,Q=Q+Math.imul(e,P0)|0,K=K+Math.imul(e,M0)|0;var a0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(a0>>>26)|0,a0&=67108863,U=Math.imul(Z0,C0),Q=Math.imul(Z0,L0),Q=Q+Math.imul(G0,C0)|0,K=Math.imul(G0,L0),U=U+Math.imul($0,R0)|0,Q=Q+Math.imul($0,z0)|0,Q=Q+Math.imul(Q0,R0)|0,K=K+Math.imul(Q0,z0)|0,U=U+Math.imul(o,P0)|0,Q=Q+Math.imul(o,M0)|0,Q=Q+Math.imul(a,P0)|0,K=K+Math.imul(a,M0)|0;var e0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(e0>>>26)|0,e0&=67108863,U=Math.imul(Z0,R0),Q=Math.imul(Z0,z0),Q=Q+Math.imul(G0,R0)|0,K=Math.imul(G0,z0),U=U+Math.imul($0,P0)|0,Q=Q+Math.imul($0,M0)|0,Q=Q+Math.imul(Q0,P0)|0,K=K+Math.imul(Q0,M0)|0;var r0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(r0>>>26)|0,r0&=67108863,U=Math.imul(Z0,P0),Q=Math.imul(Z0,M0),Q=Q+Math.imul(G0,P0)|0,K=Math.imul(G0,M0);var i0=(O+U|0)+((Q&8191)<<13)|0;return O=(K+(Q>>>13)|0)+(i0>>>26)|0,i0&=67108863,I[0]=Q$,I[1]=k0,I[2]=g0,I[3]=f0,I[4]=c0,I[5]=h0,I[6]=d0,I[7]=b0,I[8]=l0,I[9]=o0,I[10]=u0,I[11]=n0,I[12]=s0,I[13]=t0,I[14]=m0,I[15]=a0,I[16]=e0,I[17]=r0,I[18]=i0,O!==0&&(I[19]=O,G.length++),G};Math.imul||(M=R);function v($,Y,G){G.negative=Y.negative^$.negative,G.length=$.length+Y.length;for(var Z=0,V=0,I=0;I>>26)|0,V+=O>>>26,O&=67108863}G.words[I]=U,Z=O,O=V}return Z!==0?G.words[I]=Z:G.length--,G.strip()}function q($,Y,G){var Z=new g;return Z.mulp($,Y,G)}X.prototype.mulTo=function($,Y){var G,Z=this.length+$.length;return this.length===10&&$.length===10?G=M(this,$,Y):Z<63?G=R(this,$,Y):Z<1024?G=v(this,$,Y):G=q(this,$,Y),G};function g($,Y){this.x=$,this.y=Y}g.prototype.makeRBT=function($){for(var Y=new Array($),G=X.prototype._countBits($)-1,Z=0;Z<$;Z++)Y[Z]=this.revBin(Z,G,$);return Y},g.prototype.revBin=function($,Y,G){if($===0||$===G-1)return $;for(var Z=0,V=0;V>=1;return Z},g.prototype.permute=function($,Y,G,Z,V,I){for(var O=0;O>>1)V++;return 1<>>13,G[2*I+1]=V&8191,V=V>>>13;for(I=2*Y;I>=26,Y+=Z/67108864|0,Y+=V>>>26,this.words[G]=V&67108863}return Y!==0&&(this.words[G]=Y,this.length++),this},X.prototype.muln=function($){return this.clone().imuln($)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function($){var Y=E($);if(Y.length===0)return new X(1);for(var G=this,Z=0;Z=0);var Y=$%26,G=($-Y)/26,Z=67108863>>>26-Y<<26-Y,V;if(Y!==0){var I=0;for(V=0;V>>26-Y}I&&(this.words[V]=I,this.length++)}if(G!==0){for(V=this.length-1;V>=0;V--)this.words[V+G]=this.words[V];for(V=0;V=0);var Z;Y?Z=(Y-Y%26)/26:Z=0;var V=$%26,I=Math.min(($-V)/26,this.length),O=67108863^67108863>>>V<I)for(this.length-=I,Q=0;Q=0&&(K!==0||Q>=Z);Q--){var L=this.words[Q]|0;this.words[Q]=K<<26-V|L>>>V,K=L&O}return U&&K!==0&&(U.words[U.length++]=K),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},X.prototype.ishrn=function($,Y,G){return F(this.negative===0),this.iushrn($,Y,G)},X.prototype.shln=function($){return this.clone().ishln($)},X.prototype.ushln=function($){return this.clone().iushln($)},X.prototype.shrn=function($){return this.clone().ishrn($)},X.prototype.ushrn=function($){return this.clone().iushrn($)},X.prototype.testn=function($){F(typeof $=="number"&&$>=0);var Y=$%26,G=($-Y)/26,Z=1<=0);var Y=$%26,G=($-Y)/26;if(F(this.negative===0,"imaskn works only with positive numbers"),this.length<=G)return this;if(Y!==0&&G++,this.length=Math.min(G,this.length),Y!==0){var Z=67108863^67108863>>>Y<=67108864;Y++)this.words[Y]-=67108864,Y===this.length-1?this.words[Y+1]=1:this.words[Y+1]++;return this.length=Math.max(this.length,Y+1),this},X.prototype.isubn=function($){if(F(typeof $=="number"),F($<67108864),$<0)return this.iaddn(-$);if(this.negative!==0)return this.negative=0,this.iaddn($),this.negative=1,this;if(this.words[0]-=$,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Y=0;Y>26)-(U/67108864|0),this.words[V+G]=I&67108863}for(;V>26,this.words[V+G]=I&67108863;if(O===0)return this.strip();for(F(O===-1),O=0,V=0;V>26,this.words[V]=I&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function($,Y){var G=this.length-$.length,Z=this.clone(),V=$,I=V.words[V.length-1]|0,O=this._countBits(I);G=26-O,G!==0&&(V=V.ushln(G),Z.iushln(G),I=V.words[V.length-1]|0);var U=Z.length-V.length,Q;if(Y!=="mod"){Q=new X(null),Q.length=U+1,Q.words=new Array(Q.length);for(var K=0;K=0;A--){var S=(Z.words[V.length+A]|0)*67108864+(Z.words[V.length+A-1]|0);for(S=Math.min(S/I|0,67108863),Z._ishlnsubmul(V,S,A);Z.negative!==0;)S--,Z.negative=0,Z._ishlnsubmul(V,1,A),Z.isZero()||(Z.negative^=1);Q&&(Q.words[A]=S)}return Q&&Q.strip(),Z.strip(),Y!=="div"&&G!==0&&Z.iushrn(G),{div:Q||null,mod:Z}},X.prototype.divmod=function($,Y,G){if(F(!$.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var Z,V,I;return this.negative!==0&&$.negative===0?(I=this.neg().divmod($,Y),Y!=="mod"&&(Z=I.div.neg()),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.iadd($)),{div:Z,mod:V}):this.negative===0&&$.negative!==0?(I=this.divmod($.neg(),Y),Y!=="mod"&&(Z=I.div.neg()),{div:Z,mod:I.mod}):(this.negative&$.negative)!==0?(I=this.neg().divmod($.neg(),Y),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.isub($)),{div:I.div,mod:V}):$.length>this.length||this.cmp($)<0?{div:new X(0),mod:this}:$.length===1?Y==="div"?{div:this.divn($.words[0]),mod:null}:Y==="mod"?{div:null,mod:new X(this.modn($.words[0]))}:{div:this.divn($.words[0]),mod:new X(this.modn($.words[0]))}:this._wordDiv($,Y)},X.prototype.div=function($){return this.divmod($,"div",!1).div},X.prototype.mod=function($){return this.divmod($,"mod",!1).mod},X.prototype.umod=function($){return this.divmod($,"mod",!0).mod},X.prototype.divRound=function($){var Y=this.divmod($);if(Y.mod.isZero())return Y.div;var G=Y.div.negative!==0?Y.mod.isub($):Y.mod,Z=$.ushrn(1),V=$.andln(1),I=G.cmp(Z);return I<0||V===1&&I===0?Y.div:Y.div.negative!==0?Y.div.isubn(1):Y.div.iaddn(1)},X.prototype.modn=function($){F($<=67108863);for(var Y=(1<<26)%$,G=0,Z=this.length-1;Z>=0;Z--)G=(Y*G+(this.words[Z]|0))%$;return G},X.prototype.idivn=function($){F($<=67108863);for(var Y=0,G=this.length-1;G>=0;G--){var Z=(this.words[G]|0)+Y*67108864;this.words[G]=Z/$|0,Y=Z%$}return this.strip()},X.prototype.divn=function($){return this.clone().idivn($)},X.prototype.egcd=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=new X(0),O=new X(1),U=0;Y.isEven()&&G.isEven();)Y.iushrn(1),G.iushrn(1),++U;for(var Q=G.clone(),K=Y.clone();!Y.isZero();){for(var L=0,A=1;(Y.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0)for(Y.iushrn(L);L-- >0;)(Z.isOdd()||V.isOdd())&&(Z.iadd(Q),V.isub(K)),Z.iushrn(1),V.iushrn(1);for(var S=0,x=1;(G.words[0]&x)===0&&S<26;++S,x<<=1);if(S>0)for(G.iushrn(S);S-- >0;)(I.isOdd()||O.isOdd())&&(I.iadd(Q),O.isub(K)),I.iushrn(1),O.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(I),V.isub(O)):(G.isub(Y),I.isub(Z),O.isub(V))}return{a:I,b:O,gcd:G.iushln(U)}},X.prototype._invmp=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=G.clone();Y.cmpn(1)>0&&G.cmpn(1)>0;){for(var O=0,U=1;(Y.words[0]&U)===0&&O<26;++O,U<<=1);if(O>0)for(Y.iushrn(O);O-- >0;)Z.isOdd()&&Z.iadd(I),Z.iushrn(1);for(var Q=0,K=1;(G.words[0]&K)===0&&Q<26;++Q,K<<=1);if(Q>0)for(G.iushrn(Q);Q-- >0;)V.isOdd()&&V.iadd(I),V.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(V)):(G.isub(Y),V.isub(Z))}var L;return Y.cmpn(1)===0?L=Z:L=V,L.cmpn(0)<0&&L.iadd($),L},X.prototype.gcd=function($){if(this.isZero())return $.abs();if($.isZero())return this.abs();var Y=this.clone(),G=$.clone();Y.negative=0,G.negative=0;for(var Z=0;Y.isEven()&&G.isEven();Z++)Y.iushrn(1),G.iushrn(1);do{for(;Y.isEven();)Y.iushrn(1);for(;G.isEven();)G.iushrn(1);var V=Y.cmp(G);if(V<0){var I=Y;Y=G,G=I}else if(V===0||G.cmpn(1)===0)break;Y.isub(G)}while(!0);return G.iushln(Z)},X.prototype.invm=function($){return this.egcd($).a.umod($)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function($){return this.words[0]&$},X.prototype.bincn=function($){F(typeof $=="number");var Y=$%26,G=($-Y)/26,Z=1<>>26,O&=67108863,this.words[I]=O}return V!==0&&(this.words[I]=V,this.length++),this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function($){var Y=$<0;if(this.negative!==0&&!Y)return-1;if(this.negative===0&&Y)return 1;this.strip();var G;if(this.length>1)G=1;else{Y&&($=-$),F($<=67108863,"Number is too big");var Z=this.words[0]|0;G=Z===$?0:Z<$?-1:1}return this.negative!==0?-G|0:G},X.prototype.cmp=function($){if(this.negative!==0&&$.negative===0)return-1;if(this.negative===0&&$.negative!==0)return 1;var Y=this.ucmp($);return this.negative!==0?-Y|0:Y},X.prototype.ucmp=function($){if(this.length>$.length)return 1;if(this.length<$.length)return-1;for(var Y=0,G=this.length-1;G>=0;G--){var Z=this.words[G]|0,V=$.words[G]|0;if(Z!==V){ZV&&(Y=1);break}}return Y},X.prototype.gtn=function($){return this.cmpn($)===1},X.prototype.gt=function($){return this.cmp($)===1},X.prototype.gten=function($){return this.cmpn($)>=0},X.prototype.gte=function($){return this.cmp($)>=0},X.prototype.ltn=function($){return this.cmpn($)===-1},X.prototype.lt=function($){return this.cmp($)===-1},X.prototype.lten=function($){return this.cmpn($)<=0},X.prototype.lte=function($){return this.cmp($)<=0},X.prototype.eqn=function($){return this.cmpn($)===0},X.prototype.eq=function($){return this.cmp($)===0},X.red=function($){return new p($)},X.prototype.toRed=function($){return F(!this.red,"Already a number in reduction context"),F(this.negative===0,"red works only with positives"),$.convertTo(this)._forceRed($)},X.prototype.fromRed=function(){return F(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function($){return this.red=$,this},X.prototype.forceRed=function($){return F(!this.red,"Already a number in reduction context"),this._forceRed($)},X.prototype.redAdd=function($){return F(this.red,"redAdd works only with red numbers"),this.red.add(this,$)},X.prototype.redIAdd=function($){return F(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,$)},X.prototype.redSub=function($){return F(this.red,"redSub works only with red numbers"),this.red.sub(this,$)},X.prototype.redISub=function($){return F(this.red,"redISub works only with red numbers"),this.red.isub(this,$)},X.prototype.redShl=function($){return F(this.red,"redShl works only with red numbers"),this.red.shl(this,$)},X.prototype.redMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.mul(this,$)},X.prototype.redIMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.imul(this,$)},X.prototype.redSqr=function(){return F(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return F(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return F(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return F(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return F(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function($){return F(this.red&&!$.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,$)};var B={k256:null,p224:null,p192:null,p25519:null};function w($,Y){this.name=$,this.p=new X(Y,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}w.prototype._tmp=function(){var $=new X(null);return $.words=new Array(Math.ceil(this.n/13)),$},w.prototype.ireduce=function($){var Y=$,G;do this.split(Y,this.tmp),Y=this.imulK(Y),Y=Y.iadd(this.tmp),G=Y.bitLength();while(G>this.n);var Z=G0?Y.isub(this.p):Y.strip!==void 0?Y.strip():Y._strip(),Y},w.prototype.split=function($,Y){$.iushrn(this.n,0,Y)},w.prototype.imulK=function($){return $.imul(this.k)};function f(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}P(f,w),f.prototype.split=function($,Y){for(var G=4194303,Z=Math.min($.length,9),V=0;V>>22,I=O}I>>>=22,$.words[V-10]=I,I===0&&$.length>10?$.length-=10:$.length-=9},f.prototype.imulK=function($){$.words[$.length]=0,$.words[$.length+1]=0,$.length+=2;for(var Y=0,G=0;G<$.length;G++){var Z=$.words[G]|0;Y+=Z*977,$.words[G]=Y&67108863,Y=Z*64+(Y/67108864|0)}return $.words[$.length-1]===0&&($.length--,$.words[$.length-1]===0&&$.length--),$};function b(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}P(b,w);function u(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}P(u,w);function Y0(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}P(Y0,w),Y0.prototype.imulK=function($){for(var Y=0,G=0;G<$.length;G++){var Z=($.words[G]|0)*19+Y,V=Z&67108863;Z>>>=26,$.words[G]=V,Y=Z}return Y!==0&&($.words[$.length++]=Y),$},X._prime=function($){if(B[$])return B[$];var Y;if($==="k256")Y=new f;else if($==="p224")Y=new b;else if($==="p192")Y=new u;else if($==="p25519")Y=new Y0;else throw new Error("Unknown prime "+$);return B[$]=Y,Y};function p($){if(typeof $=="string"){var Y=X._prime($);this.m=Y.p,this.prime=Y}else F($.gtn(1),"modulus must be greater than 1"),this.m=$,this.prime=null}p.prototype._verify1=function($){F($.negative===0,"red works only with positives"),F($.red,"red works only with red numbers")},p.prototype._verify2=function($,Y){F(($.negative|Y.negative)===0,"red works only with positives"),F($.red&&$.red===Y.red,"red works only with red numbers")},p.prototype.imod=function($){return this.prime?this.prime.ireduce($)._forceRed(this):$.umod(this.m)._forceRed(this)},p.prototype.neg=function($){return $.isZero()?$.clone():this.m.sub($)._forceRed(this)},p.prototype.add=function($,Y){this._verify2($,Y);var G=$.add(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G._forceRed(this)},p.prototype.iadd=function($,Y){this._verify2($,Y);var G=$.iadd(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G},p.prototype.sub=function($,Y){this._verify2($,Y);var G=$.sub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G._forceRed(this)},p.prototype.isub=function($,Y){this._verify2($,Y);var G=$.isub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G},p.prototype.shl=function($,Y){return this._verify1($),this.imod($.ushln(Y))},p.prototype.imul=function($,Y){return this._verify2($,Y),this.imod($.imul(Y))},p.prototype.mul=function($,Y){return this._verify2($,Y),this.imod($.mul(Y))},p.prototype.isqr=function($){return this.imul($,$.clone())},p.prototype.sqr=function($){return this.mul($,$)},p.prototype.sqrt=function($){if($.isZero())return $.clone();var Y=this.m.andln(3);if(F(Y%2===1),Y===3){var G=this.m.add(new X(1)).iushrn(2);return this.pow($,G)}for(var Z=this.m.subn(1),V=0;!Z.isZero()&&Z.andln(1)===0;)V++,Z.iushrn(1);F(!Z.isZero());var I=new X(1).toRed(this),O=I.redNeg(),U=this.m.subn(1).iushrn(1),Q=this.m.bitLength();for(Q=new X(2*Q*Q).toRed(this);this.pow(Q,U).cmp(O)!==0;)Q.redIAdd(O);for(var K=this.pow(Q,Z),L=this.pow($,Z.addn(1).iushrn(1)),A=this.pow($,Z),S=V;A.cmp(I)!==0;){for(var x=A,y=0;x.cmp(I)!==0;y++)x=x.redSqr();F(y=0;V--){for(var K=Y.words[V],L=Q-1;L>=0;L--){var A=K>>L&1;if(I!==Z[0]&&(I=this.sqr(I)),A===0&&O===0){U=0;continue}O<<=1,O|=A,U++,!(U!==G&&(V!==0||L!==0))&&(I=this.mul(I,Z[O]),U=0,O=0)}Q=26}return I},p.prototype.convertTo=function($){var Y=$.umod(this.m);return Y===$?Y.clone():Y},p.prototype.convertFrom=function($){var Y=$.clone();return Y.red=null,Y},X.mont=function($){return new v0($)};function v0($){p.call(this,$),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new X(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}P(v0,p),v0.prototype.convertTo=function($){return this.imod($.ushln(this.shift))},v0.prototype.convertFrom=function($){var Y=this.imod($.mul(this.rinv));return Y.red=null,Y},v0.prototype.imul=function($,Y){if($.isZero()||Y.isZero())return $.words[0]=0,$.length=1,$;var G=$.imul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.mul=function($,Y){if($.isZero()||Y.isZero())return new X(0)._forceRed(this);var G=$.mul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.invm=function($){var Y=this.imod($._invmp(this.m).mul(this.r2));return Y._forceRed(this)}})(typeof _>"u"||_,N)}}),DY=S0({"node_modules/miller-rabin/node_modules/bn.js/lib/bn.js"(N,_){(function(j,k){function F($,Y){if(!$)throw new Error(Y||"Assertion failed")}function P($,Y){$.super_=Y;var G=function(){};G.prototype=Y.prototype,$.prototype=new G,$.prototype.constructor=$}function X($,Y,G){if(X.isBN($))return $;this.negative=0,this.words=null,this.length=0,this.red=null,$!==null&&((Y==="le"||Y==="be")&&(G=Y,Y=10),this._init($||0,Y||10,G||"be"))}typeof j=="object"?j.exports=X:k.BN=X,X.BN=X,X.wordSize=26;var C=j0;X.isBN=function($){return $ instanceof X?!0:$!==null&&typeof $=="object"&&$.constructor.wordSize===X.wordSize&&Array.isArray($.words)},X.max=function($,Y){return $.cmp(Y)>0?$:Y},X.min=function($,Y){return $.cmp(Y)<0?$:Y},X.prototype._init=function($,Y,G){if(typeof $=="number")return this._initNumber($,Y,G);if(typeof $=="object")return this._initArray($,Y,G);Y==="hex"&&(Y=16),F(Y===(Y|0)&&Y>=2&&Y<=36),$=$.toString().replace(/\s+/g,"");var Z=0;$[0]==="-"&&(Z++,this.negative=1),Z<$.length&&(Y===16?this._parseHex($,Z,G):(this._parseBase($,Y,Z),G==="le"&&this._initArray(this.toArray(),Y,G)))},X.prototype._initNumber=function($,Y,G){$<0&&(this.negative=1,$=-$),$<67108864?(this.words=[$&67108863],this.length=1):$<4503599627370496?(this.words=[$&67108863,$/67108864&67108863],this.length=2):(F($<9007199254740992),this.words=[$&67108863,$/67108864&67108863,1],this.length=3),G==="le"&&this._initArray(this.toArray(),Y,G)},X.prototype._initArray=function($,Y,G){if(F(typeof $.length=="number"),$.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil($.length/3),this.words=new Array(this.length);for(var Z=0;Z=0;Z-=3)I=$[Z]|$[Z-1]<<8|$[Z-2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);else if(G==="le")for(Z=0,V=0;Z<$.length;Z+=3)I=$[Z]|$[Z+1]<<8|$[Z+2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);return this.strip()};function z($,Y){var G=$.charCodeAt(Y);return G>=65&&G<=70?G-55:G>=97&&G<=102?G-87:G-48&15}function T($,Y,G){var Z=z($,G);return G-1>=Y&&(Z|=z($,G-1)<<4),Z}X.prototype._parseHex=function($,Y,G){this.length=Math.ceil(($.length-Y)/6),this.words=new Array(this.length);for(var Z=0;Z=Y;Z-=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8;else{var U=$.length-Y;for(Z=U%2===0?Y+1:Y;Z<$.length;Z+=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8}this.strip()};function H($,Y,G,Z){for(var V=0,I=Math.min($.length,G),O=Y;O=49?V+=U-49+10:U>=17?V+=U-17+10:V+=U}return V}X.prototype._parseBase=function($,Y,G){this.words=[0],this.length=1;for(var Z=0,V=1;V<=67108863;V*=Y)Z++;Z--,V=V/Y|0;for(var I=$.length-G,O=I%Z,U=Math.min(I,I-O)+G,Q=0,K=G;K1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},X.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},X.prototype.inspect=function(){return(this.red?""};var J=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],W=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],D=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];X.prototype.toString=function($,Y){$=$||10,Y=Y|0||1;var G;if($===16||$==="hex"){G="";for(var Z=0,V=0,I=0;I>>24-Z&16777215,V!==0||I!==this.length-1?G=J[6-U.length]+U+G:G=U+G,Z+=2,Z>=26&&(Z-=26,I--)}for(V!==0&&(G=V.toString(16)+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}if($===($|0)&&$>=2&&$<=36){var Q=W[$],K=D[$];G="";var L=this.clone();for(L.negative=0;!L.isZero();){var A=L.modn(K).toString($);L=L.idivn(K),L.isZero()?G=A+G:G=J[Q-A.length]+A+G}for(this.isZero()&&(G="0"+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}F(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var $=this.words[0];return this.length===2?$+=this.words[1]*67108864:this.length===3&&this.words[2]===1?$+=4503599627370496+this.words[1]*67108864:this.length>2&&F(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-$:$},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function($,Y){return F(typeof C<"u"),this.toArrayLike(C,$,Y)},X.prototype.toArray=function($,Y){return this.toArrayLike(Array,$,Y)},X.prototype.toArrayLike=function($,Y,G){var Z=this.byteLength(),V=G||Math.max(1,Z);F(Z<=V,"byte array longer than desired length"),F(V>0,"Requested array length <= 0"),this.strip();var I=Y==="le",O=new $(V),U,Q,K=this.clone();if(I){for(Q=0;!K.isZero();Q++)U=K.andln(255),K.iushrn(8),O[Q]=U;for(;Q=4096&&(G+=13,Y>>>=13),Y>=64&&(G+=7,Y>>>=7),Y>=8&&(G+=4,Y>>>=4),Y>=2&&(G+=2,Y>>>=2),G+Y},X.prototype._zeroBits=function($){if($===0)return 26;var Y=$,G=0;return(Y&8191)===0&&(G+=13,Y>>>=13),(Y&127)===0&&(G+=7,Y>>>=7),(Y&15)===0&&(G+=4,Y>>>=4),(Y&3)===0&&(G+=2,Y>>>=2),(Y&1)===0&&G++,G},X.prototype.bitLength=function(){var $=this.words[this.length-1],Y=this._countBits($);return(this.length-1)*26+Y};function E($){for(var Y=new Array($.bitLength()),G=0;G>>V}return Y}X.prototype.zeroBits=function(){if(this.isZero())return 0;for(var $=0,Y=0;Y$.length?this.clone().ior($):$.clone().ior(this)},X.prototype.uor=function($){return this.length>$.length?this.clone().iuor($):$.clone().iuor(this)},X.prototype.iuand=function($){var Y;this.length>$.length?Y=$:Y=this;for(var G=0;G$.length?this.clone().iand($):$.clone().iand(this)},X.prototype.uand=function($){return this.length>$.length?this.clone().iuand($):$.clone().iuand(this)},X.prototype.iuxor=function($){var Y,G;this.length>$.length?(Y=this,G=$):(Y=$,G=this);for(var Z=0;Z$.length?this.clone().ixor($):$.clone().ixor(this)},X.prototype.uxor=function($){return this.length>$.length?this.clone().iuxor($):$.clone().iuxor(this)},X.prototype.inotn=function($){F(typeof $=="number"&&$>=0);var Y=Math.ceil($/26)|0,G=$%26;this._expand(Y),G>0&&Y--;for(var Z=0;Z0&&(this.words[Z]=~this.words[Z]&67108863>>26-G),this.strip()},X.prototype.notn=function($){return this.clone().inotn($)},X.prototype.setn=function($,Y){F(typeof $=="number"&&$>=0);var G=$/26|0,Z=$%26;return this._expand(G+1),Y?this.words[G]=this.words[G]|1<$.length?(G=this,Z=$):(G=$,Z=this);for(var V=0,I=0;I>>26;for(;V!==0&&I>>26;if(this.length=G.length,V!==0)this.words[this.length]=V,this.length++;else if(G!==this)for(;I$.length?this.clone().iadd($):$.clone().iadd(this)},X.prototype.isub=function($){if($.negative!==0){$.negative=0;var Y=this.iadd($);return $.negative=1,Y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd($),this.negative=1,this._normSign();var G=this.cmp($);if(G===0)return this.negative=0,this.length=1,this.words[0]=0,this;var Z,V;G>0?(Z=this,V=$):(Z=$,V=this);for(var I=0,O=0;O>26,this.words[O]=Y&67108863;for(;I!==0&&O>26,this.words[O]=Y&67108863;if(I===0&&O>>26,A=Q&67108863,S=Math.min(K,Y.length-1),x=Math.max(0,K-$.length+1);x<=S;x++){var y=K-x|0;V=$.words[y]|0,I=Y.words[x]|0,O=V*I+A,L+=O/67108864|0,A=O&67108863}G.words[K]=A|0,Q=L|0}return Q!==0?G.words[K]=Q|0:G.length--,G.strip()}var M=function($,Y,G){var Z=$.words,V=Y.words,I=G.words,O=0,U,Q,K,L=Z[0]|0,A=L&8191,S=L>>>13,x=Z[1]|0,y=x&8191,c=x>>>13,q0=Z[2]|0,h=q0&8191,d=q0>>>13,_0=Z[3]|0,l=_0&8191,n=_0>>>13,y0=Z[4]|0,t=y0&8191,s=y0>>>13,w0=Z[5]|0,m=w0&8191,r=w0>>>13,$$=Z[6]|0,i=$$&8191,e=$$>>>13,x0=Z[7]|0,o=x0&8191,a=x0>>>13,p0=Z[8]|0,$0=p0&8191,Q0=p0>>>13,Y$=Z[9]|0,Z0=Y$&8191,G0=Y$>>>13,Z$=V[0]|0,V0=Z$&8191,U0=Z$>>>13,G$=V[1]|0,X0=G$&8191,K0=G$>>>13,V$=V[2]|0,I0=V$&8191,O0=V$>>>13,U$=V[3]|0,J0=U$&8191,F0=U$>>>13,X$=V[4]|0,A0=X$&8191,W0=X$>>>13,K$=V[5]|0,H0=K$&8191,E0=K$>>>13,I$=V[6]|0,T0=I$&8191,D0=I$>>>13,O$=V[7]|0,C0=O$&8191,L0=O$>>>13,J$=V[8]|0,R0=J$&8191,z0=J$>>>13,F$=V[9]|0,P0=F$&8191,M0=F$>>>13;G.negative=$.negative^Y.negative,G.length=19,U=Math.imul(A,V0),Q=Math.imul(A,U0),Q=Q+Math.imul(S,V0)|0,K=Math.imul(S,U0);var Q$=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(Q$>>>26)|0,Q$&=67108863,U=Math.imul(y,V0),Q=Math.imul(y,U0),Q=Q+Math.imul(c,V0)|0,K=Math.imul(c,U0),U=U+Math.imul(A,X0)|0,Q=Q+Math.imul(A,K0)|0,Q=Q+Math.imul(S,X0)|0,K=K+Math.imul(S,K0)|0;var k0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(k0>>>26)|0,k0&=67108863,U=Math.imul(h,V0),Q=Math.imul(h,U0),Q=Q+Math.imul(d,V0)|0,K=Math.imul(d,U0),U=U+Math.imul(y,X0)|0,Q=Q+Math.imul(y,K0)|0,Q=Q+Math.imul(c,X0)|0,K=K+Math.imul(c,K0)|0,U=U+Math.imul(A,I0)|0,Q=Q+Math.imul(A,O0)|0,Q=Q+Math.imul(S,I0)|0,K=K+Math.imul(S,O0)|0;var g0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(g0>>>26)|0,g0&=67108863,U=Math.imul(l,V0),Q=Math.imul(l,U0),Q=Q+Math.imul(n,V0)|0,K=Math.imul(n,U0),U=U+Math.imul(h,X0)|0,Q=Q+Math.imul(h,K0)|0,Q=Q+Math.imul(d,X0)|0,K=K+Math.imul(d,K0)|0,U=U+Math.imul(y,I0)|0,Q=Q+Math.imul(y,O0)|0,Q=Q+Math.imul(c,I0)|0,K=K+Math.imul(c,O0)|0,U=U+Math.imul(A,J0)|0,Q=Q+Math.imul(A,F0)|0,Q=Q+Math.imul(S,J0)|0,K=K+Math.imul(S,F0)|0;var f0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(f0>>>26)|0,f0&=67108863,U=Math.imul(t,V0),Q=Math.imul(t,U0),Q=Q+Math.imul(s,V0)|0,K=Math.imul(s,U0),U=U+Math.imul(l,X0)|0,Q=Q+Math.imul(l,K0)|0,Q=Q+Math.imul(n,X0)|0,K=K+Math.imul(n,K0)|0,U=U+Math.imul(h,I0)|0,Q=Q+Math.imul(h,O0)|0,Q=Q+Math.imul(d,I0)|0,K=K+Math.imul(d,O0)|0,U=U+Math.imul(y,J0)|0,Q=Q+Math.imul(y,F0)|0,Q=Q+Math.imul(c,J0)|0,K=K+Math.imul(c,F0)|0,U=U+Math.imul(A,A0)|0,Q=Q+Math.imul(A,W0)|0,Q=Q+Math.imul(S,A0)|0,K=K+Math.imul(S,W0)|0;var c0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(c0>>>26)|0,c0&=67108863,U=Math.imul(m,V0),Q=Math.imul(m,U0),Q=Q+Math.imul(r,V0)|0,K=Math.imul(r,U0),U=U+Math.imul(t,X0)|0,Q=Q+Math.imul(t,K0)|0,Q=Q+Math.imul(s,X0)|0,K=K+Math.imul(s,K0)|0,U=U+Math.imul(l,I0)|0,Q=Q+Math.imul(l,O0)|0,Q=Q+Math.imul(n,I0)|0,K=K+Math.imul(n,O0)|0,U=U+Math.imul(h,J0)|0,Q=Q+Math.imul(h,F0)|0,Q=Q+Math.imul(d,J0)|0,K=K+Math.imul(d,F0)|0,U=U+Math.imul(y,A0)|0,Q=Q+Math.imul(y,W0)|0,Q=Q+Math.imul(c,A0)|0,K=K+Math.imul(c,W0)|0,U=U+Math.imul(A,H0)|0,Q=Q+Math.imul(A,E0)|0,Q=Q+Math.imul(S,H0)|0,K=K+Math.imul(S,E0)|0;var h0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(h0>>>26)|0,h0&=67108863,U=Math.imul(i,V0),Q=Math.imul(i,U0),Q=Q+Math.imul(e,V0)|0,K=Math.imul(e,U0),U=U+Math.imul(m,X0)|0,Q=Q+Math.imul(m,K0)|0,Q=Q+Math.imul(r,X0)|0,K=K+Math.imul(r,K0)|0,U=U+Math.imul(t,I0)|0,Q=Q+Math.imul(t,O0)|0,Q=Q+Math.imul(s,I0)|0,K=K+Math.imul(s,O0)|0,U=U+Math.imul(l,J0)|0,Q=Q+Math.imul(l,F0)|0,Q=Q+Math.imul(n,J0)|0,K=K+Math.imul(n,F0)|0,U=U+Math.imul(h,A0)|0,Q=Q+Math.imul(h,W0)|0,Q=Q+Math.imul(d,A0)|0,K=K+Math.imul(d,W0)|0,U=U+Math.imul(y,H0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(c,H0)|0,K=K+Math.imul(c,E0)|0,U=U+Math.imul(A,T0)|0,Q=Q+Math.imul(A,D0)|0,Q=Q+Math.imul(S,T0)|0,K=K+Math.imul(S,D0)|0;var d0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(d0>>>26)|0,d0&=67108863,U=Math.imul(o,V0),Q=Math.imul(o,U0),Q=Q+Math.imul(a,V0)|0,K=Math.imul(a,U0),U=U+Math.imul(i,X0)|0,Q=Q+Math.imul(i,K0)|0,Q=Q+Math.imul(e,X0)|0,K=K+Math.imul(e,K0)|0,U=U+Math.imul(m,I0)|0,Q=Q+Math.imul(m,O0)|0,Q=Q+Math.imul(r,I0)|0,K=K+Math.imul(r,O0)|0,U=U+Math.imul(t,J0)|0,Q=Q+Math.imul(t,F0)|0,Q=Q+Math.imul(s,J0)|0,K=K+Math.imul(s,F0)|0,U=U+Math.imul(l,A0)|0,Q=Q+Math.imul(l,W0)|0,Q=Q+Math.imul(n,A0)|0,K=K+Math.imul(n,W0)|0,U=U+Math.imul(h,H0)|0,Q=Q+Math.imul(h,E0)|0,Q=Q+Math.imul(d,H0)|0,K=K+Math.imul(d,E0)|0,U=U+Math.imul(y,T0)|0,Q=Q+Math.imul(y,D0)|0,Q=Q+Math.imul(c,T0)|0,K=K+Math.imul(c,D0)|0,U=U+Math.imul(A,C0)|0,Q=Q+Math.imul(A,L0)|0,Q=Q+Math.imul(S,C0)|0,K=K+Math.imul(S,L0)|0;var b0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(b0>>>26)|0,b0&=67108863,U=Math.imul($0,V0),Q=Math.imul($0,U0),Q=Q+Math.imul(Q0,V0)|0,K=Math.imul(Q0,U0),U=U+Math.imul(o,X0)|0,Q=Q+Math.imul(o,K0)|0,Q=Q+Math.imul(a,X0)|0,K=K+Math.imul(a,K0)|0,U=U+Math.imul(i,I0)|0,Q=Q+Math.imul(i,O0)|0,Q=Q+Math.imul(e,I0)|0,K=K+Math.imul(e,O0)|0,U=U+Math.imul(m,J0)|0,Q=Q+Math.imul(m,F0)|0,Q=Q+Math.imul(r,J0)|0,K=K+Math.imul(r,F0)|0,U=U+Math.imul(t,A0)|0,Q=Q+Math.imul(t,W0)|0,Q=Q+Math.imul(s,A0)|0,K=K+Math.imul(s,W0)|0,U=U+Math.imul(l,H0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(n,H0)|0,K=K+Math.imul(n,E0)|0,U=U+Math.imul(h,T0)|0,Q=Q+Math.imul(h,D0)|0,Q=Q+Math.imul(d,T0)|0,K=K+Math.imul(d,D0)|0,U=U+Math.imul(y,C0)|0,Q=Q+Math.imul(y,L0)|0,Q=Q+Math.imul(c,C0)|0,K=K+Math.imul(c,L0)|0,U=U+Math.imul(A,R0)|0,Q=Q+Math.imul(A,z0)|0,Q=Q+Math.imul(S,R0)|0,K=K+Math.imul(S,z0)|0;var l0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(l0>>>26)|0,l0&=67108863,U=Math.imul(Z0,V0),Q=Math.imul(Z0,U0),Q=Q+Math.imul(G0,V0)|0,K=Math.imul(G0,U0),U=U+Math.imul($0,X0)|0,Q=Q+Math.imul($0,K0)|0,Q=Q+Math.imul(Q0,X0)|0,K=K+Math.imul(Q0,K0)|0,U=U+Math.imul(o,I0)|0,Q=Q+Math.imul(o,O0)|0,Q=Q+Math.imul(a,I0)|0,K=K+Math.imul(a,O0)|0,U=U+Math.imul(i,J0)|0,Q=Q+Math.imul(i,F0)|0,Q=Q+Math.imul(e,J0)|0,K=K+Math.imul(e,F0)|0,U=U+Math.imul(m,A0)|0,Q=Q+Math.imul(m,W0)|0,Q=Q+Math.imul(r,A0)|0,K=K+Math.imul(r,W0)|0,U=U+Math.imul(t,H0)|0,Q=Q+Math.imul(t,E0)|0,Q=Q+Math.imul(s,H0)|0,K=K+Math.imul(s,E0)|0,U=U+Math.imul(l,T0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(n,T0)|0,K=K+Math.imul(n,D0)|0,U=U+Math.imul(h,C0)|0,Q=Q+Math.imul(h,L0)|0,Q=Q+Math.imul(d,C0)|0,K=K+Math.imul(d,L0)|0,U=U+Math.imul(y,R0)|0,Q=Q+Math.imul(y,z0)|0,Q=Q+Math.imul(c,R0)|0,K=K+Math.imul(c,z0)|0,U=U+Math.imul(A,P0)|0,Q=Q+Math.imul(A,M0)|0,Q=Q+Math.imul(S,P0)|0,K=K+Math.imul(S,M0)|0;var o0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(o0>>>26)|0,o0&=67108863,U=Math.imul(Z0,X0),Q=Math.imul(Z0,K0),Q=Q+Math.imul(G0,X0)|0,K=Math.imul(G0,K0),U=U+Math.imul($0,I0)|0,Q=Q+Math.imul($0,O0)|0,Q=Q+Math.imul(Q0,I0)|0,K=K+Math.imul(Q0,O0)|0,U=U+Math.imul(o,J0)|0,Q=Q+Math.imul(o,F0)|0,Q=Q+Math.imul(a,J0)|0,K=K+Math.imul(a,F0)|0,U=U+Math.imul(i,A0)|0,Q=Q+Math.imul(i,W0)|0,Q=Q+Math.imul(e,A0)|0,K=K+Math.imul(e,W0)|0,U=U+Math.imul(m,H0)|0,Q=Q+Math.imul(m,E0)|0,Q=Q+Math.imul(r,H0)|0,K=K+Math.imul(r,E0)|0,U=U+Math.imul(t,T0)|0,Q=Q+Math.imul(t,D0)|0,Q=Q+Math.imul(s,T0)|0,K=K+Math.imul(s,D0)|0,U=U+Math.imul(l,C0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(n,C0)|0,K=K+Math.imul(n,L0)|0,U=U+Math.imul(h,R0)|0,Q=Q+Math.imul(h,z0)|0,Q=Q+Math.imul(d,R0)|0,K=K+Math.imul(d,z0)|0,U=U+Math.imul(y,P0)|0,Q=Q+Math.imul(y,M0)|0,Q=Q+Math.imul(c,P0)|0,K=K+Math.imul(c,M0)|0;var u0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(u0>>>26)|0,u0&=67108863,U=Math.imul(Z0,I0),Q=Math.imul(Z0,O0),Q=Q+Math.imul(G0,I0)|0,K=Math.imul(G0,O0),U=U+Math.imul($0,J0)|0,Q=Q+Math.imul($0,F0)|0,Q=Q+Math.imul(Q0,J0)|0,K=K+Math.imul(Q0,F0)|0,U=U+Math.imul(o,A0)|0,Q=Q+Math.imul(o,W0)|0,Q=Q+Math.imul(a,A0)|0,K=K+Math.imul(a,W0)|0,U=U+Math.imul(i,H0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,H0)|0,K=K+Math.imul(e,E0)|0,U=U+Math.imul(m,T0)|0,Q=Q+Math.imul(m,D0)|0,Q=Q+Math.imul(r,T0)|0,K=K+Math.imul(r,D0)|0,U=U+Math.imul(t,C0)|0,Q=Q+Math.imul(t,L0)|0,Q=Q+Math.imul(s,C0)|0,K=K+Math.imul(s,L0)|0,U=U+Math.imul(l,R0)|0,Q=Q+Math.imul(l,z0)|0,Q=Q+Math.imul(n,R0)|0,K=K+Math.imul(n,z0)|0,U=U+Math.imul(h,P0)|0,Q=Q+Math.imul(h,M0)|0,Q=Q+Math.imul(d,P0)|0,K=K+Math.imul(d,M0)|0;var n0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(n0>>>26)|0,n0&=67108863,U=Math.imul(Z0,J0),Q=Math.imul(Z0,F0),Q=Q+Math.imul(G0,J0)|0,K=Math.imul(G0,F0),U=U+Math.imul($0,A0)|0,Q=Q+Math.imul($0,W0)|0,Q=Q+Math.imul(Q0,A0)|0,K=K+Math.imul(Q0,W0)|0,U=U+Math.imul(o,H0)|0,Q=Q+Math.imul(o,E0)|0,Q=Q+Math.imul(a,H0)|0,K=K+Math.imul(a,E0)|0,U=U+Math.imul(i,T0)|0,Q=Q+Math.imul(i,D0)|0,Q=Q+Math.imul(e,T0)|0,K=K+Math.imul(e,D0)|0,U=U+Math.imul(m,C0)|0,Q=Q+Math.imul(m,L0)|0,Q=Q+Math.imul(r,C0)|0,K=K+Math.imul(r,L0)|0,U=U+Math.imul(t,R0)|0,Q=Q+Math.imul(t,z0)|0,Q=Q+Math.imul(s,R0)|0,K=K+Math.imul(s,z0)|0,U=U+Math.imul(l,P0)|0,Q=Q+Math.imul(l,M0)|0,Q=Q+Math.imul(n,P0)|0,K=K+Math.imul(n,M0)|0;var s0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(s0>>>26)|0,s0&=67108863,U=Math.imul(Z0,A0),Q=Math.imul(Z0,W0),Q=Q+Math.imul(G0,A0)|0,K=Math.imul(G0,W0),U=U+Math.imul($0,H0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Q0,H0)|0,K=K+Math.imul(Q0,E0)|0,U=U+Math.imul(o,T0)|0,Q=Q+Math.imul(o,D0)|0,Q=Q+Math.imul(a,T0)|0,K=K+Math.imul(a,D0)|0,U=U+Math.imul(i,C0)|0,Q=Q+Math.imul(i,L0)|0,Q=Q+Math.imul(e,C0)|0,K=K+Math.imul(e,L0)|0,U=U+Math.imul(m,R0)|0,Q=Q+Math.imul(m,z0)|0,Q=Q+Math.imul(r,R0)|0,K=K+Math.imul(r,z0)|0,U=U+Math.imul(t,P0)|0,Q=Q+Math.imul(t,M0)|0,Q=Q+Math.imul(s,P0)|0,K=K+Math.imul(s,M0)|0;var t0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(t0>>>26)|0,t0&=67108863,U=Math.imul(Z0,H0),Q=Math.imul(Z0,E0),Q=Q+Math.imul(G0,H0)|0,K=Math.imul(G0,E0),U=U+Math.imul($0,T0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Q0,T0)|0,K=K+Math.imul(Q0,D0)|0,U=U+Math.imul(o,C0)|0,Q=Q+Math.imul(o,L0)|0,Q=Q+Math.imul(a,C0)|0,K=K+Math.imul(a,L0)|0,U=U+Math.imul(i,R0)|0,Q=Q+Math.imul(i,z0)|0,Q=Q+Math.imul(e,R0)|0,K=K+Math.imul(e,z0)|0,U=U+Math.imul(m,P0)|0,Q=Q+Math.imul(m,M0)|0,Q=Q+Math.imul(r,P0)|0,K=K+Math.imul(r,M0)|0;var m0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(m0>>>26)|0,m0&=67108863,U=Math.imul(Z0,T0),Q=Math.imul(Z0,D0),Q=Q+Math.imul(G0,T0)|0,K=Math.imul(G0,D0),U=U+Math.imul($0,C0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Q0,C0)|0,K=K+Math.imul(Q0,L0)|0,U=U+Math.imul(o,R0)|0,Q=Q+Math.imul(o,z0)|0,Q=Q+Math.imul(a,R0)|0,K=K+Math.imul(a,z0)|0,U=U+Math.imul(i,P0)|0,Q=Q+Math.imul(i,M0)|0,Q=Q+Math.imul(e,P0)|0,K=K+Math.imul(e,M0)|0;var a0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(a0>>>26)|0,a0&=67108863,U=Math.imul(Z0,C0),Q=Math.imul(Z0,L0),Q=Q+Math.imul(G0,C0)|0,K=Math.imul(G0,L0),U=U+Math.imul($0,R0)|0,Q=Q+Math.imul($0,z0)|0,Q=Q+Math.imul(Q0,R0)|0,K=K+Math.imul(Q0,z0)|0,U=U+Math.imul(o,P0)|0,Q=Q+Math.imul(o,M0)|0,Q=Q+Math.imul(a,P0)|0,K=K+Math.imul(a,M0)|0;var e0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(e0>>>26)|0,e0&=67108863,U=Math.imul(Z0,R0),Q=Math.imul(Z0,z0),Q=Q+Math.imul(G0,R0)|0,K=Math.imul(G0,z0),U=U+Math.imul($0,P0)|0,Q=Q+Math.imul($0,M0)|0,Q=Q+Math.imul(Q0,P0)|0,K=K+Math.imul(Q0,M0)|0;var r0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(r0>>>26)|0,r0&=67108863,U=Math.imul(Z0,P0),Q=Math.imul(Z0,M0),Q=Q+Math.imul(G0,P0)|0,K=Math.imul(G0,M0);var i0=(O+U|0)+((Q&8191)<<13)|0;return O=(K+(Q>>>13)|0)+(i0>>>26)|0,i0&=67108863,I[0]=Q$,I[1]=k0,I[2]=g0,I[3]=f0,I[4]=c0,I[5]=h0,I[6]=d0,I[7]=b0,I[8]=l0,I[9]=o0,I[10]=u0,I[11]=n0,I[12]=s0,I[13]=t0,I[14]=m0,I[15]=a0,I[16]=e0,I[17]=r0,I[18]=i0,O!==0&&(I[19]=O,G.length++),G};Math.imul||(M=R);function v($,Y,G){G.negative=Y.negative^$.negative,G.length=$.length+Y.length;for(var Z=0,V=0,I=0;I>>26)|0,V+=O>>>26,O&=67108863}G.words[I]=U,Z=O,O=V}return Z!==0?G.words[I]=Z:G.length--,G.strip()}function q($,Y,G){var Z=new g;return Z.mulp($,Y,G)}X.prototype.mulTo=function($,Y){var G,Z=this.length+$.length;return this.length===10&&$.length===10?G=M(this,$,Y):Z<63?G=R(this,$,Y):Z<1024?G=v(this,$,Y):G=q(this,$,Y),G};function g($,Y){this.x=$,this.y=Y}g.prototype.makeRBT=function($){for(var Y=new Array($),G=X.prototype._countBits($)-1,Z=0;Z<$;Z++)Y[Z]=this.revBin(Z,G,$);return Y},g.prototype.revBin=function($,Y,G){if($===0||$===G-1)return $;for(var Z=0,V=0;V>=1;return Z},g.prototype.permute=function($,Y,G,Z,V,I){for(var O=0;O>>1)V++;return 1<>>13,G[2*I+1]=V&8191,V=V>>>13;for(I=2*Y;I>=26,Y+=Z/67108864|0,Y+=V>>>26,this.words[G]=V&67108863}return Y!==0&&(this.words[G]=Y,this.length++),this},X.prototype.muln=function($){return this.clone().imuln($)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function($){var Y=E($);if(Y.length===0)return new X(1);for(var G=this,Z=0;Z=0);var Y=$%26,G=($-Y)/26,Z=67108863>>>26-Y<<26-Y,V;if(Y!==0){var I=0;for(V=0;V>>26-Y}I&&(this.words[V]=I,this.length++)}if(G!==0){for(V=this.length-1;V>=0;V--)this.words[V+G]=this.words[V];for(V=0;V=0);var Z;Y?Z=(Y-Y%26)/26:Z=0;var V=$%26,I=Math.min(($-V)/26,this.length),O=67108863^67108863>>>V<I)for(this.length-=I,Q=0;Q=0&&(K!==0||Q>=Z);Q--){var L=this.words[Q]|0;this.words[Q]=K<<26-V|L>>>V,K=L&O}return U&&K!==0&&(U.words[U.length++]=K),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},X.prototype.ishrn=function($,Y,G){return F(this.negative===0),this.iushrn($,Y,G)},X.prototype.shln=function($){return this.clone().ishln($)},X.prototype.ushln=function($){return this.clone().iushln($)},X.prototype.shrn=function($){return this.clone().ishrn($)},X.prototype.ushrn=function($){return this.clone().iushrn($)},X.prototype.testn=function($){F(typeof $=="number"&&$>=0);var Y=$%26,G=($-Y)/26,Z=1<=0);var Y=$%26,G=($-Y)/26;if(F(this.negative===0,"imaskn works only with positive numbers"),this.length<=G)return this;if(Y!==0&&G++,this.length=Math.min(G,this.length),Y!==0){var Z=67108863^67108863>>>Y<=67108864;Y++)this.words[Y]-=67108864,Y===this.length-1?this.words[Y+1]=1:this.words[Y+1]++;return this.length=Math.max(this.length,Y+1),this},X.prototype.isubn=function($){if(F(typeof $=="number"),F($<67108864),$<0)return this.iaddn(-$);if(this.negative!==0)return this.negative=0,this.iaddn($),this.negative=1,this;if(this.words[0]-=$,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Y=0;Y>26)-(U/67108864|0),this.words[V+G]=I&67108863}for(;V>26,this.words[V+G]=I&67108863;if(O===0)return this.strip();for(F(O===-1),O=0,V=0;V>26,this.words[V]=I&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function($,Y){var G=this.length-$.length,Z=this.clone(),V=$,I=V.words[V.length-1]|0,O=this._countBits(I);G=26-O,G!==0&&(V=V.ushln(G),Z.iushln(G),I=V.words[V.length-1]|0);var U=Z.length-V.length,Q;if(Y!=="mod"){Q=new X(null),Q.length=U+1,Q.words=new Array(Q.length);for(var K=0;K=0;A--){var S=(Z.words[V.length+A]|0)*67108864+(Z.words[V.length+A-1]|0);for(S=Math.min(S/I|0,67108863),Z._ishlnsubmul(V,S,A);Z.negative!==0;)S--,Z.negative=0,Z._ishlnsubmul(V,1,A),Z.isZero()||(Z.negative^=1);Q&&(Q.words[A]=S)}return Q&&Q.strip(),Z.strip(),Y!=="div"&&G!==0&&Z.iushrn(G),{div:Q||null,mod:Z}},X.prototype.divmod=function($,Y,G){if(F(!$.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var Z,V,I;return this.negative!==0&&$.negative===0?(I=this.neg().divmod($,Y),Y!=="mod"&&(Z=I.div.neg()),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.iadd($)),{div:Z,mod:V}):this.negative===0&&$.negative!==0?(I=this.divmod($.neg(),Y),Y!=="mod"&&(Z=I.div.neg()),{div:Z,mod:I.mod}):(this.negative&$.negative)!==0?(I=this.neg().divmod($.neg(),Y),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.isub($)),{div:I.div,mod:V}):$.length>this.length||this.cmp($)<0?{div:new X(0),mod:this}:$.length===1?Y==="div"?{div:this.divn($.words[0]),mod:null}:Y==="mod"?{div:null,mod:new X(this.modn($.words[0]))}:{div:this.divn($.words[0]),mod:new X(this.modn($.words[0]))}:this._wordDiv($,Y)},X.prototype.div=function($){return this.divmod($,"div",!1).div},X.prototype.mod=function($){return this.divmod($,"mod",!1).mod},X.prototype.umod=function($){return this.divmod($,"mod",!0).mod},X.prototype.divRound=function($){var Y=this.divmod($);if(Y.mod.isZero())return Y.div;var G=Y.div.negative!==0?Y.mod.isub($):Y.mod,Z=$.ushrn(1),V=$.andln(1),I=G.cmp(Z);return I<0||V===1&&I===0?Y.div:Y.div.negative!==0?Y.div.isubn(1):Y.div.iaddn(1)},X.prototype.modn=function($){F($<=67108863);for(var Y=(1<<26)%$,G=0,Z=this.length-1;Z>=0;Z--)G=(Y*G+(this.words[Z]|0))%$;return G},X.prototype.idivn=function($){F($<=67108863);for(var Y=0,G=this.length-1;G>=0;G--){var Z=(this.words[G]|0)+Y*67108864;this.words[G]=Z/$|0,Y=Z%$}return this.strip()},X.prototype.divn=function($){return this.clone().idivn($)},X.prototype.egcd=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=new X(0),O=new X(1),U=0;Y.isEven()&&G.isEven();)Y.iushrn(1),G.iushrn(1),++U;for(var Q=G.clone(),K=Y.clone();!Y.isZero();){for(var L=0,A=1;(Y.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0)for(Y.iushrn(L);L-- >0;)(Z.isOdd()||V.isOdd())&&(Z.iadd(Q),V.isub(K)),Z.iushrn(1),V.iushrn(1);for(var S=0,x=1;(G.words[0]&x)===0&&S<26;++S,x<<=1);if(S>0)for(G.iushrn(S);S-- >0;)(I.isOdd()||O.isOdd())&&(I.iadd(Q),O.isub(K)),I.iushrn(1),O.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(I),V.isub(O)):(G.isub(Y),I.isub(Z),O.isub(V))}return{a:I,b:O,gcd:G.iushln(U)}},X.prototype._invmp=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=G.clone();Y.cmpn(1)>0&&G.cmpn(1)>0;){for(var O=0,U=1;(Y.words[0]&U)===0&&O<26;++O,U<<=1);if(O>0)for(Y.iushrn(O);O-- >0;)Z.isOdd()&&Z.iadd(I),Z.iushrn(1);for(var Q=0,K=1;(G.words[0]&K)===0&&Q<26;++Q,K<<=1);if(Q>0)for(G.iushrn(Q);Q-- >0;)V.isOdd()&&V.iadd(I),V.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(V)):(G.isub(Y),V.isub(Z))}var L;return Y.cmpn(1)===0?L=Z:L=V,L.cmpn(0)<0&&L.iadd($),L},X.prototype.gcd=function($){if(this.isZero())return $.abs();if($.isZero())return this.abs();var Y=this.clone(),G=$.clone();Y.negative=0,G.negative=0;for(var Z=0;Y.isEven()&&G.isEven();Z++)Y.iushrn(1),G.iushrn(1);do{for(;Y.isEven();)Y.iushrn(1);for(;G.isEven();)G.iushrn(1);var V=Y.cmp(G);if(V<0){var I=Y;Y=G,G=I}else if(V===0||G.cmpn(1)===0)break;Y.isub(G)}while(!0);return G.iushln(Z)},X.prototype.invm=function($){return this.egcd($).a.umod($)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function($){return this.words[0]&$},X.prototype.bincn=function($){F(typeof $=="number");var Y=$%26,G=($-Y)/26,Z=1<>>26,O&=67108863,this.words[I]=O}return V!==0&&(this.words[I]=V,this.length++),this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function($){var Y=$<0;if(this.negative!==0&&!Y)return-1;if(this.negative===0&&Y)return 1;this.strip();var G;if(this.length>1)G=1;else{Y&&($=-$),F($<=67108863,"Number is too big");var Z=this.words[0]|0;G=Z===$?0:Z<$?-1:1}return this.negative!==0?-G|0:G},X.prototype.cmp=function($){if(this.negative!==0&&$.negative===0)return-1;if(this.negative===0&&$.negative!==0)return 1;var Y=this.ucmp($);return this.negative!==0?-Y|0:Y},X.prototype.ucmp=function($){if(this.length>$.length)return 1;if(this.length<$.length)return-1;for(var Y=0,G=this.length-1;G>=0;G--){var Z=this.words[G]|0,V=$.words[G]|0;if(Z!==V){ZV&&(Y=1);break}}return Y},X.prototype.gtn=function($){return this.cmpn($)===1},X.prototype.gt=function($){return this.cmp($)===1},X.prototype.gten=function($){return this.cmpn($)>=0},X.prototype.gte=function($){return this.cmp($)>=0},X.prototype.ltn=function($){return this.cmpn($)===-1},X.prototype.lt=function($){return this.cmp($)===-1},X.prototype.lten=function($){return this.cmpn($)<=0},X.prototype.lte=function($){return this.cmp($)<=0},X.prototype.eqn=function($){return this.cmpn($)===0},X.prototype.eq=function($){return this.cmp($)===0},X.red=function($){return new p($)},X.prototype.toRed=function($){return F(!this.red,"Already a number in reduction context"),F(this.negative===0,"red works only with positives"),$.convertTo(this)._forceRed($)},X.prototype.fromRed=function(){return F(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function($){return this.red=$,this},X.prototype.forceRed=function($){return F(!this.red,"Already a number in reduction context"),this._forceRed($)},X.prototype.redAdd=function($){return F(this.red,"redAdd works only with red numbers"),this.red.add(this,$)},X.prototype.redIAdd=function($){return F(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,$)},X.prototype.redSub=function($){return F(this.red,"redSub works only with red numbers"),this.red.sub(this,$)},X.prototype.redISub=function($){return F(this.red,"redISub works only with red numbers"),this.red.isub(this,$)},X.prototype.redShl=function($){return F(this.red,"redShl works only with red numbers"),this.red.shl(this,$)},X.prototype.redMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.mul(this,$)},X.prototype.redIMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.imul(this,$)},X.prototype.redSqr=function(){return F(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return F(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return F(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return F(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return F(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function($){return F(this.red&&!$.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,$)};var B={k256:null,p224:null,p192:null,p25519:null};function w($,Y){this.name=$,this.p=new X(Y,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}w.prototype._tmp=function(){var $=new X(null);return $.words=new Array(Math.ceil(this.n/13)),$},w.prototype.ireduce=function($){var Y=$,G;do this.split(Y,this.tmp),Y=this.imulK(Y),Y=Y.iadd(this.tmp),G=Y.bitLength();while(G>this.n);var Z=G0?Y.isub(this.p):Y.strip!==void 0?Y.strip():Y._strip(),Y},w.prototype.split=function($,Y){$.iushrn(this.n,0,Y)},w.prototype.imulK=function($){return $.imul(this.k)};function f(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}P(f,w),f.prototype.split=function($,Y){for(var G=4194303,Z=Math.min($.length,9),V=0;V>>22,I=O}I>>>=22,$.words[V-10]=I,I===0&&$.length>10?$.length-=10:$.length-=9},f.prototype.imulK=function($){$.words[$.length]=0,$.words[$.length+1]=0,$.length+=2;for(var Y=0,G=0;G<$.length;G++){var Z=$.words[G]|0;Y+=Z*977,$.words[G]=Y&67108863,Y=Z*64+(Y/67108864|0)}return $.words[$.length-1]===0&&($.length--,$.words[$.length-1]===0&&$.length--),$};function b(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}P(b,w);function u(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}P(u,w);function Y0(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}P(Y0,w),Y0.prototype.imulK=function($){for(var Y=0,G=0;G<$.length;G++){var Z=($.words[G]|0)*19+Y,V=Z&67108863;Z>>>=26,$.words[G]=V,Y=Z}return Y!==0&&($.words[$.length++]=Y),$},X._prime=function($){if(B[$])return B[$];var Y;if($==="k256")Y=new f;else if($==="p224")Y=new b;else if($==="p192")Y=new u;else if($==="p25519")Y=new Y0;else throw new Error("Unknown prime "+$);return B[$]=Y,Y};function p($){if(typeof $=="string"){var Y=X._prime($);this.m=Y.p,this.prime=Y}else F($.gtn(1),"modulus must be greater than 1"),this.m=$,this.prime=null}p.prototype._verify1=function($){F($.negative===0,"red works only with positives"),F($.red,"red works only with red numbers")},p.prototype._verify2=function($,Y){F(($.negative|Y.negative)===0,"red works only with positives"),F($.red&&$.red===Y.red,"red works only with red numbers")},p.prototype.imod=function($){return this.prime?this.prime.ireduce($)._forceRed(this):$.umod(this.m)._forceRed(this)},p.prototype.neg=function($){return $.isZero()?$.clone():this.m.sub($)._forceRed(this)},p.prototype.add=function($,Y){this._verify2($,Y);var G=$.add(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G._forceRed(this)},p.prototype.iadd=function($,Y){this._verify2($,Y);var G=$.iadd(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G},p.prototype.sub=function($,Y){this._verify2($,Y);var G=$.sub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G._forceRed(this)},p.prototype.isub=function($,Y){this._verify2($,Y);var G=$.isub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G},p.prototype.shl=function($,Y){return this._verify1($),this.imod($.ushln(Y))},p.prototype.imul=function($,Y){return this._verify2($,Y),this.imod($.imul(Y))},p.prototype.mul=function($,Y){return this._verify2($,Y),this.imod($.mul(Y))},p.prototype.isqr=function($){return this.imul($,$.clone())},p.prototype.sqr=function($){return this.mul($,$)},p.prototype.sqrt=function($){if($.isZero())return $.clone();var Y=this.m.andln(3);if(F(Y%2===1),Y===3){var G=this.m.add(new X(1)).iushrn(2);return this.pow($,G)}for(var Z=this.m.subn(1),V=0;!Z.isZero()&&Z.andln(1)===0;)V++,Z.iushrn(1);F(!Z.isZero());var I=new X(1).toRed(this),O=I.redNeg(),U=this.m.subn(1).iushrn(1),Q=this.m.bitLength();for(Q=new X(2*Q*Q).toRed(this);this.pow(Q,U).cmp(O)!==0;)Q.redIAdd(O);for(var K=this.pow(Q,Z),L=this.pow($,Z.addn(1).iushrn(1)),A=this.pow($,Z),S=V;A.cmp(I)!==0;){for(var x=A,y=0;x.cmp(I)!==0;y++)x=x.redSqr();F(y=0;V--){for(var K=Y.words[V],L=Q-1;L>=0;L--){var A=K>>L&1;if(I!==Z[0]&&(I=this.sqr(I)),A===0&&O===0){U=0;continue}O<<=1,O|=A,U++,!(U!==G&&(V!==0||L!==0))&&(I=this.mul(I,Z[O]),U=0,O=0)}Q=26}return I},p.prototype.convertTo=function($){var Y=$.umod(this.m);return Y===$?Y.clone():Y},p.prototype.convertFrom=function($){var Y=$.clone();return Y.red=null,Y},X.mont=function($){return new v0($)};function v0($){p.call(this,$),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new X(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}P(v0,p),v0.prototype.convertTo=function($){return this.imod($.ushln(this.shift))},v0.prototype.convertFrom=function($){var Y=this.imod($.mul(this.rinv));return Y.red=null,Y},v0.prototype.imul=function($,Y){if($.isZero()||Y.isZero())return $.words[0]=0,$.length=1,$;var G=$.imul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.mul=function($,Y){if($.isZero()||Y.isZero())return new X(0)._forceRed(this);var G=$.mul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.invm=function($){var Y=this.imod($._invmp(this.m).mul(this.r2));return Y._forceRed(this)}})(typeof _>"u"||_,N)}}),AZ=S0({"(disabled):node_modules/crypto-browserify/index.js"(){}}),c$=S0({"node_modules/brorand/index.js"(N,_){var j;_.exports=function(F){return j||(j=new k(null)),j.generate(F)};function k(F){this.rand=F}_.exports.Rand=k,k.prototype.generate=function(F){return this._rand(F)},k.prototype._rand=function(F){var P=new j0(F);return W$.getRandomValues(P),P}}}),PQ=S0({"node_modules/miller-rabin/lib/mr.js"(N,_){var j=DY(),k=c$();function F(P){this.rand=P||new k.Rand}_.exports=F,F.create=function(P){return new F(P)},F.prototype._randbelow=function(P){var X=P.bitLength(),C=Math.ceil(X/8);do var z=new j(this.rand.generate(C));while(z.cmp(P)>=0);return z},F.prototype._randrange=function(P,X){var C=X.sub(P);return P.add(this._randbelow(C))},F.prototype.test=function(P,X,C){var z=P.bitLength(),T=j.mont(P),H=new j(1).toRed(T);X||(X=Math.max(1,z/48|0));for(var J=P.subn(1),W=0;!J.testn(W);W++);for(var D=P.shrn(W),E=J.toRed(T),R=!0;X>0;X--){var M=this._randrange(new j(2),J);C&&C(M);var v=M.toRed(T).redPow(D);if(!(v.cmp(H)===0||v.cmp(E)===0)){for(var q=1;q0;X--){var E=this._randrange(new j(2),H),R=P.gcd(E);if(R.cmpn(1)!==0)return R;var M=E.toRed(z).redPow(W);if(!(M.cmp(T)===0||M.cmp(D)===0)){for(var v=1;vb;)Y0.ishrn(1);if(Y0.isEven()&&Y0.iadd(C),Y0.testn(1)||Y0.iadd(z),u.cmp(z)){if(!u.cmp(T))for(;Y0.mod(W).cmp(D);)Y0.iadd(M)}else for(;Y0.mod(F).cmp(R);)Y0.iadd(M);if(p=Y0.shrn(1),B(p)&&B(Y0)&&w(p)&&w(Y0)&&X.test(p)&&X.test(Y0))return Y0}}}}),CY=S0({"node_modules/diffie-hellman/lib/primes.json"(N,_){_.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}}}),LY=S0({"node_modules/diffie-hellman/lib/dh.js"(N,_){var j=zQ(),k=PQ(),F=new k,P=new j(24),X=new j(11),C=new j(10),z=new j(3),T=new j(7),H=MQ(),J=L$();_.exports=M;function W(q,g){return g=g||"utf8",j0.isBuffer(q)||(q=new j0(q,g)),this._pub=new j(q),this}function D(q,g){return g=g||"utf8",j0.isBuffer(q)||(q=new j0(q,g)),this._priv=new j(q),this}var E={};function R(q,g){var B=g.toString("hex"),w=[B,q.toString(16)].join("_");if(w in E)return E[w];var f=0;if(q.isEven()||!H.simpleSieve||!H.fermatTest(q)||!F.test(q))return f+=1,B==="02"||B==="05"?f+=8:f+=4,E[w]=f,f;F.test(q.shrn(1))||(f+=2);var b;switch(B){case"02":q.mod(P).cmp(X)&&(f+=8);break;case"05":b=q.mod(C),b.cmp(z)&&b.cmp(T)&&(f+=8);break;default:f+=4}return E[w]=f,f}function M(q,g,B){this.setGenerator(g),this.__prime=new j(q),this._prime=j.mont(this.__prime),this._primeLen=q.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,B?(this.setPublicKey=W,this.setPrivateKey=D):this._primeCode=8}Object.defineProperty(M.prototype,"verifyError",{enumerable:!0,get:function(){return typeof this._primeCode!="number"&&(this._primeCode=R(this.__prime,this.__gen)),this._primeCode}}),M.prototype.generateKeys=function(){return this._priv||(this._priv=new j(J(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},M.prototype.computeSecret=function(q){q=new j(q),q=q.toRed(this._prime);var g=q.redPow(this._priv).fromRed(),B=new j0(g.toArray()),w=this.getPrime();if(B.length0?Z:V},X.min=function(Z,V){return Z.cmp(V)<0?Z:V},X.prototype._init=function(Z,V,I){if(typeof Z=="number")return this._initNumber(Z,V,I);if(typeof Z=="object")return this._initArray(Z,V,I);V==="hex"&&(V=16),F(V===(V|0)&&V>=2&&V<=36),Z=Z.toString().replace(/\s+/g,"");var O=0;Z[0]==="-"&&(O++,this.negative=1),O=0;O-=3)Q=Z[O]|Z[O-1]<<8|Z[O-2]<<16,this.words[U]|=Q<>>26-K&67108863,K+=24,K>=26&&(K-=26,U++);else if(I==="le")for(O=0,U=0;O>>26-K&67108863,K+=24,K>=26&&(K-=26,U++);return this._strip()};function z(Z,V){var I=Z.charCodeAt(V);if(I>=48&&I<=57)return I-48;if(I>=65&&I<=70)return I-55;if(I>=97&&I<=102)return I-87;F(!1,"Invalid character in "+Z)}function T(Z,V,I){var O=z(Z,I);return I-1>=V&&(O|=z(Z,I-1)<<4),O}X.prototype._parseHex=function(Z,V,I){this.length=Math.ceil((Z.length-V)/6),this.words=new Array(this.length);for(var O=0;O=V;O-=2)K=T(Z,V,O)<=18?(U-=18,Q+=1,this.words[Q]|=K>>>26):U+=8;else{var L=Z.length-V;for(O=L%2===0?V+1:V;O=18?(U-=18,Q+=1,this.words[Q]|=K>>>26):U+=8}this._strip()};function H(Z,V,I,O){for(var U=0,Q=0,K=Math.min(Z.length,I),L=V;L=49?Q=A-49+10:A>=17?Q=A-17+10:Q=A,F(A>=0&&Q1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},X.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{X.prototype[Symbol.for("nodejs.util.inspect.custom")]=W}catch{X.prototype.inspect=W}else X.prototype.inspect=W;function W(){return(this.red?""}var D=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],E=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],R=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];X.prototype.toString=function(Z,V){Z=Z||10,V=V|0||1;var I;if(Z===16||Z==="hex"){I="";for(var O=0,U=0,Q=0;Q>>24-O&16777215,O+=2,O>=26&&(O-=26,Q--),U!==0||Q!==this.length-1?I=D[6-L.length]+L+I:I=L+I}for(U!==0&&(I=U.toString(16)+I);I.length%V!==0;)I="0"+I;return this.negative!==0&&(I="-"+I),I}if(Z===(Z|0)&&Z>=2&&Z<=36){var A=E[Z],S=R[Z];I="";var x=this.clone();for(x.negative=0;!x.isZero();){var y=x.modrn(S).toString(Z);x=x.idivn(S),x.isZero()?I=y+I:I=D[A-y.length]+y+I}for(this.isZero()&&(I="0"+I);I.length%V!==0;)I="0"+I;return this.negative!==0&&(I="-"+I),I}F(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var Z=this.words[0];return this.length===2?Z+=this.words[1]*67108864:this.length===3&&this.words[2]===1?Z+=4503599627370496+this.words[1]*67108864:this.length>2&&F(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-Z:Z},X.prototype.toJSON=function(){return this.toString(16,2)},C&&(X.prototype.toBuffer=function(Z,V){return this.toArrayLike(C,Z,V)}),X.prototype.toArray=function(Z,V){return this.toArrayLike(Array,Z,V)};var M=function(Z,V){return Z.allocUnsafe?Z.allocUnsafe(V):new Z(V)};X.prototype.toArrayLike=function(Z,V,I){this._strip();var O=this.byteLength(),U=I||Math.max(1,O);F(O<=U,"byte array longer than desired length"),F(U>0,"Requested array length <= 0");var Q=M(Z,U),K=V==="le"?"LE":"BE";return this["_toArrayLike"+K](Q,O),Q},X.prototype._toArrayLikeLE=function(Z,V){for(var I=0,O=0,U=0,Q=0;U>8&255),I>16&255),Q===6?(I>24&255),O=0,Q=0):(O=K>>>24,Q+=2)}if(I=0&&(Z[I--]=K>>8&255),I>=0&&(Z[I--]=K>>16&255),Q===6?(I>=0&&(Z[I--]=K>>24&255),O=0,Q=0):(O=K>>>24,Q+=2)}if(I>=0)for(Z[I--]=O;I>=0;)Z[I--]=0},Math.clz32?X.prototype._countBits=function(Z){return 32-Math.clz32(Z)}:X.prototype._countBits=function(Z){var V=Z,I=0;return V>=4096&&(I+=13,V>>>=13),V>=64&&(I+=7,V>>>=7),V>=8&&(I+=4,V>>>=4),V>=2&&(I+=2,V>>>=2),I+V},X.prototype._zeroBits=function(Z){if(Z===0)return 26;var V=Z,I=0;return(V&8191)===0&&(I+=13,V>>>=13),(V&127)===0&&(I+=7,V>>>=7),(V&15)===0&&(I+=4,V>>>=4),(V&3)===0&&(I+=2,V>>>=2),(V&1)===0&&I++,I},X.prototype.bitLength=function(){var Z=this.words[this.length-1],V=this._countBits(Z);return(this.length-1)*26+V};function v(Z){for(var V=new Array(Z.bitLength()),I=0;I>>U&1}return V}X.prototype.zeroBits=function(){if(this.isZero())return 0;for(var Z=0,V=0;VZ.length?this.clone().ior(Z):Z.clone().ior(this)},X.prototype.uor=function(Z){return this.length>Z.length?this.clone().iuor(Z):Z.clone().iuor(this)},X.prototype.iuand=function(Z){var V;this.length>Z.length?V=Z:V=this;for(var I=0;IZ.length?this.clone().iand(Z):Z.clone().iand(this)},X.prototype.uand=function(Z){return this.length>Z.length?this.clone().iuand(Z):Z.clone().iuand(this)},X.prototype.iuxor=function(Z){var V,I;this.length>Z.length?(V=this,I=Z):(V=Z,I=this);for(var O=0;OZ.length?this.clone().ixor(Z):Z.clone().ixor(this)},X.prototype.uxor=function(Z){return this.length>Z.length?this.clone().iuxor(Z):Z.clone().iuxor(this)},X.prototype.inotn=function(Z){F(typeof Z=="number"&&Z>=0);var V=Math.ceil(Z/26)|0,I=Z%26;this._expand(V),I>0&&V--;for(var O=0;O0&&(this.words[O]=~this.words[O]&67108863>>26-I),this._strip()},X.prototype.notn=function(Z){return this.clone().inotn(Z)},X.prototype.setn=function(Z,V){F(typeof Z=="number"&&Z>=0);var I=Z/26|0,O=Z%26;return this._expand(I+1),V?this.words[I]=this.words[I]|1<Z.length?(I=this,O=Z):(I=Z,O=this);for(var U=0,Q=0;Q>>26;for(;U!==0&&Q>>26;if(this.length=I.length,U!==0)this.words[this.length]=U,this.length++;else if(I!==this)for(;QZ.length?this.clone().iadd(Z):Z.clone().iadd(this)},X.prototype.isub=function(Z){if(Z.negative!==0){Z.negative=0;var V=this.iadd(Z);return Z.negative=1,V._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(Z),this.negative=1,this._normSign();var I=this.cmp(Z);if(I===0)return this.negative=0,this.length=1,this.words[0]=0,this;var O,U;I>0?(O=this,U=Z):(O=Z,U=this);for(var Q=0,K=0;K>26,this.words[K]=V&67108863;for(;Q!==0&&K>26,this.words[K]=V&67108863;if(Q===0&&K>>26,y=A&67108863,c=Math.min(S,V.length-1),q0=Math.max(0,S-Z.length+1);q0<=c;q0++){var h=S-q0|0;U=Z.words[h]|0,Q=V.words[q0]|0,K=U*Q+y,x+=K/67108864|0,y=K&67108863}I.words[S]=y|0,A=x|0}return A!==0?I.words[S]=A|0:I.length--,I._strip()}var g=function(Z,V,I){var O=Z.words,U=V.words,Q=I.words,K=0,L,A,S,x=O[0]|0,y=x&8191,c=x>>>13,q0=O[1]|0,h=q0&8191,d=q0>>>13,_0=O[2]|0,l=_0&8191,n=_0>>>13,y0=O[3]|0,t=y0&8191,s=y0>>>13,w0=O[4]|0,m=w0&8191,r=w0>>>13,$$=O[5]|0,i=$$&8191,e=$$>>>13,x0=O[6]|0,o=x0&8191,a=x0>>>13,p0=O[7]|0,$0=p0&8191,Q0=p0>>>13,Y$=O[8]|0,Z0=Y$&8191,G0=Y$>>>13,Z$=O[9]|0,V0=Z$&8191,U0=Z$>>>13,G$=U[0]|0,X0=G$&8191,K0=G$>>>13,V$=U[1]|0,I0=V$&8191,O0=V$>>>13,U$=U[2]|0,J0=U$&8191,F0=U$>>>13,X$=U[3]|0,A0=X$&8191,W0=X$>>>13,K$=U[4]|0,H0=K$&8191,E0=K$>>>13,I$=U[5]|0,T0=I$&8191,D0=I$>>>13,O$=U[6]|0,C0=O$&8191,L0=O$>>>13,J$=U[7]|0,R0=J$&8191,z0=J$>>>13,F$=U[8]|0,P0=F$&8191,M0=F$>>>13,Q$=U[9]|0,k0=Q$&8191,g0=Q$>>>13;I.negative=Z.negative^V.negative,I.length=19,L=Math.imul(y,X0),A=Math.imul(y,K0),A=A+Math.imul(c,X0)|0,S=Math.imul(c,K0);var f0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(f0>>>26)|0,f0&=67108863,L=Math.imul(h,X0),A=Math.imul(h,K0),A=A+Math.imul(d,X0)|0,S=Math.imul(d,K0),L=L+Math.imul(y,I0)|0,A=A+Math.imul(y,O0)|0,A=A+Math.imul(c,I0)|0,S=S+Math.imul(c,O0)|0;var c0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(c0>>>26)|0,c0&=67108863,L=Math.imul(l,X0),A=Math.imul(l,K0),A=A+Math.imul(n,X0)|0,S=Math.imul(n,K0),L=L+Math.imul(h,I0)|0,A=A+Math.imul(h,O0)|0,A=A+Math.imul(d,I0)|0,S=S+Math.imul(d,O0)|0,L=L+Math.imul(y,J0)|0,A=A+Math.imul(y,F0)|0,A=A+Math.imul(c,J0)|0,S=S+Math.imul(c,F0)|0;var h0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(h0>>>26)|0,h0&=67108863,L=Math.imul(t,X0),A=Math.imul(t,K0),A=A+Math.imul(s,X0)|0,S=Math.imul(s,K0),L=L+Math.imul(l,I0)|0,A=A+Math.imul(l,O0)|0,A=A+Math.imul(n,I0)|0,S=S+Math.imul(n,O0)|0,L=L+Math.imul(h,J0)|0,A=A+Math.imul(h,F0)|0,A=A+Math.imul(d,J0)|0,S=S+Math.imul(d,F0)|0,L=L+Math.imul(y,A0)|0,A=A+Math.imul(y,W0)|0,A=A+Math.imul(c,A0)|0,S=S+Math.imul(c,W0)|0;var d0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(d0>>>26)|0,d0&=67108863,L=Math.imul(m,X0),A=Math.imul(m,K0),A=A+Math.imul(r,X0)|0,S=Math.imul(r,K0),L=L+Math.imul(t,I0)|0,A=A+Math.imul(t,O0)|0,A=A+Math.imul(s,I0)|0,S=S+Math.imul(s,O0)|0,L=L+Math.imul(l,J0)|0,A=A+Math.imul(l,F0)|0,A=A+Math.imul(n,J0)|0,S=S+Math.imul(n,F0)|0,L=L+Math.imul(h,A0)|0,A=A+Math.imul(h,W0)|0,A=A+Math.imul(d,A0)|0,S=S+Math.imul(d,W0)|0,L=L+Math.imul(y,H0)|0,A=A+Math.imul(y,E0)|0,A=A+Math.imul(c,H0)|0,S=S+Math.imul(c,E0)|0;var b0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(b0>>>26)|0,b0&=67108863,L=Math.imul(i,X0),A=Math.imul(i,K0),A=A+Math.imul(e,X0)|0,S=Math.imul(e,K0),L=L+Math.imul(m,I0)|0,A=A+Math.imul(m,O0)|0,A=A+Math.imul(r,I0)|0,S=S+Math.imul(r,O0)|0,L=L+Math.imul(t,J0)|0,A=A+Math.imul(t,F0)|0,A=A+Math.imul(s,J0)|0,S=S+Math.imul(s,F0)|0,L=L+Math.imul(l,A0)|0,A=A+Math.imul(l,W0)|0,A=A+Math.imul(n,A0)|0,S=S+Math.imul(n,W0)|0,L=L+Math.imul(h,H0)|0,A=A+Math.imul(h,E0)|0,A=A+Math.imul(d,H0)|0,S=S+Math.imul(d,E0)|0,L=L+Math.imul(y,T0)|0,A=A+Math.imul(y,D0)|0,A=A+Math.imul(c,T0)|0,S=S+Math.imul(c,D0)|0;var l0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(l0>>>26)|0,l0&=67108863,L=Math.imul(o,X0),A=Math.imul(o,K0),A=A+Math.imul(a,X0)|0,S=Math.imul(a,K0),L=L+Math.imul(i,I0)|0,A=A+Math.imul(i,O0)|0,A=A+Math.imul(e,I0)|0,S=S+Math.imul(e,O0)|0,L=L+Math.imul(m,J0)|0,A=A+Math.imul(m,F0)|0,A=A+Math.imul(r,J0)|0,S=S+Math.imul(r,F0)|0,L=L+Math.imul(t,A0)|0,A=A+Math.imul(t,W0)|0,A=A+Math.imul(s,A0)|0,S=S+Math.imul(s,W0)|0,L=L+Math.imul(l,H0)|0,A=A+Math.imul(l,E0)|0,A=A+Math.imul(n,H0)|0,S=S+Math.imul(n,E0)|0,L=L+Math.imul(h,T0)|0,A=A+Math.imul(h,D0)|0,A=A+Math.imul(d,T0)|0,S=S+Math.imul(d,D0)|0,L=L+Math.imul(y,C0)|0,A=A+Math.imul(y,L0)|0,A=A+Math.imul(c,C0)|0,S=S+Math.imul(c,L0)|0;var o0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(o0>>>26)|0,o0&=67108863,L=Math.imul($0,X0),A=Math.imul($0,K0),A=A+Math.imul(Q0,X0)|0,S=Math.imul(Q0,K0),L=L+Math.imul(o,I0)|0,A=A+Math.imul(o,O0)|0,A=A+Math.imul(a,I0)|0,S=S+Math.imul(a,O0)|0,L=L+Math.imul(i,J0)|0,A=A+Math.imul(i,F0)|0,A=A+Math.imul(e,J0)|0,S=S+Math.imul(e,F0)|0,L=L+Math.imul(m,A0)|0,A=A+Math.imul(m,W0)|0,A=A+Math.imul(r,A0)|0,S=S+Math.imul(r,W0)|0,L=L+Math.imul(t,H0)|0,A=A+Math.imul(t,E0)|0,A=A+Math.imul(s,H0)|0,S=S+Math.imul(s,E0)|0,L=L+Math.imul(l,T0)|0,A=A+Math.imul(l,D0)|0,A=A+Math.imul(n,T0)|0,S=S+Math.imul(n,D0)|0,L=L+Math.imul(h,C0)|0,A=A+Math.imul(h,L0)|0,A=A+Math.imul(d,C0)|0,S=S+Math.imul(d,L0)|0,L=L+Math.imul(y,R0)|0,A=A+Math.imul(y,z0)|0,A=A+Math.imul(c,R0)|0,S=S+Math.imul(c,z0)|0;var u0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(u0>>>26)|0,u0&=67108863,L=Math.imul(Z0,X0),A=Math.imul(Z0,K0),A=A+Math.imul(G0,X0)|0,S=Math.imul(G0,K0),L=L+Math.imul($0,I0)|0,A=A+Math.imul($0,O0)|0,A=A+Math.imul(Q0,I0)|0,S=S+Math.imul(Q0,O0)|0,L=L+Math.imul(o,J0)|0,A=A+Math.imul(o,F0)|0,A=A+Math.imul(a,J0)|0,S=S+Math.imul(a,F0)|0,L=L+Math.imul(i,A0)|0,A=A+Math.imul(i,W0)|0,A=A+Math.imul(e,A0)|0,S=S+Math.imul(e,W0)|0,L=L+Math.imul(m,H0)|0,A=A+Math.imul(m,E0)|0,A=A+Math.imul(r,H0)|0,S=S+Math.imul(r,E0)|0,L=L+Math.imul(t,T0)|0,A=A+Math.imul(t,D0)|0,A=A+Math.imul(s,T0)|0,S=S+Math.imul(s,D0)|0,L=L+Math.imul(l,C0)|0,A=A+Math.imul(l,L0)|0,A=A+Math.imul(n,C0)|0,S=S+Math.imul(n,L0)|0,L=L+Math.imul(h,R0)|0,A=A+Math.imul(h,z0)|0,A=A+Math.imul(d,R0)|0,S=S+Math.imul(d,z0)|0,L=L+Math.imul(y,P0)|0,A=A+Math.imul(y,M0)|0,A=A+Math.imul(c,P0)|0,S=S+Math.imul(c,M0)|0;var n0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(n0>>>26)|0,n0&=67108863,L=Math.imul(V0,X0),A=Math.imul(V0,K0),A=A+Math.imul(U0,X0)|0,S=Math.imul(U0,K0),L=L+Math.imul(Z0,I0)|0,A=A+Math.imul(Z0,O0)|0,A=A+Math.imul(G0,I0)|0,S=S+Math.imul(G0,O0)|0,L=L+Math.imul($0,J0)|0,A=A+Math.imul($0,F0)|0,A=A+Math.imul(Q0,J0)|0,S=S+Math.imul(Q0,F0)|0,L=L+Math.imul(o,A0)|0,A=A+Math.imul(o,W0)|0,A=A+Math.imul(a,A0)|0,S=S+Math.imul(a,W0)|0,L=L+Math.imul(i,H0)|0,A=A+Math.imul(i,E0)|0,A=A+Math.imul(e,H0)|0,S=S+Math.imul(e,E0)|0,L=L+Math.imul(m,T0)|0,A=A+Math.imul(m,D0)|0,A=A+Math.imul(r,T0)|0,S=S+Math.imul(r,D0)|0,L=L+Math.imul(t,C0)|0,A=A+Math.imul(t,L0)|0,A=A+Math.imul(s,C0)|0,S=S+Math.imul(s,L0)|0,L=L+Math.imul(l,R0)|0,A=A+Math.imul(l,z0)|0,A=A+Math.imul(n,R0)|0,S=S+Math.imul(n,z0)|0,L=L+Math.imul(h,P0)|0,A=A+Math.imul(h,M0)|0,A=A+Math.imul(d,P0)|0,S=S+Math.imul(d,M0)|0,L=L+Math.imul(y,k0)|0,A=A+Math.imul(y,g0)|0,A=A+Math.imul(c,k0)|0,S=S+Math.imul(c,g0)|0;var s0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(s0>>>26)|0,s0&=67108863,L=Math.imul(V0,I0),A=Math.imul(V0,O0),A=A+Math.imul(U0,I0)|0,S=Math.imul(U0,O0),L=L+Math.imul(Z0,J0)|0,A=A+Math.imul(Z0,F0)|0,A=A+Math.imul(G0,J0)|0,S=S+Math.imul(G0,F0)|0,L=L+Math.imul($0,A0)|0,A=A+Math.imul($0,W0)|0,A=A+Math.imul(Q0,A0)|0,S=S+Math.imul(Q0,W0)|0,L=L+Math.imul(o,H0)|0,A=A+Math.imul(o,E0)|0,A=A+Math.imul(a,H0)|0,S=S+Math.imul(a,E0)|0,L=L+Math.imul(i,T0)|0,A=A+Math.imul(i,D0)|0,A=A+Math.imul(e,T0)|0,S=S+Math.imul(e,D0)|0,L=L+Math.imul(m,C0)|0,A=A+Math.imul(m,L0)|0,A=A+Math.imul(r,C0)|0,S=S+Math.imul(r,L0)|0,L=L+Math.imul(t,R0)|0,A=A+Math.imul(t,z0)|0,A=A+Math.imul(s,R0)|0,S=S+Math.imul(s,z0)|0,L=L+Math.imul(l,P0)|0,A=A+Math.imul(l,M0)|0,A=A+Math.imul(n,P0)|0,S=S+Math.imul(n,M0)|0,L=L+Math.imul(h,k0)|0,A=A+Math.imul(h,g0)|0,A=A+Math.imul(d,k0)|0,S=S+Math.imul(d,g0)|0;var t0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(t0>>>26)|0,t0&=67108863,L=Math.imul(V0,J0),A=Math.imul(V0,F0),A=A+Math.imul(U0,J0)|0,S=Math.imul(U0,F0),L=L+Math.imul(Z0,A0)|0,A=A+Math.imul(Z0,W0)|0,A=A+Math.imul(G0,A0)|0,S=S+Math.imul(G0,W0)|0,L=L+Math.imul($0,H0)|0,A=A+Math.imul($0,E0)|0,A=A+Math.imul(Q0,H0)|0,S=S+Math.imul(Q0,E0)|0,L=L+Math.imul(o,T0)|0,A=A+Math.imul(o,D0)|0,A=A+Math.imul(a,T0)|0,S=S+Math.imul(a,D0)|0,L=L+Math.imul(i,C0)|0,A=A+Math.imul(i,L0)|0,A=A+Math.imul(e,C0)|0,S=S+Math.imul(e,L0)|0,L=L+Math.imul(m,R0)|0,A=A+Math.imul(m,z0)|0,A=A+Math.imul(r,R0)|0,S=S+Math.imul(r,z0)|0,L=L+Math.imul(t,P0)|0,A=A+Math.imul(t,M0)|0,A=A+Math.imul(s,P0)|0,S=S+Math.imul(s,M0)|0,L=L+Math.imul(l,k0)|0,A=A+Math.imul(l,g0)|0,A=A+Math.imul(n,k0)|0,S=S+Math.imul(n,g0)|0;var m0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(m0>>>26)|0,m0&=67108863,L=Math.imul(V0,A0),A=Math.imul(V0,W0),A=A+Math.imul(U0,A0)|0,S=Math.imul(U0,W0),L=L+Math.imul(Z0,H0)|0,A=A+Math.imul(Z0,E0)|0,A=A+Math.imul(G0,H0)|0,S=S+Math.imul(G0,E0)|0,L=L+Math.imul($0,T0)|0,A=A+Math.imul($0,D0)|0,A=A+Math.imul(Q0,T0)|0,S=S+Math.imul(Q0,D0)|0,L=L+Math.imul(o,C0)|0,A=A+Math.imul(o,L0)|0,A=A+Math.imul(a,C0)|0,S=S+Math.imul(a,L0)|0,L=L+Math.imul(i,R0)|0,A=A+Math.imul(i,z0)|0,A=A+Math.imul(e,R0)|0,S=S+Math.imul(e,z0)|0,L=L+Math.imul(m,P0)|0,A=A+Math.imul(m,M0)|0,A=A+Math.imul(r,P0)|0,S=S+Math.imul(r,M0)|0,L=L+Math.imul(t,k0)|0,A=A+Math.imul(t,g0)|0,A=A+Math.imul(s,k0)|0,S=S+Math.imul(s,g0)|0;var a0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(a0>>>26)|0,a0&=67108863,L=Math.imul(V0,H0),A=Math.imul(V0,E0),A=A+Math.imul(U0,H0)|0,S=Math.imul(U0,E0),L=L+Math.imul(Z0,T0)|0,A=A+Math.imul(Z0,D0)|0,A=A+Math.imul(G0,T0)|0,S=S+Math.imul(G0,D0)|0,L=L+Math.imul($0,C0)|0,A=A+Math.imul($0,L0)|0,A=A+Math.imul(Q0,C0)|0,S=S+Math.imul(Q0,L0)|0,L=L+Math.imul(o,R0)|0,A=A+Math.imul(o,z0)|0,A=A+Math.imul(a,R0)|0,S=S+Math.imul(a,z0)|0,L=L+Math.imul(i,P0)|0,A=A+Math.imul(i,M0)|0,A=A+Math.imul(e,P0)|0,S=S+Math.imul(e,M0)|0,L=L+Math.imul(m,k0)|0,A=A+Math.imul(m,g0)|0,A=A+Math.imul(r,k0)|0,S=S+Math.imul(r,g0)|0;var e0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(e0>>>26)|0,e0&=67108863,L=Math.imul(V0,T0),A=Math.imul(V0,D0),A=A+Math.imul(U0,T0)|0,S=Math.imul(U0,D0),L=L+Math.imul(Z0,C0)|0,A=A+Math.imul(Z0,L0)|0,A=A+Math.imul(G0,C0)|0,S=S+Math.imul(G0,L0)|0,L=L+Math.imul($0,R0)|0,A=A+Math.imul($0,z0)|0,A=A+Math.imul(Q0,R0)|0,S=S+Math.imul(Q0,z0)|0,L=L+Math.imul(o,P0)|0,A=A+Math.imul(o,M0)|0,A=A+Math.imul(a,P0)|0,S=S+Math.imul(a,M0)|0,L=L+Math.imul(i,k0)|0,A=A+Math.imul(i,g0)|0,A=A+Math.imul(e,k0)|0,S=S+Math.imul(e,g0)|0;var r0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(r0>>>26)|0,r0&=67108863,L=Math.imul(V0,C0),A=Math.imul(V0,L0),A=A+Math.imul(U0,C0)|0,S=Math.imul(U0,L0),L=L+Math.imul(Z0,R0)|0,A=A+Math.imul(Z0,z0)|0,A=A+Math.imul(G0,R0)|0,S=S+Math.imul(G0,z0)|0,L=L+Math.imul($0,P0)|0,A=A+Math.imul($0,M0)|0,A=A+Math.imul(Q0,P0)|0,S=S+Math.imul(Q0,M0)|0,L=L+Math.imul(o,k0)|0,A=A+Math.imul(o,g0)|0,A=A+Math.imul(a,k0)|0,S=S+Math.imul(a,g0)|0;var i0=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(i0>>>26)|0,i0&=67108863,L=Math.imul(V0,R0),A=Math.imul(V0,z0),A=A+Math.imul(U0,R0)|0,S=Math.imul(U0,z0),L=L+Math.imul(Z0,P0)|0,A=A+Math.imul(Z0,M0)|0,A=A+Math.imul(G0,P0)|0,S=S+Math.imul(G0,M0)|0,L=L+Math.imul($0,k0)|0,A=A+Math.imul($0,g0)|0,A=A+Math.imul(Q0,k0)|0,S=S+Math.imul(Q0,g0)|0;var N$=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(N$>>>26)|0,N$&=67108863,L=Math.imul(V0,P0),A=Math.imul(V0,M0),A=A+Math.imul(U0,P0)|0,S=Math.imul(U0,M0),L=L+Math.imul(Z0,k0)|0,A=A+Math.imul(Z0,g0)|0,A=A+Math.imul(G0,k0)|0,S=S+Math.imul(G0,g0)|0;var x$=(K+L|0)+((A&8191)<<13)|0;K=(S+(A>>>13)|0)+(x$>>>26)|0,x$&=67108863,L=Math.imul(V0,k0),A=Math.imul(V0,g0),A=A+Math.imul(U0,k0)|0,S=Math.imul(U0,g0);var B$=(K+L|0)+((A&8191)<<13)|0;return K=(S+(A>>>13)|0)+(B$>>>26)|0,B$&=67108863,Q[0]=f0,Q[1]=c0,Q[2]=h0,Q[3]=d0,Q[4]=b0,Q[5]=l0,Q[6]=o0,Q[7]=u0,Q[8]=n0,Q[9]=s0,Q[10]=t0,Q[11]=m0,Q[12]=a0,Q[13]=e0,Q[14]=r0,Q[15]=i0,Q[16]=N$,Q[17]=x$,Q[18]=B$,K!==0&&(Q[19]=K,I.length++),I};Math.imul||(g=q);function B(Z,V,I){I.negative=V.negative^Z.negative,I.length=Z.length+V.length;for(var O=0,U=0,Q=0;Q>>26)|0,U+=K>>>26,K&=67108863}I.words[Q]=L,O=K,K=U}return O!==0?I.words[Q]=O:I.length--,I._strip()}function w(Z,V,I){return B(Z,V,I)}X.prototype.mulTo=function(Z,V){var I,O=this.length+Z.length;return this.length===10&&Z.length===10?I=g(this,Z,V):O<63?I=q(this,Z,V):O<1024?I=B(this,Z,V):I=w(this,Z,V),I};function f(Z,V){this.x=Z,this.y=V}f.prototype.makeRBT=function(Z){for(var V=new Array(Z),I=X.prototype._countBits(Z)-1,O=0;O>=1;return O},f.prototype.permute=function(Z,V,I,O,U,Q){for(var K=0;K>>1)U++;return 1<>>13,I[2*Q+1]=U&8191,U=U>>>13;for(Q=2*V;Q>=26,I+=U/67108864|0,I+=Q>>>26,this.words[O]=Q&67108863}return I!==0&&(this.words[O]=I,this.length++),V?this.ineg():this},X.prototype.muln=function(Z){return this.clone().imuln(Z)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function(Z){var V=v(Z);if(V.length===0)return new X(1);for(var I=this,O=0;O=0);var V=Z%26,I=(Z-V)/26,O=67108863>>>26-V<<26-V,U;if(V!==0){var Q=0;for(U=0;U>>26-V}Q&&(this.words[U]=Q,this.length++)}if(I!==0){for(U=this.length-1;U>=0;U--)this.words[U+I]=this.words[U];for(U=0;U=0);var O;V?O=(V-V%26)/26:O=0;var U=Z%26,Q=Math.min((Z-U)/26,this.length),K=67108863^67108863>>>U<Q)for(this.length-=Q,A=0;A=0&&(S!==0||A>=O);A--){var x=this.words[A]|0;this.words[A]=S<<26-U|x>>>U,S=x&K}return L&&S!==0&&(L.words[L.length++]=S),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},X.prototype.ishrn=function(Z,V,I){return F(this.negative===0),this.iushrn(Z,V,I)},X.prototype.shln=function(Z){return this.clone().ishln(Z)},X.prototype.ushln=function(Z){return this.clone().iushln(Z)},X.prototype.shrn=function(Z){return this.clone().ishrn(Z)},X.prototype.ushrn=function(Z){return this.clone().iushrn(Z)},X.prototype.testn=function(Z){F(typeof Z=="number"&&Z>=0);var V=Z%26,I=(Z-V)/26,O=1<=0);var V=Z%26,I=(Z-V)/26;if(F(this.negative===0,"imaskn works only with positive numbers"),this.length<=I)return this;if(V!==0&&I++,this.length=Math.min(I,this.length),V!==0){var O=67108863^67108863>>>V<=67108864;V++)this.words[V]-=67108864,V===this.length-1?this.words[V+1]=1:this.words[V+1]++;return this.length=Math.max(this.length,V+1),this},X.prototype.isubn=function(Z){if(F(typeof Z=="number"),F(Z<67108864),Z<0)return this.iaddn(-Z);if(this.negative!==0)return this.negative=0,this.iaddn(Z),this.negative=1,this;if(this.words[0]-=Z,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var V=0;V>26)-(L/67108864|0),this.words[U+I]=Q&67108863}for(;U>26,this.words[U+I]=Q&67108863;if(K===0)return this._strip();for(F(K===-1),K=0,U=0;U>26,this.words[U]=Q&67108863;return this.negative=1,this._strip()},X.prototype._wordDiv=function(Z,V){var I=this.length-Z.length,O=this.clone(),U=Z,Q=U.words[U.length-1]|0,K=this._countBits(Q);I=26-K,I!==0&&(U=U.ushln(I),O.iushln(I),Q=U.words[U.length-1]|0);var L=O.length-U.length,A;if(V!=="mod"){A=new X(null),A.length=L+1,A.words=new Array(A.length);for(var S=0;S=0;y--){var c=(O.words[U.length+y]|0)*67108864+(O.words[U.length+y-1]|0);for(c=Math.min(c/Q|0,67108863),O._ishlnsubmul(U,c,y);O.negative!==0;)c--,O.negative=0,O._ishlnsubmul(U,1,y),O.isZero()||(O.negative^=1);A&&(A.words[y]=c)}return A&&A._strip(),O._strip(),V!=="div"&&I!==0&&O.iushrn(I),{div:A||null,mod:O}},X.prototype.divmod=function(Z,V,I){if(F(!Z.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var O,U,Q;return this.negative!==0&&Z.negative===0?(Q=this.neg().divmod(Z,V),V!=="mod"&&(O=Q.div.neg()),V!=="div"&&(U=Q.mod.neg(),I&&U.negative!==0&&U.iadd(Z)),{div:O,mod:U}):this.negative===0&&Z.negative!==0?(Q=this.divmod(Z.neg(),V),V!=="mod"&&(O=Q.div.neg()),{div:O,mod:Q.mod}):(this.negative&Z.negative)!==0?(Q=this.neg().divmod(Z.neg(),V),V!=="div"&&(U=Q.mod.neg(),I&&U.negative!==0&&U.isub(Z)),{div:Q.div,mod:U}):Z.length>this.length||this.cmp(Z)<0?{div:new X(0),mod:this}:Z.length===1?V==="div"?{div:this.divn(Z.words[0]),mod:null}:V==="mod"?{div:null,mod:new X(this.modrn(Z.words[0]))}:{div:this.divn(Z.words[0]),mod:new X(this.modrn(Z.words[0]))}:this._wordDiv(Z,V)},X.prototype.div=function(Z){return this.divmod(Z,"div",!1).div},X.prototype.mod=function(Z){return this.divmod(Z,"mod",!1).mod},X.prototype.umod=function(Z){return this.divmod(Z,"mod",!0).mod},X.prototype.divRound=function(Z){var V=this.divmod(Z);if(V.mod.isZero())return V.div;var I=V.div.negative!==0?V.mod.isub(Z):V.mod,O=Z.ushrn(1),U=Z.andln(1),Q=I.cmp(O);return Q<0||U===1&&Q===0?V.div:V.div.negative!==0?V.div.isubn(1):V.div.iaddn(1)},X.prototype.modrn=function(Z){var V=Z<0;V&&(Z=-Z),F(Z<=67108863);for(var I=(1<<26)%Z,O=0,U=this.length-1;U>=0;U--)O=(I*O+(this.words[U]|0))%Z;return V?-O:O},X.prototype.modn=function(Z){return this.modrn(Z)},X.prototype.idivn=function(Z){var V=Z<0;V&&(Z=-Z),F(Z<=67108863);for(var I=0,O=this.length-1;O>=0;O--){var U=(this.words[O]|0)+I*67108864;this.words[O]=U/Z|0,I=U%Z}return this._strip(),V?this.ineg():this},X.prototype.divn=function(Z){return this.clone().idivn(Z)},X.prototype.egcd=function(Z){F(Z.negative===0),F(!Z.isZero());var V=this,I=Z.clone();V.negative!==0?V=V.umod(Z):V=V.clone();for(var O=new X(1),U=new X(0),Q=new X(0),K=new X(1),L=0;V.isEven()&&I.isEven();)V.iushrn(1),I.iushrn(1),++L;for(var A=I.clone(),S=V.clone();!V.isZero();){for(var x=0,y=1;(V.words[0]&y)===0&&x<26;++x,y<<=1);if(x>0)for(V.iushrn(x);x-- >0;)(O.isOdd()||U.isOdd())&&(O.iadd(A),U.isub(S)),O.iushrn(1),U.iushrn(1);for(var c=0,q0=1;(I.words[0]&q0)===0&&c<26;++c,q0<<=1);if(c>0)for(I.iushrn(c);c-- >0;)(Q.isOdd()||K.isOdd())&&(Q.iadd(A),K.isub(S)),Q.iushrn(1),K.iushrn(1);V.cmp(I)>=0?(V.isub(I),O.isub(Q),U.isub(K)):(I.isub(V),Q.isub(O),K.isub(U))}return{a:Q,b:K,gcd:I.iushln(L)}},X.prototype._invmp=function(Z){F(Z.negative===0),F(!Z.isZero());var V=this,I=Z.clone();V.negative!==0?V=V.umod(Z):V=V.clone();for(var O=new X(1),U=new X(0),Q=I.clone();V.cmpn(1)>0&&I.cmpn(1)>0;){for(var K=0,L=1;(V.words[0]&L)===0&&K<26;++K,L<<=1);if(K>0)for(V.iushrn(K);K-- >0;)O.isOdd()&&O.iadd(Q),O.iushrn(1);for(var A=0,S=1;(I.words[0]&S)===0&&A<26;++A,S<<=1);if(A>0)for(I.iushrn(A);A-- >0;)U.isOdd()&&U.iadd(Q),U.iushrn(1);V.cmp(I)>=0?(V.isub(I),O.isub(U)):(I.isub(V),U.isub(O))}var x;return V.cmpn(1)===0?x=O:x=U,x.cmpn(0)<0&&x.iadd(Z),x},X.prototype.gcd=function(Z){if(this.isZero())return Z.abs();if(Z.isZero())return this.abs();var V=this.clone(),I=Z.clone();V.negative=0,I.negative=0;for(var O=0;V.isEven()&&I.isEven();O++)V.iushrn(1),I.iushrn(1);do{for(;V.isEven();)V.iushrn(1);for(;I.isEven();)I.iushrn(1);var U=V.cmp(I);if(U<0){var Q=V;V=I,I=Q}else if(U===0||I.cmpn(1)===0)break;V.isub(I)}while(!0);return I.iushln(O)},X.prototype.invm=function(Z){return this.egcd(Z).a.umod(Z)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function(Z){return this.words[0]&Z},X.prototype.bincn=function(Z){F(typeof Z=="number");var V=Z%26,I=(Z-V)/26,O=1<>>26,K&=67108863,this.words[Q]=K}return U!==0&&(this.words[Q]=U,this.length++),this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function(Z){var V=Z<0;if(this.negative!==0&&!V)return-1;if(this.negative===0&&V)return 1;this._strip();var I;if(this.length>1)I=1;else{V&&(Z=-Z),F(Z<=67108863,"Number is too big");var O=this.words[0]|0;I=O===Z?0:OZ.length)return 1;if(this.length=0;I--){var O=this.words[I]|0,U=Z.words[I]|0;if(O!==U){OU&&(V=1);break}}return V},X.prototype.gtn=function(Z){return this.cmpn(Z)===1},X.prototype.gt=function(Z){return this.cmp(Z)===1},X.prototype.gten=function(Z){return this.cmpn(Z)>=0},X.prototype.gte=function(Z){return this.cmp(Z)>=0},X.prototype.ltn=function(Z){return this.cmpn(Z)===-1},X.prototype.lt=function(Z){return this.cmp(Z)===-1},X.prototype.lten=function(Z){return this.cmpn(Z)<=0},X.prototype.lte=function(Z){return this.cmp(Z)<=0},X.prototype.eqn=function(Z){return this.cmpn(Z)===0},X.prototype.eq=function(Z){return this.cmp(Z)===0},X.red=function(Z){return new Y(Z)},X.prototype.toRed=function(Z){return F(!this.red,"Already a number in reduction context"),F(this.negative===0,"red works only with positives"),Z.convertTo(this)._forceRed(Z)},X.prototype.fromRed=function(){return F(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function(Z){return this.red=Z,this},X.prototype.forceRed=function(Z){return F(!this.red,"Already a number in reduction context"),this._forceRed(Z)},X.prototype.redAdd=function(Z){return F(this.red,"redAdd works only with red numbers"),this.red.add(this,Z)},X.prototype.redIAdd=function(Z){return F(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,Z)},X.prototype.redSub=function(Z){return F(this.red,"redSub works only with red numbers"),this.red.sub(this,Z)},X.prototype.redISub=function(Z){return F(this.red,"redISub works only with red numbers"),this.red.isub(this,Z)},X.prototype.redShl=function(Z){return F(this.red,"redShl works only with red numbers"),this.red.shl(this,Z)},X.prototype.redMul=function(Z){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,Z),this.red.mul(this,Z)},X.prototype.redIMul=function(Z){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,Z),this.red.imul(this,Z)},X.prototype.redSqr=function(){return F(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return F(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return F(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return F(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return F(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function(Z){return F(this.red&&!Z.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,Z)};var b={k256:null,p224:null,p192:null,p25519:null};function u(Z,V){this.name=Z,this.p=new X(V,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}u.prototype._tmp=function(){var Z=new X(null);return Z.words=new Array(Math.ceil(this.n/13)),Z},u.prototype.ireduce=function(Z){var V=Z,I;do this.split(V,this.tmp),V=this.imulK(V),V=V.iadd(this.tmp),I=V.bitLength();while(I>this.n);var O=I0?V.isub(this.p):V.strip!==void 0?V.strip():V._strip(),V},u.prototype.split=function(Z,V){Z.iushrn(this.n,0,V)},u.prototype.imulK=function(Z){return Z.imul(this.k)};function Y0(){u.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}P(Y0,u),Y0.prototype.split=function(Z,V){for(var I=4194303,O=Math.min(Z.length,9),U=0;U>>22,Q=K}Q>>>=22,Z.words[U-10]=Q,Q===0&&Z.length>10?Z.length-=10:Z.length-=9},Y0.prototype.imulK=function(Z){Z.words[Z.length]=0,Z.words[Z.length+1]=0,Z.length+=2;for(var V=0,I=0;I>>=26,Z.words[I]=U,V=O}return V!==0&&(Z.words[Z.length++]=V),Z},X._prime=function(Z){if(b[Z])return b[Z];var V;if(Z==="k256")V=new Y0;else if(Z==="p224")V=new p;else if(Z==="p192")V=new v0;else if(Z==="p25519")V=new $;else throw new Error("Unknown prime "+Z);return b[Z]=V,V};function Y(Z){if(typeof Z=="string"){var V=X._prime(Z);this.m=V.p,this.prime=V}else F(Z.gtn(1),"modulus must be greater than 1"),this.m=Z,this.prime=null}Y.prototype._verify1=function(Z){F(Z.negative===0,"red works only with positives"),F(Z.red,"red works only with red numbers")},Y.prototype._verify2=function(Z,V){F((Z.negative|V.negative)===0,"red works only with positives"),F(Z.red&&Z.red===V.red,"red works only with red numbers")},Y.prototype.imod=function(Z){return this.prime?this.prime.ireduce(Z)._forceRed(this):(J(Z,Z.umod(this.m)._forceRed(this)),Z)},Y.prototype.neg=function(Z){return Z.isZero()?Z.clone():this.m.sub(Z)._forceRed(this)},Y.prototype.add=function(Z,V){this._verify2(Z,V);var I=Z.add(V);return I.cmp(this.m)>=0&&I.isub(this.m),I._forceRed(this)},Y.prototype.iadd=function(Z,V){this._verify2(Z,V);var I=Z.iadd(V);return I.cmp(this.m)>=0&&I.isub(this.m),I},Y.prototype.sub=function(Z,V){this._verify2(Z,V);var I=Z.sub(V);return I.cmpn(0)<0&&I.iadd(this.m),I._forceRed(this)},Y.prototype.isub=function(Z,V){this._verify2(Z,V);var I=Z.isub(V);return I.cmpn(0)<0&&I.iadd(this.m),I},Y.prototype.shl=function(Z,V){return this._verify1(Z),this.imod(Z.ushln(V))},Y.prototype.imul=function(Z,V){return this._verify2(Z,V),this.imod(Z.imul(V))},Y.prototype.mul=function(Z,V){return this._verify2(Z,V),this.imod(Z.mul(V))},Y.prototype.isqr=function(Z){return this.imul(Z,Z.clone())},Y.prototype.sqr=function(Z){return this.mul(Z,Z)},Y.prototype.sqrt=function(Z){if(Z.isZero())return Z.clone();var V=this.m.andln(3);if(F(V%2===1),V===3){var I=this.m.add(new X(1)).iushrn(2);return this.pow(Z,I)}for(var O=this.m.subn(1),U=0;!O.isZero()&&O.andln(1)===0;)U++,O.iushrn(1);F(!O.isZero());var Q=new X(1).toRed(this),K=Q.redNeg(),L=this.m.subn(1).iushrn(1),A=this.m.bitLength();for(A=new X(2*A*A).toRed(this);this.pow(A,L).cmp(K)!==0;)A.redIAdd(K);for(var S=this.pow(A,O),x=this.pow(Z,O.addn(1).iushrn(1)),y=this.pow(Z,O),c=U;y.cmp(Q)!==0;){for(var q0=y,h=0;q0.cmp(Q)!==0;h++)q0=q0.redSqr();F(h=0;U--){for(var S=V.words[U],x=A-1;x>=0;x--){var y=S>>x&1;if(Q!==O[0]&&(Q=this.sqr(Q)),y===0&&K===0){L=0;continue}K<<=1,K|=y,L++,!(L!==I&&(U!==0||x!==0))&&(Q=this.mul(Q,O[K]),L=0,K=0)}A=26}return Q},Y.prototype.convertTo=function(Z){var V=Z.umod(this.m);return V===Z?V.clone():V},Y.prototype.convertFrom=function(Z){var V=Z.clone();return V.red=null,V},X.mont=function(Z){return new G(Z)};function G(Z){Y.call(this,Z),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new X(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}P(G,Y),G.prototype.convertTo=function(Z){return this.imod(Z.ushln(this.shift))},G.prototype.convertFrom=function(Z){var V=this.imod(Z.mul(this.rinv));return V.red=null,V},G.prototype.imul=function(Z,V){if(Z.isZero()||V.isZero())return Z.words[0]=0,Z.length=1,Z;var I=Z.imul(V),O=I.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),U=I.isub(O).iushrn(this.shift),Q=U;return U.cmp(this.m)>=0?Q=U.isub(this.m):U.cmpn(0)<0&&(Q=U.iadd(this.m)),Q._forceRed(this)},G.prototype.mul=function(Z,V){if(Z.isZero()||V.isZero())return new X(0)._forceRed(this);var I=Z.mul(V),O=I.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),U=I.isub(O).iushrn(this.shift),Q=U;return U.cmp(this.m)>=0?Q=U.isub(this.m):U.cmpn(0)<0&&(Q=U.iadd(this.m)),Q._forceRed(this)},G.prototype.invm=function(Z){var V=this.imod(Z._invmp(this.m).mul(this.r2));return V._forceRed(this)}})(typeof _>"u"||_,N)}}),d$=S0({"node_modules/browserify-rsa/index.js"(N,_){var j=h$(),k=L$();function F(C){var z=P(C),T=z.toRed(j.mont(C.modulus)).redPow(new j(C.publicExponent)).fromRed();return{blinder:T,unblinder:z.invm(C.modulus)}}function P(C){var z=C.modulus.byteLength(),T;do T=new j(k(z));while(T.cmp(C.modulus)>=0||!T.umod(C.prime1)||!T.umod(C.prime2));return T}function X(C,z){var T=F(z),H=z.modulus.byteLength(),J=new j(C).mul(T.blinder).umod(z.modulus),W=J.toRed(j.mont(z.prime1)),D=J.toRed(j.mont(z.prime2)),E=z.coefficient,R=z.prime1,M=z.prime2,v=W.redPow(z.exponent1).fromRed(),q=D.redPow(z.exponent2).fromRed(),g=v.isub(q).imul(E).umod(R).imul(M);return q.iadd(g).imul(T.unblinder).umod(z.modulus).toArrayLike(j0,"be",H)}X.getr=P,_.exports=X}}),zY=S0({"node_modules/elliptic/package.json"(N,_){_.exports={name:"elliptic",version:"6.5.4",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git@github.com:indutny/elliptic"},keywords:["EC","Elliptic","curve","Cryptography"],author:"Fedor Indutny ",license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},dependencies:{"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"}}}}),D$=S0({"node_modules/elliptic/node_modules/bn.js/lib/bn.js"(N,_){(function(j,k){function F($,Y){if(!$)throw new Error(Y||"Assertion failed")}function P($,Y){$.super_=Y;var G=function(){};G.prototype=Y.prototype,$.prototype=new G,$.prototype.constructor=$}function X($,Y,G){if(X.isBN($))return $;this.negative=0,this.words=null,this.length=0,this.red=null,$!==null&&((Y==="le"||Y==="be")&&(G=Y,Y=10),this._init($||0,Y||10,G||"be"))}typeof j=="object"?j.exports=X:k.BN=X,X.BN=X,X.wordSize=26;var C=j0;X.isBN=function($){return $ instanceof X?!0:$!==null&&typeof $=="object"&&$.constructor.wordSize===X.wordSize&&Array.isArray($.words)},X.max=function($,Y){return $.cmp(Y)>0?$:Y},X.min=function($,Y){return $.cmp(Y)<0?$:Y},X.prototype._init=function($,Y,G){if(typeof $=="number")return this._initNumber($,Y,G);if(typeof $=="object")return this._initArray($,Y,G);Y==="hex"&&(Y=16),F(Y===(Y|0)&&Y>=2&&Y<=36),$=$.toString().replace(/\s+/g,"");var Z=0;$[0]==="-"&&(Z++,this.negative=1),Z<$.length&&(Y===16?this._parseHex($,Z,G):(this._parseBase($,Y,Z),G==="le"&&this._initArray(this.toArray(),Y,G)))},X.prototype._initNumber=function($,Y,G){$<0&&(this.negative=1,$=-$),$<67108864?(this.words=[$&67108863],this.length=1):$<4503599627370496?(this.words=[$&67108863,$/67108864&67108863],this.length=2):(F($<9007199254740992),this.words=[$&67108863,$/67108864&67108863,1],this.length=3),G==="le"&&this._initArray(this.toArray(),Y,G)},X.prototype._initArray=function($,Y,G){if(F(typeof $.length=="number"),$.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil($.length/3),this.words=new Array(this.length);for(var Z=0;Z=0;Z-=3)I=$[Z]|$[Z-1]<<8|$[Z-2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);else if(G==="le")for(Z=0,V=0;Z<$.length;Z+=3)I=$[Z]|$[Z+1]<<8|$[Z+2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);return this.strip()};function z($,Y){var G=$.charCodeAt(Y);return G>=65&&G<=70?G-55:G>=97&&G<=102?G-87:G-48&15}function T($,Y,G){var Z=z($,G);return G-1>=Y&&(Z|=z($,G-1)<<4),Z}X.prototype._parseHex=function($,Y,G){this.length=Math.ceil(($.length-Y)/6),this.words=new Array(this.length);for(var Z=0;Z=Y;Z-=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8;else{var U=$.length-Y;for(Z=U%2===0?Y+1:Y;Z<$.length;Z+=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8}this.strip()};function H($,Y,G,Z){for(var V=0,I=Math.min($.length,G),O=Y;O=49?V+=U-49+10:U>=17?V+=U-17+10:V+=U}return V}X.prototype._parseBase=function($,Y,G){this.words=[0],this.length=1;for(var Z=0,V=1;V<=67108863;V*=Y)Z++;Z--,V=V/Y|0;for(var I=$.length-G,O=I%Z,U=Math.min(I,I-O)+G,Q=0,K=G;K1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},X.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},X.prototype.inspect=function(){return(this.red?""};var J=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],W=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],D=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];X.prototype.toString=function($,Y){$=$||10,Y=Y|0||1;var G;if($===16||$==="hex"){G="";for(var Z=0,V=0,I=0;I>>24-Z&16777215,V!==0||I!==this.length-1?G=J[6-U.length]+U+G:G=U+G,Z+=2,Z>=26&&(Z-=26,I--)}for(V!==0&&(G=V.toString(16)+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}if($===($|0)&&$>=2&&$<=36){var Q=W[$],K=D[$];G="";var L=this.clone();for(L.negative=0;!L.isZero();){var A=L.modn(K).toString($);L=L.idivn(K),L.isZero()?G=A+G:G=J[Q-A.length]+A+G}for(this.isZero()&&(G="0"+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}F(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var $=this.words[0];return this.length===2?$+=this.words[1]*67108864:this.length===3&&this.words[2]===1?$+=4503599627370496+this.words[1]*67108864:this.length>2&&F(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-$:$},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function($,Y){return F(typeof C<"u"),this.toArrayLike(C,$,Y)},X.prototype.toArray=function($,Y){return this.toArrayLike(Array,$,Y)},X.prototype.toArrayLike=function($,Y,G){var Z=this.byteLength(),V=G||Math.max(1,Z);F(Z<=V,"byte array longer than desired length"),F(V>0,"Requested array length <= 0"),this.strip();var I=Y==="le",O=new $(V),U,Q,K=this.clone();if(I){for(Q=0;!K.isZero();Q++)U=K.andln(255),K.iushrn(8),O[Q]=U;for(;Q=4096&&(G+=13,Y>>>=13),Y>=64&&(G+=7,Y>>>=7),Y>=8&&(G+=4,Y>>>=4),Y>=2&&(G+=2,Y>>>=2),G+Y},X.prototype._zeroBits=function($){if($===0)return 26;var Y=$,G=0;return(Y&8191)===0&&(G+=13,Y>>>=13),(Y&127)===0&&(G+=7,Y>>>=7),(Y&15)===0&&(G+=4,Y>>>=4),(Y&3)===0&&(G+=2,Y>>>=2),(Y&1)===0&&G++,G},X.prototype.bitLength=function(){var $=this.words[this.length-1],Y=this._countBits($);return(this.length-1)*26+Y};function E($){for(var Y=new Array($.bitLength()),G=0;G>>V}return Y}X.prototype.zeroBits=function(){if(this.isZero())return 0;for(var $=0,Y=0;Y$.length?this.clone().ior($):$.clone().ior(this)},X.prototype.uor=function($){return this.length>$.length?this.clone().iuor($):$.clone().iuor(this)},X.prototype.iuand=function($){var Y;this.length>$.length?Y=$:Y=this;for(var G=0;G$.length?this.clone().iand($):$.clone().iand(this)},X.prototype.uand=function($){return this.length>$.length?this.clone().iuand($):$.clone().iuand(this)},X.prototype.iuxor=function($){var Y,G;this.length>$.length?(Y=this,G=$):(Y=$,G=this);for(var Z=0;Z$.length?this.clone().ixor($):$.clone().ixor(this)},X.prototype.uxor=function($){return this.length>$.length?this.clone().iuxor($):$.clone().iuxor(this)},X.prototype.inotn=function($){F(typeof $=="number"&&$>=0);var Y=Math.ceil($/26)|0,G=$%26;this._expand(Y),G>0&&Y--;for(var Z=0;Z0&&(this.words[Z]=~this.words[Z]&67108863>>26-G),this.strip()},X.prototype.notn=function($){return this.clone().inotn($)},X.prototype.setn=function($,Y){F(typeof $=="number"&&$>=0);var G=$/26|0,Z=$%26;return this._expand(G+1),Y?this.words[G]=this.words[G]|1<$.length?(G=this,Z=$):(G=$,Z=this);for(var V=0,I=0;I>>26;for(;V!==0&&I>>26;if(this.length=G.length,V!==0)this.words[this.length]=V,this.length++;else if(G!==this)for(;I$.length?this.clone().iadd($):$.clone().iadd(this)},X.prototype.isub=function($){if($.negative!==0){$.negative=0;var Y=this.iadd($);return $.negative=1,Y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd($),this.negative=1,this._normSign();var G=this.cmp($);if(G===0)return this.negative=0,this.length=1,this.words[0]=0,this;var Z,V;G>0?(Z=this,V=$):(Z=$,V=this);for(var I=0,O=0;O>26,this.words[O]=Y&67108863;for(;I!==0&&O>26,this.words[O]=Y&67108863;if(I===0&&O>>26,A=Q&67108863,S=Math.min(K,Y.length-1),x=Math.max(0,K-$.length+1);x<=S;x++){var y=K-x|0;V=$.words[y]|0,I=Y.words[x]|0,O=V*I+A,L+=O/67108864|0,A=O&67108863}G.words[K]=A|0,Q=L|0}return Q!==0?G.words[K]=Q|0:G.length--,G.strip()}var M=function($,Y,G){var Z=$.words,V=Y.words,I=G.words,O=0,U,Q,K,L=Z[0]|0,A=L&8191,S=L>>>13,x=Z[1]|0,y=x&8191,c=x>>>13,q0=Z[2]|0,h=q0&8191,d=q0>>>13,_0=Z[3]|0,l=_0&8191,n=_0>>>13,y0=Z[4]|0,t=y0&8191,s=y0>>>13,w0=Z[5]|0,m=w0&8191,r=w0>>>13,$$=Z[6]|0,i=$$&8191,e=$$>>>13,x0=Z[7]|0,o=x0&8191,a=x0>>>13,p0=Z[8]|0,$0=p0&8191,Q0=p0>>>13,Y$=Z[9]|0,Z0=Y$&8191,G0=Y$>>>13,Z$=V[0]|0,V0=Z$&8191,U0=Z$>>>13,G$=V[1]|0,X0=G$&8191,K0=G$>>>13,V$=V[2]|0,I0=V$&8191,O0=V$>>>13,U$=V[3]|0,J0=U$&8191,F0=U$>>>13,X$=V[4]|0,A0=X$&8191,W0=X$>>>13,K$=V[5]|0,H0=K$&8191,E0=K$>>>13,I$=V[6]|0,T0=I$&8191,D0=I$>>>13,O$=V[7]|0,C0=O$&8191,L0=O$>>>13,J$=V[8]|0,R0=J$&8191,z0=J$>>>13,F$=V[9]|0,P0=F$&8191,M0=F$>>>13;G.negative=$.negative^Y.negative,G.length=19,U=Math.imul(A,V0),Q=Math.imul(A,U0),Q=Q+Math.imul(S,V0)|0,K=Math.imul(S,U0);var Q$=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(Q$>>>26)|0,Q$&=67108863,U=Math.imul(y,V0),Q=Math.imul(y,U0),Q=Q+Math.imul(c,V0)|0,K=Math.imul(c,U0),U=U+Math.imul(A,X0)|0,Q=Q+Math.imul(A,K0)|0,Q=Q+Math.imul(S,X0)|0,K=K+Math.imul(S,K0)|0;var k0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(k0>>>26)|0,k0&=67108863,U=Math.imul(h,V0),Q=Math.imul(h,U0),Q=Q+Math.imul(d,V0)|0,K=Math.imul(d,U0),U=U+Math.imul(y,X0)|0,Q=Q+Math.imul(y,K0)|0,Q=Q+Math.imul(c,X0)|0,K=K+Math.imul(c,K0)|0,U=U+Math.imul(A,I0)|0,Q=Q+Math.imul(A,O0)|0,Q=Q+Math.imul(S,I0)|0,K=K+Math.imul(S,O0)|0;var g0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(g0>>>26)|0,g0&=67108863,U=Math.imul(l,V0),Q=Math.imul(l,U0),Q=Q+Math.imul(n,V0)|0,K=Math.imul(n,U0),U=U+Math.imul(h,X0)|0,Q=Q+Math.imul(h,K0)|0,Q=Q+Math.imul(d,X0)|0,K=K+Math.imul(d,K0)|0,U=U+Math.imul(y,I0)|0,Q=Q+Math.imul(y,O0)|0,Q=Q+Math.imul(c,I0)|0,K=K+Math.imul(c,O0)|0,U=U+Math.imul(A,J0)|0,Q=Q+Math.imul(A,F0)|0,Q=Q+Math.imul(S,J0)|0,K=K+Math.imul(S,F0)|0;var f0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(f0>>>26)|0,f0&=67108863,U=Math.imul(t,V0),Q=Math.imul(t,U0),Q=Q+Math.imul(s,V0)|0,K=Math.imul(s,U0),U=U+Math.imul(l,X0)|0,Q=Q+Math.imul(l,K0)|0,Q=Q+Math.imul(n,X0)|0,K=K+Math.imul(n,K0)|0,U=U+Math.imul(h,I0)|0,Q=Q+Math.imul(h,O0)|0,Q=Q+Math.imul(d,I0)|0,K=K+Math.imul(d,O0)|0,U=U+Math.imul(y,J0)|0,Q=Q+Math.imul(y,F0)|0,Q=Q+Math.imul(c,J0)|0,K=K+Math.imul(c,F0)|0,U=U+Math.imul(A,A0)|0,Q=Q+Math.imul(A,W0)|0,Q=Q+Math.imul(S,A0)|0,K=K+Math.imul(S,W0)|0;var c0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(c0>>>26)|0,c0&=67108863,U=Math.imul(m,V0),Q=Math.imul(m,U0),Q=Q+Math.imul(r,V0)|0,K=Math.imul(r,U0),U=U+Math.imul(t,X0)|0,Q=Q+Math.imul(t,K0)|0,Q=Q+Math.imul(s,X0)|0,K=K+Math.imul(s,K0)|0,U=U+Math.imul(l,I0)|0,Q=Q+Math.imul(l,O0)|0,Q=Q+Math.imul(n,I0)|0,K=K+Math.imul(n,O0)|0,U=U+Math.imul(h,J0)|0,Q=Q+Math.imul(h,F0)|0,Q=Q+Math.imul(d,J0)|0,K=K+Math.imul(d,F0)|0,U=U+Math.imul(y,A0)|0,Q=Q+Math.imul(y,W0)|0,Q=Q+Math.imul(c,A0)|0,K=K+Math.imul(c,W0)|0,U=U+Math.imul(A,H0)|0,Q=Q+Math.imul(A,E0)|0,Q=Q+Math.imul(S,H0)|0,K=K+Math.imul(S,E0)|0;var h0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(h0>>>26)|0,h0&=67108863,U=Math.imul(i,V0),Q=Math.imul(i,U0),Q=Q+Math.imul(e,V0)|0,K=Math.imul(e,U0),U=U+Math.imul(m,X0)|0,Q=Q+Math.imul(m,K0)|0,Q=Q+Math.imul(r,X0)|0,K=K+Math.imul(r,K0)|0,U=U+Math.imul(t,I0)|0,Q=Q+Math.imul(t,O0)|0,Q=Q+Math.imul(s,I0)|0,K=K+Math.imul(s,O0)|0,U=U+Math.imul(l,J0)|0,Q=Q+Math.imul(l,F0)|0,Q=Q+Math.imul(n,J0)|0,K=K+Math.imul(n,F0)|0,U=U+Math.imul(h,A0)|0,Q=Q+Math.imul(h,W0)|0,Q=Q+Math.imul(d,A0)|0,K=K+Math.imul(d,W0)|0,U=U+Math.imul(y,H0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(c,H0)|0,K=K+Math.imul(c,E0)|0,U=U+Math.imul(A,T0)|0,Q=Q+Math.imul(A,D0)|0,Q=Q+Math.imul(S,T0)|0,K=K+Math.imul(S,D0)|0;var d0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(d0>>>26)|0,d0&=67108863,U=Math.imul(o,V0),Q=Math.imul(o,U0),Q=Q+Math.imul(a,V0)|0,K=Math.imul(a,U0),U=U+Math.imul(i,X0)|0,Q=Q+Math.imul(i,K0)|0,Q=Q+Math.imul(e,X0)|0,K=K+Math.imul(e,K0)|0,U=U+Math.imul(m,I0)|0,Q=Q+Math.imul(m,O0)|0,Q=Q+Math.imul(r,I0)|0,K=K+Math.imul(r,O0)|0,U=U+Math.imul(t,J0)|0,Q=Q+Math.imul(t,F0)|0,Q=Q+Math.imul(s,J0)|0,K=K+Math.imul(s,F0)|0,U=U+Math.imul(l,A0)|0,Q=Q+Math.imul(l,W0)|0,Q=Q+Math.imul(n,A0)|0,K=K+Math.imul(n,W0)|0,U=U+Math.imul(h,H0)|0,Q=Q+Math.imul(h,E0)|0,Q=Q+Math.imul(d,H0)|0,K=K+Math.imul(d,E0)|0,U=U+Math.imul(y,T0)|0,Q=Q+Math.imul(y,D0)|0,Q=Q+Math.imul(c,T0)|0,K=K+Math.imul(c,D0)|0,U=U+Math.imul(A,C0)|0,Q=Q+Math.imul(A,L0)|0,Q=Q+Math.imul(S,C0)|0,K=K+Math.imul(S,L0)|0;var b0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(b0>>>26)|0,b0&=67108863,U=Math.imul($0,V0),Q=Math.imul($0,U0),Q=Q+Math.imul(Q0,V0)|0,K=Math.imul(Q0,U0),U=U+Math.imul(o,X0)|0,Q=Q+Math.imul(o,K0)|0,Q=Q+Math.imul(a,X0)|0,K=K+Math.imul(a,K0)|0,U=U+Math.imul(i,I0)|0,Q=Q+Math.imul(i,O0)|0,Q=Q+Math.imul(e,I0)|0,K=K+Math.imul(e,O0)|0,U=U+Math.imul(m,J0)|0,Q=Q+Math.imul(m,F0)|0,Q=Q+Math.imul(r,J0)|0,K=K+Math.imul(r,F0)|0,U=U+Math.imul(t,A0)|0,Q=Q+Math.imul(t,W0)|0,Q=Q+Math.imul(s,A0)|0,K=K+Math.imul(s,W0)|0,U=U+Math.imul(l,H0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(n,H0)|0,K=K+Math.imul(n,E0)|0,U=U+Math.imul(h,T0)|0,Q=Q+Math.imul(h,D0)|0,Q=Q+Math.imul(d,T0)|0,K=K+Math.imul(d,D0)|0,U=U+Math.imul(y,C0)|0,Q=Q+Math.imul(y,L0)|0,Q=Q+Math.imul(c,C0)|0,K=K+Math.imul(c,L0)|0,U=U+Math.imul(A,R0)|0,Q=Q+Math.imul(A,z0)|0,Q=Q+Math.imul(S,R0)|0,K=K+Math.imul(S,z0)|0;var l0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(l0>>>26)|0,l0&=67108863,U=Math.imul(Z0,V0),Q=Math.imul(Z0,U0),Q=Q+Math.imul(G0,V0)|0,K=Math.imul(G0,U0),U=U+Math.imul($0,X0)|0,Q=Q+Math.imul($0,K0)|0,Q=Q+Math.imul(Q0,X0)|0,K=K+Math.imul(Q0,K0)|0,U=U+Math.imul(o,I0)|0,Q=Q+Math.imul(o,O0)|0,Q=Q+Math.imul(a,I0)|0,K=K+Math.imul(a,O0)|0,U=U+Math.imul(i,J0)|0,Q=Q+Math.imul(i,F0)|0,Q=Q+Math.imul(e,J0)|0,K=K+Math.imul(e,F0)|0,U=U+Math.imul(m,A0)|0,Q=Q+Math.imul(m,W0)|0,Q=Q+Math.imul(r,A0)|0,K=K+Math.imul(r,W0)|0,U=U+Math.imul(t,H0)|0,Q=Q+Math.imul(t,E0)|0,Q=Q+Math.imul(s,H0)|0,K=K+Math.imul(s,E0)|0,U=U+Math.imul(l,T0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(n,T0)|0,K=K+Math.imul(n,D0)|0,U=U+Math.imul(h,C0)|0,Q=Q+Math.imul(h,L0)|0,Q=Q+Math.imul(d,C0)|0,K=K+Math.imul(d,L0)|0,U=U+Math.imul(y,R0)|0,Q=Q+Math.imul(y,z0)|0,Q=Q+Math.imul(c,R0)|0,K=K+Math.imul(c,z0)|0,U=U+Math.imul(A,P0)|0,Q=Q+Math.imul(A,M0)|0,Q=Q+Math.imul(S,P0)|0,K=K+Math.imul(S,M0)|0;var o0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(o0>>>26)|0,o0&=67108863,U=Math.imul(Z0,X0),Q=Math.imul(Z0,K0),Q=Q+Math.imul(G0,X0)|0,K=Math.imul(G0,K0),U=U+Math.imul($0,I0)|0,Q=Q+Math.imul($0,O0)|0,Q=Q+Math.imul(Q0,I0)|0,K=K+Math.imul(Q0,O0)|0,U=U+Math.imul(o,J0)|0,Q=Q+Math.imul(o,F0)|0,Q=Q+Math.imul(a,J0)|0,K=K+Math.imul(a,F0)|0,U=U+Math.imul(i,A0)|0,Q=Q+Math.imul(i,W0)|0,Q=Q+Math.imul(e,A0)|0,K=K+Math.imul(e,W0)|0,U=U+Math.imul(m,H0)|0,Q=Q+Math.imul(m,E0)|0,Q=Q+Math.imul(r,H0)|0,K=K+Math.imul(r,E0)|0,U=U+Math.imul(t,T0)|0,Q=Q+Math.imul(t,D0)|0,Q=Q+Math.imul(s,T0)|0,K=K+Math.imul(s,D0)|0,U=U+Math.imul(l,C0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(n,C0)|0,K=K+Math.imul(n,L0)|0,U=U+Math.imul(h,R0)|0,Q=Q+Math.imul(h,z0)|0,Q=Q+Math.imul(d,R0)|0,K=K+Math.imul(d,z0)|0,U=U+Math.imul(y,P0)|0,Q=Q+Math.imul(y,M0)|0,Q=Q+Math.imul(c,P0)|0,K=K+Math.imul(c,M0)|0;var u0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(u0>>>26)|0,u0&=67108863,U=Math.imul(Z0,I0),Q=Math.imul(Z0,O0),Q=Q+Math.imul(G0,I0)|0,K=Math.imul(G0,O0),U=U+Math.imul($0,J0)|0,Q=Q+Math.imul($0,F0)|0,Q=Q+Math.imul(Q0,J0)|0,K=K+Math.imul(Q0,F0)|0,U=U+Math.imul(o,A0)|0,Q=Q+Math.imul(o,W0)|0,Q=Q+Math.imul(a,A0)|0,K=K+Math.imul(a,W0)|0,U=U+Math.imul(i,H0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,H0)|0,K=K+Math.imul(e,E0)|0,U=U+Math.imul(m,T0)|0,Q=Q+Math.imul(m,D0)|0,Q=Q+Math.imul(r,T0)|0,K=K+Math.imul(r,D0)|0,U=U+Math.imul(t,C0)|0,Q=Q+Math.imul(t,L0)|0,Q=Q+Math.imul(s,C0)|0,K=K+Math.imul(s,L0)|0,U=U+Math.imul(l,R0)|0,Q=Q+Math.imul(l,z0)|0,Q=Q+Math.imul(n,R0)|0,K=K+Math.imul(n,z0)|0,U=U+Math.imul(h,P0)|0,Q=Q+Math.imul(h,M0)|0,Q=Q+Math.imul(d,P0)|0,K=K+Math.imul(d,M0)|0;var n0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(n0>>>26)|0,n0&=67108863,U=Math.imul(Z0,J0),Q=Math.imul(Z0,F0),Q=Q+Math.imul(G0,J0)|0,K=Math.imul(G0,F0),U=U+Math.imul($0,A0)|0,Q=Q+Math.imul($0,W0)|0,Q=Q+Math.imul(Q0,A0)|0,K=K+Math.imul(Q0,W0)|0,U=U+Math.imul(o,H0)|0,Q=Q+Math.imul(o,E0)|0,Q=Q+Math.imul(a,H0)|0,K=K+Math.imul(a,E0)|0,U=U+Math.imul(i,T0)|0,Q=Q+Math.imul(i,D0)|0,Q=Q+Math.imul(e,T0)|0,K=K+Math.imul(e,D0)|0,U=U+Math.imul(m,C0)|0,Q=Q+Math.imul(m,L0)|0,Q=Q+Math.imul(r,C0)|0,K=K+Math.imul(r,L0)|0,U=U+Math.imul(t,R0)|0,Q=Q+Math.imul(t,z0)|0,Q=Q+Math.imul(s,R0)|0,K=K+Math.imul(s,z0)|0,U=U+Math.imul(l,P0)|0,Q=Q+Math.imul(l,M0)|0,Q=Q+Math.imul(n,P0)|0,K=K+Math.imul(n,M0)|0;var s0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(s0>>>26)|0,s0&=67108863,U=Math.imul(Z0,A0),Q=Math.imul(Z0,W0),Q=Q+Math.imul(G0,A0)|0,K=Math.imul(G0,W0),U=U+Math.imul($0,H0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Q0,H0)|0,K=K+Math.imul(Q0,E0)|0,U=U+Math.imul(o,T0)|0,Q=Q+Math.imul(o,D0)|0,Q=Q+Math.imul(a,T0)|0,K=K+Math.imul(a,D0)|0,U=U+Math.imul(i,C0)|0,Q=Q+Math.imul(i,L0)|0,Q=Q+Math.imul(e,C0)|0,K=K+Math.imul(e,L0)|0,U=U+Math.imul(m,R0)|0,Q=Q+Math.imul(m,z0)|0,Q=Q+Math.imul(r,R0)|0,K=K+Math.imul(r,z0)|0,U=U+Math.imul(t,P0)|0,Q=Q+Math.imul(t,M0)|0,Q=Q+Math.imul(s,P0)|0,K=K+Math.imul(s,M0)|0;var t0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(t0>>>26)|0,t0&=67108863,U=Math.imul(Z0,H0),Q=Math.imul(Z0,E0),Q=Q+Math.imul(G0,H0)|0,K=Math.imul(G0,E0),U=U+Math.imul($0,T0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Q0,T0)|0,K=K+Math.imul(Q0,D0)|0,U=U+Math.imul(o,C0)|0,Q=Q+Math.imul(o,L0)|0,Q=Q+Math.imul(a,C0)|0,K=K+Math.imul(a,L0)|0,U=U+Math.imul(i,R0)|0,Q=Q+Math.imul(i,z0)|0,Q=Q+Math.imul(e,R0)|0,K=K+Math.imul(e,z0)|0,U=U+Math.imul(m,P0)|0,Q=Q+Math.imul(m,M0)|0,Q=Q+Math.imul(r,P0)|0,K=K+Math.imul(r,M0)|0;var m0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(m0>>>26)|0,m0&=67108863,U=Math.imul(Z0,T0),Q=Math.imul(Z0,D0),Q=Q+Math.imul(G0,T0)|0,K=Math.imul(G0,D0),U=U+Math.imul($0,C0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Q0,C0)|0,K=K+Math.imul(Q0,L0)|0,U=U+Math.imul(o,R0)|0,Q=Q+Math.imul(o,z0)|0,Q=Q+Math.imul(a,R0)|0,K=K+Math.imul(a,z0)|0,U=U+Math.imul(i,P0)|0,Q=Q+Math.imul(i,M0)|0,Q=Q+Math.imul(e,P0)|0,K=K+Math.imul(e,M0)|0;var a0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(a0>>>26)|0,a0&=67108863,U=Math.imul(Z0,C0),Q=Math.imul(Z0,L0),Q=Q+Math.imul(G0,C0)|0,K=Math.imul(G0,L0),U=U+Math.imul($0,R0)|0,Q=Q+Math.imul($0,z0)|0,Q=Q+Math.imul(Q0,R0)|0,K=K+Math.imul(Q0,z0)|0,U=U+Math.imul(o,P0)|0,Q=Q+Math.imul(o,M0)|0,Q=Q+Math.imul(a,P0)|0,K=K+Math.imul(a,M0)|0;var e0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(e0>>>26)|0,e0&=67108863,U=Math.imul(Z0,R0),Q=Math.imul(Z0,z0),Q=Q+Math.imul(G0,R0)|0,K=Math.imul(G0,z0),U=U+Math.imul($0,P0)|0,Q=Q+Math.imul($0,M0)|0,Q=Q+Math.imul(Q0,P0)|0,K=K+Math.imul(Q0,M0)|0;var r0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(r0>>>26)|0,r0&=67108863,U=Math.imul(Z0,P0),Q=Math.imul(Z0,M0),Q=Q+Math.imul(G0,P0)|0,K=Math.imul(G0,M0);var i0=(O+U|0)+((Q&8191)<<13)|0;return O=(K+(Q>>>13)|0)+(i0>>>26)|0,i0&=67108863,I[0]=Q$,I[1]=k0,I[2]=g0,I[3]=f0,I[4]=c0,I[5]=h0,I[6]=d0,I[7]=b0,I[8]=l0,I[9]=o0,I[10]=u0,I[11]=n0,I[12]=s0,I[13]=t0,I[14]=m0,I[15]=a0,I[16]=e0,I[17]=r0,I[18]=i0,O!==0&&(I[19]=O,G.length++),G};Math.imul||(M=R);function v($,Y,G){G.negative=Y.negative^$.negative,G.length=$.length+Y.length;for(var Z=0,V=0,I=0;I>>26)|0,V+=O>>>26,O&=67108863}G.words[I]=U,Z=O,O=V}return Z!==0?G.words[I]=Z:G.length--,G.strip()}function q($,Y,G){var Z=new g;return Z.mulp($,Y,G)}X.prototype.mulTo=function($,Y){var G,Z=this.length+$.length;return this.length===10&&$.length===10?G=M(this,$,Y):Z<63?G=R(this,$,Y):Z<1024?G=v(this,$,Y):G=q(this,$,Y),G};function g($,Y){this.x=$,this.y=Y}g.prototype.makeRBT=function($){for(var Y=new Array($),G=X.prototype._countBits($)-1,Z=0;Z<$;Z++)Y[Z]=this.revBin(Z,G,$);return Y},g.prototype.revBin=function($,Y,G){if($===0||$===G-1)return $;for(var Z=0,V=0;V>=1;return Z},g.prototype.permute=function($,Y,G,Z,V,I){for(var O=0;O>>1)V++;return 1<>>13,G[2*I+1]=V&8191,V=V>>>13;for(I=2*Y;I>=26,Y+=Z/67108864|0,Y+=V>>>26,this.words[G]=V&67108863}return Y!==0&&(this.words[G]=Y,this.length++),this},X.prototype.muln=function($){return this.clone().imuln($)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function($){var Y=E($);if(Y.length===0)return new X(1);for(var G=this,Z=0;Z=0);var Y=$%26,G=($-Y)/26,Z=67108863>>>26-Y<<26-Y,V;if(Y!==0){var I=0;for(V=0;V>>26-Y}I&&(this.words[V]=I,this.length++)}if(G!==0){for(V=this.length-1;V>=0;V--)this.words[V+G]=this.words[V];for(V=0;V=0);var Z;Y?Z=(Y-Y%26)/26:Z=0;var V=$%26,I=Math.min(($-V)/26,this.length),O=67108863^67108863>>>V<I)for(this.length-=I,Q=0;Q=0&&(K!==0||Q>=Z);Q--){var L=this.words[Q]|0;this.words[Q]=K<<26-V|L>>>V,K=L&O}return U&&K!==0&&(U.words[U.length++]=K),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},X.prototype.ishrn=function($,Y,G){return F(this.negative===0),this.iushrn($,Y,G)},X.prototype.shln=function($){return this.clone().ishln($)},X.prototype.ushln=function($){return this.clone().iushln($)},X.prototype.shrn=function($){return this.clone().ishrn($)},X.prototype.ushrn=function($){return this.clone().iushrn($)},X.prototype.testn=function($){F(typeof $=="number"&&$>=0);var Y=$%26,G=($-Y)/26,Z=1<=0);var Y=$%26,G=($-Y)/26;if(F(this.negative===0,"imaskn works only with positive numbers"),this.length<=G)return this;if(Y!==0&&G++,this.length=Math.min(G,this.length),Y!==0){var Z=67108863^67108863>>>Y<=67108864;Y++)this.words[Y]-=67108864,Y===this.length-1?this.words[Y+1]=1:this.words[Y+1]++;return this.length=Math.max(this.length,Y+1),this},X.prototype.isubn=function($){if(F(typeof $=="number"),F($<67108864),$<0)return this.iaddn(-$);if(this.negative!==0)return this.negative=0,this.iaddn($),this.negative=1,this;if(this.words[0]-=$,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Y=0;Y>26)-(U/67108864|0),this.words[V+G]=I&67108863}for(;V>26,this.words[V+G]=I&67108863;if(O===0)return this.strip();for(F(O===-1),O=0,V=0;V>26,this.words[V]=I&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function($,Y){var G=this.length-$.length,Z=this.clone(),V=$,I=V.words[V.length-1]|0,O=this._countBits(I);G=26-O,G!==0&&(V=V.ushln(G),Z.iushln(G),I=V.words[V.length-1]|0);var U=Z.length-V.length,Q;if(Y!=="mod"){Q=new X(null),Q.length=U+1,Q.words=new Array(Q.length);for(var K=0;K=0;A--){var S=(Z.words[V.length+A]|0)*67108864+(Z.words[V.length+A-1]|0);for(S=Math.min(S/I|0,67108863),Z._ishlnsubmul(V,S,A);Z.negative!==0;)S--,Z.negative=0,Z._ishlnsubmul(V,1,A),Z.isZero()||(Z.negative^=1);Q&&(Q.words[A]=S)}return Q&&Q.strip(),Z.strip(),Y!=="div"&&G!==0&&Z.iushrn(G),{div:Q||null,mod:Z}},X.prototype.divmod=function($,Y,G){if(F(!$.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var Z,V,I;return this.negative!==0&&$.negative===0?(I=this.neg().divmod($,Y),Y!=="mod"&&(Z=I.div.neg()),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.iadd($)),{div:Z,mod:V}):this.negative===0&&$.negative!==0?(I=this.divmod($.neg(),Y),Y!=="mod"&&(Z=I.div.neg()),{div:Z,mod:I.mod}):(this.negative&$.negative)!==0?(I=this.neg().divmod($.neg(),Y),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.isub($)),{div:I.div,mod:V}):$.length>this.length||this.cmp($)<0?{div:new X(0),mod:this}:$.length===1?Y==="div"?{div:this.divn($.words[0]),mod:null}:Y==="mod"?{div:null,mod:new X(this.modn($.words[0]))}:{div:this.divn($.words[0]),mod:new X(this.modn($.words[0]))}:this._wordDiv($,Y)},X.prototype.div=function($){return this.divmod($,"div",!1).div},X.prototype.mod=function($){return this.divmod($,"mod",!1).mod},X.prototype.umod=function($){return this.divmod($,"mod",!0).mod},X.prototype.divRound=function($){var Y=this.divmod($);if(Y.mod.isZero())return Y.div;var G=Y.div.negative!==0?Y.mod.isub($):Y.mod,Z=$.ushrn(1),V=$.andln(1),I=G.cmp(Z);return I<0||V===1&&I===0?Y.div:Y.div.negative!==0?Y.div.isubn(1):Y.div.iaddn(1)},X.prototype.modn=function($){F($<=67108863);for(var Y=(1<<26)%$,G=0,Z=this.length-1;Z>=0;Z--)G=(Y*G+(this.words[Z]|0))%$;return G},X.prototype.idivn=function($){F($<=67108863);for(var Y=0,G=this.length-1;G>=0;G--){var Z=(this.words[G]|0)+Y*67108864;this.words[G]=Z/$|0,Y=Z%$}return this.strip()},X.prototype.divn=function($){return this.clone().idivn($)},X.prototype.egcd=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=new X(0),O=new X(1),U=0;Y.isEven()&&G.isEven();)Y.iushrn(1),G.iushrn(1),++U;for(var Q=G.clone(),K=Y.clone();!Y.isZero();){for(var L=0,A=1;(Y.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0)for(Y.iushrn(L);L-- >0;)(Z.isOdd()||V.isOdd())&&(Z.iadd(Q),V.isub(K)),Z.iushrn(1),V.iushrn(1);for(var S=0,x=1;(G.words[0]&x)===0&&S<26;++S,x<<=1);if(S>0)for(G.iushrn(S);S-- >0;)(I.isOdd()||O.isOdd())&&(I.iadd(Q),O.isub(K)),I.iushrn(1),O.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(I),V.isub(O)):(G.isub(Y),I.isub(Z),O.isub(V))}return{a:I,b:O,gcd:G.iushln(U)}},X.prototype._invmp=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=G.clone();Y.cmpn(1)>0&&G.cmpn(1)>0;){for(var O=0,U=1;(Y.words[0]&U)===0&&O<26;++O,U<<=1);if(O>0)for(Y.iushrn(O);O-- >0;)Z.isOdd()&&Z.iadd(I),Z.iushrn(1);for(var Q=0,K=1;(G.words[0]&K)===0&&Q<26;++Q,K<<=1);if(Q>0)for(G.iushrn(Q);Q-- >0;)V.isOdd()&&V.iadd(I),V.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(V)):(G.isub(Y),V.isub(Z))}var L;return Y.cmpn(1)===0?L=Z:L=V,L.cmpn(0)<0&&L.iadd($),L},X.prototype.gcd=function($){if(this.isZero())return $.abs();if($.isZero())return this.abs();var Y=this.clone(),G=$.clone();Y.negative=0,G.negative=0;for(var Z=0;Y.isEven()&&G.isEven();Z++)Y.iushrn(1),G.iushrn(1);do{for(;Y.isEven();)Y.iushrn(1);for(;G.isEven();)G.iushrn(1);var V=Y.cmp(G);if(V<0){var I=Y;Y=G,G=I}else if(V===0||G.cmpn(1)===0)break;Y.isub(G)}while(!0);return G.iushln(Z)},X.prototype.invm=function($){return this.egcd($).a.umod($)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function($){return this.words[0]&$},X.prototype.bincn=function($){F(typeof $=="number");var Y=$%26,G=($-Y)/26,Z=1<>>26,O&=67108863,this.words[I]=O}return V!==0&&(this.words[I]=V,this.length++),this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function($){var Y=$<0;if(this.negative!==0&&!Y)return-1;if(this.negative===0&&Y)return 1;this.strip();var G;if(this.length>1)G=1;else{Y&&($=-$),F($<=67108863,"Number is too big");var Z=this.words[0]|0;G=Z===$?0:Z<$?-1:1}return this.negative!==0?-G|0:G},X.prototype.cmp=function($){if(this.negative!==0&&$.negative===0)return-1;if(this.negative===0&&$.negative!==0)return 1;var Y=this.ucmp($);return this.negative!==0?-Y|0:Y},X.prototype.ucmp=function($){if(this.length>$.length)return 1;if(this.length<$.length)return-1;for(var Y=0,G=this.length-1;G>=0;G--){var Z=this.words[G]|0,V=$.words[G]|0;if(Z!==V){ZV&&(Y=1);break}}return Y},X.prototype.gtn=function($){return this.cmpn($)===1},X.prototype.gt=function($){return this.cmp($)===1},X.prototype.gten=function($){return this.cmpn($)>=0},X.prototype.gte=function($){return this.cmp($)>=0},X.prototype.ltn=function($){return this.cmpn($)===-1},X.prototype.lt=function($){return this.cmp($)===-1},X.prototype.lten=function($){return this.cmpn($)<=0},X.prototype.lte=function($){return this.cmp($)<=0},X.prototype.eqn=function($){return this.cmpn($)===0},X.prototype.eq=function($){return this.cmp($)===0},X.red=function($){return new p($)},X.prototype.toRed=function($){return F(!this.red,"Already a number in reduction context"),F(this.negative===0,"red works only with positives"),$.convertTo(this)._forceRed($)},X.prototype.fromRed=function(){return F(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function($){return this.red=$,this},X.prototype.forceRed=function($){return F(!this.red,"Already a number in reduction context"),this._forceRed($)},X.prototype.redAdd=function($){return F(this.red,"redAdd works only with red numbers"),this.red.add(this,$)},X.prototype.redIAdd=function($){return F(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,$)},X.prototype.redSub=function($){return F(this.red,"redSub works only with red numbers"),this.red.sub(this,$)},X.prototype.redISub=function($){return F(this.red,"redISub works only with red numbers"),this.red.isub(this,$)},X.prototype.redShl=function($){return F(this.red,"redShl works only with red numbers"),this.red.shl(this,$)},X.prototype.redMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.mul(this,$)},X.prototype.redIMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.imul(this,$)},X.prototype.redSqr=function(){return F(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return F(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return F(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return F(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return F(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function($){return F(this.red&&!$.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,$)};var B={k256:null,p224:null,p192:null,p25519:null};function w($,Y){this.name=$,this.p=new X(Y,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}w.prototype._tmp=function(){var $=new X(null);return $.words=new Array(Math.ceil(this.n/13)),$},w.prototype.ireduce=function($){var Y=$,G;do this.split(Y,this.tmp),Y=this.imulK(Y),Y=Y.iadd(this.tmp),G=Y.bitLength();while(G>this.n);var Z=G0?Y.isub(this.p):Y.strip!==void 0?Y.strip():Y._strip(),Y},w.prototype.split=function($,Y){$.iushrn(this.n,0,Y)},w.prototype.imulK=function($){return $.imul(this.k)};function f(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}P(f,w),f.prototype.split=function($,Y){for(var G=4194303,Z=Math.min($.length,9),V=0;V>>22,I=O}I>>>=22,$.words[V-10]=I,I===0&&$.length>10?$.length-=10:$.length-=9},f.prototype.imulK=function($){$.words[$.length]=0,$.words[$.length+1]=0,$.length+=2;for(var Y=0,G=0;G<$.length;G++){var Z=$.words[G]|0;Y+=Z*977,$.words[G]=Y&67108863,Y=Z*64+(Y/67108864|0)}return $.words[$.length-1]===0&&($.length--,$.words[$.length-1]===0&&$.length--),$};function b(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}P(b,w);function u(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}P(u,w);function Y0(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}P(Y0,w),Y0.prototype.imulK=function($){for(var Y=0,G=0;G<$.length;G++){var Z=($.words[G]|0)*19+Y,V=Z&67108863;Z>>>=26,$.words[G]=V,Y=Z}return Y!==0&&($.words[$.length++]=Y),$},X._prime=function($){if(B[$])return B[$];var Y;if($==="k256")Y=new f;else if($==="p224")Y=new b;else if($==="p192")Y=new u;else if($==="p25519")Y=new Y0;else throw new Error("Unknown prime "+$);return B[$]=Y,Y};function p($){if(typeof $=="string"){var Y=X._prime($);this.m=Y.p,this.prime=Y}else F($.gtn(1),"modulus must be greater than 1"),this.m=$,this.prime=null}p.prototype._verify1=function($){F($.negative===0,"red works only with positives"),F($.red,"red works only with red numbers")},p.prototype._verify2=function($,Y){F(($.negative|Y.negative)===0,"red works only with positives"),F($.red&&$.red===Y.red,"red works only with red numbers")},p.prototype.imod=function($){return this.prime?this.prime.ireduce($)._forceRed(this):$.umod(this.m)._forceRed(this)},p.prototype.neg=function($){return $.isZero()?$.clone():this.m.sub($)._forceRed(this)},p.prototype.add=function($,Y){this._verify2($,Y);var G=$.add(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G._forceRed(this)},p.prototype.iadd=function($,Y){this._verify2($,Y);var G=$.iadd(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G},p.prototype.sub=function($,Y){this._verify2($,Y);var G=$.sub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G._forceRed(this)},p.prototype.isub=function($,Y){this._verify2($,Y);var G=$.isub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G},p.prototype.shl=function($,Y){return this._verify1($),this.imod($.ushln(Y))},p.prototype.imul=function($,Y){return this._verify2($,Y),this.imod($.imul(Y))},p.prototype.mul=function($,Y){return this._verify2($,Y),this.imod($.mul(Y))},p.prototype.isqr=function($){return this.imul($,$.clone())},p.prototype.sqr=function($){return this.mul($,$)},p.prototype.sqrt=function($){if($.isZero())return $.clone();var Y=this.m.andln(3);if(F(Y%2===1),Y===3){var G=this.m.add(new X(1)).iushrn(2);return this.pow($,G)}for(var Z=this.m.subn(1),V=0;!Z.isZero()&&Z.andln(1)===0;)V++,Z.iushrn(1);F(!Z.isZero());var I=new X(1).toRed(this),O=I.redNeg(),U=this.m.subn(1).iushrn(1),Q=this.m.bitLength();for(Q=new X(2*Q*Q).toRed(this);this.pow(Q,U).cmp(O)!==0;)Q.redIAdd(O);for(var K=this.pow(Q,Z),L=this.pow($,Z.addn(1).iushrn(1)),A=this.pow($,Z),S=V;A.cmp(I)!==0;){for(var x=A,y=0;x.cmp(I)!==0;y++)x=x.redSqr();F(y=0;V--){for(var K=Y.words[V],L=Q-1;L>=0;L--){var A=K>>L&1;if(I!==Z[0]&&(I=this.sqr(I)),A===0&&O===0){U=0;continue}O<<=1,O|=A,U++,!(U!==G&&(V!==0||L!==0))&&(I=this.mul(I,Z[O]),U=0,O=0)}Q=26}return I},p.prototype.convertTo=function($){var Y=$.umod(this.m);return Y===$?Y.clone():Y},p.prototype.convertFrom=function($){var Y=$.clone();return Y.red=null,Y},X.mont=function($){return new v0($)};function v0($){p.call(this,$),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new X(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}P(v0,p),v0.prototype.convertTo=function($){return this.imod($.ushln(this.shift))},v0.prototype.convertFrom=function($){var Y=this.imod($.mul(this.rinv));return Y.red=null,Y},v0.prototype.imul=function($,Y){if($.isZero()||Y.isZero())return $.words[0]=0,$.length=1,$;var G=$.imul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.mul=function($,Y){if($.isZero()||Y.isZero())return new X(0)._forceRed(this);var G=$.mul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.invm=function($){var Y=this.imod($._invmp(this.m).mul(this.r2));return Y._forceRed(this)}})(typeof _>"u"||_,N)}}),SQ=S0({"node_modules/minimalistic-crypto-utils/lib/utils.js"(N){var _=N;function j(P,X){if(Array.isArray(P))return P.slice();if(!P)return[];var C=[];if(typeof P!="string"){for(var z=0;z>8,J=T&255;H?C.push(H,J):C.push(J)}return C}_.toArray=j;function k(P){return P.length===1?"0"+P:P}_.zero2=k;function F(P){for(var X="",C=0;C(E>>1)-1?v=(E>>1)-q:v=q,R.isubn(v)):v=0,D[M]=v,R.iushrn(1)}return D}_.getNAF=P;function X(H,J){var W=[[],[]];H=H.clone(),J=J.clone();for(var D=0,E=0,R;H.cmpn(-D)>0||J.cmpn(-E)>0;){var M=H.andln(3)+D&3,v=J.andln(3)+E&3;M===3&&(M=-1),v===3&&(v=-1);var q;(M&1)===0?q=0:(R=H.andln(7)+D&7,(R===3||R===5)&&v===2?q=-M:q=M),W[0].push(q);var g;(v&1)===0?g=0:(R=J.andln(7)+E&7,(R===3||R===5)&&M===2?g=-v:g=v),W[1].push(g),2*D===q+1&&(D=1-D),2*E===g+1&&(E=1-E),H.iushrn(1),J.iushrn(1)}return W}_.getJSF=X;function C(H,J,W){var D="_"+J;H.prototype[J]=function(){return this[D]!==void 0?this[D]:this[D]=W.call(this)}}_.cachedProperty=C;function z(H){return typeof H=="string"?_.toArray(H,"hex"):H}_.parseBytes=z;function T(H){return new j(H,"hex","le")}_.intFromLE=T}}),g$=S0({"node_modules/elliptic/lib/elliptic/curve/base.js"(N,_){var j=D$(),k=E$(),F=k.getNAF,P=k.getJSF,X=k.assert;function C(T,H){this.type=T,this.p=new j(H.p,16),this.red=H.prime?j.red(H.prime):j.mont(this.p),this.zero=new j(0).toRed(this.red),this.one=new j(1).toRed(this.red),this.two=new j(2).toRed(this.red),this.n=H.n&&new j(H.n,16),this.g=H.g&&this.pointFromJSON(H.g,H.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var J=this.n&&this.p.div(this.n);!J||J.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}_.exports=C,C.prototype.point=function(){throw new Error("Not implemented")},C.prototype.validate=function(){throw new Error("Not implemented")},C.prototype._fixedNafMul=function(T,H){X(T.precomputed);var J=T._getDoubles(),W=F(H,1,this._bitLength),D=(1<=R;v--)M=(M<<1)+W[v];E.push(M)}for(var q=this.jpoint(null,null,null),g=this.jpoint(null,null,null),B=D;B>0;B--){for(R=0;R=0;M--){for(var v=0;M>=0&&E[M]===0;M--)v++;if(M>=0&&v++,R=R.dblp(v),M<0)break;var q=E[M];X(q!==0),T.type==="affine"?q>0?R=R.mixedAdd(D[q-1>>1]):R=R.mixedAdd(D[-q-1>>1].neg()):q>0?R=R.add(D[q-1>>1]):R=R.add(D[-q-1>>1].neg())}return T.type==="affine"?R.toP():R},C.prototype._wnafMulAdd=function(T,H,J,W,D){var E=this._wnafT1,R=this._wnafT2,M=this._wnafT3,v=0,q,g,B;for(q=0;q=1;q-=2){var f=q-1,b=q;if(E[f]!==1||E[b]!==1){M[f]=F(J[f],E[f],this._bitLength),M[b]=F(J[b],E[b],this._bitLength),v=Math.max(M[f].length,v),v=Math.max(M[b].length,v);continue}var u=[H[f],null,null,H[b]];H[f].y.cmp(H[b].y)===0?(u[1]=H[f].add(H[b]),u[2]=H[f].toJ().mixedAdd(H[b].neg())):H[f].y.cmp(H[b].y.redNeg())===0?(u[1]=H[f].toJ().mixedAdd(H[b]),u[2]=H[f].add(H[b].neg())):(u[1]=H[f].toJ().mixedAdd(H[b]),u[2]=H[f].toJ().mixedAdd(H[b].neg()));var Y0=[-3,-1,-5,-7,0,7,5,1,3],p=P(J[f],J[b]);for(v=Math.max(p[0].length,v),M[f]=new Array(v),M[b]=new Array(v),g=0;g=0;q--){for(var Z=0;q>=0;){var V=!0;for(g=0;g=0&&Z++,Y=Y.dblp(Z),q<0)break;for(g=0;g0?B=R[g][I-1>>1]:I<0&&(B=R[g][-I-1>>1].neg()),B.type==="affine"?Y=Y.mixedAdd(B):Y=Y.add(B))}}for(q=0;q=Math.ceil((T.bitLength()+1)/H.step):!1},z.prototype._getDoubles=function(T,H){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var J=[this],W=this,D=0;D=0&&(f=q,b=g),B.negative&&(B=B.neg(),w=w.neg()),f.negative&&(f=f.neg(),b=b.neg()),[{a:B,b:w},{a:f,b}]},C.prototype._endoSplit=function(H){var J=this.endo.basis,W=J[0],D=J[1],E=D.b.mul(H).divRound(this.n),R=W.b.neg().mul(H).divRound(this.n),M=E.mul(W.a),v=R.mul(D.a),q=E.mul(W.b),g=R.mul(D.b),B=H.sub(M).sub(v),w=q.add(g).neg();return{k1:B,k2:w}},C.prototype.pointFromX=function(H,J){H=new k(H,16),H.red||(H=H.toRed(this.red));var W=H.redSqr().redMul(H).redIAdd(H.redMul(this.a)).redIAdd(this.b),D=W.redSqrt();if(D.redSqr().redSub(W).cmp(this.zero)!==0)throw new Error("invalid point");var E=D.fromRed().isOdd();return(J&&!E||!J&&E)&&(D=D.redNeg()),this.point(H,D)},C.prototype.validate=function(H){if(H.inf)return!0;var{x:J,y:W}=H,D=this.a.redMul(J),E=J.redSqr().redMul(J).redIAdd(D).redIAdd(this.b);return W.redSqr().redISub(E).cmpn(0)===0},C.prototype._endoWnafMulAdd=function(H,J,W){for(var D=this._endoWnafT1,E=this._endoWnafT2,R=0;R":""},z.prototype.isInfinity=function(){return this.inf},z.prototype.add=function(H){if(this.inf)return H;if(H.inf)return this;if(this.eq(H))return this.dbl();if(this.neg().eq(H))return this.curve.point(null,null);if(this.x.cmp(H.x)===0)return this.curve.point(null,null);var J=this.y.redSub(H.y);J.cmpn(0)!==0&&(J=J.redMul(this.x.redSub(H.x).redInvm()));var W=J.redSqr().redISub(this.x).redISub(H.x),D=J.redMul(this.x.redSub(W)).redISub(this.y);return this.curve.point(W,D)},z.prototype.dbl=function(){if(this.inf)return this;var H=this.y.redAdd(this.y);if(H.cmpn(0)===0)return this.curve.point(null,null);var J=this.curve.a,W=this.x.redSqr(),D=H.redInvm(),E=W.redAdd(W).redIAdd(W).redIAdd(J).redMul(D),R=E.redSqr().redISub(this.x.redAdd(this.x)),M=E.redMul(this.x.redSub(R)).redISub(this.y);return this.curve.point(R,M)},z.prototype.getX=function(){return this.x.fromRed()},z.prototype.getY=function(){return this.y.fromRed()},z.prototype.mul=function(H){return H=new k(H,16),this.isInfinity()?this:this._hasDoubles(H)?this.curve._fixedNafMul(this,H):this.curve.endo?this.curve._endoWnafMulAdd([this],[H]):this.curve._wnafMul(this,H)},z.prototype.mulAdd=function(H,J,W){var D=[this,J],E=[H,W];return this.curve.endo?this.curve._endoWnafMulAdd(D,E):this.curve._wnafMulAdd(1,D,E,2)},z.prototype.jmulAdd=function(H,J,W){var D=[this,J],E=[H,W];return this.curve.endo?this.curve._endoWnafMulAdd(D,E,!0):this.curve._wnafMulAdd(1,D,E,2,!0)},z.prototype.eq=function(H){return this===H||this.inf===H.inf&&(this.inf||this.x.cmp(H.x)===0&&this.y.cmp(H.y)===0)},z.prototype.neg=function(H){if(this.inf)return this;var J=this.curve.point(this.x,this.y.redNeg());if(H&&this.precomputed){var W=this.precomputed,D=function(E){return E.neg()};J.precomputed={naf:W.naf&&{wnd:W.naf.wnd,points:W.naf.points.map(D)},doubles:W.doubles&&{step:W.doubles.step,points:W.doubles.points.map(D)}}}return J},z.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var H=this.curve.jpoint(this.x,this.y,this.curve.one);return H};function T(H,J,W,D){P.BasePoint.call(this,H,"jacobian"),J===null&&W===null&&D===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new k(0)):(this.x=new k(J,16),this.y=new k(W,16),this.z=new k(D,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}F(T,P.BasePoint),C.prototype.jpoint=function(H,J,W){return new T(this,H,J,W)},T.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var H=this.z.redInvm(),J=H.redSqr(),W=this.x.redMul(J),D=this.y.redMul(J).redMul(H);return this.curve.point(W,D)},T.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},T.prototype.add=function(H){if(this.isInfinity())return H;if(H.isInfinity())return this;var J=H.z.redSqr(),W=this.z.redSqr(),D=this.x.redMul(J),E=H.x.redMul(W),R=this.y.redMul(J.redMul(H.z)),M=H.y.redMul(W.redMul(this.z)),v=D.redSub(E),q=R.redSub(M);if(v.cmpn(0)===0)return q.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var g=v.redSqr(),B=g.redMul(v),w=D.redMul(g),f=q.redSqr().redIAdd(B).redISub(w).redISub(w),b=q.redMul(w.redISub(f)).redISub(R.redMul(B)),u=this.z.redMul(H.z).redMul(v);return this.curve.jpoint(f,b,u)},T.prototype.mixedAdd=function(H){if(this.isInfinity())return H.toJ();if(H.isInfinity())return this;var J=this.z.redSqr(),W=this.x,D=H.x.redMul(J),E=this.y,R=H.y.redMul(J).redMul(this.z),M=W.redSub(D),v=E.redSub(R);if(M.cmpn(0)===0)return v.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var q=M.redSqr(),g=q.redMul(M),B=W.redMul(q),w=v.redSqr().redIAdd(g).redISub(B).redISub(B),f=v.redMul(B.redISub(w)).redISub(E.redMul(g)),b=this.z.redMul(M);return this.curve.jpoint(w,f,b)},T.prototype.dblp=function(H){if(H===0)return this;if(this.isInfinity())return this;if(!H)return this.dbl();var J;if(this.curve.zeroA||this.curve.threeA){var W=this;for(J=0;J=0)return!1;if(W.redIAdd(E),this.x.cmp(W)===0)return!0}},T.prototype.inspect=function(){return this.isInfinity()?"":""},T.prototype.isInfinity=function(){return this.z.cmpn(0)===0}}}),MY=S0({"node_modules/elliptic/lib/elliptic/curve/mont.js"(N,_){var j=D$(),k=B0(),F=g$(),P=E$();function X(z){F.call(this,"mont",z),this.a=new j(z.a,16).toRed(this.red),this.b=new j(z.b,16).toRed(this.red),this.i4=new j(4).toRed(this.red).redInvm(),this.two=new j(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}k(X,F),_.exports=X,X.prototype.validate=function(z){var T=z.normalize().x,H=T.redSqr(),J=H.redMul(T).redAdd(H.redMul(this.a)).redAdd(T),W=J.redSqrt();return W.redSqr().cmp(J)===0};function C(z,T,H){F.BasePoint.call(this,z,"projective"),T===null&&H===null?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new j(T,16),this.z=new j(H,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}k(C,F.BasePoint),X.prototype.decodePoint=function(z,T){return this.point(P.toArray(z,T),1)},X.prototype.point=function(z,T){return new C(this,z,T)},X.prototype.pointFromJSON=function(z){return C.fromJSON(this,z)},C.prototype.precompute=function(){},C.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},C.fromJSON=function(z,T){return new C(z,T[0],T[1]||z.one)},C.prototype.inspect=function(){return this.isInfinity()?"":""},C.prototype.isInfinity=function(){return this.z.cmpn(0)===0},C.prototype.dbl=function(){var z=this.x.redAdd(this.z),T=z.redSqr(),H=this.x.redSub(this.z),J=H.redSqr(),W=T.redSub(J),D=T.redMul(J),E=W.redMul(J.redAdd(this.curve.a24.redMul(W)));return this.curve.point(D,E)},C.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},C.prototype.diffAdd=function(z,T){var H=this.x.redAdd(this.z),J=this.x.redSub(this.z),W=z.x.redAdd(z.z),D=z.x.redSub(z.z),E=D.redMul(H),R=W.redMul(J),M=T.z.redMul(E.redAdd(R).redSqr()),v=T.x.redMul(E.redISub(R).redSqr());return this.curve.point(M,v)},C.prototype.mul=function(z){for(var T=z.clone(),H=this,J=this.curve.point(null,null),W=this,D=[];T.cmpn(0)!==0;T.iushrn(1))D.push(T.andln(1));for(var E=D.length-1;E>=0;E--)D[E]===0?(H=H.diffAdd(J,W),J=J.dbl()):(J=H.diffAdd(J,W),H=H.dbl());return J},C.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},C.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},C.prototype.eq=function(z){return this.getX().cmp(z.getX())===0},C.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},C.prototype.getX=function(){return this.normalize(),this.x.fromRed()}}}),SY=S0({"node_modules/elliptic/lib/elliptic/curve/edwards.js"(N,_){var j=E$(),k=D$(),F=B0(),P=g$(),X=j.assert;function C(T){this.twisted=(T.a|0)!==1,this.mOneA=this.twisted&&(T.a|0)===-1,this.extended=this.mOneA,P.call(this,"edwards",T),this.a=new k(T.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new k(T.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new k(T.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),X(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(T.c|0)===1}F(C,P),_.exports=C,C.prototype._mulA=function(T){return this.mOneA?T.redNeg():this.a.redMul(T)},C.prototype._mulC=function(T){return this.oneC?T:this.c.redMul(T)},C.prototype.jpoint=function(T,H,J,W){return this.point(T,H,J,W)},C.prototype.pointFromX=function(T,H){T=new k(T,16),T.red||(T=T.toRed(this.red));var J=T.redSqr(),W=this.c2.redSub(this.a.redMul(J)),D=this.one.redSub(this.c2.redMul(this.d).redMul(J)),E=W.redMul(D.redInvm()),R=E.redSqrt();if(R.redSqr().redSub(E).cmp(this.zero)!==0)throw new Error("invalid point");var M=R.fromRed().isOdd();return(H&&!M||!H&&M)&&(R=R.redNeg()),this.point(T,R)},C.prototype.pointFromY=function(T,H){T=new k(T,16),T.red||(T=T.toRed(this.red));var J=T.redSqr(),W=J.redSub(this.c2),D=J.redMul(this.d).redMul(this.c2).redSub(this.a),E=W.redMul(D.redInvm());if(E.cmp(this.zero)===0){if(H)throw new Error("invalid point");return this.point(this.zero,T)}var R=E.redSqrt();if(R.redSqr().redSub(E).cmp(this.zero)!==0)throw new Error("invalid point");return R.fromRed().isOdd()!==H&&(R=R.redNeg()),this.point(R,T)},C.prototype.validate=function(T){if(T.isInfinity())return!0;T.normalize();var H=T.x.redSqr(),J=T.y.redSqr(),W=H.redMul(this.a).redAdd(J),D=this.c2.redMul(this.one.redAdd(this.d.redMul(H).redMul(J)));return W.cmp(D)===0};function z(T,H,J,W,D){P.BasePoint.call(this,T,"projective"),H===null&&J===null&&W===null?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new k(H,16),this.y=new k(J,16),this.z=W?new k(W,16):this.curve.one,this.t=D&&new k(D,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}F(z,P.BasePoint),C.prototype.pointFromJSON=function(T){return z.fromJSON(this,T)},C.prototype.point=function(T,H,J,W){return new z(this,T,H,J,W)},z.fromJSON=function(T,H){return new z(T,H[0],H[1],H[2])},z.prototype.inspect=function(){return this.isInfinity()?"":""},z.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},z.prototype._extDbl=function(){var T=this.x.redSqr(),H=this.y.redSqr(),J=this.z.redSqr();J=J.redIAdd(J);var W=this.curve._mulA(T),D=this.x.redAdd(this.y).redSqr().redISub(T).redISub(H),E=W.redAdd(H),R=E.redSub(J),M=W.redSub(H),v=D.redMul(R),q=E.redMul(M),g=D.redMul(M),B=R.redMul(E);return this.curve.point(v,q,B,g)},z.prototype._projDbl=function(){var T=this.x.redAdd(this.y).redSqr(),H=this.x.redSqr(),J=this.y.redSqr(),W,D,E,R,M,v;if(this.curve.twisted){R=this.curve._mulA(H);var q=R.redAdd(J);this.zOne?(W=T.redSub(H).redSub(J).redMul(q.redSub(this.curve.two)),D=q.redMul(R.redSub(J)),E=q.redSqr().redSub(q).redSub(q)):(M=this.z.redSqr(),v=q.redSub(M).redISub(M),W=T.redSub(H).redISub(J).redMul(v),D=q.redMul(R.redSub(J)),E=q.redMul(v))}else R=H.redAdd(J),M=this.curve._mulC(this.z).redSqr(),v=R.redSub(M).redSub(M),W=this.curve._mulC(T.redISub(R)).redMul(v),D=this.curve._mulC(R).redMul(H.redISub(J)),E=R.redMul(v);return this.curve.point(W,D,E)},z.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},z.prototype._extAdd=function(T){var H=this.y.redSub(this.x).redMul(T.y.redSub(T.x)),J=this.y.redAdd(this.x).redMul(T.y.redAdd(T.x)),W=this.t.redMul(this.curve.dd).redMul(T.t),D=this.z.redMul(T.z.redAdd(T.z)),E=J.redSub(H),R=D.redSub(W),M=D.redAdd(W),v=J.redAdd(H),q=E.redMul(R),g=M.redMul(v),B=E.redMul(v),w=R.redMul(M);return this.curve.point(q,g,w,B)},z.prototype._projAdd=function(T){var H=this.z.redMul(T.z),J=H.redSqr(),W=this.x.redMul(T.x),D=this.y.redMul(T.y),E=this.curve.d.redMul(W).redMul(D),R=J.redSub(E),M=J.redAdd(E),v=this.x.redAdd(this.y).redMul(T.x.redAdd(T.y)).redISub(W).redISub(D),q=H.redMul(R).redMul(v),g,B;return this.curve.twisted?(g=H.redMul(M).redMul(D.redSub(this.curve._mulA(W))),B=R.redMul(M)):(g=H.redMul(M).redMul(D.redSub(W)),B=this.curve._mulC(R).redMul(M)),this.curve.point(q,g,B)},z.prototype.add=function(T){return this.isInfinity()?T:T.isInfinity()?this:this.curve.extended?this._extAdd(T):this._projAdd(T)},z.prototype.mul=function(T){return this._hasDoubles(T)?this.curve._fixedNafMul(this,T):this.curve._wnafMul(this,T)},z.prototype.mulAdd=function(T,H,J){return this.curve._wnafMulAdd(1,[this,H],[T,J],2,!1)},z.prototype.jmulAdd=function(T,H,J){return this.curve._wnafMulAdd(1,[this,H],[T,J],2,!0)},z.prototype.normalize=function(){if(this.zOne)return this;var T=this.z.redInvm();return this.x=this.x.redMul(T),this.y=this.y.redMul(T),this.t&&(this.t=this.t.redMul(T)),this.z=this.curve.one,this.zOne=!0,this},z.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},z.prototype.getX=function(){return this.normalize(),this.x.fromRed()},z.prototype.getY=function(){return this.normalize(),this.y.fromRed()},z.prototype.eq=function(T){return this===T||this.getX().cmp(T.getX())===0&&this.getY().cmp(T.getY())===0},z.prototype.eqXToP=function(T){var H=T.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(H)===0)return!0;for(var J=T.clone(),W=this.curve.redN.redMul(this.z);;){if(J.iadd(this.curve.n),J.cmp(this.curve.p)>=0)return!1;if(H.redIAdd(W),this.x.cmp(H)===0)return!0}},z.prototype.toP=z.prototype.normalize,z.prototype.mixedAdd=z.prototype.add}}),vQ=S0({"node_modules/elliptic/lib/elliptic/curve/index.js"(N){var _=N;_.base=g$(),_.short=PY(),_.mont=MY(),_.edwards=SY()}}),T$=S0({"node_modules/hash.js/lib/hash/utils.js"(N){var _=H$(),j=B0();N.inherits=j;function k(Y,G){return(Y.charCodeAt(G)&64512)!==55296||G<0||G+1>=Y.length?!1:(Y.charCodeAt(G+1)&64512)===56320}function F(Y,G){if(Array.isArray(Y))return Y.slice();if(!Y)return[];var Z=[];if(typeof Y=="string")if(G){if(G==="hex")for(Y=Y.replace(/[^a-z0-9]+/gi,""),Y.length%2!==0&&(Y="0"+Y),I=0;I>6|192,Z[V++]=O&63|128):k(Y,I)?(O=65536+((O&1023)<<10)+(Y.charCodeAt(++I)&1023),Z[V++]=O>>18|240,Z[V++]=O>>12&63|128,Z[V++]=O>>6&63|128,Z[V++]=O&63|128):(Z[V++]=O>>12|224,Z[V++]=O>>6&63|128,Z[V++]=O&63|128)}else for(I=0;I>>24|Y>>>8&65280|Y<<8&16711680|(Y&255)<<24;return G>>>0}N.htonl=X;function C(Y,G){for(var Z="",V=0;V>>0}return O}N.join32=H;function J(Y,G){for(var Z=new Array(Y.length*4),V=0,I=0;V>>24,Z[I+1]=O>>>16&255,Z[I+2]=O>>>8&255,Z[I+3]=O&255):(Z[I+3]=O>>>24,Z[I+2]=O>>>16&255,Z[I+1]=O>>>8&255,Z[I]=O&255)}return Z}N.split32=J;function W(Y,G){return Y>>>G|Y<<32-G}N.rotr32=W;function D(Y,G){return Y<>>32-G}N.rotl32=D;function E(Y,G){return Y+G>>>0}N.sum32=E;function R(Y,G,Z){return Y+G+Z>>>0}N.sum32_3=R;function M(Y,G,Z,V){return Y+G+Z+V>>>0}N.sum32_4=M;function v(Y,G,Z,V,I){return Y+G+Z+V+I>>>0}N.sum32_5=v;function q(Y,G,Z,V){var I=Y[G],O=Y[G+1],U=V+O>>>0,Q=(U>>0,Y[G+1]=U}N.sum64=q;function g(Y,G,Z,V){var I=G+V>>>0,O=(I>>0}N.sum64_hi=g;function B(Y,G,Z,V){var I=G+V;return I>>>0}N.sum64_lo=B;function w(Y,G,Z,V,I,O,U,Q){var K=0,L=G;L=L+V>>>0,K+=L>>0,K+=L>>0,K+=L>>0}N.sum64_4_hi=w;function f(Y,G,Z,V,I,O,U,Q){var K=G+V+O+Q;return K>>>0}N.sum64_4_lo=f;function b(Y,G,Z,V,I,O,U,Q,K,L){var A=0,S=G;S=S+V>>>0,A+=S>>0,A+=S>>0,A+=S>>0,A+=S>>0}N.sum64_5_hi=b;function u(Y,G,Z,V,I,O,U,Q,K,L){var A=G+V+O+Q+L;return A>>>0}N.sum64_5_lo=u;function Y0(Y,G,Z){var V=G<<32-Z|Y>>>Z;return V>>>0}N.rotr64_hi=Y0;function p(Y,G,Z){var V=Y<<32-Z|G>>>Z;return V>>>0}N.rotr64_lo=p;function v0(Y,G,Z){return Y>>>Z}N.shr64_hi=v0;function $(Y,G,Z){var V=Y<<32-Z|G>>>Z;return V>>>0}N.shr64_lo=$}}),v$=S0({"node_modules/hash.js/lib/hash/common.js"(N){var _=T$(),j=H$();function k(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}N.BlockHash=k,k.prototype.update=function(F,P){if(F=_.toArray(F,P),this.pending?this.pending=this.pending.concat(F):this.pending=F,this.pendingTotal+=F.length,this.pending.length>=this._delta8){F=this.pending;var X=F.length%this._delta8;this.pending=F.slice(F.length-X,F.length),this.pending.length===0&&(this.pending=null),F=_.join32(F,0,F.length-X,this.endian);for(var C=0;C>>24&255,C[z++]=F>>>16&255,C[z++]=F>>>8&255,C[z++]=F&255}else for(C[z++]=F&255,C[z++]=F>>>8&255,C[z++]=F>>>16&255,C[z++]=F>>>24&255,C[z++]=0,C[z++]=0,C[z++]=0,C[z++]=0,T=8;T>>3}N.g0_256=T;function H(J){return j(J,17)^j(J,19)^J>>>10}N.g1_256=H}}),vY=S0({"node_modules/hash.js/lib/hash/sha/1.js"(N,_){var j=T$(),k=v$(),F=qQ(),P=j.rotl32,X=j.sum32,C=j.sum32_5,z=F.ft_1,T=k.BlockHash,H=[1518500249,1859775393,2400959708,3395469782];function J(){if(!(this instanceof J))return new J;T.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}j.inherits(J,T),_.exports=J,J.blockSize=512,J.outSize=160,J.hmacStrength=80,J.padLength=64,J.prototype._update=function(W,D){for(var E=this.W,R=0;R<16;R++)E[R]=W[D+R];for(;Rthis.blockSize&&(P=new this.Hash().update(P).digest()),k(P.length<=this.blockSize);for(var X=P.length;X=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(C,z,T)}_.exports=P,P.prototype._init=function(X,C,z){var T=X.concat(C).concat(z);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var H=0;H=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(X.concat(z||[])),this._reseed=1},P.prototype.generate=function(X,C,z,T){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof C!="string"&&(T=z,z=C,C=null),z&&(z=k.toArray(z,T||"hex"),this._update(z));for(var H=[];H.length"}}}),yY=S0({"node_modules/elliptic/lib/elliptic/ec/signature.js"(N,_){var j=D$(),k=E$(),F=k.assert;function P(H,J){if(H instanceof P)return H;this._importDER(H,J)||(F(H.r&&H.s,"Signature without r or s"),this.r=new j(H.r,16),this.s=new j(H.s,16),H.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=H.recoveryParam)}_.exports=P;function X(){this.place=0}function C(H,J){var W=H[J.place++];if(!(W&128))return W;var D=W&15;if(D===0||D>4)return!1;for(var E=0,R=0,M=J.place;R>>=0;return E<=127?!1:(J.place=M,E)}function z(H){for(var J=0,W=H.length-1;!H[J]&&!(H[J+1]&128)&&J>>3);for(H.push(W|128);--W;)H.push(J>>>(W<<3)&255);H.push(J)}P.prototype.toDER=function(H){var J=this.r.toArray(),W=this.s.toArray();for(J[0]&128&&(J=[0].concat(J)),W[0]&128&&(W=[0].concat(W)),J=z(J),W=z(W);!W[0]&&!(W[1]&128);)W=W.slice(1);var D=[2];T(D,J.length),D=D.concat(J),D.push(2),T(D,W.length);var E=D.concat(W),R=[48];return T(R,E.length),R=R.concat(E),k.encode(R,H)}}}),wY=S0({"node_modules/elliptic/lib/elliptic/ec/index.js"(N,_){var j=D$(),k=xY(),F=E$(),P=l$(),X=c$(),C=F.assert,z=BY(),T=yY();function H(J){if(!(this instanceof H))return new H(J);typeof J=="string"&&(C(Object.prototype.hasOwnProperty.call(P,J),"Unknown curve "+J),J=P[J]),J instanceof P.PresetCurve&&(J={curve:J}),this.curve=J.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=J.curve.g,this.g.precompute(J.curve.n.bitLength()+1),this.hash=J.hash||J.curve.hash}_.exports=H,H.prototype.keyPair=function(J){return new z(this,J)},H.prototype.keyFromPrivate=function(J,W){return z.fromPrivate(this,J,W)},H.prototype.keyFromPublic=function(J,W){return z.fromPublic(this,J,W)},H.prototype.genKeyPair=function(J){J||(J={});for(var W=new k({hash:this.hash,pers:J.pers,persEnc:J.persEnc||"utf8",entropy:J.entropy||X(this.hash.hmacStrength),entropyEnc:J.entropy&&J.entropyEnc||"utf8",nonce:this.n.toArray()}),D=this.n.byteLength(),E=this.n.sub(new j(2));;){var R=new j(W.generate(D));if(!(R.cmp(E)>0))return R.iaddn(1),this.keyFromPrivate(R)}},H.prototype._truncateToN=function(J,W){var D=J.byteLength()*8-this.n.bitLength();return D>0&&(J=J.ushrn(D)),!W&&J.cmp(this.n)>=0?J.sub(this.n):J},H.prototype.sign=function(J,W,D,E){typeof D=="object"&&(E=D,D=null),E||(E={}),W=this.keyFromPrivate(W,D),J=this._truncateToN(new j(J,16));for(var R=this.n.byteLength(),M=W.getPrivate().toArray("be",R),v=J.toArray("be",R),q=new k({hash:this.hash,entropy:M,nonce:v,pers:E.pers,persEnc:E.persEnc||"utf8"}),g=this.n.sub(new j(1)),B=0;;B++){var w=E.k?E.k(B):new j(q.generate(this.n.byteLength()));if(w=this._truncateToN(w,!0),!(w.cmpn(1)<=0||w.cmp(g)>=0)){var f=this.g.mul(w);if(!f.isInfinity()){var b=f.getX(),u=b.umod(this.n);if(u.cmpn(0)!==0){var Y0=w.invm(this.n).mul(u.mul(W.getPrivate()).iadd(J));if(Y0=Y0.umod(this.n),Y0.cmpn(0)!==0){var p=(f.getY().isOdd()?1:0)|(b.cmp(u)!==0?2:0);return E.canonical&&Y0.cmp(this.nh)>0&&(Y0=this.n.sub(Y0),p^=1),new T({r:u,s:Y0,recoveryParam:p})}}}}}},H.prototype.verify=function(J,W,D,E){J=this._truncateToN(new j(J,16)),D=this.keyFromPublic(D,E),W=new T(W,"hex");var{r:R,s:M}=W;if(R.cmpn(1)<0||R.cmp(this.n)>=0||M.cmpn(1)<0||M.cmp(this.n)>=0)return!1;var v=M.invm(this.n),q=v.mul(J).umod(this.n),g=v.mul(R).umod(this.n),B;return this.curve._maxwellTrick?(B=this.g.jmulAdd(q,D.getPublic(),g),B.isInfinity()?!1:B.eqXToP(R)):(B=this.g.mulAdd(q,D.getPublic(),g),B.isInfinity()?!1:B.getX().umod(this.n).cmp(R)===0)},H.prototype.recoverPubKey=function(J,W,D,E){C((3&D)===D,"The recovery param is more than two bits"),W=new T(W,E);var R=this.n,M=new j(J),v=W.r,q=W.s,g=D&1,B=D>>1;if(v.cmp(this.curve.p.umod(this.curve.n))>=0&&B)throw new Error("Unable to find sencond key candinate");B?v=this.curve.pointFromX(v.add(this.curve.n),g):v=this.curve.pointFromX(v,g);var w=W.r.invm(R),f=R.sub(M).mul(w).umod(R),b=q.mul(w).umod(R);return this.g.mulAdd(f,v,b)},H.prototype.getKeyRecoveryParam=function(J,W,D,E){if(W=new T(W,E),W.recoveryParam!==null)return W.recoveryParam;for(var R=0;R<4;R++){var M;try{M=this.recoverPubKey(J,W,R)}catch{continue}if(M.eq(D))return R}throw new Error("Unable to find valid recovery factor")}}}),pY=S0({"node_modules/elliptic/lib/elliptic/eddsa/key.js"(N,_){var j=E$(),k=j.assert,F=j.parseBytes,P=j.cachedProperty;function X(C,z){this.eddsa=C,this._secret=F(z.secret),C.isPoint(z.pub)?this._pub=z.pub:this._pubBytes=F(z.pub)}X.fromPublic=function(C,z){return z instanceof X?z:new X(C,{pub:z})},X.fromSecret=function(C,z){return z instanceof X?z:new X(C,{secret:z})},X.prototype.secret=function(){return this._secret},P(X,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())}),P(X,"pub",function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())}),P(X,"privBytes",function(){var C=this.eddsa,z=this.hash(),T=C.encodingLength-1,H=z.slice(0,C.encodingLength);return H[0]&=248,H[T]&=127,H[T]|=64,H}),P(X,"priv",function(){return this.eddsa.decodeInt(this.privBytes())}),P(X,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()}),P(X,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)}),X.prototype.sign=function(C){return k(this._secret,"KeyPair can only verify"),this.eddsa.sign(C,this)},X.prototype.verify=function(C,z){return this.eddsa.verify(C,z,this)},X.prototype.getSecret=function(C){return k(this._secret,"KeyPair is public only"),j.encode(this.secret(),C)},X.prototype.getPublic=function(C){return j.encode(this.pubBytes(),C)},_.exports=X}}),fY=S0({"node_modules/elliptic/lib/elliptic/eddsa/signature.js"(N,_){var j=D$(),k=E$(),F=k.assert,P=k.cachedProperty,X=k.parseBytes;function C(z,T){this.eddsa=z,typeof T!="object"&&(T=X(T)),Array.isArray(T)&&(T={R:T.slice(0,z.encodingLength),S:T.slice(z.encodingLength)}),F(T.R&&T.S,"Signature without R or S"),z.isPoint(T.R)&&(this._R=T.R),T.S instanceof j&&(this._S=T.S),this._Rencoded=Array.isArray(T.R)?T.R:T.Rencoded,this._Sencoded=Array.isArray(T.S)?T.S:T.Sencoded}P(C,"S",function(){return this.eddsa.decodeInt(this.Sencoded())}),P(C,"R",function(){return this.eddsa.decodePoint(this.Rencoded())}),P(C,"Rencoded",function(){return this.eddsa.encodePoint(this.R())}),P(C,"Sencoded",function(){return this.eddsa.encodeInt(this.S())}),C.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},C.prototype.toHex=function(){return k.encode(this.toBytes(),"hex").toUpperCase()},_.exports=C}}),cY=S0({"node_modules/elliptic/lib/elliptic/eddsa/index.js"(N,_){var j=b$(),k=l$(),F=E$(),P=F.assert,X=F.parseBytes,C=pY(),z=fY();function T(H){if(P(H==="ed25519","only tested with ed25519 so far"),!(this instanceof T))return new T(H);H=k[H].curve,this.curve=H,this.g=H.g,this.g.precompute(H.n.bitLength()+1),this.pointClass=H.point().constructor,this.encodingLength=Math.ceil(H.n.bitLength()/8),this.hash=j.sha512}_.exports=T,T.prototype.sign=function(H,J){H=X(H);var W=this.keyFromSecret(J),D=this.hashInt(W.messagePrefix(),H),E=this.g.mul(D),R=this.encodePoint(E),M=this.hashInt(R,W.pubBytes(),H).mul(W.priv()),v=D.add(M).umod(this.curve.n);return this.makeSignature({R:E,S:v,Rencoded:R})},T.prototype.verify=function(H,J,W){H=X(H),J=this.makeSignature(J);var D=this.keyFromPublic(W),E=this.hashInt(J.Rencoded(),D.pubBytes(),H),R=this.g.mul(J.S()),M=J.R().add(D.pub().mul(E));return M.eq(R)},T.prototype.hashInt=function(){for(var H=this.hash(),J=0;J0?$:Y},X.min=function($,Y){return $.cmp(Y)<0?$:Y},X.prototype._init=function($,Y,G){if(typeof $=="number")return this._initNumber($,Y,G);if(typeof $=="object")return this._initArray($,Y,G);Y==="hex"&&(Y=16),F(Y===(Y|0)&&Y>=2&&Y<=36),$=$.toString().replace(/\s+/g,"");var Z=0;$[0]==="-"&&(Z++,this.negative=1),Z<$.length&&(Y===16?this._parseHex($,Z,G):(this._parseBase($,Y,Z),G==="le"&&this._initArray(this.toArray(),Y,G)))},X.prototype._initNumber=function($,Y,G){$<0&&(this.negative=1,$=-$),$<67108864?(this.words=[$&67108863],this.length=1):$<4503599627370496?(this.words=[$&67108863,$/67108864&67108863],this.length=2):(F($<9007199254740992),this.words=[$&67108863,$/67108864&67108863,1],this.length=3),G==="le"&&this._initArray(this.toArray(),Y,G)},X.prototype._initArray=function($,Y,G){if(F(typeof $.length=="number"),$.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil($.length/3),this.words=new Array(this.length);for(var Z=0;Z=0;Z-=3)I=$[Z]|$[Z-1]<<8|$[Z-2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);else if(G==="le")for(Z=0,V=0;Z<$.length;Z+=3)I=$[Z]|$[Z+1]<<8|$[Z+2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);return this.strip()};function z($,Y){var G=$.charCodeAt(Y);return G>=65&&G<=70?G-55:G>=97&&G<=102?G-87:G-48&15}function T($,Y,G){var Z=z($,G);return G-1>=Y&&(Z|=z($,G-1)<<4),Z}X.prototype._parseHex=function($,Y,G){this.length=Math.ceil(($.length-Y)/6),this.words=new Array(this.length);for(var Z=0;Z=Y;Z-=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8;else{var U=$.length-Y;for(Z=U%2===0?Y+1:Y;Z<$.length;Z+=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8}this.strip()};function H($,Y,G,Z){for(var V=0,I=Math.min($.length,G),O=Y;O=49?V+=U-49+10:U>=17?V+=U-17+10:V+=U}return V}X.prototype._parseBase=function($,Y,G){this.words=[0],this.length=1;for(var Z=0,V=1;V<=67108863;V*=Y)Z++;Z--,V=V/Y|0;for(var I=$.length-G,O=I%Z,U=Math.min(I,I-O)+G,Q=0,K=G;K1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},X.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},X.prototype.inspect=function(){return(this.red?""};var J=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],W=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],D=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];X.prototype.toString=function($,Y){$=$||10,Y=Y|0||1;var G;if($===16||$==="hex"){G="";for(var Z=0,V=0,I=0;I>>24-Z&16777215,V!==0||I!==this.length-1?G=J[6-U.length]+U+G:G=U+G,Z+=2,Z>=26&&(Z-=26,I--)}for(V!==0&&(G=V.toString(16)+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}if($===($|0)&&$>=2&&$<=36){var Q=W[$],K=D[$];G="";var L=this.clone();for(L.negative=0;!L.isZero();){var A=L.modn(K).toString($);L=L.idivn(K),L.isZero()?G=A+G:G=J[Q-A.length]+A+G}for(this.isZero()&&(G="0"+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}F(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var $=this.words[0];return this.length===2?$+=this.words[1]*67108864:this.length===3&&this.words[2]===1?$+=4503599627370496+this.words[1]*67108864:this.length>2&&F(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-$:$},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function($,Y){return F(typeof C<"u"),this.toArrayLike(C,$,Y)},X.prototype.toArray=function($,Y){return this.toArrayLike(Array,$,Y)},X.prototype.toArrayLike=function($,Y,G){var Z=this.byteLength(),V=G||Math.max(1,Z);F(Z<=V,"byte array longer than desired length"),F(V>0,"Requested array length <= 0"),this.strip();var I=Y==="le",O=new $(V),U,Q,K=this.clone();if(I){for(Q=0;!K.isZero();Q++)U=K.andln(255),K.iushrn(8),O[Q]=U;for(;Q=4096&&(G+=13,Y>>>=13),Y>=64&&(G+=7,Y>>>=7),Y>=8&&(G+=4,Y>>>=4),Y>=2&&(G+=2,Y>>>=2),G+Y},X.prototype._zeroBits=function($){if($===0)return 26;var Y=$,G=0;return(Y&8191)===0&&(G+=13,Y>>>=13),(Y&127)===0&&(G+=7,Y>>>=7),(Y&15)===0&&(G+=4,Y>>>=4),(Y&3)===0&&(G+=2,Y>>>=2),(Y&1)===0&&G++,G},X.prototype.bitLength=function(){var $=this.words[this.length-1],Y=this._countBits($);return(this.length-1)*26+Y};function E($){for(var Y=new Array($.bitLength()),G=0;G>>V}return Y}X.prototype.zeroBits=function(){if(this.isZero())return 0;for(var $=0,Y=0;Y$.length?this.clone().ior($):$.clone().ior(this)},X.prototype.uor=function($){return this.length>$.length?this.clone().iuor($):$.clone().iuor(this)},X.prototype.iuand=function($){var Y;this.length>$.length?Y=$:Y=this;for(var G=0;G$.length?this.clone().iand($):$.clone().iand(this)},X.prototype.uand=function($){return this.length>$.length?this.clone().iuand($):$.clone().iuand(this)},X.prototype.iuxor=function($){var Y,G;this.length>$.length?(Y=this,G=$):(Y=$,G=this);for(var Z=0;Z$.length?this.clone().ixor($):$.clone().ixor(this)},X.prototype.uxor=function($){return this.length>$.length?this.clone().iuxor($):$.clone().iuxor(this)},X.prototype.inotn=function($){F(typeof $=="number"&&$>=0);var Y=Math.ceil($/26)|0,G=$%26;this._expand(Y),G>0&&Y--;for(var Z=0;Z0&&(this.words[Z]=~this.words[Z]&67108863>>26-G),this.strip()},X.prototype.notn=function($){return this.clone().inotn($)},X.prototype.setn=function($,Y){F(typeof $=="number"&&$>=0);var G=$/26|0,Z=$%26;return this._expand(G+1),Y?this.words[G]=this.words[G]|1<$.length?(G=this,Z=$):(G=$,Z=this);for(var V=0,I=0;I>>26;for(;V!==0&&I>>26;if(this.length=G.length,V!==0)this.words[this.length]=V,this.length++;else if(G!==this)for(;I$.length?this.clone().iadd($):$.clone().iadd(this)},X.prototype.isub=function($){if($.negative!==0){$.negative=0;var Y=this.iadd($);return $.negative=1,Y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd($),this.negative=1,this._normSign();var G=this.cmp($);if(G===0)return this.negative=0,this.length=1,this.words[0]=0,this;var Z,V;G>0?(Z=this,V=$):(Z=$,V=this);for(var I=0,O=0;O>26,this.words[O]=Y&67108863;for(;I!==0&&O>26,this.words[O]=Y&67108863;if(I===0&&O>>26,A=Q&67108863,S=Math.min(K,Y.length-1),x=Math.max(0,K-$.length+1);x<=S;x++){var y=K-x|0;V=$.words[y]|0,I=Y.words[x]|0,O=V*I+A,L+=O/67108864|0,A=O&67108863}G.words[K]=A|0,Q=L|0}return Q!==0?G.words[K]=Q|0:G.length--,G.strip()}var M=function($,Y,G){var Z=$.words,V=Y.words,I=G.words,O=0,U,Q,K,L=Z[0]|0,A=L&8191,S=L>>>13,x=Z[1]|0,y=x&8191,c=x>>>13,q0=Z[2]|0,h=q0&8191,d=q0>>>13,_0=Z[3]|0,l=_0&8191,n=_0>>>13,y0=Z[4]|0,t=y0&8191,s=y0>>>13,w0=Z[5]|0,m=w0&8191,r=w0>>>13,$$=Z[6]|0,i=$$&8191,e=$$>>>13,x0=Z[7]|0,o=x0&8191,a=x0>>>13,p0=Z[8]|0,$0=p0&8191,Q0=p0>>>13,Y$=Z[9]|0,Z0=Y$&8191,G0=Y$>>>13,Z$=V[0]|0,V0=Z$&8191,U0=Z$>>>13,G$=V[1]|0,X0=G$&8191,K0=G$>>>13,V$=V[2]|0,I0=V$&8191,O0=V$>>>13,U$=V[3]|0,J0=U$&8191,F0=U$>>>13,X$=V[4]|0,A0=X$&8191,W0=X$>>>13,K$=V[5]|0,H0=K$&8191,E0=K$>>>13,I$=V[6]|0,T0=I$&8191,D0=I$>>>13,O$=V[7]|0,C0=O$&8191,L0=O$>>>13,J$=V[8]|0,R0=J$&8191,z0=J$>>>13,F$=V[9]|0,P0=F$&8191,M0=F$>>>13;G.negative=$.negative^Y.negative,G.length=19,U=Math.imul(A,V0),Q=Math.imul(A,U0),Q=Q+Math.imul(S,V0)|0,K=Math.imul(S,U0);var Q$=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(Q$>>>26)|0,Q$&=67108863,U=Math.imul(y,V0),Q=Math.imul(y,U0),Q=Q+Math.imul(c,V0)|0,K=Math.imul(c,U0),U=U+Math.imul(A,X0)|0,Q=Q+Math.imul(A,K0)|0,Q=Q+Math.imul(S,X0)|0,K=K+Math.imul(S,K0)|0;var k0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(k0>>>26)|0,k0&=67108863,U=Math.imul(h,V0),Q=Math.imul(h,U0),Q=Q+Math.imul(d,V0)|0,K=Math.imul(d,U0),U=U+Math.imul(y,X0)|0,Q=Q+Math.imul(y,K0)|0,Q=Q+Math.imul(c,X0)|0,K=K+Math.imul(c,K0)|0,U=U+Math.imul(A,I0)|0,Q=Q+Math.imul(A,O0)|0,Q=Q+Math.imul(S,I0)|0,K=K+Math.imul(S,O0)|0;var g0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(g0>>>26)|0,g0&=67108863,U=Math.imul(l,V0),Q=Math.imul(l,U0),Q=Q+Math.imul(n,V0)|0,K=Math.imul(n,U0),U=U+Math.imul(h,X0)|0,Q=Q+Math.imul(h,K0)|0,Q=Q+Math.imul(d,X0)|0,K=K+Math.imul(d,K0)|0,U=U+Math.imul(y,I0)|0,Q=Q+Math.imul(y,O0)|0,Q=Q+Math.imul(c,I0)|0,K=K+Math.imul(c,O0)|0,U=U+Math.imul(A,J0)|0,Q=Q+Math.imul(A,F0)|0,Q=Q+Math.imul(S,J0)|0,K=K+Math.imul(S,F0)|0;var f0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(f0>>>26)|0,f0&=67108863,U=Math.imul(t,V0),Q=Math.imul(t,U0),Q=Q+Math.imul(s,V0)|0,K=Math.imul(s,U0),U=U+Math.imul(l,X0)|0,Q=Q+Math.imul(l,K0)|0,Q=Q+Math.imul(n,X0)|0,K=K+Math.imul(n,K0)|0,U=U+Math.imul(h,I0)|0,Q=Q+Math.imul(h,O0)|0,Q=Q+Math.imul(d,I0)|0,K=K+Math.imul(d,O0)|0,U=U+Math.imul(y,J0)|0,Q=Q+Math.imul(y,F0)|0,Q=Q+Math.imul(c,J0)|0,K=K+Math.imul(c,F0)|0,U=U+Math.imul(A,A0)|0,Q=Q+Math.imul(A,W0)|0,Q=Q+Math.imul(S,A0)|0,K=K+Math.imul(S,W0)|0;var c0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(c0>>>26)|0,c0&=67108863,U=Math.imul(m,V0),Q=Math.imul(m,U0),Q=Q+Math.imul(r,V0)|0,K=Math.imul(r,U0),U=U+Math.imul(t,X0)|0,Q=Q+Math.imul(t,K0)|0,Q=Q+Math.imul(s,X0)|0,K=K+Math.imul(s,K0)|0,U=U+Math.imul(l,I0)|0,Q=Q+Math.imul(l,O0)|0,Q=Q+Math.imul(n,I0)|0,K=K+Math.imul(n,O0)|0,U=U+Math.imul(h,J0)|0,Q=Q+Math.imul(h,F0)|0,Q=Q+Math.imul(d,J0)|0,K=K+Math.imul(d,F0)|0,U=U+Math.imul(y,A0)|0,Q=Q+Math.imul(y,W0)|0,Q=Q+Math.imul(c,A0)|0,K=K+Math.imul(c,W0)|0,U=U+Math.imul(A,H0)|0,Q=Q+Math.imul(A,E0)|0,Q=Q+Math.imul(S,H0)|0,K=K+Math.imul(S,E0)|0;var h0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(h0>>>26)|0,h0&=67108863,U=Math.imul(i,V0),Q=Math.imul(i,U0),Q=Q+Math.imul(e,V0)|0,K=Math.imul(e,U0),U=U+Math.imul(m,X0)|0,Q=Q+Math.imul(m,K0)|0,Q=Q+Math.imul(r,X0)|0,K=K+Math.imul(r,K0)|0,U=U+Math.imul(t,I0)|0,Q=Q+Math.imul(t,O0)|0,Q=Q+Math.imul(s,I0)|0,K=K+Math.imul(s,O0)|0,U=U+Math.imul(l,J0)|0,Q=Q+Math.imul(l,F0)|0,Q=Q+Math.imul(n,J0)|0,K=K+Math.imul(n,F0)|0,U=U+Math.imul(h,A0)|0,Q=Q+Math.imul(h,W0)|0,Q=Q+Math.imul(d,A0)|0,K=K+Math.imul(d,W0)|0,U=U+Math.imul(y,H0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(c,H0)|0,K=K+Math.imul(c,E0)|0,U=U+Math.imul(A,T0)|0,Q=Q+Math.imul(A,D0)|0,Q=Q+Math.imul(S,T0)|0,K=K+Math.imul(S,D0)|0;var d0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(d0>>>26)|0,d0&=67108863,U=Math.imul(o,V0),Q=Math.imul(o,U0),Q=Q+Math.imul(a,V0)|0,K=Math.imul(a,U0),U=U+Math.imul(i,X0)|0,Q=Q+Math.imul(i,K0)|0,Q=Q+Math.imul(e,X0)|0,K=K+Math.imul(e,K0)|0,U=U+Math.imul(m,I0)|0,Q=Q+Math.imul(m,O0)|0,Q=Q+Math.imul(r,I0)|0,K=K+Math.imul(r,O0)|0,U=U+Math.imul(t,J0)|0,Q=Q+Math.imul(t,F0)|0,Q=Q+Math.imul(s,J0)|0,K=K+Math.imul(s,F0)|0,U=U+Math.imul(l,A0)|0,Q=Q+Math.imul(l,W0)|0,Q=Q+Math.imul(n,A0)|0,K=K+Math.imul(n,W0)|0,U=U+Math.imul(h,H0)|0,Q=Q+Math.imul(h,E0)|0,Q=Q+Math.imul(d,H0)|0,K=K+Math.imul(d,E0)|0,U=U+Math.imul(y,T0)|0,Q=Q+Math.imul(y,D0)|0,Q=Q+Math.imul(c,T0)|0,K=K+Math.imul(c,D0)|0,U=U+Math.imul(A,C0)|0,Q=Q+Math.imul(A,L0)|0,Q=Q+Math.imul(S,C0)|0,K=K+Math.imul(S,L0)|0;var b0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(b0>>>26)|0,b0&=67108863,U=Math.imul($0,V0),Q=Math.imul($0,U0),Q=Q+Math.imul(Q0,V0)|0,K=Math.imul(Q0,U0),U=U+Math.imul(o,X0)|0,Q=Q+Math.imul(o,K0)|0,Q=Q+Math.imul(a,X0)|0,K=K+Math.imul(a,K0)|0,U=U+Math.imul(i,I0)|0,Q=Q+Math.imul(i,O0)|0,Q=Q+Math.imul(e,I0)|0,K=K+Math.imul(e,O0)|0,U=U+Math.imul(m,J0)|0,Q=Q+Math.imul(m,F0)|0,Q=Q+Math.imul(r,J0)|0,K=K+Math.imul(r,F0)|0,U=U+Math.imul(t,A0)|0,Q=Q+Math.imul(t,W0)|0,Q=Q+Math.imul(s,A0)|0,K=K+Math.imul(s,W0)|0,U=U+Math.imul(l,H0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(n,H0)|0,K=K+Math.imul(n,E0)|0,U=U+Math.imul(h,T0)|0,Q=Q+Math.imul(h,D0)|0,Q=Q+Math.imul(d,T0)|0,K=K+Math.imul(d,D0)|0,U=U+Math.imul(y,C0)|0,Q=Q+Math.imul(y,L0)|0,Q=Q+Math.imul(c,C0)|0,K=K+Math.imul(c,L0)|0,U=U+Math.imul(A,R0)|0,Q=Q+Math.imul(A,z0)|0,Q=Q+Math.imul(S,R0)|0,K=K+Math.imul(S,z0)|0;var l0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(l0>>>26)|0,l0&=67108863,U=Math.imul(Z0,V0),Q=Math.imul(Z0,U0),Q=Q+Math.imul(G0,V0)|0,K=Math.imul(G0,U0),U=U+Math.imul($0,X0)|0,Q=Q+Math.imul($0,K0)|0,Q=Q+Math.imul(Q0,X0)|0,K=K+Math.imul(Q0,K0)|0,U=U+Math.imul(o,I0)|0,Q=Q+Math.imul(o,O0)|0,Q=Q+Math.imul(a,I0)|0,K=K+Math.imul(a,O0)|0,U=U+Math.imul(i,J0)|0,Q=Q+Math.imul(i,F0)|0,Q=Q+Math.imul(e,J0)|0,K=K+Math.imul(e,F0)|0,U=U+Math.imul(m,A0)|0,Q=Q+Math.imul(m,W0)|0,Q=Q+Math.imul(r,A0)|0,K=K+Math.imul(r,W0)|0,U=U+Math.imul(t,H0)|0,Q=Q+Math.imul(t,E0)|0,Q=Q+Math.imul(s,H0)|0,K=K+Math.imul(s,E0)|0,U=U+Math.imul(l,T0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(n,T0)|0,K=K+Math.imul(n,D0)|0,U=U+Math.imul(h,C0)|0,Q=Q+Math.imul(h,L0)|0,Q=Q+Math.imul(d,C0)|0,K=K+Math.imul(d,L0)|0,U=U+Math.imul(y,R0)|0,Q=Q+Math.imul(y,z0)|0,Q=Q+Math.imul(c,R0)|0,K=K+Math.imul(c,z0)|0,U=U+Math.imul(A,P0)|0,Q=Q+Math.imul(A,M0)|0,Q=Q+Math.imul(S,P0)|0,K=K+Math.imul(S,M0)|0;var o0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(o0>>>26)|0,o0&=67108863,U=Math.imul(Z0,X0),Q=Math.imul(Z0,K0),Q=Q+Math.imul(G0,X0)|0,K=Math.imul(G0,K0),U=U+Math.imul($0,I0)|0,Q=Q+Math.imul($0,O0)|0,Q=Q+Math.imul(Q0,I0)|0,K=K+Math.imul(Q0,O0)|0,U=U+Math.imul(o,J0)|0,Q=Q+Math.imul(o,F0)|0,Q=Q+Math.imul(a,J0)|0,K=K+Math.imul(a,F0)|0,U=U+Math.imul(i,A0)|0,Q=Q+Math.imul(i,W0)|0,Q=Q+Math.imul(e,A0)|0,K=K+Math.imul(e,W0)|0,U=U+Math.imul(m,H0)|0,Q=Q+Math.imul(m,E0)|0,Q=Q+Math.imul(r,H0)|0,K=K+Math.imul(r,E0)|0,U=U+Math.imul(t,T0)|0,Q=Q+Math.imul(t,D0)|0,Q=Q+Math.imul(s,T0)|0,K=K+Math.imul(s,D0)|0,U=U+Math.imul(l,C0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(n,C0)|0,K=K+Math.imul(n,L0)|0,U=U+Math.imul(h,R0)|0,Q=Q+Math.imul(h,z0)|0,Q=Q+Math.imul(d,R0)|0,K=K+Math.imul(d,z0)|0,U=U+Math.imul(y,P0)|0,Q=Q+Math.imul(y,M0)|0,Q=Q+Math.imul(c,P0)|0,K=K+Math.imul(c,M0)|0;var u0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(u0>>>26)|0,u0&=67108863,U=Math.imul(Z0,I0),Q=Math.imul(Z0,O0),Q=Q+Math.imul(G0,I0)|0,K=Math.imul(G0,O0),U=U+Math.imul($0,J0)|0,Q=Q+Math.imul($0,F0)|0,Q=Q+Math.imul(Q0,J0)|0,K=K+Math.imul(Q0,F0)|0,U=U+Math.imul(o,A0)|0,Q=Q+Math.imul(o,W0)|0,Q=Q+Math.imul(a,A0)|0,K=K+Math.imul(a,W0)|0,U=U+Math.imul(i,H0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,H0)|0,K=K+Math.imul(e,E0)|0,U=U+Math.imul(m,T0)|0,Q=Q+Math.imul(m,D0)|0,Q=Q+Math.imul(r,T0)|0,K=K+Math.imul(r,D0)|0,U=U+Math.imul(t,C0)|0,Q=Q+Math.imul(t,L0)|0,Q=Q+Math.imul(s,C0)|0,K=K+Math.imul(s,L0)|0,U=U+Math.imul(l,R0)|0,Q=Q+Math.imul(l,z0)|0,Q=Q+Math.imul(n,R0)|0,K=K+Math.imul(n,z0)|0,U=U+Math.imul(h,P0)|0,Q=Q+Math.imul(h,M0)|0,Q=Q+Math.imul(d,P0)|0,K=K+Math.imul(d,M0)|0;var n0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(n0>>>26)|0,n0&=67108863,U=Math.imul(Z0,J0),Q=Math.imul(Z0,F0),Q=Q+Math.imul(G0,J0)|0,K=Math.imul(G0,F0),U=U+Math.imul($0,A0)|0,Q=Q+Math.imul($0,W0)|0,Q=Q+Math.imul(Q0,A0)|0,K=K+Math.imul(Q0,W0)|0,U=U+Math.imul(o,H0)|0,Q=Q+Math.imul(o,E0)|0,Q=Q+Math.imul(a,H0)|0,K=K+Math.imul(a,E0)|0,U=U+Math.imul(i,T0)|0,Q=Q+Math.imul(i,D0)|0,Q=Q+Math.imul(e,T0)|0,K=K+Math.imul(e,D0)|0,U=U+Math.imul(m,C0)|0,Q=Q+Math.imul(m,L0)|0,Q=Q+Math.imul(r,C0)|0,K=K+Math.imul(r,L0)|0,U=U+Math.imul(t,R0)|0,Q=Q+Math.imul(t,z0)|0,Q=Q+Math.imul(s,R0)|0,K=K+Math.imul(s,z0)|0,U=U+Math.imul(l,P0)|0,Q=Q+Math.imul(l,M0)|0,Q=Q+Math.imul(n,P0)|0,K=K+Math.imul(n,M0)|0;var s0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(s0>>>26)|0,s0&=67108863,U=Math.imul(Z0,A0),Q=Math.imul(Z0,W0),Q=Q+Math.imul(G0,A0)|0,K=Math.imul(G0,W0),U=U+Math.imul($0,H0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Q0,H0)|0,K=K+Math.imul(Q0,E0)|0,U=U+Math.imul(o,T0)|0,Q=Q+Math.imul(o,D0)|0,Q=Q+Math.imul(a,T0)|0,K=K+Math.imul(a,D0)|0,U=U+Math.imul(i,C0)|0,Q=Q+Math.imul(i,L0)|0,Q=Q+Math.imul(e,C0)|0,K=K+Math.imul(e,L0)|0,U=U+Math.imul(m,R0)|0,Q=Q+Math.imul(m,z0)|0,Q=Q+Math.imul(r,R0)|0,K=K+Math.imul(r,z0)|0,U=U+Math.imul(t,P0)|0,Q=Q+Math.imul(t,M0)|0,Q=Q+Math.imul(s,P0)|0,K=K+Math.imul(s,M0)|0;var t0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(t0>>>26)|0,t0&=67108863,U=Math.imul(Z0,H0),Q=Math.imul(Z0,E0),Q=Q+Math.imul(G0,H0)|0,K=Math.imul(G0,E0),U=U+Math.imul($0,T0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Q0,T0)|0,K=K+Math.imul(Q0,D0)|0,U=U+Math.imul(o,C0)|0,Q=Q+Math.imul(o,L0)|0,Q=Q+Math.imul(a,C0)|0,K=K+Math.imul(a,L0)|0,U=U+Math.imul(i,R0)|0,Q=Q+Math.imul(i,z0)|0,Q=Q+Math.imul(e,R0)|0,K=K+Math.imul(e,z0)|0,U=U+Math.imul(m,P0)|0,Q=Q+Math.imul(m,M0)|0,Q=Q+Math.imul(r,P0)|0,K=K+Math.imul(r,M0)|0;var m0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(m0>>>26)|0,m0&=67108863,U=Math.imul(Z0,T0),Q=Math.imul(Z0,D0),Q=Q+Math.imul(G0,T0)|0,K=Math.imul(G0,D0),U=U+Math.imul($0,C0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Q0,C0)|0,K=K+Math.imul(Q0,L0)|0,U=U+Math.imul(o,R0)|0,Q=Q+Math.imul(o,z0)|0,Q=Q+Math.imul(a,R0)|0,K=K+Math.imul(a,z0)|0,U=U+Math.imul(i,P0)|0,Q=Q+Math.imul(i,M0)|0,Q=Q+Math.imul(e,P0)|0,K=K+Math.imul(e,M0)|0;var a0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(a0>>>26)|0,a0&=67108863,U=Math.imul(Z0,C0),Q=Math.imul(Z0,L0),Q=Q+Math.imul(G0,C0)|0,K=Math.imul(G0,L0),U=U+Math.imul($0,R0)|0,Q=Q+Math.imul($0,z0)|0,Q=Q+Math.imul(Q0,R0)|0,K=K+Math.imul(Q0,z0)|0,U=U+Math.imul(o,P0)|0,Q=Q+Math.imul(o,M0)|0,Q=Q+Math.imul(a,P0)|0,K=K+Math.imul(a,M0)|0;var e0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(e0>>>26)|0,e0&=67108863,U=Math.imul(Z0,R0),Q=Math.imul(Z0,z0),Q=Q+Math.imul(G0,R0)|0,K=Math.imul(G0,z0),U=U+Math.imul($0,P0)|0,Q=Q+Math.imul($0,M0)|0,Q=Q+Math.imul(Q0,P0)|0,K=K+Math.imul(Q0,M0)|0;var r0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(r0>>>26)|0,r0&=67108863,U=Math.imul(Z0,P0),Q=Math.imul(Z0,M0),Q=Q+Math.imul(G0,P0)|0,K=Math.imul(G0,M0);var i0=(O+U|0)+((Q&8191)<<13)|0;return O=(K+(Q>>>13)|0)+(i0>>>26)|0,i0&=67108863,I[0]=Q$,I[1]=k0,I[2]=g0,I[3]=f0,I[4]=c0,I[5]=h0,I[6]=d0,I[7]=b0,I[8]=l0,I[9]=o0,I[10]=u0,I[11]=n0,I[12]=s0,I[13]=t0,I[14]=m0,I[15]=a0,I[16]=e0,I[17]=r0,I[18]=i0,O!==0&&(I[19]=O,G.length++),G};Math.imul||(M=R);function v($,Y,G){G.negative=Y.negative^$.negative,G.length=$.length+Y.length;for(var Z=0,V=0,I=0;I>>26)|0,V+=O>>>26,O&=67108863}G.words[I]=U,Z=O,O=V}return Z!==0?G.words[I]=Z:G.length--,G.strip()}function q($,Y,G){var Z=new g;return Z.mulp($,Y,G)}X.prototype.mulTo=function($,Y){var G,Z=this.length+$.length;return this.length===10&&$.length===10?G=M(this,$,Y):Z<63?G=R(this,$,Y):Z<1024?G=v(this,$,Y):G=q(this,$,Y),G};function g($,Y){this.x=$,this.y=Y}g.prototype.makeRBT=function($){for(var Y=new Array($),G=X.prototype._countBits($)-1,Z=0;Z<$;Z++)Y[Z]=this.revBin(Z,G,$);return Y},g.prototype.revBin=function($,Y,G){if($===0||$===G-1)return $;for(var Z=0,V=0;V>=1;return Z},g.prototype.permute=function($,Y,G,Z,V,I){for(var O=0;O>>1)V++;return 1<>>13,G[2*I+1]=V&8191,V=V>>>13;for(I=2*Y;I>=26,Y+=Z/67108864|0,Y+=V>>>26,this.words[G]=V&67108863}return Y!==0&&(this.words[G]=Y,this.length++),this},X.prototype.muln=function($){return this.clone().imuln($)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function($){var Y=E($);if(Y.length===0)return new X(1);for(var G=this,Z=0;Z=0);var Y=$%26,G=($-Y)/26,Z=67108863>>>26-Y<<26-Y,V;if(Y!==0){var I=0;for(V=0;V>>26-Y}I&&(this.words[V]=I,this.length++)}if(G!==0){for(V=this.length-1;V>=0;V--)this.words[V+G]=this.words[V];for(V=0;V=0);var Z;Y?Z=(Y-Y%26)/26:Z=0;var V=$%26,I=Math.min(($-V)/26,this.length),O=67108863^67108863>>>V<I)for(this.length-=I,Q=0;Q=0&&(K!==0||Q>=Z);Q--){var L=this.words[Q]|0;this.words[Q]=K<<26-V|L>>>V,K=L&O}return U&&K!==0&&(U.words[U.length++]=K),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},X.prototype.ishrn=function($,Y,G){return F(this.negative===0),this.iushrn($,Y,G)},X.prototype.shln=function($){return this.clone().ishln($)},X.prototype.ushln=function($){return this.clone().iushln($)},X.prototype.shrn=function($){return this.clone().ishrn($)},X.prototype.ushrn=function($){return this.clone().iushrn($)},X.prototype.testn=function($){F(typeof $=="number"&&$>=0);var Y=$%26,G=($-Y)/26,Z=1<=0);var Y=$%26,G=($-Y)/26;if(F(this.negative===0,"imaskn works only with positive numbers"),this.length<=G)return this;if(Y!==0&&G++,this.length=Math.min(G,this.length),Y!==0){var Z=67108863^67108863>>>Y<=67108864;Y++)this.words[Y]-=67108864,Y===this.length-1?this.words[Y+1]=1:this.words[Y+1]++;return this.length=Math.max(this.length,Y+1),this},X.prototype.isubn=function($){if(F(typeof $=="number"),F($<67108864),$<0)return this.iaddn(-$);if(this.negative!==0)return this.negative=0,this.iaddn($),this.negative=1,this;if(this.words[0]-=$,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Y=0;Y>26)-(U/67108864|0),this.words[V+G]=I&67108863}for(;V>26,this.words[V+G]=I&67108863;if(O===0)return this.strip();for(F(O===-1),O=0,V=0;V>26,this.words[V]=I&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function($,Y){var G=this.length-$.length,Z=this.clone(),V=$,I=V.words[V.length-1]|0,O=this._countBits(I);G=26-O,G!==0&&(V=V.ushln(G),Z.iushln(G),I=V.words[V.length-1]|0);var U=Z.length-V.length,Q;if(Y!=="mod"){Q=new X(null),Q.length=U+1,Q.words=new Array(Q.length);for(var K=0;K=0;A--){var S=(Z.words[V.length+A]|0)*67108864+(Z.words[V.length+A-1]|0);for(S=Math.min(S/I|0,67108863),Z._ishlnsubmul(V,S,A);Z.negative!==0;)S--,Z.negative=0,Z._ishlnsubmul(V,1,A),Z.isZero()||(Z.negative^=1);Q&&(Q.words[A]=S)}return Q&&Q.strip(),Z.strip(),Y!=="div"&&G!==0&&Z.iushrn(G),{div:Q||null,mod:Z}},X.prototype.divmod=function($,Y,G){if(F(!$.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var Z,V,I;return this.negative!==0&&$.negative===0?(I=this.neg().divmod($,Y),Y!=="mod"&&(Z=I.div.neg()),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.iadd($)),{div:Z,mod:V}):this.negative===0&&$.negative!==0?(I=this.divmod($.neg(),Y),Y!=="mod"&&(Z=I.div.neg()),{div:Z,mod:I.mod}):(this.negative&$.negative)!==0?(I=this.neg().divmod($.neg(),Y),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.isub($)),{div:I.div,mod:V}):$.length>this.length||this.cmp($)<0?{div:new X(0),mod:this}:$.length===1?Y==="div"?{div:this.divn($.words[0]),mod:null}:Y==="mod"?{div:null,mod:new X(this.modn($.words[0]))}:{div:this.divn($.words[0]),mod:new X(this.modn($.words[0]))}:this._wordDiv($,Y)},X.prototype.div=function($){return this.divmod($,"div",!1).div},X.prototype.mod=function($){return this.divmod($,"mod",!1).mod},X.prototype.umod=function($){return this.divmod($,"mod",!0).mod},X.prototype.divRound=function($){var Y=this.divmod($);if(Y.mod.isZero())return Y.div;var G=Y.div.negative!==0?Y.mod.isub($):Y.mod,Z=$.ushrn(1),V=$.andln(1),I=G.cmp(Z);return I<0||V===1&&I===0?Y.div:Y.div.negative!==0?Y.div.isubn(1):Y.div.iaddn(1)},X.prototype.modn=function($){F($<=67108863);for(var Y=(1<<26)%$,G=0,Z=this.length-1;Z>=0;Z--)G=(Y*G+(this.words[Z]|0))%$;return G},X.prototype.idivn=function($){F($<=67108863);for(var Y=0,G=this.length-1;G>=0;G--){var Z=(this.words[G]|0)+Y*67108864;this.words[G]=Z/$|0,Y=Z%$}return this.strip()},X.prototype.divn=function($){return this.clone().idivn($)},X.prototype.egcd=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=new X(0),O=new X(1),U=0;Y.isEven()&&G.isEven();)Y.iushrn(1),G.iushrn(1),++U;for(var Q=G.clone(),K=Y.clone();!Y.isZero();){for(var L=0,A=1;(Y.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0)for(Y.iushrn(L);L-- >0;)(Z.isOdd()||V.isOdd())&&(Z.iadd(Q),V.isub(K)),Z.iushrn(1),V.iushrn(1);for(var S=0,x=1;(G.words[0]&x)===0&&S<26;++S,x<<=1);if(S>0)for(G.iushrn(S);S-- >0;)(I.isOdd()||O.isOdd())&&(I.iadd(Q),O.isub(K)),I.iushrn(1),O.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(I),V.isub(O)):(G.isub(Y),I.isub(Z),O.isub(V))}return{a:I,b:O,gcd:G.iushln(U)}},X.prototype._invmp=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=G.clone();Y.cmpn(1)>0&&G.cmpn(1)>0;){for(var O=0,U=1;(Y.words[0]&U)===0&&O<26;++O,U<<=1);if(O>0)for(Y.iushrn(O);O-- >0;)Z.isOdd()&&Z.iadd(I),Z.iushrn(1);for(var Q=0,K=1;(G.words[0]&K)===0&&Q<26;++Q,K<<=1);if(Q>0)for(G.iushrn(Q);Q-- >0;)V.isOdd()&&V.iadd(I),V.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(V)):(G.isub(Y),V.isub(Z))}var L;return Y.cmpn(1)===0?L=Z:L=V,L.cmpn(0)<0&&L.iadd($),L},X.prototype.gcd=function($){if(this.isZero())return $.abs();if($.isZero())return this.abs();var Y=this.clone(),G=$.clone();Y.negative=0,G.negative=0;for(var Z=0;Y.isEven()&&G.isEven();Z++)Y.iushrn(1),G.iushrn(1);do{for(;Y.isEven();)Y.iushrn(1);for(;G.isEven();)G.iushrn(1);var V=Y.cmp(G);if(V<0){var I=Y;Y=G,G=I}else if(V===0||G.cmpn(1)===0)break;Y.isub(G)}while(!0);return G.iushln(Z)},X.prototype.invm=function($){return this.egcd($).a.umod($)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function($){return this.words[0]&$},X.prototype.bincn=function($){F(typeof $=="number");var Y=$%26,G=($-Y)/26,Z=1<>>26,O&=67108863,this.words[I]=O}return V!==0&&(this.words[I]=V,this.length++),this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function($){var Y=$<0;if(this.negative!==0&&!Y)return-1;if(this.negative===0&&Y)return 1;this.strip();var G;if(this.length>1)G=1;else{Y&&($=-$),F($<=67108863,"Number is too big");var Z=this.words[0]|0;G=Z===$?0:Z<$?-1:1}return this.negative!==0?-G|0:G},X.prototype.cmp=function($){if(this.negative!==0&&$.negative===0)return-1;if(this.negative===0&&$.negative!==0)return 1;var Y=this.ucmp($);return this.negative!==0?-Y|0:Y},X.prototype.ucmp=function($){if(this.length>$.length)return 1;if(this.length<$.length)return-1;for(var Y=0,G=this.length-1;G>=0;G--){var Z=this.words[G]|0,V=$.words[G]|0;if(Z!==V){ZV&&(Y=1);break}}return Y},X.prototype.gtn=function($){return this.cmpn($)===1},X.prototype.gt=function($){return this.cmp($)===1},X.prototype.gten=function($){return this.cmpn($)>=0},X.prototype.gte=function($){return this.cmp($)>=0},X.prototype.ltn=function($){return this.cmpn($)===-1},X.prototype.lt=function($){return this.cmp($)===-1},X.prototype.lten=function($){return this.cmpn($)<=0},X.prototype.lte=function($){return this.cmp($)<=0},X.prototype.eqn=function($){return this.cmpn($)===0},X.prototype.eq=function($){return this.cmp($)===0},X.red=function($){return new p($)},X.prototype.toRed=function($){return F(!this.red,"Already a number in reduction context"),F(this.negative===0,"red works only with positives"),$.convertTo(this)._forceRed($)},X.prototype.fromRed=function(){return F(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function($){return this.red=$,this},X.prototype.forceRed=function($){return F(!this.red,"Already a number in reduction context"),this._forceRed($)},X.prototype.redAdd=function($){return F(this.red,"redAdd works only with red numbers"),this.red.add(this,$)},X.prototype.redIAdd=function($){return F(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,$)},X.prototype.redSub=function($){return F(this.red,"redSub works only with red numbers"),this.red.sub(this,$)},X.prototype.redISub=function($){return F(this.red,"redISub works only with red numbers"),this.red.isub(this,$)},X.prototype.redShl=function($){return F(this.red,"redShl works only with red numbers"),this.red.shl(this,$)},X.prototype.redMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.mul(this,$)},X.prototype.redIMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.imul(this,$)},X.prototype.redSqr=function(){return F(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return F(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return F(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return F(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return F(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function($){return F(this.red&&!$.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,$)};var B={k256:null,p224:null,p192:null,p25519:null};function w($,Y){this.name=$,this.p=new X(Y,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}w.prototype._tmp=function(){var $=new X(null);return $.words=new Array(Math.ceil(this.n/13)),$},w.prototype.ireduce=function($){var Y=$,G;do this.split(Y,this.tmp),Y=this.imulK(Y),Y=Y.iadd(this.tmp),G=Y.bitLength();while(G>this.n);var Z=G0?Y.isub(this.p):Y.strip!==void 0?Y.strip():Y._strip(),Y},w.prototype.split=function($,Y){$.iushrn(this.n,0,Y)},w.prototype.imulK=function($){return $.imul(this.k)};function f(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}P(f,w),f.prototype.split=function($,Y){for(var G=4194303,Z=Math.min($.length,9),V=0;V>>22,I=O}I>>>=22,$.words[V-10]=I,I===0&&$.length>10?$.length-=10:$.length-=9},f.prototype.imulK=function($){$.words[$.length]=0,$.words[$.length+1]=0,$.length+=2;for(var Y=0,G=0;G<$.length;G++){var Z=$.words[G]|0;Y+=Z*977,$.words[G]=Y&67108863,Y=Z*64+(Y/67108864|0)}return $.words[$.length-1]===0&&($.length--,$.words[$.length-1]===0&&$.length--),$};function b(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}P(b,w);function u(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}P(u,w);function Y0(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}P(Y0,w),Y0.prototype.imulK=function($){for(var Y=0,G=0;G<$.length;G++){var Z=($.words[G]|0)*19+Y,V=Z&67108863;Z>>>=26,$.words[G]=V,Y=Z}return Y!==0&&($.words[$.length++]=Y),$},X._prime=function($){if(B[$])return B[$];var Y;if($==="k256")Y=new f;else if($==="p224")Y=new b;else if($==="p192")Y=new u;else if($==="p25519")Y=new Y0;else throw new Error("Unknown prime "+$);return B[$]=Y,Y};function p($){if(typeof $=="string"){var Y=X._prime($);this.m=Y.p,this.prime=Y}else F($.gtn(1),"modulus must be greater than 1"),this.m=$,this.prime=null}p.prototype._verify1=function($){F($.negative===0,"red works only with positives"),F($.red,"red works only with red numbers")},p.prototype._verify2=function($,Y){F(($.negative|Y.negative)===0,"red works only with positives"),F($.red&&$.red===Y.red,"red works only with red numbers")},p.prototype.imod=function($){return this.prime?this.prime.ireduce($)._forceRed(this):$.umod(this.m)._forceRed(this)},p.prototype.neg=function($){return $.isZero()?$.clone():this.m.sub($)._forceRed(this)},p.prototype.add=function($,Y){this._verify2($,Y);var G=$.add(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G._forceRed(this)},p.prototype.iadd=function($,Y){this._verify2($,Y);var G=$.iadd(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G},p.prototype.sub=function($,Y){this._verify2($,Y);var G=$.sub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G._forceRed(this)},p.prototype.isub=function($,Y){this._verify2($,Y);var G=$.isub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G},p.prototype.shl=function($,Y){return this._verify1($),this.imod($.ushln(Y))},p.prototype.imul=function($,Y){return this._verify2($,Y),this.imod($.imul(Y))},p.prototype.mul=function($,Y){return this._verify2($,Y),this.imod($.mul(Y))},p.prototype.isqr=function($){return this.imul($,$.clone())},p.prototype.sqr=function($){return this.mul($,$)},p.prototype.sqrt=function($){if($.isZero())return $.clone();var Y=this.m.andln(3);if(F(Y%2===1),Y===3){var G=this.m.add(new X(1)).iushrn(2);return this.pow($,G)}for(var Z=this.m.subn(1),V=0;!Z.isZero()&&Z.andln(1)===0;)V++,Z.iushrn(1);F(!Z.isZero());var I=new X(1).toRed(this),O=I.redNeg(),U=this.m.subn(1).iushrn(1),Q=this.m.bitLength();for(Q=new X(2*Q*Q).toRed(this);this.pow(Q,U).cmp(O)!==0;)Q.redIAdd(O);for(var K=this.pow(Q,Z),L=this.pow($,Z.addn(1).iushrn(1)),A=this.pow($,Z),S=V;A.cmp(I)!==0;){for(var x=A,y=0;x.cmp(I)!==0;y++)x=x.redSqr();F(y=0;V--){for(var K=Y.words[V],L=Q-1;L>=0;L--){var A=K>>L&1;if(I!==Z[0]&&(I=this.sqr(I)),A===0&&O===0){U=0;continue}O<<=1,O|=A,U++,!(U!==G&&(V!==0||L!==0))&&(I=this.mul(I,Z[O]),U=0,O=0)}Q=26}return I},p.prototype.convertTo=function($){var Y=$.umod(this.m);return Y===$?Y.clone():Y},p.prototype.convertFrom=function($){var Y=$.clone();return Y.red=null,Y},X.mont=function($){return new v0($)};function v0($){p.call(this,$),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new X(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}P(v0,p),v0.prototype.convertTo=function($){return this.imod($.ushln(this.shift))},v0.prototype.convertFrom=function($){var Y=this.imod($.mul(this.rinv));return Y.red=null,Y},v0.prototype.imul=function($,Y){if($.isZero()||Y.isZero())return $.words[0]=0,$.length=1,$;var G=$.imul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.mul=function($,Y){if($.isZero()||Y.isZero())return new X(0)._forceRed(this);var G=$.mul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.invm=function($){var Y=this.imod($._invmp(this.m).mul(this.r2));return Y._forceRed(this)}})(typeof _>"u"||_,N)}}),u$=S0({"node_modules/safer-buffer/safer.js"(N,_){var j=i$,k=j0,F={},P;for(P in j)!j.hasOwnProperty(P)||P==="SlowBuffer"||P==="Buffer"||(F[P]=j[P]);var X=F.Buffer={};for(P in k)!k.hasOwnProperty(P)||P==="allocUnsafe"||P==="allocUnsafeSlow"||(X[P]=k[P]);if(F.Buffer.prototype=k.prototype,(!X.from||X.from===Uint8Array.from)&&(X.from=function(C,z,T){if(typeof C=="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof C);if(C&&typeof C.length>"u")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof C);return k(C,z,T)}),X.alloc||(X.alloc=function(C,z,T){if(typeof C!="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof C);if(C<0||C>=2*(1<<30))throw new RangeError('The value "'+C+'" is invalid for option "size"');var H=k(C);return!z||z.length===0?H.fill(0):typeof T=="string"?H.fill(z,T):H.fill(z),H}),!F.kStringMaxLength)try{F.kStringMaxLength=nQ}catch{}F.constants||(F.constants={MAX_LENGTH:F.kMaxLength},F.kStringMaxLength&&(F.constants.MAX_STRING_LENGTH=F.kStringMaxLength)),_.exports=F}}),n$=S0({"node_modules/asn1.js/lib/asn1/base/reporter.js"(N){var _=B0();function j(F){this._reporterState={obj:null,path:[],options:F||{},errors:[]}}N.Reporter=j,j.prototype.isError=function(F){return F instanceof k},j.prototype.save=function(){let F=this._reporterState;return{obj:F.obj,pathLen:F.path.length}},j.prototype.restore=function(F){let P=this._reporterState;P.obj=F.obj,P.path=P.path.slice(0,F.pathLen)},j.prototype.enterKey=function(F){return this._reporterState.path.push(F)},j.prototype.exitKey=function(F){let P=this._reporterState;P.path=P.path.slice(0,F-1)},j.prototype.leaveKey=function(F,P,X){let C=this._reporterState;this.exitKey(F),C.obj!==null&&(C.obj[P]=X)},j.prototype.path=function(){return this._reporterState.path.join("/")},j.prototype.enterObject=function(){let F=this._reporterState,P=F.obj;return F.obj={},P},j.prototype.leaveObject=function(F){let P=this._reporterState,X=P.obj;return P.obj=F,X},j.prototype.error=function(F){let P,X=this._reporterState,C=F instanceof k;if(C?P=F:P=new k(X.path.map(function(z){return"["+JSON.stringify(z)+"]"}).join(""),F.message||F,F.stack),!X.options.partial)throw P;return C||X.errors.push(P),P},j.prototype.wrapResult=function(F){let P=this._reporterState;return P.options.partial?{result:this.isError(F)?null:F,errors:P.errors}:F};function k(F,P){this.path=F,this.rethrow(P)}_(k,Error),k.prototype.rethrow=function(F){if(this.message=F+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,k),!this.stack)try{throw new Error(this.message)}catch(P){this.stack=P.stack}return this}}}),z$=S0({"node_modules/asn1.js/lib/asn1/base/buffer.js"(N){var _=B0(),j=n$().Reporter,k=u$().Buffer;function F(X,C){if(j.call(this,C),!k.isBuffer(X)){this.error("Input not Buffer");return}this.base=X,this.offset=0,this.length=X.length}_(F,j),N.DecoderBuffer=F,F.isDecoderBuffer=function(X){return X instanceof F?!0:typeof X=="object"&&k.isBuffer(X.base)&&X.constructor.name==="DecoderBuffer"&&typeof X.offset=="number"&&typeof X.length=="number"&&typeof X.save=="function"&&typeof X.restore=="function"&&typeof X.isEmpty=="function"&&typeof X.readUInt8=="function"&&typeof X.skip=="function"&&typeof X.raw=="function"},F.prototype.save=function(){return{offset:this.offset,reporter:j.prototype.save.call(this)}},F.prototype.restore=function(X){let C=new F(this.base);return C.offset=X.offset,C.length=this.offset,this.offset=X.offset,j.prototype.restore.call(this,X.reporter),C},F.prototype.isEmpty=function(){return this.offset===this.length},F.prototype.readUInt8=function(X){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(X||"DecoderBuffer overrun")},F.prototype.skip=function(X,C){if(!(this.offset+X<=this.length))return this.error(C||"DecoderBuffer overrun");let z=new F(this.base);return z._reporterState=this._reporterState,z.offset=this.offset,z.length=this.offset+X,this.offset+=X,z},F.prototype.raw=function(X){return this.base.slice(X?X.offset:this.offset,this.length)};function P(X,C){if(Array.isArray(X))this.length=0,this.value=X.map(function(z){return P.isEncoderBuffer(z)||(z=new P(z,C)),this.length+=z.length,z},this);else if(typeof X=="number"){if(!(0<=X&&X<=255))return C.error("non-byte EncoderBuffer value");this.value=X,this.length=1}else if(typeof X=="string")this.value=X,this.length=k.byteLength(X);else if(k.isBuffer(X))this.value=X,this.length=X.length;else return C.error("Unsupported type: "+typeof X)}N.EncoderBuffer=P,P.isEncoderBuffer=function(X){return X instanceof P?!0:typeof X=="object"&&X.constructor.name==="EncoderBuffer"&&typeof X.length=="number"&&typeof X.join=="function"},P.prototype.join=function(X,C){return X||(X=k.alloc(this.length)),C||(C=0),this.length===0||(Array.isArray(this.value)?this.value.forEach(function(z){z.join(X,C),C+=z.length}):(typeof this.value=="number"?X[C]=this.value:typeof this.value=="string"?X.write(this.value,C):k.isBuffer(this.value)&&this.value.copy(X,C),C+=this.length)),X}}}),s$=S0({"node_modules/asn1.js/lib/asn1/base/node.js"(N,_){var j=n$().Reporter,k=z$().EncoderBuffer,F=z$().DecoderBuffer,P=H$(),X=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],C=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(X),z=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function T(J,W,D){let E={};this._baseState=E,E.name=D,E.enc=J,E.parent=W||null,E.children=null,E.tag=null,E.args=null,E.reverseArgs=null,E.choice=null,E.optional=!1,E.any=!1,E.obj=!1,E.use=null,E.useDecoder=null,E.key=null,E.default=null,E.explicit=null,E.implicit=null,E.contains=null,E.parent||(E.children=[],this._wrap())}_.exports=T;var H=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];T.prototype.clone=function(){let J=this._baseState,W={};H.forEach(function(E){W[E]=J[E]});let D=new this.constructor(W.parent);return D._baseState=W,D},T.prototype._wrap=function(){let J=this._baseState;C.forEach(function(W){this[W]=function(){let D=new this.constructor(this);return J.children.push(D),D[W].apply(D,arguments)}},this)},T.prototype._init=function(J){let W=this._baseState;P(W.parent===null),J.call(this),W.children=W.children.filter(function(D){return D._baseState.parent===this},this),P.equal(W.children.length,1,"Root node can have only one child")},T.prototype._useArgs=function(J){let W=this._baseState,D=J.filter(function(E){return E instanceof this.constructor},this);J=J.filter(function(E){return!(E instanceof this.constructor)},this),D.length!==0&&(P(W.children===null),W.children=D,D.forEach(function(E){E._baseState.parent=this},this)),J.length!==0&&(P(W.args===null),W.args=J,W.reverseArgs=J.map(function(E){if(typeof E!="object"||E.constructor!==Object)return E;let R={};return Object.keys(E).forEach(function(M){M==(M|0)&&(M|=0);let v=E[M];R[v]=M}),R}))},z.forEach(function(J){T.prototype[J]=function(){let W=this._baseState;throw new Error(J+" not implemented for encoding: "+W.enc)}}),X.forEach(function(J){T.prototype[J]=function(){let W=this._baseState,D=Array.prototype.slice.call(arguments);return P(W.tag===null),W.tag=J,this._useArgs(D),this}}),T.prototype.use=function(J){P(J);let W=this._baseState;return P(W.use===null),W.use=J,this},T.prototype.optional=function(){let J=this._baseState;return J.optional=!0,this},T.prototype.def=function(J){let W=this._baseState;return P(W.default===null),W.default=J,W.optional=!0,this},T.prototype.explicit=function(J){let W=this._baseState;return P(W.explicit===null&&W.implicit===null),W.explicit=J,this},T.prototype.implicit=function(J){let W=this._baseState;return P(W.explicit===null&&W.implicit===null),W.implicit=J,this},T.prototype.obj=function(){let J=this._baseState,W=Array.prototype.slice.call(arguments);return J.obj=!0,W.length!==0&&this._useArgs(W),this},T.prototype.key=function(J){let W=this._baseState;return P(W.key===null),W.key=J,this},T.prototype.any=function(){let J=this._baseState;return J.any=!0,this},T.prototype.choice=function(J){let W=this._baseState;return P(W.choice===null),W.choice=J,this._useArgs(Object.keys(J).map(function(D){return J[D]})),this},T.prototype.contains=function(J){let W=this._baseState;return P(W.use===null),W.contains=J,this},T.prototype._decode=function(J,W){let D=this._baseState;if(D.parent===null)return J.wrapResult(D.children[0]._decode(J,W));let E=D.default,R=!0,M=null;if(D.key!==null&&(M=J.enterKey(D.key)),D.optional){let q=null;if(D.explicit!==null?q=D.explicit:D.implicit!==null?q=D.implicit:D.tag!==null&&(q=D.tag),q===null&&!D.any){let g=J.save();try{D.choice===null?this._decodeGeneric(D.tag,J,W):this._decodeChoice(J,W),R=!0}catch{R=!1}J.restore(g)}else if(R=this._peekTag(J,q,D.any),J.isError(R))return R}let v;if(D.obj&&R&&(v=J.enterObject()),R){if(D.explicit!==null){let g=this._decodeTag(J,D.explicit);if(J.isError(g))return g;J=g}let q=J.offset;if(D.use===null&&D.choice===null){let g;D.any&&(g=J.save());let B=this._decodeTag(J,D.implicit!==null?D.implicit:D.tag,D.any);if(J.isError(B))return B;D.any?E=J.raw(g):J=B}if(W&&W.track&&D.tag!==null&&W.track(J.path(),q,J.length,"tagged"),W&&W.track&&D.tag!==null&&W.track(J.path(),J.offset,J.length,"content"),D.any||(D.choice===null?E=this._decodeGeneric(D.tag,J,W):E=this._decodeChoice(J,W)),J.isError(E))return E;if(!D.any&&D.choice===null&&D.children!==null&&D.children.forEach(function(g){g._decode(J,W)}),D.contains&&(D.tag==="octstr"||D.tag==="bitstr")){let g=new F(E);E=this._getUse(D.contains,J._reporterState.obj)._decode(g,W)}}return D.obj&&R&&(E=J.leaveObject(v)),D.key!==null&&(E!==null||R===!0)?J.leaveKey(M,D.key,E):M!==null&&J.exitKey(M),E},T.prototype._decodeGeneric=function(J,W,D){let E=this._baseState;return J==="seq"||J==="set"?null:J==="seqof"||J==="setof"?this._decodeList(W,J,E.args[0],D):/str$/.test(J)?this._decodeStr(W,J,D):J==="objid"&&E.args?this._decodeObjid(W,E.args[0],E.args[1],D):J==="objid"?this._decodeObjid(W,null,null,D):J==="gentime"||J==="utctime"?this._decodeTime(W,J,D):J==="null_"?this._decodeNull(W,D):J==="bool"?this._decodeBool(W,D):J==="objDesc"?this._decodeStr(W,J,D):J==="int"||J==="enum"?this._decodeInt(W,E.args&&E.args[0],D):E.use!==null?this._getUse(E.use,W._reporterState.obj)._decode(W,D):W.error("unknown tag: "+J)},T.prototype._getUse=function(J,W){let D=this._baseState;return D.useDecoder=this._use(J,W),P(D.useDecoder._baseState.parent===null),D.useDecoder=D.useDecoder._baseState.children[0],D.implicit!==D.useDecoder._baseState.implicit&&(D.useDecoder=D.useDecoder.clone(),D.useDecoder._baseState.implicit=D.implicit),D.useDecoder},T.prototype._decodeChoice=function(J,W){let D=this._baseState,E=null,R=!1;return Object.keys(D.choice).some(function(M){let v=J.save(),q=D.choice[M];try{let g=q._decode(J,W);if(J.isError(g))return!1;E={type:M,value:g},R=!0}catch{return J.restore(v),!1}return!0},this),R?E:J.error("Choice not matched")},T.prototype._createEncoderBuffer=function(J){return new k(J,this.reporter)},T.prototype._encode=function(J,W,D){let E=this._baseState;if(E.default!==null&&E.default===J)return;let R=this._encodeValue(J,W,D);if(R!==void 0&&!this._skipDefault(R,W,D))return R},T.prototype._encodeValue=function(J,W,D){let E=this._baseState;if(E.parent===null)return E.children[0]._encode(J,W||new j);let R=null;if(this.reporter=W,E.optional&&J===void 0)if(E.default!==null)J=E.default;else return;let M=null,v=!1;if(E.any)R=this._createEncoderBuffer(J);else if(E.choice)R=this._encodeChoice(J,W);else if(E.contains)M=this._getUse(E.contains,D)._encode(J,W),v=!0;else if(E.children)M=E.children.map(function(q){if(q._baseState.tag==="null_")return q._encode(null,W,J);if(q._baseState.key===null)return W.error("Child should have a key");let g=W.enterKey(q._baseState.key);if(typeof J!="object")return W.error("Child expected, but input is not object");let B=q._encode(J[q._baseState.key],W,J);return W.leaveKey(g),B},this).filter(function(q){return q}),M=this._createEncoderBuffer(M);else if(E.tag==="seqof"||E.tag==="setof"){if(!(E.args&&E.args.length===1))return W.error("Too many args for : "+E.tag);if(!Array.isArray(J))return W.error("seqof/setof, but data is not Array");let q=this.clone();q._baseState.implicit=null,M=this._createEncoderBuffer(J.map(function(g){let B=this._baseState;return this._getUse(B.args[0],J)._encode(g,W)},q))}else E.use!==null?R=this._getUse(E.use,D)._encode(J,W):(M=this._encodePrimitive(E.tag,J),v=!0);if(!E.any&&E.choice===null){let q=E.implicit!==null?E.implicit:E.tag,g=E.implicit===null?"universal":"context";q===null?E.use===null&&W.error("Tag could be omitted only for .use()"):E.use===null&&(R=this._encodeComposite(q,v,g,M))}return E.explicit!==null&&(R=this._encodeComposite(E.explicit,!1,"context",R)),R},T.prototype._encodeChoice=function(J,W){let D=this._baseState,E=D.choice[J.type];return E||P(!1,J.type+" not found in "+JSON.stringify(Object.keys(D.choice))),E._encode(J.value,W)},T.prototype._encodePrimitive=function(J,W){let D=this._baseState;if(/str$/.test(J))return this._encodeStr(W,J);if(J==="objid"&&D.args)return this._encodeObjid(W,D.reverseArgs[0],D.args[1]);if(J==="objid")return this._encodeObjid(W,null,null);if(J==="gentime"||J==="utctime")return this._encodeTime(W,J);if(J==="null_")return this._encodeNull();if(J==="int"||J==="enum")return this._encodeInt(W,D.args&&D.reverseArgs[0]);if(J==="bool")return this._encodeBool(W);if(J==="objDesc")return this._encodeStr(W,J);throw new Error("Unsupported tag: "+J)},T.prototype._isNumstr=function(J){return/^[0-9 ]*$/.test(J)},T.prototype._isPrintstr=function(J){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(J)}}}),t$=S0({"node_modules/asn1.js/lib/asn1/constants/der.js"(N){function _(j){let k={};return Object.keys(j).forEach(function(F){(F|0)==F&&(F=F|0);let P=j[F];k[P]=F}),k}N.tagClass={0:"universal",1:"application",2:"context",3:"private"},N.tagClassByName=_(N.tagClass),N.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},N.tagByName=_(N.tag)}}),_Q=S0({"node_modules/asn1.js/lib/asn1/encoders/der.js"(N,_){var j=B0(),k=u$().Buffer,F=s$(),P=t$();function X(H){this.enc="der",this.name=H.name,this.entity=H,this.tree=new C,this.tree._init(H.body)}_.exports=X,X.prototype.encode=function(H,J){return this.tree._encode(H,J).join()};function C(H){F.call(this,"der",H)}j(C,F),C.prototype._encodeComposite=function(H,J,W,D){let E=T(H,J,W,this.reporter);if(D.length<128){let v=k.alloc(2);return v[0]=E,v[1]=D.length,this._createEncoderBuffer([v,D])}let R=1;for(let v=D.length;v>=256;v>>=8)R++;let M=k.alloc(2+R);M[0]=E,M[1]=128|R;for(let v=1+R,q=D.length;q>0;v--,q>>=8)M[v]=q&255;return this._createEncoderBuffer([M,D])},C.prototype._encodeStr=function(H,J){if(J==="bitstr")return this._createEncoderBuffer([H.unused|0,H.data]);if(J==="bmpstr"){let W=k.alloc(H.length*2);for(let D=0;D=40)return this.reporter.error("Second objid identifier OOB");H.splice(0,2,H[0]*40+H[1])}let D=0;for(let M=0;M=128;v>>=7)D++}let E=k.alloc(D),R=E.length-1;for(let M=H.length-1;M>=0;M--){let v=H[M];for(E[R--]=v&127;(v>>=7)>0;)E[R--]=128|v&127}return this._createEncoderBuffer(E)};function z(H){return H<10?"0"+H:H}C.prototype._encodeTime=function(H,J){let W,D=new Date(H);return J==="gentime"?W=[z(D.getUTCFullYear()),z(D.getUTCMonth()+1),z(D.getUTCDate()),z(D.getUTCHours()),z(D.getUTCMinutes()),z(D.getUTCSeconds()),"Z"].join(""):J==="utctime"?W=[z(D.getUTCFullYear()%100),z(D.getUTCMonth()+1),z(D.getUTCDate()),z(D.getUTCHours()),z(D.getUTCMinutes()),z(D.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+J+" time is not supported yet"),this._encodeStr(W,"octstr")},C.prototype._encodeNull=function(){return this._createEncoderBuffer("")},C.prototype._encodeInt=function(H,J){if(typeof H=="string"){if(!J)return this.reporter.error("String int or enum given, but no values map");if(!J.hasOwnProperty(H))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(H));H=J[H]}if(typeof H!="number"&&!k.isBuffer(H)){let E=H.toArray();!H.sign&&E[0]&128&&E.unshift(0),H=k.from(E)}if(k.isBuffer(H)){let E=H.length;H.length===0&&E++;let R=k.alloc(E);return H.copy(R),H.length===0&&(R[0]=0),this._createEncoderBuffer(R)}if(H<128)return this._createEncoderBuffer(H);if(H<256)return this._createEncoderBuffer([0,H]);let W=1;for(let E=H;E>=256;E>>=8)W++;let D=new Array(W);for(let E=D.length-1;E>=0;E--)D[E]=H&255,H>>=8;return D[0]&128&&D.unshift(0),this._createEncoderBuffer(k.from(D))},C.prototype._encodeBool=function(H){return this._createEncoderBuffer(H?255:0)},C.prototype._use=function(H,J){return typeof H=="function"&&(H=H(J)),H._getEncoder("der").tree},C.prototype._skipDefault=function(H,J,W){let D=this._baseState,E;if(D.default===null)return!1;let R=H.join();if(D.defaultBuffer===void 0&&(D.defaultBuffer=this._encodeValue(D.default,J,W).join()),R.length!==D.defaultBuffer.length)return!1;for(E=0;E=31?D.error("Multi-octet tag encoding unsupported"):(J||(E|=32),E|=P.tagClassByName[W||"universal"]<<6,E)}}}),hY=S0({"node_modules/asn1.js/lib/asn1/encoders/pem.js"(N,_){var j=B0(),k=_Q();function F(P){k.call(this,P),this.enc="pem"}j(F,k),_.exports=F,F.prototype.encode=function(P,X){let C=k.prototype.encode.call(this,P).toString("base64"),z=["-----BEGIN "+X.label+"-----"];for(let T=0;T>6],R=(D&32)===0;if((D&31)===31){let v=D;for(D=0;(v&128)===128;){if(v=J.readUInt8(W),J.isError(v))return v;D<<=7,D|=v&127}}else D&=31;let M=X.tag[D];return{cls:E,primitive:R,tag:D,tagStr:M}}function H(J,W,D){let E=J.readUInt8(D);if(J.isError(E))return E;if(!W&&E===128)return null;if((E&128)===0)return E;let R=E&127;if(R>4)return J.error("length octect is too long");E=0;for(let M=0;M0&&B.ishrn(w),B}function R(q,g){q=E(q,g),q=q.mod(g);var B=j.from(q.toArray());if(B.length=W)throw new Error("invalid sig")}_.exports=C}}),eY=S0({"node_modules/browserify-sign/browser/index.js"(N,_){var j=N0().Buffer,k=M$(),F=B0(),P=mY(),X=aY(),C=OQ();Object.keys(C).forEach(function(W){C[W].id=j.from(C[W].id,"hex"),C[W.toLowerCase()]=C[W]});function z(W){A$.Writable.call(this);var D=C[W];if(!D)throw new Error("Unknown message digest");this._hashType=D.hash,this._hash=k(D.hash),this._tag=D.id,this._signType=D.sign}F(z,A$.Writable),z.prototype._write=function(W,D,E){this._hash.update(W),E()},z.prototype.update=function(W,D){return typeof W=="string"&&(W=j.from(W,D)),this._hash.update(W),this},z.prototype.sign=function(W,D){this.end();var E=this._hash.digest(),R=P(E,W,this._hashType,this._signType,this._tag);return D?R.toString(D):R};function T(W){A$.Writable.call(this);var D=C[W];if(!D)throw new Error("Unknown message digest");this._hash=k(D.hash),this._tag=D.id,this._signType=D.sign}F(T,A$.Writable),T.prototype._write=function(W,D,E){this._hash.update(W),E()},T.prototype.update=function(W,D){return typeof W=="string"&&(W=j.from(W,D)),this._hash.update(W),this},T.prototype.verify=function(W,D,E){typeof D=="string"&&(D=j.from(D,E)),this.end();var R=this._hash.digest();return X(D,R,W,this._signType,this._tag)};function H(W){return new z(W)}function J(W){return new T(W)}_.exports={Sign:H,Verify:J,createSign:H,createVerify:J}}}),rY=S0({"node_modules/create-ecdh/node_modules/bn.js/lib/bn.js"(N,_){(function(j,k){function F($,Y){if(!$)throw new Error(Y||"Assertion failed")}function P($,Y){$.super_=Y;var G=function(){};G.prototype=Y.prototype,$.prototype=new G,$.prototype.constructor=$}function X($,Y,G){if(X.isBN($))return $;this.negative=0,this.words=null,this.length=0,this.red=null,$!==null&&((Y==="le"||Y==="be")&&(G=Y,Y=10),this._init($||0,Y||10,G||"be"))}typeof j=="object"?j.exports=X:k.BN=X,X.BN=X,X.wordSize=26;var C=j0;X.isBN=function($){return $ instanceof X?!0:$!==null&&typeof $=="object"&&$.constructor.wordSize===X.wordSize&&Array.isArray($.words)},X.max=function($,Y){return $.cmp(Y)>0?$:Y},X.min=function($,Y){return $.cmp(Y)<0?$:Y},X.prototype._init=function($,Y,G){if(typeof $=="number")return this._initNumber($,Y,G);if(typeof $=="object")return this._initArray($,Y,G);Y==="hex"&&(Y=16),F(Y===(Y|0)&&Y>=2&&Y<=36),$=$.toString().replace(/\s+/g,"");var Z=0;$[0]==="-"&&(Z++,this.negative=1),Z<$.length&&(Y===16?this._parseHex($,Z,G):(this._parseBase($,Y,Z),G==="le"&&this._initArray(this.toArray(),Y,G)))},X.prototype._initNumber=function($,Y,G){$<0&&(this.negative=1,$=-$),$<67108864?(this.words=[$&67108863],this.length=1):$<4503599627370496?(this.words=[$&67108863,$/67108864&67108863],this.length=2):(F($<9007199254740992),this.words=[$&67108863,$/67108864&67108863,1],this.length=3),G==="le"&&this._initArray(this.toArray(),Y,G)},X.prototype._initArray=function($,Y,G){if(F(typeof $.length=="number"),$.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil($.length/3),this.words=new Array(this.length);for(var Z=0;Z=0;Z-=3)I=$[Z]|$[Z-1]<<8|$[Z-2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);else if(G==="le")for(Z=0,V=0;Z<$.length;Z+=3)I=$[Z]|$[Z+1]<<8|$[Z+2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);return this.strip()};function z($,Y){var G=$.charCodeAt(Y);return G>=65&&G<=70?G-55:G>=97&&G<=102?G-87:G-48&15}function T($,Y,G){var Z=z($,G);return G-1>=Y&&(Z|=z($,G-1)<<4),Z}X.prototype._parseHex=function($,Y,G){this.length=Math.ceil(($.length-Y)/6),this.words=new Array(this.length);for(var Z=0;Z=Y;Z-=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8;else{var U=$.length-Y;for(Z=U%2===0?Y+1:Y;Z<$.length;Z+=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8}this.strip()};function H($,Y,G,Z){for(var V=0,I=Math.min($.length,G),O=Y;O=49?V+=U-49+10:U>=17?V+=U-17+10:V+=U}return V}X.prototype._parseBase=function($,Y,G){this.words=[0],this.length=1;for(var Z=0,V=1;V<=67108863;V*=Y)Z++;Z--,V=V/Y|0;for(var I=$.length-G,O=I%Z,U=Math.min(I,I-O)+G,Q=0,K=G;K1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},X.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},X.prototype.inspect=function(){return(this.red?""};var J=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],W=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],D=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];X.prototype.toString=function($,Y){$=$||10,Y=Y|0||1;var G;if($===16||$==="hex"){G="";for(var Z=0,V=0,I=0;I>>24-Z&16777215,V!==0||I!==this.length-1?G=J[6-U.length]+U+G:G=U+G,Z+=2,Z>=26&&(Z-=26,I--)}for(V!==0&&(G=V.toString(16)+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}if($===($|0)&&$>=2&&$<=36){var Q=W[$],K=D[$];G="";var L=this.clone();for(L.negative=0;!L.isZero();){var A=L.modn(K).toString($);L=L.idivn(K),L.isZero()?G=A+G:G=J[Q-A.length]+A+G}for(this.isZero()&&(G="0"+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}F(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var $=this.words[0];return this.length===2?$+=this.words[1]*67108864:this.length===3&&this.words[2]===1?$+=4503599627370496+this.words[1]*67108864:this.length>2&&F(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-$:$},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function($,Y){return F(typeof C<"u"),this.toArrayLike(C,$,Y)},X.prototype.toArray=function($,Y){return this.toArrayLike(Array,$,Y)},X.prototype.toArrayLike=function($,Y,G){var Z=this.byteLength(),V=G||Math.max(1,Z);F(Z<=V,"byte array longer than desired length"),F(V>0,"Requested array length <= 0"),this.strip();var I=Y==="le",O=new $(V),U,Q,K=this.clone();if(I){for(Q=0;!K.isZero();Q++)U=K.andln(255),K.iushrn(8),O[Q]=U;for(;Q=4096&&(G+=13,Y>>>=13),Y>=64&&(G+=7,Y>>>=7),Y>=8&&(G+=4,Y>>>=4),Y>=2&&(G+=2,Y>>>=2),G+Y},X.prototype._zeroBits=function($){if($===0)return 26;var Y=$,G=0;return(Y&8191)===0&&(G+=13,Y>>>=13),(Y&127)===0&&(G+=7,Y>>>=7),(Y&15)===0&&(G+=4,Y>>>=4),(Y&3)===0&&(G+=2,Y>>>=2),(Y&1)===0&&G++,G},X.prototype.bitLength=function(){var $=this.words[this.length-1],Y=this._countBits($);return(this.length-1)*26+Y};function E($){for(var Y=new Array($.bitLength()),G=0;G>>V}return Y}X.prototype.zeroBits=function(){if(this.isZero())return 0;for(var $=0,Y=0;Y$.length?this.clone().ior($):$.clone().ior(this)},X.prototype.uor=function($){return this.length>$.length?this.clone().iuor($):$.clone().iuor(this)},X.prototype.iuand=function($){var Y;this.length>$.length?Y=$:Y=this;for(var G=0;G$.length?this.clone().iand($):$.clone().iand(this)},X.prototype.uand=function($){return this.length>$.length?this.clone().iuand($):$.clone().iuand(this)},X.prototype.iuxor=function($){var Y,G;this.length>$.length?(Y=this,G=$):(Y=$,G=this);for(var Z=0;Z$.length?this.clone().ixor($):$.clone().ixor(this)},X.prototype.uxor=function($){return this.length>$.length?this.clone().iuxor($):$.clone().iuxor(this)},X.prototype.inotn=function($){F(typeof $=="number"&&$>=0);var Y=Math.ceil($/26)|0,G=$%26;this._expand(Y),G>0&&Y--;for(var Z=0;Z0&&(this.words[Z]=~this.words[Z]&67108863>>26-G),this.strip()},X.prototype.notn=function($){return this.clone().inotn($)},X.prototype.setn=function($,Y){F(typeof $=="number"&&$>=0);var G=$/26|0,Z=$%26;return this._expand(G+1),Y?this.words[G]=this.words[G]|1<$.length?(G=this,Z=$):(G=$,Z=this);for(var V=0,I=0;I>>26;for(;V!==0&&I>>26;if(this.length=G.length,V!==0)this.words[this.length]=V,this.length++;else if(G!==this)for(;I$.length?this.clone().iadd($):$.clone().iadd(this)},X.prototype.isub=function($){if($.negative!==0){$.negative=0;var Y=this.iadd($);return $.negative=1,Y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd($),this.negative=1,this._normSign();var G=this.cmp($);if(G===0)return this.negative=0,this.length=1,this.words[0]=0,this;var Z,V;G>0?(Z=this,V=$):(Z=$,V=this);for(var I=0,O=0;O>26,this.words[O]=Y&67108863;for(;I!==0&&O>26,this.words[O]=Y&67108863;if(I===0&&O>>26,A=Q&67108863,S=Math.min(K,Y.length-1),x=Math.max(0,K-$.length+1);x<=S;x++){var y=K-x|0;V=$.words[y]|0,I=Y.words[x]|0,O=V*I+A,L+=O/67108864|0,A=O&67108863}G.words[K]=A|0,Q=L|0}return Q!==0?G.words[K]=Q|0:G.length--,G.strip()}var M=function($,Y,G){var Z=$.words,V=Y.words,I=G.words,O=0,U,Q,K,L=Z[0]|0,A=L&8191,S=L>>>13,x=Z[1]|0,y=x&8191,c=x>>>13,q0=Z[2]|0,h=q0&8191,d=q0>>>13,_0=Z[3]|0,l=_0&8191,n=_0>>>13,y0=Z[4]|0,t=y0&8191,s=y0>>>13,w0=Z[5]|0,m=w0&8191,r=w0>>>13,$$=Z[6]|0,i=$$&8191,e=$$>>>13,x0=Z[7]|0,o=x0&8191,a=x0>>>13,p0=Z[8]|0,$0=p0&8191,Q0=p0>>>13,Y$=Z[9]|0,Z0=Y$&8191,G0=Y$>>>13,Z$=V[0]|0,V0=Z$&8191,U0=Z$>>>13,G$=V[1]|0,X0=G$&8191,K0=G$>>>13,V$=V[2]|0,I0=V$&8191,O0=V$>>>13,U$=V[3]|0,J0=U$&8191,F0=U$>>>13,X$=V[4]|0,A0=X$&8191,W0=X$>>>13,K$=V[5]|0,H0=K$&8191,E0=K$>>>13,I$=V[6]|0,T0=I$&8191,D0=I$>>>13,O$=V[7]|0,C0=O$&8191,L0=O$>>>13,J$=V[8]|0,R0=J$&8191,z0=J$>>>13,F$=V[9]|0,P0=F$&8191,M0=F$>>>13;G.negative=$.negative^Y.negative,G.length=19,U=Math.imul(A,V0),Q=Math.imul(A,U0),Q=Q+Math.imul(S,V0)|0,K=Math.imul(S,U0);var Q$=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(Q$>>>26)|0,Q$&=67108863,U=Math.imul(y,V0),Q=Math.imul(y,U0),Q=Q+Math.imul(c,V0)|0,K=Math.imul(c,U0),U=U+Math.imul(A,X0)|0,Q=Q+Math.imul(A,K0)|0,Q=Q+Math.imul(S,X0)|0,K=K+Math.imul(S,K0)|0;var k0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(k0>>>26)|0,k0&=67108863,U=Math.imul(h,V0),Q=Math.imul(h,U0),Q=Q+Math.imul(d,V0)|0,K=Math.imul(d,U0),U=U+Math.imul(y,X0)|0,Q=Q+Math.imul(y,K0)|0,Q=Q+Math.imul(c,X0)|0,K=K+Math.imul(c,K0)|0,U=U+Math.imul(A,I0)|0,Q=Q+Math.imul(A,O0)|0,Q=Q+Math.imul(S,I0)|0,K=K+Math.imul(S,O0)|0;var g0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(g0>>>26)|0,g0&=67108863,U=Math.imul(l,V0),Q=Math.imul(l,U0),Q=Q+Math.imul(n,V0)|0,K=Math.imul(n,U0),U=U+Math.imul(h,X0)|0,Q=Q+Math.imul(h,K0)|0,Q=Q+Math.imul(d,X0)|0,K=K+Math.imul(d,K0)|0,U=U+Math.imul(y,I0)|0,Q=Q+Math.imul(y,O0)|0,Q=Q+Math.imul(c,I0)|0,K=K+Math.imul(c,O0)|0,U=U+Math.imul(A,J0)|0,Q=Q+Math.imul(A,F0)|0,Q=Q+Math.imul(S,J0)|0,K=K+Math.imul(S,F0)|0;var f0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(f0>>>26)|0,f0&=67108863,U=Math.imul(t,V0),Q=Math.imul(t,U0),Q=Q+Math.imul(s,V0)|0,K=Math.imul(s,U0),U=U+Math.imul(l,X0)|0,Q=Q+Math.imul(l,K0)|0,Q=Q+Math.imul(n,X0)|0,K=K+Math.imul(n,K0)|0,U=U+Math.imul(h,I0)|0,Q=Q+Math.imul(h,O0)|0,Q=Q+Math.imul(d,I0)|0,K=K+Math.imul(d,O0)|0,U=U+Math.imul(y,J0)|0,Q=Q+Math.imul(y,F0)|0,Q=Q+Math.imul(c,J0)|0,K=K+Math.imul(c,F0)|0,U=U+Math.imul(A,A0)|0,Q=Q+Math.imul(A,W0)|0,Q=Q+Math.imul(S,A0)|0,K=K+Math.imul(S,W0)|0;var c0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(c0>>>26)|0,c0&=67108863,U=Math.imul(m,V0),Q=Math.imul(m,U0),Q=Q+Math.imul(r,V0)|0,K=Math.imul(r,U0),U=U+Math.imul(t,X0)|0,Q=Q+Math.imul(t,K0)|0,Q=Q+Math.imul(s,X0)|0,K=K+Math.imul(s,K0)|0,U=U+Math.imul(l,I0)|0,Q=Q+Math.imul(l,O0)|0,Q=Q+Math.imul(n,I0)|0,K=K+Math.imul(n,O0)|0,U=U+Math.imul(h,J0)|0,Q=Q+Math.imul(h,F0)|0,Q=Q+Math.imul(d,J0)|0,K=K+Math.imul(d,F0)|0,U=U+Math.imul(y,A0)|0,Q=Q+Math.imul(y,W0)|0,Q=Q+Math.imul(c,A0)|0,K=K+Math.imul(c,W0)|0,U=U+Math.imul(A,H0)|0,Q=Q+Math.imul(A,E0)|0,Q=Q+Math.imul(S,H0)|0,K=K+Math.imul(S,E0)|0;var h0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(h0>>>26)|0,h0&=67108863,U=Math.imul(i,V0),Q=Math.imul(i,U0),Q=Q+Math.imul(e,V0)|0,K=Math.imul(e,U0),U=U+Math.imul(m,X0)|0,Q=Q+Math.imul(m,K0)|0,Q=Q+Math.imul(r,X0)|0,K=K+Math.imul(r,K0)|0,U=U+Math.imul(t,I0)|0,Q=Q+Math.imul(t,O0)|0,Q=Q+Math.imul(s,I0)|0,K=K+Math.imul(s,O0)|0,U=U+Math.imul(l,J0)|0,Q=Q+Math.imul(l,F0)|0,Q=Q+Math.imul(n,J0)|0,K=K+Math.imul(n,F0)|0,U=U+Math.imul(h,A0)|0,Q=Q+Math.imul(h,W0)|0,Q=Q+Math.imul(d,A0)|0,K=K+Math.imul(d,W0)|0,U=U+Math.imul(y,H0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(c,H0)|0,K=K+Math.imul(c,E0)|0,U=U+Math.imul(A,T0)|0,Q=Q+Math.imul(A,D0)|0,Q=Q+Math.imul(S,T0)|0,K=K+Math.imul(S,D0)|0;var d0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(d0>>>26)|0,d0&=67108863,U=Math.imul(o,V0),Q=Math.imul(o,U0),Q=Q+Math.imul(a,V0)|0,K=Math.imul(a,U0),U=U+Math.imul(i,X0)|0,Q=Q+Math.imul(i,K0)|0,Q=Q+Math.imul(e,X0)|0,K=K+Math.imul(e,K0)|0,U=U+Math.imul(m,I0)|0,Q=Q+Math.imul(m,O0)|0,Q=Q+Math.imul(r,I0)|0,K=K+Math.imul(r,O0)|0,U=U+Math.imul(t,J0)|0,Q=Q+Math.imul(t,F0)|0,Q=Q+Math.imul(s,J0)|0,K=K+Math.imul(s,F0)|0,U=U+Math.imul(l,A0)|0,Q=Q+Math.imul(l,W0)|0,Q=Q+Math.imul(n,A0)|0,K=K+Math.imul(n,W0)|0,U=U+Math.imul(h,H0)|0,Q=Q+Math.imul(h,E0)|0,Q=Q+Math.imul(d,H0)|0,K=K+Math.imul(d,E0)|0,U=U+Math.imul(y,T0)|0,Q=Q+Math.imul(y,D0)|0,Q=Q+Math.imul(c,T0)|0,K=K+Math.imul(c,D0)|0,U=U+Math.imul(A,C0)|0,Q=Q+Math.imul(A,L0)|0,Q=Q+Math.imul(S,C0)|0,K=K+Math.imul(S,L0)|0;var b0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(b0>>>26)|0,b0&=67108863,U=Math.imul($0,V0),Q=Math.imul($0,U0),Q=Q+Math.imul(Q0,V0)|0,K=Math.imul(Q0,U0),U=U+Math.imul(o,X0)|0,Q=Q+Math.imul(o,K0)|0,Q=Q+Math.imul(a,X0)|0,K=K+Math.imul(a,K0)|0,U=U+Math.imul(i,I0)|0,Q=Q+Math.imul(i,O0)|0,Q=Q+Math.imul(e,I0)|0,K=K+Math.imul(e,O0)|0,U=U+Math.imul(m,J0)|0,Q=Q+Math.imul(m,F0)|0,Q=Q+Math.imul(r,J0)|0,K=K+Math.imul(r,F0)|0,U=U+Math.imul(t,A0)|0,Q=Q+Math.imul(t,W0)|0,Q=Q+Math.imul(s,A0)|0,K=K+Math.imul(s,W0)|0,U=U+Math.imul(l,H0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(n,H0)|0,K=K+Math.imul(n,E0)|0,U=U+Math.imul(h,T0)|0,Q=Q+Math.imul(h,D0)|0,Q=Q+Math.imul(d,T0)|0,K=K+Math.imul(d,D0)|0,U=U+Math.imul(y,C0)|0,Q=Q+Math.imul(y,L0)|0,Q=Q+Math.imul(c,C0)|0,K=K+Math.imul(c,L0)|0,U=U+Math.imul(A,R0)|0,Q=Q+Math.imul(A,z0)|0,Q=Q+Math.imul(S,R0)|0,K=K+Math.imul(S,z0)|0;var l0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(l0>>>26)|0,l0&=67108863,U=Math.imul(Z0,V0),Q=Math.imul(Z0,U0),Q=Q+Math.imul(G0,V0)|0,K=Math.imul(G0,U0),U=U+Math.imul($0,X0)|0,Q=Q+Math.imul($0,K0)|0,Q=Q+Math.imul(Q0,X0)|0,K=K+Math.imul(Q0,K0)|0,U=U+Math.imul(o,I0)|0,Q=Q+Math.imul(o,O0)|0,Q=Q+Math.imul(a,I0)|0,K=K+Math.imul(a,O0)|0,U=U+Math.imul(i,J0)|0,Q=Q+Math.imul(i,F0)|0,Q=Q+Math.imul(e,J0)|0,K=K+Math.imul(e,F0)|0,U=U+Math.imul(m,A0)|0,Q=Q+Math.imul(m,W0)|0,Q=Q+Math.imul(r,A0)|0,K=K+Math.imul(r,W0)|0,U=U+Math.imul(t,H0)|0,Q=Q+Math.imul(t,E0)|0,Q=Q+Math.imul(s,H0)|0,K=K+Math.imul(s,E0)|0,U=U+Math.imul(l,T0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(n,T0)|0,K=K+Math.imul(n,D0)|0,U=U+Math.imul(h,C0)|0,Q=Q+Math.imul(h,L0)|0,Q=Q+Math.imul(d,C0)|0,K=K+Math.imul(d,L0)|0,U=U+Math.imul(y,R0)|0,Q=Q+Math.imul(y,z0)|0,Q=Q+Math.imul(c,R0)|0,K=K+Math.imul(c,z0)|0,U=U+Math.imul(A,P0)|0,Q=Q+Math.imul(A,M0)|0,Q=Q+Math.imul(S,P0)|0,K=K+Math.imul(S,M0)|0;var o0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(o0>>>26)|0,o0&=67108863,U=Math.imul(Z0,X0),Q=Math.imul(Z0,K0),Q=Q+Math.imul(G0,X0)|0,K=Math.imul(G0,K0),U=U+Math.imul($0,I0)|0,Q=Q+Math.imul($0,O0)|0,Q=Q+Math.imul(Q0,I0)|0,K=K+Math.imul(Q0,O0)|0,U=U+Math.imul(o,J0)|0,Q=Q+Math.imul(o,F0)|0,Q=Q+Math.imul(a,J0)|0,K=K+Math.imul(a,F0)|0,U=U+Math.imul(i,A0)|0,Q=Q+Math.imul(i,W0)|0,Q=Q+Math.imul(e,A0)|0,K=K+Math.imul(e,W0)|0,U=U+Math.imul(m,H0)|0,Q=Q+Math.imul(m,E0)|0,Q=Q+Math.imul(r,H0)|0,K=K+Math.imul(r,E0)|0,U=U+Math.imul(t,T0)|0,Q=Q+Math.imul(t,D0)|0,Q=Q+Math.imul(s,T0)|0,K=K+Math.imul(s,D0)|0,U=U+Math.imul(l,C0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(n,C0)|0,K=K+Math.imul(n,L0)|0,U=U+Math.imul(h,R0)|0,Q=Q+Math.imul(h,z0)|0,Q=Q+Math.imul(d,R0)|0,K=K+Math.imul(d,z0)|0,U=U+Math.imul(y,P0)|0,Q=Q+Math.imul(y,M0)|0,Q=Q+Math.imul(c,P0)|0,K=K+Math.imul(c,M0)|0;var u0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(u0>>>26)|0,u0&=67108863,U=Math.imul(Z0,I0),Q=Math.imul(Z0,O0),Q=Q+Math.imul(G0,I0)|0,K=Math.imul(G0,O0),U=U+Math.imul($0,J0)|0,Q=Q+Math.imul($0,F0)|0,Q=Q+Math.imul(Q0,J0)|0,K=K+Math.imul(Q0,F0)|0,U=U+Math.imul(o,A0)|0,Q=Q+Math.imul(o,W0)|0,Q=Q+Math.imul(a,A0)|0,K=K+Math.imul(a,W0)|0,U=U+Math.imul(i,H0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,H0)|0,K=K+Math.imul(e,E0)|0,U=U+Math.imul(m,T0)|0,Q=Q+Math.imul(m,D0)|0,Q=Q+Math.imul(r,T0)|0,K=K+Math.imul(r,D0)|0,U=U+Math.imul(t,C0)|0,Q=Q+Math.imul(t,L0)|0,Q=Q+Math.imul(s,C0)|0,K=K+Math.imul(s,L0)|0,U=U+Math.imul(l,R0)|0,Q=Q+Math.imul(l,z0)|0,Q=Q+Math.imul(n,R0)|0,K=K+Math.imul(n,z0)|0,U=U+Math.imul(h,P0)|0,Q=Q+Math.imul(h,M0)|0,Q=Q+Math.imul(d,P0)|0,K=K+Math.imul(d,M0)|0;var n0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(n0>>>26)|0,n0&=67108863,U=Math.imul(Z0,J0),Q=Math.imul(Z0,F0),Q=Q+Math.imul(G0,J0)|0,K=Math.imul(G0,F0),U=U+Math.imul($0,A0)|0,Q=Q+Math.imul($0,W0)|0,Q=Q+Math.imul(Q0,A0)|0,K=K+Math.imul(Q0,W0)|0,U=U+Math.imul(o,H0)|0,Q=Q+Math.imul(o,E0)|0,Q=Q+Math.imul(a,H0)|0,K=K+Math.imul(a,E0)|0,U=U+Math.imul(i,T0)|0,Q=Q+Math.imul(i,D0)|0,Q=Q+Math.imul(e,T0)|0,K=K+Math.imul(e,D0)|0,U=U+Math.imul(m,C0)|0,Q=Q+Math.imul(m,L0)|0,Q=Q+Math.imul(r,C0)|0,K=K+Math.imul(r,L0)|0,U=U+Math.imul(t,R0)|0,Q=Q+Math.imul(t,z0)|0,Q=Q+Math.imul(s,R0)|0,K=K+Math.imul(s,z0)|0,U=U+Math.imul(l,P0)|0,Q=Q+Math.imul(l,M0)|0,Q=Q+Math.imul(n,P0)|0,K=K+Math.imul(n,M0)|0;var s0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(s0>>>26)|0,s0&=67108863,U=Math.imul(Z0,A0),Q=Math.imul(Z0,W0),Q=Q+Math.imul(G0,A0)|0,K=Math.imul(G0,W0),U=U+Math.imul($0,H0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Q0,H0)|0,K=K+Math.imul(Q0,E0)|0,U=U+Math.imul(o,T0)|0,Q=Q+Math.imul(o,D0)|0,Q=Q+Math.imul(a,T0)|0,K=K+Math.imul(a,D0)|0,U=U+Math.imul(i,C0)|0,Q=Q+Math.imul(i,L0)|0,Q=Q+Math.imul(e,C0)|0,K=K+Math.imul(e,L0)|0,U=U+Math.imul(m,R0)|0,Q=Q+Math.imul(m,z0)|0,Q=Q+Math.imul(r,R0)|0,K=K+Math.imul(r,z0)|0,U=U+Math.imul(t,P0)|0,Q=Q+Math.imul(t,M0)|0,Q=Q+Math.imul(s,P0)|0,K=K+Math.imul(s,M0)|0;var t0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(t0>>>26)|0,t0&=67108863,U=Math.imul(Z0,H0),Q=Math.imul(Z0,E0),Q=Q+Math.imul(G0,H0)|0,K=Math.imul(G0,E0),U=U+Math.imul($0,T0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Q0,T0)|0,K=K+Math.imul(Q0,D0)|0,U=U+Math.imul(o,C0)|0,Q=Q+Math.imul(o,L0)|0,Q=Q+Math.imul(a,C0)|0,K=K+Math.imul(a,L0)|0,U=U+Math.imul(i,R0)|0,Q=Q+Math.imul(i,z0)|0,Q=Q+Math.imul(e,R0)|0,K=K+Math.imul(e,z0)|0,U=U+Math.imul(m,P0)|0,Q=Q+Math.imul(m,M0)|0,Q=Q+Math.imul(r,P0)|0,K=K+Math.imul(r,M0)|0;var m0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(m0>>>26)|0,m0&=67108863,U=Math.imul(Z0,T0),Q=Math.imul(Z0,D0),Q=Q+Math.imul(G0,T0)|0,K=Math.imul(G0,D0),U=U+Math.imul($0,C0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Q0,C0)|0,K=K+Math.imul(Q0,L0)|0,U=U+Math.imul(o,R0)|0,Q=Q+Math.imul(o,z0)|0,Q=Q+Math.imul(a,R0)|0,K=K+Math.imul(a,z0)|0,U=U+Math.imul(i,P0)|0,Q=Q+Math.imul(i,M0)|0,Q=Q+Math.imul(e,P0)|0,K=K+Math.imul(e,M0)|0;var a0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(a0>>>26)|0,a0&=67108863,U=Math.imul(Z0,C0),Q=Math.imul(Z0,L0),Q=Q+Math.imul(G0,C0)|0,K=Math.imul(G0,L0),U=U+Math.imul($0,R0)|0,Q=Q+Math.imul($0,z0)|0,Q=Q+Math.imul(Q0,R0)|0,K=K+Math.imul(Q0,z0)|0,U=U+Math.imul(o,P0)|0,Q=Q+Math.imul(o,M0)|0,Q=Q+Math.imul(a,P0)|0,K=K+Math.imul(a,M0)|0;var e0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(e0>>>26)|0,e0&=67108863,U=Math.imul(Z0,R0),Q=Math.imul(Z0,z0),Q=Q+Math.imul(G0,R0)|0,K=Math.imul(G0,z0),U=U+Math.imul($0,P0)|0,Q=Q+Math.imul($0,M0)|0,Q=Q+Math.imul(Q0,P0)|0,K=K+Math.imul(Q0,M0)|0;var r0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(r0>>>26)|0,r0&=67108863,U=Math.imul(Z0,P0),Q=Math.imul(Z0,M0),Q=Q+Math.imul(G0,P0)|0,K=Math.imul(G0,M0);var i0=(O+U|0)+((Q&8191)<<13)|0;return O=(K+(Q>>>13)|0)+(i0>>>26)|0,i0&=67108863,I[0]=Q$,I[1]=k0,I[2]=g0,I[3]=f0,I[4]=c0,I[5]=h0,I[6]=d0,I[7]=b0,I[8]=l0,I[9]=o0,I[10]=u0,I[11]=n0,I[12]=s0,I[13]=t0,I[14]=m0,I[15]=a0,I[16]=e0,I[17]=r0,I[18]=i0,O!==0&&(I[19]=O,G.length++),G};Math.imul||(M=R);function v($,Y,G){G.negative=Y.negative^$.negative,G.length=$.length+Y.length;for(var Z=0,V=0,I=0;I>>26)|0,V+=O>>>26,O&=67108863}G.words[I]=U,Z=O,O=V}return Z!==0?G.words[I]=Z:G.length--,G.strip()}function q($,Y,G){var Z=new g;return Z.mulp($,Y,G)}X.prototype.mulTo=function($,Y){var G,Z=this.length+$.length;return this.length===10&&$.length===10?G=M(this,$,Y):Z<63?G=R(this,$,Y):Z<1024?G=v(this,$,Y):G=q(this,$,Y),G};function g($,Y){this.x=$,this.y=Y}g.prototype.makeRBT=function($){for(var Y=new Array($),G=X.prototype._countBits($)-1,Z=0;Z<$;Z++)Y[Z]=this.revBin(Z,G,$);return Y},g.prototype.revBin=function($,Y,G){if($===0||$===G-1)return $;for(var Z=0,V=0;V>=1;return Z},g.prototype.permute=function($,Y,G,Z,V,I){for(var O=0;O>>1)V++;return 1<>>13,G[2*I+1]=V&8191,V=V>>>13;for(I=2*Y;I>=26,Y+=Z/67108864|0,Y+=V>>>26,this.words[G]=V&67108863}return Y!==0&&(this.words[G]=Y,this.length++),this},X.prototype.muln=function($){return this.clone().imuln($)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function($){var Y=E($);if(Y.length===0)return new X(1);for(var G=this,Z=0;Z=0);var Y=$%26,G=($-Y)/26,Z=67108863>>>26-Y<<26-Y,V;if(Y!==0){var I=0;for(V=0;V>>26-Y}I&&(this.words[V]=I,this.length++)}if(G!==0){for(V=this.length-1;V>=0;V--)this.words[V+G]=this.words[V];for(V=0;V=0);var Z;Y?Z=(Y-Y%26)/26:Z=0;var V=$%26,I=Math.min(($-V)/26,this.length),O=67108863^67108863>>>V<I)for(this.length-=I,Q=0;Q=0&&(K!==0||Q>=Z);Q--){var L=this.words[Q]|0;this.words[Q]=K<<26-V|L>>>V,K=L&O}return U&&K!==0&&(U.words[U.length++]=K),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},X.prototype.ishrn=function($,Y,G){return F(this.negative===0),this.iushrn($,Y,G)},X.prototype.shln=function($){return this.clone().ishln($)},X.prototype.ushln=function($){return this.clone().iushln($)},X.prototype.shrn=function($){return this.clone().ishrn($)},X.prototype.ushrn=function($){return this.clone().iushrn($)},X.prototype.testn=function($){F(typeof $=="number"&&$>=0);var Y=$%26,G=($-Y)/26,Z=1<=0);var Y=$%26,G=($-Y)/26;if(F(this.negative===0,"imaskn works only with positive numbers"),this.length<=G)return this;if(Y!==0&&G++,this.length=Math.min(G,this.length),Y!==0){var Z=67108863^67108863>>>Y<=67108864;Y++)this.words[Y]-=67108864,Y===this.length-1?this.words[Y+1]=1:this.words[Y+1]++;return this.length=Math.max(this.length,Y+1),this},X.prototype.isubn=function($){if(F(typeof $=="number"),F($<67108864),$<0)return this.iaddn(-$);if(this.negative!==0)return this.negative=0,this.iaddn($),this.negative=1,this;if(this.words[0]-=$,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Y=0;Y>26)-(U/67108864|0),this.words[V+G]=I&67108863}for(;V>26,this.words[V+G]=I&67108863;if(O===0)return this.strip();for(F(O===-1),O=0,V=0;V>26,this.words[V]=I&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function($,Y){var G=this.length-$.length,Z=this.clone(),V=$,I=V.words[V.length-1]|0,O=this._countBits(I);G=26-O,G!==0&&(V=V.ushln(G),Z.iushln(G),I=V.words[V.length-1]|0);var U=Z.length-V.length,Q;if(Y!=="mod"){Q=new X(null),Q.length=U+1,Q.words=new Array(Q.length);for(var K=0;K=0;A--){var S=(Z.words[V.length+A]|0)*67108864+(Z.words[V.length+A-1]|0);for(S=Math.min(S/I|0,67108863),Z._ishlnsubmul(V,S,A);Z.negative!==0;)S--,Z.negative=0,Z._ishlnsubmul(V,1,A),Z.isZero()||(Z.negative^=1);Q&&(Q.words[A]=S)}return Q&&Q.strip(),Z.strip(),Y!=="div"&&G!==0&&Z.iushrn(G),{div:Q||null,mod:Z}},X.prototype.divmod=function($,Y,G){if(F(!$.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var Z,V,I;return this.negative!==0&&$.negative===0?(I=this.neg().divmod($,Y),Y!=="mod"&&(Z=I.div.neg()),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.iadd($)),{div:Z,mod:V}):this.negative===0&&$.negative!==0?(I=this.divmod($.neg(),Y),Y!=="mod"&&(Z=I.div.neg()),{div:Z,mod:I.mod}):(this.negative&$.negative)!==0?(I=this.neg().divmod($.neg(),Y),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.isub($)),{div:I.div,mod:V}):$.length>this.length||this.cmp($)<0?{div:new X(0),mod:this}:$.length===1?Y==="div"?{div:this.divn($.words[0]),mod:null}:Y==="mod"?{div:null,mod:new X(this.modn($.words[0]))}:{div:this.divn($.words[0]),mod:new X(this.modn($.words[0]))}:this._wordDiv($,Y)},X.prototype.div=function($){return this.divmod($,"div",!1).div},X.prototype.mod=function($){return this.divmod($,"mod",!1).mod},X.prototype.umod=function($){return this.divmod($,"mod",!0).mod},X.prototype.divRound=function($){var Y=this.divmod($);if(Y.mod.isZero())return Y.div;var G=Y.div.negative!==0?Y.mod.isub($):Y.mod,Z=$.ushrn(1),V=$.andln(1),I=G.cmp(Z);return I<0||V===1&&I===0?Y.div:Y.div.negative!==0?Y.div.isubn(1):Y.div.iaddn(1)},X.prototype.modn=function($){F($<=67108863);for(var Y=(1<<26)%$,G=0,Z=this.length-1;Z>=0;Z--)G=(Y*G+(this.words[Z]|0))%$;return G},X.prototype.idivn=function($){F($<=67108863);for(var Y=0,G=this.length-1;G>=0;G--){var Z=(this.words[G]|0)+Y*67108864;this.words[G]=Z/$|0,Y=Z%$}return this.strip()},X.prototype.divn=function($){return this.clone().idivn($)},X.prototype.egcd=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=new X(0),O=new X(1),U=0;Y.isEven()&&G.isEven();)Y.iushrn(1),G.iushrn(1),++U;for(var Q=G.clone(),K=Y.clone();!Y.isZero();){for(var L=0,A=1;(Y.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0)for(Y.iushrn(L);L-- >0;)(Z.isOdd()||V.isOdd())&&(Z.iadd(Q),V.isub(K)),Z.iushrn(1),V.iushrn(1);for(var S=0,x=1;(G.words[0]&x)===0&&S<26;++S,x<<=1);if(S>0)for(G.iushrn(S);S-- >0;)(I.isOdd()||O.isOdd())&&(I.iadd(Q),O.isub(K)),I.iushrn(1),O.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(I),V.isub(O)):(G.isub(Y),I.isub(Z),O.isub(V))}return{a:I,b:O,gcd:G.iushln(U)}},X.prototype._invmp=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=G.clone();Y.cmpn(1)>0&&G.cmpn(1)>0;){for(var O=0,U=1;(Y.words[0]&U)===0&&O<26;++O,U<<=1);if(O>0)for(Y.iushrn(O);O-- >0;)Z.isOdd()&&Z.iadd(I),Z.iushrn(1);for(var Q=0,K=1;(G.words[0]&K)===0&&Q<26;++Q,K<<=1);if(Q>0)for(G.iushrn(Q);Q-- >0;)V.isOdd()&&V.iadd(I),V.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(V)):(G.isub(Y),V.isub(Z))}var L;return Y.cmpn(1)===0?L=Z:L=V,L.cmpn(0)<0&&L.iadd($),L},X.prototype.gcd=function($){if(this.isZero())return $.abs();if($.isZero())return this.abs();var Y=this.clone(),G=$.clone();Y.negative=0,G.negative=0;for(var Z=0;Y.isEven()&&G.isEven();Z++)Y.iushrn(1),G.iushrn(1);do{for(;Y.isEven();)Y.iushrn(1);for(;G.isEven();)G.iushrn(1);var V=Y.cmp(G);if(V<0){var I=Y;Y=G,G=I}else if(V===0||G.cmpn(1)===0)break;Y.isub(G)}while(!0);return G.iushln(Z)},X.prototype.invm=function($){return this.egcd($).a.umod($)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function($){return this.words[0]&$},X.prototype.bincn=function($){F(typeof $=="number");var Y=$%26,G=($-Y)/26,Z=1<>>26,O&=67108863,this.words[I]=O}return V!==0&&(this.words[I]=V,this.length++),this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function($){var Y=$<0;if(this.negative!==0&&!Y)return-1;if(this.negative===0&&Y)return 1;this.strip();var G;if(this.length>1)G=1;else{Y&&($=-$),F($<=67108863,"Number is too big");var Z=this.words[0]|0;G=Z===$?0:Z<$?-1:1}return this.negative!==0?-G|0:G},X.prototype.cmp=function($){if(this.negative!==0&&$.negative===0)return-1;if(this.negative===0&&$.negative!==0)return 1;var Y=this.ucmp($);return this.negative!==0?-Y|0:Y},X.prototype.ucmp=function($){if(this.length>$.length)return 1;if(this.length<$.length)return-1;for(var Y=0,G=this.length-1;G>=0;G--){var Z=this.words[G]|0,V=$.words[G]|0;if(Z!==V){ZV&&(Y=1);break}}return Y},X.prototype.gtn=function($){return this.cmpn($)===1},X.prototype.gt=function($){return this.cmp($)===1},X.prototype.gten=function($){return this.cmpn($)>=0},X.prototype.gte=function($){return this.cmp($)>=0},X.prototype.ltn=function($){return this.cmpn($)===-1},X.prototype.lt=function($){return this.cmp($)===-1},X.prototype.lten=function($){return this.cmpn($)<=0},X.prototype.lte=function($){return this.cmp($)<=0},X.prototype.eqn=function($){return this.cmpn($)===0},X.prototype.eq=function($){return this.cmp($)===0},X.red=function($){return new p($)},X.prototype.toRed=function($){return F(!this.red,"Already a number in reduction context"),F(this.negative===0,"red works only with positives"),$.convertTo(this)._forceRed($)},X.prototype.fromRed=function(){return F(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function($){return this.red=$,this},X.prototype.forceRed=function($){return F(!this.red,"Already a number in reduction context"),this._forceRed($)},X.prototype.redAdd=function($){return F(this.red,"redAdd works only with red numbers"),this.red.add(this,$)},X.prototype.redIAdd=function($){return F(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,$)},X.prototype.redSub=function($){return F(this.red,"redSub works only with red numbers"),this.red.sub(this,$)},X.prototype.redISub=function($){return F(this.red,"redISub works only with red numbers"),this.red.isub(this,$)},X.prototype.redShl=function($){return F(this.red,"redShl works only with red numbers"),this.red.shl(this,$)},X.prototype.redMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.mul(this,$)},X.prototype.redIMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.imul(this,$)},X.prototype.redSqr=function(){return F(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return F(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return F(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return F(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return F(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function($){return F(this.red&&!$.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,$)};var B={k256:null,p224:null,p192:null,p25519:null};function w($,Y){this.name=$,this.p=new X(Y,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}w.prototype._tmp=function(){var $=new X(null);return $.words=new Array(Math.ceil(this.n/13)),$},w.prototype.ireduce=function($){var Y=$,G;do this.split(Y,this.tmp),Y=this.imulK(Y),Y=Y.iadd(this.tmp),G=Y.bitLength();while(G>this.n);var Z=G0?Y.isub(this.p):Y.strip!==void 0?Y.strip():Y._strip(),Y},w.prototype.split=function($,Y){$.iushrn(this.n,0,Y)},w.prototype.imulK=function($){return $.imul(this.k)};function f(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}P(f,w),f.prototype.split=function($,Y){for(var G=4194303,Z=Math.min($.length,9),V=0;V>>22,I=O}I>>>=22,$.words[V-10]=I,I===0&&$.length>10?$.length-=10:$.length-=9},f.prototype.imulK=function($){$.words[$.length]=0,$.words[$.length+1]=0,$.length+=2;for(var Y=0,G=0;G<$.length;G++){var Z=$.words[G]|0;Y+=Z*977,$.words[G]=Y&67108863,Y=Z*64+(Y/67108864|0)}return $.words[$.length-1]===0&&($.length--,$.words[$.length-1]===0&&$.length--),$};function b(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}P(b,w);function u(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}P(u,w);function Y0(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}P(Y0,w),Y0.prototype.imulK=function($){for(var Y=0,G=0;G<$.length;G++){var Z=($.words[G]|0)*19+Y,V=Z&67108863;Z>>>=26,$.words[G]=V,Y=Z}return Y!==0&&($.words[$.length++]=Y),$},X._prime=function($){if(B[$])return B[$];var Y;if($==="k256")Y=new f;else if($==="p224")Y=new b;else if($==="p192")Y=new u;else if($==="p25519")Y=new Y0;else throw new Error("Unknown prime "+$);return B[$]=Y,Y};function p($){if(typeof $=="string"){var Y=X._prime($);this.m=Y.p,this.prime=Y}else F($.gtn(1),"modulus must be greater than 1"),this.m=$,this.prime=null}p.prototype._verify1=function($){F($.negative===0,"red works only with positives"),F($.red,"red works only with red numbers")},p.prototype._verify2=function($,Y){F(($.negative|Y.negative)===0,"red works only with positives"),F($.red&&$.red===Y.red,"red works only with red numbers")},p.prototype.imod=function($){return this.prime?this.prime.ireduce($)._forceRed(this):$.umod(this.m)._forceRed(this)},p.prototype.neg=function($){return $.isZero()?$.clone():this.m.sub($)._forceRed(this)},p.prototype.add=function($,Y){this._verify2($,Y);var G=$.add(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G._forceRed(this)},p.prototype.iadd=function($,Y){this._verify2($,Y);var G=$.iadd(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G},p.prototype.sub=function($,Y){this._verify2($,Y);var G=$.sub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G._forceRed(this)},p.prototype.isub=function($,Y){this._verify2($,Y);var G=$.isub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G},p.prototype.shl=function($,Y){return this._verify1($),this.imod($.ushln(Y))},p.prototype.imul=function($,Y){return this._verify2($,Y),this.imod($.imul(Y))},p.prototype.mul=function($,Y){return this._verify2($,Y),this.imod($.mul(Y))},p.prototype.isqr=function($){return this.imul($,$.clone())},p.prototype.sqr=function($){return this.mul($,$)},p.prototype.sqrt=function($){if($.isZero())return $.clone();var Y=this.m.andln(3);if(F(Y%2===1),Y===3){var G=this.m.add(new X(1)).iushrn(2);return this.pow($,G)}for(var Z=this.m.subn(1),V=0;!Z.isZero()&&Z.andln(1)===0;)V++,Z.iushrn(1);F(!Z.isZero());var I=new X(1).toRed(this),O=I.redNeg(),U=this.m.subn(1).iushrn(1),Q=this.m.bitLength();for(Q=new X(2*Q*Q).toRed(this);this.pow(Q,U).cmp(O)!==0;)Q.redIAdd(O);for(var K=this.pow(Q,Z),L=this.pow($,Z.addn(1).iushrn(1)),A=this.pow($,Z),S=V;A.cmp(I)!==0;){for(var x=A,y=0;x.cmp(I)!==0;y++)x=x.redSqr();F(y=0;V--){for(var K=Y.words[V],L=Q-1;L>=0;L--){var A=K>>L&1;if(I!==Z[0]&&(I=this.sqr(I)),A===0&&O===0){U=0;continue}O<<=1,O|=A,U++,!(U!==G&&(V!==0||L!==0))&&(I=this.mul(I,Z[O]),U=0,O=0)}Q=26}return I},p.prototype.convertTo=function($){var Y=$.umod(this.m);return Y===$?Y.clone():Y},p.prototype.convertFrom=function($){var Y=$.clone();return Y.red=null,Y},X.mont=function($){return new v0($)};function v0($){p.call(this,$),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new X(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}P(v0,p),v0.prototype.convertTo=function($){return this.imod($.ushln(this.shift))},v0.prototype.convertFrom=function($){var Y=this.imod($.mul(this.rinv));return Y.red=null,Y},v0.prototype.imul=function($,Y){if($.isZero()||Y.isZero())return $.words[0]=0,$.length=1,$;var G=$.imul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.mul=function($,Y){if($.isZero()||Y.isZero())return new X(0)._forceRed(this);var G=$.mul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.invm=function($){var Y=this.imod($._invmp(this.m).mul(this.r2));return Y._forceRed(this)}})(typeof _>"u"||_,N)}}),iY=S0({"node_modules/create-ecdh/browser.js"(N,_){var j=o$(),k=rY();_.exports=function(C){return new P(C)};var F={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};F.p224=F.secp224r1,F.p256=F.secp256r1=F.prime256v1,F.p192=F.secp192r1=F.prime192v1,F.p384=F.secp384r1,F.p521=F.secp521r1;function P(C){this.curveType=F[C],this.curveType||(this.curveType={name:C}),this.curve=new j.ec(this.curveType.name),this.keys=void 0}P.prototype.generateKeys=function(C,z){return this.keys=this.curve.genKeyPair(),this.getPublicKey(C,z)},P.prototype.computeSecret=function(C,z,T){z=z||"utf8",j0.isBuffer(C)||(C=new j0(C,z));var H=this.curve.keyFromPublic(C).getPublic(),J=H.mul(this.keys.getPrivate()).getX();return X(J,T,this.curveType.byteLength)},P.prototype.getPublicKey=function(C,z){var T=this.keys.getPublic(z==="compressed",!0);return z==="hybrid"&&(T[T.length-1]%2?T[0]=7:T[0]=6),X(T,C)},P.prototype.getPrivateKey=function(C){return X(this.keys.getPrivate(),C)},P.prototype.setPublicKey=function(C,z){return z=z||"utf8",j0.isBuffer(C)||(C=new j0(C,z)),this.keys._importPublic(C),this},P.prototype.setPrivateKey=function(C,z){z=z||"utf8",j0.isBuffer(C)||(C=new j0(C,z));var T=new k(C);return T=T.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(T),this};function X(C,z,T){Array.isArray(C)||(C=C.toArray());var H=new j0(C);if(T&&H.length0?$:Y},X.min=function($,Y){return $.cmp(Y)<0?$:Y},X.prototype._init=function($,Y,G){if(typeof $=="number")return this._initNumber($,Y,G);if(typeof $=="object")return this._initArray($,Y,G);Y==="hex"&&(Y=16),F(Y===(Y|0)&&Y>=2&&Y<=36),$=$.toString().replace(/\s+/g,"");var Z=0;$[0]==="-"&&(Z++,this.negative=1),Z<$.length&&(Y===16?this._parseHex($,Z,G):(this._parseBase($,Y,Z),G==="le"&&this._initArray(this.toArray(),Y,G)))},X.prototype._initNumber=function($,Y,G){$<0&&(this.negative=1,$=-$),$<67108864?(this.words=[$&67108863],this.length=1):$<4503599627370496?(this.words=[$&67108863,$/67108864&67108863],this.length=2):(F($<9007199254740992),this.words=[$&67108863,$/67108864&67108863,1],this.length=3),G==="le"&&this._initArray(this.toArray(),Y,G)},X.prototype._initArray=function($,Y,G){if(F(typeof $.length=="number"),$.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil($.length/3),this.words=new Array(this.length);for(var Z=0;Z=0;Z-=3)I=$[Z]|$[Z-1]<<8|$[Z-2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);else if(G==="le")for(Z=0,V=0;Z<$.length;Z+=3)I=$[Z]|$[Z+1]<<8|$[Z+2]<<16,this.words[V]|=I<>>26-O&67108863,O+=24,O>=26&&(O-=26,V++);return this.strip()};function z($,Y){var G=$.charCodeAt(Y);return G>=65&&G<=70?G-55:G>=97&&G<=102?G-87:G-48&15}function T($,Y,G){var Z=z($,G);return G-1>=Y&&(Z|=z($,G-1)<<4),Z}X.prototype._parseHex=function($,Y,G){this.length=Math.ceil(($.length-Y)/6),this.words=new Array(this.length);for(var Z=0;Z=Y;Z-=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8;else{var U=$.length-Y;for(Z=U%2===0?Y+1:Y;Z<$.length;Z+=2)O=T($,Y,Z)<=18?(V-=18,I+=1,this.words[I]|=O>>>26):V+=8}this.strip()};function H($,Y,G,Z){for(var V=0,I=Math.min($.length,G),O=Y;O=49?V+=U-49+10:U>=17?V+=U-17+10:V+=U}return V}X.prototype._parseBase=function($,Y,G){this.words=[0],this.length=1;for(var Z=0,V=1;V<=67108863;V*=Y)Z++;Z--,V=V/Y|0;for(var I=$.length-G,O=I%Z,U=Math.min(I,I-O)+G,Q=0,K=G;K1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},X.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},X.prototype.inspect=function(){return(this.red?""};var J=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],W=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],D=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];X.prototype.toString=function($,Y){$=$||10,Y=Y|0||1;var G;if($===16||$==="hex"){G="";for(var Z=0,V=0,I=0;I>>24-Z&16777215,V!==0||I!==this.length-1?G=J[6-U.length]+U+G:G=U+G,Z+=2,Z>=26&&(Z-=26,I--)}for(V!==0&&(G=V.toString(16)+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}if($===($|0)&&$>=2&&$<=36){var Q=W[$],K=D[$];G="";var L=this.clone();for(L.negative=0;!L.isZero();){var A=L.modn(K).toString($);L=L.idivn(K),L.isZero()?G=A+G:G=J[Q-A.length]+A+G}for(this.isZero()&&(G="0"+G);G.length%Y!==0;)G="0"+G;return this.negative!==0&&(G="-"+G),G}F(!1,"Base should be between 2 and 36")},X.prototype.toNumber=function(){var $=this.words[0];return this.length===2?$+=this.words[1]*67108864:this.length===3&&this.words[2]===1?$+=4503599627370496+this.words[1]*67108864:this.length>2&&F(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-$:$},X.prototype.toJSON=function(){return this.toString(16)},X.prototype.toBuffer=function($,Y){return F(typeof C<"u"),this.toArrayLike(C,$,Y)},X.prototype.toArray=function($,Y){return this.toArrayLike(Array,$,Y)},X.prototype.toArrayLike=function($,Y,G){var Z=this.byteLength(),V=G||Math.max(1,Z);F(Z<=V,"byte array longer than desired length"),F(V>0,"Requested array length <= 0"),this.strip();var I=Y==="le",O=new $(V),U,Q,K=this.clone();if(I){for(Q=0;!K.isZero();Q++)U=K.andln(255),K.iushrn(8),O[Q]=U;for(;Q=4096&&(G+=13,Y>>>=13),Y>=64&&(G+=7,Y>>>=7),Y>=8&&(G+=4,Y>>>=4),Y>=2&&(G+=2,Y>>>=2),G+Y},X.prototype._zeroBits=function($){if($===0)return 26;var Y=$,G=0;return(Y&8191)===0&&(G+=13,Y>>>=13),(Y&127)===0&&(G+=7,Y>>>=7),(Y&15)===0&&(G+=4,Y>>>=4),(Y&3)===0&&(G+=2,Y>>>=2),(Y&1)===0&&G++,G},X.prototype.bitLength=function(){var $=this.words[this.length-1],Y=this._countBits($);return(this.length-1)*26+Y};function E($){for(var Y=new Array($.bitLength()),G=0;G>>V}return Y}X.prototype.zeroBits=function(){if(this.isZero())return 0;for(var $=0,Y=0;Y$.length?this.clone().ior($):$.clone().ior(this)},X.prototype.uor=function($){return this.length>$.length?this.clone().iuor($):$.clone().iuor(this)},X.prototype.iuand=function($){var Y;this.length>$.length?Y=$:Y=this;for(var G=0;G$.length?this.clone().iand($):$.clone().iand(this)},X.prototype.uand=function($){return this.length>$.length?this.clone().iuand($):$.clone().iuand(this)},X.prototype.iuxor=function($){var Y,G;this.length>$.length?(Y=this,G=$):(Y=$,G=this);for(var Z=0;Z$.length?this.clone().ixor($):$.clone().ixor(this)},X.prototype.uxor=function($){return this.length>$.length?this.clone().iuxor($):$.clone().iuxor(this)},X.prototype.inotn=function($){F(typeof $=="number"&&$>=0);var Y=Math.ceil($/26)|0,G=$%26;this._expand(Y),G>0&&Y--;for(var Z=0;Z0&&(this.words[Z]=~this.words[Z]&67108863>>26-G),this.strip()},X.prototype.notn=function($){return this.clone().inotn($)},X.prototype.setn=function($,Y){F(typeof $=="number"&&$>=0);var G=$/26|0,Z=$%26;return this._expand(G+1),Y?this.words[G]=this.words[G]|1<$.length?(G=this,Z=$):(G=$,Z=this);for(var V=0,I=0;I>>26;for(;V!==0&&I>>26;if(this.length=G.length,V!==0)this.words[this.length]=V,this.length++;else if(G!==this)for(;I$.length?this.clone().iadd($):$.clone().iadd(this)},X.prototype.isub=function($){if($.negative!==0){$.negative=0;var Y=this.iadd($);return $.negative=1,Y._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd($),this.negative=1,this._normSign();var G=this.cmp($);if(G===0)return this.negative=0,this.length=1,this.words[0]=0,this;var Z,V;G>0?(Z=this,V=$):(Z=$,V=this);for(var I=0,O=0;O>26,this.words[O]=Y&67108863;for(;I!==0&&O>26,this.words[O]=Y&67108863;if(I===0&&O>>26,A=Q&67108863,S=Math.min(K,Y.length-1),x=Math.max(0,K-$.length+1);x<=S;x++){var y=K-x|0;V=$.words[y]|0,I=Y.words[x]|0,O=V*I+A,L+=O/67108864|0,A=O&67108863}G.words[K]=A|0,Q=L|0}return Q!==0?G.words[K]=Q|0:G.length--,G.strip()}var M=function($,Y,G){var Z=$.words,V=Y.words,I=G.words,O=0,U,Q,K,L=Z[0]|0,A=L&8191,S=L>>>13,x=Z[1]|0,y=x&8191,c=x>>>13,q0=Z[2]|0,h=q0&8191,d=q0>>>13,_0=Z[3]|0,l=_0&8191,n=_0>>>13,y0=Z[4]|0,t=y0&8191,s=y0>>>13,w0=Z[5]|0,m=w0&8191,r=w0>>>13,$$=Z[6]|0,i=$$&8191,e=$$>>>13,x0=Z[7]|0,o=x0&8191,a=x0>>>13,p0=Z[8]|0,$0=p0&8191,Q0=p0>>>13,Y$=Z[9]|0,Z0=Y$&8191,G0=Y$>>>13,Z$=V[0]|0,V0=Z$&8191,U0=Z$>>>13,G$=V[1]|0,X0=G$&8191,K0=G$>>>13,V$=V[2]|0,I0=V$&8191,O0=V$>>>13,U$=V[3]|0,J0=U$&8191,F0=U$>>>13,X$=V[4]|0,A0=X$&8191,W0=X$>>>13,K$=V[5]|0,H0=K$&8191,E0=K$>>>13,I$=V[6]|0,T0=I$&8191,D0=I$>>>13,O$=V[7]|0,C0=O$&8191,L0=O$>>>13,J$=V[8]|0,R0=J$&8191,z0=J$>>>13,F$=V[9]|0,P0=F$&8191,M0=F$>>>13;G.negative=$.negative^Y.negative,G.length=19,U=Math.imul(A,V0),Q=Math.imul(A,U0),Q=Q+Math.imul(S,V0)|0,K=Math.imul(S,U0);var Q$=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(Q$>>>26)|0,Q$&=67108863,U=Math.imul(y,V0),Q=Math.imul(y,U0),Q=Q+Math.imul(c,V0)|0,K=Math.imul(c,U0),U=U+Math.imul(A,X0)|0,Q=Q+Math.imul(A,K0)|0,Q=Q+Math.imul(S,X0)|0,K=K+Math.imul(S,K0)|0;var k0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(k0>>>26)|0,k0&=67108863,U=Math.imul(h,V0),Q=Math.imul(h,U0),Q=Q+Math.imul(d,V0)|0,K=Math.imul(d,U0),U=U+Math.imul(y,X0)|0,Q=Q+Math.imul(y,K0)|0,Q=Q+Math.imul(c,X0)|0,K=K+Math.imul(c,K0)|0,U=U+Math.imul(A,I0)|0,Q=Q+Math.imul(A,O0)|0,Q=Q+Math.imul(S,I0)|0,K=K+Math.imul(S,O0)|0;var g0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(g0>>>26)|0,g0&=67108863,U=Math.imul(l,V0),Q=Math.imul(l,U0),Q=Q+Math.imul(n,V0)|0,K=Math.imul(n,U0),U=U+Math.imul(h,X0)|0,Q=Q+Math.imul(h,K0)|0,Q=Q+Math.imul(d,X0)|0,K=K+Math.imul(d,K0)|0,U=U+Math.imul(y,I0)|0,Q=Q+Math.imul(y,O0)|0,Q=Q+Math.imul(c,I0)|0,K=K+Math.imul(c,O0)|0,U=U+Math.imul(A,J0)|0,Q=Q+Math.imul(A,F0)|0,Q=Q+Math.imul(S,J0)|0,K=K+Math.imul(S,F0)|0;var f0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(f0>>>26)|0,f0&=67108863,U=Math.imul(t,V0),Q=Math.imul(t,U0),Q=Q+Math.imul(s,V0)|0,K=Math.imul(s,U0),U=U+Math.imul(l,X0)|0,Q=Q+Math.imul(l,K0)|0,Q=Q+Math.imul(n,X0)|0,K=K+Math.imul(n,K0)|0,U=U+Math.imul(h,I0)|0,Q=Q+Math.imul(h,O0)|0,Q=Q+Math.imul(d,I0)|0,K=K+Math.imul(d,O0)|0,U=U+Math.imul(y,J0)|0,Q=Q+Math.imul(y,F0)|0,Q=Q+Math.imul(c,J0)|0,K=K+Math.imul(c,F0)|0,U=U+Math.imul(A,A0)|0,Q=Q+Math.imul(A,W0)|0,Q=Q+Math.imul(S,A0)|0,K=K+Math.imul(S,W0)|0;var c0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(c0>>>26)|0,c0&=67108863,U=Math.imul(m,V0),Q=Math.imul(m,U0),Q=Q+Math.imul(r,V0)|0,K=Math.imul(r,U0),U=U+Math.imul(t,X0)|0,Q=Q+Math.imul(t,K0)|0,Q=Q+Math.imul(s,X0)|0,K=K+Math.imul(s,K0)|0,U=U+Math.imul(l,I0)|0,Q=Q+Math.imul(l,O0)|0,Q=Q+Math.imul(n,I0)|0,K=K+Math.imul(n,O0)|0,U=U+Math.imul(h,J0)|0,Q=Q+Math.imul(h,F0)|0,Q=Q+Math.imul(d,J0)|0,K=K+Math.imul(d,F0)|0,U=U+Math.imul(y,A0)|0,Q=Q+Math.imul(y,W0)|0,Q=Q+Math.imul(c,A0)|0,K=K+Math.imul(c,W0)|0,U=U+Math.imul(A,H0)|0,Q=Q+Math.imul(A,E0)|0,Q=Q+Math.imul(S,H0)|0,K=K+Math.imul(S,E0)|0;var h0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(h0>>>26)|0,h0&=67108863,U=Math.imul(i,V0),Q=Math.imul(i,U0),Q=Q+Math.imul(e,V0)|0,K=Math.imul(e,U0),U=U+Math.imul(m,X0)|0,Q=Q+Math.imul(m,K0)|0,Q=Q+Math.imul(r,X0)|0,K=K+Math.imul(r,K0)|0,U=U+Math.imul(t,I0)|0,Q=Q+Math.imul(t,O0)|0,Q=Q+Math.imul(s,I0)|0,K=K+Math.imul(s,O0)|0,U=U+Math.imul(l,J0)|0,Q=Q+Math.imul(l,F0)|0,Q=Q+Math.imul(n,J0)|0,K=K+Math.imul(n,F0)|0,U=U+Math.imul(h,A0)|0,Q=Q+Math.imul(h,W0)|0,Q=Q+Math.imul(d,A0)|0,K=K+Math.imul(d,W0)|0,U=U+Math.imul(y,H0)|0,Q=Q+Math.imul(y,E0)|0,Q=Q+Math.imul(c,H0)|0,K=K+Math.imul(c,E0)|0,U=U+Math.imul(A,T0)|0,Q=Q+Math.imul(A,D0)|0,Q=Q+Math.imul(S,T0)|0,K=K+Math.imul(S,D0)|0;var d0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(d0>>>26)|0,d0&=67108863,U=Math.imul(o,V0),Q=Math.imul(o,U0),Q=Q+Math.imul(a,V0)|0,K=Math.imul(a,U0),U=U+Math.imul(i,X0)|0,Q=Q+Math.imul(i,K0)|0,Q=Q+Math.imul(e,X0)|0,K=K+Math.imul(e,K0)|0,U=U+Math.imul(m,I0)|0,Q=Q+Math.imul(m,O0)|0,Q=Q+Math.imul(r,I0)|0,K=K+Math.imul(r,O0)|0,U=U+Math.imul(t,J0)|0,Q=Q+Math.imul(t,F0)|0,Q=Q+Math.imul(s,J0)|0,K=K+Math.imul(s,F0)|0,U=U+Math.imul(l,A0)|0,Q=Q+Math.imul(l,W0)|0,Q=Q+Math.imul(n,A0)|0,K=K+Math.imul(n,W0)|0,U=U+Math.imul(h,H0)|0,Q=Q+Math.imul(h,E0)|0,Q=Q+Math.imul(d,H0)|0,K=K+Math.imul(d,E0)|0,U=U+Math.imul(y,T0)|0,Q=Q+Math.imul(y,D0)|0,Q=Q+Math.imul(c,T0)|0,K=K+Math.imul(c,D0)|0,U=U+Math.imul(A,C0)|0,Q=Q+Math.imul(A,L0)|0,Q=Q+Math.imul(S,C0)|0,K=K+Math.imul(S,L0)|0;var b0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(b0>>>26)|0,b0&=67108863,U=Math.imul($0,V0),Q=Math.imul($0,U0),Q=Q+Math.imul(Q0,V0)|0,K=Math.imul(Q0,U0),U=U+Math.imul(o,X0)|0,Q=Q+Math.imul(o,K0)|0,Q=Q+Math.imul(a,X0)|0,K=K+Math.imul(a,K0)|0,U=U+Math.imul(i,I0)|0,Q=Q+Math.imul(i,O0)|0,Q=Q+Math.imul(e,I0)|0,K=K+Math.imul(e,O0)|0,U=U+Math.imul(m,J0)|0,Q=Q+Math.imul(m,F0)|0,Q=Q+Math.imul(r,J0)|0,K=K+Math.imul(r,F0)|0,U=U+Math.imul(t,A0)|0,Q=Q+Math.imul(t,W0)|0,Q=Q+Math.imul(s,A0)|0,K=K+Math.imul(s,W0)|0,U=U+Math.imul(l,H0)|0,Q=Q+Math.imul(l,E0)|0,Q=Q+Math.imul(n,H0)|0,K=K+Math.imul(n,E0)|0,U=U+Math.imul(h,T0)|0,Q=Q+Math.imul(h,D0)|0,Q=Q+Math.imul(d,T0)|0,K=K+Math.imul(d,D0)|0,U=U+Math.imul(y,C0)|0,Q=Q+Math.imul(y,L0)|0,Q=Q+Math.imul(c,C0)|0,K=K+Math.imul(c,L0)|0,U=U+Math.imul(A,R0)|0,Q=Q+Math.imul(A,z0)|0,Q=Q+Math.imul(S,R0)|0,K=K+Math.imul(S,z0)|0;var l0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(l0>>>26)|0,l0&=67108863,U=Math.imul(Z0,V0),Q=Math.imul(Z0,U0),Q=Q+Math.imul(G0,V0)|0,K=Math.imul(G0,U0),U=U+Math.imul($0,X0)|0,Q=Q+Math.imul($0,K0)|0,Q=Q+Math.imul(Q0,X0)|0,K=K+Math.imul(Q0,K0)|0,U=U+Math.imul(o,I0)|0,Q=Q+Math.imul(o,O0)|0,Q=Q+Math.imul(a,I0)|0,K=K+Math.imul(a,O0)|0,U=U+Math.imul(i,J0)|0,Q=Q+Math.imul(i,F0)|0,Q=Q+Math.imul(e,J0)|0,K=K+Math.imul(e,F0)|0,U=U+Math.imul(m,A0)|0,Q=Q+Math.imul(m,W0)|0,Q=Q+Math.imul(r,A0)|0,K=K+Math.imul(r,W0)|0,U=U+Math.imul(t,H0)|0,Q=Q+Math.imul(t,E0)|0,Q=Q+Math.imul(s,H0)|0,K=K+Math.imul(s,E0)|0,U=U+Math.imul(l,T0)|0,Q=Q+Math.imul(l,D0)|0,Q=Q+Math.imul(n,T0)|0,K=K+Math.imul(n,D0)|0,U=U+Math.imul(h,C0)|0,Q=Q+Math.imul(h,L0)|0,Q=Q+Math.imul(d,C0)|0,K=K+Math.imul(d,L0)|0,U=U+Math.imul(y,R0)|0,Q=Q+Math.imul(y,z0)|0,Q=Q+Math.imul(c,R0)|0,K=K+Math.imul(c,z0)|0,U=U+Math.imul(A,P0)|0,Q=Q+Math.imul(A,M0)|0,Q=Q+Math.imul(S,P0)|0,K=K+Math.imul(S,M0)|0;var o0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(o0>>>26)|0,o0&=67108863,U=Math.imul(Z0,X0),Q=Math.imul(Z0,K0),Q=Q+Math.imul(G0,X0)|0,K=Math.imul(G0,K0),U=U+Math.imul($0,I0)|0,Q=Q+Math.imul($0,O0)|0,Q=Q+Math.imul(Q0,I0)|0,K=K+Math.imul(Q0,O0)|0,U=U+Math.imul(o,J0)|0,Q=Q+Math.imul(o,F0)|0,Q=Q+Math.imul(a,J0)|0,K=K+Math.imul(a,F0)|0,U=U+Math.imul(i,A0)|0,Q=Q+Math.imul(i,W0)|0,Q=Q+Math.imul(e,A0)|0,K=K+Math.imul(e,W0)|0,U=U+Math.imul(m,H0)|0,Q=Q+Math.imul(m,E0)|0,Q=Q+Math.imul(r,H0)|0,K=K+Math.imul(r,E0)|0,U=U+Math.imul(t,T0)|0,Q=Q+Math.imul(t,D0)|0,Q=Q+Math.imul(s,T0)|0,K=K+Math.imul(s,D0)|0,U=U+Math.imul(l,C0)|0,Q=Q+Math.imul(l,L0)|0,Q=Q+Math.imul(n,C0)|0,K=K+Math.imul(n,L0)|0,U=U+Math.imul(h,R0)|0,Q=Q+Math.imul(h,z0)|0,Q=Q+Math.imul(d,R0)|0,K=K+Math.imul(d,z0)|0,U=U+Math.imul(y,P0)|0,Q=Q+Math.imul(y,M0)|0,Q=Q+Math.imul(c,P0)|0,K=K+Math.imul(c,M0)|0;var u0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(u0>>>26)|0,u0&=67108863,U=Math.imul(Z0,I0),Q=Math.imul(Z0,O0),Q=Q+Math.imul(G0,I0)|0,K=Math.imul(G0,O0),U=U+Math.imul($0,J0)|0,Q=Q+Math.imul($0,F0)|0,Q=Q+Math.imul(Q0,J0)|0,K=K+Math.imul(Q0,F0)|0,U=U+Math.imul(o,A0)|0,Q=Q+Math.imul(o,W0)|0,Q=Q+Math.imul(a,A0)|0,K=K+Math.imul(a,W0)|0,U=U+Math.imul(i,H0)|0,Q=Q+Math.imul(i,E0)|0,Q=Q+Math.imul(e,H0)|0,K=K+Math.imul(e,E0)|0,U=U+Math.imul(m,T0)|0,Q=Q+Math.imul(m,D0)|0,Q=Q+Math.imul(r,T0)|0,K=K+Math.imul(r,D0)|0,U=U+Math.imul(t,C0)|0,Q=Q+Math.imul(t,L0)|0,Q=Q+Math.imul(s,C0)|0,K=K+Math.imul(s,L0)|0,U=U+Math.imul(l,R0)|0,Q=Q+Math.imul(l,z0)|0,Q=Q+Math.imul(n,R0)|0,K=K+Math.imul(n,z0)|0,U=U+Math.imul(h,P0)|0,Q=Q+Math.imul(h,M0)|0,Q=Q+Math.imul(d,P0)|0,K=K+Math.imul(d,M0)|0;var n0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(n0>>>26)|0,n0&=67108863,U=Math.imul(Z0,J0),Q=Math.imul(Z0,F0),Q=Q+Math.imul(G0,J0)|0,K=Math.imul(G0,F0),U=U+Math.imul($0,A0)|0,Q=Q+Math.imul($0,W0)|0,Q=Q+Math.imul(Q0,A0)|0,K=K+Math.imul(Q0,W0)|0,U=U+Math.imul(o,H0)|0,Q=Q+Math.imul(o,E0)|0,Q=Q+Math.imul(a,H0)|0,K=K+Math.imul(a,E0)|0,U=U+Math.imul(i,T0)|0,Q=Q+Math.imul(i,D0)|0,Q=Q+Math.imul(e,T0)|0,K=K+Math.imul(e,D0)|0,U=U+Math.imul(m,C0)|0,Q=Q+Math.imul(m,L0)|0,Q=Q+Math.imul(r,C0)|0,K=K+Math.imul(r,L0)|0,U=U+Math.imul(t,R0)|0,Q=Q+Math.imul(t,z0)|0,Q=Q+Math.imul(s,R0)|0,K=K+Math.imul(s,z0)|0,U=U+Math.imul(l,P0)|0,Q=Q+Math.imul(l,M0)|0,Q=Q+Math.imul(n,P0)|0,K=K+Math.imul(n,M0)|0;var s0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(s0>>>26)|0,s0&=67108863,U=Math.imul(Z0,A0),Q=Math.imul(Z0,W0),Q=Q+Math.imul(G0,A0)|0,K=Math.imul(G0,W0),U=U+Math.imul($0,H0)|0,Q=Q+Math.imul($0,E0)|0,Q=Q+Math.imul(Q0,H0)|0,K=K+Math.imul(Q0,E0)|0,U=U+Math.imul(o,T0)|0,Q=Q+Math.imul(o,D0)|0,Q=Q+Math.imul(a,T0)|0,K=K+Math.imul(a,D0)|0,U=U+Math.imul(i,C0)|0,Q=Q+Math.imul(i,L0)|0,Q=Q+Math.imul(e,C0)|0,K=K+Math.imul(e,L0)|0,U=U+Math.imul(m,R0)|0,Q=Q+Math.imul(m,z0)|0,Q=Q+Math.imul(r,R0)|0,K=K+Math.imul(r,z0)|0,U=U+Math.imul(t,P0)|0,Q=Q+Math.imul(t,M0)|0,Q=Q+Math.imul(s,P0)|0,K=K+Math.imul(s,M0)|0;var t0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(t0>>>26)|0,t0&=67108863,U=Math.imul(Z0,H0),Q=Math.imul(Z0,E0),Q=Q+Math.imul(G0,H0)|0,K=Math.imul(G0,E0),U=U+Math.imul($0,T0)|0,Q=Q+Math.imul($0,D0)|0,Q=Q+Math.imul(Q0,T0)|0,K=K+Math.imul(Q0,D0)|0,U=U+Math.imul(o,C0)|0,Q=Q+Math.imul(o,L0)|0,Q=Q+Math.imul(a,C0)|0,K=K+Math.imul(a,L0)|0,U=U+Math.imul(i,R0)|0,Q=Q+Math.imul(i,z0)|0,Q=Q+Math.imul(e,R0)|0,K=K+Math.imul(e,z0)|0,U=U+Math.imul(m,P0)|0,Q=Q+Math.imul(m,M0)|0,Q=Q+Math.imul(r,P0)|0,K=K+Math.imul(r,M0)|0;var m0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(m0>>>26)|0,m0&=67108863,U=Math.imul(Z0,T0),Q=Math.imul(Z0,D0),Q=Q+Math.imul(G0,T0)|0,K=Math.imul(G0,D0),U=U+Math.imul($0,C0)|0,Q=Q+Math.imul($0,L0)|0,Q=Q+Math.imul(Q0,C0)|0,K=K+Math.imul(Q0,L0)|0,U=U+Math.imul(o,R0)|0,Q=Q+Math.imul(o,z0)|0,Q=Q+Math.imul(a,R0)|0,K=K+Math.imul(a,z0)|0,U=U+Math.imul(i,P0)|0,Q=Q+Math.imul(i,M0)|0,Q=Q+Math.imul(e,P0)|0,K=K+Math.imul(e,M0)|0;var a0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(a0>>>26)|0,a0&=67108863,U=Math.imul(Z0,C0),Q=Math.imul(Z0,L0),Q=Q+Math.imul(G0,C0)|0,K=Math.imul(G0,L0),U=U+Math.imul($0,R0)|0,Q=Q+Math.imul($0,z0)|0,Q=Q+Math.imul(Q0,R0)|0,K=K+Math.imul(Q0,z0)|0,U=U+Math.imul(o,P0)|0,Q=Q+Math.imul(o,M0)|0,Q=Q+Math.imul(a,P0)|0,K=K+Math.imul(a,M0)|0;var e0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(e0>>>26)|0,e0&=67108863,U=Math.imul(Z0,R0),Q=Math.imul(Z0,z0),Q=Q+Math.imul(G0,R0)|0,K=Math.imul(G0,z0),U=U+Math.imul($0,P0)|0,Q=Q+Math.imul($0,M0)|0,Q=Q+Math.imul(Q0,P0)|0,K=K+Math.imul(Q0,M0)|0;var r0=(O+U|0)+((Q&8191)<<13)|0;O=(K+(Q>>>13)|0)+(r0>>>26)|0,r0&=67108863,U=Math.imul(Z0,P0),Q=Math.imul(Z0,M0),Q=Q+Math.imul(G0,P0)|0,K=Math.imul(G0,M0);var i0=(O+U|0)+((Q&8191)<<13)|0;return O=(K+(Q>>>13)|0)+(i0>>>26)|0,i0&=67108863,I[0]=Q$,I[1]=k0,I[2]=g0,I[3]=f0,I[4]=c0,I[5]=h0,I[6]=d0,I[7]=b0,I[8]=l0,I[9]=o0,I[10]=u0,I[11]=n0,I[12]=s0,I[13]=t0,I[14]=m0,I[15]=a0,I[16]=e0,I[17]=r0,I[18]=i0,O!==0&&(I[19]=O,G.length++),G};Math.imul||(M=R);function v($,Y,G){G.negative=Y.negative^$.negative,G.length=$.length+Y.length;for(var Z=0,V=0,I=0;I>>26)|0,V+=O>>>26,O&=67108863}G.words[I]=U,Z=O,O=V}return Z!==0?G.words[I]=Z:G.length--,G.strip()}function q($,Y,G){var Z=new g;return Z.mulp($,Y,G)}X.prototype.mulTo=function($,Y){var G,Z=this.length+$.length;return this.length===10&&$.length===10?G=M(this,$,Y):Z<63?G=R(this,$,Y):Z<1024?G=v(this,$,Y):G=q(this,$,Y),G};function g($,Y){this.x=$,this.y=Y}g.prototype.makeRBT=function($){for(var Y=new Array($),G=X.prototype._countBits($)-1,Z=0;Z<$;Z++)Y[Z]=this.revBin(Z,G,$);return Y},g.prototype.revBin=function($,Y,G){if($===0||$===G-1)return $;for(var Z=0,V=0;V>=1;return Z},g.prototype.permute=function($,Y,G,Z,V,I){for(var O=0;O>>1)V++;return 1<>>13,G[2*I+1]=V&8191,V=V>>>13;for(I=2*Y;I>=26,Y+=Z/67108864|0,Y+=V>>>26,this.words[G]=V&67108863}return Y!==0&&(this.words[G]=Y,this.length++),this},X.prototype.muln=function($){return this.clone().imuln($)},X.prototype.sqr=function(){return this.mul(this)},X.prototype.isqr=function(){return this.imul(this.clone())},X.prototype.pow=function($){var Y=E($);if(Y.length===0)return new X(1);for(var G=this,Z=0;Z=0);var Y=$%26,G=($-Y)/26,Z=67108863>>>26-Y<<26-Y,V;if(Y!==0){var I=0;for(V=0;V>>26-Y}I&&(this.words[V]=I,this.length++)}if(G!==0){for(V=this.length-1;V>=0;V--)this.words[V+G]=this.words[V];for(V=0;V=0);var Z;Y?Z=(Y-Y%26)/26:Z=0;var V=$%26,I=Math.min(($-V)/26,this.length),O=67108863^67108863>>>V<I)for(this.length-=I,Q=0;Q=0&&(K!==0||Q>=Z);Q--){var L=this.words[Q]|0;this.words[Q]=K<<26-V|L>>>V,K=L&O}return U&&K!==0&&(U.words[U.length++]=K),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},X.prototype.ishrn=function($,Y,G){return F(this.negative===0),this.iushrn($,Y,G)},X.prototype.shln=function($){return this.clone().ishln($)},X.prototype.ushln=function($){return this.clone().iushln($)},X.prototype.shrn=function($){return this.clone().ishrn($)},X.prototype.ushrn=function($){return this.clone().iushrn($)},X.prototype.testn=function($){F(typeof $=="number"&&$>=0);var Y=$%26,G=($-Y)/26,Z=1<=0);var Y=$%26,G=($-Y)/26;if(F(this.negative===0,"imaskn works only with positive numbers"),this.length<=G)return this;if(Y!==0&&G++,this.length=Math.min(G,this.length),Y!==0){var Z=67108863^67108863>>>Y<=67108864;Y++)this.words[Y]-=67108864,Y===this.length-1?this.words[Y+1]=1:this.words[Y+1]++;return this.length=Math.max(this.length,Y+1),this},X.prototype.isubn=function($){if(F(typeof $=="number"),F($<67108864),$<0)return this.iaddn(-$);if(this.negative!==0)return this.negative=0,this.iaddn($),this.negative=1,this;if(this.words[0]-=$,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var Y=0;Y>26)-(U/67108864|0),this.words[V+G]=I&67108863}for(;V>26,this.words[V+G]=I&67108863;if(O===0)return this.strip();for(F(O===-1),O=0,V=0;V>26,this.words[V]=I&67108863;return this.negative=1,this.strip()},X.prototype._wordDiv=function($,Y){var G=this.length-$.length,Z=this.clone(),V=$,I=V.words[V.length-1]|0,O=this._countBits(I);G=26-O,G!==0&&(V=V.ushln(G),Z.iushln(G),I=V.words[V.length-1]|0);var U=Z.length-V.length,Q;if(Y!=="mod"){Q=new X(null),Q.length=U+1,Q.words=new Array(Q.length);for(var K=0;K=0;A--){var S=(Z.words[V.length+A]|0)*67108864+(Z.words[V.length+A-1]|0);for(S=Math.min(S/I|0,67108863),Z._ishlnsubmul(V,S,A);Z.negative!==0;)S--,Z.negative=0,Z._ishlnsubmul(V,1,A),Z.isZero()||(Z.negative^=1);Q&&(Q.words[A]=S)}return Q&&Q.strip(),Z.strip(),Y!=="div"&&G!==0&&Z.iushrn(G),{div:Q||null,mod:Z}},X.prototype.divmod=function($,Y,G){if(F(!$.isZero()),this.isZero())return{div:new X(0),mod:new X(0)};var Z,V,I;return this.negative!==0&&$.negative===0?(I=this.neg().divmod($,Y),Y!=="mod"&&(Z=I.div.neg()),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.iadd($)),{div:Z,mod:V}):this.negative===0&&$.negative!==0?(I=this.divmod($.neg(),Y),Y!=="mod"&&(Z=I.div.neg()),{div:Z,mod:I.mod}):(this.negative&$.negative)!==0?(I=this.neg().divmod($.neg(),Y),Y!=="div"&&(V=I.mod.neg(),G&&V.negative!==0&&V.isub($)),{div:I.div,mod:V}):$.length>this.length||this.cmp($)<0?{div:new X(0),mod:this}:$.length===1?Y==="div"?{div:this.divn($.words[0]),mod:null}:Y==="mod"?{div:null,mod:new X(this.modn($.words[0]))}:{div:this.divn($.words[0]),mod:new X(this.modn($.words[0]))}:this._wordDiv($,Y)},X.prototype.div=function($){return this.divmod($,"div",!1).div},X.prototype.mod=function($){return this.divmod($,"mod",!1).mod},X.prototype.umod=function($){return this.divmod($,"mod",!0).mod},X.prototype.divRound=function($){var Y=this.divmod($);if(Y.mod.isZero())return Y.div;var G=Y.div.negative!==0?Y.mod.isub($):Y.mod,Z=$.ushrn(1),V=$.andln(1),I=G.cmp(Z);return I<0||V===1&&I===0?Y.div:Y.div.negative!==0?Y.div.isubn(1):Y.div.iaddn(1)},X.prototype.modn=function($){F($<=67108863);for(var Y=(1<<26)%$,G=0,Z=this.length-1;Z>=0;Z--)G=(Y*G+(this.words[Z]|0))%$;return G},X.prototype.idivn=function($){F($<=67108863);for(var Y=0,G=this.length-1;G>=0;G--){var Z=(this.words[G]|0)+Y*67108864;this.words[G]=Z/$|0,Y=Z%$}return this.strip()},X.prototype.divn=function($){return this.clone().idivn($)},X.prototype.egcd=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=new X(0),O=new X(1),U=0;Y.isEven()&&G.isEven();)Y.iushrn(1),G.iushrn(1),++U;for(var Q=G.clone(),K=Y.clone();!Y.isZero();){for(var L=0,A=1;(Y.words[0]&A)===0&&L<26;++L,A<<=1);if(L>0)for(Y.iushrn(L);L-- >0;)(Z.isOdd()||V.isOdd())&&(Z.iadd(Q),V.isub(K)),Z.iushrn(1),V.iushrn(1);for(var S=0,x=1;(G.words[0]&x)===0&&S<26;++S,x<<=1);if(S>0)for(G.iushrn(S);S-- >0;)(I.isOdd()||O.isOdd())&&(I.iadd(Q),O.isub(K)),I.iushrn(1),O.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(I),V.isub(O)):(G.isub(Y),I.isub(Z),O.isub(V))}return{a:I,b:O,gcd:G.iushln(U)}},X.prototype._invmp=function($){F($.negative===0),F(!$.isZero());var Y=this,G=$.clone();Y.negative!==0?Y=Y.umod($):Y=Y.clone();for(var Z=new X(1),V=new X(0),I=G.clone();Y.cmpn(1)>0&&G.cmpn(1)>0;){for(var O=0,U=1;(Y.words[0]&U)===0&&O<26;++O,U<<=1);if(O>0)for(Y.iushrn(O);O-- >0;)Z.isOdd()&&Z.iadd(I),Z.iushrn(1);for(var Q=0,K=1;(G.words[0]&K)===0&&Q<26;++Q,K<<=1);if(Q>0)for(G.iushrn(Q);Q-- >0;)V.isOdd()&&V.iadd(I),V.iushrn(1);Y.cmp(G)>=0?(Y.isub(G),Z.isub(V)):(G.isub(Y),V.isub(Z))}var L;return Y.cmpn(1)===0?L=Z:L=V,L.cmpn(0)<0&&L.iadd($),L},X.prototype.gcd=function($){if(this.isZero())return $.abs();if($.isZero())return this.abs();var Y=this.clone(),G=$.clone();Y.negative=0,G.negative=0;for(var Z=0;Y.isEven()&&G.isEven();Z++)Y.iushrn(1),G.iushrn(1);do{for(;Y.isEven();)Y.iushrn(1);for(;G.isEven();)G.iushrn(1);var V=Y.cmp(G);if(V<0){var I=Y;Y=G,G=I}else if(V===0||G.cmpn(1)===0)break;Y.isub(G)}while(!0);return G.iushln(Z)},X.prototype.invm=function($){return this.egcd($).a.umod($)},X.prototype.isEven=function(){return(this.words[0]&1)===0},X.prototype.isOdd=function(){return(this.words[0]&1)===1},X.prototype.andln=function($){return this.words[0]&$},X.prototype.bincn=function($){F(typeof $=="number");var Y=$%26,G=($-Y)/26,Z=1<>>26,O&=67108863,this.words[I]=O}return V!==0&&(this.words[I]=V,this.length++),this},X.prototype.isZero=function(){return this.length===1&&this.words[0]===0},X.prototype.cmpn=function($){var Y=$<0;if(this.negative!==0&&!Y)return-1;if(this.negative===0&&Y)return 1;this.strip();var G;if(this.length>1)G=1;else{Y&&($=-$),F($<=67108863,"Number is too big");var Z=this.words[0]|0;G=Z===$?0:Z<$?-1:1}return this.negative!==0?-G|0:G},X.prototype.cmp=function($){if(this.negative!==0&&$.negative===0)return-1;if(this.negative===0&&$.negative!==0)return 1;var Y=this.ucmp($);return this.negative!==0?-Y|0:Y},X.prototype.ucmp=function($){if(this.length>$.length)return 1;if(this.length<$.length)return-1;for(var Y=0,G=this.length-1;G>=0;G--){var Z=this.words[G]|0,V=$.words[G]|0;if(Z!==V){ZV&&(Y=1);break}}return Y},X.prototype.gtn=function($){return this.cmpn($)===1},X.prototype.gt=function($){return this.cmp($)===1},X.prototype.gten=function($){return this.cmpn($)>=0},X.prototype.gte=function($){return this.cmp($)>=0},X.prototype.ltn=function($){return this.cmpn($)===-1},X.prototype.lt=function($){return this.cmp($)===-1},X.prototype.lten=function($){return this.cmpn($)<=0},X.prototype.lte=function($){return this.cmp($)<=0},X.prototype.eqn=function($){return this.cmpn($)===0},X.prototype.eq=function($){return this.cmp($)===0},X.red=function($){return new p($)},X.prototype.toRed=function($){return F(!this.red,"Already a number in reduction context"),F(this.negative===0,"red works only with positives"),$.convertTo(this)._forceRed($)},X.prototype.fromRed=function(){return F(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},X.prototype._forceRed=function($){return this.red=$,this},X.prototype.forceRed=function($){return F(!this.red,"Already a number in reduction context"),this._forceRed($)},X.prototype.redAdd=function($){return F(this.red,"redAdd works only with red numbers"),this.red.add(this,$)},X.prototype.redIAdd=function($){return F(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,$)},X.prototype.redSub=function($){return F(this.red,"redSub works only with red numbers"),this.red.sub(this,$)},X.prototype.redISub=function($){return F(this.red,"redISub works only with red numbers"),this.red.isub(this,$)},X.prototype.redShl=function($){return F(this.red,"redShl works only with red numbers"),this.red.shl(this,$)},X.prototype.redMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.mul(this,$)},X.prototype.redIMul=function($){return F(this.red,"redMul works only with red numbers"),this.red._verify2(this,$),this.red.imul(this,$)},X.prototype.redSqr=function(){return F(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},X.prototype.redISqr=function(){return F(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},X.prototype.redSqrt=function(){return F(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},X.prototype.redInvm=function(){return F(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},X.prototype.redNeg=function(){return F(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},X.prototype.redPow=function($){return F(this.red&&!$.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,$)};var B={k256:null,p224:null,p192:null,p25519:null};function w($,Y){this.name=$,this.p=new X(Y,16),this.n=this.p.bitLength(),this.k=new X(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}w.prototype._tmp=function(){var $=new X(null);return $.words=new Array(Math.ceil(this.n/13)),$},w.prototype.ireduce=function($){var Y=$,G;do this.split(Y,this.tmp),Y=this.imulK(Y),Y=Y.iadd(this.tmp),G=Y.bitLength();while(G>this.n);var Z=G0?Y.isub(this.p):Y.strip!==void 0?Y.strip():Y._strip(),Y},w.prototype.split=function($,Y){$.iushrn(this.n,0,Y)},w.prototype.imulK=function($){return $.imul(this.k)};function f(){w.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}P(f,w),f.prototype.split=function($,Y){for(var G=4194303,Z=Math.min($.length,9),V=0;V>>22,I=O}I>>>=22,$.words[V-10]=I,I===0&&$.length>10?$.length-=10:$.length-=9},f.prototype.imulK=function($){$.words[$.length]=0,$.words[$.length+1]=0,$.length+=2;for(var Y=0,G=0;G<$.length;G++){var Z=$.words[G]|0;Y+=Z*977,$.words[G]=Y&67108863,Y=Z*64+(Y/67108864|0)}return $.words[$.length-1]===0&&($.length--,$.words[$.length-1]===0&&$.length--),$};function b(){w.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}P(b,w);function u(){w.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}P(u,w);function Y0(){w.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}P(Y0,w),Y0.prototype.imulK=function($){for(var Y=0,G=0;G<$.length;G++){var Z=($.words[G]|0)*19+Y,V=Z&67108863;Z>>>=26,$.words[G]=V,Y=Z}return Y!==0&&($.words[$.length++]=Y),$},X._prime=function($){if(B[$])return B[$];var Y;if($==="k256")Y=new f;else if($==="p224")Y=new b;else if($==="p192")Y=new u;else if($==="p25519")Y=new Y0;else throw new Error("Unknown prime "+$);return B[$]=Y,Y};function p($){if(typeof $=="string"){var Y=X._prime($);this.m=Y.p,this.prime=Y}else F($.gtn(1),"modulus must be greater than 1"),this.m=$,this.prime=null}p.prototype._verify1=function($){F($.negative===0,"red works only with positives"),F($.red,"red works only with red numbers")},p.prototype._verify2=function($,Y){F(($.negative|Y.negative)===0,"red works only with positives"),F($.red&&$.red===Y.red,"red works only with red numbers")},p.prototype.imod=function($){return this.prime?this.prime.ireduce($)._forceRed(this):$.umod(this.m)._forceRed(this)},p.prototype.neg=function($){return $.isZero()?$.clone():this.m.sub($)._forceRed(this)},p.prototype.add=function($,Y){this._verify2($,Y);var G=$.add(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G._forceRed(this)},p.prototype.iadd=function($,Y){this._verify2($,Y);var G=$.iadd(Y);return G.cmp(this.m)>=0&&G.isub(this.m),G},p.prototype.sub=function($,Y){this._verify2($,Y);var G=$.sub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G._forceRed(this)},p.prototype.isub=function($,Y){this._verify2($,Y);var G=$.isub(Y);return G.cmpn(0)<0&&G.iadd(this.m),G},p.prototype.shl=function($,Y){return this._verify1($),this.imod($.ushln(Y))},p.prototype.imul=function($,Y){return this._verify2($,Y),this.imod($.imul(Y))},p.prototype.mul=function($,Y){return this._verify2($,Y),this.imod($.mul(Y))},p.prototype.isqr=function($){return this.imul($,$.clone())},p.prototype.sqr=function($){return this.mul($,$)},p.prototype.sqrt=function($){if($.isZero())return $.clone();var Y=this.m.andln(3);if(F(Y%2===1),Y===3){var G=this.m.add(new X(1)).iushrn(2);return this.pow($,G)}for(var Z=this.m.subn(1),V=0;!Z.isZero()&&Z.andln(1)===0;)V++,Z.iushrn(1);F(!Z.isZero());var I=new X(1).toRed(this),O=I.redNeg(),U=this.m.subn(1).iushrn(1),Q=this.m.bitLength();for(Q=new X(2*Q*Q).toRed(this);this.pow(Q,U).cmp(O)!==0;)Q.redIAdd(O);for(var K=this.pow(Q,Z),L=this.pow($,Z.addn(1).iushrn(1)),A=this.pow($,Z),S=V;A.cmp(I)!==0;){for(var x=A,y=0;x.cmp(I)!==0;y++)x=x.redSqr();F(y=0;V--){for(var K=Y.words[V],L=Q-1;L>=0;L--){var A=K>>L&1;if(I!==Z[0]&&(I=this.sqr(I)),A===0&&O===0){U=0;continue}O<<=1,O|=A,U++,!(U!==G&&(V!==0||L!==0))&&(I=this.mul(I,Z[O]),U=0,O=0)}Q=26}return I},p.prototype.convertTo=function($){var Y=$.umod(this.m);return Y===$?Y.clone():Y},p.prototype.convertFrom=function($){var Y=$.clone();return Y.red=null,Y},X.mont=function($){return new v0($)};function v0($){p.call(this,$),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new X(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}P(v0,p),v0.prototype.convertTo=function($){return this.imod($.ushln(this.shift))},v0.prototype.convertFrom=function($){var Y=this.imod($.mul(this.rinv));return Y.red=null,Y},v0.prototype.imul=function($,Y){if($.isZero()||Y.isZero())return $.words[0]=0,$.length=1,$;var G=$.imul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.mul=function($,Y){if($.isZero()||Y.isZero())return new X(0)._forceRed(this);var G=$.mul(Y),Z=G.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),V=G.isub(Z).iushrn(this.shift),I=V;return V.cmp(this.m)>=0?I=V.isub(this.m):V.cmpn(0)<0&&(I=V.iadd(this.m)),I._forceRed(this)},v0.prototype.invm=function($){var Y=this.imod($._invmp(this.m).mul(this.r2));return Y._forceRed(this)}})(typeof _>"u"||_,N)}}),{CryptoHasher:$Z}=globalThis.Bun,cQ=S0({"node_modules/public-encrypt/withPublic.js"(N,_){var j=m$(),k=N0().Buffer;function F(P,X){return k.from(P.toRed(j.mont(X.modulus)).redPow(new j(X.publicExponent)).fromRed().toArray())}_.exports=F}}),QZ=S0({"node_modules/public-encrypt/publicEncrypt.js"(N,_){var j=_$(),k=L$(),F=M$(),P=pQ(),X=fQ(),C=m$(),z=cQ(),T=d$(),H=N0().Buffer;_.exports=function(E,R,M){var v;E.padding?v=E.padding:M?v=1:v=4;var q=j(E),g;if(v===4)g=J(q,R);else if(v===1)g=W(q,R,M);else if(v===3){if(g=new C(R),g.cmp(q.modulus)>=0)throw new Error("data too long for modulus")}else throw new Error("unknown padding");return M?T(g,q):z(g,q)};function J(E,R){var M=E.modulus.byteLength(),v=R.length,q=F("sha1").update(H.alloc(0)).digest(),g=q.length,B=2*g;if(v>M-B-2)throw new Error("message too long");var w=H.alloc(M-v-B-2),f=M-g-1,b=k(g),u=X(H.concat([q,w,H.alloc(1,1),R],f),P(b,f)),Y0=X(b,P(u,g));return new C(H.concat([H.alloc(1),Y0,u],M))}function W(E,R,M){var v=R.length,q=E.modulus.byteLength();if(v>q-11)throw new Error("message too long");var g;return M?g=H.alloc(q-v-3,255):g=D(q-v-3),new C(H.concat([H.from([0,M?1:2]),g,H.alloc(1),R],q))}function D(E){for(var R=H.allocUnsafe(E),M=0,v=k(E*2),q=0,g;Mq||new P(E).cmp(v.modulus)>=0)throw new Error("decryption error");var g;R?g=z(new P(E),v):g=X(E,v);var B=T.alloc(q-g.length);if(g=T.concat([B,g],q),M===4)return H(v,g);if(M===1)return J(v,g,R);if(M===3)return g;throw new Error("unknown padding")};function H(D,E){var R=D.modulus.byteLength(),M=C("sha1").update(T.alloc(0)).digest(),v=M.length;if(E[0]!==0)throw new Error("decryption error");var q=E.slice(1,v+1),g=E.slice(v+1),B=F(q,k(g,v)),w=F(g,k(B,R-v-1));if(W(M,w.slice(0,v)))throw new Error("decryption error");for(var f=v;w[f]===0;)f++;if(w[f++]!==1)throw new Error("decryption error");return w.slice(f)}function J(D,E,R){for(var M=E.slice(0,2),v=2,q=0;E[v++]!==0;)if(v>=E.length){q++;break}var g=E.slice(2,v-1);if((M.toString("hex")!=="0002"&&!R||M.toString("hex")!=="0001"&&R)&&q++,g.length<8&&q++,q)throw new Error("decryption error");return E.slice(v)}function W(D,E){D=T.from(D),E=T.from(E);var R=0,M=D.length;D.length!==E.length&&(R++,M=Math.min(D.length,E.length));for(var v=-1;++vP||J<0)throw new TypeError("offset must be a uint32");if(J>F||J>W)throw new RangeError("offset out of range")}function C(J,W,D){if(typeof J!="number"||J!==J)throw new TypeError("size must be a number");if(J>P||J<0)throw new TypeError("size must be a uint32");if(J+W>D||J>F)throw new RangeError("buffer too small")}N.randomFill=z,N.randomFillSync=H;function z(J,W,D,E){if(!k.isBuffer(J)&&!(J instanceof global.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if(typeof W=="function")E=W,W=0,D=J.length;else if(typeof D=="function")E=D,D=J.length-W;else if(typeof E!="function")throw new TypeError('"cb" argument must be a function');return X(W,J.length),C(D,W,J.length),T(J,W,D,E)}function T(J,W,D,E){if(E){j(D,function(M,v){if(M)return E(M);v.copy(J,W),E(null,J)});return}var R=j(D);return R.copy(J,W),J}function H(J,W,D){if(typeof W>"u"&&(W=0),!k.isBuffer(J)&&!(J instanceof global.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');return X(W,J.length),D===void 0&&(D=J.length-W),C(D,W,J.length),T(J,W,D)}}}),VZ=S0({"node_modules/crypto-browserify/index.js"(N){N.randomBytes=N.rng=N.pseudoRandomBytes=N.prng=L$(),N.createHash=M$(),N.Hash=N.createHash.Hash,N.createHmac=N.Hmac=IQ();var _=QY(),j=Object.keys(_),k=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(j);N.getHashes=function(){return k};var F=HQ();N.pbkdf2=F.pbkdf2,N.pbkdf2Sync=F.pbkdf2Sync;var P=TY();N.Cipher=P.Cipher,N.createCipher=P.createCipher,N.Cipheriv=P.Cipheriv,N.createCipheriv=P.createCipheriv,N.Decipher=P.Decipher,N.createDecipher=P.createDecipher,N.Decipheriv=P.Decipheriv,N.createDecipheriv=P.createDecipheriv,N.getCiphers=P.getCiphers,N.listCiphers=P.listCiphers;var X=RY();N.DiffieHellmanGroup=X.DiffieHellmanGroup,N.createDiffieHellmanGroup=X.createDiffieHellmanGroup,N.getDiffieHellman=X.getDiffieHellman,N.createDiffieHellman=X.createDiffieHellman,N.DiffieHellman=X.DiffieHellman;var C=eY();N.createSign=C.createSign,N.Sign=C.Sign,N.createVerify=C.createVerify,N.Verify=C.Verify,N.createECDH=iY();var z=ZZ();N.publicEncrypt=z.publicEncrypt,N.privateEncrypt=z.privateEncrypt,N.publicDecrypt=z.publicDecrypt,N.privateDecrypt=z.privateDecrypt,N.getRandomValues=(H)=>W$.getRandomValues(H);var T=GZ();N.randomFill=T.randomFill,N.randomFillSync=T.randomFillSync,N.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join(` -`))},N.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}}}),a$={...VZ(),[Symbol.for("CommonJS")]:0},P$="buffer",UZ=(N)=>W$.getRandomValues(N),XZ=()=>W$.randomUUID(),KZ=(...N)=>W$.randomInt(...N),y$="timingSafeEqual"in W$?(N,_)=>{let{byteLength:j}=N,{byteLength:k}=_;if(typeof j!="number"||typeof k!="number")throw new TypeError("Input must be an array buffer view");if(j!==k)throw new RangeError("Input buffers must have the same length");return W$.timingSafeEqual(N,_)}:void 0,hQ="scryptSync"in W$?(N,_,j,k)=>{let F=W$.scryptSync(N,_,j,k);return P$!=="buffer"?new j0(F).toString(P$):new j0(F)}:void 0,dQ="scryptSync"in W$?function(N,_,j,k,F){if(typeof k=="function"&&(F=k,k=void 0),typeof F!="function"){var P=new TypeError("callback must be a function");throw P.code="ERR_INVALID_CALLBACK",P}try{let X=W$.scryptSync(N,_,j,k);process.nextTick(F,null,P$!=="buffer"?new j0(X).toString(P$):new j0(X))}catch(X){throw X}}:void 0;y$&&(Object.defineProperty(y$,"name",{value:"::bunternal::"}),Object.defineProperty(dQ,"name",{value:"::bunternal::"}),Object.defineProperty(hQ,"name",{value:"::bunternal::"}));var IZ=["p192","p224","p256","p384","p521","curve25519","ed25519","secp256k1","secp224r1","prime256v1","prime192v1","ed25519","secp384r1","secp521r1"],r$=W$;mQ(a$,{DEFAULT_ENCODING:()=>P$,getRandomValues:()=>UZ,randomUUID:()=>XZ,randomInt:()=>KZ,getCurves:()=>OZ,scrypt:()=>dQ,scryptSync:()=>hQ,timingSafeEqual:()=>y$,webcrypto:()=>r$,subtle:()=>r$.subtle});var{randomBytes:WZ,rng:HZ,pseudoRandomBytes:EZ,prng:TZ,Hash:DZ,createHash:CZ,createHmac:LZ,Hmac:RZ,getHashes:zZ,pbkdf2:PZ,pbkdf2Sync:MZ,Cipher:SZ,createCipher:vZ,Cipheriv:qZ,createCipheriv:jZ,Decipher:kZ,createDecipher:gZ,Decipheriv:_Z,createDecipheriv:NZ,getCiphers:xZ,listCiphers:BZ,DiffieHellmanGroup:yZ,createDiffieHellmanGroup:wZ,getDiffieHellman:pZ,createDiffieHellman:fZ,DiffieHellman:cZ,createSign:hZ,Sign:dZ,createVerify:bZ,Verify:lZ,createECDH:oZ,publicEncrypt:uZ,privateEncrypt:nZ,publicDecrypt:sZ,privateDecrypt:tZ,randomFill:mZ,randomFillSync:aZ,createCredentials:eZ,constants:rZ}=a$;var $G=a$;/*! safe-buffer. MIT License. Feross Aboukhadijeh */export{r$ as webcrypto,y$ as timingSafeEqual,hQ as scryptSync,dQ as scrypt,HZ as rng,XZ as randomUUID,KZ as randomInt,aZ as randomFillSync,mZ as randomFill,WZ as randomBytes,uZ as publicEncrypt,sZ as publicDecrypt,EZ as pseudoRandomBytes,TZ as prng,nZ as privateEncrypt,tZ as privateDecrypt,MZ as pbkdf2Sync,PZ as pbkdf2,BZ as listCiphers,UZ as getRandomValues,zZ as getHashes,pZ as getDiffieHellman,OZ as getCurves,xZ as getCiphers,$G as default,bZ as createVerify,hZ as createSign,LZ as createHmac,CZ as createHash,oZ as createECDH,wZ as createDiffieHellmanGroup,fZ as createDiffieHellman,NZ as createDecipheriv,gZ as createDecipher,eZ as createCredentials,jZ as createCipheriv,vZ as createCipher,rZ as constants,lZ as Verify,dZ as Sign,RZ as Hmac,DZ as Hash,yZ as DiffieHellmanGroup,cZ as DiffieHellman,_Z as Decipheriv,kZ as Decipher,P$ as DEFAULT_ENCODING,qZ as Cipheriv,SZ as Cipher}; diff --git a/src/js/out/modules/node/dgram.js b/src/js/out/modules/node/dgram.js deleted file mode 100644 index 776e80253e2353..00000000000000 --- a/src/js/out/modules/node/dgram.js +++ /dev/null @@ -1,38 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/dgram.ts -var createSocket = function() { - throwNotImplemented("node:dgram createSocket", 1630); -}, Socket = function() { - throwNotImplemented("node:dgram Socket", 1630); -}, _createSocketHandle = function() { - throwNotImplemented("node:dgram _createSocketHandle", 1630); -}, defaultObject = { - createSocket, - Socket, - _createSocketHandle, - [Symbol.for("CommonJS")]: 0 -}; -hideFromStack(createSocket, Socket, _createSocketHandle); -export { - defaultObject as default, - createSocket, - _createSocketHandle, - Socket -}; diff --git a/src/js/out/modules/node/diagnostics_channel.js b/src/js/out/modules/node/diagnostics_channel.js deleted file mode 100644 index f4d9d990c78fa4..00000000000000 --- a/src/js/out/modules/node/diagnostics_channel.js +++ /dev/null @@ -1,51 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/diagnostics_channel.js -var channel = function() { - throwNotImplemented("node:diagnostics_channel", 2688); -}, hasSubscribers = function() { - throwNotImplemented("node:diagnostics_channel", 2688); -}, subscribe = function() { - throwNotImplemented("node:diagnostics_channel", 2688); -}, unsubscribe = function() { - throwNotImplemented("node:diagnostics_channel", 2688); -}; - -class Channel { - constructor(name) { - throwNotImplemented("node:diagnostics_channel", 2688); - } -} -var defaultObject = { - channel, - hasSubscribers, - subscribe, - unsubscribe, - Channel, - [Symbol.for("CommonJS")]: 0 -}; -hideFromStack([channel, hasSubscribers, subscribe, unsubscribe, Channel]); -export { - unsubscribe, - subscribe, - hasSubscribers, - defaultObject as default, - channel, - Channel -}; diff --git a/src/js/out/modules/node/dns.js b/src/js/out/modules/node/dns.js deleted file mode 100644 index bbbc94cba1a33a..00000000000000 --- a/src/js/out/modules/node/dns.js +++ /dev/null @@ -1,535 +0,0 @@ -var lookup = function(domain, options, callback) { - if (typeof options == "function") - callback = options; - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - if (typeof options == "number") - options = { family: options }; - dns.lookup(domain, options).then((res) => { - if (res.sort((a, b) => a.family - b.family), options?.all) - callback(null, res.map(mapLookupAll)); - else { - const [{ address, family }] = res; - callback(null, address, family); - } - }, (error) => { - callback(error); - }); -}, resolveSrv = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveSrv(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolveTxt = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveTxt(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolveSoa = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveSoa(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolveNaptr = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveNaptr(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolveMx = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveMx(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolveCaa = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveCaa(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolveNs = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveNs(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolvePtr = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolvePtr(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, resolveCname = function(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveCname(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); -}, lookupService = function(address, port, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - callback(null, address, port); -}, resolve = function(hostname, rrtype, callback) { - if (typeof rrtype == "function") - callback = rrtype; - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolve(hostname).then((results) => { - switch (rrtype?.toLowerCase()) { - case "a": - case "aaaa": - callback(null, hostname, results.map(({ address }) => address)); - break; - default: - callback(null, results); - break; - } - }, (error) => { - callback(error); - }); -}, Resolver = function(options) { - return new InternalResolver(options); -}, setDefaultResultOrder = function() { -}, setServers = function() { -}, { dns } = globalThis.Bun, InternalResolver = class Resolver2 { - constructor(options) { - } - cancel() { - } - getServers() { - return []; - } - resolve(hostname, rrtype, callback) { - if (typeof rrtype == "function") - callback = rrtype, rrtype = null; - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolve(hostname).then((results) => { - switch (rrtype?.toLowerCase()) { - case "a": - case "aaaa": - callback(null, hostname, results.map(mapResolveX)); - break; - default: - callback(null, results); - break; - } - }, (error) => { - callback(error); - }); - } - resolve4(hostname, options, callback) { - if (typeof options == "function") - callback = options, options = null; - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.lookup(hostname, { family: 4 }).then((addresses) => { - callback(null, options?.ttl ? addresses : addresses.map(mapResolveX)); - }, (error) => { - callback(error); - }); - } - resolve6(hostname, options, callback) { - if (typeof options == "function") - callback = options, options = null; - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.lookup(hostname, { family: 6 }).then((addresses) => { - callback(null, options?.ttl ? addresses : addresses.map(({ address }) => address)); - }, (error) => { - callback(error); - }); - } - resolveAny(hostname, callback) { - callback(null, []); - } - resolveCname(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveCname(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolveMx(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveMx(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolveNaptr(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveNaptr(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolveNs(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveNs(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolvePtr(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolvePtr(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolveSrv(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveSrv(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolveCaa(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveCaa(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolveTxt(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveTxt(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - resolveSoa(hostname, callback) { - if (typeof callback != "function") - throw new TypeError("callback must be a function"); - dns.resolveSoa(hostname, callback).then((results) => { - callback(null, results); - }, (error) => { - callback(error); - }); - } - reverse(ip, callback) { - callback(null, []); - } - setServers(servers) { - } -}; -Object.setPrototypeOf(Resolver.prototype, InternalResolver.prototype); -Object.setPrototypeOf(Resolver, InternalResolver); -var { - resolve, - resolve4, - resolve6, - resolveAny, - resolveCname, - resolveCaa, - resolveMx, - resolveNaptr, - resolveNs, - resolvePtr, - resolveSoa, - resolveSrv, - reverse, - resolveTxt -} = InternalResolver.prototype, promisifyLookup = (res) => { - res.sort((a, b) => a.family - b.family); - const [{ address, family }] = res; - return { address, family }; -}, mapLookupAll = (res) => { - const { address, family } = res; - return { address, family }; -}, promisifyLookupAll = (res) => { - return res.sort((a, b) => a.family - b.family), res.map(mapLookupAll); -}, mapResolveX = (a) => a.address, promisifyResolveX = (res) => { - return res?.map(mapResolveX); -}, promises = { - lookup(domain, options) { - if (options?.all) - return dns.lookup(domain, options).then(promisifyLookupAll); - return dns.lookup(domain, options).then(promisifyLookup); - }, - lookupService(address, port) { - return Promise.resolve([]); - }, - resolve(hostname, rrtype) { - if (typeof rrtype !== "string") - rrtype = null; - switch (rrtype?.toLowerCase()) { - case "a": - case "aaaa": - return dns.resolve(hostname, rrtype).then(promisifyLookup); - default: - return dns.resolve(hostname, rrtype); - } - }, - resolve4(hostname, options) { - if (options?.ttl) - return dns.lookup(hostname, { family: 4 }); - return dns.lookup(hostname, { family: 4 }).then(promisifyResolveX); - }, - resolve6(hostname, options) { - if (options?.ttl) - return dns.lookup(hostname, { family: 6 }); - return dns.lookup(hostname, { family: 6 }).then(promisifyResolveX); - }, - resolveSrv(hostname) { - return dns.resolveSrv(hostname); - }, - resolveTxt(hostname) { - return dns.resolveTxt(hostname); - }, - resolveSoa(hostname) { - return dns.resolveSoa(hostname); - }, - resolveNaptr(hostname) { - return dns.resolveNaptr(hostname); - }, - resolveMx(hostname) { - return dns.resolveMx(hostname); - }, - resolveCaa(hostname) { - return dns.resolveCaa(hostname); - }, - resolveNs(hostname) { - return dns.resolveNs(hostname); - }, - resolvePtr(hostname) { - return dns.resolvePtr(hostname); - }, - resolveCname(hostname) { - return dns.resolveCname(hostname); - }, - Resolver: class Resolver3 { - constructor(options) { - } - cancel() { - } - getServers() { - return []; - } - resolve(hostname, rrtype) { - if (typeof rrtype !== "string") - rrtype = null; - switch (rrtype?.toLowerCase()) { - case "a": - case "aaaa": - return dns.resolve(hostname, rrtype).then(promisifyLookup); - default: - return dns.resolve(hostname, rrtype); - } - } - resolve4(hostname, options) { - if (options?.ttl) - return dns.lookup(hostname, { family: 4 }); - return dns.lookup(hostname, { family: 4 }).then(promisifyResolveX); - } - resolve6(hostname, options) { - if (options?.ttl) - return dns.lookup(hostname, { family: 6 }); - return dns.lookup(hostname, { family: 6 }).then(promisifyResolveX); - } - resolveAny(hostname) { - return Promise.resolve([]); - } - resolveCname(hostname) { - return dns.resolveCname(hostname); - } - resolveMx(hostname) { - return dns.resolveMx(hostname); - } - resolveNaptr(hostname) { - return dns.resolveNaptr(hostname); - } - resolveNs(hostname) { - return dns.resolveNs(hostname); - } - resolvePtr(hostname) { - return dns.resolvePtr(hostname); - } - resolveSoa(hostname) { - return dns.resolveSoa(hostname); - } - resolveSrv(hostname) { - return dns.resolveSrv(hostname); - } - resolveCaa(hostname) { - return dns.resolveCaa(hostname); - } - resolveTxt(hostname) { - return dns.resolveTxt(hostname); - } - reverse(ip) { - return Promise.resolve([]); - } - setServers(servers) { - } - } -}; -for (let key of ["resolveAny", "reverse"]) - promises[key] = () => Promise.resolve(void 0); -var exports = { - ADDRCONFIG: 0, - ALL: 1, - V4MAPPED: 2, - NODATA: "DNS_ENODATA", - FORMERR: "DNS_EFORMERR", - SERVFAIL: "DNS_ESERVFAIL", - NOTFOUND: "DNS_ENOTFOUND", - NOTIMP: "DNS_ENOTIMP", - REFUSED: "DNS_EREFUSED", - BADQUERY: "DNS_EBADQUERY", - BADNAME: "DNS_EBADNAME", - BADFAMILY: "DNS_EBADFAMILY", - BADRESP: "DNS_EBADRESP", - CONNREFUSED: "DNS_ECONNREFUSED", - TIMEOUT: "DNS_ETIMEOUT", - EOF: "DNS_EEOF", - FILE: "DNS_EFILE", - NOMEM: "DNS_ENOMEM", - DESTRUCTION: "DNS_EDESTRUCTION", - BADSTR: "DNS_EBADSTR", - BADFLAGS: "DNS_EBADFLAGS", - NONAME: "DNS_ENONAME", - BADHINTS: "DNS_EBADHINTS", - NOTINITIALIZED: "DNS_ENOTINITIALIZED", - LOADIPHLPAPI: "DNS_ELOADIPHLPAPI", - ADDRGETNETWORKPARAMS: "DNS_EADDRGETNETWORKPARAMS", - CANCELLED: "DNS_ECANCELLED", - lookup, - lookupService, - Resolver, - setServers, - setDefaultResultOrder, - resolve, - reverse, - resolve4, - resolve6, - resolveAny, - resolveCname, - resolveCaa, - resolveMx, - resolveNs, - resolvePtr, - resolveSoa, - resolveSrv, - resolveTxt, - resolveNaptr, - promises, - [Symbol.for("CommonJS")]: 0 -}, dns_default = exports, { - ADDRCONFIG, - ALL, - V4MAPPED, - NODATA, - FORMERR, - SERVFAIL, - NOTFOUND, - NOTIMP, - REFUSED, - BADQUERY, - BADNAME, - BADFAMILY, - BADRESP, - CONNREFUSED, - TIMEOUT, - EOF, - FILE, - NOMEM, - DESTRUCTION, - BADSTR, - BADFLAGS, - NONAME, - BADHINTS, - NOTINITIALIZED, - LOADIPHLPAPI, - ADDRGETNETWORKPARAMS, - CANCELLED -} = exports; -export { - setServers, - setDefaultResultOrder, - reverse, - resolveTxt, - resolveSrv, - resolveSoa, - resolvePtr, - resolveNs, - resolveNaptr, - resolveMx, - resolveCname, - resolveCaa, - resolveAny, - resolve6, - resolve4, - resolve, - promises, - lookupService, - lookup, - dns_default as default, - V4MAPPED, - TIMEOUT, - SERVFAIL, - Resolver, - REFUSED, - NOTINITIALIZED, - NOTIMP, - NOTFOUND, - NONAME, - NOMEM, - NODATA, - LOADIPHLPAPI, - FORMERR, - FILE, - EOF, - DESTRUCTION, - CONNREFUSED, - CANCELLED, - BADSTR, - BADRESP, - BADQUERY, - BADNAME, - BADHINTS, - BADFLAGS, - BADFAMILY, - ALL, - ADDRGETNETWORKPARAMS, - ADDRCONFIG -}; diff --git a/src/js/out/modules/node/dns.promises.js b/src/js/out/modules/node/dns.promises.js deleted file mode 100644 index dde4a128051f04..00000000000000 --- a/src/js/out/modules/node/dns.promises.js +++ /dev/null @@ -1,65 +0,0 @@ -import {promises} from "node:dns"; -var { - lookup, - lookupService, - resolve, - resolve4, - resolve6, - resolveAny, - resolveCname, - resolveCaa, - resolveMx, - resolveNaptr, - resolveNs, - resolvePtr, - resolveSoa, - resolveSrv, - resolveTxt, - reverse, - Resolver, - setServers, - setDefaultResultOrder -} = promises, dns_promises_default = { - lookup, - lookupService, - resolve, - resolve4, - resolve6, - resolveAny, - resolveCname, - resolveCaa, - resolveMx, - resolveNaptr, - resolveNs, - resolvePtr, - resolveSoa, - resolveSrv, - resolveTxt, - reverse, - Resolver, - setServers, - setDefaultResultOrder, - [Symbol.for("CommonJS")]: 0 -}; -export { - setServers, - setDefaultResultOrder, - reverse, - resolveTxt, - resolveSrv, - resolveSoa, - resolvePtr, - resolveNs, - resolveNaptr, - resolveMx, - resolveCname, - resolveCaa, - resolveAny, - resolve6, - resolve4, - resolve, - lookupService, - lookup, - dns_promises_default as default, - Resolver -}; diff --git a/src/js/out/modules/node/events.js b/src/js/out/modules/node/events.js deleted file mode 100644 index 21704b36d15b32..00000000000000 --- a/src/js/out/modules/node/events.js +++ /dev/null @@ -1,364 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/events.js -var EventEmitter = function(opts) { - if (this._events === void 0 || this._events === this.__proto__._events) - this._events = { __proto__: null }, this._eventsCount = 0; - if (this._maxListeners ??= void 0, this[kCapture] = opts?.captureRejections ? Boolean(opts?.captureRejections) : EventEmitterPrototype[kCapture]) - this.emit = emitWithRejectionCapture; -}, emitError = function(emitter, args) { - var { _events: events } = emitter; - if (args[0] ??= new Error("Unhandled error."), !events) - throw args[0]; - var errorMonitor = events[kErrorMonitor]; - if (errorMonitor) - for (var handler of ArrayPrototypeSlice.call(errorMonitor)) - handler.apply(emitter, args); - var handlers = events.error; - if (!handlers) - throw args[0]; - for (var handler of ArrayPrototypeSlice.call(handlers)) - handler.apply(emitter, args); - return !0; -}, addCatch = function(emitter, promise, type, args) { - promise.then(void 0, function(err) { - process.nextTick(emitUnhandledRejectionOrErr, emitter, err, type, args); - }); -}, emitUnhandledRejectionOrErr = function(emitter, err, type, args) { - if (typeof emitter[kRejection] === "function") - emitter[kRejection](err, type, ...args); - else - try { - emitter[kCapture] = !1, emitter.emit("error", err); - } finally { - emitter[kCapture] = !0; - } -}, overflowWarning = function(emitter, type, handlers) { - handlers.warned = !0; - const warn = new Error(`Possible EventEmitter memory leak detected. ${handlers.length} ${String(type)} listeners ` + `added to [${emitter.constructor.name}]. Use emitter.setMaxListeners() to increase limit`); - warn.name = "MaxListenersExceededWarning", warn.emitter = emitter, warn.type = type, warn.count = handlers.length, process.emitWarning(warn); -}, onceWrapper = function(type, listener, ...args) { - this.removeListener(type, listener), listener.apply(this, args); -}, once = function(emitter, type, options) { - var signal = options?.signal; - if (validateAbortSignal(signal, "options.signal"), signal?.aborted) - throw new AbortError(void 0, { cause: signal?.reason }); - return new Promise((resolve, reject) => { - const errorListener = (err) => { - if (emitter.removeListener(type, resolver), signal != null) - eventTargetAgnosticRemoveListener(signal, "abort", abortListener); - reject(err); - }, resolver = (...args) => { - if (typeof emitter.removeListener === "function") - emitter.removeListener("error", errorListener); - if (signal != null) - eventTargetAgnosticRemoveListener(signal, "abort", abortListener); - resolve(args); - }; - if (eventTargetAgnosticAddListener(emitter, type, resolver, { once: !0 }), type !== "error" && typeof emitter.once === "function") - emitter.once("error", errorListener); - function abortListener() { - eventTargetAgnosticRemoveListener(emitter, type, resolver), eventTargetAgnosticRemoveListener(emitter, "error", errorListener), reject(new AbortError(void 0, { cause: signal?.reason })); - } - if (signal != null) - eventTargetAgnosticAddListener(signal, "abort", abortListener, { once: !0 }); - }); -}, on = function(emitter, type, options) { - var { signal, close, highWatermark = Number.MAX_SAFE_INTEGER, lowWatermark = 1 } = options || {}; - throwNotImplemented("events.on", 2679); -}, getEventListeners = function(emitter, type) { - if (emitter instanceof EventTarget) - throwNotImplemented("getEventListeners with an EventTarget", 2678); - return emitter.listeners(type); -}, setMaxListeners = function(n, ...eventTargets) { - validateNumber(n, "setMaxListeners", 0); - var length; - if (eventTargets && (length = eventTargets.length)) - for (let i = 0;i < length; i++) - eventTargets[i].setMaxListeners(n); - else - defaultMaxListeners = n; -}, listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}, eventTargetAgnosticRemoveListener = function(emitter, name, listener, flags) { - if (typeof emitter.removeListener === "function") - emitter.removeListener(name, listener); - else - emitter.removeEventListener(name, listener, flags); -}, eventTargetAgnosticAddListener = function(emitter, name, listener, flags) { - if (typeof emitter.on === "function") - emitter.on(name, listener); - else - emitter.addEventListener(name, listener); -}, ERR_INVALID_ARG_TYPE = function(name, type, value) { - const err = new TypeError(`The "${name}" argument must be of type ${type}. Received ${value}`); - return err.code = "ERR_INVALID_ARG_TYPE", err; -}, ERR_OUT_OF_RANGE = function(name, range, value) { - const err = new RangeError(`The "${name}" argument is out of range. It must be ${range}. Received ${value}`); - return err.code = "ERR_OUT_OF_RANGE", err; -}, validateAbortSignal = function(signal, name) { - if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) - throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal); -}, validateNumber = function(value, name, min = void 0, max) { - if (typeof value !== "number") - throw new ERR_INVALID_ARG_TYPE(name, "number", value); - if (min != null && value < min || max != null && value > max || (min != null || max != null) && Number.isNaN(value)) - throw new ERR_OUT_OF_RANGE(name, `${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`, value); -}, checkListener = function(listener) { - if (typeof listener !== "function") - throw new TypeError("The listener must be a function"); -}, { isPromise, Array, Object: Object2 } = globalThis[Symbol.for("Bun.lazy")]("primordials"), SymbolFor = Symbol.for, ObjectDefineProperty = Object2.defineProperty, kCapture = Symbol("kCapture"), kErrorMonitor = SymbolFor("events.errorMonitor"), kMaxEventTargetListeners = Symbol("events.maxEventTargetListeners"), kMaxEventTargetListenersWarned = Symbol("events.maxEventTargetListenersWarned"), kWatermarkData = SymbolFor("nodejs.watermarkData"), kRejection = SymbolFor("nodejs.rejection"), captureRejectionSymbol = SymbolFor("nodejs.rejection"), ArrayPrototypeSlice = Array.prototype.slice, defaultMaxListeners = 10, EventEmitterPrototype = EventEmitter.prototype; -EventEmitterPrototype._events = void 0; -EventEmitterPrototype._eventsCount = 0; -EventEmitterPrototype._maxListeners = void 0; -EventEmitterPrototype.setMaxListeners = function setMaxListeners2(n) { - return validateNumber(n, "setMaxListeners", 0), this._maxListeners = n, this; -}; -EventEmitterPrototype.getMaxListeners = function getMaxListeners() { - return this._maxListeners ?? defaultMaxListeners; -}; -var emitWithoutRejectionCapture = function emit(type, ...args) { - if (type === "error") - return emitError(this, args); - var { _events: events } = this; - if (events === void 0) - return !1; - var handlers = events[type]; - if (handlers === void 0) - return !1; - for (var handler of [...handlers]) - handler.apply(this, args); - return !0; -}, emitWithRejectionCapture = function emit2(type, ...args) { - if (type === "error") - return emitError(this, args); - var { _events: events } = this; - if (events === void 0) - return !1; - var handlers = events[type]; - if (handlers === void 0) - return !1; - for (var handler of [...handlers]) { - var result = handler.apply(this, args); - if (result !== void 0 && isPromise(result)) - addCatch(this, result, type, args); - } - return !0; -}; -EventEmitterPrototype.emit = emitWithoutRejectionCapture; -EventEmitterPrototype.addListener = function addListener(type, fn) { - checkListener(fn); - var events = this._events; - if (!events) - events = this._events = { __proto__: null }, this._eventsCount = 0; - else if (events.newListener) - this.emit("newListener", type, fn.listener ?? fn); - var handlers = events[type]; - if (!handlers) - events[type] = [fn], this._eventsCount++; - else { - handlers.push(fn); - var m = this._maxListeners ?? defaultMaxListeners; - if (m > 0 && handlers.length > m && !handlers.warned) - overflowWarning(this, type, handlers); - } - return this; -}; -EventEmitterPrototype.on = EventEmitterPrototype.addListener; -EventEmitterPrototype.prependListener = function prependListener(type, fn) { - checkListener(fn); - var events = this._events; - if (!events) - events = this._events = { __proto__: null }, this._eventsCount = 0; - else if (events.newListener) - this.emit("newListener", type, fn.listener ?? fn); - var handlers = events[type]; - if (!handlers) - events[type] = [fn], this._eventsCount++; - else { - handlers.unshift(fn); - var m = this._maxListeners ?? defaultMaxListeners; - if (m > 0 && handlers.length > m && !handlers.warned) - overflowWarning(this, type, handlers); - } - return this; -}; -EventEmitterPrototype.once = function once2(type, fn) { - checkListener(fn); - const bound = onceWrapper.bind(this, type, fn); - return bound.listener = fn, this.addListener(type, bound), this; -}; -EventEmitterPrototype.prependOnceListener = function prependOnceListener(type, fn) { - checkListener(fn); - const bound = onceWrapper.bind(this, type, fn); - return bound.listener = fn, this.prependListener(type, bound), this; -}; -EventEmitterPrototype.removeListener = function removeListener(type, fn) { - checkListener(fn); - var { _events: events } = this; - if (!events) - return this; - var handlers = events[type]; - if (!handlers) - return this; - var length = handlers.length; - let position = -1; - for (let i = length - 1;i >= 0; i--) - if (handlers[i] === fn || handlers[i].listener === fn) { - position = i; - break; - } - if (position < 0) - return this; - if (position === 0) - handlers.shift(); - else - handlers.splice(position, 1); - if (handlers.length === 0) - delete events[type], this._eventsCount--; - return this; -}; -EventEmitterPrototype.off = EventEmitterPrototype.removeListener; -EventEmitterPrototype.removeAllListeners = function removeAllListeners(type) { - var { _events: events } = this; - if (type && events) { - if (events[type]) - delete events[type], this._eventsCount--; - } else - this._events = { __proto__: null }; - return this; -}; -EventEmitterPrototype.listeners = function listeners(type) { - var { _events: events } = this; - if (!events) - return []; - var handlers = events[type]; - if (!handlers) - return []; - return handlers.map((x) => x.listener ?? x); -}; -EventEmitterPrototype.rawListeners = function rawListeners(type) { - var { _events } = this; - if (!_events) - return []; - var handlers = _events[type]; - if (!handlers) - return []; - return handlers.slice(); -}; -EventEmitterPrototype.listenerCount = function listenerCount2(type) { - var { _events: events } = this; - if (!events) - return 0; - return events[type]?.length ?? 0; -}; -EventEmitterPrototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; -}; -EventEmitterPrototype[kCapture] = !1; -EventEmitter.once = once; -EventEmitter.on = on; -EventEmitter.getEventListeners = getEventListeners; -EventEmitter.setMaxListeners = setMaxListeners; -EventEmitter.listenerCount = listenerCount; -EventEmitter.EventEmitter = EventEmitter; -EventEmitter.usingDomains = !1; -EventEmitter.captureRejectionSymbol = captureRejectionSymbol; -ObjectDefineProperty(EventEmitter, "captureRejections", { - __proto__: null, - get() { - return EventEmitterPrototype[kCapture]; - }, - set(value) { - validateBoolean(value, "EventEmitter.captureRejections"), EventEmitterPrototype[kCapture] = value; - }, - enumerable: !0 -}); -EventEmitter.errorMonitor = kErrorMonitor; -Object2.defineProperties(EventEmitter, { - defaultMaxListeners: { - enumerable: !0, - get: () => { - return defaultMaxListeners; - }, - set: (arg) => { - validateNumber(arg, "defaultMaxListeners", 0), defaultMaxListeners = arg; - } - }, - kMaxEventTargetListeners: { - __proto__: null, - value: kMaxEventTargetListeners, - enumerable: !1, - configurable: !1, - writable: !1 - }, - kMaxEventTargetListenersWarned: { - __proto__: null, - value: kMaxEventTargetListenersWarned, - enumerable: !1, - configurable: !1, - writable: !1 - } -}); -EventEmitter.init = EventEmitter; -EventEmitter[Symbol.for("CommonJS")] = 0; - -class AbortError extends Error { - constructor(message = "The operation was aborted", options = void 0) { - if (options !== void 0 && typeof options !== "object") - throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options); - super(message, options); - this.code = "ABORT_ERR", this.name = "AbortError"; - } -} -var AsyncResource = null; - -class EventEmitterAsyncResource extends EventEmitter { - triggerAsyncId; - asyncResource; - constructor(options) { - if (!AsyncResource) - AsyncResource = import.meta.require("async_hooks").AsyncResource; - var { captureRejections = !1, triggerAsyncId, name = new.target.name, requireManualDestroy } = options || {}; - super({ captureRejections }); - this.triggerAsyncId = triggerAsyncId ?? 0, this.asyncResource = new AsyncResource(name, { triggerAsyncId, requireManualDestroy }); - } - emit(...args) { - this.asyncResource.runInAsyncScope(() => super.emit(...args)); - } - emitDestroy() { - this.asyncResource.emitDestroy(); - } -} -var usingDomains = !1; -Object2.assign(EventEmitter, { once, on, getEventListeners, setMaxListeners, listenerCount, EventEmitterAsyncResource }); -var events_default = EventEmitter; -export { - usingDomains, - setMaxListeners, - once, - on, - listenerCount, - getEventListeners, - kErrorMonitor as errorMonitor, - events_default as default, - captureRejectionSymbol, - EventEmitterAsyncResource, - EventEmitter -}; diff --git a/src/js/out/modules/node/fs.js b/src/js/out/modules/node/fs.js deleted file mode 100644 index b7457f104a79be..00000000000000 --- a/src/js/out/modules/node/fs.js +++ /dev/null @@ -1,763 +0,0 @@ -import {EventEmitter} from "node:events"; -import promises2 from "node:fs/promises"; -import {default as default2} from "node:fs/promises"; -import * as Stream from "node:stream"; -var callbackify = function(fsFunction, args) { - try { - const result = fsFunction.apply(fs, args.slice(0, args.length - 1)), callback = args[args.length - 1]; - if (typeof callback === "function") - queueMicrotask(() => callback(null, result)); - } catch (e) { - const callback = args[args.length - 1]; - if (typeof callback === "function") - queueMicrotask(() => callback(e)); - } -}; -function createReadStream(path, options) { - return new ReadStream(path, options); -} -function createWriteStream(path, options) { - return new WriteStream(path, options); -} -import {constants} from "node:fs/promises"; -var ReadStream, WriteStream, { direct, isPromise, isCallable } = globalThis[Symbol.for("Bun.lazy")]("primordials"), fs = Bun.fs(), debug = process.env.DEBUG ? console.log : () => { -}; - -class FSWatcher extends EventEmitter { - #watcher; - #listener; - constructor(path, options, listener) { - super(); - if (typeof options === "function") - listener = options, options = {}; - else if (typeof options === "string") - options = { encoding: options }; - if (typeof listener !== "function") - listener = () => { - }; - this.#listener = listener; - try { - this.#watcher = fs.watch(path, options || {}, this.#onEvent.bind(this)); - } catch (e) { - if (!e.message?.startsWith("FileNotFound")) - throw e; - const notFound = new Error(`ENOENT: no such file or directory, watch '${path}'`); - throw notFound.code = "ENOENT", notFound.errno = -2, notFound.path = path, notFound.syscall = "watch", notFound.filename = path, notFound; - } - } - #onEvent(eventType, filenameOrError) { - if (eventType === "error" || eventType === "close") - this.emit(eventType, filenameOrError); - else - this.emit("change", eventType, filenameOrError), this.#listener(eventType, filenameOrError); - } - close() { - this.#watcher?.close(), this.#watcher = null; - } - ref() { - this.#watcher?.ref(); - } - unref() { - this.#watcher?.unref(); - } -} -var access = function access2(...args) { - callbackify(fs.accessSync, args); -}, appendFile = function appendFile2(...args) { - callbackify(fs.appendFileSync, args); -}, close = function close2(...args) { - callbackify(fs.closeSync, args); -}, rm = function rm2(...args) { - callbackify(fs.rmSync, args); -}, rmdir = function rmdir2(...args) { - callbackify(fs.rmdirSync, args); -}, copyFile = function copyFile2(...args) { - callbackify(fs.copyFileSync, args); -}, exists = function exists2(...args) { - callbackify(fs.existsSync, args); -}, chown = function chown2(...args) { - callbackify(fs.chownSync, args); -}, chmod = function chmod2(...args) { - callbackify(fs.chmodSync, args); -}, fchmod = function fchmod2(...args) { - callbackify(fs.fchmodSync, args); -}, fchown = function fchown2(...args) { - callbackify(fs.fchownSync, args); -}, fstat = function fstat2(...args) { - callbackify(fs.fstatSync, args); -}, fsync = function fsync2(...args) { - callbackify(fs.fsyncSync, args); -}, ftruncate = function ftruncate2(...args) { - callbackify(fs.ftruncateSync, args); -}, futimes = function futimes2(...args) { - callbackify(fs.futimesSync, args); -}, lchmod = function lchmod2(...args) { - callbackify(fs.lchmodSync, args); -}, lchown = function lchown2(...args) { - callbackify(fs.lchownSync, args); -}, link = function link2(...args) { - callbackify(fs.linkSync, args); -}, lstat = function lstat2(...args) { - callbackify(fs.lstatSync, args); -}, mkdir = function mkdir2(...args) { - callbackify(fs.mkdirSync, args); -}, mkdtemp = function mkdtemp2(...args) { - callbackify(fs.mkdtempSync, args); -}, open = function open2(...args) { - callbackify(fs.openSync, args); -}, read = function read2(...args) { - callbackify(fs.readSync, args); -}, write = function write2(...args) { - callbackify(fs.writeSync, args); -}, readdir = function readdir2(...args) { - callbackify(fs.readdirSync, args); -}, readFile = function readFile2(...args) { - callbackify(fs.readFileSync, args); -}, writeFile = function writeFile2(...args) { - callbackify(fs.writeFileSync, args); -}, readlink = function readlink2(...args) { - callbackify(fs.readlinkSync, args); -}, realpath = function realpath2(...args) { - callbackify(fs.realpathSync, args); -}, rename = function rename2(...args) { - callbackify(fs.renameSync, args); -}, stat = function stat2(...args) { - callbackify(fs.statSync, args); -}, symlink = function symlink2(...args) { - callbackify(fs.symlinkSync, args); -}, truncate = function truncate2(...args) { - callbackify(fs.truncateSync, args); -}, unlink = function unlink2(...args) { - callbackify(fs.unlinkSync, args); -}, utimes = function utimes2(...args) { - callbackify(fs.utimesSync, args); -}, lutimes = function lutimes2(...args) { - callbackify(fs.lutimesSync, args); -}, accessSync = fs.accessSync.bind(fs), appendFileSync = fs.appendFileSync.bind(fs), closeSync = fs.closeSync.bind(fs), copyFileSync = fs.copyFileSync.bind(fs), existsSync = fs.existsSync.bind(fs), chownSync = fs.chownSync.bind(fs), chmodSync = fs.chmodSync.bind(fs), fchmodSync = fs.fchmodSync.bind(fs), fchownSync = fs.fchownSync.bind(fs), fstatSync = fs.fstatSync.bind(fs), fsyncSync = fs.fsyncSync.bind(fs), ftruncateSync = fs.ftruncateSync.bind(fs), futimesSync = fs.futimesSync.bind(fs), lchmodSync = fs.lchmodSync.bind(fs), lchownSync = fs.lchownSync.bind(fs), linkSync = fs.linkSync.bind(fs), lstatSync = fs.lstatSync.bind(fs), mkdirSync = fs.mkdirSync.bind(fs), mkdtempSync = fs.mkdtempSync.bind(fs), openSync = fs.openSync.bind(fs), readSync = fs.readSync.bind(fs), writeSync = fs.writeSync.bind(fs), readdirSync = fs.readdirSync.bind(fs), readFileSync = fs.readFileSync.bind(fs), writeFileSync = fs.writeFileSync.bind(fs), readlinkSync = fs.readlinkSync.bind(fs), realpathSync = fs.realpathSync.bind(fs), renameSync = fs.renameSync.bind(fs), statSync = fs.statSync.bind(fs), symlinkSync = fs.symlinkSync.bind(fs), truncateSync = fs.truncateSync.bind(fs), unlinkSync = fs.unlinkSync.bind(fs), utimesSync = fs.utimesSync.bind(fs), lutimesSync = fs.lutimesSync.bind(fs), rmSync = fs.rmSync.bind(fs), rmdirSync = fs.rmdirSync.bind(fs), writev = (fd, buffers, position, callback) => { - if (typeof position === "function") - callback = position, position = null; - queueMicrotask(() => { - try { - var written = fs.writevSync(fd, buffers, position); - } catch (e) { - callback(e); - } - callback(null, written, buffers); - }); -}, writevSync = fs.writevSync.bind(fs), readv = (fd, buffers, position, callback) => { - if (typeof position === "function") - callback = position, position = null; - queueMicrotask(() => { - try { - var written = fs.readvSync(fd, buffers, position); - } catch (e) { - callback(e); - } - callback(null, written, buffers); - }); -}, readvSync = fs.readvSync.bind(fs), Dirent = fs.Dirent, Stats = fs.Stats, watch = function watch2(path, options, listener) { - return new FSWatcher(path, options, listener); -}, readStreamPathFastPathSymbol = Symbol.for("Bun.Node.readStreamPathFastPath"), readStreamSymbol = Symbol.for("Bun.NodeReadStream"), readStreamPathOrFdSymbol = Symbol.for("Bun.NodeReadStreamPathOrFd"), writeStreamSymbol = Symbol.for("Bun.NodeWriteStream"), writeStreamPathFastPathSymbol = Symbol.for("Bun.NodeWriteStreamFastPath"), writeStreamPathFastPathCallSymbol = Symbol.for("Bun.NodeWriteStreamFastPathCall"), kIoDone = Symbol.for("kIoDone"), defaultReadStreamOptions = { - file: void 0, - fd: void 0, - flags: "r", - encoding: void 0, - mode: 438, - autoClose: !0, - emitClose: !0, - start: 0, - end: Infinity, - highWaterMark: 65536, - fs: { - read, - open: (path, flags, mode, cb) => { - var fd; - try { - fd = openSync(path, flags, mode); - } catch (e) { - cb(e); - return; - } - cb(null, fd); - }, - openSync, - close - }, - autoDestroy: !0 -}, ReadStreamClass; -ReadStream = function(InternalReadStream) { - return ReadStreamClass = InternalReadStream, Object.defineProperty(ReadStreamClass.prototype, Symbol.toStringTag, { - value: "ReadStream", - enumerable: !1 - }), Object.defineProperty(function ReadStream(path, options) { - return new InternalReadStream(path, options); - }, Symbol.hasInstance, { - value(instance) { - return instance instanceof InternalReadStream; - } - }); -}(class ReadStream2 extends Stream._getNativeReadableStreamPrototype(2, Stream.Readable) { - constructor(pathOrFd, options = defaultReadStreamOptions) { - if (typeof options !== "object" || !options) - throw new TypeError("Expected options to be an object"); - var { - flags = defaultReadStreamOptions.flags, - encoding = defaultReadStreamOptions.encoding, - mode = defaultReadStreamOptions.mode, - autoClose = defaultReadStreamOptions.autoClose, - emitClose = defaultReadStreamOptions.emitClose, - start = defaultReadStreamOptions.start, - end = defaultReadStreamOptions.end, - autoDestroy = defaultReadStreamOptions.autoClose, - fs: fs2 = defaultReadStreamOptions.fs, - highWaterMark = defaultReadStreamOptions.highWaterMark - } = options; - if (pathOrFd?.constructor?.name === "URL") - pathOrFd = Bun.fileURLToPath(pathOrFd); - var tempThis = {}; - if (typeof pathOrFd === "string") { - if (pathOrFd.startsWith("file://")) - pathOrFd = Bun.fileURLToPath(pathOrFd); - if (pathOrFd.length === 0) - throw new TypeError("Expected path to be a non-empty string"); - tempThis.path = tempThis.file = tempThis[readStreamPathOrFdSymbol] = pathOrFd; - } else if (typeof pathOrFd === "number") { - if (pathOrFd |= 0, pathOrFd < 0) - throw new TypeError("Expected fd to be a positive integer"); - tempThis.fd = tempThis[readStreamPathOrFdSymbol] = pathOrFd, tempThis.autoClose = !1; - } else - throw new TypeError("Expected a path or file descriptor"); - if (!tempThis.fd) - tempThis.fd = fs2.openSync(pathOrFd, flags, mode); - var fileRef = Bun.file(tempThis.fd), stream = fileRef.stream(), native = direct(stream); - if (!native) - throw debug("no native readable stream"), new Error("no native readable stream"); - var { stream: ptr } = native; - super(ptr, { - ...options, - encoding, - autoDestroy, - autoClose, - emitClose, - highWaterMark - }); - if (Object.assign(this, tempThis), this.#fileRef = fileRef, this.end = end, this._read = this.#internalRead, this.start = start, this.flags = flags, this.mode = mode, this.emitClose = emitClose, this[readStreamPathFastPathSymbol] = start === 0 && end === Infinity && autoClose && fs2 === defaultReadStreamOptions.fs && (encoding === "buffer" || encoding === "binary" || encoding == null || encoding === "utf-8" || encoding === "utf8"), this._readableState.autoClose = autoDestroy = autoClose, this._readableState.highWaterMark = highWaterMark, start !== void 0) - this.pos = start; - } - #fileRef; - #fs; - file; - path; - fd = null; - flags; - mode; - start; - end; - pos; - bytesRead = 0; - #fileSize = -1; - _read; - [readStreamSymbol] = !0; - [readStreamPathOrFdSymbol]; - [readStreamPathFastPathSymbol]; - _construct(callback) { - if (super._construct) - super._construct(callback); - else - callback(); - this.emit("open", this.fd), this.emit("ready"); - } - _destroy(err, cb) { - super._destroy(err, cb); - try { - var fd = this.fd; - if (this[readStreamPathFastPathSymbol] = !1, !fd) - cb(err); - else - this.#fs.close(fd, (er) => { - cb(er || err); - }), this.fd = null; - } catch (e) { - throw e; - } - } - close(cb) { - if (typeof cb === "function") - eos_()(this, cb); - this.destroy(); - } - push(chunk) { - var bytesRead = chunk?.length ?? 0; - if (bytesRead > 0) { - this.bytesRead += bytesRead; - var currPos = this.pos; - if (currPos !== void 0) { - if (this.bytesRead < currPos) - return !0; - if (currPos === this.start) { - var n = this.bytesRead - currPos; - chunk = chunk.slice(-n); - var [_, ...rest] = arguments; - if (this.pos = this.bytesRead, this.end && this.bytesRead >= this.end) - chunk = chunk.slice(0, this.end - this.start); - return super.push(chunk, ...rest); - } - var end = this.end; - if (end && this.bytesRead >= end) { - chunk = chunk.slice(0, end - currPos); - var [_, ...rest] = arguments; - return this.pos = this.bytesRead, super.push(chunk, ...rest); - } - this.pos = this.bytesRead; - } - } - return super.push(...arguments); - } - #internalRead(n) { - var { pos, end, bytesRead, fd, encoding } = this; - if (n = pos !== void 0 ? Math.min(end - pos + 1, n) : Math.min(end - bytesRead + 1, n), debug("n @ fs.ReadStream.#internalRead, after clamp", n), n <= 0) { - this.push(null); - return; - } - if (this.#fileSize === -1 && bytesRead === 0 && pos === void 0) { - var stat3 = fstatSync(fd); - if (this.#fileSize = stat3.size, this.#fileSize > 0 && n > this.#fileSize) - n = this.#fileSize + 1; - debug("fileSize", this.#fileSize); - } - this[kIoDone] = !1; - var res = super._read(n); - if (debug("res -- undefined? why?", res), isPromise(res)) { - var then = res?.then; - if (then && isCallable(then)) - then(() => { - if (this[kIoDone] = !0, this.destroyed) - this.emit(kIoDone); - }, (er) => { - this[kIoDone] = !0, this.#errorOrDestroy(er); - }); - } else if (this[kIoDone] = !0, this.destroyed) - this.emit(kIoDone), this.#errorOrDestroy(new Error("ERR_STREAM_PREMATURE_CLOSE")); - } - #errorOrDestroy(err, sync = null) { - var { - _readableState: r = { destroyed: !1, autoDestroy: !1 }, - _writableState: w = { destroyed: !1, autoDestroy: !1 } - } = this; - if (w?.destroyed || r?.destroyed) - return this; - if (r?.autoDestroy || w?.autoDestroy) - this.destroy(err); - else if (err) - this.emit("error", err); - } - pause() { - return this[readStreamPathFastPathSymbol] = !1, super.pause(); - } - resume() { - return this[readStreamPathFastPathSymbol] = !1, super.resume(); - } - unshift(...args) { - return this[readStreamPathFastPathSymbol] = !1, super.unshift(...args); - } - pipe(dest, pipeOpts) { - if (this[readStreamPathFastPathSymbol] && (pipeOpts?.end ?? !0) && this._readableState?.pipes?.length === 0) { - if ((writeStreamPathFastPathSymbol in dest) && dest[writeStreamPathFastPathSymbol]) { - if (dest[writeStreamPathFastPathCallSymbol](this, pipeOpts)) - return this; - } - } - return this[readStreamPathFastPathSymbol] = !1, super.pipe(dest, pipeOpts); - } -}); -var defaultWriteStreamOptions = { - fd: null, - start: void 0, - pos: void 0, - encoding: void 0, - flags: "w", - mode: 438, - fs: { - write, - close, - open, - openSync - } -}, WriteStreamClass; -WriteStream = function(InternalWriteStream) { - return WriteStreamClass = InternalWriteStream, Object.defineProperty(WriteStreamClass.prototype, Symbol.toStringTag, { - value: "WritesStream", - enumerable: !1 - }), Object.defineProperty(function WriteStream(path, options) { - return new InternalWriteStream(path, options); - }, Symbol.hasInstance, { - value(instance) { - return instance instanceof InternalWriteStream; - } - }); -}(class WriteStream2 extends Stream.NativeWritable { - constructor(path, options = defaultWriteStreamOptions) { - if (!options) - throw new TypeError("Expected options to be an object"); - var { - fs: fs2 = defaultWriteStreamOptions.fs, - start = defaultWriteStreamOptions.start, - flags = defaultWriteStreamOptions.flags, - mode = defaultWriteStreamOptions.mode, - autoClose = !0, - emitClose = !1, - autoDestroy = autoClose, - encoding = defaultWriteStreamOptions.encoding, - fd = defaultWriteStreamOptions.fd, - pos = defaultWriteStreamOptions.pos - } = options, tempThis = {}; - if (typeof path === "string") { - if (path.length === 0) - throw new TypeError("Expected a non-empty path"); - if (path.startsWith("file:")) - path = Bun.fileURLToPath(path); - tempThis.path = path, tempThis.fd = null, tempThis[writeStreamPathFastPathSymbol] = autoClose && (start === void 0 || start === 0) && fs2.write === defaultWriteStreamOptions.fs.write && fs2.close === defaultWriteStreamOptions.fs.close; - } else - tempThis.fd = fd, tempThis[writeStreamPathFastPathSymbol] = !1; - if (!tempThis.fd) - tempThis.fd = fs2.openSync(path, flags, mode); - super(tempThis.fd, { - ...options, - decodeStrings: !1, - autoDestroy, - emitClose, - fd: tempThis - }); - if (Object.assign(this, tempThis), typeof fs2?.write !== "function") - throw new TypeError("Expected fs.write to be a function"); - if (typeof fs2?.close !== "function") - throw new TypeError("Expected fs.close to be a function"); - if (typeof fs2?.open !== "function") - throw new TypeError("Expected fs.open to be a function"); - if (typeof path === "object" && path) { - if (path instanceof URL) - path = Bun.fileURLToPath(path); - } - if (typeof path !== "string" && typeof fd !== "number") - throw new TypeError("Expected a path or file descriptor"); - if (this.start = start, this.#fs = fs2, this.flags = flags, this.mode = mode, this.start !== void 0) - this.pos = this.start; - if (encoding !== defaultWriteStreamOptions.encoding) { - if (this.setDefaultEncoding(encoding), encoding !== "buffer" && encoding !== "utf8" && encoding !== "utf-8" && encoding !== "binary") - this[writeStreamPathFastPathSymbol] = !1; - } - } - get autoClose() { - return this._writableState.autoDestroy; - } - set autoClose(val) { - this._writableState.autoDestroy = val; - } - destroySoon = this.end; - open() { - } - path; - fd; - flags; - mode; - #fs; - bytesWritten = 0; - pos; - [writeStreamPathFastPathSymbol]; - [writeStreamSymbol] = !0; - start; - [writeStreamPathFastPathCallSymbol](readStream, pipeOpts) { - if (!this[writeStreamPathFastPathSymbol]) - return !1; - if (this.fd !== null) - return this[writeStreamPathFastPathSymbol] = !1, !1; - return this[kIoDone] = !1, readStream[kIoDone] = !1, Bun.write(this[writeStreamPathFastPathSymbol], readStream[readStreamPathOrFdSymbol]).then((bytesWritten) => { - readStream[kIoDone] = this[kIoDone] = !0, this.bytesWritten += bytesWritten, readStream.bytesRead += bytesWritten, this.end(), readStream.close(); - }, (err) => { - readStream[kIoDone] = this[kIoDone] = !0, this.#errorOrDestroy(err), readStream.emit("error", err); - }); - } - isBunFastPathEnabled() { - return this[writeStreamPathFastPathSymbol]; - } - disableBunFastPath() { - this[writeStreamPathFastPathSymbol] = !1; - } - #handleWrite(er, bytes) { - if (er) - return this.#errorOrDestroy(er); - this.bytesWritten += bytes; - } - #internalClose(err, cb) { - this[writeStreamPathFastPathSymbol] = !1; - var fd = this.fd; - this.#fs.close(fd, (er) => { - this.fd = null, cb(err || er); - }); - } - _construct(callback) { - if (typeof this.fd === "number") { - callback(); - return; - } - callback(), this.emit("open", this.fd), this.emit("ready"); - } - _destroy(err, cb) { - if (this.fd === null) - return cb(err); - if (this[kIoDone]) { - this.once(kIoDone, () => this.#internalClose(err, cb)); - return; - } - this.#internalClose(err, cb); - } - [kIoDone] = !1; - close(cb) { - if (cb) { - if (this.closed) { - process.nextTick(cb); - return; - } - this.on("close", cb); - } - if (!this.autoClose) - this.on("finish", this.destroy); - this.end(); - } - write(chunk, encoding = this._writableState.defaultEncoding, cb) { - if (this[writeStreamPathFastPathSymbol] = !1, typeof chunk === "string") - chunk = Buffer.from(chunk, encoding); - var native = this.pos === void 0; - return this[kIoDone] = !0, super.write(chunk, encoding, native ? (err, bytes) => { - if (this[kIoDone] = !1, this.#handleWrite(err, bytes), this.emit(kIoDone), cb) - !err ? cb() : cb(err); - } : () => { - }, native); - } - #internalWriteSlow(chunk, encoding, cb) { - this.#fs.write(this.fd, chunk, 0, chunk.length, this.pos, (err, bytes) => { - this[kIoDone] = !1, this.#handleWrite(err, bytes), this.emit(kIoDone), !err ? cb() : cb(err); - }); - } - end(chunk, encoding, cb) { - var native = this.pos === void 0; - return super.end(chunk, encoding, cb, native); - } - _write = this.#internalWriteSlow; - _writev = void 0; - get pending() { - return this.fd === null; - } - _destroy(err, cb) { - this.close(err, cb); - } - #errorOrDestroy(err) { - var { - _readableState: r = { destroyed: !1, autoDestroy: !1 }, - _writableState: w = { destroyed: !1, autoDestroy: !1 } - } = this; - if (w?.destroyed || r?.destroyed) - return this; - if (r?.autoDestroy || w?.autoDestroy) - this.destroy(err); - else if (err) - this.emit("error", err); - } -}); -Object.defineProperties(fs, { - createReadStream: { - value: createReadStream - }, - createWriteStream: { - value: createWriteStream - }, - ReadStream: { - value: ReadStream - }, - WriteStream: { - value: WriteStream - } -}); -realpath.native = realpath; -realpathSync.native = realpathSync; -var fs_default = { - [Symbol.for("CommonJS")]: 0, - access, - accessSync, - appendFile, - appendFileSync, - chmod, - chmodSync, - chown, - chownSync, - close, - closeSync, - constants: promises2.constants, - copyFile, - copyFileSync, - createReadStream, - createWriteStream, - Dirent, - exists, - existsSync, - fchmod, - fchmodSync, - fchown, - fchownSync, - fstat, - fstatSync, - fsync, - fsyncSync, - ftruncate, - ftruncateSync, - futimes, - futimesSync, - lchmod, - lchmodSync, - lchown, - lchownSync, - link, - linkSync, - lstat, - lstatSync, - lutimes, - lutimesSync, - mkdir, - mkdirSync, - mkdtemp, - mkdtempSync, - open, - openSync, - promises: promises2, - read, - readFile, - readFileSync, - readSync, - readdir, - readdirSync, - readlink, - readlinkSync, - realpath, - realpathSync, - rename, - renameSync, - rm, - rmSync, - rmdir, - rmdirSync, - stat, - statSync, - Stats, - symlink, - symlinkSync, - truncate, - truncateSync, - unlink, - unlinkSync, - utimes, - utimesSync, - write, - writeFile, - writeFileSync, - writeSync, - WriteStream, - ReadStream, - watch, - FSWatcher, - writev, - writevSync, - readv, - readvSync, - [Symbol.for("::bunternal::")]: { - ReadStreamClass, - WriteStreamClass - } -}; -export { - writevSync, - writev, - writeSync, - writeFileSync, - writeFile, - write, - watch, - utimesSync, - utimes, - unlinkSync, - unlink, - truncateSync, - truncate, - symlinkSync, - symlink, - statSync, - stat, - rmdirSync, - rmdir, - rmSync, - rm, - renameSync, - rename, - realpathSync, - realpath, - readvSync, - readv, - readlinkSync, - readlink, - readdirSync, - readdir, - readSync, - readFileSync, - readFile, - read, - default2 as promises, - openSync, - open, - mkdtempSync, - mkdtemp, - mkdirSync, - mkdir, - lutimesSync, - lutimes, - lstatSync, - lstat, - linkSync, - link, - lchownSync, - lchown, - lchmodSync, - lchmod, - futimesSync, - futimes, - ftruncateSync, - ftruncate, - fsyncSync, - fsync, - fstatSync, - fstat, - fchownSync, - fchown, - fchmodSync, - fchmod, - existsSync, - exists, - fs_default as default, - createWriteStream, - createReadStream, - copyFileSync, - copyFile, - constants, - closeSync, - close, - chownSync, - chown, - chmodSync, - chmod, - appendFileSync, - appendFile, - accessSync, - access, - WriteStream, - Stats, - ReadStream, - Dirent -}; diff --git a/src/js/out/modules/node/fs.promises.js b/src/js/out/modules/node/fs.promises.js deleted file mode 100644 index 9ac3c6f6545735..00000000000000 --- a/src/js/out/modules/node/fs.promises.js +++ /dev/null @@ -1 +0,0 @@ -var r=(B)=>{return import.meta.require(B)};function J(B,C={}){const G=[];if(B instanceof URL)throw new TypeError("Watch URLs are not supported yet");else if(Buffer.isBuffer(B))B=B.toString();else if(typeof B!=="string")throw new TypeError("Expected path to be a string or Buffer");let D=null;if(typeof C==="string")C={encoding:C};return S.watch(B,C||{},(z,A)=>{if(G.push({eventType:z,filename:A}),D){const H=D;D=null,H()}}),{async*[Symbol.asyncIterator](){let z=!1;while(!z){while(G.length){let A=G.shift();if(A.eventType==="close"){z=!0;break}if(A.eventType==="error")throw z=!0,A.filename;yield A}await new Promise((A)=>D=A)}}}}var S=Bun.fs(),I="::bunternal::",q={[I]:(B)=>{var C={[I]:function(G,D,z){var A;try{A=B.apply(S,z),z=void 0}catch(H){z=void 0,D(H);return}G(A)}}[I];return async function(...G){return await new Promise((D,z)=>{process.nextTick(C,D,z,G)})}}}[I],K=q(S.accessSync),L=q(S.appendFileSync),M=q(S.closeSync),N=q(S.copyFileSync),O=q(S.existsSync),P=q(S.chownSync),Q=q(S.chmodSync),U=q(S.fchmodSync),V=q(S.fchownSync),X=q(S.fstatSync),Y=q(S.fsyncSync),Z=q(S.ftruncateSync),_=q(S.futimesSync),$=q(S.lchmodSync),T=q(S.lchownSync),W=q(S.linkSync),k=q(S.lstatSync),E=q(S.mkdirSync),x=q(S.mkdtempSync),F=q(S.openSync),R=q(S.readSync),g=q(S.writeSync),h=q(S.readdirSync),j=q(S.readFileSync),w=q(S.writeFileSync),b=q(S.readlinkSync),u=q(S.realpathSync),d=q(S.renameSync),c=q(S.statSync),v=q(S.symlinkSync),a=q(S.truncateSync),y=q(S.unlinkSync),l=q(S.utimesSync),p=q(S.lutimesSync),m=q(S.rmSync),n=q(S.rmdirSync),t=(B,C,G)=>{return new Promise((D,z)=>{try{var A=S.writevSync(B,C,G)}catch(H){z(H);return}D({bytesWritten:A,buffers:C})})},o=(B,C,G)=>{return new Promise((D,z)=>{try{var A=S.readvSync(B,C,G)}catch(H){z(H);return}D({bytesRead:A,buffers:C})})},f={access:K,appendFile:L,close:M,copyFile:N,exists:O,chown:P,chmod:Q,fchmod:U,fchown:V,fstat:X,fsync:Y,ftruncate:Z,futimes:_,lchmod:$,lchown:T,link:W,lstat:k,mkdir:E,mkdtemp:x,open:F,read:R,write:g,readdir:h,readFile:j,writeFile:w,readlink:b,realpath:u,rename:d,stat:c,symlink:v,truncate:a,unlink:y,utimes:l,lutimes:p,rm:m,rmdir:n,watch:J,writev:t,readv:o,constants,[Symbol.for("CommonJS")]:0};export{t as writev,w as writeFile,g as write,J as watch,l as utimes,y as unlink,a as truncate,v as symlink,c as stat,n as rmdir,m as rm,d as rename,u as realpath,o as readv,b as readlink,h as readdir,j as readFile,R as read,F as open,x as mkdtemp,E as mkdir,p as lutimes,k as lstat,W as link,T as lchown,$ as lchmod,_ as futimes,Z as ftruncate,Y as fsync,X as fstat,V as fchown,U as fchmod,O as exists,f as default,N as copyFile,M as close,P as chown,Q as chmod,L as appendFile,K as access}; diff --git a/src/js/out/modules/node/http.js b/src/js/out/modules/node/http.js deleted file mode 100644 index cc9092518d26e4..00000000000000 --- a/src/js/out/modules/node/http.js +++ /dev/null @@ -1,1147 +0,0 @@ -import {EventEmitter} from "node:events"; -import {Readable, Writable, Duplex} from "node:stream"; -import {isTypedArray} from "node:util/types"; -var checkInvalidHeaderChar = function(val) { - return RegExpPrototypeExec.call(headerCharRegex, val) !== null; -}, isIPv6 = function(input) { - return new RegExp("^((?:(?:[0-9a-fA-F]{1,4}):){7}(?:(?:[0-9a-fA-F]{1,4})|:)|(?:(?:[0-9a-fA-F]{1,4}):){6}(?:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(?:[0-9a-fA-F]{1,4})|:)|(?:(?:[0-9a-fA-F]{1,4}):){5}(?::((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,2}|:)|(?:(?:[0-9a-fA-F]{1,4}):){4}(?:(:(?:[0-9a-fA-F]{1,4})){0,1}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,3}|:)|(?:(?:[0-9a-fA-F]{1,4}):){3}(?:(:(?:[0-9a-fA-F]{1,4})){0,2}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,4}|:)|(?:(?:[0-9a-fA-F]{1,4}):){2}(?:(:(?:[0-9a-fA-F]{1,4})){0,3}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,5}|:)|(?:(?:[0-9a-fA-F]{1,4}):){1}(?:(:(?:[0-9a-fA-F]{1,4})){0,4}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,6}|:)|(?::((?::(?:[0-9a-fA-F]{1,4})){0,5}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(?::(?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$").test(input); -}, isValidTLSArray = function(obj) { - if (typeof obj === "string" || isTypedArray(obj) || obj instanceof ArrayBuffer || obj instanceof Blob) - return !0; - if (Array.isArray(obj)) { - for (var i = 0;i < obj.length; i++) - if (typeof obj !== "string" && !isTypedArray(obj) && !(obj instanceof ArrayBuffer) && !(obj instanceof Blob)) - return !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; - const result = headers.get(name); - return result == null ? void 0 : result; -}; -function createServer(options, callback) { - return new Server(options, callback); -} -var emitListeningNextTick = function(self, onListen, err, hostname, port) { - if (typeof onListen === "function") - try { - onListen(err, hostname, port); - } catch (err2) { - self.emit("error", err2); - } - if (self.listening = !err, err) - self.emit("error", err); - else - self.emit("listening", hostname, port); -}, assignHeaders = function(object, req) { - var headers = req.headers.toJSON(); - const rawHeaders = newArrayWithSize(req.headers.count * 2); - var i = 0; - for (let key in headers) - rawHeaders[i++] = key, rawHeaders[i++] = headers[key]; - object.headers = headers, object.rawHeaders = rawHeaders; -}; -var getDefaultHTTPSAgent = function() { - return _defaultHTTPSAgent ??= new Agent({ defaultPort: 443, protocol: "https:" }); -}; -var urlToHttpOptions = function(url) { - var { protocol, hostname, hash, search, pathname, href, port, username, password } = url; - return { - protocol, - hostname: typeof hostname === "string" && StringPrototypeStartsWith.call(hostname, "[") ? StringPrototypeSlice.call(hostname, 1, -1) : hostname, - hash, - search, - pathname, - path: `${pathname || ""}${search || ""}`, - href, - port: port ? Number(port) : protocol === "https:" ? 443 : protocol === "http:" ? 80 : void 0, - auth: username || password ? `${decodeURIComponent(username)}:${decodeURIComponent(password)}` : void 0 - }; -}, validateHost = function(host, name) { - if (host !== null && host !== void 0 && typeof host !== "string") - throw new Error("Invalid arg type in options"); - return host; -}, checkIsHttpToken = function(val) { - return RegExpPrototypeExec.call(tokenRegExp, val) !== null; -}; -var _writeHead = function(statusCode, reason, obj, response) { - if (statusCode |= 0, statusCode < 100 || statusCode > 999) - throw new Error("status code must be between 100 and 999"); - if (typeof reason === "string") - response.statusMessage = reason; - else { - if (!response.statusMessage) - response.statusMessage = STATUS_CODES[statusCode] || "unknown"; - obj = reason; - } - response.statusCode = statusCode; - { - let k; - if (Array.isArray(obj)) { - if (obj.length % 2 !== 0) - throw new Error("raw headers must have an even number of elements"); - for (let n = 0;n < obj.length; n += 2) - if (k = obj[n + 0], k) - response.setHeader(k, obj[n + 1]); - } else if (obj) { - const keys = Object.keys(obj); - for (let i = 0;i < keys.length; i++) - if (k = keys[i], k) - response.setHeader(k, obj[k]); - } - } - if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199) - response._hasBody = !1; -}; -function request(url, options, cb) { - return new ClientRequest(url, options, cb); -} -function get(url, options, cb) { - const req = request(url, options, cb); - return req.end(), req; -} -var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/, validateHeaderName = (name, label) => { - if (typeof name !== "string" || !name || !checkIsHttpToken(name)) - throw new Error("ERR_INVALID_HTTP_TOKEN"); -}, validateHeaderValue = (name, value) => { - if (value === void 0) - throw new Error("ERR_HTTP_INVALID_HEADER_VALUE"); - if (checkInvalidHeaderChar(value)) - throw new Error("ERR_INVALID_CHAR"); -}, { URL } = globalThis, { newArrayWithSize, String, Object, Array } = globalThis[Symbol.for("Bun.lazy")]("primordials"), globalReportError = globalThis.reportError, setTimeout = globalThis.setTimeout, fetch = Bun.fetch, nop = () => { -}, __DEBUG__ = process.env.__DEBUG__, debug = __DEBUG__ ? (...args) => console.log("node:http", ...args) : nop, kEmptyObject = Object.freeze(Object.create(null)), kOutHeaders = Symbol.for("kOutHeaders"), kEndCalled = Symbol.for("kEndCalled"), kAbortController = Symbol.for("kAbortController"), kClearTimeout = Symbol("kClearTimeout"), kCorked = Symbol.for("kCorked"), searchParamsSymbol = Symbol.for("query"), StringPrototypeSlice = String.prototype.slice, StringPrototypeStartsWith = String.prototype.startsWith, StringPrototypeToUpperCase = String.prototype.toUpperCase, StringPrototypeIncludes = String.prototype.includes, StringPrototypeCharCodeAt = String.prototype.charCodeAt, StringPrototypeIndexOf = String.prototype.indexOf, ArrayIsArray = Array.isArray, RegExpPrototypeExec = RegExp.prototype.exec, ObjectAssign = Object.assign, ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty, INVALID_PATH_REGEX = /[^\u0021-\u00ff]/, NODE_HTTP_WARNING = "WARN: Agent is mostly unused in Bun's implementation of http. If you see strange behavior, this is probably the cause.", _defaultHTTPSAgent, kInternalRequest = Symbol("kInternalRequest"), kInternalSocketData = Symbol.for("::bunternal::"), kEmptyBuffer = Buffer.alloc(0); - -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; - remoteAddress = null; - remotePort; - timeout = 0; - isServer = !1; - address() { - return { - address: this.localAddress, - family: this.localFamily, - port: this.localPort - }; - } - get bufferSize() { - return this.writableLength; - } - connect(port, host, connectListener) { - return this; - } - _destroy(err, callback) { - } - _final(callback) { - } - get localAddress() { - return "127.0.0.1"; - } - get localFamily() { - return "IPv4"; - } - get localPort() { - return 80; - } - get pending() { - return this.connecting; - } - _read(size) { - } - get readyState() { - if (this.connecting) - return "opening"; - if (this.readable) - return this.writable ? "open" : "readOnly"; - else - return this.writable ? "writeOnly" : "closed"; - } - ref() { - } - get remoteFamily() { - return "IPv4"; - } - resetAndDestroy() { - } - setKeepAlive(enable = !1, initialDelay = 0) { - } - setNoDelay(noDelay = !0) { - return this; - } - setTimeout(timeout, callback) { - return this; - } - unref() { - } - _write(chunk, encoding, callback) { - } -}; - -class Agent extends EventEmitter { - defaultPort = 80; - protocol = "http:"; - options; - requests; - sockets; - freeSockets; - keepAliveMsecs; - keepAlive; - maxSockets; - maxFreeSockets; - scheduling; - maxTotalSockets; - totalSocketCount; - #fakeSocket; - static get globalAgent() { - return globalAgent; - } - static get defaultMaxSockets() { - return Infinity; - } - constructor(options = kEmptyObject) { - super(); - if (this.options = options = { ...options, path: null }, options.noDelay === void 0) - options.noDelay = !0; - this.requests = kEmptyObject, this.sockets = kEmptyObject, this.freeSockets = kEmptyObject, this.keepAliveMsecs = options.keepAliveMsecs || 1000, this.keepAlive = options.keepAlive || !1, this.maxSockets = options.maxSockets || Agent.defaultMaxSockets, this.maxFreeSockets = options.maxFreeSockets || 256, this.scheduling = options.scheduling || "lifo", this.maxTotalSockets = options.maxTotalSockets, this.totalSocketCount = 0, this.defaultPort = options.defaultPort || 80, this.protocol = options.protocol || "http:"; - } - createConnection() { - return debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createConnection is a no-op, returns fake socket"), this.#fakeSocket ??= new FakeSocket; - } - getName(options = kEmptyObject) { - let name = `http:${options.host || "localhost"}:`; - if (options.port) - name += options.port; - if (name += ":", options.localAddress) - name += options.localAddress; - if (options.family === 4 || options.family === 6) - name += `:${options.family}`; - if (options.socketPath) - name += `:${options.socketPath}`; - return name; - } - addRequest() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.addRequest is a no-op"); - } - createSocket(req, options, cb) { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.createSocket returns fake socket"), cb(null, this.#fakeSocket ??= new FakeSocket); - } - removeSocket() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.removeSocket is a no-op"); - } - keepSocketAlive() { - return debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.keepSocketAlive is a no-op"), !0; - } - reuseSocket() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.reuseSocket is a no-op"); - } - destroy() { - debug(`${NODE_HTTP_WARNING}\n`, "WARN: Agent.destroy is a no-op"); - } -} - -class Server extends EventEmitter { - #server; - #options; - #tls; - #is_tls = !1; - listening = !1; - serverName; - constructor(options, callback) { - super(); - if (typeof options === "function") - callback = options, options = {}; - else if (options == null || typeof options === "object") { - options = { ...options }, this.#tls = null; - let key = options.key; - if (key) { - if (!isValidTLSArray(key)) - throw new TypeError("key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.#is_tls = !0; - } - let cert = options.cert; - if (cert) { - if (!isValidTLSArray(cert)) - throw new TypeError("cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.#is_tls = !0; - } - let ca = options.ca; - if (ca) { - if (!isValidTLSArray(ca)) - throw new TypeError("ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.#is_tls = !0; - } - let passphrase = options.passphrase; - if (passphrase && typeof passphrase !== "string") - throw new TypeError("passphrase argument must be an string"); - let serverName = options.servername; - if (serverName && typeof serverName !== "string") - throw new TypeError("servername argument must be an string"); - let secureOptions = options.secureOptions || 0; - if (secureOptions && typeof secureOptions !== "number") - throw new TypeError("secureOptions argument must be an number"); - if (this.#is_tls) - this.#tls = { - serverName, - key, - cert, - ca, - passphrase, - secureOptions - }; - else - this.#tls = null; - } else - throw new Error("bun-http-polyfill: invalid arguments"); - if (this.#options = options, callback) - this.on("request", callback); - } - closeAllConnections() { - const server = this.#server; - if (!server) - return; - this.#server = void 0, server.stop(!0), this.emit("close"); - } - closeIdleConnections() { - } - close(optionalCallback) { - const server = this.#server; - if (!server) { - if (typeof optionalCallback === "function") - process.nextTick(optionalCallback, new Error("Server is not running")); - return; - } - if (this.#server = void 0, typeof optionalCallback === "function") - this.once("close", optionalCallback); - server.stop(), this.emit("close"); - } - address() { - if (!this.#server) - return null; - const address = this.#server.hostname; - return { - address, - family: isIPv6(address) ? "IPv6" : "IPv4", - port: this.#server.port - }; - } - listen(port, host, backlog, onListen) { - const server = this; - if (typeof host === "function") - onListen = host, host = void 0; - if (typeof port === "function") - onListen = port; - else if (typeof port === "object") { - if (port?.signal?.addEventListener("abort", () => { - this.close(); - }), host = port?.host, port = port?.port, typeof port?.callback === "function") - onListen = port?.callback; - } - if (typeof backlog === "function") - onListen = backlog; - const ResponseClass = this.#options.ServerResponse || ServerResponse, RequestClass = this.#options.IncomingMessage || IncomingMessage; - try { - const tls = this.#tls; - if (tls) - this.serverName = tls.serverName || host || "localhost"; - this.#server = Bun.serve({ - tls, - port, - hostname: host, - websocket: { - open(ws) { - ws.data.open(ws); - }, - message(ws, message) { - ws.data.message(ws, message); - }, - close(ws, code, reason) { - ws.data.close(ws, code, reason); - }, - drain(ws) { - ws.data.drain(ws); - } - }, - fetch(req, _server) { - var pendingResponse, pendingError, rejectFunction, resolveFunction, reject = (err) => { - if (pendingError) - return; - if (pendingError = err, rejectFunction) - rejectFunction(err); - }, reply = function(resp) { - if (pendingResponse) - return; - if (pendingResponse = resp, resolveFunction) - resolveFunction(resp); - }; - const http_req = new RequestClass(req), http_res = new ResponseClass({ reply, req: http_req }); - if (http_req.once("error", (err) => reject(err)), http_res.once("error", (err) => reject(err)), req.headers.get("upgrade")) { - const socket = new FakeSocket; - socket[kInternalSocketData] = [_server, http_res, req], server.emit("upgrade", http_req, socket, kEmptyBuffer); - } else - server.emit("request", http_req, http_res); - if (pendingError) - throw pendingError; - if (pendingResponse) - return pendingResponse; - return new Promise((resolve, reject2) => { - resolveFunction = resolve, rejectFunction = reject2; - }); - } - }), setTimeout(emitListeningNextTick, 1, this, onListen, null, this.#server.hostname, this.#server.port); - } catch (err) { - setTimeout(emitListeningNextTick, 1, this, onListen, err); - } - return this; - } - setTimeout(msecs, callback) { - } -} -class IncomingMessage extends Readable { - method; - complete; - constructor(req, defaultIncomingOpts) { - const method = req.method; - super(); - const url = new URL(req.url); - var { type = "request", [kInternalRequest]: nodeReq } = defaultIncomingOpts || {}; - this.#noBody = type === "request" ? method === "GET" || method === "HEAD" || method === "TRACE" || method === "CONNECT" || method === "OPTIONS" || (parseInt(req.headers.get("Content-Length") || "") || 0) === 0 : !1, this.#req = req, this.method = method, this.#type = type, this.complete = !!this.#noBody, this.#bodyStream = void 0; - const socket = new FakeSocket; - socket.remoteAddress = url.hostname, socket.remotePort = url.port, this.#fakeSocket = socket, this.url = url.pathname + url.search, this.#nodeReq = nodeReq, assignHeaders(this, req); - } - headers; - rawHeaders; - _consuming = !1; - _dumped = !1; - #bodyStream; - #fakeSocket; - #noBody = !1; - #aborted = !1; - #req; - url; - #type; - #nodeReq; - get req() { - return this.#nodeReq; - } - _construct(callback) { - if (this.#type === "response" || this.#noBody) { - callback(); - return; - } - const contentLength = this.#req.headers.get("content-length"); - if ((contentLength ? parseInt(contentLength, 10) : 0) === 0) { - this.#noBody = !0, callback(); - return; - } - callback(); - } - async#consumeStream(reader) { - while (!0) { - var { done, value } = await reader.readMany(); - if (this.#aborted) - return; - if (done) { - this.push(null), this.destroy(); - break; - } - for (var v of value) - this.push(v); - } - } - _read(size) { - if (this.#noBody) - this.push(null), this.complete = !0; - else if (this.#bodyStream == null) { - const reader = this.#req.body?.getReader(); - if (!reader) { - this.push(null); - return; - } - this.#bodyStream = reader, this.#consumeStream(reader); - } - } - get aborted() { - return this.#aborted; - } - #abort() { - if (this.#aborted) - return; - this.#aborted = !0; - var bodyStream = this.#bodyStream; - if (!bodyStream) - return; - bodyStream.cancel(), this.complete = !0, this.#bodyStream = void 0, this.push(null); - } - get connection() { - return this.#fakeSocket; - } - get statusCode() { - return this.#req.status; - } - get statusMessage() { - return STATUS_CODES[this.#req.status]; - } - get httpVersion() { - return "1.1"; - } - get rawTrailers() { - return []; - } - get httpVersionMajor() { - return 1; - } - get httpVersionMinor() { - return 1; - } - get trailers() { - return kEmptyObject; - } - get socket() { - return this.#fakeSocket ??= new FakeSocket; - } - set socket(val) { - this.#fakeSocket = val; - } - setTimeout(msecs, callback) { - throw new Error("not implemented"); - } -} - -class OutgoingMessage extends Writable { - constructor() { - super(...arguments); - } - #headers; - headersSent = !1; - sendDate = !0; - req; - timeout; - #finished = !1; - [kEndCalled] = !1; - #fakeSocket; - #timeoutTimer; - [kAbortController] = null; - _implicitHeader() { - } - get headers() { - if (!this.#headers) - return kEmptyObject; - return this.#headers.toJSON(); - } - get shouldKeepAlive() { - return !0; - } - get chunkedEncoding() { - return !1; - } - set chunkedEncoding(value) { - } - set shouldKeepAlive(value) { - } - get useChunkedEncodingByDefault() { - return !0; - } - set useChunkedEncodingByDefault(value) { - } - get socket() { - return this.#fakeSocket ??= new FakeSocket; - } - set socket(val) { - this.#fakeSocket = val; - } - get connection() { - return this.socket; - } - get finished() { - return this.#finished; - } - appendHeader(name, value) { - var headers = this.#headers ??= new Headers; - headers.append(name, value); - } - flushHeaders() { - } - getHeader(name) { - return getHeader(this.#headers, name); - } - getHeaders() { - if (!this.#headers) - return kEmptyObject; - return this.#headers.toJSON(); - } - getHeaderNames() { - var headers = this.#headers; - if (!headers) - return []; - return Array.from(headers.keys()); - } - removeHeader(name) { - if (!this.#headers) - return; - this.#headers.delete(name); - } - setHeader(name, value) { - var headers = this.#headers ??= new Headers; - return headers.set(name, value), this; - } - hasHeader(name) { - if (!this.#headers) - return !1; - return this.#headers.has(name); - } - addTrailers(headers) { - throw new Error("not implemented"); - } - [kClearTimeout]() { - if (this.#timeoutTimer) - 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.destroyed) - return 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 OriginalWriteHeadFn, OriginalImplicitHeadFn; - -class ServerResponse extends Writable { - constructor({ req, reply }) { - super(); - if (this.req = req, this._reply = reply, this.sendDate = !0, this.statusCode = 200, this.headersSent = !1, this.statusMessage = void 0, this.#controller = void 0, this.#firstWrite = void 0, this._writableState.decodeStrings = !1, this.#deferred = void 0, req.method === "HEAD") - this._hasBody = !1; - } - req; - _reply; - sendDate; - statusCode; - #headers; - headersSent = !1; - statusMessage; - #controller; - #firstWrite; - _sent100 = !1; - _defaultKeepAlive = !1; - _removedConnection = !1; - _removedContLen = !1; - _hasBody = !0; - #deferred = void 0; - #finished = !1; - _implicitHeader() { - this.writeHead(this.statusCode); - } - _write(chunk, encoding, callback) { - if (!this.#firstWrite && !this.headersSent) { - this.#firstWrite = chunk, callback(); - return; - } - this.#ensureReadableStreamController((controller) => { - controller.write(chunk), callback(); - }); - } - _writev(chunks, callback) { - if (chunks.length === 1 && !this.headersSent && !this.#firstWrite) { - this.#firstWrite = chunks[0].chunk, callback(); - return; - } - this.#ensureReadableStreamController((controller) => { - for (let chunk of chunks) - controller.write(chunk.chunk); - callback(); - }); - } - #ensureReadableStreamController(run) { - var thisController = this.#controller; - if (thisController) - return run(thisController); - this.headersSent = !0; - var firstWrite = this.#firstWrite; - this.#firstWrite = void 0, this._reply(new Response(new ReadableStream({ - type: "direct", - pull: (controller) => { - if (this.#controller = controller, firstWrite) - controller.write(firstWrite); - if (firstWrite = void 0, run(controller), !this.#finished) - return new Promise((resolve) => { - this.#deferred = resolve; - }); - } - }), { - headers: this.#headers, - status: this.statusCode, - statusText: this.statusMessage ?? STATUS_CODES[this.statusCode] - })); - } - #drainHeadersIfObservable() { - if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn) - return; - this._implicitHeader(); - } - _final(callback) { - if (!this.headersSent) { - var data = this.#firstWrite || ""; - this.#firstWrite = void 0, this.#finished = !0, this.#drainHeadersIfObservable(), this._reply(new Response(data, { - headers: this.#headers, - status: this.statusCode, - statusText: this.statusMessage ?? STATUS_CODES[this.statusCode] - })), callback && callback(); - return; - } - this.#finished = !0, this.#ensureReadableStreamController((controller) => { - controller.end(), callback(); - var deferred = this.#deferred; - if (deferred) - this.#deferred = void 0, deferred(); - }); - } - writeProcessing() { - throw new Error("not implemented"); - } - addTrailers(headers) { - throw new Error("not implemented"); - } - assignSocket(socket) { - throw new Error("not implemented"); - } - detachSocket(socket) { - throw new Error("not implemented"); - } - writeContinue(callback) { - throw new Error("not implemented"); - } - setTimeout(msecs, callback) { - throw new Error("not implemented"); - } - get shouldKeepAlive() { - return !0; - } - get chunkedEncoding() { - return !1; - } - set chunkedEncoding(value) { - } - set shouldKeepAlive(value) { - } - get useChunkedEncodingByDefault() { - return !0; - } - set useChunkedEncodingByDefault(value) { - } - appendHeader(name, value) { - var headers = this.#headers ??= new Headers; - headers.append(name, value); - } - flushHeaders() { - } - getHeader(name) { - return getHeader(this.#headers, name); - } - getHeaders() { - var headers = this.#headers; - if (!headers) - return kEmptyObject; - return headers.toJSON(); - } - getHeaderNames() { - var headers = this.#headers; - if (!headers) - return []; - return Array.from(headers.keys()); - } - removeHeader(name) { - if (!this.#headers) - return; - this.#headers.delete(name); - } - setHeader(name, value) { - var headers = this.#headers ??= new Headers; - return headers.set(name, value), this; - } - hasHeader(name) { - if (!this.#headers) - return !1; - return this.#headers.has(name); - } - writeHead(statusCode, statusMessage, headers) { - return _writeHead(statusCode, statusMessage, headers, this), this; - } -} -OriginalWriteHeadFn = ServerResponse.prototype.writeHead; -OriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader; - -class ClientRequest extends OutgoingMessage { - #timeout; - #res = null; - #upgradeOrConnect = !1; - #parser = null; - #maxHeadersCount = null; - #reusedSocket = !1; - #host; - #protocol; - #method; - #port; - #useDefaultPort; - #joinDuplicateHeaders; - #maxHeaderSize; - #agent = globalAgent; - #path; - #socketPath; - #body = null; - #fetchRequest; - #signal = null; - [kAbortController] = null; - #timeoutTimer = void 0; - #options; - #finished; - get path() { - return this.#path; - } - get port() { - return this.#port; - } - get method() { - return this.#method; - } - get host() { - return this.#host; - } - get protocol() { - return this.#protocol; - } - _write(chunk, encoding, callback) { - var body = this.#body; - if (!body) { - this.#body = chunk, callback(); - return; - } - this.#body = body + chunk, callback(); - } - _writev(chunks, callback) { - var body = this.#body; - if (!body) { - this.#body = chunks.join(), callback(); - return; - } - this.#body = body + chunks.join(), callback(); - } - _final(callback) { - if (this.#finished = !0, this[kAbortController] = new AbortController, this[kAbortController].signal.addEventListener("abort", () => { - this[kClearTimeout](); - }), this.#signal?.aborted) - this[kAbortController].abort(); - var method = this.#method, body = this.#body; - try { - this.#fetchRequest = fetch(`${this.#protocol}//${this.#host}${this.#useDefaultPort ? "" : ":" + this.#port}${this.#path}`, { - method, - headers: this.getHeaders(), - body: body && method !== "GET" && method !== "HEAD" && method !== "OPTIONS" ? body : void 0, - redirect: "manual", - verbose: Boolean(__DEBUG__), - signal: this[kAbortController].signal, - timeout: !1 - }).then((response) => { - var res = this.#res = new IncomingMessage(response, { - type: "response", - [kInternalRequest]: this - }); - this.emit("response", res); - }).catch((err) => { - if (__DEBUG__) - globalReportError(err); - this.emit("error", err); - }).finally(() => { - this.#fetchRequest = null, this[kClearTimeout](); - }); - } catch (err) { - if (__DEBUG__) - globalReportError(err); - this.emit("error", err); - } finally { - callback(); - } - } - get aborted() { - return this.#signal?.aborted || !!this[kAbortController]?.signal.aborted; - } - abort() { - if (this.aborted) - return; - this[kAbortController].abort(); - } - constructor(input, options, cb) { - super(); - if (typeof input === "string") { - const urlStr = input; - try { - var urlObject = new URL(urlStr); - } catch (e) { - throw new TypeError(`Invalid URL: ${urlStr}`); - } - input = urlToHttpOptions(urlObject); - } else if (input && typeof input === "object" && input instanceof URL) - input = urlToHttpOptions(input); - else - cb = options, options = input, input = null; - if (typeof options === "function") - cb = options, options = input || kEmptyObject; - else - options = ObjectAssign(input || {}, options); - var defaultAgent = options._defaultAgent || Agent.globalAgent; - let protocol = options.protocol; - if (!protocol) - if (options.port === 443) - protocol = "https:"; - else - protocol = defaultAgent.protocol || "http:"; - switch (this.#protocol = protocol, this.#agent?.protocol) { - case void 0: - break; - case "http:": - if (protocol === "https:") { - defaultAgent = this.#agent = getDefaultHTTPSAgent(); - break; - } - case "https:": - if (protocol === "https") { - defaultAgent = this.#agent = Agent.globalAgent; - break; - } - default: - break; - } - if (options.path) { - const path = String(options.path); - if (RegExpPrototypeExec.call(INVALID_PATH_REGEX, path) !== null) - throw debug('Path contains unescaped characters: "%s"', path), new Error("Path contains unescaped characters"); - } - if (protocol !== "http:" && protocol !== "https:" && protocol) { - const expectedProtocol = defaultAgent?.protocol ?? "http:"; - throw new Error(`Protocol mismatch. Expected: ${expectedProtocol}. Got: ${protocol}`); - } - 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"; - this.#socketPath = options.socketPath; - const signal = options.signal; - if (signal) - signal.addEventListener("abort", () => { - this[kAbortController]?.abort(); - }), this.#signal = signal; - let method = options.method; - const methodIsString = typeof method === "string"; - if (method !== null && method !== void 0 && !methodIsString) - throw new Error("ERR_INVALID_ARG_TYPE: options.method"); - if (methodIsString && method) { - if (!checkIsHttpToken(method)) - throw new Error("ERR_INVALID_HTTP_TOKEN: Method"); - method = this.#method = StringPrototypeToUpperCase.call(method); - } else - method = this.#method = "GET"; - const _maxHeaderSize = options.maxHeaderSize; - this.#maxHeaderSize = _maxHeaderSize; - var _joinDuplicateHeaders = options.joinDuplicateHeaders; - if (this.#joinDuplicateHeaders = _joinDuplicateHeaders, this.#path = options.path || "/", cb) - this.once("response", cb); - __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) - this.setHeader(key, headers[key]); - var auth = options.auth; - if (auth && !this.getHeader("Authorization")) - this.setHeader("Authorization", "Basic " + Buffer.from(auth).toString("base64")); - } - var { signal: _signal, ...optsWithoutSignal } = options; - this.#options = optsWithoutSignal; - } - setSocketKeepAlive(enable = !0, initialDelay = 0) { - __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setSocketKeepAlive is a no-op"); - } - setNoDelay(noDelay = !0) { - __DEBUG__ && debug(`${NODE_HTTP_WARNING}\n`, "WARN: ClientRequest.setNoDelay is a no-op"); - } - [kClearTimeout]() { - if (this.#timeoutTimer) - 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.destroyed) - return 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 = [ - "ACL", - "BIND", - "CHECKOUT", - "CONNECT", - "COPY", - "DELETE", - "GET", - "HEAD", - "LINK", - "LOCK", - "M-SEARCH", - "MERGE", - "MKACTIVITY", - "MKCALENDAR", - "MKCOL", - "MOVE", - "NOTIFY", - "OPTIONS", - "PATCH", - "POST", - "PROPFIND", - "PROPPATCH", - "PURGE", - "PUT", - "REBIND", - "REPORT", - "SEARCH", - "SOURCE", - "SUBSCRIBE", - "TRACE", - "UNBIND", - "UNLINK", - "UNLOCK", - "UNSUBSCRIBE" -], STATUS_CODES = { - 100: "Continue", - 101: "Switching Protocols", - 102: "Processing", - 103: "Early Hints", - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-Authoritative Information", - 204: "No Content", - 205: "Reset Content", - 206: "Partial Content", - 207: "Multi-Status", - 208: "Already Reported", - 226: "IM Used", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 305: "Use Proxy", - 307: "Temporary Redirect", - 308: "Permanent Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Payload Too Large", - 414: "URI Too Long", - 415: "Unsupported Media Type", - 416: "Range Not Satisfiable", - 417: "Expectation Failed", - 418: "I'm a Teapot", - 421: "Misdirected Request", - 422: "Unprocessable Entity", - 423: "Locked", - 424: "Failed Dependency", - 425: "Too Early", - 426: "Upgrade Required", - 428: "Precondition Required", - 429: "Too Many Requests", - 431: "Request Header Fields Too Large", - 451: "Unavailable For Legal Reasons", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported", - 506: "Variant Also Negotiates", - 507: "Insufficient Storage", - 508: "Loop Detected", - 509: "Bandwidth Limit Exceeded", - 510: "Not Extended", - 511: "Network Authentication Required" -}, globalAgent = new Agent, defaultObject = { - Agent, - Server, - METHODS, - STATUS_CODES, - createServer, - ServerResponse, - IncomingMessage, - request, - get, - maxHeaderSize: 16384, - validateHeaderName, - validateHeaderValue, - setMaxIdleHTTPParsers(max) { - debug(`${NODE_HTTP_WARNING}\n`, "setMaxIdleHTTPParsers() is a no-op"); - }, - globalAgent, - ClientRequest, - OutgoingMessage, - [Symbol.for("CommonJS")]: 0 -}, http_default = defaultObject; -export { - validateHeaderValue, - validateHeaderName, - request, - globalAgent, - get, - http_default as default, - createServer, - ServerResponse, - Server, - STATUS_CODES, - OutgoingMessage, - METHODS, - IncomingMessage, - ClientRequest, - Agent -}; diff --git a/src/js/out/modules/node/http2.js b/src/js/out/modules/node/http2.js deleted file mode 100644 index 18fea085aee717..00000000000000 --- a/src/js/out/modules/node/http2.js +++ /dev/null @@ -1,321 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/http2.ts -var connect = function() { - throwNotImplemented("node:http2 connect", 887); -}, createServer = function() { - throwNotImplemented("node:http2 createServer", 887); -}, createSecureServer = function() { - throwNotImplemented("node:http2 createSecureServer", 887); -}, getDefaultSettings = function() { - return { - headerTableSize: 4096, - enablePush: !0, - initialWindowSize: 65535, - maxFrameSize: 16384, - maxConcurrentStreams: 4294967295, - maxHeaderSize: 65535, - maxHeaderListSize: 65535, - enableConnectProtocol: !1 - }; -}, getPackedSettings = function() { - return Buffer.alloc(0); -}, getUnpackedSettings = function() { - return Buffer.alloc(0); -}, Http2ServerRequest = function() { - throwNotImplemented("node:http2 Http2ServerRequest", 887); -}, Http2ServerResponse = function() { - throwNotImplemented("node:http2 Http2ServerResponse", 887); -}, constants = { - NGHTTP2_ERR_FRAME_SIZE_ERROR: -522, - NGHTTP2_SESSION_SERVER: 0, - NGHTTP2_SESSION_CLIENT: 1, - NGHTTP2_STREAM_STATE_IDLE: 1, - NGHTTP2_STREAM_STATE_OPEN: 2, - NGHTTP2_STREAM_STATE_RESERVED_LOCAL: 3, - NGHTTP2_STREAM_STATE_RESERVED_REMOTE: 4, - NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: 5, - NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: 6, - NGHTTP2_STREAM_STATE_CLOSED: 7, - NGHTTP2_FLAG_NONE: 0, - NGHTTP2_FLAG_END_STREAM: 1, - NGHTTP2_FLAG_END_HEADERS: 4, - NGHTTP2_FLAG_ACK: 1, - NGHTTP2_FLAG_PADDED: 8, - NGHTTP2_FLAG_PRIORITY: 32, - DEFAULT_SETTINGS_HEADER_TABLE_SIZE: 4096, - DEFAULT_SETTINGS_ENABLE_PUSH: 1, - DEFAULT_SETTINGS_MAX_CONCURRENT_STREAMS: 4294967295, - DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: 65535, - DEFAULT_SETTINGS_MAX_FRAME_SIZE: 16384, - DEFAULT_SETTINGS_MAX_HEADER_LIST_SIZE: 65535, - DEFAULT_SETTINGS_ENABLE_CONNECT_PROTOCOL: 0, - MAX_MAX_FRAME_SIZE: 16777215, - MIN_MAX_FRAME_SIZE: 16384, - MAX_INITIAL_WINDOW_SIZE: 2147483647, - NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: 1, - NGHTTP2_SETTINGS_ENABLE_PUSH: 2, - NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: 3, - NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: 4, - NGHTTP2_SETTINGS_MAX_FRAME_SIZE: 5, - NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: 6, - NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL: 8, - PADDING_STRATEGY_NONE: 0, - PADDING_STRATEGY_ALIGNED: 1, - PADDING_STRATEGY_MAX: 2, - PADDING_STRATEGY_CALLBACK: 1, - NGHTTP2_NO_ERROR: 0, - NGHTTP2_PROTOCOL_ERROR: 1, - NGHTTP2_INTERNAL_ERROR: 2, - NGHTTP2_FLOW_CONTROL_ERROR: 3, - NGHTTP2_SETTINGS_TIMEOUT: 4, - NGHTTP2_STREAM_CLOSED: 5, - NGHTTP2_FRAME_SIZE_ERROR: 6, - NGHTTP2_REFUSED_STREAM: 7, - NGHTTP2_CANCEL: 8, - NGHTTP2_COMPRESSION_ERROR: 9, - NGHTTP2_CONNECT_ERROR: 10, - NGHTTP2_ENHANCE_YOUR_CALM: 11, - NGHTTP2_INADEQUATE_SECURITY: 12, - NGHTTP2_HTTP_1_1_REQUIRED: 13, - NGHTTP2_DEFAULT_WEIGHT: 16, - HTTP2_HEADER_STATUS: ":status", - HTTP2_HEADER_METHOD: ":method", - HTTP2_HEADER_AUTHORITY: ":authority", - HTTP2_HEADER_SCHEME: ":scheme", - HTTP2_HEADER_PATH: ":path", - HTTP2_HEADER_PROTOCOL: ":protocol", - HTTP2_HEADER_ACCEPT_ENCODING: "accept-encoding", - HTTP2_HEADER_ACCEPT_LANGUAGE: "accept-language", - HTTP2_HEADER_ACCEPT_RANGES: "accept-ranges", - HTTP2_HEADER_ACCEPT: "accept", - HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: "access-control-allow-credentials", - HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: "access-control-allow-headers", - HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: "access-control-allow-methods", - HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: "access-control-allow-origin", - HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: "access-control-expose-headers", - HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: "access-control-request-headers", - HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: "access-control-request-method", - HTTP2_HEADER_AGE: "age", - HTTP2_HEADER_AUTHORIZATION: "authorization", - HTTP2_HEADER_CACHE_CONTROL: "cache-control", - HTTP2_HEADER_CONNECTION: "connection", - HTTP2_HEADER_CONTENT_DISPOSITION: "content-disposition", - HTTP2_HEADER_CONTENT_ENCODING: "content-encoding", - HTTP2_HEADER_CONTENT_LENGTH: "content-length", - HTTP2_HEADER_CONTENT_TYPE: "content-type", - HTTP2_HEADER_COOKIE: "cookie", - HTTP2_HEADER_DATE: "date", - HTTP2_HEADER_ETAG: "etag", - HTTP2_HEADER_FORWARDED: "forwarded", - HTTP2_HEADER_HOST: "host", - HTTP2_HEADER_IF_MODIFIED_SINCE: "if-modified-since", - HTTP2_HEADER_IF_NONE_MATCH: "if-none-match", - HTTP2_HEADER_IF_RANGE: "if-range", - HTTP2_HEADER_LAST_MODIFIED: "last-modified", - HTTP2_HEADER_LINK: "link", - HTTP2_HEADER_LOCATION: "location", - HTTP2_HEADER_RANGE: "range", - HTTP2_HEADER_REFERER: "referer", - HTTP2_HEADER_SERVER: "server", - HTTP2_HEADER_SET_COOKIE: "set-cookie", - HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: "strict-transport-security", - HTTP2_HEADER_TRANSFER_ENCODING: "transfer-encoding", - HTTP2_HEADER_TE: "te", - HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS: "upgrade-insecure-requests", - HTTP2_HEADER_UPGRADE: "upgrade", - HTTP2_HEADER_USER_AGENT: "user-agent", - HTTP2_HEADER_VARY: "vary", - HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS: "x-content-type-options", - HTTP2_HEADER_X_FRAME_OPTIONS: "x-frame-options", - HTTP2_HEADER_KEEP_ALIVE: "keep-alive", - HTTP2_HEADER_PROXY_CONNECTION: "proxy-connection", - HTTP2_HEADER_X_XSS_PROTECTION: "x-xss-protection", - HTTP2_HEADER_ALT_SVC: "alt-svc", - HTTP2_HEADER_CONTENT_SECURITY_POLICY: "content-security-policy", - HTTP2_HEADER_EARLY_DATA: "early-data", - HTTP2_HEADER_EXPECT_CT: "expect-ct", - HTTP2_HEADER_ORIGIN: "origin", - HTTP2_HEADER_PURPOSE: "purpose", - HTTP2_HEADER_TIMING_ALLOW_ORIGIN: "timing-allow-origin", - HTTP2_HEADER_X_FORWARDED_FOR: "x-forwarded-for", - HTTP2_HEADER_PRIORITY: "priority", - HTTP2_HEADER_ACCEPT_CHARSET: "accept-charset", - HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE: "access-control-max-age", - HTTP2_HEADER_ALLOW: "allow", - HTTP2_HEADER_CONTENT_LANGUAGE: "content-language", - HTTP2_HEADER_CONTENT_LOCATION: "content-location", - HTTP2_HEADER_CONTENT_MD5: "content-md5", - HTTP2_HEADER_CONTENT_RANGE: "content-range", - HTTP2_HEADER_DNT: "dnt", - HTTP2_HEADER_EXPECT: "expect", - HTTP2_HEADER_EXPIRES: "expires", - HTTP2_HEADER_FROM: "from", - HTTP2_HEADER_IF_MATCH: "if-match", - HTTP2_HEADER_IF_UNMODIFIED_SINCE: "if-unmodified-since", - HTTP2_HEADER_MAX_FORWARDS: "max-forwards", - HTTP2_HEADER_PREFER: "prefer", - HTTP2_HEADER_PROXY_AUTHENTICATE: "proxy-authenticate", - HTTP2_HEADER_PROXY_AUTHORIZATION: "proxy-authorization", - HTTP2_HEADER_REFRESH: "refresh", - HTTP2_HEADER_RETRY_AFTER: "retry-after", - HTTP2_HEADER_TRAILER: "trailer", - HTTP2_HEADER_TK: "tk", - HTTP2_HEADER_VIA: "via", - HTTP2_HEADER_WARNING: "warning", - HTTP2_HEADER_WWW_AUTHENTICATE: "www-authenticate", - HTTP2_HEADER_HTTP2_SETTINGS: "http2-settings", - HTTP2_METHOD_ACL: "ACL", - HTTP2_METHOD_BASELINE_CONTROL: "BASELINE-CONTROL", - HTTP2_METHOD_BIND: "BIND", - HTTP2_METHOD_CHECKIN: "CHECKIN", - HTTP2_METHOD_CHECKOUT: "CHECKOUT", - HTTP2_METHOD_CONNECT: "CONNECT", - HTTP2_METHOD_COPY: "COPY", - HTTP2_METHOD_DELETE: "DELETE", - HTTP2_METHOD_GET: "GET", - HTTP2_METHOD_HEAD: "HEAD", - HTTP2_METHOD_LABEL: "LABEL", - HTTP2_METHOD_LINK: "LINK", - HTTP2_METHOD_LOCK: "LOCK", - HTTP2_METHOD_MERGE: "MERGE", - HTTP2_METHOD_MKACTIVITY: "MKACTIVITY", - HTTP2_METHOD_MKCALENDAR: "MKCALENDAR", - HTTP2_METHOD_MKCOL: "MKCOL", - HTTP2_METHOD_MKREDIRECTREF: "MKREDIRECTREF", - HTTP2_METHOD_MKWORKSPACE: "MKWORKSPACE", - HTTP2_METHOD_MOVE: "MOVE", - HTTP2_METHOD_OPTIONS: "OPTIONS", - HTTP2_METHOD_ORDERPATCH: "ORDERPATCH", - HTTP2_METHOD_PATCH: "PATCH", - HTTP2_METHOD_POST: "POST", - HTTP2_METHOD_PRI: "PRI", - HTTP2_METHOD_PROPFIND: "PROPFIND", - HTTP2_METHOD_PROPPATCH: "PROPPATCH", - HTTP2_METHOD_PUT: "PUT", - HTTP2_METHOD_REBIND: "REBIND", - HTTP2_METHOD_REPORT: "REPORT", - HTTP2_METHOD_SEARCH: "SEARCH", - HTTP2_METHOD_TRACE: "TRACE", - HTTP2_METHOD_UNBIND: "UNBIND", - HTTP2_METHOD_UNCHECKOUT: "UNCHECKOUT", - HTTP2_METHOD_UNLINK: "UNLINK", - HTTP2_METHOD_UNLOCK: "UNLOCK", - HTTP2_METHOD_UPDATE: "UPDATE", - HTTP2_METHOD_UPDATEREDIRECTREF: "UPDATEREDIRECTREF", - HTTP2_METHOD_VERSION_CONTROL: "VERSION-CONTROL", - HTTP_STATUS_CONTINUE: 100, - HTTP_STATUS_SWITCHING_PROTOCOLS: 101, - HTTP_STATUS_PROCESSING: 102, - HTTP_STATUS_EARLY_HINTS: 103, - HTTP_STATUS_OK: 200, - HTTP_STATUS_CREATED: 201, - HTTP_STATUS_ACCEPTED: 202, - HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: 203, - HTTP_STATUS_NO_CONTENT: 204, - HTTP_STATUS_RESET_CONTENT: 205, - HTTP_STATUS_PARTIAL_CONTENT: 206, - HTTP_STATUS_MULTI_STATUS: 207, - HTTP_STATUS_ALREADY_REPORTED: 208, - HTTP_STATUS_IM_USED: 226, - HTTP_STATUS_MULTIPLE_CHOICES: 300, - HTTP_STATUS_MOVED_PERMANENTLY: 301, - HTTP_STATUS_FOUND: 302, - HTTP_STATUS_SEE_OTHER: 303, - HTTP_STATUS_NOT_MODIFIED: 304, - HTTP_STATUS_USE_PROXY: 305, - HTTP_STATUS_TEMPORARY_REDIRECT: 307, - HTTP_STATUS_PERMANENT_REDIRECT: 308, - HTTP_STATUS_BAD_REQUEST: 400, - HTTP_STATUS_UNAUTHORIZED: 401, - HTTP_STATUS_PAYMENT_REQUIRED: 402, - HTTP_STATUS_FORBIDDEN: 403, - HTTP_STATUS_NOT_FOUND: 404, - HTTP_STATUS_METHOD_NOT_ALLOWED: 405, - HTTP_STATUS_NOT_ACCEPTABLE: 406, - HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: 407, - HTTP_STATUS_REQUEST_TIMEOUT: 408, - HTTP_STATUS_CONFLICT: 409, - HTTP_STATUS_GONE: 410, - HTTP_STATUS_LENGTH_REQUIRED: 411, - HTTP_STATUS_PRECONDITION_FAILED: 412, - HTTP_STATUS_PAYLOAD_TOO_LARGE: 413, - HTTP_STATUS_URI_TOO_LONG: 414, - HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: 415, - HTTP_STATUS_RANGE_NOT_SATISFIABLE: 416, - HTTP_STATUS_EXPECTATION_FAILED: 417, - HTTP_STATUS_TEAPOT: 418, - HTTP_STATUS_MISDIRECTED_REQUEST: 421, - HTTP_STATUS_UNPROCESSABLE_ENTITY: 422, - HTTP_STATUS_LOCKED: 423, - HTTP_STATUS_FAILED_DEPENDENCY: 424, - HTTP_STATUS_TOO_EARLY: 425, - HTTP_STATUS_UPGRADE_REQUIRED: 426, - HTTP_STATUS_PRECONDITION_REQUIRED: 428, - HTTP_STATUS_TOO_MANY_REQUESTS: 429, - HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: 431, - HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: 451, - HTTP_STATUS_INTERNAL_SERVER_ERROR: 500, - HTTP_STATUS_NOT_IMPLEMENTED: 501, - HTTP_STATUS_BAD_GATEWAY: 502, - HTTP_STATUS_SERVICE_UNAVAILABLE: 503, - HTTP_STATUS_GATEWAY_TIMEOUT: 504, - HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: 505, - HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: 506, - HTTP_STATUS_INSUFFICIENT_STORAGE: 507, - HTTP_STATUS_LOOP_DETECTED: 508, - HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: 509, - HTTP_STATUS_NOT_EXTENDED: 510, - HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: 511 -}, sensitiveHeaders = Symbol.for("nodejs.http2.sensitiveHeaders"), defaultObject = { - constants, - createServer, - createSecureServer, - getDefaultSettings, - getPackedSettings, - getUnpackedSettings, - sensitiveHeaders, - Http2ServerRequest, - Http2ServerResponse, - [Symbol.for("CommonJS")]: 0, - connect -}; -hideFromStack([ - Http2ServerRequest, - Http2ServerResponse, - connect, - createServer, - createSecureServer, - getDefaultSettings, - getPackedSettings, - getUnpackedSettings -]); -export { - sensitiveHeaders, - getUnpackedSettings, - getPackedSettings, - getDefaultSettings, - defaultObject as default, - createServer, - createSecureServer, - constants, - connect, - Http2ServerResponse, - Http2ServerRequest -}; diff --git a/src/js/out/modules/node/https.js b/src/js/out/modules/node/https.js deleted file mode 100644 index 4fbf284d594f5f..00000000000000 --- a/src/js/out/modules/node/https.js +++ /dev/null @@ -1,54 +0,0 @@ -import * as http from "node:http"; -var request2 = function(input, options, cb) { - if (input && typeof input === "object" && !(input instanceof URL)) - input.protocol ??= "https:"; - else if (typeof options === "object") - options.protocol ??= "https:"; - return http.request(input, options, cb); -}, get = function(input, options, cb) { - const req = request2(input, options, cb); - return req.end(), req; -}, { - Agent, - Server, - METHODS, - STATUS_CODES, - createServer, - ServerResponse, - IncomingMessage, - maxHeaderSize, - validateHeaderName, - validateHeaderValue, - globalAgent -} = http, defaultExport = { - Agent, - Server, - METHODS, - STATUS_CODES, - createServer, - ServerResponse, - IncomingMessage, - request: request2, - get, - maxHeaderSize, - validateHeaderName, - validateHeaderValue, - globalAgent -}; -var https_default = defaultExport; -export { - validateHeaderValue, - validateHeaderName, - request2 as request, - maxHeaderSize, - globalAgent, - get, - https_default as default, - createServer, - ServerResponse, - Server, - STATUS_CODES, - METHODS, - IncomingMessage, - Agent -}; diff --git a/src/js/out/modules/node/inspector.js b/src/js/out/modules/node/inspector.js deleted file mode 100644 index 3a5073efc7aea4..00000000000000 --- a/src/js/out/modules/node/inspector.js +++ /dev/null @@ -1,60 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/inspector.ts -import EventEmitter from "node:events"; -var open = function() { - throwNotImplemented("node:inspector open", 2445); -}, close = function() { - throwNotImplemented("node:inspector close", 2445); -}, url = function() { - throwNotImplemented("node:inspector url", 2445); -}, waitForDebugger = function() { - throwNotImplemented("node:inspector waitForDebugger", 2445); -}; - -class Session extends EventEmitter { - constructor() { - super(); - throwNotImplemented("node:inspector Session", 2445); - } -} -var console = { - ...globalThis.console, - context: { - console: globalThis.console - } -}, defaultObject = { - console, - open, - close, - url, - waitForDebugger, - Session, - [Symbol.for("CommonJS")]: 0 -}; -hideFromStack(open, close, url, waitForDebugger, Session.prototype.constructor); -export { - waitForDebugger, - url, - open, - defaultObject as default, - console, - close, - Session -}; diff --git a/src/js/out/modules/node/net.js b/src/js/out/modules/node/net.js deleted file mode 100644 index ca64e39b01eb95..00000000000000 --- a/src/js/out/modules/node/net.js +++ /dev/null @@ -1,553 +0,0 @@ -import {Duplex} from "node:stream"; -import {EventEmitter} from "node:events"; -var isIPv4 = function(s) { - return IPv4Reg.test(s); -}, isIPv6 = function(s) { - return IPv6Reg.test(s); -}, isIP = function(s) { - if (isIPv4(s)) - return 4; - if (isIPv6(s)) - return 6; - return 0; -}, createConnection = function(port, host, connectListener) { - if (typeof port === "object") - return new Socket(port).connect(port, host, connectListener); - return new Socket().connect(port, host, connectListener); -}, emitErrorNextTick = function(self, error) { - self.emit("error", error); -}, emitListeningNextTick = function(self, onListen) { - if (typeof onListen === "function") - try { - onListen(); - } catch (err) { - self.emit("error", err); - } - self.emit("listening"); -}, createServer = function(options, connectionListener) { - return new Server(options, connectionListener); -}, v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])", v4Str = `(${v4Seg}[.]){3}${v4Seg}`, IPv4Reg = new RegExp(`^${v4Str}\$`), v6Seg = "(?:[0-9a-fA-F]{1,4})", IPv6Reg = new RegExp("^(" + `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + ")(%[0-9a-zA-Z-.:]{1,})?$"), { Bun, createFIFO, Object } = globalThis[Symbol.for("Bun.lazy")]("primordials"), { connect: bunConnect } = Bun, { setTimeout } = globalThis, bunTlsSymbol = Symbol.for("::buntls::"), bunSocketServerHandlers = Symbol.for("::bunsocket_serverhandlers::"), bunSocketServerConnections = Symbol.for("::bunnetserverconnections::"), bunSocketServerOptions = Symbol.for("::bunnetserveroptions::"), bunSocketInternal = Symbol.for("::bunnetsocketinternal::"), bunTLSConnectOptions = Symbol.for("::buntlsconnectoptions::"), SocketClass, Socket = function(InternalSocket) { - return SocketClass = InternalSocket, Object.defineProperty(SocketClass.prototype, Symbol.toStringTag, { - value: "Socket", - enumerable: !1 - }), Object.defineProperty(function Socket(options) { - return new InternalSocket(options); - }, Symbol.hasInstance, { - value(instance) { - return instance instanceof InternalSocket; - } - }); -}(class Socket2 extends Duplex { - static #Handlers = { - close: Socket2.#Close, - connectError(socket, error) { - socket.data.emit("error", error); - }, - data({ data: self }, buffer) { - self.bytesRead += buffer.length; - const queue = self.#readQueue; - if (queue.isEmpty()) { - if (self.push(buffer)) - return; - } - queue.push(buffer); - }, - drain: Socket2.#Drain, - end: Socket2.#Close, - error(socket, error) { - const self = socket.data, callback = self.#writeCallback; - if (callback) - self.#writeCallback = null, callback(error); - self.emit("error", error); - }, - open(socket) { - const self = socket.data; - socket.timeout(self.timeout), socket.ref(), self[bunSocketInternal] = socket, self.connecting = !1; - const options = self[bunTLSConnectOptions]; - if (options) { - const { session } = options; - if (session) - self.setSession(session); - } - if (!self.#upgraded) - self.emit("connect", self); - Socket2.#Drain(socket); - }, - handshake(socket, success, verifyError) { - const { data: self } = socket; - self._securePending = !1, self.secureConnecting = !1, self._secureEstablished = !!success, self.emit("secure", self); - const { checkServerIdentity } = self[bunTLSConnectOptions]; - if (!verifyError && typeof checkServerIdentity === "function" && self.servername) { - const cert = self.getPeerCertificate(!0); - verifyError = checkServerIdentity(self.servername, cert); - } - if (self._requestCert || self._rejectUnauthorized) { - if (verifyError) { - if (self.authorized = !1, self.authorizationError = verifyError.code || verifyError.message, self._rejectUnauthorized) { - self.destroy(verifyError); - return; - } - } - } else - self.authorized = !0; - self.emit("secureConnect", verifyError); - }, - timeout(socket) { - const self = socket.data; - self.emit("timeout", self); - }, - binaryType: "buffer" - }; - static #Close(socket) { - const self = socket.data; - if (self.#closed) - return; - self.#closed = !0, self[bunSocketInternal] = null; - const queue = self.#readQueue; - if (queue.isEmpty()) { - if (self.push(null)) - return; - } - queue.push(null); - } - static #Drain(socket) { - const self = socket.data, callback = self.#writeCallback; - if (callback) { - const chunk = self.#writeChunk, written = socket.write(chunk); - if (self.bytesWritten += written, written < chunk.length) - self.#writeChunk = chunk.slice(written); - else - self.#writeCallback = null, self.#writeChunk = null, callback(null); - } - } - static [bunSocketServerHandlers] = { - data: Socket2.#Handlers.data, - close(socket) { - Socket2.#Handlers.close(socket), this.data[bunSocketServerConnections]--; - }, - end(socket) { - Socket2.#Handlers.end(socket), this.data[bunSocketServerConnections]--; - }, - open(socket) { - const self = this.data, options = self[bunSocketServerOptions], { pauseOnConnect, connectionListener, InternalSocketClass, requestCert, rejectUnauthorized } = options, _socket = new InternalSocketClass({}); - if (_socket.isServer = !0, _socket._requestCert = requestCert, _socket._rejectUnauthorized = rejectUnauthorized, _socket.#attach(this.localPort, socket), self.maxConnections && self[bunSocketServerConnections] >= self.maxConnections) { - const data = { - localAddress: _socket.localAddress, - localPort: _socket.localPort, - localFamily: _socket.localFamily, - remoteAddress: _socket.remoteAddress, - remotePort: _socket.remotePort, - remoteFamily: _socket.remoteFamily || "IPv4" - }; - socket.end(), self.emit("drop", data); - return; - } - if (!pauseOnConnect) - _socket.resume(); - if (self[bunSocketServerConnections]++, typeof connectionListener == "function") - if (InternalSocketClass.name === "TLSSocket") - self.once("secureConnection", () => connectionListener(_socket)); - else - connectionListener(_socket); - self.emit("connection", _socket); - }, - handshake(socket, success, verifyError) { - const { data: self } = socket; - if (self.emit("secure", self), self._securePending = !1, self.secureConnecting = !1, self._secureEstablished = !!success, self._requestCert || self._rejectUnauthorized) { - if (verifyError) { - if (self.authorized = !1, self.authorizationError = verifyError.code || verifyError.message, self._rejectUnauthorized) { - self.destroy(verifyError); - return; - } - } - } else - self.authorized = !0; - self.emit("secureConnection", verifyError); - }, - error(socket, error) { - Socket2.#Handlers.error(socket, error), this.data.emit("error", error); - }, - timeout: Socket2.#Handlers.timeout, - connectError: Socket2.#Handlers.connectError, - drain: Socket2.#Handlers.drain, - binaryType: "buffer" - }; - bytesRead = 0; - bytesWritten = 0; - #closed = !1; - connecting = !1; - localAddress = "127.0.0.1"; - #readQueue = createFIFO(); - remotePort; - [bunSocketInternal] = null; - [bunTLSConnectOptions] = null; - timeout = 0; - #writeCallback; - #writeChunk; - #pendingRead; - isServer = !1; - _handle; - _parent; - _parentWrap; - #socket; - #upgraded; - constructor(options) { - const { socket, signal, write, read, allowHalfOpen = !1, ...opts } = options || {}; - super({ - ...opts, - allowHalfOpen, - readable: !0, - writable: !0 - }); - if (this._handle = this, this._parent = this, this._parentWrap = this, this.#pendingRead = void 0, this.#upgraded = !1, socket instanceof Socket2) - this.#socket = socket; - signal?.once("abort", () => this.destroy()), this.once("connect", () => this.emit("ready")); - } - address() { - return { - address: this.localAddress, - family: this.localFamily, - port: this.localPort - }; - } - get bufferSize() { - return this.writableLength; - } - #attach(port, socket) { - if (this.remotePort = port, socket.data = this, socket.timeout(this.timeout), socket.ref(), this[bunSocketInternal] = socket, this.connecting = !1, !this.#upgraded) - this.emit("connect", this); - Socket2.#Drain(socket); - } - connect(port, host, connectListener) { - var path, connection = this.#socket, _checkServerIdentity = void 0; - if (typeof port === "string") { - if (path = port, port = void 0, typeof host === "function") - connectListener = host, host = void 0; - } else if (typeof host == "function") { - if (typeof port === "string") - path = port, port = void 0; - connectListener = host, host = void 0; - } - if (typeof port == "object") { - var { - port, - host, - path, - socket, - localAddress, - localPort, - family, - hints, - lookup, - noDelay, - keepAlive, - keepAliveInitialDelay, - requestCert, - rejectUnauthorized, - pauseOnConnect, - servername, - checkServerIdentity, - session - } = port; - if (_checkServerIdentity = checkServerIdentity, this.servername = servername, socket) - connection = socket; - } - if (!pauseOnConnect) - this.resume(); - this.connecting = !0, this.remotePort = port; - const bunTLS = this[bunTlsSymbol]; - var tls = void 0; - if (typeof bunTLS === "function") { - if (tls = bunTLS.call(this, port, host, !0), this._requestCert = !0, this._rejectUnauthorized = rejectUnauthorized, tls) { - if (tls.rejectUnauthorized = rejectUnauthorized, tls.requestCert = !0, tls.session = session || tls.session, this.servername = tls.servername, tls.checkServerIdentity = _checkServerIdentity || tls.checkServerIdentity, this[bunTLSConnectOptions] = tls, !connection && tls.socket) - connection = tls.socket; - } - if (connection) { - if (typeof connection !== "object" || !(connection instanceof Socket2) || typeof connection[bunTlsSymbol] === "function") - throw new TypeError("socket must be an instance of net.Socket"); - } - if (this.authorized = !1, this.secureConnecting = !0, this._secureEstablished = !1, this._securePending = !0, connectListener) - this.on("secureConnect", connectListener); - } else if (connectListener) - this.on("connect", connectListener); - if (connection) { - const socket2 = connection[bunSocketInternal]; - if (socket2) { - this.connecting = !0, this.#upgraded = !0; - const result = socket2.upgradeTLS({ - data: this, - tls, - socket: Socket2.#Handlers - }); - if (result) { - const [raw, tls2] = result; - connection[bunSocketInternal] = raw, raw.timeout(raw.timeout), raw.connecting = !1, this[bunSocketInternal] = tls2; - } else - throw this[bunSocketInternal] = null, new Error("Invalid socket"); - } else - connection.once("connect", () => { - const socket3 = connection[bunSocketInternal]; - if (!socket3) - return; - this.connecting = !0, this.#upgraded = !0; - const result = socket3.upgradeTLS({ - data: this, - tls, - socket: Socket2.#Handlers - }); - if (result) { - const [raw, tls2] = result; - connection[bunSocketInternal] = raw, raw.timeout(raw.timeout), raw.connecting = !1, this[bunSocketInternal] = tls2; - } else - throw this[bunSocketInternal] = null, new Error("Invalid socket"); - }); - } else if (path) - bunConnect({ - data: this, - unix: path, - socket: Socket2.#Handlers, - tls - }).catch((error) => { - this.emit("error", error); - }); - else - bunConnect({ - data: this, - hostname: host || "localhost", - port, - socket: Socket2.#Handlers, - tls - }).catch((error) => { - this.emit("error", error); - }); - return this; - } - _destroy(err, callback) { - this[bunSocketInternal]?.end(), callback(err); - } - _final(callback) { - this[bunSocketInternal]?.end(), callback(); - } - get localAddress() { - return "127.0.0.1"; - } - get localFamily() { - return "IPv4"; - } - get localPort() { - return this[bunSocketInternal]?.localPort; - } - get pending() { - return this.connecting; - } - _read(size) { - const queue = this.#readQueue; - let chunk; - while (chunk = queue.peek()) { - if (!this.push(chunk)) - return; - queue.shift(); - } - } - get readyState() { - if (this.connecting) - return "opening"; - if (this.readable) - return this.writable ? "open" : "readOnly"; - else - return this.writable ? "writeOnly" : "closed"; - } - ref() { - this[bunSocketInternal]?.ref(); - } - get remoteAddress() { - return this[bunSocketInternal]?.remoteAddress; - } - get remoteFamily() { - return "IPv4"; - } - resetAndDestroy() { - this[bunSocketInternal]?.end(); - } - setKeepAlive(enable = !1, initialDelay = 0) { - return this; - } - setNoDelay(noDelay = !0) { - return this; - } - setTimeout(timeout, callback) { - if (this[bunSocketInternal]?.timeout(timeout), this.timeout = timeout, callback) - this.once("timeout", callback); - return this; - } - unref() { - this[bunSocketInternal]?.unref(); - } - _write(chunk, encoding, callback) { - if (typeof chunk == "string" && encoding !== "ascii") - chunk = Buffer.from(chunk, encoding); - var written = this[bunSocketInternal]?.write(chunk); - if (written == chunk.length) - callback(); - else if (this.#writeCallback) - callback(new Error("overlapping _write()")); - else { - if (written > 0) - if (typeof chunk == "string") - chunk = chunk.slice(written); - else - chunk = chunk.subarray(written); - this.#writeCallback = callback, this.#writeChunk = chunk; - } - } -}), connect = createConnection; - -class Server extends EventEmitter { - #server; - #listening = !1; - [bunSocketServerConnections] = 0; - [bunSocketServerOptions]; - maxConnections = 0; - constructor(options, connectionListener) { - super(); - if (typeof options === "function") - connectionListener = options, options = {}; - else if (options == null || typeof options === "object") - options = { ...options }; - else - throw new Error("bun-net-polyfill: invalid arguments"); - const { maxConnections } = options; - this.maxConnections = Number.isSafeInteger(maxConnections) && maxConnections > 0 ? maxConnections : 0, options.connectionListener = connectionListener, this[bunSocketServerOptions] = options; - } - ref() { - return this.#server?.ref(), this; - } - unref() { - return this.#server?.unref(), this; - } - close(callback) { - if (this.#server) { - if (this.#server.stop(!0), this.#server = null, this.#listening = !1, this[bunSocketServerConnections] = 0, this.emit("close"), typeof callback === "function") - callback(); - return this; - } - if (typeof callback === "function") { - const error = new Error("Server is not running"); - error.code = "ERR_SERVER_NOT_RUNNING", callback(error); - } - return this; - } - address() { - const server = this.#server; - if (server) { - const unix = server.unix; - if (unix) - return unix; - let address = server.hostname; - const type = isIP(address), port = server.port; - if (typeof port === "number") - return { - port, - address, - family: type ? `IPv${type}` : void 0 - }; - if (type) - return { - address, - family: type ? `IPv${type}` : void 0 - }; - return address; - } - return null; - } - getConnections(callback) { - if (typeof callback === "function") - callback(null, this.#server ? this[bunSocketServerConnections] : 0); - return this; - } - listen(port, hostname, onListen) { - let backlog, path, exclusive = !1; - if (typeof port === "string") { - if (Number.isSafeInteger(hostname)) { - if (hostname > 0) - backlog = hostname; - } else if (typeof hostname === "function") - onListen = hostname; - path = port, hostname = void 0, port = void 0; - } else { - if (typeof hostname === "function") - onListen = hostname, hostname = void 0; - if (typeof port === "function") - onListen = port, port = 0; - else if (typeof port === "object") { - const options = port; - options.signal?.addEventListener("abort", () => this.close()), hostname = options.host, exclusive = options.exclusive === !0; - const path2 = options.path; - if (port = options.port, !Number.isSafeInteger(port) || port < 0) - if (path2) - hostname = path2, port = void 0; - else { - let message = 'The argument \'options\' must have the property "port" or "path"'; - try { - message = `${message}. Received ${JSON.stringify(options)}`; - } catch { - } - const error = new TypeError(message); - throw error.code = "ERR_INVALID_ARG_VALUE", error; - } - else if (!Number.isSafeInteger(port) || port < 0) - port = 0; - if (typeof port.callback === "function") - onListen = port?.callback; - } else if (!Number.isSafeInteger(port) || port < 0) - port = 0; - hostname = hostname || "::"; - } - try { - var tls = void 0, TLSSocketClass = void 0; - const bunTLS = this[bunTlsSymbol], options = this[bunSocketServerOptions]; - if (typeof bunTLS === "function") - [tls, TLSSocketClass] = bunTLS.call(this, port, hostname, !1), options.servername = tls.serverName, options.InternalSocketClass = TLSSocketClass; - else - options.InternalSocketClass = SocketClass; - this.#server = Bun.listen(path ? { - exclusive, - unix: path, - tls, - socket: SocketClass[bunSocketServerHandlers] - } : { - exclusive, - port, - hostname, - tls, - socket: SocketClass[bunSocketServerHandlers] - }), this.#server.data = this, this.#listening = !0, setTimeout(emitListeningNextTick, 1, this, onListen); - } catch (err) { - this.#listening = !1, setTimeout(emitErrorNextTick, 1, this, err); - } - return this; - } -} -var net_default = { - createServer, - Server, - createConnection, - connect, - isIP, - isIPv4, - isIPv6, - Socket, - [Symbol.for("CommonJS")]: 0, - [Symbol.for("::bunternal::")]: SocketClass -}; -export { - isIPv6, - isIPv4, - isIP, - net_default as default, - createServer, - createConnection, - connect, - Socket, - Server -}; diff --git a/src/js/out/modules/node/os.js b/src/js/out/modules/node/os.js deleted file mode 100644 index cc457e06d5e088..00000000000000 --- a/src/js/out/modules/node/os.js +++ /dev/null @@ -1,85 +0,0 @@ -var bound = function(obj) { - return { - arch: obj.arch.bind(obj), - cpus: obj.cpus.bind(obj), - endianness: obj.endianness.bind(obj), - freemem: obj.freemem.bind(obj), - getPriority: obj.getPriority.bind(obj), - homedir: obj.homedir.bind(obj), - hostname: obj.hostname.bind(obj), - loadavg: obj.loadavg.bind(obj), - networkInterfaces: obj.networkInterfaces.bind(obj), - platform: obj.platform.bind(obj), - release: obj.release.bind(obj), - setPriority: obj.setPriority.bind(obj), - get tmpdir() { - return tmpdir; - }, - totalmem: obj.totalmem.bind(obj), - type: obj.type.bind(obj), - uptime: obj.uptime.bind(obj), - userInfo: obj.userInfo.bind(obj), - version: obj.version.bind(obj), - machine: obj.machine.bind(obj), - devNull: obj.devNull, - EOL: obj.EOL, - constants: obj.constants, - [Symbol.for("CommonJS")]: 0 - }; -}, tmpdir = function() { - var { Bun: Bun2 } = globalThis[Symbol.for("Bun.lazy")]("primordials"), env = Bun2.env; - return tmpdir = function() { - var path = env.TMPDIR || env.TMP || env.TEMP || "/tmp"; - const length = path.length; - if (length > 1 && path[length - 1] === "/") - path = path.slice(0, -1); - return path; - }, tmpdir(); -}, os = bound(Bun._Os()), { - arch, - cpus, - endianness, - freemem, - getPriority, - homedir, - hostname, - loadavg, - networkInterfaces, - platform, - release, - setPriority, - totalmem, - type, - uptime, - userInfo, - version, - machine, - devNull, - EOL, - constants -} = os, os_default = os; -export { - version, - userInfo, - uptime, - type, - totalmem, - tmpdir, - setPriority, - release, - platform, - networkInterfaces, - machine, - loadavg, - hostname, - homedir, - getPriority, - freemem, - endianness, - devNull, - os_default as default, - cpus, - constants, - arch, - EOL -}; diff --git a/src/js/out/modules/node/path.js b/src/js/out/modules/node/path.js deleted file mode 100644 index e9af36285dd002..00000000000000 --- a/src/js/out/modules/node/path.js +++ /dev/null @@ -1,59 +0,0 @@ -var bound = function(obj) { - var result = createModule({ - basename: obj.basename.bind(obj), - dirname: obj.dirname.bind(obj), - extname: obj.extname.bind(obj), - format: obj.format.bind(obj), - isAbsolute: obj.isAbsolute.bind(obj), - join: obj.join.bind(obj), - normalize: obj.normalize.bind(obj), - parse: obj.parse.bind(obj), - relative: obj.relative.bind(obj), - resolve: obj.resolve.bind(obj), - toNamespacedPath: obj.toNamespacedPath.bind(obj), - sep: obj.sep, - delimiter: obj.delimiter - }); - return result.default = result, result; -}, createModule = (obj) => Object.assign(Object.create(null), obj), path = bound(Bun._Path()), posix = bound(Bun._Path(!1)), win32 = bound(Bun._Path(!0)); -path.win32 = win32; -path.posix = posix; -var { - basename, - dirname, - extname, - format, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - toNamespacedPath, - sep, - delimiter, - __esModule -} = path; -path[Symbol.for("CommonJS")] = 0; -path.__esModule = !0; -var path_default = path; -export { - win32, - toNamespacedPath, - sep, - resolve, - relative, - posix, - parse, - normalize, - join, - isAbsolute, - format, - extname, - dirname, - delimiter, - path_default as default, - createModule, - basename, - __esModule -}; diff --git a/src/js/out/modules/node/path.posix.js b/src/js/out/modules/node/path.posix.js deleted file mode 100644 index e60e44ca01bee9..00000000000000 --- a/src/js/out/modules/node/path.posix.js +++ /dev/null @@ -1,49 +0,0 @@ -var bound = function(obj) { - return { - basename: obj.basename.bind(obj), - dirname: obj.dirname.bind(obj), - extname: obj.extname.bind(obj), - format: obj.format.bind(obj), - isAbsolute: obj.isAbsolute.bind(obj), - join: obj.join.bind(obj), - normalize: obj.normalize.bind(obj), - parse: obj.parse.bind(obj), - relative: obj.relative.bind(obj), - resolve: obj.resolve.bind(obj), - toNamespacedPath: obj.toNamespacedPath.bind(obj), - sep: obj.sep, - delimiter: obj.delimiter - }; -}, path = bound(Bun._Path(!1)); -path[Symbol.for("CommonJS")] = 0; -var { - basename, - dirname, - extname, - format, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - toNamespacedPath, - sep, - delimiter -} = path, path_posix_default = path; -export { - toNamespacedPath, - sep, - resolve, - relative, - parse, - normalize, - join, - isAbsolute, - format, - extname, - dirname, - delimiter, - path_posix_default as default, - basename -}; diff --git a/src/js/out/modules/node/path.win32.js b/src/js/out/modules/node/path.win32.js deleted file mode 100644 index d4a7a15ac5c513..00000000000000 --- a/src/js/out/modules/node/path.win32.js +++ /dev/null @@ -1,47 +0,0 @@ -var bound = function(obj) { - return { - basename: obj.basename.bind(obj), - dirname: obj.dirname.bind(obj), - extname: obj.extname.bind(obj), - format: obj.format.bind(obj), - isAbsolute: obj.isAbsolute.bind(obj), - join: obj.join.bind(obj), - normalize: obj.normalize.bind(obj), - parse: obj.parse.bind(obj), - relative: obj.relative.bind(obj), - resolve: obj.resolve.bind(obj), - toNamespacedPath: obj.toNamespacedPath.bind(obj), - sep: obj.sep, - delimiter: obj.delimiter - }; -}, path = bound(Bun._Path(!0)), { - basename, - dirname, - extname, - format, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - toNamespacedPath, - sep, - delimiter -} = path, path_win32_default = path; -export { - toNamespacedPath, - sep, - resolve, - relative, - parse, - normalize, - join, - isAbsolute, - format, - extname, - dirname, - delimiter, - path_win32_default as default, - basename -}; diff --git a/src/js/out/modules/node/perf_hooks.js b/src/js/out/modules/node/perf_hooks.js deleted file mode 100644 index af20677d76379c..00000000000000 --- a/src/js/out/modules/node/perf_hooks.js +++ /dev/null @@ -1,65 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/perf_hooks.js -var constants = { - NODE_PERFORMANCE_GC_MAJOR: 4, - NODE_PERFORMANCE_GC_MINOR: 1, - NODE_PERFORMANCE_GC_INCREMENTAL: 8, - NODE_PERFORMANCE_GC_WEAKCB: 16, - NODE_PERFORMANCE_GC_FLAGS_NO: 0, - NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: 2, - NODE_PERFORMANCE_GC_FLAGS_FORCED: 4, - NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: 8, - NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: 16, - NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: 32, - NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: 64 -}, performance = globalThis.performance; - -class PerformanceObserver { - constructor() { - throwNotImplemented("PerformanceObserver"); - } -} - -class PerformanceEntry { - constructor() { - throwNotImplemented("PerformanceEntry"); - } -} - -class PerformanceNodeTiming { - constructor() { - throw new Error("PerformanceNodeTiming is not supported in this environment."); - } -} -var perf_hooks_default = { - performance, - constants, - PerformanceEntry, - PerformanceNodeTiming, - [Symbol.for("CommonJS")]: 0 -}; -export { - performance, - perf_hooks_default as default, - constants, - PerformanceObserver, - PerformanceNodeTiming, - PerformanceEntry -}; diff --git a/src/js/out/modules/node/readline.js b/src/js/out/modules/node/readline.js deleted file mode 100644 index 6cfac471d797da..00000000000000 --- a/src/js/out/modules/node/readline.js +++ /dev/null @@ -1,1665 +0,0 @@ -import {EventEmitter} from "node:events"; -import {clearTimeout, setTimeout} from "node:timers"; -import {StringDecoder} from "node:string_decoder"; -var stripVTControlCharacters = function(str) { - return validateString(str, "str"), RegExpPrototypeSymbolReplace.call(ansi, str, ""); -}, promisify = function(original) { - if (validateFunction(original, "original"), original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - return validateFunction(fn, "util.promisify.custom"), ObjectDefineProperty(fn, kCustomPromisifiedSymbol, { - __proto__: null, - value: fn, - enumerable: !1, - writable: !1, - configurable: !0 - }); - } - var argumentNames = original[kCustomPromisifyArgsSymbol]; - function fn(...args) { - return new Promise((resolve, reject) => { - ArrayPrototypePush.call(args, (err, ...values) => { - if (err) - return reject(err); - if (argumentNames !== void 0 && values.length > 1) { - var obj = {}; - for (var i2 = 0;i2 < argumentNames.length; i2++) - obj[argumentNames[i2]] = values[i2]; - resolve(obj); - } else - resolve(values[0]); - }), ReflectApply(original, this, args); - }); - } - ObjectSetPrototypeOf(fn, ObjectGetPrototypeOf(original)), ObjectDefineProperty(fn, kCustomPromisifiedSymbol, { - __proto__: null, - value: fn, - enumerable: !1, - writable: !1, - configurable: !0 - }); - var descriptors = ObjectGetOwnPropertyDescriptors(original), propertiesValues = ObjectValues(descriptors); - for (var i = 0;i < propertiesValues.length; i++) - ObjectSetPrototypeOf(propertiesValues[i], null); - return ObjectDefineProperties(fn, descriptors); -}, getNodeErrorByName = function(typeName) { - var base = errorBases[typeName]; - if (base) - return base; - if (!ObjectKeys(VALID_NODE_ERROR_BASES).includes(typeName)) - throw new Error("Invalid NodeError type"); - var Base = VALID_NODE_ERROR_BASES[typeName]; - - class NodeError extends Base { - [kIsNodeError] = !0; - code; - constructor(msg, opts) { - super(msg, opts); - this.code = opts?.code || "ERR_GENERIC"; - } - toString() { - return `${this.name} [${this.code}]: ${this.message}`; - } - } - return errorBases[typeName] = NodeError, NodeError; -}, validateFunction = function(value, name) { - if (typeof value !== "function") - throw new ERR_INVALID_ARG_TYPE(name, "Function", value); -}, validateAbortSignal = function(signal, name) { - if (signal !== void 0 && (signal === null || typeof signal !== "object" || !("aborted" in signal))) - throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal); -}, validateArray = function(value, name, minLength = 0) { - if (!ArrayIsArray(value)) - throw new ERR_INVALID_ARG_TYPE(name, "Array", value); - if (value.length < minLength) { - var reason = `must be longer than ${minLength}`; - throw new ERR_INVALID_ARG_VALUE(name, value, reason); - } -}, validateString = function(value, name) { - if (typeof value !== "string") - throw new ERR_INVALID_ARG_TYPE(name, "string", value); -}, validateBoolean = function(value, name) { - if (typeof value !== "boolean") - throw new ERR_INVALID_ARG_TYPE(name, "boolean", value); -}; -var validateInteger = function(value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) { - if (typeof value !== "number") - throw new ERR_INVALID_ARG_TYPE(name, "number", value); - if (!NumberIsInteger(value)) - throw new ERR_OUT_OF_RANGE(name, "an integer", value); - if (value < min || value > max) - throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); -}, validateUint32 = function(value, name, positive = !1) { - if (typeof value !== "number") - throw new ERR_INVALID_ARG_TYPE(name, "number", value); - if (!NumberIsInteger(value)) - throw new ERR_OUT_OF_RANGE(name, "an integer", value); - var min = positive ? 1 : 0, max = 4294967295; - if (value < min || value > max) - throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); -}, CSI = function(strings, ...args) { - var ret = `${kEscape}[`; - for (var n = 0;n < strings.length; n++) - if (ret += strings[n], n < args.length) - ret += args[n]; - return ret; -}, charLengthLeft = function(str, i) { - if (i <= 0) - return 0; - if (i > 1 && StringPrototypeCodePointAt.call(str, i - 2) >= kUTF16SurrogateThreshold || StringPrototypeCodePointAt.call(str, i - 1) >= kUTF16SurrogateThreshold) - return 2; - return 1; -}, charLengthAt = function(str, i) { - if (str.length <= i) - return 1; - return StringPrototypeCodePointAt.call(str, i) >= kUTF16SurrogateThreshold ? 2 : 1; -}; -function* emitKeys(stream) { - while (!0) { - var ch = yield, s = ch, escaped = !1, keySeq = null, keyName, keyCtrl2 = !1, keyMeta = !1, keyShift = !1; - if (ch === kEscape) { - if (escaped = !0, s += ch = yield, ch === kEscape) - s += ch = yield; - } - if (escaped && (ch === "O" || ch === "[")) { - var code = ch, modifier = 0; - if (ch === "O") { - if (s += ch = yield, ch >= "0" && ch <= "9") - modifier = (ch >> 0) - 1, s += ch = yield; - code += ch; - } else if (ch === "[") { - if (s += ch = yield, ch === "[") - code += ch, s += ch = yield; - var cmdStart = s.length - 1; - if (ch >= "0" && ch <= "9") { - if (s += ch = yield, ch >= "0" && ch <= "9") - s += ch = yield; - } - if (ch === ";") { - if (s += ch = yield, ch >= "0" && ch <= "9") - s += yield; - } - var cmd = StringPrototypeSlice.call(s, cmdStart), match; - if (match = RegExpPrototypeExec.call(/^(\d\d?)(;(\d))?([~^$])$/, cmd)) - code += match[1] + match[4], modifier = (match[3] || 1) - 1; - else if (match = RegExpPrototypeExec.call(/^((\d;)?(\d))?([A-Za-z])$/, cmd)) - code += match[4], modifier = (match[3] || 1) - 1; - else - code += cmd; - } - switch (keyCtrl2 = !!(modifier & 4), keyMeta = !!(modifier & 10), keyShift = !!(modifier & 1), code) { - case "[P": - keyName = "f1"; - break; - case "[Q": - keyName = "f2"; - break; - case "[R": - keyName = "f3"; - break; - case "[S": - keyName = "f4"; - break; - case "OP": - keyName = "f1"; - break; - case "OQ": - keyName = "f2"; - break; - case "OR": - keyName = "f3"; - break; - case "OS": - keyName = "f4"; - break; - case "[11~": - keyName = "f1"; - break; - case "[12~": - keyName = "f2"; - break; - case "[13~": - keyName = "f3"; - break; - case "[14~": - keyName = "f4"; - break; - case "[[A": - keyName = "f1"; - break; - case "[[B": - keyName = "f2"; - break; - case "[[C": - keyName = "f3"; - break; - case "[[D": - keyName = "f4"; - break; - case "[[E": - keyName = "f5"; - break; - case "[15~": - keyName = "f5"; - break; - case "[17~": - keyName = "f6"; - break; - case "[18~": - keyName = "f7"; - break; - case "[19~": - keyName = "f8"; - break; - case "[20~": - keyName = "f9"; - break; - case "[21~": - keyName = "f10"; - break; - case "[23~": - keyName = "f11"; - break; - case "[24~": - keyName = "f12"; - break; - case "[A": - keyName = "up"; - break; - case "[B": - keyName = "down"; - break; - case "[C": - keyName = "right"; - break; - case "[D": - keyName = "left"; - break; - case "[E": - keyName = "clear"; - break; - case "[F": - keyName = "end"; - break; - case "[H": - keyName = "home"; - break; - case "OA": - keyName = "up"; - break; - case "OB": - keyName = "down"; - break; - case "OC": - keyName = "right"; - break; - case "OD": - keyName = "left"; - break; - case "OE": - keyName = "clear"; - break; - case "OF": - keyName = "end"; - break; - case "OH": - keyName = "home"; - break; - case "[1~": - keyName = "home"; - break; - case "[2~": - keyName = "insert"; - break; - case "[3~": - keyName = "delete"; - break; - case "[4~": - keyName = "end"; - break; - case "[5~": - keyName = "pageup"; - break; - case "[6~": - keyName = "pagedown"; - break; - case "[[5~": - keyName = "pageup"; - break; - case "[[6~": - keyName = "pagedown"; - break; - case "[7~": - keyName = "home"; - break; - case "[8~": - keyName = "end"; - break; - case "[a": - keyName = "up", keyShift = !0; - break; - case "[b": - keyName = "down", keyShift = !0; - break; - case "[c": - keyName = "right", keyShift = !0; - break; - case "[d": - keyName = "left", keyShift = !0; - break; - case "[e": - keyName = "clear", keyShift = !0; - break; - case "[2$": - keyName = "insert", keyShift = !0; - break; - case "[3$": - keyName = "delete", keyShift = !0; - break; - case "[5$": - keyName = "pageup", keyShift = !0; - break; - case "[6$": - keyName = "pagedown", keyShift = !0; - break; - case "[7$": - keyName = "home", keyShift = !0; - break; - case "[8$": - keyName = "end", keyShift = !0; - break; - case "Oa": - keyName = "up", keyCtrl2 = !0; - break; - case "Ob": - keyName = "down", keyCtrl2 = !0; - break; - case "Oc": - keyName = "right", keyCtrl2 = !0; - break; - case "Od": - keyName = "left", keyCtrl2 = !0; - break; - case "Oe": - keyName = "clear", keyCtrl2 = !0; - break; - case "[2^": - keyName = "insert", keyCtrl2 = !0; - break; - case "[3^": - keyName = "delete", keyCtrl2 = !0; - break; - case "[5^": - keyName = "pageup", keyCtrl2 = !0; - break; - case "[6^": - keyName = "pagedown", keyCtrl2 = !0; - break; - case "[7^": - keyName = "home", keyCtrl2 = !0; - break; - case "[8^": - keyName = "end", keyCtrl2 = !0; - break; - case "[Z": - keyName = "tab", keyShift = !0; - break; - default: - keyName = "undefined"; - break; - } - } else if (ch === "\r") - keyName = "return", keyMeta = escaped; - else if (ch === "\n") - keyName = "enter", keyMeta = escaped; - else if (ch === "\t") - keyName = "tab", keyMeta = escaped; - else if (ch === "\b" || ch === "\x7F") - keyName = "backspace", keyMeta = escaped; - else if (ch === kEscape) - keyName = "escape", keyMeta = escaped; - else if (ch === " ") - keyName = "space", keyMeta = escaped; - else if (!escaped && ch <= "\x1A") - keyName = StringFromCharCode(StringPrototypeCharCodeAt.call(ch) + StringPrototypeCharCodeAt.call("a") - 1), keyCtrl2 = !0; - else if (RegExpPrototypeExec.call(/^[0-9A-Za-z]$/, ch) !== null) - keyName = StringPrototypeToLowerCase.call(ch), keyShift = RegExpPrototypeExec.call(/^[A-Z]$/, ch) !== null, keyMeta = escaped; - else if (escaped) - keyName = ch.length ? void 0 : "escape", keyMeta = !0; - if (keySeq = s, s.length !== 0 && (keyName !== void 0 || escaped)) - stream.emit("keypress", escaped ? void 0 : s, { - sequence: keySeq, - name: keyName, - ctrl: keyCtrl2, - meta: keyMeta, - shift: keyShift - }); - else if (charLengthAt(s, 0) === s.length) - stream.emit("keypress", s, { - sequence: keySeq, - name: keyName, - ctrl: keyCtrl2, - meta: keyMeta, - shift: keyShift - }); - } -} -var commonPrefix = function(strings) { - if (strings.length === 0) - return ""; - if (strings.length === 1) - return strings[0]; - var sorted = ArrayPrototypeSort.call(ArrayPrototypeSlice.call(strings)), min = sorted[0], max = sorted[sorted.length - 1]; - for (var i = 0;i < min.length; i++) - if (min[i] !== max[i]) - return StringPrototypeSlice.call(min, 0, i); - return min; -}, cursorTo = function(stream, x, y, callback) { - if (callback !== void 0) - validateFunction(callback, "callback"); - if (typeof y === "function") - callback = y, y = void 0; - if (NumberIsNaN(x)) - throw new ERR_INVALID_ARG_VALUE("x", x); - if (NumberIsNaN(y)) - throw new ERR_INVALID_ARG_VALUE("y", y); - if (stream == null || typeof x !== "number" && typeof y !== "number") { - if (typeof callback === "function") - process.nextTick(callback, null); - return !0; - } - if (typeof x !== "number") - throw new ERR_INVALID_CURSOR_POS; - var data = typeof y !== "number" ? CSI`${x + 1}G` : CSI`${y + 1};${x + 1}H`; - return stream.write(data, callback); -}, moveCursor = function(stream, dx, dy, callback) { - if (callback !== void 0) - validateFunction(callback, "callback"); - if (stream == null || !(dx || dy)) { - if (typeof callback === "function") - process.nextTick(callback, null); - return !0; - } - var data = ""; - if (dx < 0) - data += CSI`${-dx}D`; - else if (dx > 0) - data += CSI`${dx}C`; - if (dy < 0) - data += CSI`${-dy}A`; - else if (dy > 0) - data += CSI`${dy}B`; - return stream.write(data, callback); -}, clearLine = function(stream, dir, callback) { - if (callback !== void 0) - validateFunction(callback, "callback"); - if (stream === null || stream === void 0) { - if (typeof callback === "function") - process.nextTick(callback, null); - return !0; - } - var type = dir < 0 ? kClearToLineBeginning : dir > 0 ? kClearToLineEnd : kClearLine; - return stream.write(type, callback); -}, clearScreenDown = function(stream, callback) { - if (callback !== void 0) - validateFunction(callback, "callback"); - if (stream === null || stream === void 0) { - if (typeof callback === "function") - process.nextTick(callback, null); - return !0; - } - return stream.write(kClearScreenDown, callback); -}, emitKeypressEvents = function(stream, iface = {}) { - if (stream[KEYPRESS_DECODER]) - return; - stream[KEYPRESS_DECODER] = new StringDecoder("utf8"), stream[ESCAPE_DECODER] = emitKeys(stream), stream[ESCAPE_DECODER].next(); - var triggerEscape = () => stream[ESCAPE_DECODER].next(""), { escapeCodeTimeout = ESCAPE_CODE_TIMEOUT } = iface, timeoutId; - function onData(input) { - if (stream.listenerCount("keypress") > 0) { - var string = stream[KEYPRESS_DECODER].write(input); - if (string) { - clearTimeout(timeoutId), iface[kSawKeyPress] = charLengthAt(string, 0) === string.length, iface.isCompletionEnabled = !1; - var length = 0; - for (var character of new SafeStringIterator(string)) { - if (length += character.length, length === string.length) - iface.isCompletionEnabled = !0; - try { - if (stream[ESCAPE_DECODER].next(character), length === string.length && character === kEscape) - timeoutId = setTimeout(triggerEscape, escapeCodeTimeout); - } catch (err) { - throw stream[ESCAPE_DECODER] = emitKeys(stream), stream[ESCAPE_DECODER].next(), err; - } - } - } - } else - stream.removeListener("data", onData), stream.on("newListener", onNewListener); - } - function onNewListener(event) { - if (event === "keypress") - stream.on("data", onData), stream.removeListener("newListener", onNewListener); - } - if (stream.listenerCount("keypress") > 0) - stream.on("data", onData); - else - stream.on("newListener", onNewListener); -}, onSelfCloseWithTerminal = function() { - var input = this.input, output = this.output; - if (!input) - throw new Error("Input not set, invalid state for readline!"); - if (input.removeListener("keypress", this[kOnKeyPress]), input.removeListener("error", this[kOnError]), input.removeListener("end", this[kOnTermEnd]), output !== null && output !== void 0) - output.removeListener("resize", this[kOnResize]); -}, onSelfCloseWithoutTerminal = function() { - var input = this.input; - if (!input) - throw new Error("Input not set, invalid state for readline!"); - input.removeListener("data", this[kOnData]), input.removeListener("error", this[kOnError]), input.removeListener("end", this[kOnEnd]); -}, onError = function(err) { - this.emit("error", err); -}, onData = function(data) { - debug("onData"), this[kNormalWrite](data); -}, onEnd = function() { - if (debug("onEnd"), typeof this[kLine_buffer] === "string" && this[kLine_buffer].length > 0) - this.emit("line", this[kLine_buffer]); - this.close(); -}, onTermEnd = function() { - if (debug("onTermEnd"), typeof this.line === "string" && this.line.length > 0) - this.emit("line", this.line); - this.close(); -}, onKeyPress = function(s, key) { - if (this[kTtyWrite](s, key), key && key.sequence) { - var ch = StringPrototypeCodePointAt.call(key.sequence, 0); - if (ch >= 55296 && ch <= 57343) - this[kRefreshLine](); - } -}, onResize = function() { - this[kRefreshLine](); -}, InterfaceConstructor = function(input, output, completer, terminal) { - if (!(this instanceof InterfaceConstructor)) - return new InterfaceConstructor(input, output, completer, terminal); - EventEmitter.call(this), this[kOnSelfCloseWithoutTerminal] = onSelfCloseWithoutTerminal.bind(this), this[kOnSelfCloseWithTerminal] = onSelfCloseWithTerminal.bind(this), this[kOnError] = onError.bind(this), this[kOnData] = onData.bind(this), this[kOnEnd] = onEnd.bind(this), this[kOnTermEnd] = onTermEnd.bind(this), this[kOnKeyPress] = onKeyPress.bind(this), this[kOnResize] = onResize.bind(this), this[kSawReturnAt] = 0, this.isCompletionEnabled = !0, this[kSawKeyPress] = !1, this[kPreviousKey] = null, this.escapeCodeTimeout = ESCAPE_CODE_TIMEOUT, this.tabSize = 8; - var history, historySize, removeHistoryDuplicates = !1, crlfDelay, prompt = "> ", signal; - if (input?.input) { - output = input.output, completer = input.completer, terminal = input.terminal, history = input.history, historySize = input.historySize, signal = input.signal; - var tabSize = input.tabSize; - if (tabSize !== void 0) - validateUint32(tabSize, "tabSize", !0), this.tabSize = tabSize; - removeHistoryDuplicates = input.removeHistoryDuplicates; - var inputPrompt = input.prompt; - if (inputPrompt !== void 0) - prompt = inputPrompt; - var inputEscapeCodeTimeout = input.escapeCodeTimeout; - if (inputEscapeCodeTimeout !== void 0) - if (NumberIsFinite(inputEscapeCodeTimeout)) - this.escapeCodeTimeout = inputEscapeCodeTimeout; - else - throw new ERR_INVALID_ARG_VALUE("input.escapeCodeTimeout", this.escapeCodeTimeout); - if (signal) - validateAbortSignal(signal, "options.signal"); - crlfDelay = input.crlfDelay, input = input.input; - } - if (completer !== void 0 && typeof completer !== "function") - throw new ERR_INVALID_ARG_VALUE("completer", completer); - if (history === void 0) - history = []; - else - validateArray(history, "history"); - if (historySize === void 0) - historySize = kHistorySize; - if (typeof historySize !== "number" || NumberIsNaN(historySize) || historySize < 0) - throw new ERR_INVALID_ARG_VALUE("historySize", historySize); - if (terminal === void 0 && !(output === null || output === void 0)) - terminal = !!output.isTTY; - if (this.line = "", this[kSubstringSearch] = null, this.output = output, this.input = input, this[kUndoStack] = [], this[kRedoStack] = [], this.history = history, this.historySize = historySize, this[kKillRing] = [], this[kKillRingCursor] = 0, this.removeHistoryDuplicates = !!removeHistoryDuplicates, this.crlfDelay = crlfDelay ? MathMax(kMincrlfDelay, crlfDelay) : kMincrlfDelay, this.completer = completer, this.setPrompt(prompt), this.terminal = !!terminal, this[kLineObjectStream] = void 0, input.on("error", this[kOnError]), !this.terminal) - input.on("data", this[kOnData]), input.on("end", this[kOnEnd]), this.once("close", this[kOnSelfCloseWithoutTerminal]), this[kDecoder] = new StringDecoder("utf8"); - else { - if (emitKeypressEvents(input, this), input.on("keypress", this[kOnKeyPress]), input.on("end", this[kOnTermEnd]), this[kSetRawMode](!0), this.terminal = !0, this.cursor = 0, this.historyIndex = -1, output !== null && output !== void 0) - output.on("resize", this[kOnResize]); - this.once("close", this[kOnSelfCloseWithTerminal]); - } - if (signal) { - var onAborted = (() => this.close()).bind(this); - if (signal.aborted) - process.nextTick(onAborted); - else - signal.addEventListener("abort", onAborted, { once: !0 }), this.once("close", () => signal.removeEventListener("abort", onAborted)); - } - this.line = "", input.resume(); -}, Interface = function(input, output, completer, terminal) { - if (!(this instanceof Interface)) - return new Interface(input, output, completer, terminal); - if (input?.input && typeof input.completer === "function" && input.completer.length !== 2) { - var { completer } = input; - input.completer = (v, cb) => cb(null, completer(v)); - } else if (typeof completer === "function" && completer.length !== 2) { - var realCompleter = completer; - completer = (v, cb) => cb(null, realCompleter(v)); - } - InterfaceConstructor.call(this, input, output, completer, terminal); -}, createInterface = function(input, output, completer, terminal) { - return new Interface(input, output, completer, terminal); -}; -var { Array, RegExp, String, Bun } = globalThis[Symbol.for("Bun.lazy")]("primordials"), isWritable, { inspect } = Bun, debug = process.env.BUN_JS_DEBUG ? console.log : () => { -}, SymbolAsyncIterator = Symbol.asyncIterator, SymbolIterator = Symbol.iterator, SymbolFor = Symbol.for, SymbolReplace = Symbol.replace, ArrayFrom = Array.from, ArrayIsArray = Array.isArray, ArrayPrototypeFilter = Array.prototype.filter, ArrayPrototypeSort = Array.prototype.sort, ArrayPrototypeIndexOf = Array.prototype.indexOf, ArrayPrototypeJoin = Array.prototype.join, ArrayPrototypeMap = Array.prototype.map, ArrayPrototypePop = Array.prototype.pop, ArrayPrototypePush = Array.prototype.push, ArrayPrototypeSlice = Array.prototype.slice, ArrayPrototypeSplice = Array.prototype.splice, ArrayPrototypeReverse = Array.prototype.reverse, ArrayPrototypeShift = Array.prototype.shift, ArrayPrototypeUnshift = Array.prototype.unshift, RegExpPrototypeExec = RegExp.prototype.exec, RegExpPrototypeSymbolReplace = RegExp.prototype[SymbolReplace], StringFromCharCode = String.fromCharCode, StringPrototypeCharCodeAt = String.prototype.charCodeAt, StringPrototypeCodePointAt = String.prototype.codePointAt, StringPrototypeSlice = String.prototype.slice, StringPrototypeToLowerCase = String.prototype.toLowerCase, StringPrototypeEndsWith = String.prototype.endsWith, StringPrototypeRepeat = String.prototype.repeat, StringPrototypeStartsWith = String.prototype.startsWith, StringPrototypeTrim = String.prototype.trim, StringPrototypeNormalize = String.prototype.normalize, NumberIsNaN = Number.isNaN, NumberIsFinite = Number.isFinite, NumberIsInteger = Number.isInteger, NumberMAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER, MathCeil = Math.ceil, MathFloor = Math.floor, MathMax = Math.max, MathMaxApply = Math.max.apply, DateNow = Date.now, FunctionPrototype = Function.prototype, StringPrototype = String.prototype, StringPrototypeSymbolIterator = StringPrototype[SymbolIterator], StringIteratorPrototypeNext = StringPrototypeSymbolIterator.call("").next, ObjectSetPrototypeOf = Object.setPrototypeOf, ObjectDefineProperty = Object.defineProperty, ObjectDefineProperties = Object.defineProperties, ObjectFreeze = Object.freeze; -var { create: ObjectCreate, keys: ObjectKeys } = Object; -var createSafeIterator = (factory, next) => { - class SafeIterator { - #iterator; - constructor(iterable) { - this.#iterator = factory.call(iterable); - } - next() { - return next.call(this.#iterator); - } - [SymbolIterator]() { - return this; - } - } - return ObjectSetPrototypeOf(SafeIterator.prototype, null), ObjectFreeze(SafeIterator.prototype), ObjectFreeze(SafeIterator), SafeIterator; -}, SafeStringIterator = createSafeIterator(StringPrototypeSymbolIterator, StringIteratorPrototypeNext), isFullWidthCodePoint = (code) => { - return code >= 4352 && (code <= 4447 || code === 9001 || code === 9002 || code >= 11904 && code <= 12871 && code !== 12351 || code >= 12880 && code <= 19903 || code >= 19968 && code <= 42182 || code >= 43360 && code <= 43388 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65040 && code <= 65049 || code >= 65072 && code <= 65131 || code >= 65281 && code <= 65376 || code >= 65504 && code <= 65510 || code >= 110592 && code <= 110593 || code >= 127488 && code <= 127569 || code >= 127744 && code <= 128591 || code >= 131072 && code <= 262141); -}, isZeroWidthCodePoint = (code) => { - return code <= 31 || code >= 127 && code <= 159 || code >= 768 && code <= 879 || code >= 8203 && code <= 8207 || code >= 8400 && code <= 8447 || code >= 65024 && code <= 65039 || code >= 65056 && code <= 65071 || code >= 917760 && code <= 917999; -}, getStringWidth = function getStringWidth2(str, removeControlChars = !0) { - var width = 0; - if (removeControlChars) - str = stripVTControlCharacters(str); - str = StringPrototypeNormalize.call(str, "NFC"); - for (var char of new SafeStringIterator(str)) { - var code = StringPrototypeCodePointAt.call(char, 0); - if (isFullWidthCodePoint(code)) - width += 2; - else if (!isZeroWidthCodePoint(code)) - width++; - } - return width; -}, ansiPattern = "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", ansi = new RegExp(ansiPattern, "g"), kCustomPromisifiedSymbol = SymbolFor("nodejs.util.promisify.custom"), kCustomPromisifyArgsSymbol = Symbol("customPromisifyArgs"); -promisify.custom = kCustomPromisifiedSymbol; -var kUTF16SurrogateThreshold = 65536, kEscape = "\x1B", kSubstringSearch = Symbol("kSubstringSearch"), kIsNodeError = Symbol("kIsNodeError"), errorBases = {}, VALID_NODE_ERROR_BASES = { - TypeError, - RangeError, - Error -}, NodeError = getNodeErrorByName("Error"), NodeTypeError = getNodeErrorByName("TypeError"), NodeRangeError = getNodeErrorByName("RangeError"); - -class ERR_INVALID_ARG_TYPE extends NodeTypeError { - constructor(name, type, value) { - super(`The "${name}" argument must be of type ${type}. Received type ${typeof value}`, { - code: "ERR_INVALID_ARG_TYPE" - }); - } -} - -class ERR_INVALID_ARG_VALUE extends NodeTypeError { - constructor(name, value, reason = "not specified") { - super(`The value "${String(value)}" is invalid for argument '${name}'. Reason: ${reason}`, { - code: "ERR_INVALID_ARG_VALUE" - }); - } -} - -class ERR_INVALID_CURSOR_POS extends NodeTypeError { - constructor() { - super("Cannot set cursor row without setting its column", { - code: "ERR_INVALID_CURSOR_POS" - }); - } -} - -class ERR_OUT_OF_RANGE extends NodeRangeError { - constructor(name, range, received) { - super(`The value of "${name}" is out of range. It must be ${range}. Received ${received}`, { - code: "ERR_OUT_OF_RANGE" - }); - } -} - -class ERR_USE_AFTER_CLOSE extends NodeError { - constructor() { - super("This socket has been ended by the other party", { - code: "ERR_USE_AFTER_CLOSE" - }); - } -} - -class AbortError extends Error { - code; - constructor() { - super("The operation was aborted"); - this.code = "ABORT_ERR"; - } -} -var kClearLine, kClearScreenDown, kClearToLineBeginning, kClearToLineEnd; -CSI.kEscape = kEscape; -CSI.kClearLine = kClearLine = CSI`2K`; -CSI.kClearScreenDown = kClearScreenDown = CSI`0J`; -CSI.kClearToLineBeginning = kClearToLineBeginning = CSI`1K`; -CSI.kClearToLineEnd = kClearToLineEnd = CSI`0K`; -var KEYPRESS_DECODER = Symbol("keypress-decoder"), ESCAPE_DECODER = Symbol("escape-decoder"), ESCAPE_CODE_TIMEOUT = 500, kEmptyObject = ObjectFreeze(ObjectCreate(null)), kHistorySize = 30, kMaxUndoRedoStackSize = 2048, kMincrlfDelay = 100, lineEnding = /\r?\n|\r(?!\n)/g, kMaxLengthOfKillRing = 32, kLineObjectStream = Symbol("line object stream"), kQuestionCancel = Symbol("kQuestionCancel"), kQuestion = Symbol("kQuestion"), kAddHistory = Symbol("_addHistory"), kBeforeEdit = Symbol("_beforeEdit"), kDecoder = Symbol("_decoder"), kDeleteLeft = Symbol("_deleteLeft"), kDeleteLineLeft = Symbol("_deleteLineLeft"), kDeleteLineRight = Symbol("_deleteLineRight"), kDeleteRight = Symbol("_deleteRight"), kDeleteWordLeft = Symbol("_deleteWordLeft"), kDeleteWordRight = Symbol("_deleteWordRight"), kGetDisplayPos = Symbol("_getDisplayPos"), kHistoryNext = Symbol("_historyNext"), kHistoryPrev = Symbol("_historyPrev"), kInsertString = Symbol("_insertString"), kLine = Symbol("_line"), kLine_buffer = Symbol("_line_buffer"), kKillRing = Symbol("_killRing"), kKillRingCursor = Symbol("_killRingCursor"), kMoveCursor = Symbol("_moveCursor"), kNormalWrite = Symbol("_normalWrite"), kOldPrompt = Symbol("_oldPrompt"), kOnLine = Symbol("_onLine"), kPreviousKey = Symbol("_previousKey"), kPrompt = Symbol("_prompt"), kPushToKillRing = Symbol("_pushToKillRing"), kPushToUndoStack = Symbol("_pushToUndoStack"), kQuestionCallback = Symbol("_questionCallback"), kRedo = Symbol("_redo"), kRedoStack = Symbol("_redoStack"), kRefreshLine = Symbol("_refreshLine"), kSawKeyPress = Symbol("_sawKeyPress"), kSawReturnAt = Symbol("_sawReturnAt"), kSetRawMode = Symbol("_setRawMode"), kTabComplete = Symbol("_tabComplete"), kTabCompleter = Symbol("_tabCompleter"), kTtyWrite = Symbol("_ttyWrite"), kUndo = Symbol("_undo"), kUndoStack = Symbol("_undoStack"), kWordLeft = Symbol("_wordLeft"), kWordRight = Symbol("_wordRight"), kWriteToOutput = Symbol("_writeToOutput"), kYank = Symbol("_yank"), kYanking = Symbol("_yanking"), kYankPop = Symbol("_yankPop"), kFirstEventParam = Symbol("nodejs.kFirstEventParam"), kOnSelfCloseWithTerminal = Symbol("_onSelfCloseWithTerminal"), kOnSelfCloseWithoutTerminal = Symbol("_onSelfCloseWithoutTerminal"), kOnKeyPress = Symbol("_onKeyPress"), kOnError = Symbol("_onError"), kOnData = Symbol("_onData"), kOnEnd = Symbol("_onEnd"), kOnTermEnd = Symbol("_onTermEnd"), kOnResize = Symbol("_onResize"); -ObjectSetPrototypeOf(InterfaceConstructor.prototype, EventEmitter.prototype); -var _Interface = class Interface2 extends InterfaceConstructor { - constructor(input, output, completer, terminal) { - super(input, output, completer, terminal); - } - get columns() { - var output = this.output; - if (output && output.columns) - return output.columns; - return Infinity; - } - setPrompt(prompt) { - this[kPrompt] = prompt; - } - getPrompt() { - return this[kPrompt]; - } - [kSetRawMode](mode) { - var input = this.input, { setRawMode, wasInRawMode } = input; - return debug("setRawMode", mode, "set!"), wasInRawMode; - } - prompt(preserveCursor) { - if (this.paused) - this.resume(); - if (this.terminal) { - if (!preserveCursor) - this.cursor = 0; - this[kRefreshLine](); - } else - this[kWriteToOutput](this[kPrompt]); - } - [kQuestion](query, cb) { - if (this.closed) - throw new ERR_USE_AFTER_CLOSE("readline"); - if (this[kQuestionCallback]) - this.prompt(); - else - this[kOldPrompt] = this[kPrompt], this.setPrompt(query), this[kQuestionCallback] = cb, this.prompt(); - } - [kOnLine](line) { - if (this[kQuestionCallback]) { - var cb = this[kQuestionCallback]; - this[kQuestionCallback] = null, this.setPrompt(this[kOldPrompt]), cb(line); - } else - this.emit("line", line); - } - [kBeforeEdit](oldText, oldCursor) { - this[kPushToUndoStack](oldText, oldCursor); - } - [kQuestionCancel]() { - if (this[kQuestionCallback]) - this[kQuestionCallback] = null, this.setPrompt(this[kOldPrompt]), this.clearLine(); - } - [kWriteToOutput](stringToWrite) { - if (validateString(stringToWrite, "stringToWrite"), this.output !== null && this.output !== void 0) - this.output.write(stringToWrite); - } - [kAddHistory]() { - if (this.line.length === 0) - return ""; - if (this.historySize === 0) - return this.line; - if (StringPrototypeTrim.call(this.line).length === 0) - return this.line; - if (this.history.length === 0 || this.history[0] !== this.line) { - if (this.removeHistoryDuplicates) { - var dupIndex = ArrayPrototypeIndexOf.call(this.history, this.line); - if (dupIndex !== -1) - ArrayPrototypeSplice.call(this.history, dupIndex, 1); - } - if (ArrayPrototypeUnshift.call(this.history, this.line), this.history.length > this.historySize) - ArrayPrototypePop.call(this.history); - } - this.historyIndex = -1; - var line = this.history[0]; - return this.emit("history", this.history), line; - } - [kRefreshLine]() { - var line = this[kPrompt] + this.line, dispPos = this[kGetDisplayPos](line), lineCols = dispPos.cols, lineRows = dispPos.rows, cursorPos = this.getCursorPos(), prevRows = this.prevRows || 0; - if (prevRows > 0) - moveCursor(this.output, 0, -prevRows); - if (cursorTo(this.output, 0), clearScreenDown(this.output), this[kWriteToOutput](line), lineCols === 0) - this[kWriteToOutput](" "); - cursorTo(this.output, cursorPos.cols); - var diff = lineRows - cursorPos.rows; - if (diff > 0) - moveCursor(this.output, 0, -diff); - this.prevRows = cursorPos.rows; - } - close() { - if (this.closed) - return; - if (this.pause(), this.terminal) - this[kSetRawMode](!1); - this.closed = !0, this.emit("close"); - } - pause() { - if (this.paused) - return; - return this.input.pause(), this.paused = !0, this.emit("pause"), this; - } - resume() { - if (!this.paused) - return; - return this.input.resume(), this.paused = !1, this.emit("resume"), this; - } - write(d, key) { - if (this.paused) - this.resume(); - if (this.terminal) - this[kTtyWrite](d, key); - else - this[kNormalWrite](d); - } - [kNormalWrite](b) { - if (b === void 0) - return; - var string = this[kDecoder].write(b); - if (this[kSawReturnAt] && DateNow() - this[kSawReturnAt] <= this.crlfDelay) { - if (StringPrototypeCodePointAt.call(string) === 10) - string = StringPrototypeSlice.call(string, 1); - this[kSawReturnAt] = 0; - } - var newPartContainsEnding = RegExpPrototypeExec.call(lineEnding, string); - if (newPartContainsEnding !== null) { - if (this[kLine_buffer]) - string = this[kLine_buffer] + string, this[kLine_buffer] = null, newPartContainsEnding = RegExpPrototypeExec.call(lineEnding, string); - this[kSawReturnAt] = StringPrototypeEndsWith.call(string, "\r") ? DateNow() : 0; - var indexes = [0, newPartContainsEnding.index, lineEnding.lastIndex], nextMatch; - while ((nextMatch = RegExpPrototypeExec.call(lineEnding, string)) !== null) - ArrayPrototypePush.call(indexes, nextMatch.index, lineEnding.lastIndex); - var lastIndex = indexes.length - 1; - this[kLine_buffer] = StringPrototypeSlice.call(string, indexes[lastIndex]); - for (var i = 1;i < lastIndex; i += 2) - this[kOnLine](StringPrototypeSlice.call(string, indexes[i - 1], indexes[i])); - } else if (string) - if (this[kLine_buffer]) - this[kLine_buffer] += string; - else - this[kLine_buffer] = string; - } - [kInsertString](c) { - if (this[kBeforeEdit](this.line, this.cursor), this.cursor < this.line.length) { - var beg = StringPrototypeSlice.call(this.line, 0, this.cursor), end = StringPrototypeSlice.call(this.line, this.cursor, this.line.length); - this.line = beg + c + end, this.cursor += c.length, this[kRefreshLine](); - } else { - var oldPos = this.getCursorPos(); - this.line += c, this.cursor += c.length; - var newPos = this.getCursorPos(); - if (oldPos.rows < newPos.rows) - this[kRefreshLine](); - else - this[kWriteToOutput](c); - } - } - async[kTabComplete](lastKeypressWasTab) { - this.pause(); - var string = StringPrototypeSlice.call(this.line, 0, this.cursor), value; - try { - value = await this.completer(string); - } catch (err) { - this[kWriteToOutput](`Tab completion error: ${inspect(err)}`); - return; - } finally { - this.resume(); - } - this[kTabCompleter](lastKeypressWasTab, value); - } - [kTabCompleter](lastKeypressWasTab, { 0: completions, 1: completeOn }) { - if (!completions || completions.length === 0) - return; - var prefix = commonPrefix(ArrayPrototypeFilter.call(completions, (e) => e !== "")); - if (StringPrototypeStartsWith.call(prefix, completeOn) && prefix.length > completeOn.length) { - this[kInsertString](StringPrototypeSlice.call(prefix, completeOn.length)); - return; - } else if (!StringPrototypeStartsWith.call(completeOn, prefix)) { - this.line = StringPrototypeSlice.call(this.line, 0, this.cursor - completeOn.length) + prefix + StringPrototypeSlice.call(this.line, this.cursor, this.line.length), this.cursor = this.cursor - completeOn.length + prefix.length, this._refreshLine(); - return; - } - if (!lastKeypressWasTab) - return; - this[kBeforeEdit](this.line, this.cursor); - var completionsWidth = ArrayPrototypeMap.call(completions, (e) => getStringWidth(e)), width = MathMaxApply(completionsWidth) + 2, maxColumns = MathFloor(this.columns / width) || 1; - if (maxColumns === Infinity) - maxColumns = 1; - var output = "\r\n", lineIndex = 0, whitespace = 0; - for (var i = 0;i < completions.length; i++) { - var completion = completions[i]; - if (completion === "" || lineIndex === maxColumns) - output += "\r\n", lineIndex = 0, whitespace = 0; - else - output += StringPrototypeRepeat.call(" ", whitespace); - if (completion !== "") - output += completion, whitespace = width - completionsWidth[i], lineIndex++; - else - output += "\r\n"; - } - if (lineIndex !== 0) - output += "\r\n\r\n"; - this[kWriteToOutput](output), this[kRefreshLine](); - } - [kWordLeft]() { - if (this.cursor > 0) { - var leading = StringPrototypeSlice.call(this.line, 0, this.cursor), reversed = ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)), ""), match = RegExpPrototypeExec.call(/^\s*(?:[^\w\s]+|\w+)?/, reversed); - this[kMoveCursor](-match[0].length); - } - } - [kWordRight]() { - if (this.cursor < this.line.length) { - var trailing = StringPrototypeSlice.call(this.line, this.cursor), match = RegExpPrototypeExec.call(/^(?:\s+|[^\w\s]+|\w+)\s*/, trailing); - this[kMoveCursor](match[0].length); - } - } - [kDeleteLeft]() { - if (this.cursor > 0 && this.line.length > 0) { - this[kBeforeEdit](this.line, this.cursor); - var charSize = charLengthLeft(this.line, this.cursor); - this.line = StringPrototypeSlice.call(this.line, 0, this.cursor - charSize) + StringPrototypeSlice.call(this.line, this.cursor, this.line.length), this.cursor -= charSize, this[kRefreshLine](); - } - } - [kDeleteRight]() { - if (this.cursor < this.line.length) { - this[kBeforeEdit](this.line, this.cursor); - var charSize = charLengthAt(this.line, this.cursor); - this.line = StringPrototypeSlice.call(this.line, 0, this.cursor) + StringPrototypeSlice.call(this.line, this.cursor + charSize, this.line.length), this[kRefreshLine](); - } - } - [kDeleteWordLeft]() { - if (this.cursor > 0) { - this[kBeforeEdit](this.line, this.cursor); - var leading = StringPrototypeSlice.call(this.line, 0, this.cursor), reversed = ArrayPrototypeJoin.call(ArrayPrototypeReverse.call(ArrayFrom(leading)), ""), match = RegExpPrototypeExec.call(/^\s*(?:[^\w\s]+|\w+)?/, reversed); - leading = StringPrototypeSlice.call(leading, 0, leading.length - match[0].length), this.line = leading + StringPrototypeSlice.call(this.line, this.cursor, this.line.length), this.cursor = leading.length, this[kRefreshLine](); - } - } - [kDeleteWordRight]() { - if (this.cursor < this.line.length) { - this[kBeforeEdit](this.line, this.cursor); - var trailing = StringPrototypeSlice.call(this.line, this.cursor), match = RegExpPrototypeExec.call(/^(?:\s+|\W+|\w+)\s*/, trailing); - this.line = StringPrototypeSlice.call(this.line, 0, this.cursor) + StringPrototypeSlice.call(trailing, match[0].length), this[kRefreshLine](); - } - } - [kDeleteLineLeft]() { - this[kBeforeEdit](this.line, this.cursor); - var del = StringPrototypeSlice.call(this.line, 0, this.cursor); - this.line = StringPrototypeSlice.call(this.line, this.cursor), this.cursor = 0, this[kPushToKillRing](del), this[kRefreshLine](); - } - [kDeleteLineRight]() { - this[kBeforeEdit](this.line, this.cursor); - var del = StringPrototypeSlice.call(this.line, this.cursor); - this.line = StringPrototypeSlice.call(this.line, 0, this.cursor), this[kPushToKillRing](del), this[kRefreshLine](); - } - [kPushToKillRing](del) { - if (!del || del === this[kKillRing][0]) - return; - ArrayPrototypeUnshift.call(this[kKillRing], del), this[kKillRingCursor] = 0; - while (this[kKillRing].length > kMaxLengthOfKillRing) - ArrayPrototypePop.call(this[kKillRing]); - } - [kYank]() { - if (this[kKillRing].length > 0) - this[kYanking] = !0, this[kInsertString](this[kKillRing][this[kKillRingCursor]]); - } - [kYankPop]() { - if (!this[kYanking]) - return; - if (this[kKillRing].length > 1) { - var lastYank = this[kKillRing][this[kKillRingCursor]]; - if (this[kKillRingCursor]++, this[kKillRingCursor] >= this[kKillRing].length) - this[kKillRingCursor] = 0; - var currentYank = this[kKillRing][this[kKillRingCursor]], head = StringPrototypeSlice.call(this.line, 0, this.cursor - lastYank.length), tail = StringPrototypeSlice.call(this.line, this.cursor); - this.line = head + currentYank + tail, this.cursor = head.length + currentYank.length, this[kRefreshLine](); - } - } - clearLine() { - this[kMoveCursor](Infinity), this[kWriteToOutput]("\r\n"), this.line = "", this.cursor = 0, this.prevRows = 0; - } - [kLine]() { - var line = this[kAddHistory](); - this[kUndoStack] = [], this[kRedoStack] = [], this.clearLine(), this[kOnLine](line); - } - [kPushToUndoStack](text, cursor) { - if (ArrayPrototypePush.call(this[kUndoStack], { text, cursor }) > kMaxUndoRedoStackSize) - ArrayPrototypeShift.call(this[kUndoStack]); - } - [kUndo]() { - if (this[kUndoStack].length <= 0) - return; - ArrayPrototypePush.call(this[kRedoStack], { - text: this.line, - cursor: this.cursor - }); - var entry = ArrayPrototypePop.call(this[kUndoStack]); - this.line = entry.text, this.cursor = entry.cursor, this[kRefreshLine](); - } - [kRedo]() { - if (this[kRedoStack].length <= 0) - return; - ArrayPrototypePush.call(this[kUndoStack], { - text: this.line, - cursor: this.cursor - }); - var entry = ArrayPrototypePop.call(this[kRedoStack]); - this.line = entry.text, this.cursor = entry.cursor, this[kRefreshLine](); - } - [kHistoryNext]() { - if (this.historyIndex >= 0) { - this[kBeforeEdit](this.line, this.cursor); - var search = this[kSubstringSearch] || "", index = this.historyIndex - 1; - while (index >= 0 && (!StringPrototypeStartsWith.call(this.history[index], search) || this.line === this.history[index])) - index--; - if (index === -1) - this.line = search; - else - this.line = this.history[index]; - this.historyIndex = index, this.cursor = this.line.length, this[kRefreshLine](); - } - } - [kHistoryPrev]() { - if (this.historyIndex < this.history.length && this.history.length) { - this[kBeforeEdit](this.line, this.cursor); - var search = this[kSubstringSearch] || "", index = this.historyIndex + 1; - while (index < this.history.length && (!StringPrototypeStartsWith.call(this.history[index], search) || this.line === this.history[index])) - index++; - if (index === this.history.length) - this.line = search; - else - this.line = this.history[index]; - this.historyIndex = index, this.cursor = this.line.length, this[kRefreshLine](); - } - } - [kGetDisplayPos](str) { - var offset = 0, col = this.columns, rows = 0; - str = stripVTControlCharacters(str); - for (var char of new SafeStringIterator(str)) { - if (char === "\n") { - rows += MathCeil(offset / col) || 1, offset = 0; - continue; - } - if (char === "\t") { - offset += this.tabSize - offset % this.tabSize; - continue; - } - var width = getStringWidth(char, !1); - if (width === 0 || width === 1) - offset += width; - else { - if ((offset + 1) % col === 0) - offset++; - offset += 2; - } - } - var cols = offset % col; - return rows += (offset - cols) / col, { cols, rows }; - } - getCursorPos() { - var strBeforeCursor = this[kPrompt] + StringPrototypeSlice.call(this.line, 0, this.cursor); - return this[kGetDisplayPos](strBeforeCursor); - } - [kMoveCursor](dx) { - if (dx === 0) - return; - var oldPos = this.getCursorPos(); - if (this.cursor += dx, this.cursor < 0) - this.cursor = 0; - else if (this.cursor > this.line.length) - this.cursor = this.line.length; - var newPos = this.getCursorPos(); - if (oldPos.rows === newPos.rows) { - var diffWidth = newPos.cols - oldPos.cols; - moveCursor(this.output, diffWidth, 0); - } else - this[kRefreshLine](); - } - [kTtyWrite](s, key) { - var previousKey = this[kPreviousKey]; - key = key || kEmptyObject, this[kPreviousKey] = key; - var { name: keyName, meta: keyMeta, ctrl: keyCtrl2, shift: keyShift, sequence: keySeq } = key; - if (!keyMeta || keyName !== "y") - this[kYanking] = !1; - if ((keyName === "up" || keyName === "down") && !keyCtrl2 && !keyMeta && !keyShift) { - if (this[kSubstringSearch] === null) - this[kSubstringSearch] = StringPrototypeSlice.call(this.line, 0, this.cursor); - } else if (this[kSubstringSearch] !== null) { - if (this[kSubstringSearch] = null, this.history.length === this.historyIndex) - this.historyIndex = -1; - } - if (typeof keySeq === "string") - switch (StringPrototypeCodePointAt.call(keySeq, 0)) { - case 31: - this[kUndo](); - return; - case 30: - this[kRedo](); - return; - default: - break; - } - if (keyName === "escape") - return; - if (keyCtrl2 && keyShift) - switch (keyName) { - case "backspace": - this[kDeleteLineLeft](); - break; - case "delete": - this[kDeleteLineRight](); - break; - } - else if (keyCtrl2) - switch (keyName) { - case "c": - if (this.listenerCount("SIGINT") > 0) - this.emit("SIGINT"); - else - this.close(); - break; - case "h": - this[kDeleteLeft](); - break; - case "d": - if (this.cursor === 0 && this.line.length === 0) - this.close(); - else if (this.cursor < this.line.length) - this[kDeleteRight](); - break; - case "u": - this[kDeleteLineLeft](); - break; - case "k": - this[kDeleteLineRight](); - break; - case "a": - this[kMoveCursor]((-Infinity)); - break; - case "e": - this[kMoveCursor](Infinity); - break; - case "b": - this[kMoveCursor](-charLengthLeft(this.line, this.cursor)); - break; - case "f": - this[kMoveCursor](+charLengthAt(this.line, this.cursor)); - break; - case "l": - cursorTo(this.output, 0, 0), clearScreenDown(this.output), this[kRefreshLine](); - break; - case "n": - this[kHistoryNext](); - break; - case "p": - this[kHistoryPrev](); - break; - case "y": - this[kYank](); - break; - case "z": - if (this.listenerCount("SIGTSTP") > 0) - this.emit("SIGTSTP"); - else - process.once("SIGCONT", () => { - if (!this.paused) - this.pause(), this.emit("SIGCONT"); - this[kSetRawMode](!0), this[kRefreshLine](); - }), this[kSetRawMode](!1), process.kill(process.pid, "SIGTSTP"); - break; - case "w": - case "backspace": - this[kDeleteWordLeft](); - break; - case "delete": - this[kDeleteWordRight](); - break; - case "left": - this[kWordLeft](); - break; - case "right": - this[kWordRight](); - break; - } - else if (keyMeta) - switch (keyName) { - case "b": - this[kWordLeft](); - break; - case "f": - this[kWordRight](); - break; - case "d": - case "delete": - this[kDeleteWordRight](); - break; - case "backspace": - this[kDeleteWordLeft](); - break; - case "y": - this[kYankPop](); - break; - } - else { - if (this[kSawReturnAt] && keyName !== "enter") - this[kSawReturnAt] = 0; - switch (keyName) { - case "return": - this[kSawReturnAt] = DateNow(), this[kLine](); - break; - case "enter": - if (this[kSawReturnAt] === 0 || DateNow() - this[kSawReturnAt] > this.crlfDelay) - this[kLine](); - this[kSawReturnAt] = 0; - break; - case "backspace": - this[kDeleteLeft](); - break; - case "delete": - this[kDeleteRight](); - break; - case "left": - this[kMoveCursor](-charLengthLeft(this.line, this.cursor)); - break; - case "right": - this[kMoveCursor](+charLengthAt(this.line, this.cursor)); - break; - case "home": - this[kMoveCursor]((-Infinity)); - break; - case "end": - this[kMoveCursor](Infinity); - break; - case "up": - this[kHistoryPrev](); - break; - case "down": - this[kHistoryNext](); - break; - case "tab": - if (typeof this.completer === "function" && this.isCompletionEnabled) { - var lastKeypressWasTab = previousKey && previousKey.name === "tab"; - this[kTabComplete](lastKeypressWasTab); - break; - } - default: - if (typeof s === "string" && s) { - var nextMatch = RegExpPrototypeExec.call(lineEnding, s); - if (nextMatch !== null) { - this[kInsertString](StringPrototypeSlice.call(s, 0, nextMatch.index)); - var { lastIndex } = lineEnding; - while ((nextMatch = RegExpPrototypeExec.call(lineEnding, s)) !== null) - this[kLine](), this[kInsertString](StringPrototypeSlice.call(s, lastIndex, nextMatch.index)), { lastIndex } = lineEnding; - if (lastIndex === s.length) - this[kLine](); - } else - this[kInsertString](s); - } - } - } - } - [SymbolAsyncIterator]() { - if (this[kLineObjectStream] === void 0) - this[kLineObjectStream] = EventEmitter.on(this, "line", { - close: ["close"], - highWatermark: 1024, - [kFirstEventParam]: !0 - }); - return this[kLineObjectStream]; - } -}; -ObjectSetPrototypeOf(Interface.prototype, _Interface.prototype); -ObjectSetPrototypeOf(Interface, _Interface); -Interface.prototype.question = function question(query, options, cb) { - if (cb = typeof options === "function" ? options : cb, options === null || typeof options !== "object") - options = kEmptyObject; - var signal = options?.signal; - if (signal) { - if (validateAbortSignal(signal, "options.signal"), signal.aborted) - return; - var onAbort = () => { - this[kQuestionCancel](); - }; - signal.addEventListener("abort", onAbort, { once: !0 }); - var cleanup = () => { - signal.removeEventListener("abort", onAbort); - }, originalCb = cb; - cb = typeof cb === "function" ? (answer) => { - return cleanup(), originalCb(answer); - } : cleanup; - } - if (typeof cb === "function") - this[kQuestion](query, cb); -}; -Interface.prototype.question[promisify.custom] = function question2(query, options) { - if (options === null || typeof options !== "object") - options = kEmptyObject; - var signal = options?.signal; - if (signal && signal.aborted) - return PromiseReject(new AbortError(void 0, { cause: signal.reason })); - return new Promise((resolve, reject) => { - var cb = resolve; - if (signal) { - var onAbort = () => { - reject(new AbortError(void 0, { cause: signal.reason })); - }; - signal.addEventListener("abort", onAbort, { once: !0 }), cb = (answer) => { - signal.removeEventListener("abort", onAbort), resolve(answer); - }; - } - this.question(query, options, cb); - }); -}; -ObjectDefineProperties(Interface.prototype, { - [kSetRawMode]: { - __proto__: null, - get() { - return this._setRawMode; - } - }, - [kOnLine]: { - __proto__: null, - get() { - return this._onLine; - } - }, - [kWriteToOutput]: { - __proto__: null, - get() { - return this._writeToOutput; - } - }, - [kAddHistory]: { - __proto__: null, - get() { - return this._addHistory; - } - }, - [kRefreshLine]: { - __proto__: null, - get() { - return this._refreshLine; - } - }, - [kNormalWrite]: { - __proto__: null, - get() { - return this._normalWrite; - } - }, - [kInsertString]: { - __proto__: null, - get() { - return this._insertString; - } - }, - [kTabComplete]: { - __proto__: null, - get() { - return this._tabComplete; - } - }, - [kWordLeft]: { - __proto__: null, - get() { - return this._wordLeft; - } - }, - [kWordRight]: { - __proto__: null, - get() { - return this._wordRight; - } - }, - [kDeleteLeft]: { - __proto__: null, - get() { - return this._deleteLeft; - } - }, - [kDeleteRight]: { - __proto__: null, - get() { - return this._deleteRight; - } - }, - [kDeleteWordLeft]: { - __proto__: null, - get() { - return this._deleteWordLeft; - } - }, - [kDeleteWordRight]: { - __proto__: null, - get() { - return this._deleteWordRight; - } - }, - [kDeleteLineLeft]: { - __proto__: null, - get() { - return this._deleteLineLeft; - } - }, - [kDeleteLineRight]: { - __proto__: null, - get() { - return this._deleteLineRight; - } - }, - [kLine]: { - __proto__: null, - get() { - return this._line; - } - }, - [kHistoryNext]: { - __proto__: null, - get() { - return this._historyNext; - } - }, - [kHistoryPrev]: { - __proto__: null, - get() { - return this._historyPrev; - } - }, - [kGetDisplayPos]: { - __proto__: null, - get() { - return this._getDisplayPos; - } - }, - [kMoveCursor]: { - __proto__: null, - get() { - return this._moveCursor; - } - }, - [kTtyWrite]: { - __proto__: null, - get() { - return this._ttyWrite; - } - }, - _decoder: { - __proto__: null, - get() { - return this[kDecoder]; - }, - set(value) { - this[kDecoder] = value; - } - }, - _line_buffer: { - __proto__: null, - get() { - return this[kLine_buffer]; - }, - set(value) { - this[kLine_buffer] = value; - } - }, - _oldPrompt: { - __proto__: null, - get() { - return this[kOldPrompt]; - }, - set(value) { - this[kOldPrompt] = value; - } - }, - _previousKey: { - __proto__: null, - get() { - return this[kPreviousKey]; - }, - set(value) { - this[kPreviousKey] = value; - } - }, - _prompt: { - __proto__: null, - get() { - return this[kPrompt]; - }, - set(value) { - this[kPrompt] = value; - } - }, - _questionCallback: { - __proto__: null, - get() { - return this[kQuestionCallback]; - }, - set(value) { - this[kQuestionCallback] = value; - } - }, - _sawKeyPress: { - __proto__: null, - get() { - return this[kSawKeyPress]; - }, - set(value) { - this[kSawKeyPress] = value; - } - }, - _sawReturnAt: { - __proto__: null, - get() { - return this[kSawReturnAt]; - }, - set(value) { - this[kSawReturnAt] = value; - } - } -}); -Interface.prototype._setRawMode = _Interface.prototype[kSetRawMode]; -Interface.prototype._onLine = _Interface.prototype[kOnLine]; -Interface.prototype._writeToOutput = _Interface.prototype[kWriteToOutput]; -Interface.prototype._addHistory = _Interface.prototype[kAddHistory]; -Interface.prototype._refreshLine = _Interface.prototype[kRefreshLine]; -Interface.prototype._normalWrite = _Interface.prototype[kNormalWrite]; -Interface.prototype._insertString = _Interface.prototype[kInsertString]; -Interface.prototype._tabComplete = function(lastKeypressWasTab) { - this.pause(); - var string = StringPrototypeSlice.call(this.line, 0, this.cursor); - this.completer(string, (err, value) => { - if (this.resume(), err) { - this._writeToOutput(`Tab completion error: ${inspect(err)}`); - return; - } - this[kTabCompleter](lastKeypressWasTab, value); - }); -}; -Interface.prototype._wordLeft = _Interface.prototype[kWordLeft]; -Interface.prototype._wordRight = _Interface.prototype[kWordRight]; -Interface.prototype._deleteLeft = _Interface.prototype[kDeleteLeft]; -Interface.prototype._deleteRight = _Interface.prototype[kDeleteRight]; -Interface.prototype._deleteWordLeft = _Interface.prototype[kDeleteWordLeft]; -Interface.prototype._deleteWordRight = _Interface.prototype[kDeleteWordRight]; -Interface.prototype._deleteLineLeft = _Interface.prototype[kDeleteLineLeft]; -Interface.prototype._deleteLineRight = _Interface.prototype[kDeleteLineRight]; -Interface.prototype._line = _Interface.prototype[kLine]; -Interface.prototype._historyNext = _Interface.prototype[kHistoryNext]; -Interface.prototype._historyPrev = _Interface.prototype[kHistoryPrev]; -Interface.prototype._getDisplayPos = _Interface.prototype[kGetDisplayPos]; -Interface.prototype._getCursorPos = _Interface.prototype.getCursorPos; -Interface.prototype._moveCursor = _Interface.prototype[kMoveCursor]; -Interface.prototype._ttyWrite = _Interface.prototype[kTtyWrite]; - -class Readline { - #autoCommit = !1; - #stream; - #todo = []; - constructor(stream, options = void 0) { - if (isWritable ??= import.meta.require("node:stream").isWritable, !isWritable(stream)) - throw new ERR_INVALID_ARG_TYPE("stream", "Writable", stream); - if (this.#stream = stream, options?.autoCommit != null) - validateBoolean(options.autoCommit, "options.autoCommit"), this.#autoCommit = options.autoCommit; - } - cursorTo(x, y = void 0) { - if (validateInteger(x, "x"), y != null) - validateInteger(y, "y"); - var data = y == null ? CSI`${x + 1}G` : CSI`${y + 1};${x + 1}H`; - if (this.#autoCommit) - process.nextTick(() => this.#stream.write(data)); - else - ArrayPrototypePush.call(this.#todo, data); - return this; - } - moveCursor(dx, dy) { - if (dx || dy) { - validateInteger(dx, "dx"), validateInteger(dy, "dy"); - var data = ""; - if (dx < 0) - data += CSI`${-dx}D`; - else if (dx > 0) - data += CSI`${dx}C`; - if (dy < 0) - data += CSI`${-dy}A`; - else if (dy > 0) - data += CSI`${dy}B`; - if (this.#autoCommit) - process.nextTick(() => this.#stream.write(data)); - else - ArrayPrototypePush.call(this.#todo, data); - } - return this; - } - clearLine(dir) { - validateInteger(dir, "dir", -1, 1); - var data = dir < 0 ? kClearToLineBeginning : dir > 0 ? kClearToLineEnd : kClearLine; - if (this.#autoCommit) - process.nextTick(() => this.#stream.write(data)); - else - ArrayPrototypePush.call(this.#todo, data); - return this; - } - clearScreenDown() { - if (this.#autoCommit) - process.nextTick(() => this.#stream.write(kClearScreenDown)); - else - ArrayPrototypePush.call(this.#todo, kClearScreenDown); - return this; - } - commit() { - return new Promise((resolve) => { - this.#stream.write(ArrayPrototypeJoin.call(this.#todo, ""), resolve), this.#todo = []; - }); - } - rollback() { - return this.#todo = [], this; - } -} -var PromisesInterface = class Interface3 extends _Interface { - constructor(input, output, completer, terminal) { - super(input, output, completer, terminal); - } - question(query, options = kEmptyObject) { - var signal = options?.signal; - if (signal) { - if (validateAbortSignal(signal, "options.signal"), signal.aborted) - return PromiseReject(new AbortError(void 0, { cause: signal.reason })); - } - return new Promise((resolve, reject) => { - var cb = resolve; - if (options?.signal) { - var onAbort = () => { - this[kQuestionCancel](), reject(new AbortError(void 0, { cause: signal.reason })); - }; - signal.addEventListener("abort", onAbort, { once: !0 }), cb = (answer) => { - signal.removeEventListener("abort", onAbort), resolve(answer); - }; - } - this[kQuestion](query, cb); - }); - } -}, Interface = Interface, clearLine = clearLine, clearScreenDown = clearScreenDown, createInterface = createInterface, cursorTo = cursorTo, emitKeypressEvents = emitKeypressEvents, moveCursor = moveCursor, promises = { - Readline, - Interface: PromisesInterface, - createInterface(input, output, completer, terminal) { - return new PromisesInterface(input, output, completer, terminal); - } -}, readline_default = { - Interface, - clearLine, - clearScreenDown, - createInterface, - cursorTo, - emitKeypressEvents, - moveCursor, - promises, - [SymbolFor("__BUN_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED__")]: { - CSI, - utils: { - getStringWidth, - stripVTControlCharacters - } - }, - [SymbolFor("CommonJS")]: 0 -}; -export { - promises, - moveCursor, - emitKeypressEvents, - readline_default as default, - cursorTo, - createInterface, - clearScreenDown, - clearLine, - Interface -}; diff --git a/src/js/out/modules/node/readline.promises.js b/src/js/out/modules/node/readline.promises.js deleted file mode 100644 index 61a6d256f3b158..00000000000000 --- a/src/js/out/modules/node/readline.promises.js +++ /dev/null @@ -1,13 +0,0 @@ -import {promises} from "node:readline"; -var { Readline, Interface, createInterface } = promises, readline_promises_default = { - Readline, - Interface, - createInterface, - [Symbol.for("CommonJS")]: 0 -}; -export { - readline_promises_default as default, - createInterface, - Readline, - Interface -}; diff --git a/src/js/out/modules/node/repl.js b/src/js/out/modules/node/repl.js deleted file mode 100644 index c1eb35e9739b8e..00000000000000 --- a/src/js/out/modules/node/repl.js +++ /dev/null @@ -1,90 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/repl.ts -var REPLServer = function() { - throwNotImplemented("node:repl REPLServer"); -}, Recoverable = function() { - throwNotImplemented("node:repl Recoverable"); -}, start = function() { - throwNotImplemented("node:repl"); -}, REPL_MODE_SLOPPY = 0, REPL_MODE_STRICT = 1, repl = { - [Symbol.for("CommonJS")]: 0, - lines: [], - context: globalThis, - historyIndex: -1, - cursor: 0, - historySize: 1000, - removeHistoryDuplicates: !1, - crlfDelay: 100, - completer: () => { - throwNotImplemented("node:repl"); - }, - history: [], - _initialPrompt: "> ", - terminal: !0, - input: new Proxy({}, { - get() { - throwNotImplemented("node:repl"); - }, - has: () => !1, - ownKeys: () => [], - getOwnPropertyDescriptor: () => { - return; - }, - set() { - throwNotImplemented("node:repl"); - } - }), - line: "", - eval: () => { - throwNotImplemented("node:repl"); - }, - isCompletionEnabled: !0, - escapeCodeTimeout: 500, - tabSize: 8, - breakEvalOnSigint: !0, - useGlobal: !0, - underscoreAssigned: !1, - last: void 0, - _domain: void 0, - allowBlockingCompletions: !1, - useColors: !0, - output: new Proxy({}, { - get() { - throwNotImplemented("node:repl"); - }, - has: () => !1, - ownKeys: () => [], - getOwnPropertyDescriptor: () => { - return; - }, - set() { - throwNotImplemented("node:repl"); - } - }) -}; -export { - start, - repl, - repl as default, - Recoverable, - REPL_MODE_STRICT, - REPL_MODE_SLOPPY, - REPLServer -}; diff --git a/src/js/out/modules/node/stream.consumers.js b/src/js/out/modules/node/stream.consumers.js deleted file mode 100644 index 96ecae4e71039a..00000000000000 --- a/src/js/out/modules/node/stream.consumers.js +++ /dev/null @@ -1 +0,0 @@ -var k=(o)=>{return import.meta.require(o)};var{Bun:p}=globalThis[Symbol.for("Bun.lazy")]("primordials"),O=p.readableStreamToArrayBuffer,c=p.readableStreamToText,g=(o)=>p.readableStreamToText(o).then(JSON.parse),h=async(o)=>{return new Buffer(await O(o))},i=p.readableStreamToBlob,v={[Symbol.for("CommonJS")]:0,arrayBuffer:O,text:c,json:g,buffer:h,blob:i};export{c as text,g as json,v as default,h as buffer,i as blob,O as arrayBuffer}; diff --git a/src/js/out/modules/node/stream.js b/src/js/out/modules/node/stream.js deleted file mode 100644 index b001443b4664eb..00000000000000 --- a/src/js/out/modules/node/stream.js +++ /dev/null @@ -1,2 +0,0 @@ -var UQ=(a)=>{return import.meta.require(a)};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,T]=globalThis[Symbol.for("Bun.lazy")](a),g=[!1],k=function(E,P,Z,U){if(P>0){const I=Z.subarray(0,P),_=Z.subarray(P);if(I.byteLength>0)E.push(I);if(U)E.push(null);return _.byteLength>0?_:void 0}if(U)E.push(null);return Z},c=function(E,P,Z,U){if(P.byteLength>0)E.push(P);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(P,Z={}){super(Z);if(typeof Z.highWaterMark==="number")this.#J=Z.highWaterMark;else this.#J=262144;this.#q=P,this.#X=!1,this.#H=void 0,this.#K=!1,this.#B={},l.register(this,this.#q,this.#B)}_read(P){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(P),Z)}#$(P){this.#X=!0;const Z=G(P,this.#J);if(typeof Z==="number"&&Z>1)this.#Z=!0,this.#J=Math.min(this.#J,Z);if(T){const U=T(P);if((U?.byteLength??0)>0)this.push(U)}}#z(P=this.#J){var Z=this.#H;if(Z?.byteLength??0D?P:D;this.#H=Z=new Buffer(U)}return Z}#Y(P,Z,U){if(typeof P==="number"){if(P>=this.#J&&!this.#Z&&!U)this.#J*=2,this.#Z=!0;return k(this,P,Z,U)}else if(typeof P==="boolean")return process.nextTick(()=>{this.push(null)}),Z?.byteLength??0>0?Z:void 0;else if(ArrayBuffer.isView(P)){if(P.byteLength>=this.#J&&!this.#Z&&!U)this.#J*=2,this.#Z=!0;return c(this,P,Z,U)}else throw new Error("Invalid result from pull")}#V(P,Z){g[0]=!1;var U=B(Z,P,g);if(xq(U))return this.#K=!0,U.then((I)=>{this.#K=!1,this.#H=this.#Y(I,P,g[0])},(I)=>{errorOrDestroy(this,I)});else this.#H=this.#Y(U,P,g[0])}_destroy(P,Z){var U=this.#q;if(U===0){Z(P);return}if(l.unregister(this.#B),this.#q=0,R)R(U,!1);y(U,P),Z(P)}ref(){var P=this.#q;if(P===0)return;if(this.#Q++===0)R(P,!0)}unref(){var P=this.#q;if(P===0)return;if(this.#Q--===1)R(P,!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"),FQ=zq.create,LQ=zq.defineProperty,jQ=zq.getOwnPropertyDescriptor,rq=zq.getOwnPropertyNames,NQ=zq.getPrototypeOf,AQ=zq.prototype.hasOwnProperty,EQ=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 IQ=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=T,M=g}),resolve:A,reject:M}},promisify(A){return new Promise((M,R)=>{A((T,...g)=>{if(T)return R(T);return M(...g)})})},debuglog(){return function(){}},format(A,...M){return A.replace(/%([sdifj])/g,function(...[R,T]){const g=M.shift();if(T==="f")return g.toFixed(6);else if(T==="j")return JSON.stringify(g);else if(T==="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"],T=/^([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="",I=Z.length;const _=Z[0]==="-"?1:0;for(;I>=_+4;I-=3)U=`_${Z.slice(I-3,I)}${U}`;return`${Z.slice(0,I)}${U}`}function l(Z,U,I){if(typeof U==="function")return c(U.length<=I.length,`Code: ${Z}; The provided arguments length (${I.length}) does not match the required ones (${U.length}).`),U(...I);const _=(U.match(/%[dfijoOs]/g)||[]).length;if(c(_===I.length,`Code: ${Z}; The provided arguments length (${I.length}) does not match the required ones (${_}).`),I.length===0)return U;return B(U,...I)}function D(Z,U,I){if(!I)I=Error;class _ extends I{constructor(...t){super(l(Z,U,t))}toString(){return`${this.name} [${Z}]: ${this.message}`}}zq.defineProperties(_.prototype,{name:{value:I.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 I=new A([U,Z],U.message);return I.code=U.code,I}return Z||U}var P=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,I)=>{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(T.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(I==null)_+=`. Received ${I}`;else if(typeof I==="function"&&I.name)_+=`. Received function ${I.name}`;else if(typeof I==="object"){var n;if((n=I.constructor)!==null&&n!==void 0&&n.name)_+=`. Received an instance of ${I.constructor.name}`;else{const Y=G(I,{depth:-1});_+=`. Received ${Y}`}}else{let Y=G(I,{colors:!1});if(Y.length>25)Y=`${Y.slice(0,25)}...`;_+=`. Received type ${typeof I} (${Y})`}return _},TypeError),D("ERR_INVALID_ARG_VALUE",(Z,U,I="is invalid")=>{let _=G(U);if(_.length>128)_=_.slice(0,128)+"...";return`The ${Z.includes(".")?"property":"argument"} '${Z}' ${I}. Received ${_}`},TypeError),D("ERR_INVALID_RETURN_VALUE",(Z,U,I)=>{var _;const t=I!==null&&I!==void 0&&(_=I.constructor)!==null&&_!==void 0&&_.name?`instance of ${I.constructor.name}`:`type ${typeof I}`;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 I=Z.length;switch(Z=(Array.isArray(Z)?Z:[Z]).map((_)=>`"${_}"`).join(" or "),I){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,I)=>{c(U,'Missing "range" argument');let _;if(Number.isInteger(I)&&Math.abs(I)>4294967296)_=O(String(I));else if(typeof I==="bigint"){if(_=String(I),I>2n**32n||I<-(2n**32n))_=O(_);_+="n"}else _=G(I);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:P,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:T,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:P,ERR_OUT_OF_RANGE:Z,ERR_UNKNOWN_SIGNAL:U}}=Wq(),{normalizeEncoding:I}=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 P(h,V,K);V=g(V,8)}return u(V,h,0,4294967295),V}var m=D((V,h,Q=T,H=R)=>{if(typeof V!=="number")throw new E(h,"number",V);if(!M(V))throw new Z(h,"an integer",V);if(VH)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(VH)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 P(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{if(!t(V))throw new E(h,["Buffer","TypedArray","DataView"],V)});function e(V,h){const Q=I(h),H=V.length;if(Q==="hex"&&H%2!==0)throw new P("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"),T=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 P(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 I(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&&I(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[T])!==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:T,isErrored:u,kIsErrored:M,isReadable:U,kIsReadable:R,isClosed:$,isDestroyed:D,isDuplexNodeStream:c,isFinished:_,isIterable:l,isReadableNodeStream:g,isReadableEnded:P,isReadableFinished:Z,isReadableErrored:i,isNodeStream:O,isWritable:I,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:T,validateObject:g}=Cq(),{Promise:k}=Vq(),{isClosed:c,isReadable:O,isReadableNodeStream:l,isReadableFinished:D,isReadableErrored:p,isWritable:E,isWritableNodeStream:P,isWritableFinished:Z,isWritableErrored:U,isNodeStream:I,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");T(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:P(Y);if(!I(Y))throw new y("stream","Stream",Y);const{_writableState:w,_readableState:S}=Y,N=()=>{if(!Y.writable)o()};let W=_(Y)&&l(Y)===J&&P(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:T}=Cq(),g=Vq().Symbol("kWeak"),{finished:k}=Fq(),{ArrayPrototypePush:c,MathFloor:O,Number:l,NumberIsNaN:D,Promise:p,PromiseReject:E,PromisePrototypeCatch:P,Symbol:Z}=Vq(),U=Z("kEmpty"),I=Z("kEof");function _(N,W){if(typeof N!=="function")throw new B("fn",["Function","AsyncFunction"],N);if(W!=null)T(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(I)}catch(q){const X=E(q);P(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===I)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)T(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)T(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)T(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)T(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)T(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:T,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){P(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 P(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(P,K,F);else P(K,F)}}function I(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&&!T(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:I,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 T=this;function g(E){if(M.writable&&M.write(E)===!1&&T.pause)T.pause()}T.on("data",g);function k(){if(T.readable&&T.resume)T.resume()}if(M.on("drain",k),!M._isStdio&&(!R||R.end!==!1))T.on("end",O),T.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(T,"error",D),A(M,"error",D);function p(){T.removeListener("data",g),M.removeListener("drain",k),T.removeListener("end",O),T.removeListener("close",l),T.removeListener("error",D),M.removeListener("error",D),T.removeListener("end",p),T.removeListener("close",p),M.removeListener("close",p)}return T.on("end",p),T.on("close",p),M.on("close",p),M.emit("pipe",T),M};function A(M,R,T){if(typeof M.prependListener==="function")return M.prependListener(R,T);if(!M._events||!M._events[R])M.on(R,T);else if(B(M._events[R]))M._events[R].unshift(T);else M._events[R]=[T,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=(T,g)=>{if(typeof T!=="object"||!("aborted"in T))throw new A(g,"AbortSignal",T)};function R(T){return!!(T&&typeof T.pipe==="function")}j.exports.addAbortSignal=function T(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(T,g){if(typeof T!=="object"||!("aborted"in T))return g;const k=()=>{g.destroy(new B(void 0,{cause:T.reason}))};if(T.aborted)k();else T.addEventListener("abort",k),y(g,()=>T.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(T,g,k){return T.highWaterMark!=null?T.highWaterMark:g?T[k]:null}function M(T){return T?16:16384}function R(T,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(T.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(T,g,k){let c;if(typeof g==="string"||g instanceof Buffer)return new T({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 T({objectMode:!0,highWaterMark:1,...k});let D=!1;l._read=function(){if(!D)D=!0,E()},l._destroy=function(P,Z){B(p(P),()=>Xq(Z,P),(U)=>Xq(Z,U||P))};async function p(P){const Z=P!==void 0&&P!==null,U=typeof c.throw==="function";if(Z&&U){const{value:I,done:_}=await c.throw(P);if(await I,_)return}if(typeof c.return==="function"){const{value:I}=await c.return();await I}}async function E(){for(;;){try{const{value:P,done:Z}=O?await c.next():c.next();if(Z)l.push(null);else{const U=P&&typeof P.then==="function"?await P:P;if(U===null)throw D=!1,new M;else if(l.push(U))continue;else D=!1}}catch(P){l.destroy(P)}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:T,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)})}T(E.prototype,D.prototype),T(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 P 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(;X0)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{this.#Q=!0,X(q)});return}try{X(q)}catch(x){globalThis.reportError(x)}}}uq=P;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 P({highWaterMark:C,encoding:x,objectMode:v,signal:Jq},q)}j.exports=E,pq=Z;var{addAbortSignal:U}=Sq(),I=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.length0){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-q0)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;Jq0,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{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:T,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:P,ERR_MULTIPLE_CALLBACK:Z,ERR_STREAM_CANNOT_PIPE:U,ERR_STREAM_DESTROYED:I,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 I("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=T(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.lengthL.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;f1&&Q._writev){H.pendingcb-=r-1;const X=H.allNoop?K:(x)=>{for(let v=q;v256)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 P("_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 I("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{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{if(S!=null)throw new O("nully","body",S)},(S)=>{l(z,S)});return z=new I({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 P(I,$,{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 I({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 I({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 T in Uq.prototype)if(!R.prototype[T])R.prototype[T]=Uq.prototype[T];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 T(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!==T)T.call(this)}M.prototype._final=T,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,P)=>{if(E){O(E);return}if(P!=null)this.push(P);if(D.ended||p===l.length||l.length{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(P(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;h0,d=H||(w===null||w===void 0?void 0:w.end)!==!1,f=h===J.length-1;if(I(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}),!P(Qq))throw new c("Iterable, AsyncIterable or Stream","source",Qq)}else if(P(Q)||U(Q))Qq=Q;else Qq=T.from(Q);else if(typeof Q==="function")if(Qq=n(Qq),Qq=Q(Qq,{signal:N}),H){if(!P(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(P(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(I(Q)){if(U(Qq)){$q+=2;const r=u(Qq,Q,qq,{end:d});if(Z(Q)&&f)b.push(r)}else if(P(Qq))$q++,K(Qq,Q,qq,{end:d});else throw new k("val",["Readable","Iterable","AsyncIterable"],Qq);Qq=Q}else Qq=T.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:T,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;$0&&!R(O[$]))throw new g(`streams[${$}]`,l[$],"must be writable")}let D,p,E,P,Z;function U($){const n=P;if(P=null,n)n($);else if($)Z.destroy($);else if(!i&&!t)Z.destroy()}const I=O[0],_=B(O,U),t=!!R(I),i=!!M(_);if(Z=new G({writableObjectMode:!!(I!==null&&I!==void 0&&I.writableObjectMode),readableObjectMode:!!(_!==null&&_!==void 0&&_.writableObjectMode),writable:t,readable:i}),t)Z._write=function($,n,Y){if(I.write($,n))Y();else D=Y},Z._final=function($){I.end(),p=$},I.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(!$&&P!==null)$=new T;if(E=null,D=null,p=null,P===null)n($);else P=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 T(...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:T}}}),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:T}}=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 P of G(M)){let Z=function(...I){if(new.target)throw T();return p.Readable.from(y(U,this,I))};const U=M[P];B(Z,"name",{value:U.name}),B(Z,"length",{value:U.length}),B(p.Readable.prototype,P,{value:Z,enumerable:!1,configurable:!0,writable:!0})}for(let P of G(R)){let Z=function(...I){if(new.target)throw T();return y(U,this,I)};const U=R[P];B(Z,"name",{value:U.name}),B(Z,"length",{value:U.length}),B(p.Readable.prototype,P,{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 P(Z){return Z instanceof Uint8Array},p._uint8ArrayToBuffer=function P(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 lQ=Yq,TQ=Yq._uint8ArrayToBuffer,PQ=Yq._isUint8Array,xQ=Yq.isDisturbed,OQ=Yq.isErrored,CQ=Yq.isWritable,_Q=Yq.isReadable,DQ=Yq.Readable,Uq=Yq.Writable,wQ=Yq.Duplex,vQ=Yq.Transform,RQ=Yq.PassThrough,SQ=Yq.addAbortSignal,gQ=Yq.finished,kQ=Yq.destroy,fQ=Yq.pipeline,yQ=Yq.compose,VQ=Yq.Stream,hQ=Yq.eos=Fq,pQ=Yq._getNativeReadableStreamPrototype,iq=Yq.NativeWritable,uQ=VQ.promises;export{uQ as promises,fQ as pipeline,CQ as isWritable,_Q as isReadable,OQ as isErrored,xQ as isDisturbed,gQ as finished,hQ as eos,kQ as destroy,lQ as default,yQ as compose,SQ as addAbortSignal,TQ as _uint8ArrayToBuffer,PQ as _isUint8Array,pQ as _getNativeReadableStreamPrototype,Uq as Writable,vQ as Transform,VQ as Stream,DQ as Readable,RQ as PassThrough,iq as NativeWritable,wQ as Duplex}; diff --git a/src/js/out/modules/node/stream.promises.js b/src/js/out/modules/node/stream.promises.js deleted file mode 100644 index 00ad9e50100280..00000000000000 --- a/src/js/out/modules/node/stream.promises.js +++ /dev/null @@ -1 +0,0 @@ -var g=(J)=>{return import.meta.require(J)};import{promises as S} from"node:stream";var{pipeline:b,finished:c}=S,q={pipeline:b,finished:c,[Symbol.for("CommonJS")]:0};export{b as pipeline,c as finished,q as default}; diff --git a/src/js/out/modules/node/stream.web.js b/src/js/out/modules/node/stream.web.js deleted file mode 100644 index 933a2c6d19244d..00000000000000 --- a/src/js/out/modules/node/stream.web.js +++ /dev/null @@ -1 +0,0 @@ -var X=(j)=>{return import.meta.require(j)};var{ReadableStream:k,ReadableStreamDefaultReader:v,ReadableStreamBYOBReader:w,ReadableStreamBYOBRequest:z,ReadableByteStreamController:A,ReadableStreamDefaultController:F,TransformStream:G,TransformStreamDefaultController:H,WritableStream:I,WritableStreamDefaultWriter:J,WritableStreamDefaultController:K,ByteLengthQueuingStrategy:M,CountQueuingStrategy:N,TextEncoderStream:P,TextDecoderStream:U,CompressionStream:V,DecompressionStream:W}=globalThis,_={ReadableStream:k,ReadableStreamDefaultReader:v,ReadableStreamBYOBReader:w,ReadableStreamBYOBRequest:z,ReadableByteStreamController:A,ReadableStreamDefaultController:F,TransformStream:G,TransformStreamDefaultController:H,WritableStream:I,WritableStreamDefaultWriter:J,WritableStreamDefaultController:K,ByteLengthQueuingStrategy:M,CountQueuingStrategy:N,TextEncoderStream:P,TextDecoderStream:U,CompressionStream:V,DecompressionStream:W,[Symbol.for("CommonJS")]:0};export{_ as default,J as WritableStreamDefaultWriter,K as WritableStreamDefaultController,I as WritableStream,H as TransformStreamDefaultController,G as TransformStream,P as TextEncoderStream,U as TextDecoderStream,v as ReadableStreamDefaultReader,F as ReadableStreamDefaultController,z as ReadableStreamBYOBRequest,w as ReadableStreamBYOBReader,k as ReadableStream,A as ReadableByteStreamController,W as DecompressionStream,N as CountQueuingStrategy,V as CompressionStream,M as ByteLengthQueuingStrategy}; diff --git a/src/js/out/modules/node/timers.js b/src/js/out/modules/node/timers.js deleted file mode 100644 index 15b3680c067118..00000000000000 --- a/src/js/out/modules/node/timers.js +++ /dev/null @@ -1,17 +0,0 @@ -var { setTimeout, clearTimeout, setInterval, setImmediate, clearInterval, clearImmediate } = globalThis, timers_default = { - setInterval, - setImmediate, - setTimeout, - clearInterval, - clearTimeout, - [Symbol.for("CommonJS")]: 0 -}; -export { - setTimeout, - setInterval, - setImmediate, - timers_default as default, - clearTimeout, - clearInterval, - clearImmediate -}; diff --git a/src/js/out/modules/node/timers.promises.js b/src/js/out/modules/node/timers.promises.js deleted file mode 100644 index d76e46f3c8bedd..00000000000000 --- a/src/js/out/modules/node/timers.promises.js +++ /dev/null @@ -1,182 +0,0 @@ -var validateObject = function(object, name) { - if (object === null || typeof object !== "object") - throw new ERR_INVALID_ARG_TYPE(name, "Object", object); -}, validateBoolean = function(value, name) { - if (typeof value !== "boolean") - throw new ERR_INVALID_ARG_TYPE(name, "boolean", value); -}, validateAbortSignal = function(signal, name) { - if (typeof signal !== "undefined" && (signal === null || typeof signal !== "object" || !("aborted" in signal))) - throw new ERR_INVALID_ARG_TYPE(name, "AbortSignal", signal); -}, asyncIterator = function({ next: nextFunction, return: returnFunction }) { - const result = {}; - if (typeof nextFunction === "function") - result.next = nextFunction; - if (typeof returnFunction === "function") - result.return = returnFunction; - return result[symbolAsyncIterator] = function() { - return this; - }, result; -}, setTimeoutPromise = function(after = 1, value, options = {}) { - const arguments_ = [].concat(value ?? []); - try { - validateObject(options, "options"); - } catch (error) { - return Promise.reject(error); - } - const { signal, ref: reference = !0 } = options; - try { - validateAbortSignal(signal, "options.signal"); - } catch (error) { - return Promise.reject(error); - } - try { - validateBoolean(reference, "options.ref"); - } catch (error) { - return Promise.reject(error); - } - if (signal?.aborted) - return Promise.reject(new AbortError); - let onCancel; - const returnValue = new Promise((resolve, reject) => { - const timeout = setTimeout(() => resolve(value), after, ...arguments_); - if (!reference) - timeout?.unref?.(); - if (signal) - onCancel = () => { - clearTimeout(timeout), reject(new AbortError); - }, signal.addEventListener("abort", onCancel); - }); - if (typeof onCancel !== "undefined") - returnValue.finally(() => signal.removeEventListener("abort", onCancel)); - return returnValue; -}, setImmediatePromise = function(value, options = {}) { - try { - validateObject(options, "options"); - } catch (error) { - return Promise.reject(error); - } - const { signal, ref: reference = !0 } = options; - try { - validateAbortSignal(signal, "options.signal"); - } catch (error) { - return Promise.reject(error); - } - try { - validateBoolean(reference, "options.ref"); - } catch (error) { - return Promise.reject(error); - } - if (signal?.aborted) - return Promise.reject(new AbortError); - let onCancel; - const returnValue = new Promise((resolve, reject) => { - const immediate = setImmediate(() => resolve(value)); - if (!reference) - immediate?.unref?.(); - if (signal) - onCancel = () => { - clearImmediate(immediate), reject(new AbortError); - }, signal.addEventListener("abort", onCancel); - }); - if (typeof onCancel !== "undefined") - returnValue.finally(() => signal.removeEventListener("abort", onCancel)); - return returnValue; -}, setIntervalPromise = function(after = 1, value, options = {}) { - try { - validateObject(options, "options"); - } catch (error) { - return asyncIterator({ - next: function() { - return Promise.reject(error); - } - }); - } - const { signal, ref: reference = !0 } = options; - try { - validateAbortSignal(signal, "options.signal"); - } catch (error) { - return asyncIterator({ - next: function() { - return Promise.reject(error); - } - }); - } - try { - validateBoolean(reference, "options.ref"); - } catch (error) { - return asyncIterator({ - next: function() { - return Promise.reject(error); - } - }); - } - if (signal?.aborted) - return asyncIterator({ - next: function() { - return Promise.reject(new AbortError); - } - }); - let onCancel, interval; - try { - let notYielded = 0, callback; - if (interval = setInterval(() => { - if (notYielded++, callback) - callback(), callback = void 0; - }, after), !reference) - interval?.unref?.(); - if (signal) - onCancel = () => { - if (clearInterval(interval), callback) - callback(), callback = void 0; - }, signal.addEventListener("abort", onCancel); - return asyncIterator({ - next: function() { - return new Promise((resolve, reject) => { - if (!signal?.aborted) - if (notYielded === 0) - callback = resolve; - else - resolve(); - else if (notYielded === 0) - reject(new AbortError); - else - resolve(); - }).then(() => { - if (notYielded > 0) - return notYielded = notYielded - 1, { done: !1, value }; - return { done: !0 }; - }); - }, - return: function() { - return clearInterval(interval), signal?.removeEventListener("abort", onCancel), Promise.resolve({}); - } - }); - } catch (error) { - return asyncIterator({ - next: function() { - clearInterval(interval), signal?.removeEventListener("abort", onCancel); - } - }); - } -}, symbolAsyncIterator = Symbol.asyncIterator; - -class ERR_INVALID_ARG_TYPE extends Error { - constructor(name, expected, actual) { - super(`${name} must be ${expected}, ${typeof actual} given`); - this.code = "ERR_INVALID_ARG_TYPE"; - } -} - -class AbortError extends Error { - constructor() { - super("The operation was aborted"); - this.code = "ABORT_ERR"; - } -} -var timers_promises_default = { setTimeout: setTimeoutPromise, setImmediate: setImmediatePromise, setInterval: setIntervalPromise }; -export { - setTimeoutPromise as setTimeout, - setIntervalPromise as setInterval, - setImmediatePromise as setImmediate, - timers_promises_default as default -}; diff --git a/src/js/out/modules/node/tls.js b/src/js/out/modules/node/tls.js deleted file mode 100644 index fba1e413af110c..00000000000000 --- a/src/js/out/modules/node/tls.js +++ /dev/null @@ -1,460 +0,0 @@ -import {isArrayBufferView, isTypedArray} from "node:util/types"; -import net, {Server as NetServer} from "node:net"; -var parseCertString = function() { - throwNotImplemented("Not implemented"); -}, isValidTLSArray = function(obj) { - if (typeof obj === "string" || isTypedArray(obj) || obj instanceof ArrayBuffer || obj instanceof Blob) - return !0; - if (Array.isArray(obj)) { - for (var i = 0;i < obj.length; i++) - if (typeof obj !== "string" && !isTypedArray(obj) && !(obj instanceof ArrayBuffer) && !(obj instanceof Blob)) - return !1; - return !0; - } -}, unfqdn = function(host2) { - return RegExpPrototypeSymbolReplace.call(/[.]$/, host2, ""); -}, toLowerCase = function(c) { - return StringFromCharCode.call(32 + StringPrototypeCharCodeAt.call(c, 0)); -}, splitHost = function(host2) { - return StringPrototypeSplit.call(RegExpPrototypeSymbolReplace.call(/[A-Z]/g, unfqdn(host2), toLowerCase), "."); -}, check = function(hostParts, pattern, wildcards) { - if (!pattern) - return !1; - const patternParts = splitHost(pattern); - if (hostParts.length !== patternParts.length) - return !1; - if (ArrayPrototypeIncludes.call(patternParts, "")) - return !1; - const isBad = (s) => RegExpPrototypeExec.call(/[^\u0021-\u007F]/u, s) !== null; - if (ArrayPrototypeSome.call(patternParts, isBad)) - return !1; - for (let i = hostParts.length - 1;i > 0; i -= 1) - if (hostParts[i] !== patternParts[i]) - return !1; - const hostSubdomain = hostParts[0], patternSubdomain = patternParts[0], patternSubdomainParts = StringPrototypeSplit.call(patternSubdomain, "*"); - if (patternSubdomainParts.length === 1 || StringPrototypeIncludes.call(patternSubdomain, "xn--")) - return hostSubdomain === patternSubdomain; - if (!wildcards) - return !1; - if (patternSubdomainParts.length > 2) - return !1; - if (patternParts.length <= 2) - return !1; - const { 0: prefix, 1: suffix } = patternSubdomainParts; - if (prefix.length + suffix.length > hostSubdomain.length) - return !1; - if (!StringPrototypeStartsWith.call(hostSubdomain, prefix)) - return !1; - if (!StringPrototypeEndsWith.call(hostSubdomain, suffix)) - return !1; - return !0; -}, splitEscapedAltNames = function(altNames) { - const result = []; - let currentToken = "", offset = 0; - while (offset !== altNames.length) { - const nextSep = StringPrototypeIndexOf.call(altNames, ", ", offset), nextQuote = StringPrototypeIndexOf.call(altNames, '"', offset); - if (nextQuote !== -1 && (nextSep === -1 || nextQuote < nextSep)) { - currentToken += StringPrototypeSubstring.call(altNames, offset, nextQuote); - const match = RegExpPrototypeExec.call(jsonStringPattern, StringPrototypeSubstring.call(altNames, nextQuote)); - if (!match) { - let error = new SyntaxError("ERR_TLS_CERT_ALTNAME_FORMAT: Invalid subject alternative name string"); - throw error.name = ERR_TLS_CERT_ALTNAME_FORMAT, error; - } - currentToken += JSON.parse(match[0]), offset = nextQuote + match[0].length; - } else if (nextSep !== -1) - currentToken += StringPrototypeSubstring.call(altNames, offset, nextSep), ArrayPrototypePush.call(result, currentToken), currentToken = "", offset = nextSep + 2; - else - currentToken += StringPrototypeSubstring.call(altNames, offset), offset = altNames.length; - } - return ArrayPrototypePush.call(result, currentToken), result; -}, checkServerIdentity = function(hostname, cert) { - const { subject, subjectaltname: altNames } = cert, dnsNames = [], ips = []; - if (hostname = "" + hostname, altNames) { - const splitAltNames = StringPrototypeIncludes.call(altNames, '"') ? splitEscapedAltNames(altNames) : StringPrototypeSplit.call(altNames, ", "); - ArrayPrototypeForEach.call(splitAltNames, (name) => { - if (StringPrototypeStartsWith.call(name, "DNS:")) - ArrayPrototypePush.call(dnsNames, StringPrototypeSlice.call(name, 4)); - else if (StringPrototypeStartsWith.call(name, "IP Address:")) - ArrayPrototypePush.call(ips, canonicalizeIP(StringPrototypeSlice.call(name, 11))); - }); - } - let valid = !1, reason = "Unknown reason"; - if (hostname = unfqdn(hostname), net.isIP(hostname)) { - if (valid = ArrayPrototypeIncludes.call(ips, canonicalizeIP(hostname)), !valid) - reason = `IP: ${hostname} is not in the cert's list: ` + ArrayPrototypeJoin.call(ips, ", "); - } else if (dnsNames.length > 0 || subject?.CN) { - const hostParts = splitHost(hostname), wildcard = (pattern) => check(hostParts, pattern, !0); - if (dnsNames.length > 0) { - if (valid = ArrayPrototypeSome.call(dnsNames, wildcard), !valid) - reason = `Host: ${hostname}. is not in the cert's altnames: ${altNames}`; - } else { - const cn = subject.CN; - if (Array.isArray(cn)) - valid = ArrayPrototypeSome.call(cn, wildcard); - else if (cn) - valid = wildcard(cn); - if (!valid) - reason = `Host: ${hostname}. is not cert's CN: ${cn}`; - } - } else - reason = "Cert does not contain a DNS name"; - if (!valid) { - let error = new Error(`ERR_TLS_CERT_ALTNAME_INVALID: Hostname/IP does not match certificate's altnames: ${reason}`); - return error.name = "ERR_TLS_CERT_ALTNAME_INVALID", error.reason = reason, error.host = host, error.cert = cert, error; - } -}, SecureContext = function(options) { - return new InternalSecureContext(options); -}, createSecureContext = function(options) { - return new SecureContext(options); -}, translatePeerCertificate = function(c) { - if (!c) - return null; - if (c.issuerCertificate != null && c.issuerCertificate !== c) - c.issuerCertificate = translatePeerCertificate(c.issuerCertificate); - if (c.infoAccess != null) { - const info = c.infoAccess; - c.infoAccess = { __proto__: null }, RegExpPrototypeSymbolReplace.call(/([^\n:]*):([^\n]*)(?:\n|$)/g, info, (all, key, val) => { - if (val.charCodeAt(0) === 34) - val = JSONParse(val); - if (key in c.infoAccess) - ArrayPrototypePush.call(c.infoAccess[key], val); - else - c.infoAccess[key] = [val]; - }); - } - return c; -}, createServer = function(options, connectionListener) { - return new Server(options, connectionListener); -}, getCiphers = function() { - return DEFAULT_CIPHERS.split(":"); -}, getCurves = function() { - return; -}, convertProtocols = function(protocols) { - const lens = new Array(protocols.length), buff = Buffer.allocUnsafe(ArrayPrototypeReduce.call(protocols, (p, c, i) => { - const len = Buffer.byteLength(c); - if (len > 255) - throw new RangeError("The byte length of the protocol at index " + `${i} exceeds the maximum length.`, "<= 255", len, !0); - return lens[i] = len, p + 1 + len; - }, 0)); - let offset = 0; - for (let i = 0, c = protocols.length;i < c; i++) - buff[offset++] = lens[i], buff.write(protocols[i], offset), offset += lens[i]; - return buff; -}, convertALPNProtocols = function(protocols, out) { - if (Array.isArray(protocols)) - out.ALPNProtocols = convertProtocols(protocols); - else if (isTypedArray(protocols)) - out.ALPNProtocols = Buffer.from(protocols); - else if (isArrayBufferView(protocols)) - out.ALPNProtocols = Buffer.from(protocols.buffer.slice(protocols.byteOffset, protocols.byteOffset + protocols.byteLength)); - else if (Buffer.isBuffer(protocols)) - out.ALPNProtocols = protocols; -}, InternalTCPSocket = net[Symbol.for("::bunternal::")], bunSocketInternal = Symbol.for("::bunnetsocketinternal::"), { RegExp, Array, String } = globalThis[Symbol.for("Bun.lazy")]("primordials"), SymbolReplace = Symbol.replace, RegExpPrototypeSymbolReplace = RegExp.prototype[SymbolReplace], RegExpPrototypeExec = RegExp.prototype.exec, StringPrototypeStartsWith = String.prototype.startsWith, StringPrototypeSlice = String.prototype.slice, StringPrototypeIncludes = String.prototype.includes, StringPrototypeSplit = String.prototype.split, StringPrototypeIndexOf = String.prototype.indexOf, StringPrototypeSubstring = String.prototype.substring, StringPrototypeEndsWith = String.prototype.endsWith, StringFromCharCode = String.fromCharCode, StringPrototypeCharCodeAt = String.prototype.charCodeAt, ArrayPrototypeIncludes = Array.prototype.includes, ArrayPrototypeJoin = Array.prototype.join, ArrayPrototypeForEach = Array.prototype.forEach, ArrayPrototypePush = Array.prototype.push, ArrayPrototypeSome = Array.prototype.some, ArrayPrototypeReduce = Array.prototype.reduce, jsonStringPattern = /^"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/, InternalSecureContext = class SecureContext2 { - context; - constructor(options) { - const context = {}; - if (options) { - let key = options.key; - if (key) { - if (!isValidTLSArray(key)) - throw new TypeError("key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.key = key; - } - let cert = options.cert; - if (cert) { - if (!isValidTLSArray(cert)) - throw new TypeError("cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.cert = cert; - } - let ca = options.ca; - if (ca) { - if (!isValidTLSArray(ca)) - throw new TypeError("ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.ca = ca; - } - let passphrase = options.passphrase; - if (passphrase && typeof passphrase !== "string") - throw new TypeError("passphrase argument must be an string"); - this.passphrase = passphrase; - let servername = options.servername; - if (servername && typeof servername !== "string") - throw new TypeError("servername argument must be an string"); - this.servername = servername; - let secureOptions = options.secureOptions || 0; - if (secureOptions && typeof secureOptions !== "number") - throw new TypeError("secureOptions argument must be an number"); - this.secureOptions = secureOptions; - } - this.context = context; - } -}, buntls = Symbol.for("::buntls::"), SocketClass, TLSSocket = function(InternalTLSSocket) { - return SocketClass = InternalTLSSocket, Object.defineProperty(SocketClass.prototype, Symbol.toStringTag, { - value: "TLSSocket", - enumerable: !1 - }), Object.defineProperty(function Socket(options) { - return new InternalTLSSocket(options); - }, Symbol.hasInstance, { - value(instance) { - return instance instanceof InternalTLSSocket; - } - }); -}(class TLSSocket2 extends InternalTCPSocket { - #secureContext; - ALPNProtocols; - #socket; - #checkServerIdentity; - #session; - constructor(socket, options) { - super(socket instanceof InternalTCPSocket ? options : options || socket); - if (options = options || socket || {}, typeof options === "object") { - const { ALPNProtocols } = options; - if (ALPNProtocols) - convertALPNProtocols(ALPNProtocols, this); - if (socket instanceof InternalTCPSocket) - this.#socket = socket; - } - this.#secureContext = options.secureContext || createSecureContext(options), this.authorized = !1, this.secureConnecting = !0, this._secureEstablished = !1, this._securePending = !0, this.#checkServerIdentity = options.checkServerIdentity || checkServerIdentity, this.#session = options.session || null; - } - _secureEstablished = !1; - _securePending = !0; - _newSessionPending; - _controlReleased; - secureConnecting = !1; - _SNICallback; - servername; - authorized = !1; - authorizationError; - #renegotiationDisabled = !1; - encrypted = !0; - _start() { - this.connect(); - } - getSession() { - return this[bunSocketInternal]?.getSession(); - } - getEphemeralKeyInfo() { - return this[bunSocketInternal]?.getEphemeralKeyInfo(); - } - getCipher() { - return this[bunSocketInternal]?.getCipher(); - } - getSharedSigalgs() { - return this[bunSocketInternal]?.getSharedSigalgs(); - } - getProtocol() { - return this[bunSocketInternal]?.getTLSVersion(); - } - getFinished() { - return this[bunSocketInternal]?.getTLSFinishedMessage() || void 0; - } - getPeerFinished() { - return this[bunSocketInternal]?.getTLSPeerFinishedMessage() || void 0; - } - isSessionReused() { - return !!this.#session; - } - renegotiate() { - if (this.#renegotiationDisabled) { - const error = new Error("ERR_TLS_RENEGOTIATION_DISABLED: TLS session renegotiation disabled for this socket"); - throw error.name = "ERR_TLS_RENEGOTIATION_DISABLED", error; - } - throw Error("Not implented in Bun yet"); - } - disableRenegotiation() { - this.#renegotiationDisabled = !0; - } - getTLSTicket() { - return this[bunSocketInternal]?.getTLSTicket(); - } - exportKeyingMaterial(length, label, context) { - if (context) - return this[bunSocketInternal]?.exportKeyingMaterial(length, label, context); - return this[bunSocketInternal]?.exportKeyingMaterial(length, label); - } - setMaxSendFragment(size) { - return this[bunSocketInternal]?.setMaxSendFragment(size) || !1; - } - enableTrace() { - } - setServername(name) { - if (this.isServer) { - let error = new Error("ERR_TLS_SNI_FROM_SERVER: Cannot issue SNI from a TLS server-side socket"); - throw error.name = "ERR_TLS_SNI_FROM_SERVER", error; - } - this.servername = name, this[bunSocketInternal]?.setServername(name); - } - setSession(session) { - if (this.#session = session, typeof session === "string") - session = Buffer.from(session, "latin1"); - return this[bunSocketInternal]?.setSession(session); - } - getPeerCertificate(abbreviated) { - const cert = arguments.length < 1 ? this[bunSocketInternal]?.getPeerCertificate() : this[bunSocketInternal]?.getPeerCertificate(abbreviated); - if (cert) - return translatePeerCertificate(cert); - } - getCertificate() { - const cert = this[bunSocketInternal]?.getCertificate(); - if (cert) - return translatePeerCertificate(cert); - } - getPeerX509Certificate() { - throw Error("Not implented in Bun yet"); - } - getX509Certificate() { - throw Error("Not implented in Bun yet"); - } - get alpnProtocol() { - return this[bunSocketInternal]?.alpnProtocol; - } - [buntls](port, host2) { - return { - socket: this.#socket, - ALPNProtocols: this.ALPNProtocols, - serverName: this.servername || host2 || "localhost", - checkServerIdentity: this.#checkServerIdentity, - session: this.#session, - ...this.#secureContext - }; - } -}); - -class Server extends NetServer { - key; - cert; - ca; - passphrase; - secureOptions; - _rejectUnauthorized; - _requestCert; - servername; - ALPNProtocols; - constructor(options, secureConnectionListener) { - super(options, secureConnectionListener); - this.setSecureContext(options); - } - setSecureContext(options) { - if (options instanceof InternalSecureContext) - options = options.context; - if (options) { - const { ALPNProtocols } = options; - if (ALPNProtocols) - convertALPNProtocols(ALPNProtocols, this); - let key = options.key; - if (key) { - if (!isValidTLSArray(key)) - throw new TypeError("key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.key = key; - } - let cert = options.cert; - if (cert) { - if (!isValidTLSArray(cert)) - throw new TypeError("cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.cert = cert; - } - let ca = options.ca; - if (ca) { - if (!isValidTLSArray(ca)) - throw new TypeError("ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile"); - this.ca = ca; - } - let passphrase = options.passphrase; - if (passphrase && typeof passphrase !== "string") - throw new TypeError("passphrase argument must be an string"); - this.passphrase = passphrase; - let servername = options.servername; - if (servername && typeof servername !== "string") - throw new TypeError("servername argument must be an string"); - this.servername = servername; - let secureOptions = options.secureOptions || 0; - if (secureOptions && typeof secureOptions !== "number") - throw new TypeError("secureOptions argument must be an number"); - this.secureOptions = secureOptions; - const requestCert = options.requestCert || !1; - if (requestCert) - this._requestCert = requestCert; - else - this._requestCert = void 0; - const rejectUnauthorized = options.rejectUnauthorized || !1; - if (rejectUnauthorized) - this._rejectUnauthorized = rejectUnauthorized; - else - this._rejectUnauthorized = void 0; - } - } - getTicketKeys() { - throw Error("Not implented in Bun yet"); - } - setTicketKeys() { - throw Error("Not implented in Bun yet"); - } - [buntls](port, host2, isClient) { - return [ - { - serverName: this.servername || host2 || "localhost", - key: this.key, - cert: this.cert, - ca: this.ca, - passphrase: this.passphrase, - secureOptions: this.secureOptions, - rejectUnauthorized: isClient ? !1 : this._rejectUnauthorized, - requestCert: isClient ? !1 : this._requestCert, - ALPNProtocols: this.ALPNProtocols - }, - SocketClass - ]; - } -} -var CLIENT_RENEG_LIMIT = 3, CLIENT_RENEG_WINDOW = 600, DEFAULT_ECDH_CURVE = "auto", DEFAULT_CIPHERS = "DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256", DEFAULT_MIN_VERSION = "TLSv1.2", DEFAULT_MAX_VERSION = "TLSv1.3", createConnection = (port, host2, connectListener) => { - if (typeof port === "object") { - port.checkServerIdentity; - const { ALPNProtocols } = port; - if (ALPNProtocols) - convertALPNProtocols(ALPNProtocols, port); - return new TLSSocket(port).connect(port, host2, connectListener); - } - return new TLSSocket().connect(port, host2, connectListener); -}, connect = createConnection, rootCertificates = globalThis[Symbol.for("Bun.lazy")]("rootCertificates"), exports = { - [Symbol.for("CommonJS")]: 0, - CLIENT_RENEG_LIMIT, - CLIENT_RENEG_WINDOW, - connect, - convertALPNProtocols, - createConnection, - createSecureContext, - createServer, - DEFAULT_CIPHERS, - DEFAULT_ECDH_CURVE, - DEFAULT_MAX_VERSION, - DEFAULT_MIN_VERSION, - getCiphers, - getCurves, - parseCertString, - SecureContext, - Server, - TLSSocket, - checkServerIdentity, - rootCertificates -}; -export { - rootCertificates, - parseCertString, - getCurves, - getCiphers, - exports as default, - createServer, - createSecureContext, - createConnection, - convertALPNProtocols, - connect, - checkServerIdentity, - TLSSocket, - Server, - SecureContext, - DEFAULT_MIN_VERSION, - DEFAULT_MAX_VERSION, - DEFAULT_ECDH_CURVE, - DEFAULT_CIPHERS, - CLIENT_RENEG_WINDOW, - CLIENT_RENEG_LIMIT -}; diff --git a/src/js/out/modules/node/trace_events.js b/src/js/out/modules/node/trace_events.js deleted file mode 100644 index 71fcfb89017001..00000000000000 --- a/src/js/out/modules/node/trace_events.js +++ /dev/null @@ -1,25 +0,0 @@ -var ERR_INVALID_ARG_TYPE = function(name, type, value) { - const err = new TypeError(`The "${name}" argument must be of type ${type}. Received ${value}`); - return err.code = "ERR_INVALID_ARG_TYPE", err; -}, createTracing = function(opts) { - if (typeof opts !== "object" || opts == null) - throw new ERR_INVALID_ARG_TYPE("options", "Object", opts); - return new Tracing(opts); -}, getEnabledCategories = function() { - return ""; -}; - -class Tracing { - enabled = !1; - categories = ""; -} -var defaultObject = { - createTracing, - getEnabledCategories, - [Symbol.for("CommonJS")]: 0 -}; -export { - getEnabledCategories, - defaultObject as default, - createTracing -}; diff --git a/src/js/out/modules/node/url.js b/src/js/out/modules/node/url.js deleted file mode 100644 index 58017868846fd7..00000000000000 --- a/src/js/out/modules/node/url.js +++ /dev/null @@ -1 +0,0 @@ -var Kf=(N)=>{return import.meta.require(N)};var $=function(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null},g=function(N,J,f){if(N&&typeof N==="object"&&N instanceof $)return N;var X=new $;return X.parse(N,J,f),X},t=function(N){if(typeof N==="string")N=g(N);if(!(N instanceof $))return $.prototype.format.call(N);return N.format()},ff=function(N,J){return g(N,!1,!0).resolve(J)},Nf=function(N,J){if(!N)return J;return g(N,!1,!0).resolveObject(J)},Bf=function(N){const J={protocol:N.protocol,hostname:typeof N.hostname==="string"&&N.hostname.startsWith("[")?N.hostname.slice(1,-1):N.hostname,hash:N.hash,search:N.search,pathname:N.pathname,path:`${N.pathname||""}${N.search||""}`,href:N.href};if(N.port!=="")J.port=Number(N.port);if(N.username||N.password)J.auth=`${decodeURIComponent(N.username)}:${decodeURIComponent(N.password)}`;return J},{URL:n,URLSearchParams:H}=globalThis,i=/^([a-z0-9.+-]+:)/i,o=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,a=["<",">",'"',"`"," ","\r","\n","\t"],l=["{","}","|","\\","^","`"].concat(a),E=["'"].concat(l),m=["%","/","?",";","#"].concat(E),c=["/","?","#"],s=255,P=/^[+a-z0-9A-Z_-]{0,63}$/,r=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,e={javascript:!0,"javascript:":!0},d={javascript:!0,"javascript:":!0},L={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};$.prototype.parse=function(N,J,f){if(typeof N!=="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof N);var X=N.indexOf("?"),V=X!==-1&&X127)z+="x";else z+=x[C];if(!z.match(P)){var q=G.slice(0,K),F=G.slice(K+1),Q=x.match(r);if(Q)q.push(Q[1]),F.unshift(Q[2]);if(F.length)B="/"+F.join(".")+B;this.hostname=q.join(".");break}}}}if(this.hostname.length>s)this.hostname="";else this.hostname=this.hostname.toLowerCase();if(!R)this.hostname=new n("http://"+this.hostname).hostname;var b=this.port?":"+this.port:"",v=this.hostname||"";if(this.host=v+b,this.href+=this.host,R){if(this.hostname=this.hostname.substr(1,this.hostname.length-2),B[0]!=="/")B="/"+B}}if(!e[I])for(var K=0,M=E.length;K0?f.host.split("@"):!1;if(z)f.auth=z.shift(),f.hostname=z.shift(),f.host=f.hostname}if(f.search=N.search,f.query=N.query,f.pathname!==null||f.search!==null)f.path=(f.pathname?f.pathname:"")+(f.search?f.search:"");return f.href=f.format(),f}if(!G.length){if(f.pathname=null,f.search)f.path="/"+f.search;else f.path=null;return f.href=f.format(),f}var C=G.slice(-1)[0],S=(f.host||N.host||G.length>1)&&(C==="."||C==="..")||C==="",q=0;for(var F=G.length;F>=0;F--)if(C=G[F],C===".")G.splice(F,1);else if(C==="..")G.splice(F,1),q++;else if(q)G.splice(F,1),q--;if(!Z&&!R)for(;q--;q)G.unshift("..");if(Z&&G[0]!==""&&(!G[0]||G[0].charAt(0)!=="/"))G.unshift("");if(S&&G.join("/").substr(-1)!=="/")G.push("");var Q=G[0]===""||G[0]&&G[0].charAt(0)==="/";if(x){f.hostname=Q?"":G.length?G.shift():"",f.host=f.hostname;var z=f.host&&f.host.indexOf("@")>0?f.host.split("@"):!1;if(z)f.auth=z.shift(),f.hostname=z.shift(),f.host=f.hostname}if(Z=Z||f.host&&G.length,Z&&!Q)G.unshift("");if(G.length>0)f.pathname=G.join("/");else f.pathname=null,f.path=null;if(f.pathname!==null||f.search!==null)f.path=(f.pathname?f.pathname:"")+(f.search?f.search:"");return f.auth=N.auth||f.auth,f.slashes=f.slashes||N.slashes,f.href=f.format(),f};$.prototype.parseHost=function(){var N=this.host,J=o.exec(N);if(J){if(J=J[0],J!==":")this.port=J.substr(1);N=N.substr(0,N.length-J.length)}if(N)this.hostname=N};var p=globalThis[Symbol.for("Bun.lazy")],Gf=p("pathToFileURL"),Jf=p("fileURLToPath"),Vf={parse:g,resolve:ff,resolveObject:Nf,format:t,Url:$,URLSearchParams:H,URL:n,pathToFileURL:Gf,fileURLToPath:Jf,urlToHttpOptions:Bf,[Symbol.for("CommonJS")]:0};export{Bf as urlToHttpOptions,Nf as resolveObject,ff as resolve,Gf as pathToFileURL,g as parse,t as format,Jf as fileURLToPath,Vf as default,$ as Url,H as URLSearchParams,n as URL}; diff --git a/src/js/out/modules/node/util.js b/src/js/out/modules/node/util.js deleted file mode 100644 index eade9e0d9b7480..00000000000000 --- a/src/js/out/modules/node/util.js +++ /dev/null @@ -1,454 +0,0 @@ -import * as types from "node:util/types"; -import {default as default2} from "node:util/types"; -var isBufferInterface = function({ copy, fill, readUint8 }) { - return typeof copy === "function" && typeof fill === "function" && typeof readUint8 === "function"; -}; -function isBuffer(value) { - return Buffer.isBuffer(value) || typeof value === "object" && isBufferInterface(value || {}); -} -var isFunction = function(value) { - return typeof value === "function"; -}, format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0;i < arguments.length; i++) - objects.push(inspect(arguments[i])); - return objects.join(" "); - } - var i = 1, args = arguments, len = args.length, str = String(f).replace(formatRegExp, function(x2) { - if (x2 === "%%") - return "%"; - if (i >= len) - return x2; - switch (x2) { - case "%s": - return String(args[i++]); - case "%d": - return Number(args[i++]); - case "%j": - try { - return JSON.stringify(args[i++]); - } catch (_) { - return "[Circular]"; - } - default: - return x2; - } - }); - for (var x = args[i];i < len; x = args[++i]) - if (isNull(x) || !isObject(x)) - str += " " + x; - else - str += " " + inspect(x); - return str; -}, deprecate = function(fn, msg, code) { - if (process.noDeprecation === !0) - return fn; - var warned = !1; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - var err = new Error(msg); - if (code) - err.code = code; - throw err; - } else if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - warned = !0; - } - return fn.apply(this, arguments); - } - return deprecated; -}, debuglog = function(set) { - if (set = set.toUpperCase(), !debugs[set]) - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = format.apply(cjs_exports, arguments); - console.error("%s %d: %s", set, pid, msg); - }; - } else - debugs[set] = function() { - }; - return debugs[set]; -}, inspect = function(obj, opts) { - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - if (arguments.length >= 3) - ctx.depth = arguments[2]; - if (arguments.length >= 4) - ctx.colors = arguments[3]; - if (isBoolean(opts)) - ctx.showHidden = opts; - else if (opts) - _extend(ctx, opts); - if (isUndefined(ctx.showHidden)) - ctx.showHidden = !1; - if (isUndefined(ctx.depth)) - ctx.depth = 2; - if (isUndefined(ctx.colors)) - ctx.colors = !1; - if (isUndefined(ctx.customInspect)) - ctx.customInspect = !0; - if (ctx.colors) - ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -}, stylizeWithColor = function(str, styleType) { - var style = inspect.styles[styleType]; - if (style) - return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m"; - else - return str; -}, stylizeNoColor = function(str, styleType) { - return str; -}, arrayToHash = function(array) { - var hash = {}; - return array.forEach(function(val, idx) { - hash[val] = !0; - }), hash; -}, formatValue = function(ctx, value, recurseTimes) { - if (ctx.customInspect && value && isFunction(value.inspect) && value.inspect !== inspect && !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) - ret = formatValue(ctx, ret, recurseTimes); - return ret; - } - var primitive = formatPrimitive(ctx, value); - if (primitive) - return primitive; - var keys = Object.keys(value), visibleKeys = arrayToHash(keys); - if (ctx.showHidden) - keys = Object.getOwnPropertyNames(value); - if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) - return formatError(value); - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ": " + value.name : ""; - return ctx.stylize("[Function" + name + "]", "special"); - } - if (isRegExp2(value)) - return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); - if (isDate2(value)) - return ctx.stylize(Date.prototype.toString.call(value), "date"); - if (isError(value)) - return formatError(value); - } - var base = "", array = !1, braces = ["{", "}"]; - if (isArray(value)) - array = !0, braces = ["[", "]"]; - if (isFunction(value)) { - var n = value.name ? ": " + value.name : ""; - base = " [Function" + n + "]"; - } - if (isRegExp2(value)) - base = " " + RegExp.prototype.toString.call(value); - if (isDate2(value)) - base = " " + Date.prototype.toUTCString.call(value); - if (isError(value)) - base = " " + formatError(value); - if (keys.length === 0 && (!array || value.length == 0)) - return braces[0] + base + braces[1]; - if (recurseTimes < 0) - if (isRegExp2(value)) - return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); - else - return ctx.stylize("[Object]", "special"); - ctx.seen.push(value); - var output; - if (array) - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - else - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - return ctx.seen.pop(), reduceToSingleString(output, base, braces); -}, formatPrimitive = function(ctx, value) { - if (isUndefined(value)) - return ctx.stylize("undefined", "undefined"); - if (isString(value)) { - var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; - return ctx.stylize(simple, "string"); - } - if (isNumber(value)) - return ctx.stylize("" + value, "number"); - if (isBoolean(value)) - return ctx.stylize("" + value, "boolean"); - if (isNull(value)) - return ctx.stylize("null", "null"); -}, formatError = function(value) { - return "[" + Error.prototype.toString.call(value) + "]"; -}, formatArray = function(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length;i < l; ++i) - if (hasOwnProperty(value, String(i))) - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), !0)); - else - output.push(""); - return keys.forEach(function(key) { - if (!key.match(/^\d+$/)) - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, !0)); - }), output; -}, formatProperty = function(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - if (desc = Object.getOwnPropertyDescriptor(value, key) || { - value: value[key] - }, desc.get) - if (desc.set) - str = ctx.stylize("[Getter/Setter]", "special"); - else - str = ctx.stylize("[Getter]", "special"); - else if (desc.set) - str = ctx.stylize("[Setter]", "special"); - if (!hasOwnProperty(visibleKeys, key)) - name = "[" + key + "]"; - if (!str) - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) - str = formatValue(ctx, desc.value, null); - else - str = formatValue(ctx, desc.value, recurseTimes - 1); - if (str.indexOf("\n") > -1) - if (array) - str = str.split("\n").map(function(line) { - return " " + line; - }).join("\n").substr(2); - else - str = "\n" + str.split("\n").map(function(line) { - return " " + line; - }).join("\n"); - } else - str = ctx.stylize("[Circular]", "special"); - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) - return str; - if (name = JSON.stringify("" + key), name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) - name = name.substr(1, name.length - 2), name = ctx.stylize(name, "name"); - else - name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"), name = ctx.stylize(name, "string"); - } - return name + ": " + str; -}, reduceToSingleString = function(output, base, braces) { - var numLinesEst = 0, length = output.reduce(function(prev, cur) { - if (numLinesEst++, cur.indexOf("\n") >= 0) - numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; - }, 0); - if (length > 60) - return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n ") + " " + braces[1]; - return braces[0] + base + " " + output.join(", ") + " " + braces[1]; -}, isArray = function(ar) { - return Array.isArray(ar); -}, isBoolean = function(arg) { - return typeof arg === "boolean"; -}, isNull = function(arg) { - return arg === null; -}, isNullOrUndefined = function(arg) { - return arg == null; -}, isNumber = function(arg) { - return typeof arg === "number"; -}, isString = function(arg) { - return typeof arg === "string"; -}, isSymbol = function(arg) { - return typeof arg === "symbol"; -}, isUndefined = function(arg) { - return arg === void 0; -}, isObject = function(arg) { - return typeof arg === "object" && arg !== null; -}, isPrimitive = function(arg) { - return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || typeof arg === "undefined"; -}, pad = function(n) { - return n < 10 ? "0" + n.toString(10) : n.toString(10); -}, timestamp = function() { - var d = new Date, time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(":"); - return [d.getDate(), months[d.getMonth()], time].join(" "); -}, hasOwnProperty = function(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -}, callbackifyOnRejected = function(reason, cb) { - if (!reason) { - var newReason = new Error("Promise was rejected with a falsy value"); - newReason.reason = reason, newReason.code = "ERR_FALSY_VALUE_REJECTION", reason = newReason; - } - return cb(reason); -}, callbackify = function(original) { - if (typeof original !== "function") - throw new TypeError('The "original" argument must be of type Function'); - function callbackified() { - var args = Array.prototype.slice.call(arguments), maybeCb = args.pop(); - if (typeof maybeCb !== "function") - throw new TypeError("The last argument must be of type Function"); - var self = this, cb = function() { - return maybeCb.apply(self, arguments); - }; - original.apply(this, args).then(function(ret) { - process.nextTick(cb, null, ret); - }, function(rej) { - process.nextTick(callbackifyOnRejected, rej, cb); - }); - } - return Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)), Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)), callbackified; -}, cjs_exports = {}, util_default = cjs_exports, __getOwnPropNames = Object.getOwnPropertyNames, __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}, require_inherits_browser = __commonJS({ - "node_modules/inherits/inherits_browser.js"(exports, module2) { - module2.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor, ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: !1, - writable: !0, - configurable: !0 - } - }); - }; - } -}), deepEquals = Bun.deepEquals, isDeepStrictEqual = (a, b) => deepEquals(a, b, !0), getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors, formatRegExp = /%[sdj%]/g, debugs = {}, debugEnvRegex = /^$/; -if (process.env.NODE_DEBUG) - debugEnv = process.env.NODE_DEBUG, debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase(), debugEnvRegex = new RegExp("^" + debugEnv + "$", "i"); -var debugEnv; -inspect.colors = { - bold: [1, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - white: [37, 39], - grey: [90, 39], - black: [30, 39], - blue: [34, 39], - cyan: [36, 39], - green: [32, 39], - magenta: [35, 39], - red: [31, 39], - yellow: [33, 39] -}; -inspect.styles = { - special: "cyan", - number: "yellow", - boolean: "yellow", - undefined: "grey", - null: "bold", - string: "green", - date: "magenta", - regexp: "red" -}; -var isRegExp2 = types.isRegExp, isDate2 = types.isDate, isError = types.isNativeError, months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], log = function log2() { - console.log("%s - %s", timestamp(), format.apply(cjs_exports, arguments)); -}, inherits = inherits = require_inherits_browser(), _extend = function(origin, add) { - if (!add || !isObject(add)) - return origin; - var keys = Object.keys(add), i = keys.length; - while (i--) - origin[keys[i]] = add[keys[i]]; - return origin; -}, kCustomPromisifiedSymbol = Symbol.for("util.promisify.custom"), promisify = function promisify2(original) { - if (typeof original !== "function") - throw new TypeError('The "original" argument must be of type Function'); - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== "function") - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - return Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, - enumerable: !1, - writable: !1, - configurable: !0 - }), fn; - } - function fn() { - var promiseResolve, promiseReject, promise = new Promise(function(resolve, reject) { - promiseResolve = resolve, promiseReject = reject; - }), args = []; - for (var i = 0;i < arguments.length; i++) - args.push(arguments[i]); - args.push(function(err, value) { - if (err) - promiseReject(err); - else - promiseResolve(value); - }); - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - return promise; - } - if (Object.setPrototypeOf(fn, Object.getPrototypeOf(original)), kCustomPromisifiedSymbol) - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, - enumerable: !1, - writable: !1, - configurable: !0 - }); - return Object.defineProperties(fn, getOwnPropertyDescriptors(original)); -}; -promisify.custom = kCustomPromisifiedSymbol; -var { TextDecoder, TextEncoder } = globalThis, toUSVString = (input) => { - return (input + "").toWellFormed(); -}; -Object.assign(cjs_exports, { - format, - deprecate, - debuglog, - _extend, - inspect, - types, - isArray, - isBoolean, - isNull, - isNullOrUndefined, - isNumber, - isString, - isSymbol, - isUndefined, - isRegExp: isRegExp2, - isObject, - isDate: isDate2, - isFunction, - isError, - isPrimitive, - isBuffer, - log, - inherits, - toUSVString, - promisify, - callbackify, - isDeepStrictEqual, - TextDecoder, - TextEncoder, - [Symbol.for("CommonJS")]: 0 -}); -export { - default2 as types, - toUSVString, - promisify, - log, - isUndefined, - isSymbol, - isString, - isRegExp2 as isRegExp, - isPrimitive, - isObject, - isNumber, - isNullOrUndefined, - isNull, - isFunction, - isError, - isDeepStrictEqual, - isDate2 as isDate, - isBuffer, - isBoolean, - isArray, - inspect, - inherits, - format, - deprecate, - util_default as default, - debuglog, - callbackify, - TextEncoder, - TextDecoder -}; diff --git a/src/js/out/modules/node/v8.js b/src/js/out/modules/node/v8.js deleted file mode 100644 index b2a42e898f3820..00000000000000 --- a/src/js/out/modules/node/v8.js +++ /dev/null @@ -1,140 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/v8.ts -import {serialize as jscSerialize, deserialize as jscDeserialize} from "bun:jsc"; -var notimpl = function(message) { - throwNotImplemented("node:v8 " + message); -}, cachedDataVersionTag = function() { - notimpl("cachedDataVersionTag"); -}, getHeapSnapshot = function() { - notimpl("getHeapSnapshot"); -}, getHeapStatistics = function() { - notimpl("getHeapStatistics"); -}, getHeapSpaceStatistics = function() { - notimpl("getHeapSpaceStatistics"); -}, getHeapCodeStatistics = function() { - notimpl("getHeapCodeStatistics"); -}, setFlagsFromString = function() { - notimpl("setFlagsFromString"); -}, deserialize = function(value) { - return jscDeserialize(value); -}, takeCoverage = function() { - notimpl("takeCoverage"); -}, stopCoverage = function() { - notimpl("stopCoverage"); -}, serialize = function(arg1) { - return jscSerialize(arg1, { binaryType: "nodebuffer" }); -}, writeHeapSnapshot = function() { - notimpl("writeHeapSnapshot"); -}, setHeapSnapshotNearHeapLimit = function() { - notimpl("setHeapSnapshotNearHeapLimit"); -}; - -class Deserializer { - constructor() { - notimpl("Deserializer"); - } -} - -class Serializer { - constructor() { - notimpl("Serializer"); - } -} - -class DefaultDeserializer extends Deserializer { - constructor() { - super(...arguments); - } -} - -class DefaultSerializer extends Serializer { - constructor() { - super(...arguments); - } -} - -class GCProfiler { - constructor() { - notimpl("GCProfiler"); - } -} -var promiseHooks = { - createHook: () => { - notimpl("createHook"); - }, - onInit: () => { - notimpl("onInit"); - }, - onBefore: () => { - notimpl("onBefore"); - }, - onAfter: () => { - notimpl("onAfter"); - }, - onSettled: () => { - notimpl("onSettled"); - } -}, startupSnapshot = { - addDeserializeCallback: () => notimpl("addDeserializeCallback"), - addSerializeCallback: () => notimpl("addSerializeCallback"), - setDeserializeMainFunction: () => notimpl("setDeserializeMainFunction"), - isBuildingSnapshot: () => notimpl("isBuildingSnapshot") -}, defaultObject = { - cachedDataVersionTag, - getHeapSnapshot, - getHeapStatistics, - getHeapSpaceStatistics, - getHeapCodeStatistics, - setFlagsFromString, - deserialize, - takeCoverage, - stopCoverage, - serialize, - writeHeapSnapshot, - setHeapSnapshotNearHeapLimit, - promiseHooks, - startupSnapshot, - Deserializer, - Serializer, - [Symbol.for("CommonJS")]: 0 -}; -hideFromStack(notimpl, cachedDataVersionTag, getHeapSnapshot, getHeapStatistics, getHeapSpaceStatistics, getHeapCodeStatistics, setFlagsFromString, deserialize, takeCoverage, stopCoverage, serialize, writeHeapSnapshot, setHeapSnapshotNearHeapLimit, Deserializer, Serializer, DefaultDeserializer, DefaultSerializer, GCProfiler); -export { - writeHeapSnapshot, - takeCoverage, - stopCoverage, - startupSnapshot, - setHeapSnapshotNearHeapLimit, - setFlagsFromString, - serialize, - promiseHooks, - getHeapStatistics, - getHeapSpaceStatistics, - getHeapSnapshot, - getHeapCodeStatistics, - deserialize, - defaultObject as default, - cachedDataVersionTag, - Serializer, - GCProfiler, - Deserializer, - DefaultSerializer, - DefaultDeserializer -}; diff --git a/src/js/out/modules/node/vm.js b/src/js/out/modules/node/vm.js deleted file mode 100644 index 5afa4a3b973450..00000000000000 --- a/src/js/out/modules/node/vm.js +++ /dev/null @@ -1,47 +0,0 @@ -function throwNotImplemented(feature, issue) { - throw hideFromStack(throwNotImplemented), new NotImplementedError(feature, issue); -} -function hideFromStack(...fns) { - for (let fn of fns) - Object.defineProperty(fn, "name", { - value: "::bunternal::" - }); -} - -class NotImplementedError extends Error { - code; - constructor(feature, issue) { - super(feature + " is not yet implemented in Bun." + (issue ? " Track the status & thumbs up the issue: https://github.com/oven-sh/bun/issues/" + issue : "")); - this.name = "NotImplementedError", this.code = "ERR_NOT_IMPLEMENTED", hideFromStack(NotImplementedError); - } -} - -// src/js/node/vm.ts -var runInContext = function(code, context, options) { - return new Script(code, options).runInContext(context); -}, compileFunction = function() { - throwNotImplemented("node:vm compileFunction", 401); -}, measureMemory = function() { - throwNotImplemented("node:vm measureMemory", 401); -}, vm = globalThis[Symbol.for("Bun.lazy")]("vm"), { createContext, isContext, Script, runInNewContext, runInThisContext } = vm, defaultObject = { - createContext, - runInContext, - runInNewContext, - runInThisContext, - isContext, - compileFunction, - measureMemory, - Script, - [Symbol.for("CommonJS")]: 0 -}; -export { - runInThisContext, - runInNewContext, - runInContext, - measureMemory, - isContext, - defaultObject as default, - createContext, - compileFunction, - Script -}; diff --git a/src/js/out/modules/node/wasi.js b/src/js/out/modules/node/wasi.js deleted file mode 100644 index ab6cf6abf66add..00000000000000 --- a/src/js/out/modules/node/wasi.js +++ /dev/null @@ -1,1102 +0,0 @@ -var nodeFsConstants = constants, __getOwnPropNames = Object.getOwnPropertyNames, __commonJS = (cb, mod) => function __require2() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}, require_types = __commonJS({ - "node_modules/wasi-js/dist/types.js"(exports) { - Object.defineProperty(exports, "__esModule", { value: !0 }), exports.WASIKillError = exports.WASIExitError = exports.WASIError = void 0; - var WASIError = class extends Error { - constructor(errno) { - super(); - this.errno = errno, Object.setPrototypeOf(this, WASIError.prototype); - } - }; - exports.WASIError = WASIError; - var WASIExitError = class extends Error { - constructor(code) { - super(`WASI Exit error: ${code}`); - this.code = code, Object.setPrototypeOf(this, WASIExitError.prototype); - } - }; - exports.WASIExitError = WASIExitError; - var WASIKillError = class extends Error { - constructor(signal) { - super(`WASI Kill signal: ${signal}`); - this.signal = signal, Object.setPrototypeOf(this, WASIKillError.prototype); - } - }; - exports.WASIKillError = WASIKillError; - } -}), require_constants = __commonJS({ - "node_modules/wasi-js/dist/constants.js"(exports) { - Object.defineProperty(exports, "__esModule", { value: !0 }), exports.WASI_ENOMSG = exports.WASI_ENOMEM = exports.WASI_ENOLINK = exports.WASI_ENOLCK = exports.WASI_ENOEXEC = exports.WASI_ENOENT = exports.WASI_ENODEV = exports.WASI_ENOBUFS = exports.WASI_ENFILE = exports.WASI_ENETUNREACH = exports.WASI_ENETRESET = exports.WASI_ENETDOWN = exports.WASI_ENAMETOOLONG = exports.WASI_EMULTIHOP = exports.WASI_EMSGSIZE = exports.WASI_EMLINK = exports.WASI_EMFILE = exports.WASI_ELOOP = exports.WASI_EISDIR = exports.WASI_EISCONN = exports.WASI_EIO = exports.WASI_EINVAL = exports.WASI_EINTR = exports.WASI_EINPROGRESS = exports.WASI_EILSEQ = exports.WASI_EIDRM = exports.WASI_EHOSTUNREACH = exports.WASI_EFBIG = exports.WASI_EFAULT = exports.WASI_EEXIST = exports.WASI_EDQUOT = exports.WASI_EDOM = exports.WASI_EDESTADDRREQ = exports.WASI_EDEADLK = exports.WASI_ECONNRESET = exports.WASI_ECONNREFUSED = exports.WASI_ECONNABORTED = exports.WASI_ECHILD = exports.WASI_ECANCELED = exports.WASI_EBUSY = exports.WASI_EBADMSG = exports.WASI_EBADF = exports.WASI_EALREADY = exports.WASI_EAGAIN = exports.WASI_EAFNOSUPPORT = exports.WASI_EADDRNOTAVAIL = exports.WASI_EADDRINUSE = exports.WASI_EACCES = exports.WASI_E2BIG = exports.WASI_ESUCCESS = void 0, exports.WASI_SIGVTALRM = exports.WASI_SIGUSR2 = exports.WASI_SIGUSR1 = exports.WASI_SIGURG = exports.WASI_SIGTTOU = exports.WASI_SIGTTIN = exports.WASI_SIGTSTP = exports.WASI_SIGTRAP = exports.WASI_SIGTERM = exports.WASI_SIGSTOP = exports.WASI_SIGSEGV = exports.WASI_SIGQUIT = exports.WASI_SIGPIPE = exports.WASI_SIGKILL = exports.WASI_SIGINT = exports.WASI_SIGILL = exports.WASI_SIGHUP = exports.WASI_SIGFPE = exports.WASI_SIGCONT = exports.WASI_SIGCHLD = exports.WASI_SIGBUS = exports.WASI_SIGALRM = exports.WASI_SIGABRT = exports.WASI_ENOTCAPABLE = exports.WASI_EXDEV = exports.WASI_ETXTBSY = exports.WASI_ETIMEDOUT = exports.WASI_ESTALE = exports.WASI_ESRCH = exports.WASI_ESPIPE = exports.WASI_EROFS = exports.WASI_ERANGE = exports.WASI_EPROTOTYPE = exports.WASI_EPROTONOSUPPORT = exports.WASI_EPROTO = exports.WASI_EPIPE = exports.WASI_EPERM = exports.WASI_EOWNERDEAD = exports.WASI_EOVERFLOW = exports.WASI_ENXIO = exports.WASI_ENOTTY = exports.WASI_ENOTSUP = exports.WASI_ENOTSOCK = exports.WASI_ENOTRECOVERABLE = exports.WASI_ENOTEMPTY = exports.WASI_ENOTDIR = exports.WASI_ENOTCONN = exports.WASI_ENOSYS = exports.WASI_ENOSPC = exports.WASI_ENOPROTOOPT = void 0, exports.RIGHTS_REGULAR_FILE_BASE = exports.RIGHTS_CHARACTER_DEVICE_INHERITING = exports.RIGHTS_CHARACTER_DEVICE_BASE = exports.RIGHTS_BLOCK_DEVICE_INHERITING = exports.RIGHTS_BLOCK_DEVICE_BASE = exports.RIGHTS_ALL = exports.WASI_RIGHT_SOCK_SHUTDOWN = exports.WASI_RIGHT_POLL_FD_READWRITE = exports.WASI_RIGHT_PATH_UNLINK_FILE = exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY = exports.WASI_RIGHT_PATH_SYMLINK = exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES = exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE = exports.WASI_RIGHT_FD_FILESTAT_GET = exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES = exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE = exports.WASI_RIGHT_PATH_FILESTAT_GET = exports.WASI_RIGHT_PATH_RENAME_TARGET = exports.WASI_RIGHT_PATH_RENAME_SOURCE = exports.WASI_RIGHT_PATH_READLINK = exports.WASI_RIGHT_FD_READDIR = exports.WASI_RIGHT_PATH_OPEN = exports.WASI_RIGHT_PATH_LINK_TARGET = exports.WASI_RIGHT_PATH_LINK_SOURCE = exports.WASI_RIGHT_PATH_CREATE_FILE = exports.WASI_RIGHT_PATH_CREATE_DIRECTORY = exports.WASI_RIGHT_FD_ALLOCATE = exports.WASI_RIGHT_FD_ADVISE = exports.WASI_RIGHT_FD_WRITE = exports.WASI_RIGHT_FD_TELL = exports.WASI_RIGHT_FD_SYNC = exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS = exports.WASI_RIGHT_FD_SEEK = exports.WASI_RIGHT_FD_READ = exports.WASI_RIGHT_FD_DATASYNC = exports.WASI_FDFLAG_SYNC = exports.WASI_FDFLAG_RSYNC = exports.WASI_FDFLAG_NONBLOCK = exports.WASI_FDFLAG_DSYNC = exports.WASI_FDFLAG_APPEND = exports.WASI_FILETYPE_SYMBOLIC_LINK = exports.WASI_FILETYPE_SOCKET_STREAM = exports.WASI_FILETYPE_SOCKET_DGRAM = exports.WASI_FILETYPE_REGULAR_FILE = exports.WASI_FILETYPE_DIRECTORY = exports.WASI_FILETYPE_CHARACTER_DEVICE = exports.WASI_FILETYPE_BLOCK_DEVICE = exports.WASI_FILETYPE_UNKNOWN = exports.WASI_SIGXFSZ = exports.WASI_SIGXCPU = void 0, exports.SIGNAL_MAP = exports.ERROR_MAP = exports.WASI_WHENCE_END = exports.WASI_WHENCE_CUR = exports.WASI_WHENCE_SET = exports.WASI_STDERR_FILENO = exports.WASI_STDOUT_FILENO = exports.WASI_STDIN_FILENO = exports.WASI_DIRCOOKIE_START = exports.WASI_PREOPENTYPE_DIR = exports.WASI_O_TRUNC = exports.WASI_O_EXCL = exports.WASI_O_DIRECTORY = exports.WASI_O_CREAT = exports.WASI_FILESTAT_SET_MTIM_NOW = exports.WASI_FILESTAT_SET_MTIM = exports.WASI_FILESTAT_SET_ATIM_NOW = exports.WASI_FILESTAT_SET_ATIM = exports.WASI_EVENTTYPE_FD_WRITE = exports.WASI_EVENTTYPE_FD_READ = exports.WASI_EVENTTYPE_CLOCK = exports.WASI_CLOCK_THREAD_CPUTIME_ID = exports.WASI_CLOCK_PROCESS_CPUTIME_ID = exports.WASI_CLOCK_MONOTONIC = exports.WASI_CLOCK_REALTIME = exports.RIGHTS_TTY_INHERITING = exports.RIGHTS_TTY_BASE = exports.RIGHTS_SOCKET_INHERITING = exports.RIGHTS_SOCKET_BASE = exports.RIGHTS_DIRECTORY_INHERITING = exports.RIGHTS_DIRECTORY_BASE = exports.RIGHTS_REGULAR_FILE_INHERITING = void 0, exports.WASI_ESUCCESS = 0, exports.WASI_E2BIG = 1, exports.WASI_EACCES = 2, exports.WASI_EADDRINUSE = 3, exports.WASI_EADDRNOTAVAIL = 4, exports.WASI_EAFNOSUPPORT = 5, exports.WASI_EAGAIN = 6, exports.WASI_EALREADY = 7, exports.WASI_EBADF = 8, exports.WASI_EBADMSG = 9, exports.WASI_EBUSY = 10, exports.WASI_ECANCELED = 11, exports.WASI_ECHILD = 12, exports.WASI_ECONNABORTED = 13, exports.WASI_ECONNREFUSED = 14, exports.WASI_ECONNRESET = 15, exports.WASI_EDEADLK = 16, exports.WASI_EDESTADDRREQ = 17, exports.WASI_EDOM = 18, exports.WASI_EDQUOT = 19, exports.WASI_EEXIST = 20, exports.WASI_EFAULT = 21, exports.WASI_EFBIG = 22, exports.WASI_EHOSTUNREACH = 23, exports.WASI_EIDRM = 24, exports.WASI_EILSEQ = 25, exports.WASI_EINPROGRESS = 26, exports.WASI_EINTR = 27, exports.WASI_EINVAL = 28, exports.WASI_EIO = 29, exports.WASI_EISCONN = 30, exports.WASI_EISDIR = 31, exports.WASI_ELOOP = 32, exports.WASI_EMFILE = 33, exports.WASI_EMLINK = 34, exports.WASI_EMSGSIZE = 35, exports.WASI_EMULTIHOP = 36, exports.WASI_ENAMETOOLONG = 37, exports.WASI_ENETDOWN = 38, exports.WASI_ENETRESET = 39, exports.WASI_ENETUNREACH = 40, exports.WASI_ENFILE = 41, exports.WASI_ENOBUFS = 42, exports.WASI_ENODEV = 43, exports.WASI_ENOENT = 44, exports.WASI_ENOEXEC = 45, exports.WASI_ENOLCK = 46, exports.WASI_ENOLINK = 47, exports.WASI_ENOMEM = 48, exports.WASI_ENOMSG = 49, exports.WASI_ENOPROTOOPT = 50, exports.WASI_ENOSPC = 51, exports.WASI_ENOSYS = 52, exports.WASI_ENOTCONN = 53, exports.WASI_ENOTDIR = 54, exports.WASI_ENOTEMPTY = 55, exports.WASI_ENOTRECOVERABLE = 56, exports.WASI_ENOTSOCK = 57, exports.WASI_ENOTSUP = 58, exports.WASI_ENOTTY = 59, exports.WASI_ENXIO = 60, exports.WASI_EOVERFLOW = 61, exports.WASI_EOWNERDEAD = 62, exports.WASI_EPERM = 63, exports.WASI_EPIPE = 64, exports.WASI_EPROTO = 65, exports.WASI_EPROTONOSUPPORT = 66, exports.WASI_EPROTOTYPE = 67, exports.WASI_ERANGE = 68, exports.WASI_EROFS = 69, exports.WASI_ESPIPE = 70, exports.WASI_ESRCH = 71, exports.WASI_ESTALE = 72, exports.WASI_ETIMEDOUT = 73, exports.WASI_ETXTBSY = 74, exports.WASI_EXDEV = 75, exports.WASI_ENOTCAPABLE = 76, exports.WASI_SIGABRT = 0, exports.WASI_SIGALRM = 1, exports.WASI_SIGBUS = 2, exports.WASI_SIGCHLD = 3, exports.WASI_SIGCONT = 4, exports.WASI_SIGFPE = 5, exports.WASI_SIGHUP = 6, exports.WASI_SIGILL = 7, exports.WASI_SIGINT = 8, exports.WASI_SIGKILL = 9, exports.WASI_SIGPIPE = 10, exports.WASI_SIGQUIT = 11, exports.WASI_SIGSEGV = 12, exports.WASI_SIGSTOP = 13, exports.WASI_SIGTERM = 14, exports.WASI_SIGTRAP = 15, exports.WASI_SIGTSTP = 16, exports.WASI_SIGTTIN = 17, exports.WASI_SIGTTOU = 18, exports.WASI_SIGURG = 19, exports.WASI_SIGUSR1 = 20, exports.WASI_SIGUSR2 = 21, exports.WASI_SIGVTALRM = 22, exports.WASI_SIGXCPU = 23, exports.WASI_SIGXFSZ = 24, exports.WASI_FILETYPE_UNKNOWN = 0, exports.WASI_FILETYPE_BLOCK_DEVICE = 1, exports.WASI_FILETYPE_CHARACTER_DEVICE = 2, exports.WASI_FILETYPE_DIRECTORY = 3, exports.WASI_FILETYPE_REGULAR_FILE = 4, exports.WASI_FILETYPE_SOCKET_DGRAM = 5, exports.WASI_FILETYPE_SOCKET_STREAM = 6, exports.WASI_FILETYPE_SYMBOLIC_LINK = 7, exports.WASI_FDFLAG_APPEND = 1, exports.WASI_FDFLAG_DSYNC = 2, exports.WASI_FDFLAG_NONBLOCK = 4, exports.WASI_FDFLAG_RSYNC = 8, exports.WASI_FDFLAG_SYNC = 16, exports.WASI_RIGHT_FD_DATASYNC = BigInt(1), exports.WASI_RIGHT_FD_READ = BigInt(2), exports.WASI_RIGHT_FD_SEEK = BigInt(4), exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS = BigInt(8), exports.WASI_RIGHT_FD_SYNC = BigInt(16), exports.WASI_RIGHT_FD_TELL = BigInt(32), exports.WASI_RIGHT_FD_WRITE = BigInt(64), exports.WASI_RIGHT_FD_ADVISE = BigInt(128), exports.WASI_RIGHT_FD_ALLOCATE = BigInt(256), exports.WASI_RIGHT_PATH_CREATE_DIRECTORY = BigInt(512), exports.WASI_RIGHT_PATH_CREATE_FILE = BigInt(1024), exports.WASI_RIGHT_PATH_LINK_SOURCE = BigInt(2048), exports.WASI_RIGHT_PATH_LINK_TARGET = BigInt(4096), exports.WASI_RIGHT_PATH_OPEN = BigInt(8192), exports.WASI_RIGHT_FD_READDIR = BigInt(16384), exports.WASI_RIGHT_PATH_READLINK = BigInt(32768), exports.WASI_RIGHT_PATH_RENAME_SOURCE = BigInt(65536), exports.WASI_RIGHT_PATH_RENAME_TARGET = BigInt(131072), exports.WASI_RIGHT_PATH_FILESTAT_GET = BigInt(262144), exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE = BigInt(524288), exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES = BigInt(1048576), exports.WASI_RIGHT_FD_FILESTAT_GET = BigInt(2097152), exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE = BigInt(4194304), exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES = BigInt(8388608), exports.WASI_RIGHT_PATH_SYMLINK = BigInt(16777216), exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY = BigInt(33554432), exports.WASI_RIGHT_PATH_UNLINK_FILE = BigInt(67108864), exports.WASI_RIGHT_POLL_FD_READWRITE = BigInt(134217728), exports.WASI_RIGHT_SOCK_SHUTDOWN = BigInt(268435456), exports.RIGHTS_ALL = exports.WASI_RIGHT_FD_DATASYNC | exports.WASI_RIGHT_FD_READ | exports.WASI_RIGHT_FD_SEEK | exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS | exports.WASI_RIGHT_FD_SYNC | exports.WASI_RIGHT_FD_TELL | exports.WASI_RIGHT_FD_WRITE | exports.WASI_RIGHT_FD_ADVISE | exports.WASI_RIGHT_FD_ALLOCATE | exports.WASI_RIGHT_PATH_CREATE_DIRECTORY | exports.WASI_RIGHT_PATH_CREATE_FILE | exports.WASI_RIGHT_PATH_LINK_SOURCE | exports.WASI_RIGHT_PATH_LINK_TARGET | exports.WASI_RIGHT_PATH_OPEN | exports.WASI_RIGHT_FD_READDIR | exports.WASI_RIGHT_PATH_READLINK | exports.WASI_RIGHT_PATH_RENAME_SOURCE | exports.WASI_RIGHT_PATH_RENAME_TARGET | exports.WASI_RIGHT_PATH_FILESTAT_GET | exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE | exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES | exports.WASI_RIGHT_FD_FILESTAT_GET | exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES | exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE | exports.WASI_RIGHT_PATH_SYMLINK | exports.WASI_RIGHT_PATH_UNLINK_FILE | exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY | exports.WASI_RIGHT_POLL_FD_READWRITE | exports.WASI_RIGHT_SOCK_SHUTDOWN, exports.RIGHTS_BLOCK_DEVICE_BASE = exports.RIGHTS_ALL, exports.RIGHTS_BLOCK_DEVICE_INHERITING = exports.RIGHTS_ALL, exports.RIGHTS_CHARACTER_DEVICE_BASE = exports.RIGHTS_ALL, exports.RIGHTS_CHARACTER_DEVICE_INHERITING = exports.RIGHTS_ALL, exports.RIGHTS_REGULAR_FILE_BASE = exports.WASI_RIGHT_FD_DATASYNC | exports.WASI_RIGHT_FD_READ | exports.WASI_RIGHT_FD_SEEK | exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS | exports.WASI_RIGHT_FD_SYNC | exports.WASI_RIGHT_FD_TELL | exports.WASI_RIGHT_FD_WRITE | exports.WASI_RIGHT_FD_ADVISE | exports.WASI_RIGHT_FD_ALLOCATE | exports.WASI_RIGHT_FD_FILESTAT_GET | exports.WASI_RIGHT_FD_FILESTAT_SET_SIZE | exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES | exports.WASI_RIGHT_POLL_FD_READWRITE, exports.RIGHTS_REGULAR_FILE_INHERITING = BigInt(0), exports.RIGHTS_DIRECTORY_BASE = exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS | exports.WASI_RIGHT_FD_SYNC | exports.WASI_RIGHT_FD_ADVISE | exports.WASI_RIGHT_PATH_CREATE_DIRECTORY | exports.WASI_RIGHT_PATH_CREATE_FILE | exports.WASI_RIGHT_PATH_LINK_SOURCE | exports.WASI_RIGHT_PATH_LINK_TARGET | exports.WASI_RIGHT_PATH_OPEN | exports.WASI_RIGHT_FD_READDIR | exports.WASI_RIGHT_PATH_READLINK | exports.WASI_RIGHT_PATH_RENAME_SOURCE | exports.WASI_RIGHT_PATH_RENAME_TARGET | exports.WASI_RIGHT_PATH_FILESTAT_GET | exports.WASI_RIGHT_PATH_FILESTAT_SET_SIZE | exports.WASI_RIGHT_PATH_FILESTAT_SET_TIMES | exports.WASI_RIGHT_FD_FILESTAT_GET | exports.WASI_RIGHT_FD_FILESTAT_SET_TIMES | exports.WASI_RIGHT_PATH_SYMLINK | exports.WASI_RIGHT_PATH_UNLINK_FILE | exports.WASI_RIGHT_PATH_REMOVE_DIRECTORY | exports.WASI_RIGHT_POLL_FD_READWRITE, exports.RIGHTS_DIRECTORY_INHERITING = exports.RIGHTS_DIRECTORY_BASE | exports.RIGHTS_REGULAR_FILE_BASE, exports.RIGHTS_SOCKET_BASE = exports.WASI_RIGHT_FD_READ | exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS | exports.WASI_RIGHT_FD_WRITE | exports.WASI_RIGHT_FD_FILESTAT_GET | exports.WASI_RIGHT_POLL_FD_READWRITE | exports.WASI_RIGHT_SOCK_SHUTDOWN, exports.RIGHTS_SOCKET_INHERITING = exports.RIGHTS_ALL, exports.RIGHTS_TTY_BASE = exports.WASI_RIGHT_FD_READ | exports.WASI_RIGHT_FD_FDSTAT_SET_FLAGS | exports.WASI_RIGHT_FD_WRITE | exports.WASI_RIGHT_FD_FILESTAT_GET | exports.WASI_RIGHT_POLL_FD_READWRITE, exports.RIGHTS_TTY_INHERITING = BigInt(0), exports.WASI_CLOCK_REALTIME = 0, exports.WASI_CLOCK_MONOTONIC = 1, exports.WASI_CLOCK_PROCESS_CPUTIME_ID = 2, exports.WASI_CLOCK_THREAD_CPUTIME_ID = 3, exports.WASI_EVENTTYPE_CLOCK = 0, exports.WASI_EVENTTYPE_FD_READ = 1, exports.WASI_EVENTTYPE_FD_WRITE = 2, exports.WASI_FILESTAT_SET_ATIM = 1 << 0, exports.WASI_FILESTAT_SET_ATIM_NOW = 1 << 1, exports.WASI_FILESTAT_SET_MTIM = 1 << 2, exports.WASI_FILESTAT_SET_MTIM_NOW = 1 << 3, exports.WASI_O_CREAT = 1 << 0, exports.WASI_O_DIRECTORY = 1 << 1, exports.WASI_O_EXCL = 1 << 2, exports.WASI_O_TRUNC = 1 << 3, exports.WASI_PREOPENTYPE_DIR = 0, exports.WASI_DIRCOOKIE_START = 0, exports.WASI_STDIN_FILENO = 0, exports.WASI_STDOUT_FILENO = 1, exports.WASI_STDERR_FILENO = 2, exports.WASI_WHENCE_SET = 0, exports.WASI_WHENCE_CUR = 1, exports.WASI_WHENCE_END = 2, exports.ERROR_MAP = { - E2BIG: exports.WASI_E2BIG, - EACCES: exports.WASI_EACCES, - EADDRINUSE: exports.WASI_EADDRINUSE, - EADDRNOTAVAIL: exports.WASI_EADDRNOTAVAIL, - EAFNOSUPPORT: exports.WASI_EAFNOSUPPORT, - EALREADY: exports.WASI_EALREADY, - EAGAIN: exports.WASI_EAGAIN, - EBADF: exports.WASI_EBADF, - EBADMSG: exports.WASI_EBADMSG, - EBUSY: exports.WASI_EBUSY, - ECANCELED: exports.WASI_ECANCELED, - ECHILD: exports.WASI_ECHILD, - ECONNABORTED: exports.WASI_ECONNABORTED, - ECONNREFUSED: exports.WASI_ECONNREFUSED, - ECONNRESET: exports.WASI_ECONNRESET, - EDEADLOCK: exports.WASI_EDEADLK, - EDESTADDRREQ: exports.WASI_EDESTADDRREQ, - EDOM: exports.WASI_EDOM, - EDQUOT: exports.WASI_EDQUOT, - EEXIST: exports.WASI_EEXIST, - EFAULT: exports.WASI_EFAULT, - EFBIG: exports.WASI_EFBIG, - EHOSTDOWN: exports.WASI_EHOSTUNREACH, - EHOSTUNREACH: exports.WASI_EHOSTUNREACH, - EIDRM: exports.WASI_EIDRM, - EILSEQ: exports.WASI_EILSEQ, - EINPROGRESS: exports.WASI_EINPROGRESS, - EINTR: exports.WASI_EINTR, - EINVAL: exports.WASI_EINVAL, - EIO: exports.WASI_EIO, - EISCONN: exports.WASI_EISCONN, - EISDIR: exports.WASI_EISDIR, - ELOOP: exports.WASI_ELOOP, - EMFILE: exports.WASI_EMFILE, - EMLINK: exports.WASI_EMLINK, - EMSGSIZE: exports.WASI_EMSGSIZE, - EMULTIHOP: exports.WASI_EMULTIHOP, - ENAMETOOLONG: exports.WASI_ENAMETOOLONG, - ENETDOWN: exports.WASI_ENETDOWN, - ENETRESET: exports.WASI_ENETRESET, - ENETUNREACH: exports.WASI_ENETUNREACH, - ENFILE: exports.WASI_ENFILE, - ENOBUFS: exports.WASI_ENOBUFS, - ENODEV: exports.WASI_ENODEV, - ENOENT: exports.WASI_ENOENT, - ENOEXEC: exports.WASI_ENOEXEC, - ENOLCK: exports.WASI_ENOLCK, - ENOLINK: exports.WASI_ENOLINK, - ENOMEM: exports.WASI_ENOMEM, - ENOMSG: exports.WASI_ENOMSG, - ENOPROTOOPT: exports.WASI_ENOPROTOOPT, - ENOSPC: exports.WASI_ENOSPC, - ENOSYS: exports.WASI_ENOSYS, - ENOTCONN: exports.WASI_ENOTCONN, - ENOTDIR: exports.WASI_ENOTDIR, - ENOTEMPTY: exports.WASI_ENOTEMPTY, - ENOTRECOVERABLE: exports.WASI_ENOTRECOVERABLE, - ENOTSOCK: exports.WASI_ENOTSOCK, - ENOTTY: exports.WASI_ENOTTY, - ENXIO: exports.WASI_ENXIO, - EOVERFLOW: exports.WASI_EOVERFLOW, - EOWNERDEAD: exports.WASI_EOWNERDEAD, - EPERM: exports.WASI_EPERM, - EPIPE: exports.WASI_EPIPE, - EPROTO: exports.WASI_EPROTO, - EPROTONOSUPPORT: exports.WASI_EPROTONOSUPPORT, - EPROTOTYPE: exports.WASI_EPROTOTYPE, - ERANGE: exports.WASI_ERANGE, - EROFS: exports.WASI_EROFS, - ESPIPE: exports.WASI_ESPIPE, - ESRCH: exports.WASI_ESRCH, - ESTALE: exports.WASI_ESTALE, - ETIMEDOUT: exports.WASI_ETIMEDOUT, - ETXTBSY: exports.WASI_ETXTBSY, - EXDEV: exports.WASI_EXDEV - }, exports.SIGNAL_MAP = { - [exports.WASI_SIGHUP]: "SIGHUP", - [exports.WASI_SIGINT]: "SIGINT", - [exports.WASI_SIGQUIT]: "SIGQUIT", - [exports.WASI_SIGILL]: "SIGILL", - [exports.WASI_SIGTRAP]: "SIGTRAP", - [exports.WASI_SIGABRT]: "SIGABRT", - [exports.WASI_SIGBUS]: "SIGBUS", - [exports.WASI_SIGFPE]: "SIGFPE", - [exports.WASI_SIGKILL]: "SIGKILL", - [exports.WASI_SIGUSR1]: "SIGUSR1", - [exports.WASI_SIGSEGV]: "SIGSEGV", - [exports.WASI_SIGUSR2]: "SIGUSR2", - [exports.WASI_SIGPIPE]: "SIGPIPE", - [exports.WASI_SIGALRM]: "SIGALRM", - [exports.WASI_SIGTERM]: "SIGTERM", - [exports.WASI_SIGCHLD]: "SIGCHLD", - [exports.WASI_SIGCONT]: "SIGCONT", - [exports.WASI_SIGSTOP]: "SIGSTOP", - [exports.WASI_SIGTSTP]: "SIGTSTP", - [exports.WASI_SIGTTIN]: "SIGTTIN", - [exports.WASI_SIGTTOU]: "SIGTTOU", - [exports.WASI_SIGURG]: "SIGURG", - [exports.WASI_SIGXCPU]: "SIGXCPU", - [exports.WASI_SIGXFSZ]: "SIGXFSZ", - [exports.WASI_SIGVTALRM]: "SIGVTALRM" - }; - } -}), require_wasi = __commonJS({ - "node_modules/wasi-js/dist/wasi.js"(exports) { - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { default: mod }; - }; - let fs; - Object.defineProperty(exports, "__esModule", { value: !0 }), exports.SOCKET_DEFAULT_RIGHTS = void 0; - var log = () => { - }, logOpen = () => { - }, SC_OPEN_MAX = 32768, types_1 = require_types(), constants_1 = require_constants(), STDIN_DEFAULT_RIGHTS = constants_1.WASI_RIGHT_FD_DATASYNC | constants_1.WASI_RIGHT_FD_READ | constants_1.WASI_RIGHT_FD_SYNC | constants_1.WASI_RIGHT_FD_ADVISE | constants_1.WASI_RIGHT_FD_FILESTAT_GET | constants_1.WASI_RIGHT_POLL_FD_READWRITE, STDOUT_DEFAULT_RIGHTS = constants_1.WASI_RIGHT_FD_DATASYNC | constants_1.WASI_RIGHT_FD_WRITE | constants_1.WASI_RIGHT_FD_SYNC | constants_1.WASI_RIGHT_FD_ADVISE | constants_1.WASI_RIGHT_FD_FILESTAT_GET | constants_1.WASI_RIGHT_POLL_FD_READWRITE, STDERR_DEFAULT_RIGHTS = STDOUT_DEFAULT_RIGHTS; - exports.SOCKET_DEFAULT_RIGHTS = constants_1.WASI_RIGHT_FD_DATASYNC | constants_1.WASI_RIGHT_FD_READ | constants_1.WASI_RIGHT_FD_WRITE | constants_1.WASI_RIGHT_FD_ADVISE | constants_1.WASI_RIGHT_FD_FILESTAT_GET | constants_1.WASI_RIGHT_POLL_FD_READWRITE | constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS; - var msToNs = (ms) => { - const msInt = Math.trunc(ms), decimal = BigInt(Math.round((ms - msInt) * 1e6)); - return BigInt(msInt) * BigInt(1e6) + decimal; - }, nsToMs = (ns) => { - if (typeof ns === "number") - ns = Math.trunc(ns); - const nsInt = BigInt(ns); - return Number(nsInt / BigInt(1e6)); - }, wrap = (f) => (...args) => { - try { - return f(...args); - } catch (err) { - let e = err; - while (e.prev != null) - e = e.prev; - if (e?.code && typeof e?.code === "string") - return constants_1.ERROR_MAP[e.code] || constants_1.WASI_EINVAL; - if (e instanceof types_1.WASIError) - return e.errno; - throw e; - } - }, stat = (wasi, fd) => { - const entry = wasi.FD_MAP.get(fd); - if (!entry) - throw new types_1.WASIError(constants_1.WASI_EBADF); - if (entry.filetype === void 0) { - const stats = wasi.fstatSync(entry.real), { filetype, rightsBase, rightsInheriting } = translateFileAttributes(wasi, fd, stats); - if (entry.filetype = filetype, !entry.rights) - entry.rights = { - base: rightsBase, - inheriting: rightsInheriting - }; - } - return entry; - }, translateFileAttributes = (wasi, fd, stats) => { - switch (!0) { - case stats.isBlockDevice(): - return { - filetype: constants_1.WASI_FILETYPE_BLOCK_DEVICE, - rightsBase: constants_1.RIGHTS_BLOCK_DEVICE_BASE, - rightsInheriting: constants_1.RIGHTS_BLOCK_DEVICE_INHERITING - }; - case stats.isCharacterDevice(): { - const filetype = constants_1.WASI_FILETYPE_CHARACTER_DEVICE; - if (fd !== void 0 && wasi.bindings.isTTY(fd)) - return { - filetype, - rightsBase: constants_1.RIGHTS_TTY_BASE, - rightsInheriting: constants_1.RIGHTS_TTY_INHERITING - }; - return { - filetype, - rightsBase: constants_1.RIGHTS_CHARACTER_DEVICE_BASE, - rightsInheriting: constants_1.RIGHTS_CHARACTER_DEVICE_INHERITING - }; - } - case stats.isDirectory(): - return { - filetype: constants_1.WASI_FILETYPE_DIRECTORY, - rightsBase: constants_1.RIGHTS_DIRECTORY_BASE, - rightsInheriting: constants_1.RIGHTS_DIRECTORY_INHERITING - }; - case stats.isFIFO(): - return { - filetype: constants_1.WASI_FILETYPE_SOCKET_STREAM, - rightsBase: constants_1.RIGHTS_SOCKET_BASE, - rightsInheriting: constants_1.RIGHTS_SOCKET_INHERITING - }; - case stats.isFile(): - return { - filetype: constants_1.WASI_FILETYPE_REGULAR_FILE, - rightsBase: constants_1.RIGHTS_REGULAR_FILE_BASE, - rightsInheriting: constants_1.RIGHTS_REGULAR_FILE_INHERITING - }; - case stats.isSocket(): - return { - filetype: constants_1.WASI_FILETYPE_SOCKET_STREAM, - rightsBase: constants_1.RIGHTS_SOCKET_BASE, - rightsInheriting: constants_1.RIGHTS_SOCKET_INHERITING - }; - case stats.isSymbolicLink(): - return { - filetype: constants_1.WASI_FILETYPE_SYMBOLIC_LINK, - rightsBase: BigInt(0), - rightsInheriting: BigInt(0) - }; - default: - return { - filetype: constants_1.WASI_FILETYPE_UNKNOWN, - rightsBase: BigInt(0), - rightsInheriting: BigInt(0) - }; - } - }, warnedAboutSleep = !1, defaultConfig; - function getDefaults() { - if (defaultConfig) - return defaultConfig; - const defaultBindings = { - hrtime: () => process.hrtime.bigint(), - exit: (code) => { - process.exit(code); - }, - kill: (signal) => { - process.kill(process.pid, signal); - }, - randomFillSync: (array) => crypto.getRandomValues(array), - isTTY: (fd) => import.meta.require("node:tty").isatty(fd), - fs: Bun.fs(), - path: import.meta.require("node:path") - }; - return defaultConfig = { - args: [], - env: {}, - preopens: {}, - bindings: defaultBindings, - sleep: (ms) => { - Bun.sleepSync(ms); - } - }; - } - var WASI = class WASI2 { - constructor(wasiConfig = {}) { - const defaultConfig2 = getDefaults(); - this.lastStdin = 0, this.sleep = wasiConfig.sleep || defaultConfig2.sleep, this.getStdin = wasiConfig.getStdin, this.sendStdout = wasiConfig.sendStdout, this.sendStderr = wasiConfig.sendStderr; - let preopens = wasiConfig.preopens ?? defaultConfig2.preopens; - this.env = wasiConfig.env ?? defaultConfig2.env; - const args = wasiConfig.args ?? defaultConfig2.args; - this.memory = void 0, this.view = void 0, this.bindings = wasiConfig.bindings || defaultConfig2.bindings; - const bindings2 = this.bindings; - fs = bindings2.fs, this.FD_MAP = new Map([ - [ - constants_1.WASI_STDIN_FILENO, - { - real: 0, - filetype: constants_1.WASI_FILETYPE_CHARACTER_DEVICE, - rights: { - base: STDIN_DEFAULT_RIGHTS, - inheriting: BigInt(0) - }, - path: "/dev/stdin" - } - ], - [ - constants_1.WASI_STDOUT_FILENO, - { - real: 1, - filetype: constants_1.WASI_FILETYPE_CHARACTER_DEVICE, - rights: { - base: STDOUT_DEFAULT_RIGHTS, - inheriting: BigInt(0) - }, - path: "/dev/stdout" - } - ], - [ - constants_1.WASI_STDERR_FILENO, - { - real: 2, - filetype: constants_1.WASI_FILETYPE_CHARACTER_DEVICE, - rights: { - base: STDERR_DEFAULT_RIGHTS, - inheriting: BigInt(0) - }, - path: "/dev/stderr" - } - ] - ]); - const path = bindings2.path; - for (let [k, v] of Object.entries(preopens)) { - const real = fs.openSync(v, nodeFsConstants.O_RDONLY), newfd = this.getUnusedFileDescriptor(); - this.FD_MAP.set(newfd, { - real, - filetype: constants_1.WASI_FILETYPE_DIRECTORY, - rights: { - base: constants_1.RIGHTS_DIRECTORY_BASE, - inheriting: constants_1.RIGHTS_DIRECTORY_INHERITING - }, - fakePath: k, - path: v - }); - } - const getiovs = (iovs, iovsLen) => { - this.refreshMemory(); - const { view, memory } = this, { buffer } = memory, { byteLength } = buffer; - if (iovsLen === 1) { - const ptr = iovs, buf = view.getUint32(ptr, !0); - let bufLen = view.getUint32(ptr + 4, !0); - if (bufLen > byteLength - buf) - console.log({ - buf, - bufLen, - total_memory: byteLength - }), log("getiovs: warning -- truncating buffer to fit in memory"), bufLen = Math.min(bufLen, Math.max(0, byteLength - buf)); - try { - return [new Uint8Array(buffer, buf, bufLen)]; - } catch (err) { - throw console.warn("WASI.getiovs -- invalid buffer", err), new types_1.WASIError(constants_1.WASI_EINVAL); - } - } - const buffers = []; - buffers.length = iovsLen; - for (let i = 0, ptr = iovs;i < iovsLen; i++, ptr += 8) { - const buf = view.getUint32(ptr, !0); - let bufLen = view.getUint32(ptr + 4, !0); - if (bufLen > byteLength - buf) - console.log({ - buf, - bufLen, - total_memory: byteLength - }), log("getiovs: warning -- truncating buffer to fit in memory"), bufLen = Math.min(bufLen, Math.max(0, byteLength - buf)); - try { - buffers[i] = new Uint8Array(buffer, buf, bufLen); - } catch (err) { - throw console.warn("WASI.getiovs -- invalid buffer", err), new types_1.WASIError(constants_1.WASI_EINVAL); - } - } - return buffers; - }, CHECK_FD = (fd, rights) => { - const stats = stat(this, fd); - if (rights !== BigInt(0) && (stats.rights.base & rights) === BigInt(0)) - throw new types_1.WASIError(constants_1.WASI_EPERM); - return stats; - }, CPUTIME_START = Bun.nanoseconds(), timeOrigin = Math.trunc(performance.timeOrigin * 1e6), now = (clockId) => { - switch (clockId) { - case constants_1.WASI_CLOCK_MONOTONIC: - return Bun.nanoseconds(); - case constants_1.WASI_CLOCK_REALTIME: - return Bun.nanoseconds() + timeOrigin; - case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID: - case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID: - return Bun.nanoseconds() - CPUTIME_START; - default: - return null; - } - }; - if (this.wasiImport = { - args_get: (argv, argvBuf) => { - this.refreshMemory(); - let coffset = argv, offset = argvBuf; - return args.forEach((a) => { - this.view.setUint32(coffset, offset, !0), coffset += 4, offset += Buffer.from(this.memory.buffer).write(`${a}\0`, offset); - }), constants_1.WASI_ESUCCESS; - }, - args_sizes_get: (argc, argvBufSize) => { - this.refreshMemory(), this.view.setUint32(argc, args.length, !0); - const size = args.reduce((acc, a) => acc + Buffer.byteLength(a) + 1, 0); - return this.view.setUint32(argvBufSize, size, !0), constants_1.WASI_ESUCCESS; - }, - environ_get: (environ, environBuf) => { - this.refreshMemory(); - let coffset = environ, offset = environBuf; - return Object.entries(this.env).forEach(([key, value]) => { - this.view.setUint32(coffset, offset, !0), coffset += 4, offset += Buffer.from(this.memory.buffer).write(`${key}=${value}\0`, offset); - }), constants_1.WASI_ESUCCESS; - }, - environ_sizes_get: (environCount, environBufSize) => { - this.refreshMemory(); - const envProcessed = Object.entries(this.env).map(([key, value]) => `${key}=${value}\0`), size = envProcessed.reduce((acc, e) => acc + Buffer.byteLength(e), 0); - return this.view.setUint32(environCount, envProcessed.length, !0), this.view.setUint32(environBufSize, size, !0), constants_1.WASI_ESUCCESS; - }, - clock_res_get: (clockId, resolution) => { - let res; - switch (clockId) { - case constants_1.WASI_CLOCK_MONOTONIC: - case constants_1.WASI_CLOCK_PROCESS_CPUTIME_ID: - case constants_1.WASI_CLOCK_THREAD_CPUTIME_ID: { - res = BigInt(1); - break; - } - case constants_1.WASI_CLOCK_REALTIME: { - res = BigInt(1000); - break; - } - } - if (!res) - throw Error("invalid clockId"); - return this.view.setBigUint64(resolution, res), constants_1.WASI_ESUCCESS; - }, - clock_time_get: (clockId, _precision, time) => { - this.refreshMemory(); - const n = now(clockId); - if (n === null) - return constants_1.WASI_EINVAL; - return this.view.setBigUint64(time, BigInt(n), !0), constants_1.WASI_ESUCCESS; - }, - fd_advise: wrap((fd, _offset, _len, _advice) => { - return CHECK_FD(fd, constants_1.WASI_RIGHT_FD_ADVISE), constants_1.WASI_ENOSYS; - }), - fd_allocate: wrap((fd, _offset, _len) => { - return CHECK_FD(fd, constants_1.WASI_RIGHT_FD_ALLOCATE), constants_1.WASI_ENOSYS; - }), - fd_close: wrap((fd) => { - const stats = CHECK_FD(fd, BigInt(0)); - return fs.closeSync(stats.real), this.FD_MAP.delete(fd), constants_1.WASI_ESUCCESS; - }), - fd_datasync: wrap((fd) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_DATASYNC); - return fs.fdatasyncSync(stats.real), constants_1.WASI_ESUCCESS; - }), - fd_fdstat_get: wrap((fd, bufPtr) => { - const stats = CHECK_FD(fd, BigInt(0)); - if (this.refreshMemory(), stats.filetype == null) - throw Error("stats.filetype must be set"); - return this.view.setUint8(bufPtr, stats.filetype), this.view.setUint16(bufPtr + 2, 0, !0), this.view.setUint16(bufPtr + 4, 0, !0), this.view.setBigUint64(bufPtr + 8, BigInt(stats.rights.base), !0), this.view.setBigUint64(bufPtr + 8 + 8, BigInt(stats.rights.inheriting), !0), constants_1.WASI_ESUCCESS; - }), - fd_fdstat_set_flags: wrap((fd, flags) => { - if (CHECK_FD(fd, constants_1.WASI_RIGHT_FD_FDSTAT_SET_FLAGS), this.wasiImport.sock_fcntlSetFlags(fd, flags) == 0) - return constants_1.WASI_ESUCCESS; - return constants_1.WASI_ENOSYS; - }), - fd_fdstat_set_rights: wrap((fd, fsRightsBase, fsRightsInheriting) => { - const stats = CHECK_FD(fd, BigInt(0)); - if ((stats.rights.base | fsRightsBase) > stats.rights.base) - return constants_1.WASI_EPERM; - if ((stats.rights.inheriting | fsRightsInheriting) > stats.rights.inheriting) - return constants_1.WASI_EPERM; - return stats.rights.base = fsRightsBase, stats.rights.inheriting = fsRightsInheriting, constants_1.WASI_ESUCCESS; - }), - fd_filestat_get: wrap((fd, bufPtr) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_FILESTAT_GET), rstats = this.fstatSync(stats.real); - if (this.refreshMemory(), this.view.setBigUint64(bufPtr, BigInt(rstats.dev), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.ino), !0), bufPtr += 8, stats.filetype == null) - throw Error("stats.filetype must be set"); - return this.view.setUint8(bufPtr, stats.filetype), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.nlink), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.size), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, msToNs(rstats.atimeMs), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, msToNs(rstats.mtimeMs), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, msToNs(rstats.ctimeMs), !0), constants_1.WASI_ESUCCESS; - }), - fd_filestat_set_size: wrap((fd, stSize) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE); - return fs.ftruncateSync(stats.real, Number(stSize)), constants_1.WASI_ESUCCESS; - }), - fd_filestat_set_times: wrap((fd, stAtim, stMtim, fstflags) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_FILESTAT_SET_TIMES), rstats = this.fstatSync(stats.real); - let { atime: atim, mtime: mtim } = rstats; - const n = nsToMs(now(constants_1.WASI_CLOCK_REALTIME)), atimflags = constants_1.WASI_FILESTAT_SET_ATIM | constants_1.WASI_FILESTAT_SET_ATIM_NOW; - if ((fstflags & atimflags) === atimflags) - return constants_1.WASI_EINVAL; - const mtimflags = constants_1.WASI_FILESTAT_SET_MTIM | constants_1.WASI_FILESTAT_SET_MTIM_NOW; - if ((fstflags & mtimflags) === mtimflags) - return constants_1.WASI_EINVAL; - if ((fstflags & constants_1.WASI_FILESTAT_SET_ATIM) === constants_1.WASI_FILESTAT_SET_ATIM) - atim = nsToMs(stAtim); - else if ((fstflags & constants_1.WASI_FILESTAT_SET_ATIM_NOW) === constants_1.WASI_FILESTAT_SET_ATIM_NOW) - atim = n; - if ((fstflags & constants_1.WASI_FILESTAT_SET_MTIM) === constants_1.WASI_FILESTAT_SET_MTIM) - mtim = nsToMs(stMtim); - else if ((fstflags & constants_1.WASI_FILESTAT_SET_MTIM_NOW) === constants_1.WASI_FILESTAT_SET_MTIM_NOW) - mtim = n; - return fs.futimesSync(stats.real, new Date(atim), new Date(mtim)), constants_1.WASI_ESUCCESS; - }), - fd_prestat_get: wrap((fd, bufPtr) => { - const stats = CHECK_FD(fd, BigInt(0)); - return this.refreshMemory(), this.view.setUint8(bufPtr, constants_1.WASI_PREOPENTYPE_DIR), this.view.setUint32(bufPtr + 4, Buffer.byteLength(stats.fakePath ?? stats.path ?? ""), !0), constants_1.WASI_ESUCCESS; - }), - fd_prestat_dir_name: wrap((fd, pathPtr, pathLen) => { - const stats = CHECK_FD(fd, BigInt(0)); - return this.refreshMemory(), Buffer.from(this.memory.buffer).write(stats.fakePath ?? stats.path ?? "", pathPtr, pathLen, "utf8"), constants_1.WASI_ESUCCESS; - }), - fd_pwrite: wrap((fd, iovs, iovsLen, offset, nwritten) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_WRITE | constants_1.WASI_RIGHT_FD_SEEK); - let written = 0; - return getiovs(iovs, iovsLen).forEach((iov) => { - let w = 0; - while (w < iov.byteLength) - w += fs.writeSync(stats.real, iov, w, iov.byteLength - w, Number(offset) + written + w); - written += w; - }), this.view.setUint32(nwritten, written, !0), constants_1.WASI_ESUCCESS; - }), - fd_write: wrap((fd, iovs, iovsLen, nwritten) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_WRITE), IS_STDOUT = fd == constants_1.WASI_STDOUT_FILENO, IS_STDERR = fd == constants_1.WASI_STDERR_FILENO; - let written = 0; - return getiovs(iovs, iovsLen).forEach((iov) => { - if (iov.byteLength == 0) - return; - if (IS_STDOUT && this.sendStdout != null) - this.sendStdout(iov), written += iov.byteLength; - else if (IS_STDERR && this.sendStderr != null) - this.sendStderr(iov), written += iov.byteLength; - else { - let w = 0; - while (w < iov.byteLength) { - const i = fs.writeSync(stats.real, iov, w, iov.byteLength - w, stats.offset ? Number(stats.offset) : null); - if (stats.offset) - stats.offset += BigInt(i); - w += i; - } - written += w; - } - }), this.view.setUint32(nwritten, written, !0), constants_1.WASI_ESUCCESS; - }), - fd_pread: wrap((fd, iovs, iovsLen, offset, nread) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_READ | constants_1.WASI_RIGHT_FD_SEEK); - let read = 0; - outer: - for (let iov of getiovs(iovs, iovsLen)) { - let r = 0; - while (r < iov.byteLength) { - const length = iov.byteLength - r, rr = fs.readSync(stats.real, iov, r, iov.byteLength - r, Number(offset) + read + r); - if (r += rr, read += rr, rr === 0 || rr < length) - break outer; - } - read += r; - } - return this.view.setUint32(nread, read, !0), constants_1.WASI_ESUCCESS; - }), - fd_read: wrap((fd, iovs, iovsLen, nread) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_READ), IS_STDIN = fd == constants_1.WASI_STDIN_FILENO; - let read = 0; - outer: - for (let iov of getiovs(iovs, iovsLen)) { - let r = 0; - while (r < iov.byteLength) { - let length = iov.byteLength - r, position = IS_STDIN || stats.offset === void 0 ? null : Number(stats.offset), rr = 0; - if (IS_STDIN) - if (this.getStdin != null) { - if (this.stdinBuffer == null) - this.stdinBuffer = this.getStdin(); - if (this.stdinBuffer != null) { - if (rr = this.stdinBuffer.copy(iov), rr == this.stdinBuffer.length) - this.stdinBuffer = void 0; - else - this.stdinBuffer = this.stdinBuffer.slice(rr); - if (rr > 0) - this.lastStdin = (new Date()).valueOf(); - } - } else { - if (this.sleep == null && !warnedAboutSleep) - warnedAboutSleep = !0, console.log("(cpu waiting for stdin: please define a way to sleep!) "); - try { - rr = fs.readSync(stats.real, iov, r, length, position); - } catch (_err) { - } - if (rr == 0) - this.shortPause(); - else - this.lastStdin = (new Date()).valueOf(); - } - else - rr = fs.readSync(stats.real, iov, r, length, position); - if (stats.filetype == constants_1.WASI_FILETYPE_REGULAR_FILE) - stats.offset = (stats.offset ? stats.offset : BigInt(0)) + BigInt(rr); - if (r += rr, read += rr, rr === 0 || rr < length) - break outer; - } - } - return this.view.setUint32(nread, read, !0), constants_1.WASI_ESUCCESS; - }), - fd_readdir: wrap((fd, bufPtr, bufLen, cookie, bufusedPtr) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_READDIR); - this.refreshMemory(); - const entries = fs.readdirSync(stats.path, { withFileTypes: !0 }), startPtr = bufPtr; - for (let i = Number(cookie);i < entries.length; i += 1) { - const entry = entries[i]; - let nameLength = Buffer.byteLength(entry.name); - if (bufPtr - startPtr > bufLen) - break; - if (this.view.setBigUint64(bufPtr, BigInt(i + 1), !0), bufPtr += 8, bufPtr - startPtr > bufLen) - break; - const rstats = fs.lstatSync(path.resolve(stats.path, entry.name)); - if (this.view.setBigUint64(bufPtr, BigInt(rstats.ino), !0), bufPtr += 8, bufPtr - startPtr > bufLen) - break; - if (this.view.setUint32(bufPtr, nameLength, !0), bufPtr += 4, bufPtr - startPtr > bufLen) - break; - let filetype; - switch (!0) { - case rstats.isBlockDevice(): - filetype = constants_1.WASI_FILETYPE_BLOCK_DEVICE; - break; - case rstats.isCharacterDevice(): - filetype = constants_1.WASI_FILETYPE_CHARACTER_DEVICE; - break; - case rstats.isDirectory(): - filetype = constants_1.WASI_FILETYPE_DIRECTORY; - break; - case rstats.isFIFO(): - filetype = constants_1.WASI_FILETYPE_SOCKET_STREAM; - break; - case rstats.isFile(): - filetype = constants_1.WASI_FILETYPE_REGULAR_FILE; - break; - case rstats.isSocket(): - filetype = constants_1.WASI_FILETYPE_SOCKET_STREAM; - break; - case rstats.isSymbolicLink(): - filetype = constants_1.WASI_FILETYPE_SYMBOLIC_LINK; - break; - default: - filetype = constants_1.WASI_FILETYPE_UNKNOWN; - break; - } - if (this.view.setUint8(bufPtr, filetype), bufPtr += 1, bufPtr += 3, bufPtr + nameLength >= startPtr + bufLen) - break; - Buffer.from(this.memory.buffer).write(entry.name, bufPtr), bufPtr += nameLength; - } - const bufused = bufPtr - startPtr; - return this.view.setUint32(bufusedPtr, Math.min(bufused, bufLen), !0), constants_1.WASI_ESUCCESS; - }), - fd_renumber: wrap((from, to) => { - return CHECK_FD(from, BigInt(0)), CHECK_FD(to, BigInt(0)), fs.closeSync(this.FD_MAP.get(from).real), this.FD_MAP.set(from, this.FD_MAP.get(to)), this.FD_MAP.delete(to), constants_1.WASI_ESUCCESS; - }), - fd_seek: wrap((fd, offset, whence, newOffsetPtr) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_SEEK); - switch (this.refreshMemory(), whence) { - case constants_1.WASI_WHENCE_CUR: - stats.offset = (stats.offset ? stats.offset : BigInt(0)) + BigInt(offset); - break; - case constants_1.WASI_WHENCE_END: - const { size } = this.fstatSync(stats.real); - stats.offset = BigInt(size) + BigInt(offset); - break; - case constants_1.WASI_WHENCE_SET: - stats.offset = BigInt(offset); - break; - } - if (stats.offset == null) - throw Error("stats.offset must be defined"); - return this.view.setBigUint64(newOffsetPtr, stats.offset, !0), constants_1.WASI_ESUCCESS; - }), - fd_tell: wrap((fd, offsetPtr) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_TELL); - if (this.refreshMemory(), !stats.offset) - stats.offset = BigInt(0); - return this.view.setBigUint64(offsetPtr, stats.offset, !0), constants_1.WASI_ESUCCESS; - }), - fd_sync: wrap((fd) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_FD_SYNC); - return fs.fsyncSync(stats.real), constants_1.WASI_ESUCCESS; - }), - path_create_directory: wrap((fd, pathPtr, pathLen) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_PATH_CREATE_DIRECTORY); - if (!stats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const p = Buffer.from(this.memory.buffer, pathPtr, pathLen).toString(); - return fs.mkdirSync(path.resolve(stats.path, p)), constants_1.WASI_ESUCCESS; - }), - path_filestat_get: wrap((fd, flags, pathPtr, pathLen, bufPtr) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_PATH_FILESTAT_GET); - if (!stats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const p = Buffer.from(this.memory.buffer, pathPtr, pathLen).toString(); - let rstats; - if (flags) - rstats = fs.statSync(path.resolve(stats.path, p)); - else - rstats = fs.lstatSync(path.resolve(stats.path, p)); - return this.view.setBigUint64(bufPtr, BigInt(rstats.dev), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.ino), !0), bufPtr += 8, this.view.setUint8(bufPtr, translateFileAttributes(this, void 0, rstats).filetype), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.nlink), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.size), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.atime.getTime() * 1e6), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.mtime.getTime() * 1e6), !0), bufPtr += 8, this.view.setBigUint64(bufPtr, BigInt(rstats.ctime.getTime() * 1e6), !0), constants_1.WASI_ESUCCESS; - }), - path_filestat_set_times: wrap((fd, _dirflags, pathPtr, pathLen, stAtim, stMtim, fstflags) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_PATH_FILESTAT_SET_TIMES); - if (!stats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const rstats = this.fstatSync(stats.real); - let { atime: atim, mtime: mtim } = rstats; - const n = nsToMs(now(constants_1.WASI_CLOCK_REALTIME)), atimflags = constants_1.WASI_FILESTAT_SET_ATIM | constants_1.WASI_FILESTAT_SET_ATIM_NOW; - if ((fstflags & atimflags) === atimflags) - return constants_1.WASI_EINVAL; - const mtimflags = constants_1.WASI_FILESTAT_SET_MTIM | constants_1.WASI_FILESTAT_SET_MTIM_NOW; - if ((fstflags & mtimflags) === mtimflags) - return constants_1.WASI_EINVAL; - if ((fstflags & constants_1.WASI_FILESTAT_SET_ATIM) === constants_1.WASI_FILESTAT_SET_ATIM) - atim = nsToMs(stAtim); - else if ((fstflags & constants_1.WASI_FILESTAT_SET_ATIM_NOW) === constants_1.WASI_FILESTAT_SET_ATIM_NOW) - atim = n; - if ((fstflags & constants_1.WASI_FILESTAT_SET_MTIM) === constants_1.WASI_FILESTAT_SET_MTIM) - mtim = nsToMs(stMtim); - else if ((fstflags & constants_1.WASI_FILESTAT_SET_MTIM_NOW) === constants_1.WASI_FILESTAT_SET_MTIM_NOW) - mtim = n; - const p = Buffer.from(this.memory.buffer, pathPtr, pathLen).toString(); - return fs.utimesSync(path.resolve(stats.path, p), new Date(atim), new Date(mtim)), constants_1.WASI_ESUCCESS; - }), - path_link: wrap((oldFd, _oldFlags, oldPath, oldPathLen, newFd, newPath, newPathLen) => { - const ostats = CHECK_FD(oldFd, constants_1.WASI_RIGHT_PATH_LINK_SOURCE), nstats = CHECK_FD(newFd, constants_1.WASI_RIGHT_PATH_LINK_TARGET); - if (!ostats.path || !nstats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const op = Buffer.from(this.memory.buffer, oldPath, oldPathLen).toString(), np = Buffer.from(this.memory.buffer, newPath, newPathLen).toString(); - return fs.linkSync(path.resolve(ostats.path, op), path.resolve(nstats.path, np)), constants_1.WASI_ESUCCESS; - }), - path_open: wrap((dirfd, _dirflags, pathPtr, pathLen, oflags, fsRightsBase, fsRightsInheriting, fsFlags, fdPtr) => { - try { - const stats = CHECK_FD(dirfd, constants_1.WASI_RIGHT_PATH_OPEN); - fsRightsBase = BigInt(fsRightsBase), fsRightsInheriting = BigInt(fsRightsInheriting); - const read = (fsRightsBase & (constants_1.WASI_RIGHT_FD_READ | constants_1.WASI_RIGHT_FD_READDIR)) !== BigInt(0), write = (fsRightsBase & (constants_1.WASI_RIGHT_FD_DATASYNC | constants_1.WASI_RIGHT_FD_WRITE | constants_1.WASI_RIGHT_FD_ALLOCATE | constants_1.WASI_RIGHT_FD_FILESTAT_SET_SIZE)) !== BigInt(0); - let noflags; - if (write && read) - noflags = nodeFsConstants.O_RDWR; - else if (read) - noflags = nodeFsConstants.O_RDONLY; - else if (write) - noflags = nodeFsConstants.O_WRONLY; - let neededBase = fsRightsBase | constants_1.WASI_RIGHT_PATH_OPEN, neededInheriting = fsRightsBase | fsRightsInheriting; - if ((oflags & constants_1.WASI_O_CREAT) !== 0) - noflags |= nodeFsConstants.O_CREAT, neededBase |= constants_1.WASI_RIGHT_PATH_CREATE_FILE; - if ((oflags & constants_1.WASI_O_DIRECTORY) !== 0) - noflags |= nodeFsConstants.O_DIRECTORY; - if ((oflags & constants_1.WASI_O_EXCL) !== 0) - noflags |= nodeFsConstants.O_EXCL; - if ((oflags & constants_1.WASI_O_TRUNC) !== 0) - noflags |= nodeFsConstants.O_TRUNC, neededBase |= constants_1.WASI_RIGHT_PATH_FILESTAT_SET_SIZE; - if ((fsFlags & constants_1.WASI_FDFLAG_APPEND) !== 0) - noflags |= nodeFsConstants.O_APPEND; - if ((fsFlags & constants_1.WASI_FDFLAG_DSYNC) !== 0) { - if (nodeFsConstants.O_DSYNC) - noflags |= nodeFsConstants.O_DSYNC; - else - noflags |= nodeFsConstants.O_SYNC; - neededInheriting |= constants_1.WASI_RIGHT_FD_DATASYNC; - } - if ((fsFlags & constants_1.WASI_FDFLAG_NONBLOCK) !== 0) - noflags |= nodeFsConstants.O_NONBLOCK; - if ((fsFlags & constants_1.WASI_FDFLAG_RSYNC) !== 0) { - if (nodeFsConstants.O_RSYNC) - noflags |= nodeFsConstants.O_RSYNC; - else - noflags |= nodeFsConstants.O_SYNC; - neededInheriting |= constants_1.WASI_RIGHT_FD_SYNC; - } - if ((fsFlags & constants_1.WASI_FDFLAG_SYNC) !== 0) - noflags |= nodeFsConstants.O_SYNC, neededInheriting |= constants_1.WASI_RIGHT_FD_SYNC; - if (write && (noflags & (nodeFsConstants.O_APPEND | nodeFsConstants.O_TRUNC)) === 0) - neededInheriting |= constants_1.WASI_RIGHT_FD_SEEK; - this.refreshMemory(); - const p = Buffer.from(this.memory.buffer, pathPtr, pathLen).toString(); - if (p == "dev/tty") - return this.view.setUint32(fdPtr, constants_1.WASI_STDIN_FILENO, !0), constants_1.WASI_ESUCCESS; - if (logOpen("path_open", p), p.startsWith("proc/")) - throw new types_1.WASIError(constants_1.WASI_EBADF); - const fullUnresolved = path.resolve(p); - let full; - try { - full = fs.realpathSync(fullUnresolved); - } catch (e) { - if (e?.code === "ENOENT") - full = fullUnresolved; - else - throw e; - } - let isDirectory; - if (write) - try { - isDirectory = fs.statSync(full).isDirectory(); - } catch (_err) { - } - let realfd; - if (!write && isDirectory) - realfd = fs.openSync(full, nodeFsConstants.O_RDONLY); - else - realfd = fs.openSync(full, noflags); - const newfd = this.getUnusedFileDescriptor(); - this.FD_MAP.set(newfd, { - real: realfd, - filetype: void 0, - rights: { - base: neededBase, - inheriting: neededInheriting - }, - path: full - }), stat(this, newfd), this.view.setUint32(fdPtr, newfd, !0); - } catch (e) { - console.error(e); - } - return constants_1.WASI_ESUCCESS; - }), - path_readlink: wrap((fd, pathPtr, pathLen, buf, bufLen, bufused) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_PATH_READLINK); - if (!stats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const p = Buffer.from(this.memory.buffer, pathPtr, pathLen).toString(), full = path.resolve(stats.path, p), r = fs.readlinkSync(full), used = Buffer.from(this.memory.buffer).write(r, buf, bufLen); - return this.view.setUint32(bufused, used, !0), constants_1.WASI_ESUCCESS; - }), - path_remove_directory: wrap((fd, pathPtr, pathLen) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_PATH_REMOVE_DIRECTORY); - if (!stats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const p = Buffer.from(this.memory.buffer, pathPtr, pathLen).toString(); - return fs.rmdirSync(path.resolve(stats.path, p)), constants_1.WASI_ESUCCESS; - }), - path_rename: wrap((oldFd, oldPath, oldPathLen, newFd, newPath, newPathLen) => { - const ostats = CHECK_FD(oldFd, constants_1.WASI_RIGHT_PATH_RENAME_SOURCE), nstats = CHECK_FD(newFd, constants_1.WASI_RIGHT_PATH_RENAME_TARGET); - if (!ostats.path || !nstats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const op = Buffer.from(this.memory.buffer, oldPath, oldPathLen).toString(), np = Buffer.from(this.memory.buffer, newPath, newPathLen).toString(); - return fs.renameSync(path.resolve(ostats.path, op), path.resolve(nstats.path, np)), constants_1.WASI_ESUCCESS; - }), - path_symlink: wrap((oldPath, oldPathLen, fd, newPath, newPathLen) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_PATH_SYMLINK); - if (!stats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const op = Buffer.from(this.memory.buffer, oldPath, oldPathLen).toString(), np = Buffer.from(this.memory.buffer, newPath, newPathLen).toString(); - return fs.symlinkSync(op, path.resolve(stats.path, np)), constants_1.WASI_ESUCCESS; - }), - path_unlink_file: wrap((fd, pathPtr, pathLen) => { - const stats = CHECK_FD(fd, constants_1.WASI_RIGHT_PATH_UNLINK_FILE); - if (!stats.path) - return constants_1.WASI_EINVAL; - this.refreshMemory(); - const p = Buffer.from(this.memory.buffer, pathPtr, pathLen).toString(); - return fs.unlinkSync(path.resolve(stats.path, p)), constants_1.WASI_ESUCCESS; - }), - poll_oneoff: (sin, sout, nsubscriptions, neventsPtr) => { - let nevents = 0, name = "", waitTimeNs = BigInt(0), fd = -1, fd_type = "read", fd_timeout_ms = 0; - const startNs = BigInt(bindings2.hrtime()); - this.refreshMemory(); - let last_sin = sin; - for (let i = 0;i < nsubscriptions; i += 1) { - const userdata = this.view.getBigUint64(sin, !0); - sin += 8; - const type = this.view.getUint8(sin); - if (sin += 1, sin += 7, log.enabled) { - if (type == constants_1.WASI_EVENTTYPE_CLOCK) - name = "poll_oneoff (type=WASI_EVENTTYPE_CLOCK): "; - else if (type == constants_1.WASI_EVENTTYPE_FD_READ) - name = "poll_oneoff (type=WASI_EVENTTYPE_FD_READ): "; - else - name = "poll_oneoff (type=WASI_EVENTTYPE_FD_WRITE): "; - log(name); - } - switch (type) { - case constants_1.WASI_EVENTTYPE_CLOCK: { - const clockid = this.view.getUint32(sin, !0); - sin += 4, sin += 4; - const timeout = this.view.getBigUint64(sin, !0); - sin += 8, sin += 8; - const subclockflags = this.view.getUint16(sin, !0); - sin += 2, sin += 6; - const absolute = subclockflags === 1; - if (log.enabled) - log(name, { clockid, timeout, absolute }); - if (!absolute) - fd_timeout_ms = timeout / BigInt(1e6); - let e = constants_1.WASI_ESUCCESS; - const t = now(clockid); - if (t == null) - e = constants_1.WASI_EINVAL; - else { - const tNS = BigInt(t), waitNs = (absolute ? timeout : tNS + timeout) - tNS; - if (waitNs > waitTimeNs) - waitTimeNs = waitNs; - } - this.view.setBigUint64(sout, userdata, !0), sout += 8, this.view.setUint16(sout, e, !0), sout += 2, this.view.setUint8(sout, constants_1.WASI_EVENTTYPE_CLOCK), sout += 1, sout += 5, nevents += 1; - break; - } - case constants_1.WASI_EVENTTYPE_FD_READ: - case constants_1.WASI_EVENTTYPE_FD_WRITE: { - if (fd = this.view.getUint32(sin, !0), fd_type = type == constants_1.WASI_EVENTTYPE_FD_READ ? "read" : "write", sin += 4, log(name, "fd =", fd), sin += 28, this.view.setBigUint64(sout, userdata, !0), sout += 8, this.view.setUint16(sout, constants_1.WASI_ENOSYS, !0), sout += 2, this.view.setUint8(sout, type), sout += 1, sout += 5, nevents += 1, fd == constants_1.WASI_STDIN_FILENO && constants_1.WASI_EVENTTYPE_FD_READ == type) - this.shortPause(); - break; - } - default: - return constants_1.WASI_EINVAL; - } - if (sin - last_sin != 48) - console.warn("*** BUG in wasi-js in poll_oneoff ", { - i, - sin, - last_sin, - diff: sin - last_sin - }); - last_sin = sin; - } - if (this.view.setUint32(neventsPtr, nevents, !0), nevents == 2 && fd >= 0) { - const r = this.wasiImport.sock_pollSocket(fd, fd_type, fd_timeout_ms); - if (r != constants_1.WASI_ENOSYS) - return r; - } - if (waitTimeNs > 0) { - if (waitTimeNs -= Bun.nanoseconds() - timeOrigin, waitTimeNs >= 1e6) { - if (this.sleep == null && !warnedAboutSleep) - warnedAboutSleep = !0, console.log("(100% cpu burning waiting for stdin: please define a way to sleep!) "); - if (this.sleep != null) { - const ms = nsToMs(waitTimeNs); - this.sleep(ms); - } else { - const end = BigInt(bindings2.hrtime()) + waitTimeNs; - while (BigInt(bindings2.hrtime()) < end) - ; - } - } - } - return constants_1.WASI_ESUCCESS; - }, - proc_exit: (rval) => { - return bindings2.exit(rval), constants_1.WASI_ESUCCESS; - }, - proc_raise: (sig) => { - if (!(sig in constants_1.SIGNAL_MAP)) - return constants_1.WASI_EINVAL; - return bindings2.kill(constants_1.SIGNAL_MAP[sig]), constants_1.WASI_ESUCCESS; - }, - random_get: (bufPtr, bufLen) => { - return this.refreshMemory(), crypto.getRandomValues(this.memory.buffer, bufPtr, bufLen), bufLen; - }, - sched_yield() { - return constants_1.WASI_ESUCCESS; - }, - sock_recv() { - return constants_1.WASI_ENOSYS; - }, - sock_send() { - return constants_1.WASI_ENOSYS; - }, - sock_shutdown() { - return constants_1.WASI_ENOSYS; - }, - sock_fcntlSetFlags(_fd, _flags) { - return constants_1.WASI_ENOSYS; - }, - sock_pollSocket(_fd, _eventtype, _timeout_ms) { - return constants_1.WASI_ENOSYS; - } - }, log.enabled) - Object.keys(this.wasiImport).forEach((key) => { - const prevImport = this.wasiImport[key]; - this.wasiImport[key] = function(...args2) { - log(key, args2); - try { - let result = prevImport(...args2); - return log("result", result), result; - } catch (e) { - throw log("error: ", e), e; - } - }; - }); - } - getState() { - return { env: this.env, FD_MAP: this.FD_MAP, bindings }; - } - setState(state) { - this.env = state.env, this.FD_MAP = state.FD_MAP, bindings = state.bindings; - } - fstatSync(real_fd) { - if (real_fd <= 2) - try { - return fs.fstatSync(real_fd); - } catch (_) { - const now = new Date; - return { - dev: 0, - mode: 8592, - nlink: 1, - uid: 0, - gid: 0, - rdev: 0, - blksize: 65536, - ino: 0, - size: 0, - blocks: 0, - atimeMs: now.valueOf(), - mtimeMs: now.valueOf(), - ctimeMs: now.valueOf(), - birthtimeMs: 0, - atime: new Date, - mtime: new Date, - ctime: new Date, - birthtime: new Date(0) - }; - } - return fs.fstatSync(real_fd); - } - shortPause() { - if (this.sleep == null) - return; - if ((new Date()).valueOf() - this.lastStdin > 2000) - this.sleep(50); - } - getUnusedFileDescriptor(start = 3) { - let fd = start; - while (this.FD_MAP.has(fd)) - fd += 1; - if (fd > SC_OPEN_MAX) - throw Error("no available file descriptors"); - return fd; - } - refreshMemory() { - if (!this.view || this.view.buffer.byteLength === 0) - this.view = new DataView(this.memory.buffer); - } - setMemory(memory) { - this.memory = memory; - } - start(instance, memory) { - const exports2 = instance.exports; - if (exports2 === null || typeof exports2 !== "object") - throw new Error(`instance.exports must be an Object. Received ${exports2}.`); - if (memory == null) { - if (memory = exports2.memory, !(memory instanceof WebAssembly.Memory)) - throw new Error(`instance.exports.memory must be a WebAssembly.Memory. Recceived ${memory}.`); - } - if (this.setMemory(memory), exports2._start) - exports2._start(); - } - getImports(module2) { - let namespace = null; - const imports = WebAssembly.Module.imports(module2); - for (let imp of imports) { - if (imp.kind !== "function") - continue; - if (!imp.module.startsWith("wasi_")) - continue; - namespace = imp.module; - break; - } - switch (namespace) { - case "wasi_unstable": - return { - wasi_unstable: this.wasiImport - }; - case "wasi_snapshot_preview1": - return { - wasi_snapshot_preview1: this.wasiImport - }; - default: - throw new Error("No WASI namespace found. Only wasi_unstable and wasi_snapshot_preview1 are supported.\n\nList of imports:\n\n" + imports.map(({ name, kind, module }) => `${module}:${name} (${kind})`).join("\n") + "\n"); - } - } - initWasiFdInfo() { - if (this.env.WASI_FD_INFO != null) { - const fdInfo = JSON.parse(this.env.WASI_FD_INFO); - for (let wasi_fd in fdInfo) { - console.log(wasi_fd); - const fd = parseInt(wasi_fd); - if (this.FD_MAP.has(fd)) - continue; - const real = fdInfo[wasi_fd]; - try { - this.fstatSync(real); - } catch (_err) { - console.log("discarding ", { wasi_fd, real }); - continue; - } - const file = { - real, - filetype: constants_1.WASI_FILETYPE_SOCKET_STREAM, - rights: { - base: STDIN_DEFAULT_RIGHTS, - inheriting: BigInt(0) - } - }; - this.FD_MAP.set(fd, file); - } - console.log("after initWasiFdInfo: ", this.FD_MAP), console.log("fdInfo = ", fdInfo); - } else - console.log("no WASI_FD_INFO"); - } - }; - exports.default = WASI; - } -}), WASIExport = require_wasi(), WASI = WASIExport.default; -WASIExport[Symbol.for("CommonJS")] = 0; -var wasi_default = WASIExport; -export { - wasi_default as default, - WASIExport as WASI -}; diff --git a/src/js/out/modules/node/zlib.js b/src/js/out/modules/node/zlib.js deleted file mode 100644 index 39565887821dc8..00000000000000 --- a/src/js/out/modules/node/zlib.js +++ /dev/null @@ -1 +0,0 @@ -var p1=(Y)=>{return import.meta.require(Y)};import{default as R0} from"node:assert";import*as t0 from"node:assert";import*as o0 from"node:buffer";import*as s0 from"node:stream";import*as W1 from"node:util";var j1,J1,Y1,G1,q1,X1,U1,P1,K1,F1,H1,z1,Z1,L1,C1,N1,I1,O1,B1,D1,M1,k1,v1,R1,A1,g1,w1,T1,S1;var y1=Object.getOwnPropertyNames;var A0=(Y,g)=>function b(){return g||(0,Y[y1(Y)[0]])((g={exports:{}}).exports,g),g.exports};var E1=A0({"node_modules/pako/lib/zlib/zstream.js"(Y,g){function b(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}g.exports=b}}),r0=A0({"node_modules/pako/lib/utils/common.js"(Y){var g=typeof Uint8Array!=="undefined"&&typeof Uint16Array!=="undefined"&&typeof Int32Array!=="undefined";function b(C,w){return Object.prototype.hasOwnProperty.call(C,w)}Y.assign=function(C){var w=Array.prototype.slice.call(arguments,1);while(w.length){var v=w.shift();if(!v)continue;if(typeof v!=="object")throw new TypeError(v+"must be non-object");for(var k in v)if(b(v,k))C[k]=v[k]}return C},Y.shrinkBuf=function(C,w){if(C.length===w)return C;if(C.subarray)return C.subarray(0,w);return C.length=w,C};var L={arraySet:function(C,w,v,k,B){if(w.subarray&&C.subarray){C.set(w.subarray(v,v+k),B);return}for(var N=0;N=0)W[F]=0}var v=0,k=1,B=2,N=3,y=258,m=29,p=256,t=p+1+m,u=30,s=19,W0=2*t+1,E=15,S=16,J0=7,G0=256,F0=16,f=17,d=18,z=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],h=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],V0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],j=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],K=512,O=new Array((t+2)*2);w(O);var I=new Array(u*2);w(I);var c=new Array(K);w(c);var l=new Array(y-N+1);w(l);var D=new Array(m);w(D);var Q0=new Array(u);w(Q0);function i(W,F,Z,R,G){this.static_tree=W,this.extra_bits=F,this.extra_base=Z,this.elems=R,this.max_length=G,this.has_stree=W&&W.length}var H0,N0,I0;function K0(W,F){this.dyn_tree=W,this.max_code=0,this.stat_desc=F}function X0(W){return W<256?c[W]:c[256+(W>>>7)]}function U0(W,F){W.pending_buf[W.pending++]=F&255,W.pending_buf[W.pending++]=F>>>8&255}function a(W,F,Z){if(W.bi_valid>S-Z)W.bi_buf|=F<>S-W.bi_valid,W.bi_valid+=Z-S;else W.bi_buf|=F<>>=1,Z<<=1;while(--F>0);return Z>>>1}function z0(W){if(W.bi_valid===16)U0(W,W.bi_buf),W.bi_buf=0,W.bi_valid=0;else if(W.bi_valid>=8)W.pending_buf[W.pending++]=W.bi_buf&255,W.bi_buf>>=8,W.bi_valid-=8}function Z0(W,F){var{dyn_tree:Z,max_code:R}=F,G=F.stat_desc.static_tree,P=F.stat_desc.has_stree,$=F.stat_desc.extra_bits,H=F.stat_desc.extra_base,x=F.stat_desc.max_length,Q,X,U,V,J,q,T=0;for(V=0;V<=E;V++)W.bl_count[V]=0;Z[W.heap[W.heap_max]*2+1]=0;for(Q=W.heap_max+1;Qx)V=x,T++;if(Z[X*2+1]=V,X>R)continue;if(W.bl_count[V]++,J=0,X>=H)J=$[X-H];if(q=Z[X*2],W.opt_len+=q*(V+J),P)W.static_len+=q*(G[X*2+1]+J)}if(T===0)return;do{V=x-1;while(W.bl_count[V]===0)V--;W.bl_count[V]--,W.bl_count[V+1]+=2,W.bl_count[x]--,T-=2}while(T>0);for(V=x;V!==0;V--){X=W.bl_count[V];while(X!==0){if(U=W.heap[--Q],U>R)continue;if(Z[U*2+1]!==V)W.opt_len+=(V-Z[U*2+1])*Z[U*2],Z[U*2+1]=V;X--}}}function g0(W,F,Z){var R=new Array(E+1),G=0,P,$;for(P=1;P<=E;P++)R[P]=G=G+Z[P-1]<<1;for($=0;$<=F;$++){var H=W[$*2+1];if(H===0)continue;W[$*2]=r(R[H]++,H)}}function j0(){var W,F,Z,R,G,P=new Array(E+1);Z=0;for(R=0;R>=7;for(;R8)U0(W,W.bi_buf);else if(W.bi_valid>0)W.pending_buf[W.pending++]=W.bi_buf;W.bi_buf=0,W.bi_valid=0}function w0(W,F,Z,R){if(c0(W),R)U0(W,Z),U0(W,~Z);g.arraySet(W.pending_buf,W.window,F,Z,W.pending),W.pending+=Z}function v0(W,F,Z,R){var G=F*2,P=Z*2;return W[G]>1;$>=1;$--)q0(W,Z,$);Q=P;do $=W.heap[1],W.heap[1]=W.heap[W.heap_len--],q0(W,Z,1),H=W.heap[1],W.heap[--W.heap_max]=$,W.heap[--W.heap_max]=H,Z[Q*2]=Z[$*2]+Z[H*2],W.depth[Q]=(W.depth[$]>=W.depth[H]?W.depth[$]:W.depth[H])+1,Z[$*2+1]=Z[H*2+1]=Q,W.heap[1]=Q++,q0(W,Z,1);while(W.heap_len>=2);W.heap[--W.heap_max]=W.heap[1],Z0(W,F),g0(Z,x,W.bl_count)}function p0(W,F,Z){var R,G=-1,P,$=F[1],H=0,x=7,Q=4;if($===0)x=138,Q=3;F[(Z+1)*2+1]=65535;for(R=0;R<=Z;R++){if(P=$,$=F[(R+1)*2+1],++H=3;F--)if(W.bl_tree[j[F]*2+1]!==0)break;return W.opt_len+=3*(F+1)+5+5+4,F}function i0(W,F,Z,R){var G;a(W,F-257,5),a(W,Z-1,5),a(W,R-4,4);for(G=0;G>>=1)if(F&1&&W.dyn_ltree[Z*2]!==0)return L;if(W.dyn_ltree[18]!==0||W.dyn_ltree[20]!==0||W.dyn_ltree[26]!==0)return n;for(Z=32;Z0){if(W.strm.data_type===C)W.strm.data_type=d0(W);if(T0(W,W.l_desc),T0(W,W.d_desc),$=S0(W),G=W.opt_len+3+7>>>3,P=W.static_len+3+7>>>3,P<=G)G=P}else G=P=Z+5;if(Z+4<=G&&F!==-1)m0(W,F,Z,R);else if(W.strategy===b||P===G)a(W,(k<<1)+(R?1:0),3),_(W,O,I);else a(W,(B<<1)+(R?1:0),3),i0(W,W.l_desc.max_code+1,W.d_desc.max_code+1,$+1),_(W,W.dyn_ltree,W.dyn_dtree);if(M0(W),R)c0(W)}function n0(W,F,Z){if(W.pending_buf[W.d_buf+W.last_lit*2]=F>>>8&255,W.pending_buf[W.d_buf+W.last_lit*2+1]=F&255,W.pending_buf[W.l_buf+W.last_lit]=Z&255,W.last_lit++,F===0)W.dyn_ltree[Z*2]++;else W.matches++,F--,W.dyn_ltree[(l[Z]+p+1)*2]++,W.dyn_dtree[X0(F)*2]++;return W.last_lit===W.lit_bufsize-1}Y._tr_init=_0,Y._tr_stored_block=m0,Y._tr_flush_block=h0,Y._tr_tally=n0,Y._tr_align=B0}}),Q1=A0({"node_modules/pako/lib/zlib/adler32.js"(Y,g){function b(L,n,C,w){var v=L&65535|0,k=L>>>16&65535|0,B=0;while(C!==0){B=C>2000?2000:C,C-=B;do v=v+n[w++]|0,k=k+v|0;while(--B);v%=65521,k%=65521}return v|k<<16|0}g.exports=b}}),$1=A0({"node_modules/pako/lib/zlib/crc32.js"(Y,g){function b(){var C,w=[];for(var v=0;v<256;v++){C=v;for(var k=0;k<8;k++)C=C&1?3988292384^C>>>1:C>>>1;w[v]=C}return w}var L=b();function n(C,w,v,k){var B=L,N=k+v;C^=-1;for(var y=k;y>>8^B[(C^w[y])&255];return C^-1}g.exports=n}}),h1=A0({"node_modules/pako/lib/zlib/messages.js"(Y,g){g.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}}}),f1=A0({"node_modules/pako/lib/zlib/deflate.js"(Y){var g=r0(),b=x1(),L=Q1(),n=$1(),C=h1(),w=0,v=1,k=3,B=4,N=5,y=0,m=1,p=-2,t=-3,u=-5,s=-1,W0=1,E=2,S=3,J0=4,G0=0,F0=2,f=8,d=9,z=15,h=8,V0=29,j=256,K=j+1+V0,O=30,I=19,c=2*K+1,l=15,D=3,Q0=258,i=Q0+D+1,H0=32,N0=42,I0=69,K0=73,X0=91,U0=103,a=113,Y0=666,r=1,z0=2,Z0=3,g0=4,j0=3;function M0(Q,X){return Q.msg=C[X],X}function c0(Q){return(Q<<1)-(Q>4?9:0)}function w0(Q){var X=Q.length;while(--X>=0)Q[X]=0}function v0(Q){var X=Q.state,U=X.pending;if(U>Q.avail_out)U=Q.avail_out;if(U===0)return;if(g.arraySet(Q.output,X.pending_buf,X.pending_out,U,Q.next_out),Q.next_out+=U,X.pending_out+=U,Q.total_out+=U,Q.avail_out-=U,X.pending-=U,X.pending===0)X.pending_out=0}function q0(Q,X){b._tr_flush_block(Q,Q.block_start>=0?Q.block_start:-1,Q.strstart-Q.block_start,X),Q.block_start=Q.strstart,v0(Q.strm)}function _(Q,X){Q.pending_buf[Q.pending++]=X}function T0(Q,X){Q.pending_buf[Q.pending++]=X>>>8&255,Q.pending_buf[Q.pending++]=X&255}function p0(Q,X,U,V){var J=Q.avail_in;if(J>V)J=V;if(J===0)return 0;if(Q.avail_in-=J,g.arraySet(X,Q.input,Q.next_in,J,U),Q.state.wrap===1)Q.adler=L(Q.adler,X,J,U);else if(Q.state.wrap===2)Q.adler=n(Q.adler,X,J,U);return Q.next_in+=J,Q.total_in+=J,J}function b0(Q,X){var{max_chain_length:U,strstart:V}=Q,J,q,T=Q.prev_length,M=Q.nice_match,A=Q.strstart>Q.w_size-i?Q.strstart-(Q.w_size-i):0,o=Q.window,f0=Q.w_mask,P0=Q.prev,e=Q.strstart+Q0,C0=o[V+T-1],D0=o[V+T];if(Q.prev_length>=Q.good_match)U>>=2;if(M>Q.lookahead)M=Q.lookahead;do{if(J=X,o[J+T]!==D0||o[J+T-1]!==C0||o[J]!==o[V]||o[++J]!==o[V+1])continue;V+=2,J++;do;while(o[++V]===o[++J]&&o[++V]===o[++J]&&o[++V]===o[++J]&&o[++V]===o[++J]&&o[++V]===o[++J]&&o[++V]===o[++J]&&o[++V]===o[++J]&&o[++V]===o[++J]&&VT){if(Q.match_start=X,T=q,q>=M)break;C0=o[V+T-1],D0=o[V+T]}}while((X=P0[X&f0])>A&&--U!==0);if(T<=Q.lookahead)return T;return Q.lookahead}function S0(Q){var X=Q.w_size,U,V,J,q,T;do{if(q=Q.window_size-Q.lookahead-Q.strstart,Q.strstart>=X+(X-i)){g.arraySet(Q.window,Q.window,X,X,0),Q.match_start-=X,Q.strstart-=X,Q.block_start-=X,V=Q.hash_size,U=V;do J=Q.head[--U],Q.head[U]=J>=X?J-X:0;while(--V);V=X,U=V;do J=Q.prev[--U],Q.prev[U]=J>=X?J-X:0;while(--V);q+=X}if(Q.strm.avail_in===0)break;if(V=p0(Q.strm,Q.window,Q.strstart+Q.lookahead,q),Q.lookahead+=V,Q.lookahead+Q.insert>=D){T=Q.strstart-Q.insert,Q.ins_h=Q.window[T],Q.ins_h=(Q.ins_h<Q.pending_buf_size-5)U=Q.pending_buf_size-5;for(;;){if(Q.lookahead<=1){if(S0(Q),Q.lookahead===0&&X===w)return r;if(Q.lookahead===0)break}Q.strstart+=Q.lookahead,Q.lookahead=0;var V=Q.block_start+U;if(Q.strstart===0||Q.strstart>=V){if(Q.lookahead=Q.strstart-V,Q.strstart=V,q0(Q,!1),Q.strm.avail_out===0)return r}if(Q.strstart-Q.block_start>=Q.w_size-i){if(q0(Q,!1),Q.strm.avail_out===0)return r}}if(Q.insert=0,X===B){if(q0(Q,!0),Q.strm.avail_out===0)return Z0;return g0}if(Q.strstart>Q.block_start){if(q0(Q,!1),Q.strm.avail_out===0)return r}return r}function d0(Q,X){var U,V;for(;;){if(Q.lookahead=D)Q.ins_h=(Q.ins_h<=D)if(V=b._tr_tally(Q,Q.strstart-Q.match_start,Q.match_length-D),Q.lookahead-=Q.match_length,Q.match_length<=Q.max_lazy_match&&Q.lookahead>=D){Q.match_length--;do Q.strstart++,Q.ins_h=(Q.ins_h<=D)Q.ins_h=(Q.ins_h<4096))Q.match_length=D-1}if(Q.prev_length>=D&&Q.match_length<=Q.prev_length){J=Q.strstart+Q.lookahead-D,V=b._tr_tally(Q,Q.strstart-1-Q.prev_match,Q.prev_length-D),Q.lookahead-=Q.prev_length-1,Q.prev_length-=2;do if(++Q.strstart<=J)Q.ins_h=(Q.ins_h<=D&&Q.strstart>0){if(J=Q.strstart-1,V=T[J],V===T[++J]&&V===T[++J]&&V===T[++J]){q=Q.strstart+Q0;do;while(V===T[++J]&&V===T[++J]&&V===T[++J]&&V===T[++J]&&V===T[++J]&&V===T[++J]&&V===T[++J]&&V===T[++J]&&JQ.lookahead)Q.match_length=Q.lookahead}}if(Q.match_length>=D)U=b._tr_tally(Q,1,Q.match_length-D),Q.lookahead-=Q.match_length,Q.strstart+=Q.match_length,Q.match_length=0;else U=b._tr_tally(Q,0,Q.window[Q.strstart]),Q.lookahead--,Q.strstart++;if(U){if(q0(Q,!1),Q.strm.avail_out===0)return r}}if(Q.insert=0,X===B){if(q0(Q,!0),Q.strm.avail_out===0)return Z0;return g0}if(Q.last_lit){if(q0(Q,!1),Q.strm.avail_out===0)return r}return z0}function m0(Q,X){var U;for(;;){if(Q.lookahead===0){if(S0(Q),Q.lookahead===0){if(X===w)return r;break}}if(Q.match_length=0,U=b._tr_tally(Q,0,Q.window[Q.strstart]),Q.lookahead--,Q.strstart++,U){if(q0(Q,!1),Q.strm.avail_out===0)return r}}if(Q.insert=0,X===B){if(q0(Q,!0),Q.strm.avail_out===0)return Z0;return g0}if(Q.last_lit){if(q0(Q,!1),Q.strm.avail_out===0)return r}return z0}function B0(Q,X,U,V,J){this.good_length=Q,this.max_lazy=X,this.nice_length=U,this.max_chain=V,this.func=J}var h0=[new B0(0,0,0,0,i0),new B0(4,4,8,4,d0),new B0(4,5,16,8,d0),new B0(4,6,32,32,d0),new B0(4,4,16,16,E0),new B0(8,16,32,32,E0),new B0(8,16,128,128,E0),new B0(8,32,128,256,E0),new B0(32,128,258,1024,E0),new B0(32,258,258,4096,E0)];function n0(Q){Q.window_size=2*Q.w_size,w0(Q.head),Q.max_lazy_match=h0[Q.level].max_lazy,Q.good_match=h0[Q.level].good_length,Q.nice_match=h0[Q.level].nice_length,Q.max_chain_length=h0[Q.level].max_chain,Q.strstart=0,Q.block_start=0,Q.lookahead=0,Q.insert=0,Q.match_length=Q.prev_length=D-1,Q.match_available=0,Q.ins_h=0}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=f,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new g.Buf16(c*2),this.dyn_dtree=new g.Buf16((2*O+1)*2),this.bl_tree=new g.Buf16((2*I+1)*2),w0(this.dyn_ltree),w0(this.dyn_dtree),w0(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new g.Buf16(l+1),this.heap=new g.Buf16(2*K+1),w0(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new g.Buf16(2*K+1),w0(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function F(Q){var X;if(!Q||!Q.state)return M0(Q,p);if(Q.total_in=Q.total_out=0,Q.data_type=F0,X=Q.state,X.pending=0,X.pending_out=0,X.wrap<0)X.wrap=-X.wrap;return X.status=X.wrap?N0:a,Q.adler=X.wrap===2?0:1,X.last_flush=w,b._tr_init(X),y}function Z(Q){var X=F(Q);if(X===y)n0(Q.state);return X}function R(Q,X){if(!Q||!Q.state)return p;if(Q.state.wrap!==2)return p;return Q.state.gzhead=X,y}function G(Q,X,U,V,J,q){if(!Q)return p;var T=1;if(X===s)X=6;if(V<0)T=0,V=-V;else if(V>15)T=2,V-=16;if(J<1||J>d||U!==f||V<8||V>15||X<0||X>9||q<0||q>J0)return M0(Q,p);if(V===8)V=9;var M=new W;return Q.state=M,M.strm=Q,M.wrap=T,M.gzhead=null,M.w_bits=V,M.w_size=1<N||X<0)return Q?M0(Q,p):p;if(V=Q.state,!Q.output||!Q.input&&Q.avail_in!==0||V.status===Y0&&X!==B)return M0(Q,Q.avail_out===0?u:p);if(V.strm=Q,U=V.last_flush,V.last_flush=X,V.status===N0)if(V.wrap===2)if(Q.adler=0,_(V,31),_(V,139),_(V,8),!V.gzhead)_(V,0),_(V,0),_(V,0),_(V,0),_(V,0),_(V,V.level===9?2:V.strategy>=E||V.level<2?4:0),_(V,j0),V.status=a;else{if(_(V,(V.gzhead.text?1:0)+(V.gzhead.hcrc?2:0)+(!V.gzhead.extra?0:4)+(!V.gzhead.name?0:8)+(!V.gzhead.comment?0:16)),_(V,V.gzhead.time&255),_(V,V.gzhead.time>>8&255),_(V,V.gzhead.time>>16&255),_(V,V.gzhead.time>>24&255),_(V,V.level===9?2:V.strategy>=E||V.level<2?4:0),_(V,V.gzhead.os&255),V.gzhead.extra&&V.gzhead.extra.length)_(V,V.gzhead.extra.length&255),_(V,V.gzhead.extra.length>>8&255);if(V.gzhead.hcrc)Q.adler=n(Q.adler,V.pending_buf,V.pending,0);V.gzindex=0,V.status=I0}else{var T=f+(V.w_bits-8<<4)<<8,M=-1;if(V.strategy>=E||V.level<2)M=0;else if(V.level<6)M=1;else if(V.level===6)M=2;else M=3;if(T|=M<<6,V.strstart!==0)T|=H0;if(T+=31-T%31,V.status=a,T0(V,T),V.strstart!==0)T0(V,Q.adler>>>16),T0(V,Q.adler&65535);Q.adler=1}if(V.status===I0)if(V.gzhead.extra){J=V.pending;while(V.gzindex<(V.gzhead.extra.length&65535)){if(V.pending===V.pending_buf_size){if(V.gzhead.hcrc&&V.pending>J)Q.adler=n(Q.adler,V.pending_buf,V.pending-J,J);if(v0(Q),J=V.pending,V.pending===V.pending_buf_size)break}_(V,V.gzhead.extra[V.gzindex]&255),V.gzindex++}if(V.gzhead.hcrc&&V.pending>J)Q.adler=n(Q.adler,V.pending_buf,V.pending-J,J);if(V.gzindex===V.gzhead.extra.length)V.gzindex=0,V.status=K0}else V.status=K0;if(V.status===K0)if(V.gzhead.name){J=V.pending;do{if(V.pending===V.pending_buf_size){if(V.gzhead.hcrc&&V.pending>J)Q.adler=n(Q.adler,V.pending_buf,V.pending-J,J);if(v0(Q),J=V.pending,V.pending===V.pending_buf_size){q=1;break}}if(V.gzindexJ)Q.adler=n(Q.adler,V.pending_buf,V.pending-J,J);if(q===0)V.gzindex=0,V.status=X0}else V.status=X0;if(V.status===X0)if(V.gzhead.comment){J=V.pending;do{if(V.pending===V.pending_buf_size){if(V.gzhead.hcrc&&V.pending>J)Q.adler=n(Q.adler,V.pending_buf,V.pending-J,J);if(v0(Q),J=V.pending,V.pending===V.pending_buf_size){q=1;break}}if(V.gzindexJ)Q.adler=n(Q.adler,V.pending_buf,V.pending-J,J);if(q===0)V.status=U0}else V.status=U0;if(V.status===U0)if(V.gzhead.hcrc){if(V.pending+2>V.pending_buf_size)v0(Q);if(V.pending+2<=V.pending_buf_size)_(V,Q.adler&255),_(V,Q.adler>>8&255),Q.adler=0,V.status=a}else V.status=a;if(V.pending!==0){if(v0(Q),Q.avail_out===0)return V.last_flush=-1,y}else if(Q.avail_in===0&&c0(X)<=c0(U)&&X!==B)return M0(Q,u);if(V.status===Y0&&Q.avail_in!==0)return M0(Q,u);if(Q.avail_in!==0||V.lookahead!==0||X!==w&&V.status!==Y0){var A=V.strategy===E?m0(V,X):V.strategy===S?_0(V,X):h0[V.level].func(V,X);if(A===Z0||A===g0)V.status=Y0;if(A===r||A===Z0){if(Q.avail_out===0)V.last_flush=-1;return y}if(A===z0){if(X===v)b._tr_align(V);else if(X!==N){if(b._tr_stored_block(V,0,0,!1),X===k){if(w0(V.head),V.lookahead===0)V.strstart=0,V.block_start=0,V.insert=0}}if(v0(Q),Q.avail_out===0)return V.last_flush=-1,y}}if(X!==B)return y;if(V.wrap<=0)return m;if(V.wrap===2)_(V,Q.adler&255),_(V,Q.adler>>8&255),_(V,Q.adler>>16&255),_(V,Q.adler>>24&255),_(V,Q.total_in&255),_(V,Q.total_in>>8&255),_(V,Q.total_in>>16&255),_(V,Q.total_in>>24&255);else T0(V,Q.adler>>>16),T0(V,Q.adler&65535);if(v0(Q),V.wrap>0)V.wrap=-V.wrap;return V.pending!==0?y:m}function H(Q){var X;if(!Q||!Q.state)return p;if(X=Q.state.status,X!==N0&&X!==I0&&X!==K0&&X!==X0&&X!==U0&&X!==a&&X!==Y0)return M0(Q,p);return Q.state=null,X===a?M0(Q,t):y}function x(Q,X){var U=X.length,V,J,q,T,M,A,o,f0;if(!Q||!Q.state)return p;if(V=Q.state,T=V.wrap,T===2||T===1&&V.status!==N0||V.lookahead)return p;if(T===1)Q.adler=L(Q.adler,X,U,0);if(V.wrap=0,U>=V.w_size){if(T===0)w0(V.head),V.strstart=0,V.block_start=0,V.insert=0;f0=new g.Buf8(V.w_size),g.arraySet(f0,X,U-V.w_size,V.w_size,0),X=f0,U=V.w_size}M=Q.avail_in,A=Q.next_in,o=Q.input,Q.avail_in=U,Q.next_in=0,Q.input=X,S0(V);while(V.lookahead>=D){J=V.strstart,q=V.lookahead-(D-1);do V.ins_h=(V.ins_h<>>24,E>>>=z,S-=z,z=d>>>16&255,z===0)I[N++]=d&65535;else if(z&16){if(h=d&65535,z&=15,z){if(S>>=z,S-=z}if(S<15)E+=O[k++]<>>24,E>>>=z,S-=z,z=d>>>16&255,z&16){if(V0=d&65535,z&=15,Sp){C.msg="invalid distance too far back",v.mode=b;break Q}if(E>>>=z,S-=z,z=N-y,V0>z){if(z=V0-z,z>u){if(v.sane){C.msg="invalid distance too far back",v.mode=b;break Q}}if(j=0,K=W0,s===0){if(j+=t-z,z2)I[N++]=K[j++],I[N++]=K[j++],I[N++]=K[j++],h-=3;if(h){if(I[N++]=K[j++],h>1)I[N++]=K[j++]}}else{j=N-V0;do I[N++]=I[j++],I[N++]=I[j++],I[N++]=I[j++],h-=3;while(h>2);if(h){if(I[N++]=I[j++],h>1)I[N++]=I[j++]}}}else if((z&64)===0){d=G0[(d&65535)+(E&(1<>3,k-=h,S-=h<<3,E&=(1<=1;h--)if(X0[h]!==0)break;if(V0>h)V0=h;if(h===0)return E[S++]=1<<24|64<<16|0,E[S++]=1<<24|64<<16|0,G0.bits=1,0;for(z=1;z0&&(t===w||h!==1))return-1;U0[1]=0;for(f=1;fn||t===k&&I>C)return 1;for(;;){if(r=f-K,J0[d]K0)z0=a[Y0+J0[d]],Z0=N0[I0+J0[d]];else z0=96,Z0=0;l=1<>K)+D]=r<<24|z0<<16|Z0|0;while(D!==0);l=1<>=1;if(l!==0)c&=l-1,c+=l;else c=0;if(d++,--X0[f]===0){if(f===h)break;f=u[s+J0[d]]}if(f>V0&&(c&i)!==Q0){if(K===0)K=V0;H0+=z,j=f-K,O=1<n||t===k&&I>C)return 1;Q0=c&i,E[Q0]=V0<<24|j<<16|H0-S|0}}if(c!==0)E[H0+c]=f-K<<24|64<<16|0;return G0.bits=V0,0}}}),d1=A0({"node_modules/pako/lib/zlib/inflate.js"(Y){var g=r0(),b=Q1(),L=$1(),n=u1(),C=b1(),w=0,v=1,k=2,B=4,N=5,y=6,m=0,p=1,t=2,u=-2,s=-3,W0=-4,E=-5,S=8,J0=1,G0=2,F0=3,f=4,d=5,z=6,h=7,V0=8,j=9,K=10,O=11,I=12,c=13,l=14,D=15,Q0=16,i=17,H0=18,N0=19,I0=20,K0=21,X0=22,U0=23,a=24,Y0=25,r=26,z0=27,Z0=28,g0=29,j0=30,M0=31,c0=32,w0=852,v0=592,q0=15,_=q0;function T0(G){return(G>>>24&255)+(G>>>8&65280)+((G&65280)<<8)+((G&255)<<24)}function p0(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new g.Buf16(320),this.work=new g.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function b0(G){var P;if(!G||!G.state)return u;if(P=G.state,G.total_in=G.total_out=P.total=0,G.msg="",P.wrap)G.adler=P.wrap&1;return P.mode=J0,P.last=0,P.havedict=0,P.dmax=32768,P.head=null,P.hold=0,P.bits=0,P.lencode=P.lendyn=new g.Buf32(w0),P.distcode=P.distdyn=new g.Buf32(v0),P.sane=1,P.back=-1,m}function S0(G){var P;if(!G||!G.state)return u;return P=G.state,P.wsize=0,P.whave=0,P.wnext=0,b0(G)}function i0(G,P){var $,H;if(!G||!G.state)return u;if(H=G.state,P<0)$=0,P=-P;else if($=(P>>4)+1,P<48)P&=15;if(P&&(P<8||P>15))return u;if(H.window!==null&&H.wbits!==P)H.window=null;return H.wrap=$,H.wbits=P,S0(G)}function d0(G,P){var $,H;if(!G)return u;if(H=new p0,G.state=H,H.window=null,$=i0(G,P),$!==m)G.state=null;return $}function E0(G){return d0(G,_)}var _0=!0,m0,B0;function h0(G){if(_0){var P;m0=new g.Buf32(512),B0=new g.Buf32(32),P=0;while(P<144)G.lens[P++]=8;while(P<256)G.lens[P++]=9;while(P<280)G.lens[P++]=7;while(P<288)G.lens[P++]=8;C(v,G.lens,0,288,m0,0,G.work,{bits:9}),P=0;while(P<32)G.lens[P++]=5;C(k,G.lens,0,32,B0,0,G.work,{bits:5}),_0=!1}G.lencode=m0,G.lenbits=9,G.distcode=B0,G.distbits=5}function n0(G,P,$,H){var x,Q=G.state;if(Q.window===null)Q.wsize=1<=Q.wsize)g.arraySet(Q.window,P,$-Q.wsize,Q.wsize,0),Q.wnext=0,Q.whave=Q.wsize;else{if(x=Q.wsize-Q.wnext,x>H)x=H;if(g.arraySet(Q.window,P,$-H,x,Q.wnext),H-=x,H)g.arraySet(Q.window,P,$-H,H,0),Q.wnext=H,Q.whave=Q.wsize;else{if(Q.wnext+=x,Q.wnext===Q.wsize)Q.wnext=0;if(Q.whave>>8&255,$.check=L($.check,O0,2,0),J=0,q=0,$.mode=G0;break}if($.flags=0,$.head)$.head.done=!1;if(!($.wrap&1)||(((J&255)<<8)+(J>>8))%31){G.msg="incorrect header check",$.mode=j0;break}if((J&15)!==S){G.msg="unknown compression method",$.mode=j0;break}if(J>>>=4,q-=4,L0=(J&15)+8,$.wbits===0)$.wbits=L0;else if(L0>$.wbits){G.msg="invalid window size",$.mode=j0;break}$.dmax=1<>8&1;if($.flags&512)O0[0]=J&255,O0[1]=J>>>8&255,$.check=L($.check,O0,2,0);J=0,q=0,$.mode=F0;case F0:while(q<32){if(U===0)break Q;U--,J+=H[Q++]<>>8&255,O0[2]=J>>>16&255,O0[3]=J>>>24&255,$.check=L($.check,O0,4,0);J=0,q=0,$.mode=f;case f:while(q<16){if(U===0)break Q;U--,J+=H[Q++]<>8;if($.flags&512)O0[0]=J&255,O0[1]=J>>>8&255,$.check=L($.check,O0,2,0);J=0,q=0,$.mode=d;case d:if($.flags&1024){while(q<16){if(U===0)break Q;U--,J+=H[Q++]<>>8&255,$.check=L($.check,O0,2,0);J=0,q=0}else if($.head)$.head.extra=null;$.mode=z;case z:if($.flags&1024){if(A=$.length,A>U)A=U;if(A){if($.head){if(L0=$.head.extra_len-$.length,!$.head.extra)$.head.extra=new Array($.head.extra_len);g.arraySet($.head.extra,H,Q,A,L0)}if($.flags&512)$.check=L($.check,H,A,Q);U-=A,Q+=A,$.length-=A}if($.length)break Q}$.length=0,$.mode=h;case h:if($.flags&2048){if(U===0)break Q;A=0;do if(L0=H[Q+A++],$.head&&L0&&$.length<65536)$.head.name+=String.fromCharCode(L0);while(L0&&A>9&1,$.head.done=!0;G.adler=$.check=0,$.mode=I;break;case K:while(q<32){if(U===0)break Q;U--,J+=H[Q++]<>>=q&7,q-=q&7,$.mode=z0;break}while(q<3){if(U===0)break Q;U--,J+=H[Q++]<>>=1,q-=1,J&3){case 0:$.mode=l;break;case 1:if(h0($),$.mode=I0,P===y){J>>>=2,q-=2;break Q}break;case 2:$.mode=i;break;case 3:G.msg="invalid block type",$.mode=j0}J>>>=2,q-=2;break;case l:J>>>=q&7,q-=q&7;while(q<32){if(U===0)break Q;U--,J+=H[Q++]<>>16^65535)){G.msg="invalid stored block lengths",$.mode=j0;break}if($.length=J&65535,J=0,q=0,$.mode=D,P===y)break Q;case D:$.mode=Q0;case Q0:if(A=$.length,A){if(A>U)A=U;if(A>V)A=V;if(A===0)break Q;g.arraySet(x,H,Q,A,X),U-=A,Q+=A,V-=A,X+=A,$.length-=A;break}$.mode=I;break;case i:while(q<14){if(U===0)break Q;U--,J+=H[Q++]<>>=5,q-=5,$.ndist=(J&31)+1,J>>>=5,q-=5,$.ncode=(J&15)+4,J>>>=4,q-=4,$.nlen>286||$.ndist>30){G.msg="too many length or distance symbols",$.mode=j0;break}$.have=0,$.mode=H0;case H0:while($.have<$.ncode){while(q<3){if(U===0)break Q;U--,J+=H[Q++]<>>=3,q-=3}while($.have<19)$.lens[e0[$.have++]]=0;if($.lencode=$.lendyn,$.lenbits=7,u0={bits:$.lenbits},y0=C(w,$.lens,0,19,$.lencode,0,$.work,u0),$.lenbits=u0.bits,y0){G.msg="invalid code lengths set",$.mode=j0;break}$.have=0,$.mode=N0;case N0:while($.have<$.nlen+$.ndist){for(;;){if(P0=$.lencode[J&(1<<$.lenbits)-1],e=P0>>>24,C0=P0>>>16&255,D0=P0&65535,e<=q)break;if(U===0)break Q;U--,J+=H[Q++]<>>=e,q-=e,$.lens[$.have++]=D0;else{if(D0===16){x0=e+2;while(q>>=e,q-=e,$.have===0){G.msg="invalid bit length repeat",$.mode=j0;break}L0=$.lens[$.have-1],A=3+(J&3),J>>>=2,q-=2}else if(D0===17){x0=e+3;while(q>>=e,q-=e,L0=0,A=3+(J&7),J>>>=3,q-=3}else{x0=e+7;while(q>>=e,q-=e,L0=0,A=11+(J&127),J>>>=7,q-=7}if($.have+A>$.nlen+$.ndist){G.msg="invalid bit length repeat",$.mode=j0;break}while(A--)$.lens[$.have++]=L0}}if($.mode===j0)break;if($.lens[256]===0){G.msg="invalid code -- missing end-of-block",$.mode=j0;break}if($.lenbits=9,u0={bits:$.lenbits},y0=C(v,$.lens,0,$.nlen,$.lencode,0,$.work,u0),$.lenbits=u0.bits,y0){G.msg="invalid literal/lengths set",$.mode=j0;break}if($.distbits=6,$.distcode=$.distdyn,u0={bits:$.distbits},y0=C(k,$.lens,$.nlen,$.ndist,$.distcode,0,$.work,u0),$.distbits=u0.bits,y0){G.msg="invalid distances set",$.mode=j0;break}if($.mode=I0,P===y)break Q;case I0:$.mode=K0;case K0:if(U>=6&&V>=258){if(G.next_out=X,G.avail_out=V,G.next_in=Q,G.avail_in=U,$.hold=J,$.bits=q,n(G,M),X=G.next_out,x=G.output,V=G.avail_out,Q=G.next_in,H=G.input,U=G.avail_in,J=$.hold,q=$.bits,$.mode===I)$.back=-1;break}$.back=0;for(;;){if(P0=$.lencode[J&(1<<$.lenbits)-1],e=P0>>>24,C0=P0>>>16&255,D0=P0&65535,e<=q)break;if(U===0)break Q;U--,J+=H[Q++]<>k0)],e=P0>>>24,C0=P0>>>16&255,D0=P0&65535,k0+e<=q)break;if(U===0)break Q;U--,J+=H[Q++]<>>=k0,q-=k0,$.back+=k0}if(J>>>=e,q-=e,$.back+=e,$.length=D0,C0===0){$.mode=r;break}if(C0&32){$.back=-1,$.mode=I;break}if(C0&64){G.msg="invalid literal/length code",$.mode=j0;break}$.extra=C0&15,$.mode=X0;case X0:if($.extra){x0=$.extra;while(q>>=$.extra,q-=$.extra,$.back+=$.extra}$.was=$.length,$.mode=U0;case U0:for(;;){if(P0=$.distcode[J&(1<<$.distbits)-1],e=P0>>>24,C0=P0>>>16&255,D0=P0&65535,e<=q)break;if(U===0)break Q;U--,J+=H[Q++]<>k0)],e=P0>>>24,C0=P0>>>16&255,D0=P0&65535,k0+e<=q)break;if(U===0)break Q;U--,J+=H[Q++]<>>=k0,q-=k0,$.back+=k0}if(J>>>=e,q-=e,$.back+=e,C0&64){G.msg="invalid distance code",$.mode=j0;break}$.offset=D0,$.extra=C0&15,$.mode=a;case a:if($.extra){x0=$.extra;while(q>>=$.extra,q-=$.extra,$.back+=$.extra}if($.offset>$.dmax){G.msg="invalid distance too far back",$.mode=j0;break}$.mode=Y0;case Y0:if(V===0)break Q;if(A=M-V,$.offset>A){if(A=$.offset-A,A>$.whave){if($.sane){G.msg="invalid distance too far back",$.mode=j0;break}}if(A>$.wnext)A-=$.wnext,o=$.wsize-A;else o=$.wnext-A;if(A>$.length)A=$.length;f0=$.window}else f0=x,o=X-$.offset,A=$.length;if(A>V)A=V;V-=A,$.length-=A;do x[X++]=f0[o++];while(--A);if($.length===0)$.mode=K0;break;case r:if(V===0)break Q;x[X++]=$.length,V--,$.mode=K0;break;case z0:if($.wrap){while(q<32){if(U===0)break Q;U--,J|=H[Q++]<Y.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=B,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}k.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}if(this.pending_close=!1,R0(this.init_done,"close before init"),R0(this.mode<=Y.UNZIP),this.mode===Y.DEFLATE||this.mode===Y.GZIP||this.mode===Y.DEFLATERAW)b.deflateEnd(this.strm);else if(this.mode===Y.INFLATE||this.mode===Y.GUNZIP||this.mode===Y.INFLATERAW||this.mode===Y.UNZIP)L.inflateEnd(this.strm);this.mode=Y.NONE,this.dictionary=null},k.prototype.write=function(B,N,y,m,p,t,u){return this._write(!0,B,N,y,m,p,t,u)},k.prototype.writeSync=function(B,N,y,m,p,t,u){return this._write(!1,B,N,y,m,p,t,u)},k.prototype._write=function(B,N,y,m,p,t,u,s){if(R0.equal(arguments.length,8),R0(this.init_done,"write before init"),R0(this.mode!==Y.NONE,"already finalized"),R0.equal(!1,this.write_in_progress,"write already in progress"),R0.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,R0.equal(!1,N===void 0,"must provide flush value"),this.write_in_progress=!0,N!==Y.Z_NO_FLUSH&&N!==Y.Z_PARTIAL_FLUSH&&N!==Y.Z_SYNC_FLUSH&&N!==Y.Z_FULL_FLUSH&&N!==Y.Z_FINISH&&N!==Y.Z_BLOCK)throw new Error("Invalid flush value");if(y==null)y=Buffer.alloc(0),p=0,m=0;if(this.strm.avail_in=p,this.strm.input=y,this.strm.next_in=m,this.strm.avail_out=s,this.strm.output=t,this.strm.next_out=u,this.flush=N,!B){if(this._process(),this._checkError())return this._afterSync();return}var W0=this;return process.nextTick(function(){W0._process(),W0._after()}),this},k.prototype._afterSync=function(){var B=this.strm.avail_out,N=this.strm.avail_in;return this.write_in_progress=!1,[N,B]},k.prototype._process=function(){var B=null;switch(this.mode){case Y.DEFLATE:case Y.GZIP:case Y.DEFLATERAW:this.err=b.deflate(this.strm,this.flush);break;case Y.UNZIP:if(this.strm.avail_in>0)B=this.strm.next_in;switch(this.gzip_id_bytes_read){case 0:if(B===null)break;if(this.strm.input[B]===w){if(this.gzip_id_bytes_read=1,B++,this.strm.avail_in===1)break}else{this.mode=Y.INFLATE;break}case 1:if(B===null)break;if(this.strm.input[B]===v)this.gzip_id_bytes_read=2,this.mode=Y.GUNZIP;else this.mode=Y.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case Y.INFLATE:case Y.GUNZIP:case Y.INFLATERAW:if(this.err=L.inflate(this.strm,this.flush),this.err===Y.Z_NEED_DICT&&this.dictionary){if(this.err=L.inflateSetDictionary(this.strm,this.dictionary),this.err===Y.Z_OK)this.err=L.inflate(this.strm,this.flush);else if(this.err===Y.Z_DATA_ERROR)this.err=Y.Z_NEED_DICT}while(this.strm.avail_in>0&&this.mode===Y.GUNZIP&&this.err===Y.Z_STREAM_END&&this.strm.next_in[0]!==0)this.reset(),this.err=L.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}},k.prototype._checkError=function(){switch(this.err){case Y.Z_OK:case Y.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===Y.Z_FINISH)return this._error("unexpected end of file"),!1;break;case Y.Z_STREAM_END:break;case Y.Z_NEED_DICT:if(this.dictionary==null)this._error("Missing dictionary");else this._error("Bad dictionary");return!1;default:return this._error("Zlib error"),!1}return!0},k.prototype._after=function(){if(!this._checkError())return;var B=this.strm.avail_out,N=this.strm.avail_in;if(this.write_in_progress=!1,this.callback(N,B),this.pending_close)this.close()},k.prototype._error=function(B){if(this.strm.msg)B=this.strm.msg;if(this.onerror(B,this.err),this.write_in_progress=!1,this.pending_close)this.close()},k.prototype.init=function(B,N,y,m,p){R0(arguments.length===4||arguments.length===5,"init(windowBits, level, memLevel, strategy, [dictionary])"),R0(B>=8&&B<=15,"invalid windowBits"),R0(N>=-1&&N<=9,"invalid compression level"),R0(y>=1&&y<=9,"invalid memlevel"),R0(m===Y.Z_FILTERED||m===Y.Z_HUFFMAN_ONLY||m===Y.Z_RLE||m===Y.Z_FIXED||m===Y.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(N,B,y,m,p),this._setDictionary()},k.prototype.params=function(){throw new Error("deflateParams Not supported")},k.prototype.reset=function(){this._reset(),this._setDictionary()},k.prototype._init=function(B,N,y,m,p){if(this.level=B,this.windowBits=N,this.memLevel=y,this.strategy=m,this.flush=Y.Z_NO_FLUSH,this.err=Y.Z_OK,this.mode===Y.GZIP||this.mode===Y.GUNZIP)this.windowBits+=16;if(this.mode===Y.UNZIP)this.windowBits+=32;if(this.mode===Y.DEFLATERAW||this.mode===Y.INFLATERAW)this.windowBits=-1*this.windowBits;switch(this.strm=new g,this.mode){case Y.DEFLATE:case Y.GZIP:case Y.DEFLATERAW:this.err=b.deflateInit2(this.strm,this.level,Y.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case Y.INFLATE:case Y.GUNZIP:case Y.INFLATERAW:case Y.UNZIP:this.err=L.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}if(this.err!==Y.Z_OK)this._error("Init error");this.dictionary=p,this.write_in_progress=!1,this.init_done=!0},k.prototype._setDictionary=function(){if(this.dictionary==null)return;switch(this.err=Y.Z_OK,this.mode){case Y.DEFLATE:case Y.DEFLATERAW:this.err=b.deflateSetDictionary(this.strm,this.dictionary);break;default:break}if(this.err!==Y.Z_OK)this._error("Failed to set dictionary")},k.prototype._reset=function(){switch(this.err=Y.Z_OK,this.mode){case Y.DEFLATE:case Y.DEFLATERAW:case Y.GZIP:this.err=b.deflateReset(this.strm);break;case Y.INFLATE:case Y.INFLATERAW:case Y.GUNZIP:this.err=L.inflateReset(this.strm);break;default:break}if(this.err!==Y.Z_OK)this._error("Failed to reset stream")},Y.Zlib=k}}),c1=A0({"node_modules/browserify-zlib/lib/index.js"(Y){var g=o0.Buffer,b=s0.Transform,L=m1(),n=W1,C=t0.ok,w=o0.kMaxLength,v="Cannot create final Buffer. It would be larger than 0x"+w.toString(16)+" bytes";L.Z_MIN_WINDOWBITS=8,L.Z_MAX_WINDOWBITS=15,L.Z_DEFAULT_WINDOWBITS=15,L.Z_MIN_CHUNK=64,L.Z_MAX_CHUNK=Infinity,L.Z_DEFAULT_CHUNK=16384,L.Z_MIN_MEMLEVEL=1,L.Z_MAX_MEMLEVEL=9,L.Z_DEFAULT_MEMLEVEL=8,L.Z_MIN_LEVEL=-1,L.Z_MAX_LEVEL=9,L.Z_DEFAULT_LEVEL=L.Z_DEFAULT_COMPRESSION;var k=Object.keys(L);for(N=0;N=w)H0=new RangeError(v);else i=g.concat(I,c);I=[],j.close(),O(H0,i)}}function s(j,K){if(typeof K==="string")K=g.from(K);if(!g.isBuffer(K))throw new TypeError("Not a string or buffer");var O=j._finishFlushFlag;return j._processChunk(K,O)}function W0(j){if(!(this instanceof W0))return new W0(j);z.call(this,j,L.DEFLATE)}function E(j){if(!(this instanceof E))return new E(j);z.call(this,j,L.INFLATE)}function S(j){if(!(this instanceof S))return new S(j);z.call(this,j,L.GZIP)}function J0(j){if(!(this instanceof J0))return new J0(j);z.call(this,j,L.GUNZIP)}function G0(j){if(!(this instanceof G0))return new G0(j);z.call(this,j,L.DEFLATERAW)}function F0(j){if(!(this instanceof F0))return new F0(j);z.call(this,j,L.INFLATERAW)}function f(j){if(!(this instanceof f))return new f(j);z.call(this,j,L.UNZIP)}function d(j){return j===L.Z_NO_FLUSH||j===L.Z_PARTIAL_FLUSH||j===L.Z_SYNC_FLUSH||j===L.Z_FULL_FLUSH||j===L.Z_FINISH||j===L.Z_BLOCK}function z(j,K){var O=this;if(this._opts=j=j||{},this._chunkSize=j.chunkSize||Y.Z_DEFAULT_CHUNK,b.call(this,j),j.flush&&!d(j.flush))throw new Error("Invalid flush flag: "+j.flush);if(j.finishFlush&&!d(j.finishFlush))throw new Error("Invalid flush flag: "+j.finishFlush);if(this._flushFlag=j.flush||L.Z_NO_FLUSH,this._finishFlushFlag=typeof j.finishFlush!=="undefined"?j.finishFlush:L.Z_FINISH,j.chunkSize){if(j.chunkSizeY.Z_MAX_CHUNK)throw new Error("Invalid chunk size: "+j.chunkSize)}if(j.windowBits){if(j.windowBitsY.Z_MAX_WINDOWBITS)throw new Error("Invalid windowBits: "+j.windowBits)}if(j.level){if(j.levelY.Z_MAX_LEVEL)throw new Error("Invalid compression level: "+j.level)}if(j.memLevel){if(j.memLevelY.Z_MAX_MEMLEVEL)throw new Error("Invalid memLevel: "+j.memLevel)}if(j.strategy){if(j.strategy!=Y.Z_FILTERED&&j.strategy!=Y.Z_HUFFMAN_ONLY&&j.strategy!=Y.Z_RLE&&j.strategy!=Y.Z_FIXED&&j.strategy!=Y.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+j.strategy)}if(j.dictionary){if(!g.isBuffer(j.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance")}this._handle=new L.Zlib(K);var I=this;this._hadError=!1,this._handle.onerror=function(D,Q0){h(I),I._hadError=!0;var i=new Error(D);i.errno=Q0,i.code=Y.codes[Q0],I.emit("error",i)};var c=Y.Z_DEFAULT_COMPRESSION;if(typeof j.level==="number")c=j.level;var l=Y.Z_DEFAULT_STRATEGY;if(typeof j.strategy==="number")l=j.strategy;this._handle.init(j.windowBits||Y.Z_DEFAULT_WINDOWBITS,c,j.memLevel||Y.Z_DEFAULT_MEMLEVEL,l,j.dictionary),this._buffer=g.allocUnsafe(this._chunkSize),this._offset=0,this._level=c,this._strategy=l,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!O._handle},configurable:!0,enumerable:!0})}n.inherits(z,b),z.prototype.params=function(j,K,O){if(jY.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+j);if(K!=Y.Z_FILTERED&&K!=Y.Z_HUFFMAN_ONLY&&K!=Y.Z_RLE&&K!=Y.Z_FIXED&&K!=Y.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+K);if(this._level!==j||this._strategy!==K){var I=this;this.flush(L.Z_SYNC_FLUSH,function(){if(C(I._handle,"zlib binding closed"),I._handle.params(j,K),!I._hadError){if(I._level=j,I._strategy=K,O)O()}})}else process.nextTick(O)},z.prototype.reset=function(){return C(this._handle,"zlib binding closed"),this._handle.reset()},z.prototype._flush=function(j){this._transform(g.alloc(0),"",j)},z.prototype.flush=function(j,K){var O=this,I=this._writableState;if(typeof j==="function"||j===void 0&&!K)K=j,j=L.Z_FULL_FLUSH;if(I.ended){if(K)process.nextTick(K)}else if(I.ending){if(K)this.once("end",K)}else if(I.needDrain){if(K)this.once("drain",function(){return O.flush(j,K)})}else this._flushFlag=j,this.write(g.alloc(0),"",K)},z.prototype.close=function(j){h(this,j),process.nextTick(V0,this)};function h(j,K){if(K)process.nextTick(K);if(!j._handle)return;j._handle.close(),j._handle=null}function V0(j){j.emit("close")}z.prototype._transform=function(j,K,O){var I,c=this._writableState,l=c.ending||c.ended,D=l&&(!j||c.length===j.length);if(j!==null&&!g.isBuffer(j))return O(new Error("invalid input"));if(!this._handle)return O(new Error("zlib binding closed"));if(D)I=this._finishFlushFlag;else if(I=this._flushFlag,j.length>=c.length)this._flushFlag=this._opts.flush||L.Z_NO_FLUSH;this._processChunk(j,I,O)},z.prototype._processChunk=function(j,K,O){var I=j&&j.length,c=this._chunkSize-this._offset,l=0,D=this,Q0=typeof O==="function";if(!Q0){var i=[],H0=0,N0;this.on("error",function(a){N0=a}),C(this._handle,"zlib binding closed");do var I0=this._handle.writeSync(K,j,l,I,this._buffer,this._offset,c);while(!this._hadError&&U0(I0[0],I0[1]));if(this._hadError)throw N0;if(H0>=w)throw h(this),new RangeError(v);var K0=g.concat(i,H0);return h(this),K0}C(this._handle,"zlib binding closed");var X0=this._handle.write(K,j,l,I,this._buffer,this._offset,c);X0.buffer=j,X0.callback=U0;function U0(a,Y0){if(this)this.buffer=null,this.callback=null;if(D._hadError)return;var r=c-Y0;if(C(r>=0,"have should not go down"),r>0){var z0=D._buffer.slice(D._offset,D._offset+r);if(D._offset+=r,Q0)D.push(z0);else i.push(z0),H0+=z0.length}if(Y0===0||D._offset>=D._chunkSize)c=D._chunkSize,D._offset=0,D._buffer=g.allocUnsafe(D._chunkSize);if(Y0===0){if(l+=I-a,I=a,!Q0)return!0;var Z0=D._handle.write(K,j,l,I,D._buffer,D._offset,D._chunkSize);Z0.callback=U0,Z0.buffer=j;return}if(!Q0)return!1;O()}},n.inherits(W0,z),n.inherits(E,z),n.inherits(S,z),n.inherits(J0,z),n.inherits(G0,z),n.inherits(F0,z),n.inherits(f,z)}}),$0=c1();$0[Symbol.for("CommonJS")]=0;var a1=$0;j1=$0.Deflate;J1=$0.Inflate;Y1=$0.Gzip;G1=$0.Gunzip;q1=$0.DeflateRaw;X1=$0.InflateRaw;U1=$0.Unzip;P1=$0.createDeflate;K1=$0.createInflate;F1=$0.createDeflateRaw;H1=$0.createInflateRaw;z1=$0.createGzip;Z1=$0.createGunzip;L1=$0.createUnzip;C1=$0.deflate;N1=$0.deflateSync;I1=$0.gzip;O1=$0.gzipSync;B1=$0.deflateRaw;D1=$0.deflateRawSync;M1=$0.unzip;k1=$0.unzipSync;v1=$0.inflate;R1=$0.inflateSync;A1=$0.gunzip;g1=$0.gunzipSync;w1=$0.inflateRaw;T1=$0.inflateRawSync;S1=$0.constants;export{k1 as unzipSync,M1 as unzip,R1 as inflateSync,T1 as inflateRawSync,w1 as inflateRaw,v1 as inflate,O1 as gzipSync,I1 as gzip,g1 as gunzipSync,A1 as gunzip,N1 as deflateSync,D1 as deflateRawSync,B1 as deflateRaw,C1 as deflate,a1 as default,L1 as createUnzip,H1 as createInflateRaw,K1 as createInflate,z1 as createGzip,Z1 as createGunzip,F1 as createDeflateRaw,P1 as createDeflate,S1 as constants,U1 as Unzip,X1 as InflateRaw,J1 as Inflate,Y1 as Gzip,G1 as Gunzip,q1 as DeflateRaw,j1 as Deflate}; diff --git a/src/js/out/modules/thirdparty/depd.js b/src/js/out/modules/thirdparty/depd.js deleted file mode 100644 index 6118e8cf1b282b..00000000000000 --- a/src/js/out/modules/thirdparty/depd.js +++ /dev/null @@ -1,23 +0,0 @@ -var depd2 = function(namespace) { - if (!namespace) - throw new TypeError("argument namespace is required"); - function deprecate(message) { - } - return deprecate._file = void 0, deprecate._ignored = !0, deprecate._namespace = namespace, deprecate._traced = !1, deprecate._warned = Object.create(null), deprecate.function = wrapfunction, deprecate.property = wrapproperty, deprecate; -}, wrapfunction = function(fn, message) { - if (typeof fn !== "function") - throw new TypeError("argument fn must be a function"); - return fn; -}, wrapproperty = function(obj, prop, message) { - if (!obj || typeof obj !== "object" && typeof obj !== "function") - throw new TypeError("argument obj must be object"); - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - if (!descriptor) - throw new TypeError("must call property on owner object"); - if (!descriptor.configurable) - throw new TypeError("property must be configurable"); -}, depd_default = depd2; -depd2[Symbol.for("CommonJS")] = 0; -export { - depd_default as default -}; diff --git a/src/js/out/modules/thirdparty/detect-libc.js b/src/js/out/modules/thirdparty/detect-libc.js deleted file mode 100644 index 1c4e18a7a3a261..00000000000000 --- a/src/js/out/modules/thirdparty/detect-libc.js +++ /dev/null @@ -1,29 +0,0 @@ -function family() { - return Promise.resolve(familySync()); -} -function familySync() { - return null; -} -function versionAsync() { - return Promise.resolve(version()); -} -function version() { - return null; -} -function isNonGlibcLinuxSync() { - return !1; -} -function isNonGlibcLinux() { - return Promise.resolve(isNonGlibcLinuxSync()); -} -var GLIBC = "glibc", MUSL = "musl"; -export { - versionAsync, - version, - isNonGlibcLinuxSync, - isNonGlibcLinux, - familySync, - family, - MUSL, - GLIBC -}; diff --git a/src/js/out/modules/thirdparty/detect-libc.linux.js b/src/js/out/modules/thirdparty/detect-libc.linux.js deleted file mode 100644 index 1c4e18a7a3a261..00000000000000 --- a/src/js/out/modules/thirdparty/detect-libc.linux.js +++ /dev/null @@ -1,29 +0,0 @@ -function family() { - return Promise.resolve(familySync()); -} -function familySync() { - return null; -} -function versionAsync() { - return Promise.resolve(version()); -} -function version() { - return null; -} -function isNonGlibcLinuxSync() { - return !1; -} -function isNonGlibcLinux() { - return Promise.resolve(isNonGlibcLinuxSync()); -} -var GLIBC = "glibc", MUSL = "musl"; -export { - versionAsync, - version, - isNonGlibcLinuxSync, - isNonGlibcLinux, - familySync, - family, - MUSL, - GLIBC -}; diff --git a/src/js/out/modules/thirdparty/undici.js b/src/js/out/modules/thirdparty/undici.js deleted file mode 100644 index 20dec6158f0e16..00000000000000 --- a/src/js/out/modules/thirdparty/undici.js +++ /dev/null @@ -1,231 +0,0 @@ -import {EventEmitter} from "node:events"; -import NodeStreamModule from "node:stream"; -import {Readable} from "node:stream"; -var notImplemented = function() { - throw new Error("Not implemented in bun"); -}; -async function request(url, options = { - method: "GET", - signal: null, - headers: null, - query: null, - reset: !1, - throwOnError: !1, - body: null -}) { - let { - method = "GET", - headers: inputHeaders, - query, - signal, - reset = !1, - throwOnError = !1, - body: inputBody, - maxRedirections - } = options; - if (typeof url === "string") { - if (query) - url = new URL(url); - } else if (typeof url === "object" && url !== null) { - if (!(url instanceof URL)) - throw new Error("not implemented"); - } else - throw new TypeError("url must be a string, URL, or UrlObject"); - if (typeof url === "string" && query) - url = new URL(url); - if (typeof url === "object" && url !== null && query) { - if (query) - url.search = new URLSearchParams(query).toString(); - } - if (method = method && typeof method === "string" ? method.toUpperCase() : null, inputBody && (method === "GET" || method === "HEAD")) - throw new Error("Body not allowed for GET or HEAD requests"); - if (inputBody && inputBody.read && inputBody instanceof Readable) { - let data = ""; - inputBody.setEncoding("utf8"); - for await (let chunk of stream) - data += chunk; - inputBody = (new TextEncoder()).encode(data); - } - if (maxRedirections !== void 0 && Number.isNaN(maxRedirections)) - throw new Error("maxRedirections must be a number if defined"); - if (signal && !(signal instanceof AbortSignal)) - throw new Error("signal must be an instance of AbortSignal"); - let resp; - const { - status: statusCode, - headers, - trailers - } = resp = await fetch(url, { - signal, - mode: "cors", - method, - headers: inputHeaders || kEmptyObject, - body: inputBody, - redirect: maxRedirections === "undefined" || maxRedirections > 0 ? "follow" : "manual", - keepalive: !reset - }); - if (throwOnError && statusCode >= 400 && statusCode < 600) - throw new Error(`Request failed with status code ${statusCode}`); - const body = resp.body ? new BodyReadable(resp) : null; - return { statusCode, headers: headers.toJSON(), body, trailers, opaque: kEmptyObject, context: kEmptyObject }; -} -var stream = function() { - throw new Error("Not implemented in bun"); -}, pipeline = function() { - throw new Error("Not implemented in bun"); -}, connect = function() { - throw new Error("Not implemented in bun"); -}, upgrade = function() { - throw new Error("Not implemented in bun"); -}, mockErrors = function() { - throw new Error("Not implemented in bun"); -}; -function Undici() { - throw new Error("Not implemented in bun"); -} -var { Object } = globalThis[Symbol.for("Bun.lazy")]("primordials"), { _ReadableFromWebForUndici: ReadableFromWeb } = NodeStreamModule[Symbol.for("::bunternal::")], ObjectCreate = Object.create, kEmptyObject = ObjectCreate(null), fetch = Bun.fetch, Response = globalThis.Response, Headers = globalThis.Headers, Request = globalThis.Request, URLSearchParams = globalThis.URLSearchParams, URL = globalThis.URL; - -class File extends Blob { -} - -class FileReader extends EventTarget { - constructor() { - throw new Error("Not implemented yet!"); - } -} -var FormData = globalThis.FormData; - -class BodyReadable extends ReadableFromWeb { - #response; - #bodyUsed; - constructor(response, options = {}) { - var { body } = response; - if (!body) - throw new Error("Response body is null"); - super(options, body); - this.#response = response, this.#bodyUsed = response.bodyUsed; - } - get bodyUsed() { - return this.#bodyUsed; - } - #consume() { - if (this.#bodyUsed) - throw new TypeError("unusable"); - this.#bodyUsed = !0; - } - async arrayBuffer() { - return this.#consume(), await this.#response.arrayBuffer(); - } - async blob() { - return this.#consume(), await this.#response.blob(); - } - async formData() { - return this.#consume(), await this.#response.formData(); - } - async json() { - return this.#consume(), await this.#response.json(); - } - async text() { - return this.#consume(), await this.#response.text(); - } -} - -class MockClient { - constructor() { - throw new Error("Not implemented in bun"); - } -} - -class MockPool { - constructor() { - throw new Error("Not implemented in bun"); - } -} - -class MockAgent { - constructor() { - throw new Error("Not implemented in bun"); - } -} - -class Dispatcher extends EventEmitter { -} - -class Agent extends Dispatcher { -} - -class Pool extends Dispatcher { - request() { - throw new Error("Not implemented in bun"); - } -} - -class BalancedPool extends Dispatcher { -} - -class Client extends Dispatcher { - request() { - throw new Error("Not implemented in bun"); - } -} -Undici.Dispatcher = Dispatcher; -Undici.Pool = Pool; -Undici.BalancedPool = BalancedPool; -Undici.Client = Client; -Undici.Agent = Agent; -Undici.buildConnector = Undici.errors = Undici.setGlobalDispatcher = Undici.getGlobalDispatcher = Undici.request = Undici.stream = Undici.pipeline = Undici.connect = Undici.upgrade = Undici.MockClient = Undici.MockPool = Undici.MockAgent = Undici.mockErrors = notImplemented; -Undici.fetch = fetch; -var undici_default = { - fetch, - Response, - Headers, - Request, - URLSearchParams, - URL, - File, - FileReader, - FormData, - request, - stream, - pipeline, - connect, - upgrade, - MockClient, - MockPool, - MockAgent, - mockErrors, - Dispatcher, - Pool, - BalancedPool, - Client, - Agent, - Undici, - [Symbol.for("CommonJS")]: 0 -}; -export { - upgrade, - stream, - request, - pipeline, - mockErrors, - fetch, - undici_default as default, - connect, - Undici, - URLSearchParams, - URL, - Response, - Request, - Pool, - MockPool, - MockClient, - MockAgent, - Headers, - FormData, - FileReader, - File, - Dispatcher, - Client, - BalancedPool, - Agent -}; diff --git a/src/js/out/modules/thirdparty/ws.js b/src/js/out/modules/thirdparty/ws.js deleted file mode 100644 index a30a4c688e7329..00000000000000 --- a/src/js/out/modules/thirdparty/ws.js +++ /dev/null @@ -1,734 +0,0 @@ -import {EventEmitter} from "node:events"; -import http from "node:http"; -var emitWarning = function(type, message) { - if (emittedWarnings.has(type)) - return; - emittedWarnings.add(type), console.warn("[bun] Warning:", message); -}, subprotocolParse = function(header) { - const protocols = new Set; - let start = -1, end = -1, i = 0; - for (i;i < header.length; i++) { - const code = header.charCodeAt(i); - if (end === -1 && wsTokenChars[code] === 1) { - if (start === -1) - start = i; - } else if (i !== 0 && (code === 32 || code === 9)) { - if (end === -1 && start !== -1) - end = i; - } else if (code === 44) { - if (start === -1) - throw new SyntaxError(`Unexpected character at index ${i}`); - if (end === -1) - end = i; - const protocol2 = header.slice(start, end); - if (protocols.has(protocol2)) - throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); - protocols.add(protocol2), start = end = -1; - } else - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (start === -1 || end !== -1) - throw new SyntaxError("Unexpected end of input"); - const protocol = header.slice(start, i); - if (protocols.has(protocol)) - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - return protocols.add(protocol), protocols; -}, wsEmitClose = function(server) { - server._state = CLOSED, server.emit("close"); -}, abortHandshake = function(response, code, message, headers) { - message = message || http.STATUS_CODES[code], headers = { - Connection: "close", - "Content-Type": "text/html", - "Content-Length": Buffer.byteLength(message), - ...headers - }, response.writeHead(code, headers), response.write(message), response.end(); -}, abortHandshakeOrEmitwsClientError = function(server, req, response, socket, code, message) { - if (server.listenerCount("wsClientError")) { - const err = new Error(message); - Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError), server.emit("wsClientError", err, socket, req); - } else - abortHandshake(response, code, message); -}, kBunInternals = Symbol.for("::bunternal::"), readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"], encoder = new TextEncoder, eventIds = { - open: 1, - close: 2, - message: 3, - error: 4, - ping: 5, - pong: 6 -}, emittedWarnings = new Set; - -class BunWebSocket extends EventEmitter { - static CONNECTING = 0; - static OPEN = 1; - static CLOSING = 2; - static CLOSED = 3; - #ws; - #paused = !1; - #fragments = !1; - #binaryType = "nodebuffer"; - #eventId = 0; - constructor(url, protocols, options) { - super(); - let ws = this.#ws = new WebSocket(url, protocols); - ws.binaryType = "nodebuffer"; - } - on(event, listener) { - if (event === "unexpected-response" || event === "upgrade" || event === "redirect") - emitWarning(event, "ws.WebSocket '" + event + "' event is not implemented in bun"); - const mask = 1 << eventIds[event]; - if (mask && (this.#eventId & mask) !== mask) { - if (this.#eventId |= mask, event === "open") - this.#ws.addEventListener("open", () => { - this.emit("open"); - }); - else if (event === "close") - this.#ws.addEventListener("close", ({ code, reason, wasClean }) => { - this.emit("close", code, reason, wasClean); - }); - else if (event === "message") - this.#ws.addEventListener("message", ({ data }) => { - const isBinary = typeof data !== "string"; - if (isBinary) - this.emit("message", this.#fragments ? [data] : data, isBinary); - else { - let encoded = encoder.encode(data); - if (this.#binaryType !== "arraybuffer") - encoded = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength); - this.emit("message", this.#fragments ? [encoded] : encoded, isBinary); - } - }); - else if (event === "error") - this.#ws.addEventListener("error", (err) => { - this.emit("error", err); - }); - else if (event === "ping") - this.#ws.addEventListener("ping", ({ data }) => { - this.emit("ping", data); - }); - else if (event === "pong") - this.#ws.addEventListener("pong", ({ data }) => { - this.emit("pong", data); - }); - } - return super.on(event, listener); - } - send(data, opts, cb) { - try { - this.#ws.send(data, opts?.compress); - } catch (error) { - typeof cb === "function" && cb(error); - return; - } - typeof cb === "function" && cb(); - } - close(code, reason) { - this.#ws.close(code, reason); - } - terminate() { - this.#ws.terminate(); - } - get url() { - return this.#ws.url; - } - get readyState() { - return this.#ws.readyState; - } - get binaryType() { - return this.#binaryType; - } - set binaryType(value) { - if (value === "nodebuffer" || value === "arraybuffer") - this.#ws.binaryType = this.#binaryType = value, this.#fragments = !1; - else if (value === "fragments") - this.#ws.binaryType = "nodebuffer", this.#binaryType = "fragments", this.#fragments = !0; - else - throw new Error(`Invalid binaryType: ${value}`); - } - get protocol() { - return this.#ws.protocol; - } - get extensions() { - return this.#ws.extensions; - } - addEventListener(type, listener, options) { - this.#ws.addEventListener(type, listener, options); - } - removeEventListener(type, listener) { - this.#ws.removeEventListener(type, listener); - } - get onopen() { - return this.#ws.onopen; - } - set onopen(value) { - this.#ws.onopen = value; - } - get onerror() { - return this.#ws.onerror; - } - set onerror(value) { - this.#ws.onerror = value; - } - get onclose() { - return this.#ws.onclose; - } - set onclose(value) { - this.#ws.onclose = value; - } - get onmessage() { - return this.#ws.onmessage; - } - set onmessage(value) { - this.#ws.onmessage = value; - } - get bufferedAmount() { - return this.#ws.bufferedAmount; - } - get isPaused() { - return this.#paused; - } - ping(data, mask, cb) { - if (typeof data === "function") - cb = data, data = mask = void 0; - else if (typeof mask === "function") - cb = mask, mask = void 0; - if (typeof data === "number") - data = data.toString(); - try { - this.#ws.ping(data); - } catch (error) { - typeof cb === "function" && cb(error); - return; - } - typeof cb === "function" && cb(); - } - pong(data, mask, cb) { - if (typeof data === "function") - cb = data, data = mask = void 0; - else if (typeof mask === "function") - cb = mask, mask = void 0; - if (typeof data === "number") - data = data.toString(); - try { - this.#ws.pong(data); - } catch (error) { - typeof cb === "function" && cb(error); - return; - } - typeof cb === "function" && cb(); - } - pause() { - switch (this.readyState) { - case WebSocket.CONNECTING: - case WebSocket.CLOSED: - return; - } - this.#paused = !0, emitWarning("pause()", "ws.WebSocket.pause() is not implemented in bun"); - } - resume() { - switch (this.readyState) { - case WebSocket.CONNECTING: - case WebSocket.CLOSED: - return; - } - this.#paused = !1, emitWarning("resume()", "ws.WebSocket.resume() is not implemented in bun"); - } -} -BunWebSocket.WebSocket = BunWebSocket; -var wsKeyRegex = /^[+/0-9A-Za-z]{22}==$/, wsTokenChars = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 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, - 0, - 0, - 0, - 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, - 0, - 1, - 0, - 1, - 0 -], RUNNING = 0, CLOSING = 1, CLOSED = 2; - -class BunWebSocketMocked extends EventEmitter { - #ws; - #state; - #enquedMessages = []; - #url; - #protocol; - #extensions; - #bufferedAmount = 0; - #binaryType = "arraybuffer"; - #onclose; - #onerror; - #onmessage; - #onopen; - constructor(url, protocol, extensions, binaryType) { - super(); - if (this.#ws = null, this.#state = 0, this.#url = url, this.#bufferedAmount = 0, binaryType = binaryType || "arraybuffer", binaryType !== "nodebuffer" && binaryType !== "blob" && binaryType !== "arraybuffer") - throw new TypeError("binaryType must be either 'blob', 'arraybuffer' or 'nodebuffer'"); - this.#binaryType = binaryType, this.#protocol = protocol, this.#extensions = extensions; - const message = this.#message.bind(this), open = this.#open.bind(this), close = this.#close.bind(this), drain = this.#drain.bind(this); - this[kBunInternals] = { - message, - open, - close, - drain - }; - } - #message(ws, message) { - if (this.#ws = ws, typeof message === "string") - if (this.#binaryType === "arraybuffer") - message = encoder.encode(message).buffer; - else if (this.#binaryType === "blob") - message = new Blob([message], { type: "text/plain" }); - else - message = Buffer.from(message); - else if (this.#binaryType !== "nodebuffer") { - if (this.#binaryType === "arraybuffer") - message = new Uint8Array(message); - else if (this.#binaryType === "blob") - message = new Blob([message]); - } - this.emit("message", message); - } - #open(ws) { - this.#ws = ws, this.#state = 1, this.emit("open", this), this.#drain(ws); - } - #close(ws, code, reason) { - this.#state = 3, this.#ws = null, this.emit("close", code, reason); - } - #drain(ws) { - const chunk = this.#enquedMessages[0]; - if (chunk) { - const [data, compress, cb] = chunk; - if (ws.send(data, compress) == -1) - return; - typeof cb === "function" && cb(), this.#bufferedAmount -= chunk.length, this.#enquedMessages.shift(); - } - } - send(data, opts, cb) { - if (this.#state === 1) { - const compress = opts?.compress; - if (this.#ws.send(data, compress) == -1) { - this.#enquedMessages.push([data, compress, cb]), this.#bufferedAmount += data.length; - return; - } - typeof cb === "function" && cb(); - } else if (this.#state === 0) - this.#enquedMessages.push([data, opts?.compress, cb]), this.#bufferedAmount += data.length; - } - close(code, reason) { - if (this.#state === 1) - this.#state = 2, this.#ws.close(code, reason); - } - get binaryType() { - return this.#binaryType; - } - set binaryType(type) { - if (type !== "nodebuffer" && type !== "blob" && type !== "arraybuffer") - throw new TypeError("binaryType must be either 'blob', 'arraybuffer' or 'nodebuffer'"); - this.#binaryType = type; - } - get readyState() { - return this.#state; - } - get url() { - return this.#url; - } - get protocol() { - return this.#protocol; - } - get extensions() { - return this.#extensions; - } - get bufferedAmount() { - return this.#bufferedAmount ?? 0; - } - setSocket(socket, head, options) { - throw new Error("Not implemented"); - } - set onclose(cb) { - if (this.#onclose) - this.removeListener("close", this.#onclose); - this.on("close", cb), this.#onclose = cb; - } - set onerror(cb) { - if (this.#onerror) - this.removeListener("error", this.#onerror); - this.on("error", cb), this.#onerror = cb; - } - set onmessage(cb) { - if (this.#onmessage) - this.removeListener("message", this.#onmessage); - this.on("message", cb), this.#onmessage = cb; - } - set onopen(cb) { - if (this.#onopen) - this.removeListener("open", this.#onopen); - this.on("open", cb), this.#onopen = cb; - } - get onclose() { - return this.#onclose; - } - get onerror() { - return this.#onerror; - } - get onmessage() { - return this.#onmessage; - } - get onopen() { - return this.#onopen; - } -} - -class Server extends EventEmitter { - _server; - options; - clients; - _shouldEmitClose; - _state; - _removeListeners; - constructor(options, callback) { - super(); - if (options = { - maxPayload: 104857600, - skipUTF8Validation: !1, - perMessageDeflate: !1, - handleProtocols: null, - clientTracking: !0, - verifyClient: null, - noServer: !1, - backlog: null, - server: null, - host: null, - path: null, - port: null, - ...options - }, options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) - throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified'); - if (options.port != null) - this._server = http.createServer((req, res) => { - const body = http.STATUS_CODES[426]; - res.writeHead(426, { - "Content-Length": body.length, - "Content-Type": "text/plain" - }), res.end(body); - }), this._server.listen(options.port, options.host, options.backlog, callback); - else if (options.server) - this._server = options.server; - if (this._server) { - const emitConnection = this.emit.bind(this, "connection"), emitListening = this.emit.bind(this, "listening"), emitError = this.emit.bind(this, "error"), doUpgrade = (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - }; - this._server.on("listening", emitListening), this._server.on("error", emitError), this._server.on("upgrade", doUpgrade), this._removeListeners = () => { - this._server.removeListener("upgrade", doUpgrade), this._server.removeListener("listening", emitListening), this._server.removeListener("error", emitError); - }; - } - if (options.perMessageDeflate === !0) - options.perMessageDeflate = {}; - if (options.clientTracking) - this.clients = new Set, this._shouldEmitClose = !1; - this.options = options, this._state = RUNNING; - } - address() { - if (this.options.noServer) - throw new Error('The server is operating in "noServer" mode'); - if (!this._server) - return null; - return this._server.address(); - } - close(cb) { - if (this._state === CLOSED) { - if (cb) - this.once("close", () => { - cb(new Error("The server is not running")); - }); - process.nextTick((server) => { - server._state = CLOSED, server.emit("close"); - }, this); - return; - } - if (cb) - this.once("close", cb); - if (this._state === CLOSING) - return; - if (this._state = CLOSING, this.options.noServer || this.options.server) { - if (this._server) - this._removeListeners(), this._removeListeners = this._server = null; - if (this.clients) - if (!this.clients.size) - process.nextTick((server) => { - server._state = CLOSED, server.emit("close"); - }, this); - else - this._shouldEmitClose = !0; - else - process.nextTick((server) => { - server._state = CLOSED, server.emit("close"); - }, this); - } else { - const server = this._server; - this._removeListeners(), this._removeListeners = this._server = null, server.close(() => { - this._state = CLOSED, this.emit("close"); - }); - } - } - shouldHandle(req) { - if (this.options.path) { - const index = req.url.indexOf("?"); - if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) - return !1; - } - return !0; - } - completeUpgrade(extensions, key, protocols, request, socket, head, cb) { - const [server, response, req] = socket[kBunInternals]; - if (this._state > RUNNING) - return abortHandshake(response, 503); - let protocol = ""; - if (protocols.size) - protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, request) : protocols.values().next().value; - const ws = new BunWebSocketMocked(request.url, protocol, extensions, "nodebuffer"), headers = ["HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade"]; - if (this.emit("headers", headers, request), server.upgrade(req, { - data: ws[kBunInternals] - })) { - if (response._reply(void 0), this.clients) - this.clients.add(ws), ws.on("close", () => { - if (this.clients.delete(ws), this._shouldEmitClose && !this.clients.size) - process.nextTick(wsEmitClose, this); - }); - cb(ws, request); - } else - abortHandshake(response, 500); - } - handleUpgrade(req, socket, head, cb) { - const [_, response] = socket[kBunInternals], key = req.headers["sec-websocket-key"], version = +req.headers["sec-websocket-version"]; - if (req.method !== "GET") { - abortHandshakeOrEmitwsClientError(this, req, response, socket, 405, "Invalid HTTP method"); - return; - } - if (req.headers.upgrade.toLowerCase() !== "websocket") { - abortHandshakeOrEmitwsClientError(this, req, response, socket, 400, "Invalid Upgrade header"); - return; - } - if (!key || !wsKeyRegex.test(key)) { - abortHandshakeOrEmitwsClientError(this, req, response, socket, 400, "Missing or invalid Sec-WebSocket-Key header"); - return; - } - if (version !== 8 && version !== 13) { - abortHandshakeOrEmitwsClientError(this, req, response, socket, 400, "Missing or invalid Sec-WebSocket-Version header"); - return; - } - if (!this.shouldHandle(req)) { - abortHandshake(response, 400); - return; - } - const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; - let protocols = new Set; - if (secWebSocketProtocol !== void 0) - try { - protocols = subprotocolParse(secWebSocketProtocol); - } catch (err) { - abortHandshakeOrEmitwsClientError(this, req, response, socket, 400, "Invalid Sec-WebSocket-Protocol header"); - return; - } - const extensions = {}; - if (this.options.verifyClient) { - const info = { - origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info, (verified, code, message, headers) => { - if (!verified) - return abortHandshake(response, code || 401, message, headers); - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - }); - return; - } - if (!this.options.verifyClient(info)) - return abortHandshake(response, 401); - } - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - } -} -BunWebSocket.WebSocketServer = Server; -BunWebSocket.Server = Server; -Object.defineProperty(BunWebSocket, "CONNECTING", { - enumerable: !0, - value: readyStates.indexOf("CONNECTING") -}); -Object.defineProperty(BunWebSocket.prototype, "CONNECTING", { - enumerable: !0, - value: readyStates.indexOf("CONNECTING") -}); -Object.defineProperty(BunWebSocket, "OPEN", { - enumerable: !0, - value: readyStates.indexOf("OPEN") -}); -Object.defineProperty(BunWebSocket.prototype, "OPEN", { - enumerable: !0, - value: readyStates.indexOf("OPEN") -}); -Object.defineProperty(BunWebSocket, "CLOSING", { - enumerable: !0, - value: readyStates.indexOf("CLOSING") -}); -Object.defineProperty(BunWebSocket.prototype, "CLOSING", { - enumerable: !0, - value: readyStates.indexOf("CLOSING") -}); -Object.defineProperty(BunWebSocket, "CLOSED", { - enumerable: !0, - value: readyStates.indexOf("CLOSED") -}); -Object.defineProperty(BunWebSocket.prototype, "CLOSED", { - enumerable: !0, - value: readyStates.indexOf("CLOSED") -}); - -class Sender { - constructor() { - throw new Error("Not supported yet in Bun"); - } -} -BunWebSocket.Sender = Sender; - -class Receiver { - constructor() { - throw new Error("Not supported yet in Bun"); - } -} -BunWebSocket.Receiver = Receiver; -var createWebSocketStream = (ws) => { - throw new Error("Not supported yet in Bun"); -}; -BunWebSocket.createWebSocketStream = createWebSocketStream; -BunWebSocket[Symbol.for("CommonJS")] = 0; -var ws_default = BunWebSocket; -export { - ws_default as default, - createWebSocketStream, - Server as WebSocketServer, - BunWebSocket as WebSocket, - Server, - Sender, - Receiver -}; diff --git a/src/js/private.d.ts b/src/js/private.d.ts index eae2047fb8385b..2667df6311c4a5 100644 --- a/src/js/private.d.ts +++ b/src/js/private.d.ts @@ -95,7 +95,7 @@ declare module "bun" { }; function fs(): BunFS; function _Os(): typeof import("node:os"); - function _Path(isWindows?: boolean): typeof import("node:path"); + function _Path(isWin32?: boolean): typeof import("node:path"); function jest(): typeof import("bun:test"); var main: string; var tty: Array<{ hasColors: boolean }>; @@ -129,6 +129,7 @@ interface LoaderEntry { evaluated: boolean; then?: any; isAsync: boolean; + isSatisfied: boolean; } interface LoaderModule { @@ -145,7 +146,6 @@ declare interface Error { * This is only valid in src/js/ as it is replaced with `globalThis[Symbol.for("Bun.lazy")]` at bundle time. */ function $lazy(id: T): BunLazyModules[T]; -function $lazy(id: "createImportMeta", from: string): BunLazyModules[T]; interface BunLazyModules { /** @@ -193,9 +193,18 @@ interface BunLazyModules { set: typeof import("./builtins/AsyncContext").setAsyncContext; cleanupLater: () => void; }; + "worker_threads": [ + // + workerData: any, + threadId: number, + _receiveMessageOnPort: (port: MessagePort) => any, + ]; // ReadableStream related [1]: any; [2]: any; [4]: any; } + +/** Assign to this variable in src/js/{bun,node,thirdparty} to act as module.exports */ +declare var $exports: any; diff --git a/src/js/thirdparty/depd.js b/src/js/thirdparty/depd.js index 2da8901bc73fe2..9279253ef90f65 100644 --- a/src/js/thirdparty/depd.js +++ b/src/js/thirdparty/depd.js @@ -1,4 +1,4 @@ -function depd2(namespace) { +export default function depd(namespace) { if (!namespace) { throw new TypeError("argument namespace is required"); } @@ -30,6 +30,3 @@ function wrapproperty(obj, prop, message) { throw new TypeError("property must be configurable"); } } - -export default depd2; -depd2[Symbol.for("CommonJS")] = 0; diff --git a/src/js/thirdparty/detect-libc.js b/src/js/thirdparty/detect-libc.js index 514a765363471f..1a6f97e79698ca 100644 --- a/src/js/thirdparty/detect-libc.js +++ b/src/js/thirdparty/detect-libc.js @@ -1,27 +1,38 @@ // Hardcoded module "detect-libc" for darwin -export function family() { +function family() { return Promise.resolve(familySync()); } -export function familySync() { +function familySync() { return null; } -export const GLIBC = "glibc"; -export const MUSL = "musl"; +const GLIBC = "glibc"; +const MUSL = "musl"; -export function versionAsync() { +function versionAsync() { return Promise.resolve(version()); } -export function version() { +function version() { return null; } -export function isNonGlibcLinuxSync() { +function isNonGlibcLinuxSync() { return false; } -export function isNonGlibcLinux() { +function isNonGlibcLinux() { return Promise.resolve(isNonGlibcLinuxSync()); } + +export default { + GLIBC, + MUSL, + family, + familySync, + isNonGlibcLinux, + isNonGlibcLinuxSync, + version, + versionAsync, +}; diff --git a/src/js/thirdparty/detect-libc.linux.js b/src/js/thirdparty/detect-libc.linux.js index 4c65572470cc04..2866b18c0dc104 100644 --- a/src/js/thirdparty/detect-libc.linux.js +++ b/src/js/thirdparty/detect-libc.linux.js @@ -1,35 +1,38 @@ // Hardcoded module "detect-libc" for linux -export function family() { +function family() { return Promise.resolve(familySync()); } -export function familySync() { - if (process.platform === "linux") { - return GLIBC; - } else { - return null; - } +function familySync() { + return GLIBC; } -export const GLIBC = "glibc"; -export const MUSL = "musl"; +const GLIBC = "glibc"; +const MUSL = "musl"; -export function versionAsync() { +function versionAsync() { return Promise.resolve(version()); } -export function version() { - if (process.platform === "linux") { - return "2.29"; - } else { - return null; - } +function version() { + return "2.29"; } -export function isNonGlibcLinuxSync() { +function isNonGlibcLinuxSync() { return false; } -export function isNonGlibcLinux() { +function isNonGlibcLinux() { return Promise.resolve(isNonGlibcLinuxSync()); } + +export default { + GLIBC, + MUSL, + family, + familySync, + isNonGlibcLinux, + isNonGlibcLinuxSync, + version, + versionAsync, +}; diff --git a/src/js/thirdparty/isomorphic-fetch.js b/src/js/thirdparty/isomorphic-fetch.js new file mode 100644 index 00000000000000..59c8a6d06d249a --- /dev/null +++ b/src/js/thirdparty/isomorphic-fetch.js @@ -0,0 +1,5 @@ +const bunFetch = Bun.fetch; +const fetch = (...args) => bunFetch(...args); +fetch.default = fetch; +fetch.fetch = fetch; +export default fetch; diff --git a/src/js/thirdparty/node-fetch.js b/src/js/thirdparty/node-fetch.js new file mode 100644 index 00000000000000..f8bc9e3cd291de --- /dev/null +++ b/src/js/thirdparty/node-fetch.js @@ -0,0 +1,64 @@ +const { Headers, Request, Response, Blob, File = Blob, FormData } = globalThis; +const realFetch = Bun.fetch; + +function fetch(...args) { + // require("node-fetch") returns the default export which means we need to + // repeat the ESM exports onto it. + // + // We don't want to copy that onto the global fetch object, so we wrap it. + return realFetch(...args); +} + +class AbortError extends DOMException { + constructor(message) { + super(message, "AbortError"); + } +} + +class FetchBaseError extends Error { + constructor(message, type) { + super(message); + this.type = type; + } +} + +class FetchError extends FetchBaseError { + constructor(message, type, systemError) { + super(message, type); + this.code = systemError?.code; + } +} + +function blobFrom(path, options) { + return Promise.resolve(Bun.file(data)); +} + +function blobFromSync(path, options) { + return Bun.file(data); +} + +var fileFrom = blobFrom; +var fileFromSync = blobFromSync; + +function isRedirect(code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +} + +export default Object.assign(fetch, { + AbortError, + Blob, + FetchBaseError, + FetchError, + File, + FormData, + Headers, + Request, + Response, + blobFrom, + blobFromSync, + fileFrom, + fileFromSync, + isRedirect, + fetch, + default: fetch, +}); diff --git a/src/js/thirdparty/undici.js b/src/js/thirdparty/undici.js index e7c6338766f253..ec0096ff84220e 100644 --- a/src/js/thirdparty/undici.js +++ b/src/js/thirdparty/undici.js @@ -1,9 +1,7 @@ -const { Object } = $lazy("primordials"); -import { EventEmitter } from "events"; -import NodeStreamModule from "node:stream"; -import { Readable } from "node:stream"; - -const { _ReadableFromWebForUndici: ReadableFromWeb } = NodeStreamModule[Symbol.for("::bunternal::")]; +const EventEmitter = require("node:events"); +const StreamModule = require("node:stream"); +const { Readable } = StreamModule; +const { _ReadableFromWebForUndici: ReadableFromWeb } = StreamModule[Symbol.for("::bunternal::")]; const ObjectCreate = Object.create; const kEmptyObject = ObjectCreate(null); @@ -261,7 +259,7 @@ function mockErrors() { throw new Error("Not implemented in bun"); } -export function Undici() { +function Undici() { throw new Error("Not implemented in bun"); } @@ -327,31 +325,4 @@ export default { Client, Agent, Undici, - [Symbol.for("CommonJS")]: 0, -}; - -export { - fetch, - Response, - Headers, - Request, - URLSearchParams, - URL, - File, - FileReader, - FormData, - request, - stream, - pipeline, - connect, - upgrade, - MockClient, - MockPool, - MockAgent, - mockErrors, - Dispatcher, - Pool, - BalancedPool, - Client, - Agent, }; diff --git a/src/js/thirdparty/vercel_fetch.js b/src/js/thirdparty/vercel_fetch.js new file mode 100644 index 00000000000000..9d9be6c172e1b2 --- /dev/null +++ b/src/js/thirdparty/vercel_fetch.js @@ -0,0 +1,32 @@ +// This is just a no-op. Intent is to prevent importing a bunch of stuff that isn't relevant. +export default (wrapper = Bun.fetch) => { + async function vercelFetch(url, opts = {}) { + // Convert Object bodies to JSON if they are JS objects + if ( + opts.body && + typeof opts.body === "object" && + (!("buffer" in opts.body) || typeof opts.body.buffer !== "object" || !(opts.body.buffer instanceof ArrayBuffer)) + ) { + opts.body = JSON.stringify(opts.body); + // Content length will automatically be set + if (!opts.headers) opts.headers = new Headers(); + + opts.headers.set("Content-Type", "application/json"); + } + + try { + return await wrapper(url, opts); + } catch (err) { + if (typeof err === "string") { + err = new Error(err); + } + + err.url = url; + err.opts = opts; + throw err; + } + } + + vercelFetch.default = vercelFetch; + return vercelFetch; +}; diff --git a/src/js/thirdparty/ws.js b/src/js/thirdparty/ws.js index 8fa5491e3994ca..fe79449715f81d 100644 --- a/src/js/thirdparty/ws.js +++ b/src/js/thirdparty/ws.js @@ -3,8 +3,8 @@ // this just wraps WebSocket to look like an EventEmitter // without actually using an EventEmitter polyfill -import { EventEmitter } from "node:events"; -import http from "node:http"; +const EventEmitter = require("node:events"); +const http = require("node:http"); const kBunInternals = Symbol.for("::bunternal::"); const readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; @@ -265,8 +265,7 @@ class BunWebSocket extends EventEmitter { emitWarning("resume()", "ws.WebSocket.resume() is not implemented in bun"); } } - -BunWebSocket.WebSocket = BunWebSocket; +Object.defineProperty(BunWebSocket, "name", { value: "WebSocket" }); const wsKeyRegex = /^[+/0-9A-Za-z]{22}==$/; const wsTokenChars = [ @@ -715,7 +714,7 @@ class BunWebSocketMocked extends EventEmitter { } } -class Server extends EventEmitter { +class WebSocketServer extends EventEmitter { _server; options; clients; @@ -1082,9 +1081,6 @@ class Server extends EventEmitter { } } -BunWebSocket.WebSocketServer = Server; -BunWebSocket.Server = Server; - Object.defineProperty(BunWebSocket, "CONNECTING", { enumerable: true, value: readyStates.indexOf("CONNECTING"), @@ -1131,23 +1127,21 @@ class Sender { } } -BunWebSocket.Sender = Sender; - class Receiver { constructor() { throw new Error("Not supported yet in Bun"); } } -BunWebSocket.Receiver = Receiver; - var createWebSocketStream = ws => { throw new Error("Not supported yet in Bun"); }; -BunWebSocket.createWebSocketStream = createWebSocketStream; - -BunWebSocket[Symbol.for("CommonJS")] = 0; - -export default BunWebSocket; -export { createWebSocketStream, Server, Receiver, Sender, BunWebSocket as WebSocket, Server as WebSocketServer }; +export default Object.assign(BunWebSocket, { + createWebSocketStream, + Receiver, + Sender, + WebSocket: BunWebSocket, + Server: WebSocketServer, + WebSocketServer: WebSocketServer, +}); diff --git a/src/js/tsconfig.json b/src/js/tsconfig.json index 09a0abbb26bc68..e835e16035c33f 100644 --- a/src/js/tsconfig.json +++ b/src/js/tsconfig.json @@ -1,14 +1,25 @@ { "extends": "../../tsconfig.base.json", "compilerOptions": { - "noEmit": true + "lib": ["ESNext"], + "module": "ESNext", + "isolatedModules": true, + "noEmit": true, + "paths": { + "$shared": ["./internal/shared.ts"], //deprecated + "internal/*": ["./internal/*"] //deprecated + } }, "include": [ + // "node", "bun", + "builtins", + "functions", + "internal", "thirdparty", - "build-*", - "shared.ts", + "_codegen", + "builtins.d.ts", "private.d.ts", "../../packages/bun-types/index.d.ts" ] diff --git a/src/js/bun/wasi-runner.js b/src/js/wasi-runner.js similarity index 87% rename from src/js/bun/wasi-runner.js rename to src/js/wasi-runner.js index 9f7b469e11ea98..5e7cb48cdb478e 100644 --- a/src/js/bun/wasi-runner.js +++ b/src/js/wasi-runner.js @@ -1,6 +1,7 @@ /** This file is used when a .wasm file is ran. - * The contents of `../node/wasi.js` is pasted into the top of this file. + * The transpiled contents of `./node/wasi.js` is pasted into the top of this file. */ +import { WASI } from "node:wasi"; const filePath = process.argv.at(1); if (!filePath) { @@ -34,7 +35,7 @@ const wasi = new WASI({ let source = globalThis.wasmSourceBytes; if (!source) { - const fs = Bun.fs(); + const fs = import.meta.require("fs"); const file = import.meta.path; source = fs.readFileSync(file); } diff --git a/src/js_ast.zig b/src/js_ast.zig index b5f47474afb5a8..af010dfa8ca412 100644 --- a/src/js_ast.zig +++ b/src/js_ast.zig @@ -25,6 +25,7 @@ const JSONParser = bun.JSON; const is_bindgen = std.meta.globalOption("bindgen", bool) orelse false; const ComptimeStringMap = bun.ComptimeStringMap; const JSPrinter = @import("./js_printer.zig"); +const js_lexer = @import("./js_lexer.zig"); const ThreadlocalArena = @import("./mimalloc_arena.zig").Arena; /// This is the index to the automatically-generated part containing code that @@ -840,6 +841,7 @@ pub const G = struct { get, set, spread, + declare, class_static_block, pub fn jsonStringify(self: @This(), opts: anytype, o: anytype) !void { @@ -1701,18 +1703,28 @@ pub const E = struct { return toStringFromF64Safe(this.value, allocator); } + pub fn toStringSafelyWithDecimalPlaces(this: Number, allocator: std.mem.Allocator) ?string { + if (this.value == @trunc(this.value)) { + return toStringFromF64Safe(this.value, allocator); + } + + return std.fmt.allocPrint(allocator, "{d}", .{this.value}) catch return null; + } + pub fn toStringFromF64Safe(value: f64, allocator: std.mem.Allocator) ?string { - if (value == @trunc(value) and (value < std.math.maxInt(i32) and value > std.math.minInt(i32))) { - const int_value = @as(i64, @intFromFloat(value)); - const abs = @as(u64, @intCast(std.math.absInt(int_value) catch return null)); - if (abs < double_digit.len) { - return if (int_value < 0) - neg_double_digit[abs] - else - double_digit[abs]; - } + if (comptime !Environment.isWasm) { + if (value == @trunc(value) and (value < std.math.maxInt(i32) and value > std.math.minInt(i32))) { + const int_value = @as(i64, @intFromFloat(value)); + const abs = @as(u64, @intCast(std.math.absInt(int_value) catch return null)); + if (abs < double_digit.len) { + return if (int_value < 0) + neg_double_digit[abs] + else + double_digit[abs]; + } - return std.fmt.allocPrint(allocator, "{d}", .{@as(i32, @intCast(int_value))}) catch return null; + return std.fmt.allocPrint(allocator, "{d}", .{@as(i32, @intCast(int_value))}) catch return null; + } } if (std.math.isNan(value)) { @@ -2248,6 +2260,11 @@ pub const E = struct { } if (s.isUTF8()) { + if (comptime !Environment.isNative) { + var allocated = (strings.toUTF16Alloc(bun.default_allocator, s.data, false) catch return 0) orelse return s.data.len; + defer bun.default_allocator.free(allocated); + return @as(u32, @truncate(allocated.len)); + } return @as(u32, @truncate(bun.simdutf.length.utf16.from.utf8.le(s.data))); } @@ -2358,7 +2375,6 @@ pub const E = struct { } pub fn toJS(s: *String, allocator: std.mem.Allocator, globalObject: *JSC.JSGlobalObject) JSC.JSValue { - s.resolveRopeIfNeeded(allocator); if (!s.isPresent()) { var emp = bun.String.empty; return emp.toJS(globalObject); @@ -2366,14 +2382,20 @@ pub const E = struct { if (s.is_utf16) { var out = bun.String.createUninitializedUTF16(s.len()); - defer out.deref(); @memcpy(@constCast(out.utf16()), s.slice16()); return out.toJS(globalObject); } { - var out = bun.String.create(s.slice(allocator)); + s.resolveRopeIfNeeded(allocator); + + const decoded = js_lexer.decodeUTF8(s.slice(allocator), allocator) catch unreachable; + defer allocator.free(decoded); + + var out = bun.String.createUninitializedUTF16(decoded.len); defer out.deref(); + @memcpy(@constCast(out.utf16()), decoded); + return out.toJS(globalObject); } } @@ -3062,7 +3084,7 @@ pub const Expr = struct { ) !Expr { var bytes = blob.sharedView(); - const mime_type = mime_type_ orelse HTTP.MimeType.init(blob.content_type); + const mime_type = mime_type_ orelse HTTP.MimeType.init(blob.content_type, null, null); if (mime_type.category == .json) { var source = logger.Source.initPathString("fetch.json", bytes); @@ -4127,6 +4149,14 @@ pub const Expr = struct { return @as(Tag, this.data).isPrimitiveLiteral(); } + pub fn isRef(this: Expr, ref: Ref) bool { + return switch (this.data) { + .e_import_identifier => |import_identifier| import_identifier.ref.eql(ref), + .e_identifier => |ident| ident.ref.eql(ref), + else => false, + }; + } + pub const Tag = enum(u6) { e_array, e_unary, @@ -5940,8 +5970,6 @@ pub const Ast = struct { wrapper_ref: Ref = Ref.None, require_ref: Ref = Ref.None, - bun_plugin: BunPlugin = .{}, - prepend_part: ?Part = null, // These are used when bundling. They are filled in during the parser pass @@ -6413,7 +6441,6 @@ pub const Part = struct { cjs_imports, react_fast_refresh, dirname_filename, - bun_plugin, bun_test, dead_due_to_inlining, commonjs_named_export, @@ -6681,11 +6708,6 @@ pub fn printmem(comptime format: string, args: anytype) void { Output.print(format, args); } -pub const BunPlugin = struct { - ref: Ref = Ref.None, - hoisted_stmts: std.ArrayListUnmanaged(Stmt) = .{}, -}; - pub const Macro = struct { const JavaScript = @import("root").bun.JSC; const JSCBase = @import("./bun.js/base.zig"); @@ -9780,10 +9802,10 @@ pub const Macro = struct { if (value.jsType() == .DOMWrapper) { if (value.as(JSC.WebCore.Response)) |resp| { - mime_type = HTTP.MimeType.init(resp.mimeType(null)); + mime_type = HTTP.MimeType.init(resp.mimeType(null), null, null); blob_ = resp.body.use(); } else if (value.as(JSC.WebCore.Request)) |resp| { - mime_type = HTTP.MimeType.init(resp.mimeType()); + mime_type = HTTP.MimeType.init(resp.mimeType(), null, null); blob_ = resp.body.value.use(); } else if (value.as(JSC.WebCore.Blob)) |resp| { blob_ = resp.*; @@ -9951,12 +9973,8 @@ pub const Macro = struct { }, .String => { var bun_str = value.toBunString(this.global); - if (bun_str.is8Bit()) { - if (strings.isAllASCII(bun_str.latin1())) { - return Expr.init(E.String, E.String.init(this.allocator.dupe(u8, bun_str.latin1()) catch unreachable), this.caller.loc); - } - } + // encode into utf16 so the printer escapes the string correctly var utf16_bytes = this.allocator.alloc(u16, bun_str.length()) catch unreachable; var out_slice = utf16_bytes[0 .. (bun_str.encodeInto(std.mem.sliceAsBytes(utf16_bytes), .utf16le) catch 0) / 2]; return Expr.init(E.String, E.String.init(out_slice), this.caller.loc); diff --git a/src/js_lexer.zig b/src/js_lexer.zig index a0ad75c7bd74bb..1417ea01e48b41 100644 --- a/src/js_lexer.zig +++ b/src/js_lexer.zig @@ -75,6 +75,19 @@ pub const JSONOptions = struct { was_originally_macro: bool = false, }; +pub fn decodeUTF8(bytes: string, allocator: std.mem.Allocator) ![]const u16 { + var log = logger.Log.init(allocator); + defer log.deinit(); + var source = logger.Source.initEmptyFile(""); + var lexer = try NewLexer(.{}).init(&log, source, allocator); + defer lexer.deinit(); + + var buf = std.ArrayList(u16).init(allocator); + try lexer.decodeEscapeSequences(0, bytes, @TypeOf(buf), &buf); + + return buf.items; +} + pub fn NewLexer( comptime json_options: JSONOptions, ) type { @@ -721,7 +734,7 @@ fn NewLexer_( needs_slow_path = true; } else if (is_json and lexer.code_point < 0x20) { try lexer.syntaxError(); - } else if (comptime quote == '"' or quote == '\'') { + } else if (comptime (quote == '"' or quote == '\'') and Environment.isNative) { const remainder = lexer.source.contents[lexer.current..]; if (remainder.len >= 4096) { lexer.current += indexOfInterestingCharacterInStringLiteral(remainder, quote) orelse { diff --git a/src/js_parser.zig b/src/js_parser.zig index 6390dfdbaabbb7..976642eb9b08a7 100644 --- a/src/js_parser.zig +++ b/src/js_parser.zig @@ -46,6 +46,12 @@ fn _disabledAssert(_: bool) void { unreachable; } +fn __wrapSyntaxError(loc: @import("std").builtin.SourceLocation) void { + Output.print("SyntaxError at {d}:{d}", .{ + loc.line, + loc.column, + }); +} const assert = if (Environment.allow_assert) std.debug.assert else _disabledAssert; const debug = Output.scoped(.JSParser, false); const ExprListLoc = struct { @@ -386,6 +392,7 @@ const JSXTag = struct { if (strings.indexOfChar(member, '-')) |index| { try p.log.addError(p.source, logger.Loc{ .start = member_range.loc.start + @as(i32, @intCast(index)) }, "Unexpected \"-\""); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -2810,6 +2817,74 @@ pub const Parser = struct { } } + pub fn analyze(self: *Parser, context: *anyopaque, callback: *const fn (*anyopaque, *TSXParser, []js_ast.Part) anyerror!void) anyerror!void { + var p: TSXParser = undefined; + try TSXParser.init(self.allocator, self.log, self.source, self.define, self.lexer, self.options, &p); + p.should_fold_typescript_constant_expressions = false; + + defer p.lexer.deinit(); + + // Consume a leading hashbang comment + var hashbang: string = ""; + if (p.lexer.token == .t_hashbang) { + hashbang = p.lexer.identifier; + try p.lexer.next(); + } + + // Parse the file in the first pass, but do not bind symbols + var opts = ParseStatementOptions{ .is_module_scope = true }; + const parse_tracer = bun.tracy.traceNamed(@src(), "JSParser.parse"); + + const stmts = p.parseStmtsUpTo(js_lexer.T.t_end_of_file, &opts) catch |err| { + if (comptime Environment.isWasm) { + Output.print("JSParser.parse: caught error {s} at location: {d}\n", .{ @errorName(err), p.lexer.loc().start }); + p.log.printForLogLevel(Output.writer()) catch {}; + } + return err; + }; + + parse_tracer.end(); + + if (self.log.errors > 0) { + if (comptime Environment.isWasm) { + // If the logger is backed by console.log, every print appends a newline. + // so buffering is kind of mandatory here + const fakeWriter = struct { + fn writeAll(_: @This(), data: []const u8) anyerror!usize { + if (data.len == 0) return 0; + + Output.print("{s}", .{data}); + return data.len; + } + }; + var writer = std.io.Writer(fakeWriter, anyerror, fakeWriter.writeAll){ + .context = fakeWriter{}, + }; + var buffered_writer = std.io.bufferedWriter(writer); + var actual = buffered_writer.writer(); + for (self.log.msgs.items) |msg| { + var m: logger.Msg = msg; + m.writeFormat(actual, true) catch {}; + } + buffered_writer.flush() catch {}; + } + return error.SyntaxError; + } + + const visit_tracer = bun.tracy.traceNamed(@src(), "JSParser.visit"); + try p.prepareForVisitPass(); + + var parts = ListManaged(js_ast.Part).init(p.allocator); + defer parts.deinit(); + + try p.appendPart(&parts, stmts); + visit_tracer.end(); + + const analyze_tracer = bun.tracy.traceNamed(@src(), "JSParser.analyze"); + try callback(context, &p, parts.items); + analyze_tracer.end(); + } + fn _parse(self: *Parser, comptime ParserType: type) !js_ast.Result { var p: ParserType = undefined; const orig_error_count = self.log.errors; @@ -2858,6 +2933,7 @@ pub const Parser = struct { // Example where NOT halting causes a crash: A TS enum with a number literal as a member name // https://discord.com/channels/876711213126520882/876711213126520885/1039325382488371280 if (self.log.errors > orig_error_count) { + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -3015,6 +3091,7 @@ pub const Parser = struct { // If there were errors while visiting, also halt here if (self.log.errors > orig_error_count) { + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -4287,11 +4364,10 @@ pub const Parser = struct { } pub fn init(_options: Options, log: *logger.Log, source: *const logger.Source, define: *Define, allocator: Allocator) !Parser { - const lexer = try js_lexer.Lexer.init(log, source.*, allocator); return Parser{ .options = _options, .allocator = allocator, - .lexer = lexer, + .lexer = try js_lexer.Lexer.init(log, source.*, allocator), .define = define, .source = source, .log = log, @@ -4803,7 +4879,6 @@ fn NewParser_( filename_ref: Ref = Ref.None, dirname_ref: Ref = Ref.None, import_meta_ref: Ref = Ref.None, - bun_plugin: js_ast.BunPlugin = .{}, scopes_in_order_visitor_index: usize = 0, has_classic_runtime_warned: bool = false, macro_call_count: MacroCallCountType = 0, @@ -8101,6 +8176,7 @@ fn NewParser_( else => { if (!found_key) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } }, @@ -8113,6 +8189,7 @@ fn NewParser_( else => { if (!p.lexer.has_newline_before) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } }, @@ -8146,38 +8223,6 @@ fn NewParser_( return p.s(S.Empty{}, loc); } - if (p.options.features.hoist_bun_plugin and strings.eqlComptime(path.text, "bun")) { - var plugin_i: usize = std.math.maxInt(usize); - const items = stmt.items; - for (items, 0..) |item, i| { - // Mark Bun.plugin() - // TODO: remove if they have multiple imports of the same name? - if (strings.eqlComptime(item.alias, "plugin")) { - const name = p.loadNameFromRef(item.name.ref.?); - const ref = try p.declareSymbol(.other, item.name.loc, name); - try p.is_import_item.put(p.allocator, ref, {}); - p.bun_plugin.ref = ref; - plugin_i = i; - break; - } - } - - if (plugin_i != std.math.maxInt(usize)) { - var list = std.ArrayListUnmanaged(@TypeOf(stmt.items[0])){ - .items = stmt.items, - .capacity = stmt.items.len, - }; - // remove it from the list - _ = list.swapRemove(plugin_i); - stmt.items = list.items; - } - - // if the import statement is now empty, remove it completely - if (stmt.items.len == 0 and stmt.default_name == null and stmt.star_name_loc == null) { - return p.s(S.Empty{}, loc); - } - } - const macro_remap = if ((comptime allow_macros) and !is_macro) p.options.macro_context.getRemap(path.text) else @@ -8521,6 +8566,7 @@ fn NewParser_( // example: // export class {} if (!is_identifier) { + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -8650,6 +8696,7 @@ fn NewParser_( p.esm_export_keyword = p.lexer.range(); } else if (!opts.is_namespace_scope) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } try p.lexer.next(); @@ -8683,12 +8730,14 @@ fn NewParser_( } try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, T.t_enum => { if (!is_typescript_enabled) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -8761,12 +8810,14 @@ fn NewParser_( } try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, T.t_default => { if (!opts.is_module_scope and (!opts.is_namespace_scope or !opts.is_typescript_declare)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -8916,6 +8967,7 @@ fn NewParser_( T.t_asterisk => { if (!opts.is_module_scope and !(opts.is_namespace_scope or !opts.is_typescript_declare)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -8969,6 +9021,7 @@ fn NewParser_( T.t_open_brace => { if (!opts.is_module_scope and !(opts.is_namespace_scope or !opts.is_typescript_declare)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -9046,10 +9099,12 @@ fn NewParser_( return p.s(S.ExportEquals{ .value = value }, loc); } try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, else => { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, } @@ -9062,6 +9117,7 @@ fn NewParser_( .t_enum => { if (!is_typescript_enabled) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } return p.parseTypescriptEnumStmt(loc, opts); @@ -9105,6 +9161,7 @@ fn NewParser_( // notimpl(); try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, .t_class => { @@ -9231,6 +9288,7 @@ fn NewParser_( if (p.lexer.token == .t_default) { if (foundDefault) { try p.log.addRangeError(p.source, p.lexer.range(), "Multiple default clauses are not allowed"); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -9420,6 +9478,7 @@ fn NewParser_( if (p.lexer.isContextualKeyword("of") or isForAwait) { if (bad_let_range) |r| { try p.log.addRangeError(p.source, r, "\"let\" must be wrapped in parentheses to be used as an expression here"); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -9428,6 +9487,7 @@ fn NewParser_( try p.lexer.expectedString("\"of\""); } else { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } } @@ -9513,6 +9573,7 @@ fn NewParser_( // "import 'path'" if (!opts.is_module_scope and (!opts.is_namespace_scope or !opts.is_typescript_declare)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } was_originally_bare_import = true; @@ -9521,6 +9582,7 @@ fn NewParser_( // "import * as ns from 'path'" if (!opts.is_module_scope and (!opts.is_namespace_scope or !opts.is_typescript_declare)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -9538,6 +9600,7 @@ fn NewParser_( // "import {item1, item2} from 'path'" if (!opts.is_module_scope and (!opts.is_namespace_scope or !opts.is_typescript_declare)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } var importClause = try p.parseImportClause(); @@ -9563,6 +9626,7 @@ fn NewParser_( // "import foo = bar" if (!opts.is_module_scope and (!opts.is_namespace_scope)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -9648,6 +9712,7 @@ fn NewParser_( }, else => { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, } @@ -9657,6 +9722,7 @@ fn NewParser_( }, else => { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, } @@ -9702,6 +9768,7 @@ fn NewParser_( try p.log.addError(p.source, logger.Loc{ .start = loc.start + 5, }, "Unexpected newline after \"throw\""); + __wrapSyntaxError(@src()); return error.SyntaxError; } const expr = try p.parseExpr(.lowest); @@ -10474,6 +10541,7 @@ fn NewParser_( // Commas after spread elements are not allowed if (has_spread and p.lexer.token == .t_comma) { p.log.addRangeError(p.source, p.lexer.range(), "Unexpected \",\" after rest pattern") catch unreachable; + __wrapSyntaxError(@src()); return error.SyntaxError; } } @@ -10521,6 +10589,7 @@ fn NewParser_( // Commas after spread elements are not allowed if (property.flags.contains(.is_spread) and p.lexer.token == .t_comma) { p.log.addRangeError(p.source, p.lexer.range(), "Unexpected \",\" after rest pattern") catch unreachable; + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -10972,6 +11041,7 @@ fn NewParser_( if (first_non_identifier_loc.start != 0 and !p.lexer.isContextualKeyword("from")) { const r = js_lexer.rangeOfIdentifier(p.source, first_non_identifier_loc); try p.lexer.addRangeError(r, "Expected identifier but found \"{s}\"", .{p.source.textForRange(r)}, true); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -11423,6 +11493,7 @@ fn NewParser_( // Newlines are not allowed before "=>" if (p.lexer.has_newline_before) { try p.log.addRangeError(p.source, p.lexer.range(), "Unexpected newline before \"=>\""); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -11913,6 +11984,7 @@ fn NewParser_( if (isStar) { if (p.lexer.has_newline_before) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } try p.lexer.next(); @@ -11997,6 +12069,7 @@ fn NewParser_( .t_asterisk => { if (kind != .normal or opts.is_generator) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -12062,7 +12135,14 @@ fn NewParser_( // https://github.com/oven-sh/bun/issues/1907 if (opts.is_class and is_typescript_enabled and strings.eqlComptime(raw, "declare")) { const scope_index = p.scopes_in_order.items.len; - _ = try p.parseProperty(kind, opts, null); + if (try p.parseProperty(kind, opts, null)) |_prop| { + var prop = _prop; + if (prop.kind == .normal and prop.value == null and opts.ts_decorators.len > 0) { + prop.kind = .declare; + return prop; + } + } + p.discardScopesUpTo(scope_index); return null; } @@ -12760,6 +12840,7 @@ fn NewParser_( // "a?.()" if (comptime !is_typescript_enabled) { try p.lexer.expected(.t_identifier); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -12911,6 +12992,7 @@ fn NewParser_( { if (errors == null) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } errors.?.invalid_expr_after_question = p.lexer.range(); @@ -12942,6 +13024,7 @@ fn NewParser_( if (!is_typescript_enabled) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13217,6 +13300,7 @@ fn NewParser_( // Prevent "||" inside "??" from the right if (level.eql(.nullish_coalescing)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13229,6 +13313,7 @@ fn NewParser_( if (p.lexer.token == .t_question_question) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } } @@ -13249,6 +13334,7 @@ fn NewParser_( // Prevent "&&" inside "??" from the right if (level.eql(.nullish_coalescing)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13261,6 +13347,7 @@ fn NewParser_( if (p.lexer.token == .t_question_question) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } } @@ -13534,6 +13621,7 @@ fn NewParser_( .t_private_identifier => { if (!p.allow_private_identifiers or !p.allow_in or level.gte(.compare)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13582,6 +13670,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == T.t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13693,6 +13782,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == .t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13706,6 +13796,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == .t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13716,6 +13807,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == .t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } if (value.data == .e_index) { @@ -13734,6 +13826,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == .t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13744,6 +13837,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == .t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13754,6 +13848,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == .t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13764,6 +13859,7 @@ fn NewParser_( const value = try p.parseExpr(.prefix); if (p.lexer.token == .t_asterisk_asterisk) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -13826,6 +13922,7 @@ fn NewParser_( if (p.lexer.token != .t_identifier or !strings.eqlComptime(p.lexer.raw(), "target")) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } const range = logger.Range{ .loc = loc, .len = p.lexer.range().end().start - loc.start }; @@ -14093,17 +14190,21 @@ fn NewParser_( } try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, .t_import => { try p.lexer.next(); return p.parseImportExpr(loc, level); }, - else => { + else => |tok| { + Output.print("Unexpected {s}", .{@tagName(tok)}); try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, } + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -14366,6 +14467,7 @@ fn NewParser_( // If we get here, it's invalid try p.log.addError(p.source, expr.loc, "Invalid JSX prop shorthand, must be identifier, dot or string"); + __wrapSyntaxError(@src()); return error.SyntaxError; }; @@ -14420,6 +14522,7 @@ fn NewParser_( const r = p.lexer.range(); // Not dealing with this right now. try p.log.addRangeError(p.source, r, "Invalid JSX escape - use XML entity codes quotes or pass a JavaScript string instead"); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -14501,6 +14604,7 @@ fn NewParser_( end_tag.name, tag.name, }); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -14523,6 +14627,7 @@ fn NewParser_( }, else => { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; }, } @@ -14556,10 +14661,6 @@ fn NewParser_( var partStmts = ListManaged(Stmt).fromOwnedSlice(allocator, stmts); // - const bun_plugin_usage_count_before: usize = if (p.options.features.hoist_bun_plugin and !p.bun_plugin.ref.isNull()) - p.symbols.items[p.bun_plugin.ref.innerIndex()].use_count_estimate - else - 0; try p.visitStmtsAndPrependTempRefs(&partStmts, &opts); @@ -14595,52 +14696,6 @@ fn NewParser_( if (partStmts.items.len > 0) { const _stmts = partStmts.items; - // -- hoist_bun_plugin -- - if (_stmts.len == 1 and p.options.features.hoist_bun_plugin and !p.bun_plugin.ref.isNull()) { - const bun_plugin_usage_count_after: usize = p.symbols.items[p.bun_plugin.ref.innerIndex()].use_count_estimate; - if (bun_plugin_usage_count_after > bun_plugin_usage_count_before) { - var previous_parts: []js_ast.Part = parts.items; - - for (previous_parts, 0..) |*previous_part, j| { - if (previous_part.stmts.len == 0) continue; - - var refs = previous_part.declared_symbols.refs(); - - for (refs) |ref| { - if (p.symbol_uses.contains(ref)) { - // we move this part to our other file - for (previous_parts[0..j]) |*this_part| { - if (this_part.stmts.len == 0) continue; - const other_refs = this_part.declared_symbols.refs(); - - for (other_refs) |other_ref| { - if (previous_part.symbol_uses.contains(other_ref)) { - try p.bun_plugin.hoisted_stmts.appendSlice(p.allocator, this_part.stmts); - this_part.stmts = &.{}; - break; - } - } - } - - try p.bun_plugin.hoisted_stmts.appendSlice(p.allocator, previous_part.stmts); - break; - } - } - } - p.bun_plugin.hoisted_stmts.append(p.allocator, _stmts[0]) catch unreachable; - - // Single-statement part which uses Bun.plugin() - // It's effectively an unrelated file - if (p.declared_symbols.len() > 0 or p.symbol_uses.count() > 0) { - p.clearSymbolUsagesFromDeadPart(.{ .stmts = undefined, .declared_symbols = p.declared_symbols, .symbol_uses = p.symbol_uses }); - p.declared_symbols.clearRetainingCapacity(); - p.import_records_for_current_part.items.len = 0; - } - return; - } - } - // -- hoist_bun_plugin -- - try parts.append(js_ast.Part{ .stmts = _stmts, .symbol_uses = p.symbol_uses, @@ -15815,7 +15870,7 @@ fn NewParser_( return p.newExpr( // Use libc fmod here to be consistent with what JavaScriptCore does // https://github.com/oven-sh/WebKit/blob/7a0b13626e5db69aa5a32d037431d381df5dfb61/Source/JavaScriptCore/runtime/MathCommon.cpp#L574-L597 - E.Number{ .value = bun.C.fmod(vals[0], vals[1]) }, + E.Number{ .value = if (comptime Environment.isNative) bun.C.fmod(vals[0], vals[1]) else std.math.mod(f64, vals[0], vals[1]) catch 0 }, expr.loc, ); } @@ -19512,6 +19567,8 @@ fn NewParser_( } } + // TODO: prop.kind == .declare and prop.value == null + if (prop.ts_decorators.len > 0) { const loc = prop.key.?.loc; const descriptor_key = switch (prop.key.?.data) { @@ -20881,6 +20938,7 @@ fn NewParser_( // Arrow functions are not allowed inside certain expressions if (level.gt(.assign)) { try p.lexer.unexpected(); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -20953,6 +21011,7 @@ fn NewParser_( // If this isn't an arrow function, then types aren't allowed if (type_colon_range.len > 0) { try p.log.addRangeError(p.source, type_colon_range, "Unexpected \":\""); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -20968,6 +21027,7 @@ fn NewParser_( p.logExprErrors(&errors); if (spread_range.len > 0) { try p.log.addRangeError(p.source, type_colon_range, "Unexpected \"...\""); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -20978,6 +21038,7 @@ fn NewParser_( // Indicate that we expected an arrow function try p.lexer.expected(.t_equals_greater_than); + __wrapSyntaxError(@src()); return error.SyntaxError; } @@ -21260,7 +21321,7 @@ fn NewParser_( logger.Loc.Empty, ); const cjsGlobal = p.newSymbol(.unbound, "$_BunCommonJSModule_$") catch unreachable; - var all_call_args = allocator.alloc(Expr, 7) catch unreachable; + var all_call_args = allocator.alloc(Expr, 8) catch unreachable; const this_module = p.newExpr( E.Dot{ .name = "module", @@ -21269,9 +21330,19 @@ fn NewParser_( }, logger.Loc.Empty, ); - var call_args = all_call_args[1..]; + var bind_args = all_call_args[0..1]; bind_args[0] = this_module; + var bind_resolve_args = all_call_args[1..2]; + var call_args = all_call_args[2..]; + + const module_id = p.newExpr(E.Dot{ + .name = "id", + .target = this_module, + .name_loc = logger.Loc.Empty, + }, logger.Loc.Empty); + + bind_resolve_args[0] = module_id; const get_require = p.newExpr( E.Dot{ .name = "require", @@ -21293,12 +21364,24 @@ fn NewParser_( logger.Loc.Empty, ); - const module_id = p.newExpr(E.Dot{ - .name = "id", - .target = this_module, + const get_resolve = p.newExpr(E.Dot{ + .name = "resolve", .name_loc = logger.Loc.Empty, + .target = get_require, }, logger.Loc.Empty); + const create_resolve_binding = p.newExpr( + E.Call{ + .target = p.newExpr(E.Dot{ + .name = "bind", + .name_loc = logger.Loc.Empty, + .target = get_resolve, + }, logger.Loc.Empty), + .args = bun.BabyList(Expr).init(bind_resolve_args), + }, + logger.Loc.Empty, + ); + const require_path = p.newExpr( E.Dot{ .name = "path", @@ -21316,15 +21399,25 @@ fn NewParser_( logger.Loc.Empty, ); + const assign_resolve_binding = p.newExpr( + E.Binary{ + .left = get_resolve, + .right = create_resolve_binding, + .op = .bin_assign, + }, + logger.Loc.Empty, + ); + const assign_id = p.newExpr(E.Binary{ .left = require_path, .right = module_id, .op = .bin_assign, }, logger.Loc.Empty); - var create_require = [3]Expr{ + var create_require = [4]Expr{ assign_binding, assign_id, + assign_resolve_binding, get_require, }; @@ -21913,7 +22006,6 @@ fn NewParser_( else false, // .top_Level_await_keyword = p.top_level_await_keyword, - .bun_plugin = p.bun_plugin, .commonjs_named_exports = p.commonjs_named_exports, .commonjs_export_names = p.commonjs_export_names.keys(), @@ -22040,7 +22132,7 @@ const JSXParser = if (bun.fast_debug_build_mode) TSXParser else NewParser(.{ .jsx = .react }); -const TSXParser = NewParser(.{ .jsx = .react, .typescript = true }); +pub const TSXParser = NewParser(.{ .jsx = .react, .typescript = true }); const TypeScriptParser = NewParser(.{ .typescript = true }); const JSParserMacro = if (bun.fast_debug_build_mode) TSParserMacro diff --git a/src/js_printer.zig b/src/js_printer.zig index 61c13c25f4b482..56b6d0faec3773 100644 --- a/src/js_printer.zig +++ b/src/js_printer.zig @@ -5650,6 +5650,7 @@ pub fn getSourceMapBuilder( is_bun_platform, ), .cover_lines_without_mappings = true, + .approximate_input_line_count = tree.approximate_newline_count, .prepend_count = is_bun_platform and generate_source_map == .lazy, .line_offset_tables = opts.line_offset_tables orelse brk: { if (generate_source_map == .lazy) break :brk SourceMap.LineOffsetTable.generate( diff --git a/src/linker.zig b/src/linker.zig index 744c5eabcf94ba..ac902d75a319d7 100644 --- a/src/linker.zig +++ b/src/linker.zig @@ -206,6 +206,62 @@ pub const Linker = struct { return linkAllowImportingFromBundle(linker, file_path, result, origin, import_path_format, ignore_runtime, true, is_bun); } + fn whenModuleNotFound( + linker: *ThisLinker, + import_record: *ImportRecord, + result: *_bundler.ParseResult, + comptime is_bun: bool, + ) !bool { + if (import_record.handles_import_errors) { + import_record.path.is_disabled = true; + return false; + } + + if (comptime is_bun) { + // make these happen at runtime + if (import_record.kind == .require or import_record.kind == .require_resolve) { + return false; + } + } + + if (import_record.path.text.len > 0 and Resolver.isPackagePath(import_record.path.text)) { + if (linker.options.target.isWebLike() and Options.ExternalModules.isNodeBuiltin(import_record.path.text)) { + try linker.log.addResolveError( + &result.source, + import_record.range, + linker.allocator, + "Could not resolve: \"{s}\". Try setting --target=\"node\"", + .{import_record.path.text}, + import_record.kind, + error.ModuleNotFound, + ); + } else { + try linker.log.addResolveError( + &result.source, + import_record.range, + linker.allocator, + "Could not resolve: \"{s}\". Maybe you need to \"bun install\"?", + .{import_record.path.text}, + import_record.kind, + error.ModuleNotFound, + ); + } + } else { + try linker.log.addResolveError( + &result.source, + import_record.range, + linker.allocator, + "Could not resolve: \"{s}\"", + .{ + import_record.path.text, + }, + import_record.kind, + error.ModuleNotFound, + ); + } + return true; + } + pub fn linkAllowImportingFromBundle( linker: *ThisLinker, file_path: Fs.Path, @@ -280,10 +336,12 @@ pub const Linker = struct { continue; } } + if (strings.startsWith(import_record.path.text, "node:")) { + // if a module is not found here, it is not found at all + // so we can just disable it + had_resolve_errors = try whenModuleNotFound(linker, import_record, result, is_bun); - if (JSC.DisabledModule.has(import_record.path.text)) { - import_record.path.is_disabled = true; - import_record.do_commonjs_transform_in_printer = true; + if (had_resolve_errors) return error.ResolveMessage; continue; } @@ -719,58 +777,7 @@ pub const Linker = struct { continue; }, error.ModuleNotFound => { - if (import_record.handles_import_errors) { - import_record.path.is_disabled = true; - continue; - } - - if (comptime is_bun) { - // make these happen at runtime - if (import_record.kind == .require or import_record.kind == .require_resolve) { - continue; - } - } - - had_resolve_errors = true; - - if (import_record.path.text.len > 0 and Resolver.isPackagePath(import_record.path.text)) { - if (linker.options.target.isWebLike() and Options.ExternalModules.isNodeBuiltin(import_record.path.text)) { - try linker.log.addResolveError( - &result.source, - import_record.range, - linker.allocator, - "Could not resolve: \"{s}\". Try setting --target=\"node\"", - .{import_record.path.text}, - import_record.kind, - err, - ); - continue; - } else { - try linker.log.addResolveError( - &result.source, - import_record.range, - linker.allocator, - "Could not resolve: \"{s}\". Maybe you need to \"bun install\"?", - .{import_record.path.text}, - import_record.kind, - err, - ); - continue; - } - } else { - try linker.log.addResolveError( - &result.source, - import_record.range, - linker.allocator, - "Could not resolve: \"{s}\"", - .{ - import_record.path.text, - }, - import_record.kind, - err, - ); - continue; - } + had_resolve_errors = try whenModuleNotFound(linker, import_record, result, is_bun); }, else => { had_resolve_errors = true; diff --git a/src/lock.zig b/src/lock.zig index 3e07945c850c28..423e617adb599e 100644 --- a/src/lock.zig +++ b/src/lock.zig @@ -116,6 +116,12 @@ pub const Lock = struct { pub inline fn unlock(this: *Lock) void { this.mutex.release(); } + + pub inline fn assertUnlocked(this: *Lock, comptime message: []const u8) void { + if (this.mutex.state.load(.Monotonic) != 0) { + @panic(message); + } + } }; pub fn spinCycle() void {} diff --git a/src/logger.zig b/src/logger.zig index 5a9e5b973fa6cd..21a58243cc83d6 100644 --- a/src/logger.zig +++ b/src/logger.zig @@ -561,7 +561,7 @@ pub const Msg = struct { try writer.print("{s}: {s}\n{s}\n{s}:{}:{} ({d})", .{ msg.kind.string(), msg.data.text, - location.line_text, + location.line_text orelse "", location.file, location.line, location.column, diff --git a/src/main_wasm.zig b/src/main_wasm.zig index d58ce60a043191..e7fd55d8018cfe 100644 --- a/src/main_wasm.zig +++ b/src/main_wasm.zig @@ -1,3 +1,4 @@ +const bun = @import("root").bun; const JSParser = bun.js_parser; const JSPrinter = bun.js_printer; const JSAst = bun.JSAst; @@ -181,26 +182,325 @@ var output_stream = std.io.fixedBufferStream(&output_stream_buf); var error_stream_buf: [16384]u8 = undefined; var error_stream = std.io.fixedBufferStream(&error_stream_buf); var output_source: global.Output.Source = undefined; -export fn init() void { +var init_counter: usize = 0; +export fn init(heapsize: u32) void { const Mimalloc = @import("./allocators/mimalloc.zig"); - // reserve 256 MB upfront - Mimalloc.mi_option_set(Mimalloc.mi_option_t.allow_decommit, 0); - Mimalloc.mi_option_set(Mimalloc.mi_option_t.limit_os_alloc, 1); - _ = Mimalloc.mi_reserve_os_memory(2.56e+8, false, true); - - output_source = global.Output.Source.init(output_stream, error_stream); - global.Output.Source.set(&output_source); - JSAst.Stmt.Data.Store.create(default_allocator); - JSAst.Expr.Data.Store.create(default_allocator); - buffer_writer = JSPrinter.BufferWriter.init(default_allocator) catch unreachable; - buffer_writer.buffer.growBy(1024) catch unreachable; - writer = JSPrinter.BufferPrinter.init(buffer_writer); - define = Define.Define.init(default_allocator, null, null) catch unreachable; + defer init_counter +%= 1; + if (init_counter == 0) { + + // reserve 256 MB upfront + Mimalloc.mi_option_set(.allow_decommit, 0); + Mimalloc.mi_option_set(.limit_os_alloc, 1); + _ = Mimalloc.mi_reserve_os_memory(heapsize, false, true); + + JSAst.Stmt.Data.Store.create(default_allocator); + JSAst.Expr.Data.Store.create(default_allocator); + buffer_writer = JSPrinter.BufferWriter.init(default_allocator) catch unreachable; + buffer_writer.buffer.growBy(1024) catch unreachable; + writer = JSPrinter.BufferPrinter.init(buffer_writer); + define = Define.Define.init(default_allocator, null, null) catch unreachable; + output_source = global.Output.Source.init(output_stream, error_stream); + global.Output.Source.set(&output_source); + } else { + buffer_writer = writer.ctx; + } } const Arena = @import("./mimalloc_arena.zig").Arena; var log: Logger.Log = undefined; +const TestAnalyzer = struct { + string_buffer: std.ArrayList(u8), + items: std.ArrayList(Api.TestResponseItem), + + pub fn visitExpr(this: *TestAnalyzer, parser: *bun.js_parser.TSXParser, expr: JSAst.Expr) !void { + switch (expr.data) { + .e_call => |call| { + if (call.target.isRef(parser.jest.@"test") or call.target.isRef(parser.jest.it) or call.target.isRef(parser.jest.describe)) { + if (call.args.len > 0) { + const label_expr: JSAst.Expr = call.args.slice()[0]; + switch (label_expr.data) { + .e_string => |str| { + try str.toUTF8(this.string_buffer.allocator); + const ptr = Api.StringPointer{ + .offset = this.string_buffer.items.len, + .length = str.data.len, + }; + try this.string_buffer.appendSlice(str.data); + try this.items.append(Api.TestResponseItem{ + .byte_offset = expr.loc.start, + .kind = if (call.target.isRef(parser.jest.describe)) Api.TestKind.describe_fn else .test_fn, + .label = ptr, + }); + }, + .e_dot => {}, + else => {}, + } + + return; + } + } else if (call.target.data == .e_dot and bun.strings.eqlComptime(call.target.data.e_dot.name, "only")) { + const target = call.target.data.e_dot.target; + if (target.isRef(parser.jest.@"test") or target.isRef(parser.jest.it) or target.isRef(parser.jest.describe)) { + if (call.args.len > 0) { + const label_expr: JSAst.Expr = call.args.slice()[0]; + switch (label_expr.data) { + .e_string => |str| { + try str.toUTF8(this.string_buffer.allocator); + const ptr = Api.StringPointer{ + .offset = this.string_buffer.items.len, + .length = str.data.len, + }; + try this.string_buffer.appendSlice(str.data); + try this.items.append(Api.TestResponseItem{ + .byte_offset = expr.loc.start, + .kind = if (target.isRef(parser.jest.describe)) Api.TestKind.describe_fn else .test_fn, + .label = ptr, + }); + }, + .e_dot => {}, + else => {}, + } + + return; + } + } + } + + try this.visitExpr(parser, call.target); + for (call.args.slice()) |arg| { + try this.visitExpr(parser, arg); + } + }, + .e_binary => |bin| { + try this.visitExpr(parser, bin.left); + try this.visitExpr(parser, bin.right); + }, + .e_new => |new| { + try this.visitExpr(parser, new.target); + for (new.args.slice()) |arg| { + try this.visitExpr(parser, arg); + } + }, + + .e_array => |arr| { + for (arr.items.slice()) |item| { + try this.visitExpr(parser, item); + } + }, + + .e_if => |if_| { + try this.visitExpr(parser, if_.no); + try this.visitExpr(parser, if_.test_); + try this.visitExpr(parser, if_.yes); + }, + + .e_function => |func| { + for (func.func.body.stmts) |stmt| { + try this.visitStmt(parser, stmt); + } + }, + + .e_arrow => |arrow| { + for (arrow.body.stmts) |stmt| { + try this.visitStmt(parser, stmt); + } + }, + else => {}, + } + } + + pub fn visitStmt(this: *TestAnalyzer, parser: *bun.js_parser.TSXParser, stmt: JSAst.Stmt) anyerror!void { + switch (stmt.data) { + .s_block => |s| { + for (s.stmts) |s2| { + try this.visitStmt(parser, s2); + } + }, + .s_do_while => |s| { + try this.visitStmt(parser, s.body); + try this.visitExpr(parser, s.test_); + }, + .s_expr => |s| { + try this.visitExpr(parser, s.value); + }, + .s_for_in => |s| { + try this.visitStmt(parser, s.init); + try this.visitStmt(parser, s.body); + try this.visitExpr(parser, s.value); + }, + .s_for_of => |s| { + try this.visitStmt(parser, s.init); + try this.visitStmt(parser, s.body); + try this.visitExpr(parser, s.value); + }, + .s_for => |s| { + if (s.init) |i| { + try this.visitStmt(parser, i); + } + if (s.test_) |i| { + try this.visitExpr(parser, i); + } + if (s.update) |i| { + try this.visitExpr(parser, i); + } + + try this.visitStmt(parser, s.body); + }, + .s_function => |s| { + for (s.func.args) |arg| { + if (arg.default) |def| { + try this.visitExpr(parser, def); + } + } + + for (s.func.body.stmts) |s2| { + try this.visitStmt(parser, s2); + } + }, + .s_if => |s| { + try this.visitExpr(parser, s.test_); + try this.visitStmt(parser, s.yes); + if (s.no) |no| { + try this.visitStmt(parser, no); + } + }, + .s_local => |s| { + for (s.decls.slice()) |decl| { + if (decl.value) |val| { + try this.visitExpr(parser, val); + } + } + }, + .s_switch => |s| { + try this.visitExpr(parser, s.test_); + for (s.cases) |c| { + for (c.body) |t| { + try this.visitStmt(parser, t); + } + if (c.value) |e2| { + try this.visitExpr(parser, e2); + } + } + }, + .s_throw => |s| { + try this.visitExpr(parser, s.value); + }, + .s_try => |s| { + for (s.body) |s2| { + try this.visitStmt(parser, s2); + } + if (s.catch_) |c| { + for (c.body) |s2| { + try this.visitStmt(parser, s2); + } + } + if (s.finally) |f| { + for (f.stmts) |s2| { + try this.visitStmt(parser, s2); + } + } + }, + .s_while => |s| { + try this.visitExpr(parser, s.test_); + try this.visitStmt(parser, s.body); + }, + + .s_import => |import| { + if (bun.strings.eqlComptime(parser.import_records.items[import.import_record_index].path.text, "bun:test")) { + for (import.items) |item| { + const clause: bun.JSAst.ClauseItem = item; + if (bun.strings.eqlComptime(clause.alias, "test")) { + parser.jest.@"test" = clause.name.ref.?; + } else if (bun.strings.eqlComptime(clause.alias, "it")) { + parser.jest.it = clause.name.ref.?; + } else if (bun.strings.eqlComptime(clause.alias, "describe")) { + parser.jest.describe = clause.name.ref.?; + } + } + } + }, + else => {}, + } + } + + pub fn visitParts( + this: *TestAnalyzer, + parser: *bun.js_parser.TSXParser, + parts: []bun.JSAst.Part, + ) anyerror!void { + var jest = &parser.jest; + if (parser.symbols.items[jest.it.innerIndex()].use_count_estimate == 0) { + if (parser.symbols.items[jest.it.innerIndex()].use_count_estimate > 0) { + jest.@"test" = jest.it; + } + } else if (parser.symbols.items[jest.@"test".innerIndex()].use_count_estimate == 0) { + if (parser.symbols.items[jest.it.innerIndex()].use_count_estimate > 0) { + jest.@"test" = jest.it; + } + } + + for (parts) |part| { + for (part.stmts) |stmt| { + try this.visitStmt(parser, stmt); + } + } + } +}; +export fn getTests(opts_array: u64) u64 { + var arena = Arena.init() catch unreachable; + var allocator = arena.allocator(); + defer arena.deinit(); + var log_ = Logger.Log.init(allocator); + var reader = ApiReader.init(Uint8Array.fromJS(opts_array), allocator); + var opts = Api.GetTestsRequest.decode(&reader) catch @panic("out of memory"); + var code = Logger.Source.initPathString(if (opts.path.len > 0) opts.path else "my-test-file.test.tsx", opts.contents); + code.contents_is_recycled = true; + defer { + JSAst.Stmt.Data.Store.reset(); + JSAst.Expr.Data.Store.reset(); + } + + var parser = JSParser.Parser.init(.{ + .jsx = .{}, + .ts = true, + }, &log_, &code, define, allocator) catch @panic("out of memory"); + + var anaylzer = TestAnalyzer{ + .items = std.ArrayList( + Api.TestResponseItem, + ).init(allocator), + .string_buffer = std.ArrayList( + u8, + ).init(allocator), + }; + parser.options.features.inject_jest_globals = true; + parser.options.features.commonjs_at_runtime = true; + parser.options.features.top_level_await = true; + + parser.analyze(&anaylzer, @ptrCast(&TestAnalyzer.visitParts)) catch |err| { + Output.print("Error: {s}\n", .{@errorName(err)}); + + if (@errorReturnTrace()) |trace| { + Output.print("{}\n", .{trace}); + } + log_.printForLogLevel(Output.writer()) catch unreachable; + return 0; + }; + + var output = std.ArrayList(u8).init(default_allocator); + var output_writer = output.writer(); + const Encoder = ApiWriter(@TypeOf(output_writer)); + var encoder = Encoder.init(output_writer); + var response = Api.GetTestsResponse{ + .tests = anaylzer.items.items, + .contents = anaylzer.string_buffer.items, + }; + + response.encode(&encoder) catch return 0; + return @as(u64, @bitCast([2]u32{ @intFromPtr(output.items.ptr), output.items.len })); +} + export fn transform(opts_array: u64) u64 { // var arena = @import("root").bun.ArenaAllocator.init(default_allocator); var arena = Arena.init() catch unreachable; @@ -235,8 +535,8 @@ export fn transform(opts_array: u64) u64 { parser.options.tree_shaking = false; parser.options.features.top_level_await = true; const result = parser.parse() catch unreachable; - if (result.ok) { - var symbols: [][]JSAst.Symbol = &([_][]JSAst.Symbol{result.ast.symbols}); + if (result == .ast and log.errors == 0) { + var symbols = JSAst.Symbol.NestedList.init(&[_]JSAst.Symbol.List{result.ast.symbols}); _ = JSPrinter.printAst( @TypeOf(&writer), @@ -246,8 +546,6 @@ export fn transform(opts_array: u64) u64 { &code, false, .{}, - void, - null, false, ) catch 0; @@ -260,7 +558,7 @@ export fn transform(opts_array: u64) u64 { } transform_response = Api.TransformResponse{ - .status = if (result.ok) Api.TransformResponseStatus.success else Api.TransformResponseStatus.fail, + .status = if (result == .ast and log.errors == 0) Api.TransformResponseStatus.success else Api.TransformResponseStatus.fail, .files = &output_files, .errors = (log.toAPI(allocator) catch unreachable).msgs, }; @@ -269,7 +567,7 @@ export fn transform(opts_array: u64) u64 { var output_writer = output.writer(); const Encoder = ApiWriter(@TypeOf(output_writer)); var encoder = Encoder.init(output_writer); - transform_response.encode(&encoder) catch unreachable; + transform_response.encode(&encoder) catch {}; return @as(u64, @bitCast([2]u32{ @intFromPtr(output.items.ptr), output.items.len })); } @@ -311,10 +609,10 @@ export fn scan(opts_array: u64) u64 { var output_writer = output.writer(); const Encoder = ApiWriter(@TypeOf(output_writer)); - if (result.ok) { + if (result == .ast) { var scanned_imports = allocator.alloc(Api.ScannedImport, result.ast.import_records.len) catch unreachable; var scanned_i: usize = 0; - for (result.ast.import_records) |import_record| { + for (result.ast.import_records.slice()) |import_record| { if (import_record.kind == .internal) continue; scanned_imports[scanned_i] = Api.ScannedImport{ .path = import_record.path.text, .kind = import_record.kind.toAPI() }; scanned_i += 1; @@ -337,6 +635,7 @@ export fn emsc_main() void { _ = transform; _ = bun_free; _ = bun_malloc; + _ = getTests; } comptime { @@ -347,4 +646,5 @@ comptime { _ = bun_free; _ = scan; _ = bun_malloc; + _ = getTests; } diff --git a/src/mimalloc_arena.zig b/src/mimalloc_arena.zig index dc71a887eb736d..c5975b72d7be2a 100644 --- a/src/mimalloc_arena.zig +++ b/src/mimalloc_arena.zig @@ -80,7 +80,7 @@ const ArenaRegistry = struct { var registry = ArenaRegistry{}; pub fn register(arena: Arena) void { - if (comptime Environment.allow_assert) { + if (comptime Environment.allow_assert and Environment.isNative) { registry.mutex.lock(); defer registry.mutex.unlock(); var entry = registry.arenas.getOrPut(arena.heap.?) catch unreachable; @@ -100,7 +100,7 @@ const ArenaRegistry = struct { } pub fn assert(arena: Arena) void { - if (comptime Environment.allow_assert) { + if (comptime Environment.allow_assert and Environment.isNative) { registry.mutex.lock(); defer registry.mutex.unlock(); const expected = registry.arenas.get(arena.heap.?) orelse { @@ -117,7 +117,7 @@ const ArenaRegistry = struct { } pub fn unregister(arena: Arena) void { - if (comptime Environment.allow_assert) { + if (comptime Environment.allow_assert and Environment.isNative) { registry.mutex.lock(); defer registry.mutex.unlock(); if (!registry.arenas.swapRemove(arena.heap.?)) { diff --git a/src/napi/napi.zig b/src/napi/napi.zig index abe8316addf7d1..9d361a14e53c1e 100644 --- a/src/napi/napi.zig +++ b/src/napi/napi.zig @@ -794,7 +794,7 @@ pub export fn napi_get_dataview_info(env: napi_env, dataview: napi_value, bytele var array_buffer = dataview.asArrayBuffer(env) orelse return .object_expected; bytelength.* = array_buffer.byte_len; data.* = array_buffer.ptr; - // TODO: will this work? will it fail due to being a DataView instead of a TypedArray? + arraybuffer.* = JSValue.c(JSC.C.JSObjectGetTypedArrayBuffer(env.ref(), dataview.asObjectRef(), null)); byte_offset.* = array_buffer.offset; return .ok; @@ -806,24 +806,24 @@ pub export fn napi_get_version(_: napi_env, result: *u32) napi_status { } pub export fn napi_create_promise(env: napi_env, deferred: *napi_deferred, promise: *napi_value) napi_status { log("napi_create_promise", .{}); - deferred.* = JSC.JSPromise.Strong.init(env).strong.ref.?; - promise.* = deferred.*.get(); + var js_promise = JSC.JSPromise.create(env); + var promise_value = js_promise.asValue(env); + deferred.* = Ref.create(env, promise_value); + promise.* = promise_value; return .ok; } pub export fn napi_resolve_deferred(env: napi_env, deferred: napi_deferred, resolution: napi_value) napi_status { log("napi_resolve_deferred", .{}); - var prom = JSC.JSPromise.Strong{ - .strong = .{ .ref = deferred }, - }; + var prom = deferred.get().asPromise() orelse return .object_expected; prom.resolve(env, resolution); + deferred.destroy(); return .ok; } pub export fn napi_reject_deferred(env: napi_env, deferred: napi_deferred, rejection: napi_value) napi_status { log("napi_reject_deferred", .{}); - var prom = JSC.JSPromise.Strong{ - .strong = .{ .ref = deferred }, - }; + var prom = deferred.get().asPromise() orelse return .object_expected; prom.reject(env, rejection); + deferred.destroy(); return .ok; } pub export fn napi_is_promise(_: napi_env, value: napi_value, is_promise: *bool) napi_status { diff --git a/src/node-fallbacks/node-fetch.js b/src/node-fallbacks/node-fetch.js index c65d4f6ed62b62..e02089623f9c63 100644 --- a/src/node-fallbacks/node-fetch.js +++ b/src/node-fallbacks/node-fetch.js @@ -71,7 +71,6 @@ export default Object.assign(fetch, { fileFromSync, isRedirect, default: fetch, - [Symbol.for("CommonJS")]: 0, }); export { diff --git a/src/node_fallbacks.zig b/src/node_fallbacks.zig index a8f12594344efe..9f88bbce38029d 100644 --- a/src/node_fallbacks.zig +++ b/src/node_fallbacks.zig @@ -71,6 +71,7 @@ const assert_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("assert@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/assert/package.json", ""), }; const buffer_package_json = PackageJSON{ @@ -80,6 +81,7 @@ const buffer_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("buffer@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/buffer/package.json", ""), }; const console_package_json = PackageJSON{ @@ -89,6 +91,7 @@ const console_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("console@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/console/package.json", ""), }; const constants_package_json = PackageJSON{ @@ -98,6 +101,7 @@ const constants_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("constants@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/constants/package.json", ""), }; const crypto_package_json = PackageJSON{ @@ -107,6 +111,7 @@ const crypto_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("crypto@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/crypto/package.json", ""), }; const domain_package_json = PackageJSON{ @@ -116,6 +121,7 @@ const domain_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("domain@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/domain/package.json", ""), }; const events_package_json = PackageJSON{ @@ -125,6 +131,7 @@ const events_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("events@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/events/package.json", ""), }; const http_package_json = PackageJSON{ @@ -134,6 +141,7 @@ const http_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("http@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/http/package.json", ""), }; const https_package_json = PackageJSON{ @@ -143,6 +151,7 @@ const https_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("https@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/https/package.json", ""), }; const net_package_json = PackageJSON{ @@ -152,6 +161,7 @@ const net_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("net@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/net/package.json", ""), }; const os_package_json = PackageJSON{ @@ -161,6 +171,7 @@ const os_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("os@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/os/package.json", ""), }; const path_package_json = PackageJSON{ @@ -170,6 +181,7 @@ const path_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("path@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/path/package.json", ""), }; const process_package_json = PackageJSON{ @@ -179,6 +191,7 @@ const process_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("process@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/process/package.json", ""), }; const punycode_package_json = PackageJSON{ @@ -188,6 +201,7 @@ const punycode_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("punycode@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/punycode/package.json", ""), }; const querystring_package_json = PackageJSON{ @@ -197,6 +211,7 @@ const querystring_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("querystring@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/querystring/package.json", ""), }; const stream_package_json = PackageJSON{ @@ -206,6 +221,7 @@ const stream_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("stream@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/stream/package.json", ""), }; const string_decoder_package_json = PackageJSON{ @@ -219,6 +235,7 @@ const string_decoder_package_json = PackageJSON{ .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/string_decoder/package.json", ""), }; @@ -229,6 +246,7 @@ const sys_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("sys@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/sys/package.json", ""), }; const timers_package_json = PackageJSON{ @@ -238,6 +256,7 @@ const timers_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("timers@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/timers/package.json", ""), }; const tty_package_json = PackageJSON{ @@ -247,6 +266,7 @@ const tty_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("tty@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/tty/package.json", ""), }; const url_package_json = PackageJSON{ @@ -256,6 +276,7 @@ const url_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("url@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/url/package.json", ""), }; const util_package_json = PackageJSON{ @@ -265,6 +286,7 @@ const util_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("util@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/util/package.json", ""), }; const zlib_package_json = PackageJSON{ @@ -274,6 +296,7 @@ const zlib_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("zlib@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/zlib/package.json", ""), }; @@ -284,6 +307,7 @@ const node_fetch_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("node-fetch@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/node-fetch/package.json", ""), }; const isomorphic_fetch_package_json = PackageJSON{ @@ -293,6 +317,7 @@ const isomorphic_fetch_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("isomorphic-fetch@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/isomorphic-fetch/package.json", ""), }; const supports_color_package_json = PackageJSON{ @@ -302,6 +327,7 @@ const supports_color_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("supports-color@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/supports-color/package.json", ""), }; @@ -312,6 +338,7 @@ const vercel_fetch_package_json = PackageJSON{ .hash = @as(u32, @truncate(bun.hash("@vercel/fetch@0.0.0-polyfill"))), .main_fields = undefined, .browser_map = undefined, + .npm_cfg_map = undefined, .source = logger.Source.initPathString("/bun-vfs/node_modules/@vercel/fetch/package.json", ""), }; diff --git a/src/options.zig b/src/options.zig index f6b955a477027b..647c8378616623 100644 --- a/src/options.zig +++ b/src/options.zig @@ -594,37 +594,22 @@ pub const Target = enum { array.set(Target.node, &[_]string{ "node", - "module", }); - - var listc = [_]string{ + array.set(Target.browser, &[_]string{ "browser", "module", - }; - array.set(Target.browser, &listc); - array.set( - Target.bun, - &[_]string{ - "bun", - "worker", - "module", - "node", - "default", - "browser", - }, - ); - array.set( - Target.bun_macro, - &[_]string{ - "macro", - "bun", - "worker", - "module", - "node", - "default", - "browser", - }, - ); + }); + array.set(Target.bun, &[_]string{ + "bun", + "worker", + "node", + }); + array.set(Target.bun_macro, &[_]string{ + "macro", + "bun", + "worker", + "node", + }); break :brk array; }; @@ -1450,6 +1435,8 @@ pub const BundleOptions = struct { minify_syntax: bool = false, minify_identifiers: bool = false, + code_coverage: bool = false, + compile: bool = false, /// This is a list of packages which even when require() is used, we will diff --git a/src/output.zig b/src/output.zig index cffa2c4143d256..4feab61893b9e7 100644 --- a/src/output.zig +++ b/src/output.zig @@ -3,7 +3,7 @@ const bun = @import("root").bun; const std = @import("std"); const Environment = @import("./env.zig"); const string = @import("root").bun.string; -const root = @import("root").bun; +const root = @import("root"); const strings = @import("root").bun.strings; const StringTypes = @import("root").bun.StringTypes; const Global = @import("root").bun.Global; @@ -402,10 +402,11 @@ pub noinline fn print(comptime fmt: string, args: anytype) void { if (comptime Environment.allow_assert) std.debug.assert(source_set); + // There's not much we can do if this errors. Especially if it's something like BrokenPipe. if (enable_buffering) { - std.fmt.format(source.buffered_stream.writer(), fmt, args) catch unreachable; + std.fmt.format(source.buffered_stream.writer(), fmt, args) catch {}; } else { - std.fmt.format(writer(), fmt, args) catch unreachable; + std.fmt.format(writer(), fmt, args) catch {}; } } } @@ -419,7 +420,7 @@ pub noinline fn print(comptime fmt: string, args: anytype) void { /// BUN_DEBUG_ALL=1 const _log_fn = fn (comptime fmt: string, args: anytype) void; pub fn scoped(comptime tag: @Type(.EnumLiteral), comptime disabled: bool) _log_fn { - if (comptime !Environment.isDebug) { + if (comptime !Environment.isDebug or !Environment.isNative) { return struct { pub fn log(comptime _: string, _: anytype) void {} }.log; @@ -664,6 +665,7 @@ pub noinline fn printError(comptime fmt: string, args: anytype) void { source.error_stream.writer().print(fmt, args) catch unreachable; root.console_error(root.Uint8Array.fromSlice(source.err_buffer[0..source.error_stream.pos])); } else { + // There's not much we can do if this errors. Especially if it's something like BrokenPipe if (enable_buffering) std.fmt.format(source.buffered_error_stream.writer(), fmt, args) catch {} else diff --git a/src/renamer.zig b/src/renamer.zig index b2164703d80b5d..9d2f7d414bbd0e 100644 --- a/src/renamer.zig +++ b/src/renamer.zig @@ -875,6 +875,10 @@ pub const ExportRenamer = struct { pub fn computeInitialReservedNames( allocator: std.mem.Allocator, ) !bun.StringHashMapUnmanaged(u32) { + if (comptime bun.Environment.isWasm) { + unreachable; + } + var names = bun.StringHashMapUnmanaged(u32){}; const extras = .{ diff --git a/src/resolver/data_url.zig b/src/resolver/data_url.zig index dd31605d9550c2..f2a042c4ff0bc9 100644 --- a/src/resolver/data_url.zig +++ b/src/resolver/data_url.zig @@ -34,7 +34,7 @@ pub const PercentEncoding = struct { if (comptime Environment.allow_assert) std.debug.assert(str.len > 0); return switch (str[0]) { 'a'...'z', 'A'...'Z', '0'...'9', '-', '.', '_', '~', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '@' => true, - '%' => str.len > 3 and isHex(str[1]) and isHex(str[2]), + '%' => str.len >= 3 and isHex(str[1]) and isHex(str[2]), else => false, }; } @@ -53,7 +53,7 @@ pub const PercentEncoding = struct { } if (ret == null) { ret = try allocator.alloc(u8, path.len); - bun.copy(u8, ret, path[0..i]); + bun.copy(u8, ret.?, path[0..i]); ret_index = i; } @@ -71,22 +71,28 @@ pub const PercentEncoding = struct { } } - if (ret) |some| return allocator.shrink(some, ret_index); + if (ret) |some| return some[0..ret_index]; return null; } }; pub const DataURL = struct { + url: bun.String = bun.String.empty, mime_type: string, data: string, is_base64: bool = false, - pub fn parse(url: string) ?DataURL { + pub fn parse(url: string) !?DataURL { if (!strings.startsWith(url, "data:")) { return null; } - const comma = strings.indexOfChar(url, ',') orelse return null; + var result = try parseWithoutCheck(url); + return result; + } + + pub fn parseWithoutCheck(url: string) !DataURL { + const comma = strings.indexOfChar(url, ',') orelse return error.InvalidDataURL; var parsed = DataURL{ .mime_type = url["data:".len..comma], @@ -102,6 +108,21 @@ pub const DataURL = struct { } pub fn decodeMimeType(d: DataURL) bun.HTTP.MimeType { - return bun.HTTP.MimeType.init(d.mime_type); + return bun.HTTP.MimeType.init(d.mime_type, null, null); + } + + pub fn decodeData(url: DataURL, allocator: std.mem.Allocator) ![]u8 { + const percent_decoded = PercentEncoding.decode(allocator, url.data) catch url.data orelse url.data; + if (url.is_base64) { + const len = bun.base64.decodeLen(percent_decoded); + var buf = try allocator.alloc(u8, len); + const result = bun.base64.decode(buf, percent_decoded); + if (result.fail or result.written != len) { + return error.Base64DecodeError; + } + return buf; + } + + return allocator.dupe(u8, percent_decoded); } }; diff --git a/src/resolver/package_json.zig b/src/resolver/package_json.zig index 75e6a7c98623eb..5e3ed5dd3f1d1c 100644 --- a/src/resolver/package_json.zig +++ b/src/resolver/package_json.zig @@ -23,6 +23,7 @@ const resolve_path = @import("./resolve_path.zig"); // Assume they're not going to have hundreds of main fields or browser map // so use an array-backed hash table instead of bucketed const MainFieldMap = bun.StringMap; +const NpmCfgMap = bun.StringMap; pub const BrowserMap = bun.StringMap; pub const MacroImportReplacementMap = bun.StringArrayHashMap(string); pub const MacroMap = bun.StringArrayHashMapUnmanaged(MacroImportReplacementMap); @@ -144,7 +145,7 @@ pub const PackageJSON = struct { // should match and the query "./ext" should ALSO match. // browser_map: BrowserMap, - + npm_cfg_map: NpmCfgMap, exports: ?ExportsMap = null, imports: ?ExportsMap = null, @@ -644,6 +645,7 @@ pub const PackageJSON = struct { .module_type = .unknown, .browser_map = BrowserMap.init(allocator, false), .main_fields = MainFieldMap.init(allocator, false), + .npm_cfg_map = NpmCfgMap.init(allocator, false), }; // Note: we tried rewriting this to be fewer loops over all the properties (asProperty loops over each) @@ -667,6 +669,22 @@ pub const PackageJSON = struct { } } + if (json.asProperty("config")) |npm_pkg_cfg| { + switch (npm_pkg_cfg.expr.data) { + .e_object => |obj| { + for (obj.properties.slice()) |*prop| { + const key = prop.key.?.asString(allocator) orelse continue; + const value = prop.value.?.asString(allocator) orelse continue; + + if (!(key.len > 0 and value.len > 0)) continue; + + package_json.npm_cfg_map.put(key, value) catch unreachable; + } + }, + else => r.log.addWarning(&json_source, npm_pkg_cfg.loc, "The \"config\" field must be an object") catch unreachable, + } + } + // If we're coming from `bun run` // We do not need to parse all this stuff. if (comptime !include_scripts) { @@ -1010,6 +1028,57 @@ pub const PackageJSON = struct { } } } + + if (json.asProperty("config")) |npm_pkg_cfg| { +<<<<<<< HEAD +<<<<<<< HEAD + parseNpmCfg(allocator, &json_source, r, npm_pkg_cfg.expr, &package_json, ""); +======= + switch (npm_pkg_cfg.expr.data) { + .e_object => |obj| { + for (obj.properties.slice()) |*prop| { + const key = prop.key.?.asString(allocator) orelse continue; + if (!(key.len > 0)) continue; + + // TODO: https://github.com/oven-sh/bun/pull/3661#discussion_r1265966897 + switch (prop.value.?.data) { + .e_string => { + const value = prop.value.?.data.asString(); + package_json.npm_cfg_map.put(key, value) catch unreachable; + }, + .e_number => { + if (prop.value.?.data.e_number.toStringSafelyWithDecimalPlaces(allocator)) |value| { + if (!(value.len > 0)) continue; + package_json.npm_cfg_map.put(key, value) catch unreachable; + } + }, + .e_boolean => { + const value = prop.value.?.asBool() orelse continue; + if (value) { + package_json.npm_cfg_map.put(key, "true") catch unreachable; + } else { + // Node.js interprets false as a empty string + package_json.npm_cfg_map.put(key, "") catch unreachable; + } + }, + .e_null => { + // Node.js interprets null as a empty string + package_json.npm_cfg_map.put(key, "") catch unreachable; + }, + else => { + r.log.addWarning(&json_source, prop.value.?.loc, "Values of \"config\" must be either a boolean, number or string") catch unreachable; + continue; + }, + } + } + }, + else => r.log.addWarning(&json_source, npm_pkg_cfg.loc, "The \"config\" field must be an object") catch unreachable, + } +>>>>>>> d653e7c3 (Add support for numbers + booleans) +======= + parseNpmCfg(allocator, &json_source, r, npm_pkg_cfg.expr, &package_json, ""); +>>>>>>> 8c495ce8 (Add object support) + } } if (generate_hash) { @@ -1021,6 +1090,78 @@ pub const PackageJSON = struct { return package_json; } + pub fn parseNpmCfg(allocator: std.mem.Allocator, json_source: ?*const logger.Source, r: *resolver.Resolver, jsonDataExpr: js_ast.Expr, package_json: *PackageJSON, prefix: []const u8) void { + switch (jsonDataExpr.data) { + .e_object => |obj| { + for (obj.properties.slice()) |*prop| { + const key = prop.key.?.asString(allocator) orelse continue; + if (key.len <= 0) continue; + + const lkey = strings.concat(allocator, &.{prefix, key}) catch unreachable; + + switch (prop.value.?.data) { + .e_object => { + const newkey = strings.concat(allocator, &.{lkey, "_"}) catch unreachable; + parseNpmCfg(allocator, json_source, r, prop.value.?, package_json, newkey); + }, + .e_string => { + const value = prop.value.?.asString(allocator) orelse continue; + package_json.npm_cfg_map.put(lkey, value) catch unreachable; + }, + .e_number => { + if (prop.value.?.data.e_number.toStringSafelyWithDecimalPlaces(allocator)) |value| { + if (!(value.len > 0)) continue; + package_json.npm_cfg_map.put(lkey, value) catch unreachable; + } + }, + .e_boolean => { + const value = prop.value.?.asBool() orelse continue; + if (value) { + package_json.npm_cfg_map.put(lkey, "true") catch unreachable; + } else { +<<<<<<< HEAD +<<<<<<< HEAD + // Node.js interprets false as an empty string +======= + // Node.js interprets false as a empty string +>>>>>>> 8c495ce8 (Add object support) +======= + // Node.js interprets false as an empty string +>>>>>>> fece4811 (Little fixes) + package_json.npm_cfg_map.put(lkey, "") catch unreachable; + } + }, + .e_null => { +<<<<<<< HEAD +<<<<<<< HEAD + // Node.js interprets null as an empty string + package_json.npm_cfg_map.put(lkey, "") catch unreachable; + }, + else => { + r.log.addWarning(json_source, prop.value.?.loc, "Values of 'config' must be either a boolean, number, string, or object.") catch unreachable; +======= + // Node.js interprets null as a empty string + package_json.npm_cfg_map.put(lkey, "") catch unreachable; + }, + else => { + r.log.addWarning(json_source, prop.value.?.loc, "Values of \"config\" must be either a boolean, number or string") catch unreachable; +>>>>>>> 8c495ce8 (Add object support) +======= + // Node.js interprets null as an empty string + package_json.npm_cfg_map.put(lkey, "") catch unreachable; + }, + else => { + r.log.addWarning(json_source, prop.value.?.loc, "Values of 'config' must be either a boolean, number, string, or object.") catch unreachable; +>>>>>>> fece4811 (Little fixes) + continue; + }, + } + } + }, + else => r.log.addWarning(json_source, jsonDataExpr.loc, "The \"config\" field must be an object") catch unreachable, + } + } + pub fn hashModule(this: *const PackageJSON, module: string) u32 { var hasher = bun.Wyhash.init(0); hasher.update(std.mem.asBytes(&this.hash)); diff --git a/src/resolver/resolve_path.zig b/src/resolver/resolve_path.zig index 877f32ded21461..4800d7d90c1af9 100644 --- a/src/resolver/resolve_path.zig +++ b/src/resolver/resolve_path.zig @@ -294,13 +294,20 @@ pub fn longestCommonPathGeneric(input: []const []const u8, comptime separator: u // /app/public/ // To detect /app/public is actually a folder, we do one more loop through the strings // and say, "do one of you have a path separator after what we thought was the end?" - for (input) |str| { + var idx = input.len; // Use this value as an invalid value. + for (input, 0..) |str, i| { if (str.len > index) { if (@call(.always_inline, isPathSeparator, .{str[index]})) { - return str[0 .. index + 1]; + idx = i; + } else { + idx = input.len; + break; } } } + if (idx != input.len) { + return input[idx][0 .. index + 1]; + } return input[0][0 .. last_common_separator + 1]; } @@ -340,7 +347,7 @@ pub fn relativeToCommonPath( const shortest = @min(normalized_from.len, normalized_to.len); - var last_common_separator = strings.lastIndexOfChar(_common_path, separator) orelse 0; + const last_common_separator = strings.lastIndexOfChar(_common_path, separator) orelse 0; if (shortest == common_path.len) { if (normalized_to.len > normalized_from.len) { diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig index 49ce9ec11ed11c..4aa4239ddf51ab 100644 --- a/src/resolver/resolver.zig +++ b/src/resolver/resolver.zig @@ -32,6 +32,7 @@ const NodeFallbackModules = @import("../node_fallbacks.zig"); const Mutex = @import("../lock.zig").Lock; const StringBoolMap = bun.StringHashMap(bool); const FileDescriptorType = bun.FileDescriptor; +const JSC = bun.JSC; const allocators = @import("../allocators.zig"); const Msg = logger.Msg; @@ -841,7 +842,9 @@ pub const Resolver = struct { } } - if (DataURL.parse(import_path)) |_data_url| { + if (DataURL.parse(import_path) catch { + return .{ .failure = error.InvalidDataURL }; + }) |_data_url| { const data_url: DataURL = _data_url; // "import 'data:text/javascript,console.log(123)';" // "@import 'data:text/css,body{background:white}';" @@ -1272,6 +1275,8 @@ pub const Resolver = struct { // "fs" // "fs/*" // These are disabled! + } else if (had_node_prefix and !JSC.HardcodedModule.Aliases.has(import_path_without_node_prefix)) { + return .{ .not_found = {} }; } else if (had_node_prefix or (strings.hasPrefixComptime(import_path_without_node_prefix, "fs") and (import_path_without_node_prefix.len == 2 or diff --git a/src/runtime.zig b/src/runtime.zig index 89fd66e7700d1e..790f5b197e451e 100644 --- a/src/runtime.zig +++ b/src/runtime.zig @@ -314,8 +314,6 @@ pub const Runtime = struct { replace_exports: ReplaceableExport.Map = .{}, - hoist_bun_plugin: bool = false, - dont_bundle_twice: bool = false, /// This is a list of packages which even when require() is used, we will diff --git a/src/sourcemap/CodeCoverage.zig b/src/sourcemap/CodeCoverage.zig new file mode 100644 index 00000000000000..a6982c603abced --- /dev/null +++ b/src/sourcemap/CodeCoverage.zig @@ -0,0 +1,651 @@ +const bun = @import("root").bun; +const std = @import("std"); +const LineOffsetTable = bun.sourcemap.LineOffsetTable; +const SourceMap = bun.sourcemap; +const Bitset = bun.bit_set.DynamicBitSetUnmanaged; +const Output = bun.Output; +const prettyFmt = Output.prettyFmt; + +/// Our code coverage currently only deals with lines of code, not statements or branches. +/// JSC doesn't expose function names in their coverage data, so we don't include that either :(. +/// Since we only need to store line numbers, our job gets simpler +/// +/// We can use two bitsets to store code coverage data for a given file +/// 1. executable_lines +/// 2. lines_which_have_executed +/// +/// Not all lines of code are executable. Comments, whitespace, empty lines, etc. are not executable. +/// It's not a problem for anyone if comments, whitespace, empty lines etc are not executed, so those should always be omitted from coverage reports +/// +/// We use two bitsets since the typical size will be decently small, +/// bitsets are simple and bitsets are relatively fast to construct and query +/// +pub const CodeCoverageReport = struct { + source_url: bun.JSC.ZigString.Slice, + executable_lines: Bitset, + lines_which_have_executed: Bitset, + functions: std.ArrayListUnmanaged(Block), + functions_which_have_executed: Bitset, + stmts_which_have_executed: Bitset, + stmts: std.ArrayListUnmanaged(Block), + total_lines: u32 = 0, + + pub const Block = struct { + start_line: u32 = 0, + end_line: u32 = 0, + }; + + pub fn linesCoverageFraction(this: *const CodeCoverageReport) f64 { + var intersected = this.executable_lines.clone(bun.default_allocator) catch @panic("OOM"); + defer intersected.deinit(bun.default_allocator); + intersected.setIntersection(this.lines_which_have_executed); + + const total_count: f64 = @floatFromInt(this.executable_lines.count()); + if (total_count == 0) { + return 1.0; + } + + const intersected_count: f64 = @floatFromInt(intersected.count()); + + return (intersected_count / total_count); + } + + pub fn stmtsCoverageFraction(this: *const CodeCoverageReport) f64 { + const total_count: f64 = @floatFromInt(this.stmts.items.len); + + if (total_count == 0) { + return 1.0; + } + + return ((@as(f64, @floatFromInt(this.stmts_which_have_executed.count()))) / (total_count)); + } + + pub fn functionCoverageFraction(this: *const CodeCoverageReport) f64 { + const total_count: f64 = @floatFromInt(this.functions.items.len); + if (total_count == 0) { + return 1.0; + } + return (@as(f64, @floatFromInt(this.functions_which_have_executed.count())) / total_count); + } + + pub fn writeFormatWithValues( + filename: []const u8, + max_filename_length: usize, + vals: CoverageFraction, + failing: CoverageFraction, + failed: bool, + writer: anytype, + indent_name: bool, + comptime enable_colors: bool, + ) !void { + if (comptime enable_colors) { + if (failed) { + try writer.writeAll(comptime prettyFmt("", true)); + } else { + try writer.writeAll(comptime prettyFmt("", true)); + } + } + + if (indent_name) { + try writer.writeAll(" "); + } + + try writer.writeAll(filename); + try writer.writeByteNTimes(' ', (max_filename_length - filename.len + @as(usize, @intFromBool(!indent_name)))); + try writer.writeAll(comptime prettyFmt(" | ", enable_colors)); + + if (comptime enable_colors) { + if (vals.functions < failing.functions) { + try writer.writeAll(comptime prettyFmt("", true)); + } else { + try writer.writeAll(comptime prettyFmt("", true)); + } + } + + try writer.print("{d: >7.2}", .{vals.functions * 100.0}); + // try writer.writeAll(comptime prettyFmt(" | ", enable_colors)); + // if (comptime enable_colors) { + // // if (vals.stmts < failing.stmts) { + // try writer.writeAll(comptime prettyFmt("", true)); + // // } else { + // // try writer.writeAll(comptime prettyFmt("", true)); + // // } + // } + // try writer.print("{d: >8.2}", .{vals.stmts * 100.0}); + try writer.writeAll(comptime prettyFmt(" | ", enable_colors)); + + if (comptime enable_colors) { + if (vals.lines < failing.lines) { + try writer.writeAll(comptime prettyFmt("", true)); + } else { + try writer.writeAll(comptime prettyFmt("", true)); + } + } + + try writer.print("{d: >7.2}", .{vals.lines * 100.0}); + } + + pub fn writeFormat( + report: *const CodeCoverageReport, + max_filename_length: usize, + fraction: *CoverageFraction, + base_path: []const u8, + writer: anytype, + comptime enable_colors: bool, + ) !void { + var failing = fraction.*; + const fns = report.functionCoverageFraction(); + const lines = report.linesCoverageFraction(); + const stmts = report.stmtsCoverageFraction(); + fraction.functions = fns; + fraction.lines = lines; + fraction.stmts = stmts; + + const failed = fns < failing.functions or lines < failing.lines; // or stmts < failing.stmts; + fraction.failing = failed; + + var filename = report.source_url.slice(); + if (base_path.len > 0) { + filename = bun.path.relative(base_path, filename); + } + + try writeFormatWithValues( + filename, + max_filename_length, + fraction.*, + failing, + failed, + writer, + true, + enable_colors, + ); + + try writer.writeAll(comptime prettyFmt(" | ", enable_colors)); + + var executable_lines_that_havent_been_executed = report.lines_which_have_executed.clone(bun.default_allocator) catch @panic("OOM"); + defer executable_lines_that_havent_been_executed.deinit(bun.default_allocator); + executable_lines_that_havent_been_executed.toggleAll(); + + // This sets statements in executed scopes + executable_lines_that_havent_been_executed.setIntersection(report.executable_lines); + + var iter = executable_lines_that_havent_been_executed.iterator(.{}); + var start_of_line_range: usize = 0; + var prev_line: usize = 0; + var is_first = true; + + while (iter.next()) |next_line| { + if (next_line == (prev_line + 1)) { + prev_line = next_line; + continue; + } else if (is_first and start_of_line_range == 0 and prev_line == 0) { + start_of_line_range = next_line; + prev_line = next_line; + continue; + } + + if (is_first) { + is_first = false; + } else { + try writer.print(comptime prettyFmt(",", enable_colors), .{}); + } + + if (start_of_line_range == prev_line) { + try writer.print(comptime prettyFmt("{d}", enable_colors), .{start_of_line_range + 1}); + } else { + try writer.print(comptime prettyFmt("{d}-{d}", enable_colors), .{ start_of_line_range + 1, prev_line + 1 }); + } + + prev_line = next_line; + start_of_line_range = next_line; + } + + if (prev_line != start_of_line_range) { + if (is_first) { + is_first = false; + } else { + try writer.print(comptime prettyFmt(",", enable_colors), .{}); + } + + if (start_of_line_range == prev_line) { + try writer.print(comptime prettyFmt("{d}", enable_colors), .{start_of_line_range + 1}); + } else { + try writer.print(comptime prettyFmt("{d}-{d}", enable_colors), .{ start_of_line_range + 1, prev_line + 1 }); + } + } + } + + pub fn deinit(this: *CodeCoverageReport, allocator: std.mem.Allocator) void { + this.executable_lines.deinit(allocator); + this.lines_which_have_executed.deinit(allocator); + this.functions.deinit(allocator); + this.stmts.deinit(allocator); + this.functions_which_have_executed.deinit(allocator); + this.stmts_which_have_executed.deinit(allocator); + } + + extern fn CodeCoverage__withBlocksAndFunctions( + *bun.JSC.VM, + i32, + *anyopaque, + bool, + *const fn ( + *Generator, + [*]const BasicBlockRange, + usize, + usize, + bool, + ) callconv(.C) void, + ) bool; + + const Generator = struct { + allocator: std.mem.Allocator, + byte_range_mapping: *ByteRangeMapping, + result: *?CodeCoverageReport, + + pub fn do( + this: *@This(), + blocks_ptr: [*]const BasicBlockRange, + blocks_len: usize, + function_start_offset: usize, + ignore_sourcemap: bool, + ) callconv(.C) void { + const blocks: []const BasicBlockRange = blocks_ptr[0..function_start_offset]; + var function_blocks: []const BasicBlockRange = blocks_ptr[function_start_offset..blocks_len]; + if (function_blocks.len > 1) { + function_blocks = function_blocks[1..]; + } + + if (blocks.len == 0) { + return; + } + + this.result.* = this.byte_range_mapping.generateCodeCoverageReportFromBlocks( + this.allocator, + this.byte_range_mapping.source_url, + blocks, + function_blocks, + ignore_sourcemap, + ) catch null; + } + }; + + pub fn generate( + globalThis: *bun.JSC.JSGlobalObject, + allocator: std.mem.Allocator, + byte_range_mapping: *ByteRangeMapping, + ignore_sourcemap_: bool, + ) ?CodeCoverageReport { + bun.JSC.markBinding(@src()); + var vm = globalThis.vm(); + + var result: ?CodeCoverageReport = null; + + var generator = Generator{ + .result = &result, + .allocator = allocator, + .byte_range_mapping = byte_range_mapping, + }; + + if (!CodeCoverage__withBlocksAndFunctions( + vm, + byte_range_mapping.source_id, + &generator, + ignore_sourcemap_, + &Generator.do, + )) { + return null; + } + + return result; + } +}; + +const BasicBlockRange = extern struct { + startOffset: c_int = 0, + endOffset: c_int = 0, + hasExecuted: bool = false, + executionCount: usize = 0, +}; + +pub const ByteRangeMapping = struct { + line_offset_table: LineOffsetTable.List = .{}, + source_id: i32, + source_url: bun.JSC.ZigString.Slice, + + pub fn isLessThan(_: void, a: ByteRangeMapping, b: ByteRangeMapping) bool { + return bun.strings.order(a.source_url.slice(), b.source_url.slice()) == .lt; + } + + pub const HashMap = std.HashMap(u64, ByteRangeMapping, bun.IdentityContext(u64), std.hash_map.default_max_load_percentage); + + pub fn deinit(this: *ByteRangeMapping) void { + this.line_offset_table.deinit(bun.default_allocator); + } + + pub threadlocal var map: ?*HashMap = null; + pub fn generate(str: bun.String, source_contents_str: bun.String, source_id: i32) callconv(.C) void { + var _map = map orelse brk: { + map = bun.JSC.VirtualMachine.get().allocator.create(HashMap) catch @panic("OOM"); + map.?.* = HashMap.init(bun.JSC.VirtualMachine.get().allocator); + break :brk map.?; + }; + var slice = str.toUTF8(bun.default_allocator); + const hash = bun.hash(slice.slice()); + var entry = _map.getOrPut(hash) catch @panic("Out of memory"); + if (entry.found_existing) { + entry.value_ptr.deinit(); + } + + var source_contents = source_contents_str.toUTF8(bun.default_allocator); + defer source_contents.deinit(); + + entry.value_ptr.* = compute(source_contents.slice(), source_id, slice); + } + + pub fn getSourceID(this: *ByteRangeMapping) callconv(.C) i32 { + return this.source_id; + } + + pub fn find(path: bun.String) callconv(.C) ?*ByteRangeMapping { + var slice = path.toUTF8(bun.default_allocator); + defer slice.deinit(); + + var map_ = map orelse return null; + const hash = bun.hash(slice.slice()); + var entry = map_.getPtr(hash) orelse return null; + return entry; + } + + pub fn generateCodeCoverageReportFromBlocks( + this: *ByteRangeMapping, + allocator: std.mem.Allocator, + source_url: bun.JSC.ZigString.Slice, + blocks: []const BasicBlockRange, + function_blocks: []const BasicBlockRange, + ignore_sourcemap: bool, + ) !CodeCoverageReport { + var line_starts = this.line_offset_table.items(.byte_offset_to_start_of_line); + + var executable_lines: Bitset = Bitset{}; + var lines_which_have_executed: Bitset = Bitset{}; + const parsed_mappings_ = bun.JSC.VirtualMachine.get().source_mappings.get( + source_url.slice(), + ); + + var functions = std.ArrayListUnmanaged(CodeCoverageReport.Block){}; + try functions.ensureTotalCapacityPrecise(allocator, function_blocks.len); + errdefer functions.deinit(allocator); + var functions_which_have_executed: Bitset = try Bitset.initEmpty(allocator, function_blocks.len); + errdefer functions_which_have_executed.deinit(allocator); + var stmts_which_have_executed: Bitset = try Bitset.initEmpty(allocator, blocks.len); + errdefer stmts_which_have_executed.deinit(allocator); + + var stmts = std.ArrayListUnmanaged(CodeCoverageReport.Block){}; + try stmts.ensureTotalCapacityPrecise(allocator, function_blocks.len); + errdefer stmts.deinit(allocator); + + errdefer executable_lines.deinit(allocator); + errdefer lines_which_have_executed.deinit(allocator); + var line_count: u32 = 0; + + if (ignore_sourcemap or parsed_mappings_ == null) { + line_count = @truncate(line_starts.len); + executable_lines = try Bitset.initEmpty(allocator, line_count); + lines_which_have_executed = try Bitset.initEmpty(allocator, line_count); + for (blocks, 0..) |block, i| { + const min: usize = @intCast(@min(block.startOffset, block.endOffset)); + const max: usize = @intCast(@max(block.startOffset, block.endOffset)); + var min_line: u32 = std.math.maxInt(u32); + var max_line: u32 = 0; + + const has_executed = block.hasExecuted or block.executionCount > 0; + + for (min..max) |byte_offset| { + const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; + const line_start_byte_offset = line_starts[new_line_index]; + if (line_start_byte_offset >= byte_offset) { + continue; + } + + const line: u32 = @intCast(new_line_index); + min_line = @min(min_line, line); + max_line = @max(max_line, line); + + executable_lines.set(@intCast(new_line_index)); + if (has_executed) { + lines_which_have_executed.set(@intCast(new_line_index)); + } + } + + if (min_line != std.math.maxInt(u32)) { + if (has_executed) + stmts_which_have_executed.set(i); + + try stmts.append(allocator, .{ + .start_line = min_line, + .end_line = max_line, + }); + } + } + + for (function_blocks, 0..) |function, i| { + const min: usize = @intCast(@min(function.startOffset, function.endOffset)); + const max: usize = @intCast(@max(function.startOffset, function.endOffset)); + var min_line: u32 = std.math.maxInt(u32); + var max_line: u32 = 0; + + for (min..max) |byte_offset| { + const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; + const line_start_byte_offset = line_starts[new_line_index]; + if (line_start_byte_offset >= byte_offset) { + continue; + } + + const line: u32 = @intCast(new_line_index); + min_line = @min(min_line, line); + max_line = @max(max_line, line); + } + + const did_fn_execute = function.executionCount > 0 or function.hasExecuted; + + // only mark the lines as executable if the function has not executed + // functions that have executed have non-executable lines in them and thats fine. + if (!did_fn_execute) { + const end = @min(max_line, line_count); + for (min_line..end) |line| { + executable_lines.set(line); + lines_which_have_executed.unset(line); + } + } + + try functions.append(allocator, .{ + .start_line = min_line, + .end_line = max_line, + }); + + if (did_fn_execute) + functions_which_have_executed.set(i); + } + } else if (parsed_mappings_) |parsed_mapping| { + line_count = @as(u32, @truncate(parsed_mapping.input_line_count)) + 1; + executable_lines = try Bitset.initEmpty(allocator, line_count); + lines_which_have_executed = try Bitset.initEmpty(allocator, line_count); + + for (blocks, 0..) |block, i| { + const min: usize = @intCast(@min(block.startOffset, block.endOffset)); + const max: usize = @intCast(@max(block.startOffset, block.endOffset)); + var min_line: u32 = std.math.maxInt(u32); + var max_line: u32 = 0; + const has_executed = block.hasExecuted or block.executionCount > 0; + + for (min..max) |byte_offset| { + const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; + const line_start_byte_offset = line_starts[new_line_index]; + if (line_start_byte_offset >= byte_offset) { + continue; + } + const column_position = byte_offset -| line_start_byte_offset; + + if (SourceMap.Mapping.find(parsed_mapping.mappings, @intCast(new_line_index), @intCast(column_position))) |point| { + if (point.original.lines < 0) continue; + + const line: u32 = @as(u32, @intCast(point.original.lines)); + + executable_lines.set(line); + if (has_executed) { + lines_which_have_executed.set(line); + } + + min_line = @min(min_line, line); + max_line = @max(max_line, line); + } + } + + if (min_line != std.math.maxInt(u32)) { + try stmts.append(allocator, .{ + .start_line = min_line, + .end_line = max_line, + }); + + if (has_executed) + stmts_which_have_executed.set(i); + } + } + + for (function_blocks, 0..) |function, i| { + const min: usize = @intCast(@min(function.startOffset, function.endOffset)); + const max: usize = @intCast(@max(function.startOffset, function.endOffset)); + var min_line: u32 = std.math.maxInt(u32); + var max_line: u32 = 0; + + for (min..max) |byte_offset| { + const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; + const line_start_byte_offset = line_starts[new_line_index]; + if (line_start_byte_offset >= byte_offset) { + continue; + } + + const column_position = byte_offset -| line_start_byte_offset; + + if (SourceMap.Mapping.find(parsed_mapping.mappings, @intCast(new_line_index), @intCast(column_position))) |point| { + if (point.original.lines < 0) continue; + + const line: u32 = @as(u32, @intCast(point.original.lines)); + min_line = @min(min_line, line); + max_line = @max(max_line, line); + } + } + + // no sourcemaps? ignore it + if (min_line == std.math.maxInt(u32) and max_line == 0) { + continue; + } + + const did_fn_execute = function.executionCount > 0 or function.hasExecuted; + + // only mark the lines as executable if the function has not executed + // functions that have executed have non-executable lines in them and thats fine. + if (!did_fn_execute) { + const end = @min(max_line, line_count); + for (min_line..end) |line| { + executable_lines.set(line); + lines_which_have_executed.unset(line); + } + } + + try functions.append(allocator, .{ + .start_line = min_line, + .end_line = max_line, + }); + if (did_fn_execute) + functions_which_have_executed.set(i); + } + } else { + unreachable; + } + + return CodeCoverageReport{ + .source_url = source_url, + .functions = functions, + .executable_lines = executable_lines, + .lines_which_have_executed = lines_which_have_executed, + .total_lines = line_count, + .stmts = stmts, + .functions_which_have_executed = functions_which_have_executed, + .stmts_which_have_executed = stmts_which_have_executed, + }; + } + + pub fn findExecutedLines( + globalThis: *bun.JSC.JSGlobalObject, + source_url: bun.String, + blocks_ptr: [*]const BasicBlockRange, + blocks_len: usize, + function_start_offset: usize, + ignore_sourcemap: bool, + ) callconv(.C) bun.JSC.JSValue { + var this = ByteRangeMapping.find(source_url) orelse return bun.JSC.JSValue.null; + + const blocks: []const BasicBlockRange = blocks_ptr[0..function_start_offset]; + var function_blocks: []const BasicBlockRange = blocks_ptr[function_start_offset..blocks_len]; + if (function_blocks.len > 1) { + function_blocks = function_blocks[1..]; + } + var url_slice = source_url.toUTF8(bun.default_allocator); + defer url_slice.deinit(); + var report = this.generateCodeCoverageReportFromBlocks(bun.default_allocator, url_slice, blocks, function_blocks, ignore_sourcemap) catch { + globalThis.throwOutOfMemory(); + return .zero; + }; + defer report.deinit(bun.default_allocator); + + var coverage_fraction = CoverageFraction{}; + + var mutable_str = bun.MutableString.initEmpty(bun.default_allocator); + defer mutable_str.deinit(); + var buffered_writer = mutable_str.bufferedWriter(); + var writer = buffered_writer.writer(); + + report.writeFormat(source_url.utf8ByteLength(), &coverage_fraction, "", &writer, false) catch { + globalThis.throwOutOfMemory(); + return .zero; + }; + + buffered_writer.flush() catch { + globalThis.throwOutOfMemory(); + return .zero; + }; + + var str = bun.String.create(mutable_str.toOwnedSliceLeaky()); + defer str.deref(); + return str.toJS(globalThis); + } + + pub fn compute(source_contents: []const u8, source_id: i32, source_url: bun.JSC.ZigString.Slice) ByteRangeMapping { + return ByteRangeMapping{ + .line_offset_table = LineOffsetTable.generate(bun.JSC.VirtualMachine.get().allocator, source_contents, 0), + .source_id = source_id, + .source_url = source_url, + }; + } +}; + +comptime { + if (bun.Environment.isNative) { + @export(ByteRangeMapping.generate, .{ .name = "ByteRangeMapping__generate" }); + @export(ByteRangeMapping.findExecutedLines, .{ .name = "ByteRangeMapping__findExecutedLines" }); + @export(ByteRangeMapping.find, .{ .name = "ByteRangeMapping__find" }); + @export(ByteRangeMapping.getSourceID, .{ .name = "ByteRangeMapping__getSourceID" }); + } +} + +pub const CoverageFraction = struct { + functions: f64 = 0.9, + lines: f64 = 0.9, + + // This metric is less accurate right now + stmts: f64 = 0.75, + + failing: bool = false, +}; diff --git a/src/sourcemap/sourcemap.zig b/src/sourcemap/sourcemap.zig index 1784228481ae06..0bcb4021d93e2c 100644 --- a/src/sourcemap/sourcemap.zig +++ b/src/sourcemap/sourcemap.zig @@ -179,6 +179,7 @@ pub const Mapping = struct { bytes: []const u8, estimated_mapping_count: ?usize, sources_count: i32, + input_line_count: usize, ) ParseResult { var mapping = Mapping.List{}; if (estimated_mapping_count) |count| { @@ -366,7 +367,12 @@ pub const Mapping = struct { }) catch unreachable; } - return ParseResult{ .success = mapping }; + return ParseResult{ + .success = .{ + .mappings = mapping, + .input_line_count = input_line_count, + }, + }; } pub const ParseResult = union(enum) { @@ -386,7 +392,17 @@ pub const Mapping = struct { }; } }, - success: Mapping.List, + success: ParsedSourceMap, + }; + + pub const ParsedSourceMap = struct { + input_line_count: usize = 0, + mappings: Mapping.List = .{}, + + pub fn deinit(this: *ParsedSourceMap, allocator: std.mem.Allocator) void { + this.mappings.deinit(allocator); + allocator.destroy(this); + } }; }; @@ -845,6 +861,38 @@ pub const LineOffsetTable = struct { return @as(i32, @intCast(original_line)) - 1; } + pub fn findIndex(byte_offsets_to_start_of_line: []const u32, loc: Logger.Loc) ?usize { + std.debug.assert(loc.start > -1); // checked by caller + var original_line: usize = 0; + const loc_start = @as(usize, @intCast(loc.start)); + + var count = @as(usize, @truncate(byte_offsets_to_start_of_line.len)); + var i: usize = 0; + while (count > 0) { + const step = count / 2; + i = original_line + step; + const byte_offset = byte_offsets_to_start_of_line[i]; + if (byte_offset == loc_start) { + return i; + } + if (i + 1 < byte_offsets_to_start_of_line.len) { + const next_byte_offset = byte_offsets_to_start_of_line[i + 1]; + if (byte_offset < loc_start and loc_start < next_byte_offset) { + return i; + } + } + + if (byte_offset < loc_start) { + original_line = i + 1; + count = count - step - 1; + } else { + count = step; + } + } + + return null; + } + pub fn generate(allocator: std.mem.Allocator, contents: []const u8, approximate_line_count: i32) List { var list = List{}; // Preallocate the top-level table using the approximate line count from the lexer @@ -933,7 +981,10 @@ pub const LineOffsetTable = struct { continue; } - var owned = columns_for_non_ascii.toOwnedSlice() catch unreachable; + // We don't call .toOwnedSlice() because it is expensive to + // reallocate the array AND when inside an Arena, it's + // hideously expensive + var owned = columns_for_non_ascii.items; if (stack_fallback.fixed_buffer_allocator.ownsSlice(std.mem.sliceAsBytes(owned))) { owned = allocator.dupe(i32, owned) catch unreachable; } @@ -1018,13 +1069,13 @@ pub fn appendMappingToBuffer(buffer_: MutableString, last_byte: u8, prev_state: const vlq = [_]VLQ{ // Record the generated column (the line is recorded using ';' elsewhere) - encodeVLQWithLookupTable(current_state.generated_column - prev_state.generated_column), + encodeVLQWithLookupTable(current_state.generated_column -| prev_state.generated_column), // Record the generated source - encodeVLQWithLookupTable(current_state.source_index - prev_state.source_index), + encodeVLQWithLookupTable(current_state.source_index -| prev_state.source_index), // Record the original line - encodeVLQWithLookupTable(current_state.original_line - prev_state.original_line), + encodeVLQWithLookupTable(current_state.original_line -| prev_state.original_line), // Record the original column - encodeVLQWithLookupTable(current_state.original_column - prev_state.original_column), + encodeVLQWithLookupTable(current_state.original_column -| prev_state.original_column), }; // Count exactly how many bytes we need to write @@ -1139,6 +1190,7 @@ pub const Chunk = struct { data: MutableString, count: usize = 0, offset: usize = 0, + approximate_input_line_count: usize = 0, pub const Format = SourceMapFormat(VLQSourceMap); @@ -1149,8 +1201,8 @@ pub const Chunk = struct { // For bun.js, we store the number of mappings and how many bytes the final list is at the beginning of the array if (prepend_count) { - map.offset = 16; - map.data.append(&[16]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) catch unreachable; + map.offset = 24; + map.data.append(&([_]u8{0} ** 24)) catch unreachable; } return map; @@ -1208,6 +1260,8 @@ pub const Chunk = struct { line_starts_with_mapping: bool = false, cover_lines_without_mappings: bool = false, + approximate_input_line_count: usize = 0, + /// When generating sourcemappings for bun, we store a count of how many mappings there were prepend_count: bool = false, @@ -1218,6 +1272,7 @@ pub const Chunk = struct { if (b.prepend_count) { b.source_map.getBuffer().list.items[0..8].* = @as([8]u8, @bitCast(b.source_map.getBuffer().list.items.len)); b.source_map.getBuffer().list.items[8..16].* = @as([8]u8, @bitCast(b.source_map.getCount())); + b.source_map.getBuffer().list.items[16..24].* = @as([8]u8, @bitCast(b.approximate_input_line_count)); } return Chunk{ .buffer = b.source_map.getBuffer(), @@ -1351,10 +1406,10 @@ pub const Chunk = struct { b.appendMapping(.{ .generated_line = b.prev_state.generated_line, - .generated_column = b.generated_column, + .generated_column = @max(b.generated_column, 0), .source_index = b.prev_state.source_index, - .original_line = original_line, - .original_column = original_column, + .original_line = @max(original_line, 0), + .original_column = @max(original_column, 0), }); // This line now has a mapping on it, so don't insert another one diff --git a/src/string.zig b/src/string.zig index 1e2ee752eaaa9d..9002234cf37caf 100644 --- a/src/string.zig +++ b/src/string.zig @@ -276,6 +276,10 @@ pub const String = extern struct { extern fn BunString__fromLatin1Unitialized(len: usize) String; extern fn BunString__fromUTF16Unitialized(len: usize) String; + pub fn isGlobal(this: String) bool { + return this.tag == Tag.ZigString and this.value.ZigString.isGloballyAllocated(); + } + pub fn toOwnedSlice(this: String, allocator: std.mem.Allocator) ![]u8 { switch (this.tag) { .ZigString => return try this.value.ZigString.toOwnedSlice(allocator), @@ -339,6 +343,54 @@ pub const String = extern struct { return this; } + pub fn clone(this: String) String { + if (this.tag == .WTFStringImpl) { + return this.dupeRef(); + } + + if (this.isEmpty()) { + return this; + } + + if (this.isUTF16()) { + var new = createUninitializedUTF16(this.length()); + @memcpy(@constCast(new.byteSlice()), this.byteSlice()); + return new; + } + + return create(this.byteSlice()); + } + + extern fn BunString__createAtom(bytes: [*]const u8, len: usize) String; + + /// May return .Dead if the string is too long or non-ascii. + pub fn createAtom(bytes: []const u8) String { + JSC.markBinding(@src()); + return BunString__createAtom(bytes.ptr, bytes.len); + } + + pub fn tryCreateAtom(bytes: []const u8) ?String { + const atom = createAtom(bytes); + if (atom.isEmpty()) { + return null; + } + + return atom; + } + + /// Atomized strings are interned strings + /// They're de-duplicated in a threadlocal hash table + /// They cannot be used from other threads. + pub fn createAtomIfPossible(bytes: []const u8) String { + if (bytes.len < 64) { + if (tryCreateAtom(bytes)) |atom| { + return atom; + } + } + + return create(bytes); + } + pub fn utf8ByteLength(this: String) usize { return switch (this.tag) { .WTFStringImpl => this.value.WTFStringImpl.utf8ByteLength(), @@ -777,6 +829,13 @@ pub const String = extern struct { return bun.strings.eqlLong(this.byteSlice(), value, true); } + extern fn BunString__toThreadSafe(this: *String) void; + pub fn toThreadSafe(this: *String) void { + if (this.tag == .WTFStringImpl) { + BunString__toThreadSafe(this); + } + } + pub fn eql(this: String, other: String) bool { return this.toZigString().eql(other.toZigString()); } @@ -786,6 +845,23 @@ pub const SliceWithUnderlyingString = struct { utf8: ZigString.Slice, underlying: String, + pub fn toThreadSafe(this: *SliceWithUnderlyingString) void { + std.debug.assert(this.underlying.tag == .WTFStringImpl); + + var orig = this.underlying.value.WTFStringImpl; + this.underlying.toThreadSafe(); + if (this.underlying.value.WTFStringImpl != orig) { + orig.deref(); + + if (this.utf8.allocator.get()) |allocator| { + if (String.isWTFAllocator(allocator)) { + this.utf8.deinit(); + this.utf8 = this.underlying.toUTF8(bun.default_allocator); + } + } + } + } + pub fn deinit(this: SliceWithUnderlyingString) void { this.utf8.deinit(); this.underlying.deref(); diff --git a/src/string_immutable.zig b/src/string_immutable.zig index c967544c74d047..fd5bcb00a4ba80 100644 --- a/src/string_immutable.zig +++ b/src/string_immutable.zig @@ -271,6 +271,10 @@ pub inline fn lastIndexOf(self: string, str: string) ?usize { } pub inline fn indexOf(self: string, str: string) ?usize { + if (comptime !bun.Environment.isNative) { + return std.mem.indexOf(u8, self, str); + } + const self_len = self.len; const str_len = str.len; @@ -672,15 +676,7 @@ pub fn startsWith(self: string, str: string) bool { return false; } - var i: usize = 0; - while (i < str.len) { - if (str[i] != self[i]) { - return false; - } - i += 1; - } - - return true; + return eqlLong(self[0..str.len], str, false); } pub inline fn endsWith(self: string, str: string) bool { @@ -929,7 +925,7 @@ inline fn eqlComptimeCheckLenWithKnownType(comptime Type: type, a: []const Type, } const len = comptime b.len; - comptime var dword_length = b.len >> 3; + comptime var dword_length = b.len >> if (Environment.isNative) 3 else 2; const slice = b; const divisor = comptime @sizeOf(Type); @@ -1484,9 +1480,12 @@ pub fn convertUTF16ToUTF8(list_: std.ArrayList(u8), comptime Type: type, utf16: pub fn toUTF8AllocWithType(allocator: std.mem.Allocator, comptime Type: type, utf16: Type) ![]u8 { if (bun.FeatureFlags.use_simdutf and comptime Type == []const u16) { const length = bun.simdutf.length.utf8.from.utf16.le(utf16); - // add 4 bytes of padding for SIMDUTF - var list = try std.ArrayList(u8).initCapacity(allocator, length + 4); + // add 16 bytes of padding for SIMDUTF + var list = try std.ArrayList(u8).initCapacity(allocator, length + 16); list = try convertUTF16ToUTF8(list, Type, utf16); + if (Environment.allow_assert) { + std.debug.assert(list.items.len == length); + } return list.items; } @@ -1500,7 +1499,11 @@ pub fn toUTF8ListWithType(list_: std.ArrayList(u8), comptime Type: type, utf16: var list = list_; const length = bun.simdutf.length.utf8.from.utf16.le(utf16); try list.ensureTotalCapacityPrecise(length + 16); - return convertUTF16ToUTF8(list, Type, utf16); + const buf = try convertUTF16ToUTF8(list, Type, utf16); + if (Environment.allow_assert) { + std.debug.assert(buf.items.len == length); + } + return buf; } return toUTF8ListWithTypeBun(list_, Type, utf16); @@ -1529,7 +1532,11 @@ pub fn toUTF8ListWithTypeBun(list_: std.ArrayList(u8), comptime Type: type, utf1 utf16_remaining = utf16_remaining[replacement.len..]; const count: usize = replacement.utf8Width(); - try list.ensureTotalCapacityPrecise(i + count + list.items.len + @as(usize, @intFromFloat((@as(f64, @floatFromInt(@as(u52, @truncate(utf16_remaining.len)))) * 1.2)))); + if (comptime Environment.isNative) { + try list.ensureTotalCapacityPrecise(i + count + list.items.len + @as(usize, @intFromFloat((@as(f64, @floatFromInt(@as(u52, @truncate(utf16_remaining.len)))) * 1.2)))); + } else { + try list.ensureTotalCapacityPrecise(i + count + list.items.len + utf16_remaining.len + 4); + } list.items.len += i; copyU16IntoU8( @@ -3453,6 +3460,10 @@ pub fn indexOfCharUsize(slice: []const u8, char: u8) ?usize { if (slice.len == 0) return null; + if (comptime !Environment.isNative) { + return std.mem.indexOfScalar(u8, slice, char); + } + const ptr = bun.C.memchr(slice.ptr, char, slice.len) orelse return null; const i = @intFromPtr(ptr) - @intFromPtr(slice.ptr); std.debug.assert(i < slice.len); @@ -3712,7 +3723,7 @@ pub fn getLinesInText(text: []const u8, line: u32, comptime line_range_count: us pub fn firstNonASCII16CheckMin(comptime Slice: type, slice: Slice, comptime check_min: bool) ?u32 { var remaining = slice; - if (comptime Environment.enableSIMD) { + if (comptime Environment.enableSIMD and Environment.isNative) { const end_ptr = remaining.ptr + remaining.len - (remaining.len % ascii_u16_vector_size); if (remaining.len > ascii_u16_vector_size) { const remaining_start = remaining.ptr; @@ -3788,7 +3799,7 @@ pub fn @"nextUTF16NonASCIIOr$`\\"( ) ?u32 { var remaining = slice; - if (comptime Environment.enableSIMD) { + if (comptime Environment.enableSIMD and Environment.isNative) { while (remaining.len >= ascii_u16_vector_size) { const vec: AsciiU16Vector = remaining[0..ascii_u16_vector_size].*; @@ -4062,7 +4073,8 @@ pub fn join(slices: []const string, delimiter: string, allocator: std.mem.Alloca pub fn order(a: []const u8, b: []const u8) std.math.Order { const len = @min(a.len, b.len); - const cmp = bun.C.memcmp(a.ptr, b.ptr, len); + + const cmp = if (comptime Environment.isNative) bun.C.memcmp(a.ptr, b.ptr, len) else return std.mem.order(u8, a, b); return switch (std.math.sign(cmp)) { 0 => std.math.order(a.len, b.len), 1 => .gt, diff --git a/src/string_mutable.zig b/src/string_mutable.zig index 239713407c3eb7..e0734574f2381b 100644 --- a/src/string_mutable.zig +++ b/src/string_mutable.zig @@ -228,7 +228,7 @@ pub const MutableString = struct { } pub fn toOwnedSlice(self: *MutableString) string { - return self.list.toOwnedSlice(self.allocator) catch @panic("TODO"); + return self.list.toOwnedSlice(self.allocator) catch @panic("Allocation Error"); // TODO } pub fn toOwnedSliceLeaky(self: *MutableString) []u8 { @@ -255,7 +255,7 @@ pub const MutableString = struct { pub fn toOwnedSliceLength(self: *MutableString, length: usize) string { self.list.shrinkAndFree(self.allocator, length); - return self.list.toOwnedSlice(self.allocator) catch @panic("TODO"); + return self.list.toOwnedSlice(self.allocator) catch @panic("Allocation Error"); // TODO } // pub fn deleteAt(self: *MutableString, i: usize) { diff --git a/src/tracy.zig b/src/tracy.zig index fb900442b539b9..a51420f02165e1 100644 --- a/src/tracy.zig +++ b/src/tracy.zig @@ -441,6 +441,10 @@ fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void { } pub fn init() bool { + if (comptime !bun.Environment.isNative) { + return false; + } + if (enable) return true; @@ -452,6 +456,10 @@ pub fn init() bool { } pub fn isConnected() bool { + if (comptime !bun.Environment.isNative) { + return false; + } + if (!enable) return false; @@ -460,6 +468,10 @@ pub fn isConnected() bool { } pub fn initThread(comptime name: [:0]const u8) void { + if (comptime !bun.Environment.isNative) { + return; + } + if (!enable) return; @@ -475,6 +487,10 @@ const ___tracy_source_location_data = extern struct { }; fn dlsym(comptime Type: type, comptime symbol: [:0]const u8) ?Type { + if (comptime !bun.Environment.isNative) { + return null; + } + if (comptime bun.Environment.isLinux) { // use LD_PRELOAD on linux if (bun.C.dlsym(Type, symbol)) |val| { diff --git a/src/url.zig b/src/url.zig index dcb1e91cd0399a..064481257e2223 100644 --- a/src/url.zig +++ b/src/url.zig @@ -36,6 +36,10 @@ pub const URL = struct { username: string = "", port_was_automatically_set: bool = false, + pub fn isFile(this: *const URL) bool { + return strings.eqlComptime(this.protocol, "file"); + } + pub fn fromJS(js_value: JSC.JSValue, globalObject: *JSC.JSGlobalObject, allocator: std.mem.Allocator) !URL { var href = JSC.URL.hrefFromJS(globalObject, js_value); if (href.tag == .Dead) { @@ -63,6 +67,10 @@ pub const URL = struct { return this.hostname.len == 0 or strings.eqlComptime(this.hostname, "localhost") or strings.eqlComptime(this.hostname, "0.0.0.0"); } + pub inline fn isUnix(this: *const URL) bool { + return strings.hasPrefixComptime(this.protocol, "unix"); + } + pub fn displayProtocol(this: *const URL) string { if (this.protocol.len > 0) { return this.protocol; diff --git a/src/watcher.zig b/src/watcher.zig index aded993e8b7dd5..a31267c5fc954f 100644 --- a/src/watcher.zig +++ b/src/watcher.zig @@ -382,6 +382,8 @@ pub fn NewWatcher(comptime ContextType: type) type { pub fn init(ctx: ContextType, fs: *Fs.FileSystem, allocator: std.mem.Allocator) !*Watcher { var watcher = try allocator.create(Watcher); + errdefer allocator.destroy(watcher); + if (!PlatformWatcher.isRunning()) { try PlatformWatcher.init(); } @@ -406,14 +408,16 @@ pub fn NewWatcher(comptime ContextType: type) type { } pub fn deinit(this: *Watcher, close_descriptors: bool) void { - this.mutex.lock(); - defer this.mutex.unlock(); - - this.close_descriptors = close_descriptors; if (this.watchloop_handle != null) { + this.mutex.lock(); + defer this.mutex.unlock(); + this.close_descriptors = close_descriptors; this.running = false; } else { - if (this.close_descriptors and this.running) { + // if the mutex is locked, then that's now a UAF. + this.mutex.assertUnlocked("Internal consistency error: watcher mutex is locked when it should not be."); + + if (close_descriptors and this.running) { const fds = this.watchlist.items(.fd); for (fds) |fd| { std.os.close(fd); @@ -454,7 +458,19 @@ pub fn NewWatcher(comptime ContextType: type) type { allocator.destroy(this); } + pub fn remove(this: *Watcher, hash: HashType) void { + this.mutex.lock(); + defer this.mutex.unlock(); + if (this.indexOf(hash)) |index| { + const fds = this.watchlist.items(.fd); + const fd = fds[index]; + std.os.close(fd); + this.watchlist.swapRemove(index); + } + } + var evict_list_i: WatchItemIndex = 0; + pub fn removeAtIndex(_: *Watcher, index: WatchItemIndex, hash: HashType, parents: []HashType, comptime kind: WatchItem.Kind) void { std.debug.assert(index != NoWatchItem); @@ -677,6 +693,7 @@ pub fn NewWatcher(comptime ContextType: type) type { package_json: ?*PackageJSON, comptime copy_file_path: bool, ) !void { + // This must lock due to concurrent transpiler this.mutex.lock(); defer this.mutex.unlock(); diff --git a/test/bun.lockb b/test/bun.lockb index f6b48c1bb627da..f3d337bb08742e 100755 Binary files a/test/bun.lockb and b/test/bun.lockb differ diff --git a/test/bundler/bundler_browser.test.ts b/test/bundler/bundler_browser.test.ts index 9c9ccf8dd8ad2e..c14e338f90bf1e 100644 --- a/test/bundler/bundler_browser.test.ts +++ b/test/bundler/bundler_browser.test.ts @@ -283,4 +283,40 @@ describe("bundler", () => { ); }, }); + + itBundled("browser/ImportNonExistentNodeBuiltinShouldError", { + skipOnEsbuild: true, + files: { + "/entry.js": ` + import net1 from "node:net1"; + `, + }, + bundleErrors: { + "/entry.js": [`Could not resolve: "node:net1". Maybe you need to "bun install"?`], + }, + }); + itBundled("browser/ImportNonExistentWithoutNodePrefix", { + skipOnEsbuild: true, + files: { + "/entry.js": ` + import net1 from "net1"; + `, + }, + bundleErrors: { + "/entry.js": [`Could not resolve: "net1". Maybe you need to "bun install"?`], + }, + }); + itBundled("browser/TargetNodeNonExistentBuiltinShouldBeExternal", { + skipOnEsbuild: true, + files: { + "/entry.js": ` + import net1 from "node:net1"; + `, + }, + target: "node", + onAfterBundle(api) { + const contents = api.readFile("out.js"); + expect(contents).toContain('from "node:net1"'); + }, + }); }); diff --git a/test/cli/hot/hot-runner-root.js b/test/cli/hot/hot-runner-root.js new file mode 100644 index 00000000000000..351ef5a655046f --- /dev/null +++ b/test/cli/hot/hot-runner-root.js @@ -0,0 +1 @@ +import "./hot-runner"; diff --git a/test/cli/hot/hot.test.ts b/test/cli/hot/hot.test.ts index 63cc3b06461a87..50a38ac68aa09d 100644 --- a/test/cli/hot/hot.test.ts +++ b/test/cli/hot/hot.test.ts @@ -2,9 +2,12 @@ import { spawn } from "bun"; import { expect, it } from "bun:test"; import { bunExe, bunEnv } from "harness"; import { readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "fs"; +import { join } from "path"; + +const hotRunnerRoot = join(import.meta.dir, "/hot-runner-root.js"); it("should hot reload when file is overwritten", async () => { - const root = import.meta.dir + "/hot-runner.js"; + const root = hotRunnerRoot; const runner = spawn({ cmd: [bunExe(), "--hot", "run", root], env: bunEnv, @@ -43,7 +46,7 @@ it("should hot reload when file is overwritten", async () => { }); it("should recover from errors", async () => { - const root = import.meta.dir + "/hot-runner.js"; + const root = hotRunnerRoot; const runner = spawn({ cmd: [bunExe(), "--hot", "run", root], env: bunEnv, @@ -111,7 +114,7 @@ it("should recover from errors", async () => { }); it("should not hot reload when a random file is written", async () => { - const root = import.meta.dir + "/hot-runner.js"; + const root = hotRunnerRoot; const runner = spawn({ cmd: [bunExe(), "--hot", "run", root], env: bunEnv, @@ -165,7 +168,7 @@ it("should not hot reload when a random file is written", async () => { }); it("should hot reload when a file is deleted and rewritten", async () => { - const root = import.meta.dir + "/hot-runner.js"; + const root = hotRunnerRoot; const runner = spawn({ cmd: [bunExe(), "--hot", "run", root], env: bunEnv, @@ -206,7 +209,7 @@ it("should hot reload when a file is deleted and rewritten", async () => { }); it("should hot reload when a file is renamed() into place", async () => { - const root = import.meta.dir + "/hot-runner.js"; + const root = hotRunnerRoot; const runner = spawn({ cmd: [bunExe(), "--hot", "run", root], env: bunEnv, diff --git a/test/cli/install/bun-add.test.ts b/test/cli/install/bun-add.test.ts index 9dd38c8cd5bc45..589b7a87e6aadc 100644 --- a/test/cli/install/bun-add.test.ts +++ b/test/cli/install/bun-add.test.ts @@ -459,7 +459,7 @@ it("should add dependency (GitHub)", async () => { " 1 packages installed", ]); expect(await exited).toBe(0); - expect(urls.sort()).toEqual([]); + expect(urls.sort()).toBeEmpty(); expect(requested).toBe(0); expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".bin", ".cache", "uglify-js"]); expect(await readdirSorted(join(package_dir, "node_modules", ".bin"))).toEqual(["uglifyjs"]); @@ -680,7 +680,7 @@ it("should add aliased dependency (GitHub)", async () => { " 1 packages installed", ]); expect(await exited).toBe(0); - expect(urls.sort()).toEqual([]); + expect(urls.sort()).toBeEmpty(); expect(requested).toBe(0); expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".bin", ".cache", "uglify"]); expect(await readdirSorted(join(package_dir, "node_modules", ".bin"))).toEqual(["uglifyjs"]); @@ -993,7 +993,7 @@ it("should handle Git URL in dependencies (SCP-style)", async () => { " 1 packages installed", ]); expect(await exited1).toBe(0); - expect(urls.sort()).toEqual([]); + expect(urls.sort()).toBeEmpty(); expect(requested).toBe(0); expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".bin", ".cache", "uglify-js"]); expect(await readdirSorted(join(package_dir, "node_modules", ".bin"))).toEqual(["uglifyjs"]); @@ -1053,7 +1053,7 @@ it("should handle Git URL in dependencies (SCP-style)", async () => { "Checked 1 installs across 2 packages (no changes)", ]); expect(await exited2).toBe(0); - expect(urls.sort()).toEqual([]); + expect(urls.sort()).toBeEmpty(); expect(requested).toBe(0); }, 20000); @@ -1255,7 +1255,7 @@ it("should add dependency without duplication", async () => { const out2 = await new Response(stdout2).text(); expect(out2.replace(/\s*\[[0-9\.]+m?s\] done\s*$/, "").split(/\r?\n/)).toEqual(["", " installed bar@0.0.2"]); expect(await exited2).toBe(0); - expect(urls.sort()).toEqual([]); + expect(urls.sort()).toBeEmpty(); expect(requested).toBe(2); expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "bar"]); expect(await readdirSorted(join(package_dir, "node_modules", "bar"))).toEqual(["package.json"]); @@ -1480,7 +1480,7 @@ it("should redirect 'install X --save' to 'add'", async () => { await installRedirectsToAdd(false); }); -async function installRedirectsToAdd(saveFlagFirst) { +async function installRedirectsToAdd(saveFlagFirst: boolean) { await writeFile( join(add_dir, "package.json"), JSON.stringify({ @@ -1516,3 +1516,57 @@ async function installRedirectsToAdd(saveFlagFirst) { expect(await exited).toBe(0); expect((await file(join(package_dir, "package.json")).text()).includes("bun-add.test")); } + +it("should add dependency alongside peerDependencies", async () => { + const urls: string[] = []; + setHandler(dummyRegistry(urls)); + await writeFile( + join(package_dir, "package.json"), + JSON.stringify({ + name: "foo", + peerDependencies: { + bar: "~0.0.1", + }, + }), + ); + const { stdout, stderr, exited } = spawn({ + cmd: [bunExe(), "add", "bar"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr).toBeDefined(); + const err = await new Response(stderr).text(); + expect(err).not.toContain("error:"); + expect(err).toContain("Saved lockfile"); + expect(stdout).toBeDefined(); + const out = await new Response(stdout).text(); + expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + "", + " installed bar@0.0.2", + "", + "", + " 1 packages installed", + ]); + expect(await exited).toBe(0); + expect(urls.sort()).toEqual([`${root_url}/bar`, `${root_url}/bar-0.0.2.tgz`]); + expect(requested).toBe(2); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "bar"]); + expect(await readdirSorted(join(package_dir, "node_modules", "bar"))).toEqual(["package.json"]); + expect(await file(join(package_dir, "node_modules", "bar", "package.json")).json()).toEqual({ + name: "bar", + version: "0.0.2", + }); + expect(await file(join(package_dir, "package.json")).json()).toEqual({ + name: "foo", + dependencies: { + bar: "^0.0.2", + }, + peerDependencies: { + bar: "~0.0.1", + }, + }); + await access(join(package_dir, "bun.lockb")); +}); diff --git a/test/cli/install/bun-install.test.ts b/test/cli/install/bun-install.test.ts index b1f453f86d8953..16525122e2b547 100644 --- a/test/cli/install/bun-install.test.ts +++ b/test/cli/install/bun-install.test.ts @@ -251,7 +251,11 @@ it("should handle workspaces", async () => { }), ); - const { stdout, stderr, exited } = spawn({ + const { + stdout: stdout1, + stderr: stderr1, + exited: exited1, + } = spawn({ cmd: [bunExe(), "install"], cwd: package_dir, stdout: null, @@ -259,12 +263,12 @@ it("should handle workspaces", async () => { stderr: "pipe", env, }); - expect(stderr).toBeDefined(); - const err = await new Response(stderr).text(); - expect(err).toContain("Saved lockfile"); - expect(stdout).toBeDefined(); - const out = await new Response(stdout).text(); - expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + expect(stderr1).toBeDefined(); + const err1 = await new Response(stderr1).text(); + expect(err1).toContain("Saved lockfile"); + expect(stdout1).toBeDefined(); + const out1 = await new Response(stdout1).text(); + expect(out1.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ " + @org/nominally-scoped@workspace:packages/nominally-scoped", " + Asterisk@workspace:packages/asterisk", " + AsteriskTheSecond@workspace:packages/second-asterisk", @@ -272,7 +276,7 @@ it("should handle workspaces", async () => { "", " 4 packages installed", ]); - expect(await exited).toBe(0); + expect(await exited1).toBe(0); expect(requested).toBe(0); expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([ ".cache", @@ -290,6 +294,51 @@ it("should handle workspaces", async () => { join("..", "..", "packages", "nominally-scoped"), ); await access(join(package_dir, "bun.lockb")); + + // Perform `bun install` again but with lockfile from before + await rm(join(package_dir, "node_modules"), { force: true, recursive: true }); + const { + stdout: stdout2, + stderr: stderr2, + exited: exited2, + } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr2).toBeDefined(); + const err2 = await new Response(stderr2).text(); + expect(err2).not.toContain("Saved lockfile"); + expect(stdout2).toBeDefined(); + const out2 = await new Response(stdout2).text(); + expect(out2.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + @org/nominally-scoped@workspace:packages/nominally-scoped", + " + Asterisk@workspace:packages/asterisk", + " + AsteriskTheSecond@workspace:packages/second-asterisk", + " + Bar@workspace:bar", + "", + " 4 packages installed", + ]); + expect(await exited2).toBe(0); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([ + "@org", + "Asterisk", + "AsteriskTheSecond", + "Bar", + ]); + expect(await readlink(join(package_dir, "node_modules", "Bar"))).toBe(join("..", "bar")); + expect(await readlink(join(package_dir, "node_modules", "Asterisk"))).toBe(join("..", "packages", "asterisk")); + expect(await readlink(join(package_dir, "node_modules", "AsteriskTheSecond"))).toBe( + join("..", "packages", "second-asterisk"), + ); + expect(await readlink(join(package_dir, "node_modules", "@org", "nominally-scoped"))).toBe( + join("..", "..", "packages", "nominally-scoped"), + ); + await access(join(package_dir, "bun.lockb")); }); it("should handle `workspace:` specifier", async () => { @@ -311,7 +360,11 @@ it("should handle `workspace:` specifier", async () => { version: "0.0.2", }), ); - const { stdout, stderr, exited } = spawn({ + const { + stdout: stdout1, + stderr: stderr1, + exited: exited1, + } = spawn({ cmd: [bunExe(), "install"], cwd: package_dir, stdout: null, @@ -319,21 +372,50 @@ it("should handle `workspace:` specifier", async () => { stderr: "pipe", env, }); - expect(stderr).toBeDefined(); - const err = await new Response(stderr).text(); - expect(err).toContain("Saved lockfile"); - expect(stdout).toBeDefined(); - const out = await new Response(stdout).text(); - expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + expect(stderr1).toBeDefined(); + const err1 = await new Response(stderr1).text(); + expect(err1).toContain("Saved lockfile"); + expect(stdout1).toBeDefined(); + const out1 = await new Response(stdout1).text(); + expect(out1.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ " + Bar@workspace:path/to/bar", "", " 1 packages installed", ]); - expect(await exited).toBe(0); + expect(await exited1).toBe(0); expect(requested).toBe(0); expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "Bar"]); expect(await readlink(join(package_dir, "node_modules", "Bar"))).toBe(join("..", "path", "to", "bar")); await access(join(package_dir, "bun.lockb")); + // Perform `bun install` again but with lockfile from before + await rm(join(package_dir, "node_modules"), { force: true, recursive: true }); + const { + stdout: stdout2, + stderr: stderr2, + exited: exited2, + } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr2).toBeDefined(); + const err2 = await new Response(stderr2).text(); + expect(err2).not.toContain("Saved lockfile"); + expect(stdout2).toBeDefined(); + const out2 = await new Response(stdout2).text(); + expect(out2.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + Bar@workspace:path/to/bar", + "", + " 1 packages installed", + ]); + expect(await exited2).toBe(0); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual(["Bar"]); + expect(await readlink(join(package_dir, "node_modules", "Bar"))).toBe(join("..", "path", "to", "bar")); + await access(join(package_dir, "bun.lockb")); }); it("should handle workspaces with packages array", async () => { @@ -724,6 +806,7 @@ it("should handle life-cycle scripts during re-installation", async () => { }); expect(stderr2).toBeDefined(); const err2 = await new Response(stderr2).text(); + expect(err2).not.toContain("error:"); expect(err2).not.toContain("Saved lockfile"); expect(stdout2).toBeDefined(); const out2 = await new Response(stdout2).text(); @@ -739,6 +822,38 @@ it("should handle life-cycle scripts during re-installation", async () => { expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual(["Bar"]); expect(await readlink(join(package_dir, "node_modules", "Bar"))).toBe(join("..", "bar")); await access(join(package_dir, "bun.lockb")); + // Perform `bun install --production` with lockfile from before + await rm(join(package_dir, "node_modules"), { force: true, recursive: true }); + const { + stdout: stdout3, + stderr: stderr3, + exited: exited3, + } = spawn({ + cmd: [bunExe(), "install", "--production"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr3).toBeDefined(); + const err3 = await new Response(stderr3).text(); + expect(err3).not.toContain("error:"); + expect(err3).not.toContain("Saved lockfile"); + expect(stdout3).toBeDefined(); + const out3 = await new Response(stdout3).text(); + expect(out3.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + "[scripts:run] Bar", + " + Bar@workspace:bar", + "[scripts:run] Foo", + "", + " 1 packages installed", + ]); + expect(await exited3).toBe(0); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual(["Bar"]); + expect(await readlink(join(package_dir, "node_modules", "Bar"))).toBe(join("..", "bar")); + await access(join(package_dir, "bun.lockb")); }); it("should ignore workspaces within workspaces", async () => { @@ -4607,7 +4722,11 @@ it("should handle `workspaces:*` and `workspace:*` gracefully", async () => { version: "0.0.1", }); await writeFile(join(package_dir, "bar", "package.json"), bar_package); - const { stdout, stderr, exited } = spawn({ + const { + stdout: stdout1, + stderr: stderr1, + exited: exited1, + } = spawn({ cmd: [bunExe(), "install"], cwd: package_dir, stdout: null, @@ -4615,22 +4734,52 @@ it("should handle `workspaces:*` and `workspace:*` gracefully", async () => { stderr: "pipe", env, }); - expect(stderr).toBeDefined(); - const err = await new Response(stderr).text(); - expect(err).toContain("Saved lockfile"); - expect(stdout).toBeDefined(); - const out = await new Response(stdout).text(); - expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + expect(stderr1).toBeDefined(); + const err1 = await new Response(stderr1).text(); + expect(err1).toContain("Saved lockfile"); + expect(stdout1).toBeDefined(); + const out1 = await new Response(stdout1).text(); + expect(out1.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ " + bar@workspace:bar", "", " 1 packages installed", ]); - expect(await exited).toBe(0); + expect(await exited1).toBe(0); expect(requested).toBe(0); expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "bar"]); expect(await readlink(join(package_dir, "node_modules", "bar"))).toBe(join("..", "bar")); expect(await file(join(package_dir, "node_modules", "bar", "package.json")).text()).toEqual(bar_package); await access(join(package_dir, "bun.lockb")); + // Perform `bun install` again but with lockfile from before + await rm(join(package_dir, "node_modules"), { force: true, recursive: true }); + const { + stdout: stdout2, + stderr: stderr2, + exited: exited2, + } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr2).toBeDefined(); + const err2 = await new Response(stderr2).text(); + expect(err2).not.toContain("Saved lockfile"); + expect(stdout2).toBeDefined(); + const out2 = await new Response(stdout2).text(); + expect(out2.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + bar@workspace:bar", + "", + " 1 packages installed", + ]); + expect(await exited2).toBe(0); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual(["bar"]); + expect(await readlink(join(package_dir, "node_modules", "bar"))).toBe(join("..", "bar")); + expect(await file(join(package_dir, "node_modules", "bar", "package.json")).text()).toEqual(bar_package); + await access(join(package_dir, "bun.lockb")); }); it("should handle `workspaces:bar` and `workspace:*` gracefully", async () => { @@ -5188,3 +5337,225 @@ it("should override aliased child npm dependency by matching workspace", async ( expect(await readlink(join(package_dir, "packages", "baz", "node_modules", "bar"))).toBe(join("..", "..", "bar")); await access(join(package_dir, "bun.lockb")); }); + +it("should handle `workspace:` with semver range", async () => { + const urls: string[] = []; + setHandler(dummyRegistry(urls)); + await writeFile( + join(package_dir, "package.json"), + JSON.stringify({ + name: "foo", + workspaces: ["bar", "baz"], + }), + ); + await mkdir(join(package_dir, "bar")); + const bar_package = JSON.stringify({ + name: "bar", + version: "0.0.1", + }); + await writeFile(join(package_dir, "bar", "package.json"), bar_package); + await mkdir(join(package_dir, "baz")); + await writeFile( + join(package_dir, "baz", "package.json"), + JSON.stringify({ + name: "baz", + version: "0.1.0", + dependencies: { + bar: "workspace:~0.0.1", + }, + }), + ); + const { stdout, stderr, exited } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr).toBeDefined(); + const err = await new Response(stderr).text(); + expect(err).toContain("Saved lockfile"); + expect(stdout).toBeDefined(); + const out = await new Response(stdout).text(); + expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + bar@workspace:bar", + " + baz@workspace:baz", + "", + " 2 packages installed", + ]); + expect(await exited).toBe(0); + expect(urls.sort()).toBeEmpty(); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "bar", "baz"]); + expect(await readlink(join(package_dir, "node_modules", "bar"))).toBe(join("..", "bar")); + expect(await file(join(package_dir, "node_modules", "bar", "package.json")).text()).toEqual(bar_package); + expect(await readlink(join(package_dir, "node_modules", "baz"))).toBe(join("..", "baz")); + expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["package.json"]); + await access(join(package_dir, "bun.lockb")); +}); + +it("should handle `workspace:` with alias & @scope", async () => { + const urls: string[] = []; + setHandler(dummyRegistry(urls)); + await writeFile( + join(package_dir, "package.json"), + JSON.stringify({ + name: "foo", + workspaces: ["packages/*"], + }), + ); + await mkdir(join(package_dir, "packages", "bar"), { recursive: true }); + const bar_package = JSON.stringify({ + name: "@moo/bar", + version: "0.1.2", + }); + await writeFile(join(package_dir, "packages", "bar", "package.json"), bar_package); + await mkdir(join(package_dir, "packages", "baz"), { recursive: true }); + await writeFile( + join(package_dir, "packages", "baz", "package.json"), + JSON.stringify({ + name: "@moz/baz", + dependencies: { + "@moz/bar": "workspace:@moo/bar@>=0.1", + }, + }), + ); + const { stdout, stderr, exited } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr).toBeDefined(); + const err = await new Response(stderr).text(); + expect(err).toContain("Saved lockfile"); + expect(stdout).toBeDefined(); + const out = await new Response(stdout).text(); + expect(out.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + @moo/bar@workspace:packages/bar", + " + @moz/baz@workspace:packages/baz", + "", + " 2 packages installed", + ]); + expect(await exited).toBe(0); + expect(urls.sort()).toBeEmpty(); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "@moo", "@moz"]); + expect(await readdirSorted(join(package_dir, "node_modules", "@moo"))).toEqual(["bar"]); + expect(await readlink(join(package_dir, "node_modules", "@moo", "bar"))).toBe(join("..", "..", "packages", "bar")); + expect(await file(join(package_dir, "node_modules", "@moo", "bar", "package.json")).text()).toEqual(bar_package); + expect(await readdirSorted(join(package_dir, "node_modules", "@moz"))).toEqual(["baz"]); + expect(await readlink(join(package_dir, "node_modules", "@moz", "baz"))).toBe(join("..", "..", "packages", "baz")); + expect(await readdirSorted(join(package_dir, "packages", "baz"))).toEqual(["node_modules", "package.json"]); + expect(await readdirSorted(join(package_dir, "packages", "baz", "node_modules"))).toEqual(["@moz"]); + expect(await readdirSorted(join(package_dir, "packages", "baz", "node_modules", "@moz"))).toEqual(["bar"]); + expect(await readlink(join(package_dir, "packages", "baz", "node_modules", "@moz", "bar"))).toBe( + join("..", "..", "..", "bar"), + ); + await access(join(package_dir, "bun.lockb")); +}); + +it("should handle `workspace:*` on both root & child", async () => { + const urls: string[] = []; + setHandler(dummyRegistry(urls)); + await writeFile( + join(package_dir, "package.json"), + JSON.stringify({ + name: "foo", + workspaces: ["packages/*"], + dependencies: { + bar: "workspace:*", + }, + }), + ); + await mkdir(join(package_dir, "packages", "bar"), { recursive: true }); + const bar_package = JSON.stringify({ + name: "bar", + version: "0.1.2", + }); + await writeFile(join(package_dir, "packages", "bar", "package.json"), bar_package); + await mkdir(join(package_dir, "packages", "baz"), { recursive: true }); + const baz_package = JSON.stringify({ + name: "baz", + version: "1.2.3", + devDependencies: { + bar: "workspace:*", + }, + }); + await writeFile(join(package_dir, "packages", "baz", "package.json"), baz_package); + const { + stdout: stdout1, + stderr: stderr1, + exited: exited1, + } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr1).toBeDefined(); + const err1 = await new Response(stderr1).text(); + expect(err1).not.toContain("error:"); + expect(err1).toContain("Saved lockfile"); + expect(stdout1).toBeDefined(); + const out1 = await new Response(stdout1).text(); + expect(out1.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + baz@workspace:packages/baz", + " + bar@workspace:packages/bar", + "", + " 2 packages installed", + ]); + expect(await exited1).toBe(0); + expect(urls.sort()).toBeEmpty(); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".cache", "bar", "baz"]); + expect(await readlink(join(package_dir, "node_modules", "bar"))).toBe(join("..", "packages", "bar")); + expect(await readdirSorted(join(package_dir, "node_modules", "bar"))).toEqual(["package.json"]); + expect(await file(join(package_dir, "node_modules", "bar", "package.json")).text()).toEqual(bar_package); + expect(await readlink(join(package_dir, "node_modules", "baz"))).toBe(join("..", "packages", "baz")); + expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["package.json"]); + expect(await file(join(package_dir, "node_modules", "baz", "package.json")).text()).toEqual(baz_package); + await access(join(package_dir, "bun.lockb")); + // Perform `bun install` again but with lockfile from before + await rm(join(package_dir, "node_modules"), { force: true, recursive: true }); + const { + stdout: stdout2, + stderr: stderr2, + exited: exited2, + } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr2).toBeDefined(); + const err2 = await new Response(stderr2).text(); + expect(err2).not.toContain("error:"); + expect(err2).not.toContain("Saved lockfile"); + expect(stdout2).toBeDefined(); + const out2 = await new Response(stdout2).text(); + expect(out2.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + baz@workspace:packages/baz", + " + bar@workspace:packages/bar", + "", + " 2 packages installed", + ]); + expect(await exited2).toBe(0); + expect(urls.sort()).toBeEmpty(); + expect(requested).toBe(0); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual(["bar", "baz"]); + expect(await readlink(join(package_dir, "node_modules", "bar"))).toBe(join("..", "packages", "bar")); + expect(await readdirSorted(join(package_dir, "node_modules", "bar"))).toEqual(["package.json"]); + expect(await file(join(package_dir, "node_modules", "bar", "package.json")).text()).toEqual(bar_package); + expect(await readlink(join(package_dir, "node_modules", "baz"))).toBe(join("..", "packages", "baz")); + expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["package.json"]); + expect(await file(join(package_dir, "node_modules", "baz", "package.json")).text()).toEqual(baz_package); + await access(join(package_dir, "bun.lockb")); +}); diff --git a/test/cli/install/bun-remove.test.ts b/test/cli/install/bun-remove.test.ts index bdf0873e960a73..5b029f143ec0c1 100644 --- a/test/cli/install/bun-remove.test.ts +++ b/test/cli/install/bun-remove.test.ts @@ -287,3 +287,33 @@ it("should retain a new line in the end of package.json", async () => { ) + "\n", ); }); + +it("should remove peerDependencies", async () => { + await writeFile( + join(package_dir, "package.json"), + JSON.stringify({ + name: "foo", + peerDependencies: { + bar: "~0.0.1", + }, + }), + ); + const { stdout, stderr, exited } = spawn({ + cmd: [bunExe(), "remove", "bar"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr).toBeDefined(); + const err = await new Response(stderr).text(); + expect(err).not.toContain("error:"); + expect(stdout).toBeDefined(); + const out = await new Response(stdout).text(); + expect(out.replace(/\s*\[[0-9\.]+m?s\]/, "").split(/\r?\n/)).toEqual([" done", ""]); + expect(await exited).toBe(0); + expect(await file(join(package_dir, "package.json")).json()).toEqual({ + name: "foo", + }); +}); diff --git a/test/cli/install/bun-run.test.ts b/test/cli/install/bun-run.test.ts index 95f33ebb89f130..4180c97165788f 100644 --- a/test/cli/install/bun-run.test.ts +++ b/test/cli/install/bun-run.test.ts @@ -1,6 +1,6 @@ -import { file, spawn } from "bun"; -import { afterEach, beforeEach, expect, it } from "bun:test"; -import { bunExe, bunEnv as env } from "harness"; +import { file, spawn, spawnSync } from "bun"; +import { afterEach, beforeEach, expect, it, describe } from "bun:test"; +import { bunEnv, bunExe, bunEnv as env } from "harness"; import { mkdtemp, realpath, rm, writeFile } from "fs/promises"; import { tmpdir } from "os"; import { join } from "path"; @@ -9,12 +9,76 @@ import { readdirSorted } from "./dummy.registry"; let run_dir: string; beforeEach(async () => { - run_dir = await realpath(await mkdtemp(join(tmpdir(), "bun-run.test"))); + run_dir = await realpath( + await mkdtemp(join(tmpdir(), "bun-run.test." + Math.trunc(Math.random() * 9999999).toString(32))), + ); }); afterEach(async () => { await rm(run_dir, { force: true, recursive: true }); }); +for (let withRun of [false, true]) { + describe(withRun ? "bun run" : "bun", () => { + describe("should work with .", () => { + it("respecting 'main' field", async () => { + await writeFile(join(run_dir, "test.js"), "console.log('Hello, world!');"); + await writeFile( + join(run_dir, "package.json"), + JSON.stringify({ + name: "test", + version: "0.0.0", + main: "test.js", + }), + ); + const { stdout, stderr, exitCode } = spawnSync({ + cmd: [bunExe(), withRun ? "run" : "", "."].filter(Boolean), + cwd: run_dir, + env: bunEnv, + }); + + expect(stderr.toString()).toBe(""); + expect(stdout.toString()).toBe("Hello, world!\n"); + expect(exitCode).toBe(0); + }); + + it("falling back to index", async () => { + await writeFile(join(run_dir, "index.ts"), "console.log('Hello, world!');"); + await writeFile( + join(run_dir, "package.json"), + JSON.stringify({ + name: "test", + version: "0.0.0", + }), + ); + + const { stdout, stderr, exitCode } = spawnSync({ + cmd: [bunExe(), withRun ? "run" : "", "."].filter(Boolean), + cwd: run_dir, + env: bunEnv, + }); + + expect(stderr.toString()).toBe(""); + expect(stdout.toString()).toBe("Hello, world!\n"); + expect(exitCode).toBe(0); + }); + + it("falling back to index with no package.json", async () => { + await writeFile(join(run_dir, "index.ts"), "console.log('Hello, world!');"); + + const { stdout, stderr, exitCode } = spawnSync({ + cmd: [bunExe(), withRun ? "run" : "", "."].filter(Boolean), + cwd: run_dir, + env: bunEnv, + }); + + expect(stderr.toString()).toBe(""); + expect(stdout.toString()).toBe("Hello, world!\n"); + expect(exitCode).toBe(0); + }); + }); + }); +} + it("should download dependency to run local file", async () => { await writeFile( join(run_dir, "test.js"), diff --git a/test/cli/install/bun-update.test.ts b/test/cli/install/bun-update.test.ts new file mode 100644 index 00000000000000..2a6ee4eafea003 --- /dev/null +++ b/test/cli/install/bun-update.test.ts @@ -0,0 +1,259 @@ +import { file, listen, Socket, spawn } from "bun"; +import { afterAll, afterEach, beforeAll, beforeEach, expect, it } from "bun:test"; +import { bunExe, bunEnv as env } from "harness"; +import { access, mkdir, readlink, realpath, rm, writeFile } from "fs/promises"; +import { join } from "path"; +import { + dummyAfterAll, + dummyAfterEach, + dummyBeforeAll, + dummyBeforeEach, + dummyRegistry, + package_dir, + readdirSorted, + requested, + root_url, + setHandler, +} from "./dummy.registry.js"; + +beforeAll(dummyBeforeAll); +afterAll(dummyAfterAll); +beforeEach(dummyBeforeEach); +afterEach(dummyAfterEach); + +it("should update to latest version of dependency", async () => { + const urls: string[] = []; + const registry = { + "0.0.3": { + bin: { + "baz-run": "index.js", + }, + }, + "0.0.5": { + bin: { + "baz-exec": "index.js", + }, + }, + latest: "0.0.3", + }; + setHandler(dummyRegistry(urls, registry)); + await writeFile( + join(package_dir, "package.json"), + JSON.stringify({ + name: "foo", + dependencies: { + baz: "~0.0.2", + }, + }), + ); + const { + stdout: stdout1, + stderr: stderr1, + exited: exited1, + } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr1).toBeDefined(); + const err1 = await new Response(stderr1).text(); + expect(err1).not.toContain("error:"); + expect(err1).toContain("Saved lockfile"); + expect(stdout1).toBeDefined(); + const out1 = await new Response(stdout1).text(); + expect(out1.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + baz@0.0.3", + "", + " 1 packages installed", + ]); + expect(await exited1).toBe(0); + expect(urls.sort()).toEqual([`${root_url}/baz`, `${root_url}/baz-0.0.3.tgz`]); + expect(requested).toBe(2); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".bin", ".cache", "baz"]); + expect(await readdirSorted(join(package_dir, "node_modules", ".bin"))).toEqual(["baz-run"]); + expect(await readlink(join(package_dir, "node_modules", ".bin", "baz-run"))).toBe(join("..", "baz", "index.js")); + expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["index.js", "package.json"]); + expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toEqual({ + name: "baz", + version: "0.0.3", + bin: { + "baz-run": "index.js", + }, + }); + await access(join(package_dir, "bun.lockb")); + // Perform `bun update` with updated registry & lockfile from before + await rm(join(package_dir, "node_modules"), { force: true, recursive: true }); + urls.length = 0; + registry.latest = "0.0.5"; + setHandler(dummyRegistry(urls, registry)); + const { + stdout: stdout2, + stderr: stderr2, + exited: exited2, + } = spawn({ + cmd: [bunExe(), "update", "baz"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr2).toBeDefined(); + const err2 = await new Response(stderr2).text(); + expect(err2).not.toContain("error:"); + expect(err2).toContain("Saved lockfile"); + expect(stdout2).toBeDefined(); + const out2 = await new Response(stdout2).text(); + expect(out2.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + "", + " installed baz@0.0.5 with binaries:", + " - baz-exec", + "", + "", + " 1 packages installed", + ]); + expect(await exited2).toBe(0); + expect(urls.sort()).toEqual([`${root_url}/baz`, `${root_url}/baz-0.0.5.tgz`]); + expect(requested).toBe(4); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".bin", ".cache", "baz"]); + expect(await readdirSorted(join(package_dir, "node_modules", ".bin"))).toEqual(["baz-exec"]); + expect(await readlink(join(package_dir, "node_modules", ".bin", "baz-exec"))).toBe(join("..", "baz", "index.js")); + expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["index.js", "package.json"]); + expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toEqual({ + name: "baz", + version: "0.0.5", + bin: { + "baz-exec": "index.js", + }, + }); + await access(join(package_dir, "bun.lockb")); +}); + +it("should update to latest versions of dependencies", async () => { + const urls: string[] = []; + const registry = { + "0.0.3": { + bin: { + "baz-run": "index.js", + }, + }, + "0.0.5": { + bin: { + "baz-exec": "index.js", + }, + }, + "0.1.0": {}, + latest: "0.0.3", + }; + setHandler(dummyRegistry(urls, registry)); + await writeFile( + join(package_dir, "package.json"), + JSON.stringify({ + name: "foo", + dependencies: { + "@barn/moo": "^0.1.0", + baz: "~0.0.2", + }, + }), + ); + const { + stdout: stdout1, + stderr: stderr1, + exited: exited1, + } = spawn({ + cmd: [bunExe(), "install"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr1).toBeDefined(); + const err1 = await new Response(stderr1).text(); + expect(err1).not.toContain("error:"); + expect(err1).toContain("Saved lockfile"); + expect(stdout1).toBeDefined(); + const out1 = await new Response(stdout1).text(); + expect(out1.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + @barn/moo@0.1.0", + " + baz@0.0.3", + "", + " 2 packages installed", + ]); + expect(await exited1).toBe(0); + expect(urls.sort()).toEqual([ + `${root_url}/@barn/moo`, + `${root_url}/@barn/moo-0.1.0.tgz`, + `${root_url}/baz`, + `${root_url}/baz-0.0.3.tgz`, + ]); + expect(requested).toBe(4); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".bin", ".cache", "@barn", "baz"]); + expect(await readdirSorted(join(package_dir, "node_modules", ".bin"))).toEqual(["baz-run"]); + expect(await readlink(join(package_dir, "node_modules", ".bin", "baz-run"))).toBe(join("..", "baz", "index.js")); + expect(await readdirSorted(join(package_dir, "node_modules", "@barn"))).toEqual(["moo"]); + expect(await readdirSorted(join(package_dir, "node_modules", "@barn", "moo"))).toEqual(["package.json"]); + expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["index.js", "package.json"]); + expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toEqual({ + name: "baz", + version: "0.0.3", + bin: { + "baz-run": "index.js", + }, + }); + await access(join(package_dir, "bun.lockb")); + // Perform `bun update` with updated registry & lockfile from before + await rm(join(package_dir, "node_modules"), { force: true, recursive: true }); + urls.length = 0; + registry.latest = "0.0.5"; + setHandler(dummyRegistry(urls, registry)); + const { + stdout: stdout2, + stderr: stderr2, + exited: exited2, + } = spawn({ + cmd: [bunExe(), "update"], + cwd: package_dir, + stdout: null, + stdin: "pipe", + stderr: "pipe", + env, + }); + expect(stderr2).toBeDefined(); + const err2 = await new Response(stderr2).text(); + expect(err2).not.toContain("error:"); + expect(err2).toContain("Saved lockfile"); + expect(stdout2).toBeDefined(); + const out2 = await new Response(stdout2).text(); + expect(out2.replace(/\s*\[[0-9\.]+m?s\]\s*$/, "").split(/\r?\n/)).toEqual([ + " + @barn/moo@0.1.0", + " + baz@0.0.5", + "", + " 2 packages installed", + ]); + expect(await exited2).toBe(0); + expect(urls.sort()).toEqual([ + `${root_url}/@barn/moo`, + `${root_url}/@barn/moo-0.1.0.tgz`, + `${root_url}/baz`, + `${root_url}/baz-0.0.5.tgz`, + ]); + expect(requested).toBe(8); + expect(await readdirSorted(join(package_dir, "node_modules"))).toEqual([".bin", ".cache", "@barn", "baz"]); + expect(await readdirSorted(join(package_dir, "node_modules", ".bin"))).toEqual(["baz-exec"]); + expect(await readlink(join(package_dir, "node_modules", ".bin", "baz-exec"))).toBe(join("..", "baz", "index.js")); + expect(await readdirSorted(join(package_dir, "node_modules", "@barn"))).toEqual(["moo"]); + expect(await readdirSorted(join(package_dir, "node_modules", "@barn", "moo"))).toEqual(["package.json"]); + expect(await readdirSorted(join(package_dir, "node_modules", "baz"))).toEqual(["index.js", "package.json"]); + expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toEqual({ + name: "baz", + version: "0.0.5", + bin: { + "baz-exec": "index.js", + }, + }); + await access(join(package_dir, "bun.lockb")); +}); diff --git a/test/cli/run/env.test.ts b/test/cli/run/env.test.ts index 6e4d83d44ece80..159793e27ef0fe 100644 --- a/test/cli/run/env.test.ts +++ b/test/cli/run/env.test.ts @@ -1,5 +1,22 @@ import { describe, expect, test } from "bun:test"; -import { bunRun, bunTest, tempDirWithFiles } from "harness"; +import { bunRun, bunTest, tempDirWithFiles, bunExe, bunEnv } from "harness"; +import path from "path"; + +function bunRunWithoutTrim(file: string, env?: Record) { + const result = Bun.spawnSync([bunExe(), file], { + cwd: path.dirname(file), + env: { + ...bunEnv, + NODE_ENV: undefined, + ...env, + }, + }); + if (!result.success) throw new Error(result.stderr.toString("utf8")); + return { + stdout: result.stdout.toString("utf8"), + stderr: result.stderr.toString("utf8").trim(), + }; +} describe(".env file is loaded", () => { test(".env", () => { @@ -338,3 +355,52 @@ test(".env in a folder doesn't throw an error", () => { const { stdout } = bunRun(`${dir}/index.ts`); expect(stdout).toBe("hey"); }); + +test("#3911", () => { + const dir = tempDirWithFiles("dotenv", { + ".env": 'KEY="a\\nb"', + "index.ts": "console.log(process.env.KEY);", + }); + const { stdout } = bunRun(`${dir}/index.ts`); + expect(stdout).toBe("a\nb"); +}); + +describe("boundary tests", () => { + test("src boundary", () => { + const dir = tempDirWithFiles("dotenv", { + ".env": 'KEY="a\\n"', + "index.ts": "console.log(process.env.KEY);", + }); + const { stdout } = bunRunWithoutTrim(`${dir}/index.ts`); + // should be "a\n" but console.log adds a newline + expect(stdout).toBe("a\n\n"); + + const dir2 = tempDirWithFiles("dotenv", { + ".env": 'KEY="a\\n', + "index.ts": "console.log(process.env.KEY);", + }); + const { stdout: stdout2 } = bunRunWithoutTrim(`${dir2}/index.ts`); + // should be "a\n but console.log adds a newline + expect(stdout2).toBe('"a\n\n'); + }); + + test("buffer boundary", () => { + const expected = "a".repeat(4094); + let content = expected + "a"; + const dir = tempDirWithFiles("dotenv", { + ".env": `KEY="${content}"`, + "index.ts": "console.log(process.env.KEY);", + }); + const { stdout } = bunRun(`${dir}/index.ts`); + + content = expected + "\\n"; + const dir2 = tempDirWithFiles("dotenv", { + ".env": `KEY="${content}"`, + "index.ts": "console.log(process.env.KEY);", + }); + const { stdout: stdout2 } = bunRun(`${dir2}/index.ts`); + // should be truncated + expect(stdout).toBe(expected); + expect(stdout2).toBe(expected); + }); +}); diff --git a/test/cli/run/require-cache-fixture.cjs b/test/cli/run/require-cache-fixture.cjs index 838be9cebdca0f..69f8cebeb0436a 100644 --- a/test/cli/run/require-cache-fixture.cjs +++ b/test/cli/run/require-cache-fixture.cjs @@ -27,13 +27,15 @@ const foo = require("./require-cache-fixture-b.cjs"); exports.foo = foo; -if (require.cache[require.resolve("./require-cache-fixture-b.cjs")].exports !== exports.foo) { +var res = require.resolve; + +if (require.cache[res("./require-cache-fixture-b.cjs")].exports !== exports.foo) { throw new Error("exports.foo !== require.cache[require.resolve('./require-cache-fixture-b')]"); } Bun.gc(true); -delete require.cache[require.resolve("./require-cache-fixture-b.cjs")]; +delete require.cache[res("./require-cache-fixture-b.cjs")]; Bun.gc(true); @@ -41,7 +43,7 @@ exports.bar = require("./require-cache-fixture-b.cjs"); Bun.gc(true); -if (require.cache[require.resolve("./require-cache-fixture-b.cjs")].exports !== exports.bar) { +if (require.cache[res("./require-cache-fixture-b.cjs")].exports !== exports.bar) { throw new Error("exports.bar !== require.cache[require.resolve('./require-cache-fixture-b')]"); } diff --git a/test/cli/run/run-cjs.test.ts b/test/cli/run/run-cjs.test.ts index 5b70f8384db5ed..38cb11e6f6a8cf 100644 --- a/test/cli/run/run-cjs.test.ts +++ b/test/cli/run/run-cjs.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import { mkdirSync, realpathSync } from "fs"; -import { bunEnv, bunExe } from "harness"; +import { bunEnv, bunExe, tempDirWithFiles, bunRunAsScript } from "harness"; import { tmpdir } from "os"; import { join } from "path"; @@ -15,6 +15,10 @@ test.todo("running a commonjs module works", async () => { }); expect(stdout.toString("utf8")).toEqual("hello world\n"); }); +<<<<<<< HEAD +<<<<<<< HEAD +======= +>>>>>>> 6ac18215 (oops) test("not running with export default class", async () => { const dir = join(realpathSync(tmpdir()), "bun-run-test2"); @@ -38,3 +42,206 @@ export default Foo }); expect(stdout.toString("utf8")).toEqual(""); }); + +test("npm_package_config", () => { +<<<<<<< HEAD +<<<<<<< HEAD + const vals = { + "port": 8000, + "password": "hello world", + "password2": " hello world ", +<<<<<<< HEAD +======= + const vals = { + "port": 8000, + "password": "hello world", +>>>>>>> 487a471a (More fixes) +======= +>>>>>>> a57fc15f (Little fixes) + "isDev": true, + "isProd": false, + "piNum": 3.14, + "emptyStr": "", +<<<<<<< HEAD +<<<<<<< HEAD +<<<<<<< HEAD + "emptyStr2": " ", +======= + // "emptyStr2": " ", TODO: fix this being "" in bun + /* "foo": { + "bar": "baz" + }, TODO: Support objects */ +>>>>>>> 487a471a (More fixes) +======= +>>>>>>> 40553a28 (Add object support) +======= + "emptyStr2": " ", +>>>>>>> a57fc15f (Little fixes) + "why": 0, + "none": null, + "emoji": "🍕" + }; +<<<<<<< HEAD + + const dir = tempDirWithFiles("npmpkgcfg", { + "package.json": JSON.stringify({ + config: vals, + "scripts": { + "dev": bunExe() + " run index.js" + } + }), + "index.js": "console.log(JSON.stringify(process.env))" + }); + + const { stdout } = bunRunAsScript(dir, "dev"); + const jsStd = JSON.parse(stdout.toString()) + + for (const [key, val] of Object.entries(vals)) { + const jsVl = jsStd[`npm_package_config_${key}`]; +<<<<<<< HEAD + + expect(jsVl).toBeTypeOf("string"); + + if (val === false || val === null) { + expect(jsVl).toEqual('""'); +<<<<<<< HEAD + continue; + } + + if (jsVl == '""' && key === "emptyStr") { + continue; + } + + expect(jsVl).toEqual(val.toString()); + } + + // Now deep objects + const deepDir = tempDirWithFiles("npmpkgcfg", { + "package.json": JSON.stringify({ + config: { + "foo": { + "bar": "baz", + "buzz": { + "fizz": " fuzz", + "dave": "🕶️", + "something": 1 + } + } + }, + "scripts": { + "dev": bunExe() + " run index.js" + } + }), + "index.js": "console.log(JSON.stringify(process.env))" + }); + + const { stdout: deepStdout } = bunRunAsScript(deepDir, "dev"); + const deepJsStd = JSON.parse(deepStdout.toString()) + + expect(deepJsStd.npm_package_config_foo_bar).toEqual("baz"); + expect(deepJsStd.npm_package_config_foo_buzz_fizz).toEqual(" fuzz"); + expect(deepJsStd.npm_package_config_foo_buzz_dave).toEqual("🕶️"); + expect(deepJsStd.npm_package_config_foo_buzz_something).toEqual("1"); +======= + const dir = tempDirWithFiles("npmpkgcfg", { + "package.json": JSON.stringify({ + "name": "bun_npm_package_config", + "config": { + "a": "echo Hello, Bun!" + }, + "scripts": { + "c": "$npm_package_config_a", + } + }) + }); + + const { stdout } = bunRunAsScript(dir, "c"); + expect(stdout.toString()).toBe("Hello, Bun!"); +======= +>>>>>>> 487a471a (More fixes) + + const dir = tempDirWithFiles("npmpkgcfg", { + "package.json": JSON.stringify({ + config: vals, + "scripts": { + "dev": bunExe() + " run index.js" + } + }), + "index.js": "console.log(JSON.stringify(process.env))" + }); + +<<<<<<< HEAD + const { stdout: stdout2 } = bunRunAsScript(dir2, "c"); + expect(stdout2.toString()).toBe("Hello, Bun!"); +<<<<<<< HEAD +>>>>>>> c750eb5d (Impl. npm_package_config) +======= +======= + const { stdout } = bunRunAsScript(dir, "dev"); + const jsStd = JSON.parse(stdout.toString()) +>>>>>>> 487a471a (More fixes) + + for (const [key, val] of Object.entries(vals)) { + const jsVl = jsStd[`npm_package_config_${key}`]; + console.log(key, jsVl, val) +======= +>>>>>>> 40553a28 (Add object support) + +<<<<<<< HEAD + const { stdout: stdout3 } = bunRunAsScript(dir3, "c"); + expect(JSON.parse(stdout3)).toEqual({ port: '8080', somebool: 'true' }); +>>>>>>> adf1d592 (Add support for numbers + booleans) +======= + expect(jsVl).toBeTypeOf("string"); + + if (val === false || val === null) { + expect(jsVl).toEqual(""); +======= +>>>>>>> a57fc15f (Little fixes) + continue; + } + + if (jsVl == '""' && key === "emptyStr") { + continue; + } + + expect(jsVl).toEqual(val.toString()); + } +<<<<<<< HEAD +>>>>>>> 487a471a (More fixes) +======= + + // Now deep objects + const deepDir = tempDirWithFiles("npmpkgcfg", { + "package.json": JSON.stringify({ + config: { + "foo": { + "bar": "baz", + "buzz": { + "fizz": " fuzz", + "dave": "🕶️", + "something": 1 + } + } + }, + "scripts": { + "dev": bunExe() + " run index.js" + } + }), + "index.js": "console.log(JSON.stringify(process.env))" + }); + + const { stdout: deepStdout } = bunRunAsScript(deepDir, "dev"); + const deepJsStd = JSON.parse(deepStdout.toString()) + + expect(deepJsStd.npm_package_config_foo_bar).toEqual("baz"); + expect(deepJsStd.npm_package_config_foo_buzz_fizz).toEqual(" fuzz"); + expect(deepJsStd.npm_package_config_foo_buzz_dave).toEqual("🕶️"); + expect(deepJsStd.npm_package_config_foo_buzz_something).toEqual("1"); +>>>>>>> 40553a28 (Add object support) +}); +<<<<<<< HEAD +======= +>>>>>>> c2a77cf7 (Rewrite built-in modules to use CommonJS over ESM (#3814)) +======= +>>>>>>> 6ac18215 (oops) diff --git a/test/harness.ts b/test/harness.ts index ab3ae5ca29dc8e..2da12e094522e7 100644 --- a/test/harness.ts +++ b/test/harness.ts @@ -1,8 +1,4 @@ import { gc as bunGC, unsafe, which } from "bun"; -import { heapStats } from "bun:jsc"; -import path from "path"; -import fs from "fs"; -import os from "os"; export const bunEnv: any = { ...process.env, @@ -43,6 +39,8 @@ export async function expectMaxObjectTypeCount( count: number, maxWait = 1000, ) { + var { heapStats } = require("bun:jsc"); + gc(); if (heapStats().objectTypeCounts[type] <= count) return; gc(true); @@ -85,7 +83,11 @@ export function hideFromStackTrace(block: CallableFunction) { } export function tempDirWithFiles(basename: string, files: Record>) { - const dir = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), basename + "_")); + var fs = require("fs"); + var path = require("path"); + var { tmpdir } = require("os"); + + const dir = fs.mkdtempSync(path.join(fs.realpathSync(tmpdir()), basename + "_")); for (const [name, contents] of Object.entries(files)) { if (typeof contents === "object") { fs.mkdirSync(path.join(dir, name)); @@ -100,6 +102,7 @@ export function tempDirWithFiles(basename: string, files: Record) { + var path = require("path"); const result = Bun.spawnSync([bunExe(), file], { cwd: path.dirname(file), env: { @@ -116,6 +119,7 @@ export function bunRun(file: string, env?: Record) { } export function bunTest(file: string, env?: Record) { + var path = require("path"); const result = Bun.spawnSync([bunExe(), "test", path.basename(file)], { cwd: path.dirname(file), env: { diff --git a/test/js/bun/ffi/ffi.test.js b/test/js/bun/ffi/ffi.test.js index c54a3d3d967a3a..5cefafaf8a9303 100644 --- a/test/js/bun/ffi/ffi.test.js +++ b/test/js/bun/ffi/ffi.test.js @@ -10,6 +10,7 @@ import { toArrayBuffer, toBuffer, viewSource, + suffix, } from "bun:ffi"; const dlopen = (...args) => { @@ -20,7 +21,7 @@ const dlopen = (...args) => { throw err; } }; -const ok = existsSync("/tmp/bun-ffi-test.dylib"); +const ok = existsSync("/tmp/bun-ffi-test." + suffix); it("ffi print", async () => { await Bun.write( @@ -626,3 +627,7 @@ it("dlopen throws an error instead of returning it", () => { } expect(err).toBeTruthy(); }); + +it('suffix does not start with a "."', () => { + expect(suffix).not.toMatch(/^\./); +}); diff --git a/test/js/bun/globals.test.js b/test/js/bun/globals.test.js index ac2d406594fb4e..6b004a5f7afe5a 100644 --- a/test/js/bun/globals.test.js +++ b/test/js/bun/globals.test.js @@ -1,8 +1,7 @@ -import { it, describe, expect } from "bun:test"; +import { expect, it } from "bun:test"; it("extendable", () => { const classes = [Blob, TextDecoder, TextEncoder, Request, Response, Headers, HTMLRewriter, Bun.Transpiler, Buffer]; - // None of these should error for (let Class of classes) { var Foo = class extends Class {}; var bar = Class === Request ? new Request({ url: "https://example.com" }) : new Foo(); @@ -15,15 +14,17 @@ it("extendable", () => { it("writable", () => { const classes = [ - // ["Blob", Blob], ["TextDecoder", TextDecoder], - // ["TextEncoder", TextEncoder], ["Request", Request], ["Response", Response], ["Headers", Headers], ["Buffer", Buffer], - // ["HTMLRewriter", HTMLRewriter], - // ["Transpiler", Bun.Transpiler], + ["Event", Event], + ["DOMException", DOMException], + ["EventTarget", EventTarget], + ["ErrorEvent", ErrorEvent], + ["CustomEvent", CustomEvent], + ["CloseEvent", CloseEvent], ]; for (let [name, Class] of classes) { globalThis[name] = 123; diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 37675c25d6f1cb..6220b6a54e4b4a 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -1,6 +1,88 @@ import { describe, expect, test } from "bun:test"; describe("Server", () => { + test.only("normlizes incoming request URLs", async () => { + const server = Bun.serve({ + fetch(request) { + return new Response(request.url, { + headers: { + "Connection": "close", + }, + }); + }, + port: 0, + }); + const received: string[] = []; + const expected: string[] = []; + for (let path of [ + "/", + "/../", + "/./", + "/foo", + "/foo/", + "/foo/bar", + "/foo/bar/", + "/foo/bar/..", + "/foo/bar/../", + "/foo/bar/../?123", + "/foo/bar/../?123=456", + "/foo/bar/../#123=456", + "/", + "/../", + "/./", + "/foo", + "/foo/", + "/foo/bar", + "/foo/bar/", + "/foo/bar/..", + "/foo/bar/../", + "/foo/bar/../?123", + "/foo/bar/../?123=456", + "/foo/bar/../#123=456", + "/../".repeat(128), + "/./".repeat(128), + "/foo".repeat(128), + "/foo/".repeat(128), + "/foo/bar".repeat(128), + "/foo/bar/".repeat(128), + "/foo/bar/..".repeat(128), + "/foo/bar/../".repeat(128), + "/../".repeat(128), + "/./".repeat(128), + "/foo".repeat(128), + "/foo/".repeat(128), + "/foo/bar".repeat(128), + "/foo/bar/".repeat(128), + "/foo/bar/..".repeat(128), + "/foo/bar/../".repeat(128), + ]) { + expected.push(new URL(path, "http://localhost:" + server.port).href); + + const { promise, resolve } = Promise.withResolvers(); + Bun.connect({ + hostname: server.hostname, + port: server.port, + + socket: { + async open(socket) { + socket.write(`GET ${path} HTTP/1.1\r\nHost: localhost:${server.port}\r\n\r\n`); + await socket.flush(); + }, + async data(socket, data) { + const lines = Buffer.from(data).toString("utf8"); + received.push(lines.split("\r\n\r\n").at(-1)!); + await socket.end(); + resolve(); + }, + }, + }); + await promise; + } + + server.stop(true); + expect(received).toEqual(expected); + }); + test("should not allow Bun.serve without first argument being a object", () => { expect(() => { //@ts-ignore @@ -205,7 +287,7 @@ describe("Server", () => { }, }); try { - const url = `http://${server.hostname}:${server.port}`; + const url = `http://${server.hostname}:${server.port}/`; const response = await server.fetch(url); expect(await response.text()).toBe("Hello World!"); expect(response.status).toBe(200); @@ -222,7 +304,7 @@ describe("Server", () => { }, }); try { - const url = `http://${server.hostname}:${server.port}`; + const url = `http://${server.hostname}:${server.port}/`; const response = await server.fetch(new Request(url)); expect(await response.text()).toBe("Hello World!"); expect(response.status).toBe(200); diff --git a/test/js/bun/resolve/import-meta.test.js b/test/js/bun/resolve/import-meta.test.js index e23b444462c434..613afe636a9ea7 100644 --- a/test/js/bun/resolve/import-meta.test.js +++ b/test/js/bun/resolve/import-meta.test.js @@ -181,3 +181,7 @@ it('import("bun") works', async () => { it("require.resolve with empty options object", () => { expect(require.resolve(import.meta.path + String(""), {})).toBe(import.meta.path); }); + +it("dynamically import bun", async () => { + expect((await import(eval("'bun'"))).default).toBe(Bun); +}); diff --git a/test/js/bun/resolve/resolve-error.test.ts b/test/js/bun/resolve/resolve-error.test.ts index d2114190fcdabf..9d2e09fad84388 100644 --- a/test/js/bun/resolve/resolve-error.test.ts +++ b/test/js/bun/resolve/resolve-error.test.ts @@ -8,4 +8,10 @@ describe("ResolveMessage", () => { expect(Bun.inspect(e.position).length > 0).toBe(true); } }); + it("invalid data URL import", async () => { + expect(async () => { + // @ts-ignore + await import("data:Hello%2C%20World!"); + }).toThrow("Cannot resolve invalid data URL"); + }); }); diff --git a/test/js/bun/sqlite/sqlite.test.js b/test/js/bun/sqlite/sqlite.test.js index e4725cac291be4..7998f74693a94d 100644 --- a/test/js/bun/sqlite/sqlite.test.js +++ b/test/js/bun/sqlite/sqlite.test.js @@ -553,3 +553,39 @@ describe("Database.run", () => { } }); }); + +it("#3991", () => { + const db = new Database(":memory:"); + db.prepare( + `CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + xx TEXT) +`, + ).run(); + + db.prepare( + `insert into users (id, xx) values ( + 'foobar', + '{ + "links": [{"1": { + "2": "https://foobar.to/123", + "3": "4" + }}] + + }' +)`, + ).run(); + + let x = db + .query( + `SELECT * FROM users + WHERE users.id = 'foobar' + limit 1`, + ) + .get(); + + // Check we don't crash when a column with a string value greater than 64 characters is present. + expect(x.abc).toBeUndefined(); + + expect(x.id).toBe("foobar"); +}); diff --git a/test/js/bun/test/expect.test.js b/test/js/bun/test/expect.test.js index ed94b7e9ae1f7b..397afd0d9b384e 100644 --- a/test/js/bun/test/expect.test.js +++ b/test/js/bun/test/expect.test.js @@ -2898,28 +2898,6 @@ describe("expect()", () => { expect({}).not.toBeNil(); }); - test("toBeArray()", () => { - expect([]).toBeArray(); - expect([1, 2, 3, "🫓"]).toBeArray(); - expect(new Array()).toBeArray(); - expect(new Array(1, 2, 3)).toBeArray(); - expect({}).not.toBeArray(); - expect("🫓").not.toBeArray(); - expect(0).not.toBeArray(); - expect(true).not.toBeArray(); - expect(null).not.toBeArray(); - }); - - test("toBeArrayOfSize()", () => { - expect([]).toBeArrayOfSize(0); - expect(new Array()).toBeArrayOfSize(0); - expect([1, 2, 3, "🫓"]).toBeArrayOfSize(4); - expect(new Array(1, 2, 3, "🫓")).toBeArrayOfSize(4); - expect({}).not.toBeArrayOfSize(1); - expect("").not.toBeArrayOfSize(1); - expect(0).not.toBeArrayOfSize(1); - }); - test("toBeTypeOf()", () => { expect("Bun! 🫓").toBeTypeOf("string"); expect(0).toBeTypeOf("number"); diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts new file mode 100644 index 00000000000000..fc4145cbe15407 --- /dev/null +++ b/test/js/bun/test/jest-each.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "bun:test"; + +const NUMBERS = [ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]; + +describe("jest-each", () => { + it("check types", () => { + expect(it.each).toBeTypeOf("function"); + expect(it.each([])).toBeTypeOf("function"); + }); + it.each(NUMBERS)("add two numbers", (a, b, e) => { + expect(a + b).toBe(e); + }); + it.each(NUMBERS)("add two numbers with callback", (a, b, e, done) => { + expect(a + b).toBe(e); + expect(done).toBeDefined(); + // We cast here because we cannot type done when typing args as ...T + (done as unknown as (err?: unknown) => void)(); + }); + it.each([ + ["a", "b", "ab"], + ["c", "d", "cd"], + ["e", "f", "ef"], + ])(`adds two strings`, (a, b, res) => { + expect(typeof a).toBe("string"); + expect(typeof b).toBe("string"); + expect(typeof res).toBe("string"); + expect(a.concat(b)).toBe(res); + }); + it.each([ + { a: 1, b: 1, e: 2 }, + { a: 1, b: 2, e: 3 }, + { a: 2, b: 13, e: 15 }, + { a: 2, b: 13, e: 15 }, + { a: 2, b: 123, e: 125 }, + { a: 15, b: 13, e: 28 }, + ])("add two numbers with object", ({ a, b, e }, cb) => { + expect(a + b).toBe(e); + cb(); + }); +}); + +describe.each(["some", "cool", "strings"])("works with describe", s => { + it(`has access to params : ${s}`, done => { + expect(s).toBeTypeOf("string"); + done(); + }); +}); diff --git a/test/js/bun/test/jest-extended.test.js b/test/js/bun/test/jest-extended.test.js index b03e0828fb6ac7..816863218501f1 100644 --- a/test/js/bun/test/jest-extended.test.js +++ b/test/js/bun/test/jest-extended.test.js @@ -15,17 +15,22 @@ const inspect = isBun ? Bun.inspect : require("util").inspect; // https://jest-extended.jestcommunity.dev/docs/matchers/ describe("jest-extended", () => { - test.todo("pass()", () => { - expect(typeof expect().pass).toBe("function"); - expect(() => expect().not.pass()).toThrow(); + test("pass()", () => { + expect(expect().pass).toBeTypeOf("function"); + expect(() => expect("ignored value").not.pass()).toThrow("passes by .pass() assertion"); + expect(() => expect().not.pass("message here")).toThrow("message here"); + expect(() => expect().pass(1)).toThrow("Expected message to be a string for 'pass'."); expect().pass(); expect().pass("message ignored"); }); - test.todo("fail()", () => { - expect(typeof expect().fail).toBe("function"); + test("fail()", () => { + expect(expect().fail).toBeTypeOf("function"); expect(() => expect("ignored value").fail("message here")).toThrow("message here"); + expect(() => expect().fail()).toThrow("fails by .fail() assertion"); + expect(() => expect().fail(1)).toThrow("Expected message to be a string for 'fail'."); expect().not.fail(); + expect().not.fail("message ignored"); }); describe("toBeEmpty()", () => { @@ -105,12 +110,62 @@ describe("jest-extended", () => { expect({}).not.toBeNil(); }); - // test('toSatisfy()') + test("toSatisfy()", () => { + // Arrow functions + const isOdd = value => value % 2 === 1; + const hasLetterH = (value) => value.includes("H"); + + expect(1).toSatisfy(isOdd); + expect("Hello").toSatisfy(hasLetterH); + + // Function expressions + function hasBunInAnArray(value) { return value.includes("bun"); } + + expect(["bun", "cheese", "patty"]).toSatisfy(hasBunInAnArray); + expect(["cheese", "patty"]).not.toSatisfy(hasBunInAnArray); + + // Inline functions + expect([]).toSatisfy((value) => value.length === 0); + expect([]).not.toSatisfy(value => value.length > 0); + + // Some other types + const fooIsBar = (value) => value?.foo === "bar"; + + expect({ foo: "bar" }).toSatisfy(fooIsBar); + expect({ foo: "bun" }).not.toSatisfy(fooIsBar); + expect({ bar: "foo" }).not.toSatisfy(fooIsBar); + + // Test errors + // @ts-expect-error + expect(() => expect(1).toSatisfy(() => new Error('Bun!'))).toThrow('predicate threw an exception'); + // @ts-expect-error + expect(() => expect(1).not.toSatisfy(() => new Error('Bun!'))).toThrow('predicate threw an exception'); + }); // Array - // test('toBeArray()') - // test('toBeArrayOfSize()') + test("toBeArray()", () => { + expect([]).toBeArray(); + expect([1, 2, 3, "🫓"]).toBeArray(); + expect(new Array()).toBeArray(); + expect(new Array(1, 2, 3)).toBeArray(); + expect({}).not.toBeArray(); + expect("🫓").not.toBeArray(); + expect(0).not.toBeArray(); + expect(true).not.toBeArray(); + expect(null).not.toBeArray(); + }); + + test("toBeArrayOfSize()", () => { + expect([]).toBeArrayOfSize(0); + expect(new Array()).toBeArrayOfSize(0); + expect([1, 2, 3, "🫓"]).toBeArrayOfSize(4); + expect(new Array(1, 2, 3, "🫓")).toBeArrayOfSize(4); + expect({}).not.toBeArrayOfSize(1); + expect("").not.toBeArrayOfSize(1); + expect(0).not.toBeArrayOfSize(1); + }); + // test('toIncludeAllMembers()') // test('toIncludeAllPartialMembers()') // test('toIncludeAnyMembers()') @@ -484,7 +539,49 @@ describe("jest-extended", () => { expect("bob").not.toInclude("alice"); }); - // test("toIncludeRepeated()") + test("toIncludeRepeated()", () => { + // 0 + expect("a").toIncludeRepeated("b", 0) + expect("b").not.toIncludeRepeated("b", 0); + + // 1 + expect("abc").toIncludeRepeated("a", 1); + expect("abc").not.toIncludeRepeated("d", 1); + + // Any other number + expect("abc abc abc").toIncludeRepeated("abc", 1); + expect("abc abc abc").toIncludeRepeated("abc", 2); + expect("abc abc abc").toIncludeRepeated("abc", 3); + expect("abc abc abc").not.toIncludeRepeated("abc", 4); + + // Emojis/Unicode + expect("😘🥳😤😘🥳").toIncludeRepeated("😘", 1); + expect("😘🥳😤😘🥳").toIncludeRepeated("🥳", 2); + expect("😘🥳😤😘🥳").not.toIncludeRepeated("😘", 3); + expect("😘🥳😤😘🥳").not.toIncludeRepeated("😶‍🌫️", 1); + + // Empty string + expect("").not.toIncludeRepeated("a", 1); + + // if toIncludeRepeated() is called with a empty string, it should throw an error or else it segfaults + expect(() => expect("a").not.toIncludeRepeated("", 1)).toThrow() + + // Just to make sure it doesn't throw an error + expect("").not.toIncludeRepeated("a", 1) + expect("").not.toIncludeRepeated("😶‍🌫️", 1) + + // Expect them to throw an error + const tstErr = (y) => { return expect("").toIncludeRepeated("a", y) }; + + expect(() => tstErr(1.23)).toThrow(); + expect(() => tstErr(Infinity)).toThrow(); + expect(() => tstErr(NaN)).toThrow(); + expect(() => tstErr(-0)).toThrow(); // -0 and below (-1, -2, ...) + expect(() => tstErr(null)).toThrow(); + expect(() => tstErr(undefined)).toThrow(); + expect(() => tstErr({})).toThrow(); + }) ; + // test("toIncludeMultiple()") // test("toEqualIgnoringWhitespace()") diff --git a/test/js/bun/util/bun-isMainThread.test.js b/test/js/bun/util/bun-isMainThread.test.js new file mode 100644 index 00000000000000..87f74d136c98d9 --- /dev/null +++ b/test/js/bun/util/bun-isMainThread.test.js @@ -0,0 +1,15 @@ +import { test, expect } from "bun:test"; +import { bunEnv, bunExe } from "harness"; + +test("Bun.isMainThread", () => { + expect(Bun.isMainThread).toBeTrue(); + + const { stdout, exitCode } = Bun.spawnSync({ + cmd: [bunExe(), import.meta.resolveSync("./main-worker-file.js")], + stderr: "inherit", + stdout: "pipe", + env: bunEnv, + }); + expect(exitCode).toBe(0); + expect(stdout.toString()).toBe("isMainThread true\nisMainThread false\n"); +}); diff --git a/test/js/bun/util/hash.test.js b/test/js/bun/util/hash.test.js index 87a5a9ce327af4..29c683801b8132 100644 --- a/test/js/bun/util/hash.test.js +++ b/test/js/bun/util/hash.test.js @@ -1,47 +1,50 @@ -import fs from "fs"; import { it, expect } from "bun:test"; -import path from "path"; import { gcTick } from "harness"; it(`Bun.hash()`, () => { gcTick(); - Bun.hash("hello world"); - Bun.hash(new TextEncoder().encode("hello world")); + expect(Bun.hash("hello world")).toBe(0x668d5e431c3b2573n); + expect(Bun.hash(new TextEncoder().encode("hello world"))).toBe(0x668d5e431c3b2573n); }); it(`Bun.hash.wyhash()`, () => { - Bun.hash.wyhash("hello world"); + expect(Bun.hash.wyhash("hello world")).toBe(0x668d5e431c3b2573n); gcTick(); - Bun.hash.wyhash(new TextEncoder().encode("hello world")); + expect(Bun.hash.wyhash(new TextEncoder().encode("hello world"))).toBe(0x668d5e431c3b2573n); }); it(`Bun.hash.adler32()`, () => { - Bun.hash.adler32("hello world"); + expect(Bun.hash.adler32("hello world")).toBe(0x1a0b045d); gcTick(); - Bun.hash.adler32(new TextEncoder().encode("hello world")); + expect(Bun.hash.adler32(new TextEncoder().encode("hello world"))).toBe(0x1a0b045d); }); it(`Bun.hash.crc32()`, () => { - Bun.hash.crc32("hello world"); + expect(Bun.hash.crc32("hello world")).toBe(0x0d4a1185); gcTick(); - Bun.hash.crc32(new TextEncoder().encode("hello world")); + expect(Bun.hash.crc32(new TextEncoder().encode("hello world"))).toBe(0x0d4a1185); }); it(`Bun.hash.cityHash32()`, () => { - Bun.hash.cityHash32("hello world"); + expect(Bun.hash.cityHash32("hello world")).toBe(0x19a7581a); gcTick(); - Bun.hash.cityHash32(new TextEncoder().encode("hello world")); + expect(Bun.hash.cityHash32(new TextEncoder().encode("hello world"))).toBe(0x19a7581a); gcTick(); }); it(`Bun.hash.cityHash64()`, () => { - Bun.hash.cityHash64("hello world"); + expect(Bun.hash.cityHash64("hello world")).toBe(0xc7920bbdbecee42fn); gcTick(); - Bun.hash.cityHash64(new TextEncoder().encode("hello world")); + expect(Bun.hash.cityHash64(new TextEncoder().encode("hello world"))).toBe(0xc7920bbdbecee42fn); gcTick(); }); it(`Bun.hash.murmur32v3()`, () => { - Bun.hash.murmur32v3("hello world"); + expect(Bun.hash.murmur32v3("hello world")).toBe(0x5e928f0f); gcTick(); - Bun.hash.murmur32v3(new TextEncoder().encode("hello world")); + expect(Bun.hash.murmur32v3(new TextEncoder().encode("hello world"))).toBe(0x5e928f0f); +}); +it(`Bun.hash.murmur32v2()`, () => { + expect(Bun.hash.murmur32v2("hello world")).toBe(0x44a81419); + gcTick(); + expect(Bun.hash.murmur32v2(new TextEncoder().encode("hello world"))).toBe(0x44a81419); }); it(`Bun.hash.murmur64v2()`, () => { - Bun.hash.murmur64v2("hello world"); + expect(Bun.hash.murmur64v2("hello world")).toBe(0xd3ba2368a832afcen); gcTick(); - Bun.hash.murmur64v2(new TextEncoder().encode("hello world")); + expect(Bun.hash.murmur64v2(new TextEncoder().encode("hello world"))).toBe(0xd3ba2368a832afcen); }); diff --git a/test/js/bun/util/inspect.test.js b/test/js/bun/util/inspect.test.js index e91204c698ffd1..4d5165543f9ba8 100644 --- a/test/js/bun/util/inspect.test.js +++ b/test/js/bun/util/inspect.test.js @@ -107,7 +107,7 @@ it("Request object", () => { ` Request (0 KB) { method: "GET", - url: "https://example.com", + url: "https://example.com/", headers: Headers {} }`.trim(), ); diff --git a/test/js/bun/util/main-worker-file.js b/test/js/bun/util/main-worker-file.js new file mode 100644 index 00000000000000..3764803978776e --- /dev/null +++ b/test/js/bun/util/main-worker-file.js @@ -0,0 +1,14 @@ +import { isMainThread } from "bun"; + +console.log("isMainThread", isMainThread); + +if (isMainThread) { + const worker = new Worker(import.meta.url); + const { promise, resolve } = Promise.withResolvers(); + + worker.addEventListener("open", () => { + resolve(); + }); + + await promise; +} diff --git a/test/js/deno/fetch/headers.test.ts b/test/js/deno/fetch/headers.test.ts index ee2466e32af0d4..efc4e6a6e113fc 100644 --- a/test/js/deno/fetch/headers.test.ts +++ b/test/js/deno/fetch/headers.test.ts @@ -311,6 +311,10 @@ test(function headersInitMultiple() { ...headers ]; assertEquals(actual, [ + [ + "x-deno", + "foo, bar" + ], [ "set-cookie", "foo=bar" @@ -318,10 +322,6 @@ test(function headersInitMultiple() { [ "set-cookie", "bar=baz" - ], - [ - "x-deno", - "foo, bar" ] ]); }); @@ -362,6 +362,10 @@ test(function headersAppendMultiple() { ...headers ]; assertEquals(actual, [ + [ + "x-deno", + "foo, bar" + ], [ "set-cookie", "foo=bar" @@ -369,10 +373,6 @@ test(function headersAppendMultiple() { [ "set-cookie", "bar=baz" - ], - [ - "x-deno", - "foo, bar" ] ]); }); diff --git a/test/js/first_party/utf-8-validate/utf-8-validate.test.ts b/test/js/first_party/utf-8-validate/utf-8-validate.test.ts new file mode 100644 index 00000000000000..781f9df8458f14 --- /dev/null +++ b/test/js/first_party/utf-8-validate/utf-8-validate.test.ts @@ -0,0 +1,7 @@ +import { test, expect } from "bun:test"; +import isValidUTF8 from "utf-8-validate"; + +test("utf-8-validate", () => { + expect(isValidUTF8(Buffer.from("😀"))).toBeTrue(); + expect(isValidUTF8(Buffer.from([0xff]))).toBeFalse(); +}); diff --git a/test/js/node/async_hooks/AsyncLocalStorage.test.ts b/test/js/node/async_hooks/AsyncLocalStorage.test.ts index 48f4cf16d105fd..40faf439ca8eec 100644 --- a/test/js/node/async_hooks/AsyncLocalStorage.test.ts +++ b/test/js/node/async_hooks/AsyncLocalStorage.test.ts @@ -1,5 +1,5 @@ import { AsyncLocalStorage, AsyncResource } from "async_hooks"; -import { beforeEach, describe, expect, test } from "bun:test"; +import { describe, expect, test } from "bun:test"; describe("AsyncLocalStorage", () => { test("throw inside of AsyncLocalStorage.run() will be passed out", () => { @@ -27,12 +27,6 @@ test("AsyncResource", () => { }); describe("async context passes through", () => { - beforeEach(() => { - /* @ts-ignore */ - const { set } = globalThis[Symbol.for("Bun.lazy")]("async_hooks"); - // just in case - set(undefined); - }); test("syncronously", () => { const s = new AsyncLocalStorage(); s.run("value", () => { diff --git a/test/js/node/buffer.test.js b/test/js/node/buffer.test.js index cfd11442348301..129ceb02b759a8 100644 --- a/test/js/node/buffer.test.js +++ b/test/js/node/buffer.test.js @@ -3,7 +3,6 @@ import { describe, it, expect, beforeEach, afterEach } from "bun:test"; import { gc } from "harness"; const BufferModule = await import("buffer"); - beforeEach(() => gc()); afterEach(() => gc()); @@ -12,7 +11,6 @@ it("isAscii", () => { expect(isAscii(new Buffer(""))).toBeTrue(); expect(isAscii(new Buffer([32, 32, 128]))).toBeFalse(); expect(isAscii(new Buffer("What did the 🦊 say?"))).toBeFalse(); - expect(isAscii(new Buffer("").buffer)).toBeTrue(); expect(isAscii(new Buffer([32, 32, 128]).buffer)).toBeFalse(); }); @@ -1203,20 +1201,22 @@ it("Buffer.compare", () => { } }); -it("Buffer.copy", () => { - var array1 = new Uint8Array(128); - array1.fill(100); - array1 = new Buffer(array1.buffer); - var array2 = new Uint8Array(128); - array2.fill(200); - array2 = new Buffer(array2.buffer); - var array3 = new Uint8Array(128); - array3 = new Buffer(array3.buffer); - gc(); - expect(array1.copy(array2)).toBe(128); - expect(array1.join("")).toBe(array2.join("")); +describe("Buffer.copy", () => { + it("should work", () => { + var array1 = new Uint8Array(128); + array1.fill(100); + array1 = new Buffer(array1.buffer); + var array2 = new Uint8Array(128); + array2.fill(200); + array2 = new Buffer(array2.buffer); + var array3 = new Uint8Array(128); + array3 = new Buffer(array3.buffer); + gc(); + expect(array1.copy(array2)).toBe(128); + expect(array1.join("")).toBe(array2.join("")); + }); - { + it("should work with offset", () => { // Create two `Buffer` instances. const buf1 = Buffer.allocUnsafe(26); const buf2 = Buffer.allocUnsafe(26).fill("!"); @@ -1229,9 +1229,23 @@ it("Buffer.copy", () => { // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. buf1.copy(buf2, 8, 16, 20); expect(buf2.toString("ascii", 0, 25)).toBe("!!!!!!!!qrst!!!!!!!!!!!!!"); - } + }); - { + it("should ignore sourceEnd if it's out of range", () => { + const buf1 = Buffer.allocUnsafe(26); + const buf2 = Buffer.allocUnsafe(10).fill("!"); + + for (let i = 0; i < 26; i++) { + // 97 is the decimal ASCII value for 'a'. + buf1[i] = i + 97; + } + + // Copy `buf1` bytes "xyz" into `buf2` starting at byte 1 of `buf2`. + expect(buf1.copy(buf2, 1, 23, 100)).toBe(3); + expect(buf2.toString()).toBe("!xyz!!!!!!"); + }); + + it("copy to the same buffer", () => { const buf = Buffer.allocUnsafe(26); for (let i = 0; i < 26; i++) { @@ -1241,7 +1255,7 @@ it("Buffer.copy", () => { buf.copy(buf, 0, 4, 10); expect(buf.toString()).toBe("efghijghijklmnopqrstuvwxyz"); - } + }); }); export function fillRepeating(dstBuffer, start, end) { diff --git a/test/js/node/child_process/child_process-node.test.js b/test/js/node/child_process/child_process-node.test.js index 25c7967363790d..18fd88687bc698 100644 --- a/test/js/node/child_process/child_process-node.test.js +++ b/test/js/node/child_process/child_process-node.test.js @@ -1,7 +1,8 @@ -import { ChildProcess, spawn, exec } from "node:child_process"; +import { ChildProcess, spawn, exec, fork } from "node:child_process"; import { createTest } from "node-harness"; import { tmpdir } from "node:os"; -import { bunExe } from "harness"; +import path from "node:path"; +import { bunEnv, bunExe } from "harness"; const { beforeAll, describe, expect, it, throws, assert, createCallCheckCtx, createDoneDotAll } = createTest( import.meta.path, ); @@ -12,6 +13,14 @@ const platformTmpDir = require("fs").realpathSync(tmpdir()); const TYPE_ERR_NAME = "TypeError"; +const fixturesDir = path.join(__dirname, "fixtures"); + +const fixtures = { + path(...args) { + return path.join(fixturesDir, ...args); + }, +}; + // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -377,7 +386,7 @@ describe("child_process default options", () => { }); describe("child_process double pipe", () => { - it.todo("should allow two pipes to be used at once", done => { + it.skip("should allow two pipes to be used at once", done => { // const { mustCallAtLeast, mustCall } = createCallCheckCtx(done); const mustCallAtLeast = fn => fn; const mustCall = fn => fn; @@ -483,3 +492,268 @@ describe("child_process double pipe", () => { ); }); }); + +describe("fork", () => { + const expectedEnv = { foo: "bar" }; + describe("abort-signal", () => { + it("Test aborting a forked child_process after calling fork", done => { + const { mustCall } = createCallCheckCtx(done); + const ac = new AbortController(); + const { signal } = ac; + const cp = fork(fixtures.path("child-process-stay-alive-forever.js", { env: bunEnv }), { + signal, + env: bunEnv, + }); + cp.on( + "exit", + mustCall((code, killSignal) => { + strictEqual(code, null); + strictEqual(killSignal, "SIGTERM"); + }), + ); + cp.on( + "error", + mustCall(err => { + strictEqual(err.name, "AbortError"); + }), + ); + process.nextTick(() => ac.abort()); + }); + it("Test aborting with custom error", done => { + const { mustCall } = createCallCheckCtx(done); + const ac = new AbortController(); + const { signal } = ac; + const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), { + signal, + env: bunEnv, + }); + cp.on( + "exit", + mustCall((code, killSignal) => { + strictEqual(code, null); + strictEqual(killSignal, "SIGTERM"); + }), + ); + cp.on( + "error", + mustCall(err => { + strictEqual(err.name, "AbortError"); + strictEqual(err.cause.name, "Error"); + strictEqual(err.cause.message, "boom"); + }), + ); + process.nextTick(() => ac.abort(new Error("boom"))); + }); + it("Test passing an already aborted signal to a forked child_process", done => { + const { mustCall } = createCallCheckCtx(done); + const signal = AbortSignal.abort(); + const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), { + signal, + env: bunEnv, + }); + cp.on( + "exit", + mustCall((code, killSignal) => { + strictEqual(code, null); + strictEqual(killSignal, "SIGTERM"); + }), + ); + cp.on( + "error", + mustCall(err => { + strictEqual(err.name, "AbortError"); + }), + ); + }); + it("Test passing an aborted signal with custom error to a forked child_process", done => { + const { mustCall } = createCallCheckCtx(done); + const signal = AbortSignal.abort(new Error("boom")); + const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), { + signal, + }); + cp.on( + "exit", + mustCall((code, killSignal) => { + strictEqual(code, null); + strictEqual(killSignal, "SIGTERM"); + }), + ); + cp.on( + "error", + mustCall(err => { + strictEqual(err.name, "AbortError"); + strictEqual(err.cause.name, "Error"); + strictEqual(err.cause.message, "boom"); + }), + ); + }); + it("Test passing a different kill signal", done => { + const { mustCall } = createCallCheckCtx(done); + const signal = AbortSignal.abort(); + const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), { + signal, + killSignal: "SIGKILL", + env: bunEnv, + }); + cp.on( + "exit", + mustCall((code, killSignal) => { + strictEqual(code, null); + strictEqual(killSignal, "SIGKILL"); + }), + ); + cp.on( + "error", + mustCall(err => { + strictEqual(err.name, "AbortError"); + }), + ); + }); + // This event doesn't run + it.todo("Test aborting a cp before close but after exit", done => { + const { mustCall, mustNotCall } = createCallCheckCtx(done); + const ac = new AbortController(); + const { signal } = ac; + const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), { + signal, + env: bunEnv, + }); + cp.on( + "exit", + mustCall(() => { + ac.abort(); + }), + ); + cp.on("error", mustNotCall()); + + setTimeout(() => cp.kill(), 1); + }); + }); + describe("args", () => { + it("Ensure that first argument `modulePath` must be provided and be of type string", () => { + const invalidModulePath = [0, true, undefined, null, [], {}, () => {}, Symbol("t")]; + invalidModulePath.forEach(modulePath => { + expect(() => fork(modulePath, { env: bunEnv })).toThrow({ + code: "ERR_INVALID_ARG_TYPE", + name: "TypeError", + message: `The "modulePath" argument must be of type string,Buffer,URL. Received ${modulePath?.toString()}`, + }); + }); + }); + it.todo( + "Ensure that the second argument of `fork` and `fork` should parse options correctly if args is undefined or null", + done => { + const invalidSecondArgs = [0, true, () => {}, Symbol("t")]; + invalidSecondArgs.forEach(arg => { + expect(() => fork(fixtures.path("child-process-echo-options.js"), arg)).toThrow({ + code: "ERR_INVALID_ARG_TYPE", + name: "TypeError", + message: `The \"args\" argument must be of type Array. Received ${arg?.toString()}`, + }); + }); + + const argsLists = [undefined, null, []]; + + const { mustCall } = createCallCheckCtx(done); + + argsLists.forEach(args => { + const cp = fork(fixtures.path("child-process-echo-options.js"), args, { + env: { ...process.env, ...expectedEnv, ...bunEnv }, + }); + + // TODO - bun has no `send` method in the process + // cp.on( + // 'message', + // common.mustCall(({ env }) => { + // assert.strictEqual(env.foo, expectedEnv.foo); + // }) + // ); + + cp.on( + "exit", + mustCall(code => { + assert.strictEqual(code, 0); + }), + ); + }); + }, + ); + it("Ensure that the third argument should be type of object if provided", () => { + const invalidThirdArgs = [0, true, () => {}, Symbol("t")]; + invalidThirdArgs.forEach(arg => { + expect(() => { + fork(fixtures.path("child-process-echo-options.js"), [], arg); + }).toThrow({ + code: "ERR_INVALID_ARG_TYPE", + name: "TypeError", + message: `The \"options\" argument must be of type object. Received ${arg?.toString()}`, + }); + }); + }); + }); + describe.todo("close", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-close.js + }); + describe.todo("detached", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-detached.js + }); + describe.todo("dgram", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-dgram.js + }); + describe.todo("net", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-net.js + }); + describe.todo("net-server", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-net-server.js + }); + describe.todo("net-socket", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-net-socket.js + }); + describe.todo("no-shell", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-no-shell.js + }); + describe.todo("ref", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-ref.js + }); + describe.todo("stdio", () => { + // https://github.com/nodejs/node/blob/v20.5.0/test/parallel/test-child-process-fork-stdio.js + }); + describe("fork", () => { + it.todo("message", () => { + // TODO - bun has no `send` method in the process + const { mustCall } = createCallCheckCtx(done); + const args = ["foo", "bar"]; + const n = fork(fixtures.path("child-process-spawn-node.js"), args); + assert.strictEqual(n.channel, n._channel); + assert.deepStrictEqual(args, ["foo", "bar"]); + n.on("message", m => { + debug("PARENT got message:", m); + assert.ok(m.foo); + }); + expect(() => n.send(undefined)).toThrow({ + name: "TypeError", + message: 'The "message" argument must be specified', + code: "ERR_MISSING_ARGS", + }); + expect(() => n.send()).toThrow({ + name: "TypeError", + message: 'The "message" argument must be specified', + code: "ERR_MISSING_ARGS", + }); + expect(() => n.send(Symbol())).toThrow({ + name: "TypeError", + message: + 'The "message" argument must be one of type string,' + + " object, number, or boolean. Received type symbol (Symbol())", + code: "ERR_INVALID_ARG_TYPE", + }); + n.send({ hello: "world" }); + n.on( + "exit", + mustCall(c => { + assert.strictEqual(c, 0); + }), + ); + }); + }); +}); diff --git a/test/js/node/child_process/child_process.test.ts b/test/js/node/child_process/child_process.test.ts index d6fe065cac8ca8..24b3b5e484be97 100644 --- a/test/js/node/child_process/child_process.test.ts +++ b/test/js/node/child_process/child_process.test.ts @@ -241,18 +241,6 @@ describe("exec()", () => { }); }); -describe("fork()", () => { - it("should throw an error when used", () => { - let err; - try { - fork("index.js"); - } catch (e) { - err = e; - } - expect(err instanceof Error).toBe(true); - }); -}); - describe("spawnSync()", () => { it("should spawn a process synchronously", () => { const { stdout } = spawnSync("echo", ["hello"], { encoding: "utf8" }); diff --git a/test/js/node/child_process/fixtures/child-process-echo-options.js b/test/js/node/child_process/fixtures/child-process-echo-options.js new file mode 100644 index 00000000000000..7d6298bd02905b --- /dev/null +++ b/test/js/node/child_process/fixtures/child-process-echo-options.js @@ -0,0 +1,2 @@ +// TODO - bun has no `send` method in the process +process?.send({ env: process.env }); diff --git a/test/js/node/child_process/fixtures/child-process-spawn-node.js b/test/js/node/child_process/fixtures/child-process-spawn-node.js new file mode 100644 index 00000000000000..a462c106e63c02 --- /dev/null +++ b/test/js/node/child_process/fixtures/child-process-spawn-node.js @@ -0,0 +1,11 @@ +const assert = require("assert"); +const debug = require("util").debuglog("test"); + +function onmessage(m) { + debug("CHILD got message:", m); + assert.ok(m.hello); + process.removeListener("message", onmessage); +} + +process.on("message", onmessage); +process?.send({ foo: "bar" }); diff --git a/test/js/node/child_process/fixtures/child-process-stay-alive-forever.js b/test/js/node/child_process/fixtures/child-process-stay-alive-forever.js new file mode 100644 index 00000000000000..d912ca3a3f128f --- /dev/null +++ b/test/js/node/child_process/fixtures/child-process-stay-alive-forever.js @@ -0,0 +1,3 @@ +setInterval(() => { + // Starting an interval to stay alive. +}, 1000); diff --git a/test/js/node/diagnostics_channel/diagnostics_channel.test.ts b/test/js/node/diagnostics_channel/diagnostics_channel.test.ts new file mode 100644 index 00000000000000..d7fd10eefaeefd --- /dev/null +++ b/test/js/node/diagnostics_channel/diagnostics_channel.test.ts @@ -0,0 +1,371 @@ +import { gc } from "bun"; +import { describe, test, expect, mock, beforeEach } from "bun:test"; +import { channel, Channel, hasSubscribers, subscribe, unsubscribe } from "node:diagnostics_channel"; +import { AsyncLocalStorage } from "node:async_hooks"; + +describe("Channel", () => { + // test-diagnostics-channel-has-subscribers.js + test("can have subscribers", () => { + const name = "channel1"; + const dc = channel(name); + expect(hasSubscribers(name)).toBeFalse(); + + dc.subscribe(() => {}); + expect(hasSubscribers(name)).toBeTrue(); + + checkCalls(); + }); + + // test-diagnostics-channel-symbol-named.js + test("can have symbol as name", () => { + const input = { + foo: "bar", + }; + + const symbol = Symbol("channel2"); + + // Individual channel objects can be created to avoid future lookups + const dc = channel(symbol); + + // Expect two successful publishes later + dc.subscribe( + mustCall((message, name) => { + expect(name).toBe(symbol); + expect(message).toStrictEqual(input); + }), + ); + + dc.publish(input); + + expect(() => { + // @ts-expect-error + channel(null); + }).toThrow(/channel argument must be of type/); + + checkCalls(); + }); + + // test-diagnostics-channel-sync-unsubscribe.js + test("does not throw when unsubscribed", () => { + const name = "channel3"; + const data = "some message"; + + const onMessageHandler: any = mustCall(() => unsubscribe(name, onMessageHandler)); + + subscribe(name, onMessageHandler); + + // This must not throw. + channel(name).publish(data); + + checkCalls(); + }); + + // test-diagnostics-channel-pub-sub.js + test("can publish and subscribe", () => { + const name = "channel4"; + const input = { + foo: "bar", + }; + + // Individual channel objects can be created to avoid future lookups + const dc = channel(name); + expect(dc).toBeInstanceOf(Channel); + + // No subscribers yet, should not publish + expect(dc.hasSubscribers).toBeFalse(); + + const subscriber = mustCall((message, name) => { + expect(name).toBe(dc.name); + expect(message).toStrictEqual(input); + }); + + // Now there's a subscriber, should publish + subscribe(name, subscriber); + expect(dc.hasSubscribers).toBeTrue(); + + // The ActiveChannel prototype swap should not fail instanceof + expect(dc).toBeInstanceOf(Channel); + + // Should trigger the subscriber once + dc.publish(input); + + // Should not publish after subscriber is unsubscribed + expect(unsubscribe(name, subscriber)).toBeTrue(); + expect(dc.hasSubscribers).toBeFalse(); + + // unsubscribe() should return false when subscriber is not found + expect(unsubscribe(name, subscriber)).toBeFalse(); + + expect(() => { + // @ts-expect-error + subscribe(name, null); + }).toThrow(/subscription argument must be of type/); + + // Reaching zero subscribers should not delete from the channels map as there + // will be no more weakref to incRef if another subscribe happens while the + // channel object itself exists. + dc.subscribe(subscriber); + dc.unsubscribe(subscriber); + dc.subscribe(subscriber); + + checkCalls(); + }); + + // test-diagnostics-channel-object-channel-pub-sub.js + test("can publish and subscribe using object", () => { + const name = "channel5"; + const input = { + foo: "bar", + }; + + // Should not have named channel + expect(hasSubscribers(name)).toBeFalse(); + + // Individual channel objects can be created to avoid future lookups + const dc = channel(name); + expect(dc).toBeInstanceOf(Channel); + expect(channel(name)).toBe(dc); // intentional object equality check + + // No subscribers yet, should not publish + expect(dc.hasSubscribers).toBeFalse(); + + const subscriber = mustCall((message, name) => { + expect(name).toBe(dc.name); + expect(message).toStrictEqual(input); + }); + + // Now there's a subscriber, should publish + dc.subscribe(subscriber); + expect(dc.hasSubscribers).toBeTrue(); + + // The ActiveChannel prototype swap should not fail instanceof + expect(dc).toBeInstanceOf(Channel); + + // Should trigger the subscriber once + dc.publish(input); + + // Should not publish after subscriber is unsubscribed + expect(dc.unsubscribe(subscriber)).toBeTrue(); + expect(dc.hasSubscribers).toBeFalse(); + + // unsubscribe() should return false when subscriber is not found + expect(dc.unsubscribe(subscriber)).toBeFalse(); + + expect(() => { + // @ts-expect-error + subscribe(null); + }).toThrow(/channel argument must be of type/); + + checkCalls(); + }); + + // test-diagnostics-channel-safe-subscriber-errors.js + // TODO: Needs support for 'uncaughtException' event + test.todo("can handle subscriber errors", () => { + const input = { + foo: "bar", + }; + const dc = channel("channel6"); + const error = new Error("This error should have been caught!"); + + process.on( + "uncaughtException", + mustCall(err => { + expect(err).toStrictEqual(error); + }), + ); + + dc.subscribe( + mustCall(() => { + throw error; + }), + ); + + // The failing subscriber should not stop subsequent subscribers from running + dc.subscribe(mustCall(() => {})); + + // Publish should continue without throwing + const fn = mustCall(() => {}); + dc.publish(input); + fn(); + + checkCalls(); + }); + + // test-diagnostics-channel-bind-store.js + // TODO: Needs support for 'uncaughtException' event + test.todo("can use bind store", () => { + let n = 0; + const name = "channel7"; + const thisArg = new Date(); + const inputs = [{ foo: "bar" }, { baz: "buz" }]; + + const dc = channel(name); + + // Bind a storage directly to published data + const store1 = new AsyncLocalStorage(); + dc.bindStore(store1); + let store1bound = true; + + // Bind a store with transformation of published data + const store2 = new AsyncLocalStorage(); + dc.bindStore( + store2, + mustCall(data => { + expect(data).toStrictEqual(inputs[n]); + return { data }; + }, 4), + ); + + // Regular subscribers should see publishes from runStores calls + dc.subscribe( + mustCall(data => { + if (store1bound) { + expect(data).toStrictEqual(store1.getStore()); + } + expect({ data }).toStrictEqual(store2.getStore()); + expect(data).toStrictEqual(inputs[n]); + }, 4), + ); + + // Verify stores are empty before run + expect(store1.getStore()).toBeUndefined(); + expect(store2.getStore()).toBeUndefined(); + + dc.runStores( + inputs[n], + mustCall(function (a, b) { + // Verify this and argument forwarding + expect(this).toBe(thisArg); + expect(a).toBe(1); + expect(b).toBe(2); + + // Verify store 1 state matches input + expect(store1.getStore()).toStrictEqual(inputs[n]); + + // Verify store 2 state has expected transformation + expect(store2.getStore()).toStrictEqual({ data: inputs[n] }); + + // Should support nested contexts + n++; + dc.runStores( + inputs[n], + mustCall(function () { + // Verify this and argument forwarding + expect(this).toBeUndefined(); + + // Verify store 1 state matches input + expect(store1.getStore()).toStrictEqual(inputs[n]); + + // Verify store 2 state has expected transformation + expect(store2.getStore()).toStrictEqual({ data: inputs[n] }); + }), + ); + n--; + + // Verify store 1 state matches input + expect(store1.getStore()).toStrictEqual(inputs[n]); + + // Verify store 2 state has expected transformation + expect(store2.getStore()).toStrictEqual({ data: inputs[n] }); + }), + thisArg, + 1, + 2, + ); + + // Verify stores are empty after run + expect(store1.getStore()).toBeUndefined(); + expect(store2.getStore()).toBeUndefined(); + + // Verify unbinding works + expect(dc.unbindStore(store1)).toBeTrue(); + store1bound = false; + + // Verify unbinding a store that is not bound returns false + expect(dc.unbindStore(store1)).toBeFalse(); + + n++; + dc.runStores( + inputs[n], + mustCall(() => { + // Verify after unbinding store 1 will remain undefined + expect(store1.getStore()).toBeUndefined(); + + // Verify still bound store 2 receives expected data + expect(store2.getStore()).toStrictEqual({ data: inputs[n] }); + }), + ); + + // Contain transformer errors and emit on next tick + const fail = new Error("fail"); + dc.bindStore(store1, () => { + throw fail; + }); + + let calledRunStores = false; + process.once( + "uncaughtException", + mustCall(err => { + expect(calledRunStores).toBeTrue(); + expect(err).toStrictEqual(fail); + }), + ); + + dc.runStores( + inputs[n], + mustCall(() => {}), + ); + calledRunStores = true; + + checkCalls(); + }); + + // test-diagnostics-channel-memory-leak.js + test("references are not leaked", () => { + function noop() {} + + const heapUsedBefore = process.memoryUsage().heapUsed; + for (let i = 0; i < 1000; i++) { + const name = `channel7-${i}`; + subscribe(name, noop); + unsubscribe(name, noop); + } + + gc(true); + const heapUsedAfter = process.memoryUsage().heapUsed; + + expect(heapUsedBefore).toBeGreaterThanOrEqual(heapUsedAfter); + }); +}); + +describe("TracingChannel", () => { + // Port tests from: + // https://github.com/search?q=repo%3Anodejs%2Fnode+test-diagnostics-channel+AND+%2Ftracing%2F&type=code + test.todo("TODO"); +}); + +const mocks = new Map(); + +function mustCall(fn: (...args: any[]) => T, expected?: number) { + const instance = mock(fn); + mocks.set(instance, expected ?? 1); + return instance; +} + +function mustNotCall(fn: (...args: any[]) => T) { + return mustCall(fn, 0); +} + +// FIXME: remove this and use `afterEach` instead +// Currently, `bun test` disallows `expect()` in `afterEach` +function checkCalls() { + for (const [mock, expected] of mocks.entries()) { + expect(mock).toHaveBeenCalledTimes(expected); + } + mocks.clear(); +} + +beforeEach(() => { + mocks.clear(); +}); diff --git a/test/js/node/disabled-module.test.cjs b/test/js/node/disabled-module.test.cjs deleted file mode 100644 index bc4817b8dae42b..00000000000000 --- a/test/js/node/disabled-module.test.cjs +++ /dev/null @@ -1,6 +0,0 @@ -test("not implemented yet module masquerades as undefined in cjs and throws an error", () => { - const worker_threads = require("worker_threads"); - - expect(typeof worker_threads).toBe("undefined"); - expect(typeof worker_threads.getEnvironmentData).toBe("undefined"); -}); diff --git a/test/js/node/disabled-module.test.js b/test/js/node/disabled-module.test.js deleted file mode 100644 index 7333a0f1f8cbfb..00000000000000 --- a/test/js/node/disabled-module.test.js +++ /dev/null @@ -1,16 +0,0 @@ -import { expect, test } from "bun:test"; -import * as worker_threads from "worker_threads"; -import worker_threads_default from "worker_threads"; - -test("not implemented yet module masquerades as undefined and throws an error", () => { - expect(typeof worker_threads.default).toBe("undefined"); - expect(typeof worker_threads_default).toBe("undefined"); - expect(typeof worker_threads.getEnvironmentData).toBe("undefined"); - expect(typeof worker_threads_default.getEnvironmentData).toBe("undefined"); -}); - -test("esbuild functions with worker_threads stub", async () => { - const esbuild = await import("esbuild"); - const result = await esbuild.transform('console . log( "hello world" )', { minify: true }); - expect(result.code).toBe('console.log("hello world");\n'); -}); diff --git a/test/js/node/dns/node-dns.test.js b/test/js/node/dns/node-dns.test.js index 5de8401469c913..f905a288569c0b 100644 --- a/test/js/node/dns/node-dns.test.js +++ b/test/js/node/dns/node-dns.test.js @@ -1,6 +1,8 @@ import { expect, test } from "bun:test"; import * as dns from "node:dns"; import * as dns_promises from "node:dns/promises"; +import * as fs from "node:fs"; +import * as os from "node:os"; // TODO: test("it exists", () => { @@ -190,3 +192,34 @@ test("dns.lookup (localhost)", done => { done(err); }); }); + +test("dns.getServers", done => { + function parseResolvConf() { + let servers = []; + try { + const content = fs.readFileSync("/etc/resolv.conf", "utf-8"); + const lines = content.split(os.EOL); + + for (const line of lines) { + const parts = line.trim().split(/\s+/); + if (parts.length >= 2 && parts[0] === "nameserver") { + servers.push(parts[1]); + } + } + } catch (err) { + done(err); + } + return servers; + } + + const expectServers = parseResolvConf(); + const actualServers = dns.getServers(); + try { + for (const server of expectServers) { + expect(actualServers).toContain(server); + } + } catch (err) { + return done(err); + } + done(); +}); diff --git a/test/js/node/fs/fs.test.ts b/test/js/node/fs/fs.test.ts index f86c9fdce4d36c..86e64b7132740e 100644 --- a/test/js/node/fs/fs.test.ts +++ b/test/js/node/fs/fs.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "bun:test"; -import { gc } from "harness"; +import { dirname } from "node:path"; +import { bunEnv, bunExe, gc } from "harness"; import fs, { closeSync, existsSync, @@ -31,6 +32,7 @@ import fs, { symlinkSync, writevSync, readvSync, + fstatSync, } from "node:fs"; import _promises from "node:fs/promises"; @@ -40,6 +42,7 @@ import { join } from "node:path"; import { ReadStream as ReadStream_, WriteStream as WriteStream_ } from "./export-from.js"; import { ReadStream as ReadStreamStar_, WriteStream as WriteStreamStar_ } from "./export-star-from.js"; +import { spawnSync } from "bun"; const Buffer = globalThis.Buffer || Uint8Array; @@ -65,6 +68,15 @@ it("writeFileSync in append should not truncate the file", () => { expect(readFileSync(path, "utf8")).toBe(str); }); +it("await readdir #3931", async () => { + const { exitCode } = spawnSync({ + cmd: [bunExe(), join(import.meta.dir, "./repro-3931.js")], + env: bunEnv, + cwd: import.meta.dir, + }); + expect(exitCode).toBe(0); +}); + it("writeFileSync NOT in append SHOULD truncate the file", () => { const path = join(tmpdir(), "writeFileSync-should-not-append-" + (Date.now() * 10000).toString(16)); @@ -159,6 +171,142 @@ it("readdirSync on import.meta.dir", () => { expect(match).toBe(true); }); +it("promises.readdir on a large folder", async () => { + const huge = join(tmpdir(), "huge-folder-" + Math.random().toString(32)); + rmSync(huge, { force: true, recursive: true }); + mkdirSync(huge, { recursive: true }); + for (let i = 0; i < 128; i++) { + writeFileSync(join(huge, "file-" + i), ""); + } + for (let j = 0; j < 4; j++) { + const promises = await Promise.all([ + fs.promises.readdir(huge), + fs.promises.readdir(huge), + fs.promises.readdir(huge), + fs.promises.readdir(huge), + ]); + + for (let chunk of promises) { + expect(chunk).toHaveLength(128); + chunk.sort(); + + let count = 0; + for (let i = 0; i < 128; i++) { + const current = chunk[i]; + if (!current.startsWith("file-")) { + throw new Error("invalid file name"); + } + + const num = parseInt(current.slice(5)); + // @ts-expect-error + count += !!(num >= 0 && num < 128); + } + + expect(count).toBe(128); + } + } + rmSync(huge, { force: true, recursive: true }); +}); + +it("promises.readFile", async () => { + expect(await fs.promises.readFile(import.meta.path, "utf-8")).toEqual(readFileSync(import.meta.path, "utf-8")); + expect(await fs.promises.readFile(import.meta.path, { encoding: "latin1" })).toEqual( + readFileSync(import.meta.path, { encoding: "latin1" }), + ); + + // We do this 20 times to check for any GC issues. + for (let i = 0; i < 20; i++) { + try { + await fs.promises.readFile("/i-dont-exist", "utf-8"); + expect(false).toBeTrue(); + } catch (e: any) { + expect(e).toBeInstanceOf(Error); + expect(e.message).toBe("No such file or directory"); + expect(e.code).toBe("ENOENT"); + expect(e.errno).toBe(-2); + expect(e.path).toBe("/i-dont-exist"); + } + } +}); + +it("promises.readFile - UTF16 file path", async () => { + const dest = `/tmp/superduperduperdupduperdupersuperduperduperduperduperduperdupersuperduperduperduperduperduperdupersuperduperduperdupe-Bun-👍-${Date.now()}-${ + (Math.random() * 1024000) | 0 + }.txt`; + await fs.promises.copyFile(import.meta.path, dest); + const expected = readFileSync(import.meta.path, "utf-8"); + Bun.gc(true); + for (let i = 0; i < 100; i++) { + expect(await fs.promises.readFile(dest, "utf-8")).toEqual(expected); + } + Bun.gc(true); +}); + +it("promises.readFile - atomized file path", async () => { + const destInput = `/tmp/superduperduperdupduperdupersuperduperduperduperduperduperdupersuperduperduperduperduperduperdupersuperduperduperdupe-Bun-👍-${Date.now()}-${ + (Math.random() * 1024000) | 0 + }.txt`; + // Force it to become an atomized string by making it a property access + const dest: string = ( + { + [destInput]: destInput, + boop: 123, + } as const + )[destInput] as string; + await fs.promises.copyFile(import.meta.path, dest); + const expected = readFileSync(import.meta.path, "utf-8"); + Bun.gc(true); + for (let i = 0; i < 100; i++) { + expect(await fs.promises.readFile(dest, "utf-8")).toEqual(expected); + } + Bun.gc(true); +}); + +it("promises.readFile with buffer as file path", async () => { + for (let i = 0; i < 10; i++) + expect(await fs.promises.readFile(Buffer.from(import.meta.path), "utf-8")).toEqual( + readFileSync(import.meta.path, "utf-8"), + ); +}); + +it("promises.readdir on a large folder withFileTypes", async () => { + const huge = join(tmpdir(), "huge-folder-" + Math.random().toString(32)); + rmSync(huge, { force: true, recursive: true }); + mkdirSync(huge, { recursive: true }); + let withFileTypes = { withFileTypes: true } as const; + for (let i = 0; i < 128; i++) { + writeFileSync(join(huge, "file-" + i), ""); + } + for (let j = 0; j < 4; j++) { + const promises = await Promise.all([ + fs.promises.readdir(huge, withFileTypes), + fs.promises.readdir(huge, withFileTypes), + fs.promises.readdir(huge, withFileTypes), + fs.promises.readdir(huge, withFileTypes), + ]); + + for (let chunk of promises) { + expect(chunk).toHaveLength(128); + chunk.sort(); + + let count = 0; + for (let i = 0; i < 128; i++) { + const current = chunk[i].name; + if (!current.startsWith("file-")) { + throw new Error("invalid file name"); + } + + const num = parseInt(current.slice(5)); + // @ts-expect-error + count += !!(num >= 0 && num < 128); + } + + expect(count).toBe(128); + } + } + rmSync(huge, { force: true, recursive: true }); +}); + it("statSync throwIfNoEntry", () => { expect(statSync("/tmp/404/not-found/ok", { throwIfNoEntry: false })).toBeUndefined(); expect(lstatSync("/tmp/404/not-found/ok", { throwIfNoEntry: false })).toBeUndefined(); @@ -171,6 +319,12 @@ it("statSync throwIfNoEntry: true", () => { expect(() => lstatSync("/tmp/404/not-found/ok")).toThrow("No such file or directory"); }); +it("stat == statSync", async () => { + const sync = statSync(import.meta.path); + const async = await promises.stat(import.meta.path); + expect(Object.entries(sync)).toEqual(Object.entries(async)); +}); + // https://github.com/oven-sh/bun/issues/1887 it("mkdtempSync, readdirSync, rmdirSync and unlinkSync with non-ascii", () => { const tempdir = mkdtempSync(`${tmpdir()}/emoji-fruit-🍇 🍈 🍉 🍊 🍋`); @@ -1323,6 +1477,26 @@ describe("fs/promises", () => { }); }); +it("stat on a large file", () => { + var dest: string = "", + fd; + try { + dest = `${tmpdir()}/fs.test.js/${Math.trunc(Math.random() * 10000000000).toString(32)}.stat.txt`; + mkdirSync(dirname(dest), { recursive: true }); + const bigBuffer = new Uint8Array(1024 * 1024 * 1024); + fd = openSync(dest, "w"); + let offset = 0; + while (offset < 5 * 1024 * 1024 * 1024) { + offset += writeSync(fd, bigBuffer, 0, bigBuffer.length, offset); + } + + expect(fstatSync(fd).size).toEqual(offset); + } finally { + if (fd) closeSync(fd); + unlinkSync(dest); + } +}); + it("fs.constants", () => { expect(constants).toBeDefined(); expect(constants.F_OK).toBeDefined(); @@ -1338,12 +1512,12 @@ it("fs.constants", () => { expect(constants.O_TRUNC).toBeDefined(); expect(constants.O_APPEND).toBeDefined(); expect(constants.O_DIRECTORY).toBeDefined(); - expect(constants.O_NOATIME).toBeDefined(); + // expect(constants.O_NOATIME).toBeDefined(); expect(constants.O_NOFOLLOW).toBeDefined(); expect(constants.O_SYNC).toBeDefined(); expect(constants.O_DSYNC).toBeDefined(); - expect(constants.O_SYMLINK).toBeDefined(); - expect(constants.O_DIRECT).toBeDefined(); + if (process.platform === "darwin") expect(constants.O_SYMLINK).toBeDefined(); + // expect(constants.O_DIRECT).toBeDefined(); expect(constants.O_NONBLOCK).toBeDefined(); expect(constants.S_IFMT).toBeDefined(); expect(constants.S_IFREG).toBeDefined(); diff --git a/test/js/node/fs/node-fetch.test.js b/test/js/node/fs/node-fetch.test.js index 33af3252dc9347..c174917a7f55bb 100644 --- a/test/js/node/fs/node-fetch.test.js +++ b/test/js/node/fs/node-fetch.test.js @@ -1,4 +1,6 @@ import fetch2, { fetch, Response, Request, Headers } from "node-fetch"; +import * as iso from "isomorphic-fetch"; +import * as vercelFetch from "@vercel/fetch"; import { test, expect } from "bun:test"; @@ -8,26 +10,24 @@ test("node-fetch", () => { expect(Headers).toBe(globalThis.Headers); }); -test("node-fetch fetches", async () => { - const server = Bun.serve({ - port: 0, - fetch(req, server) { - server.stop(); - return new Response(); - }, +for (const [impl, name] of [ + [fetch, "node-fetch.fetch"], + [fetch2, "node-fetch.default"], + [fetch2.default, "node-fetch.default.default"], + [iso.fetch, "isomorphic-fetch.fetch"], + [iso.default.fetch, "isomorphic-fetch.default.fetch"], + [iso.default, "isomorphic-fetch.default"], + [vercelFetch.default(fetch), "@vercel/fetch.default"], +]) { + test(name + " fetches", async () => { + const server = Bun.serve({ + port: 0, + fetch(req, server) { + server.stop(); + return new Response(); + }, + }); + expect(await impl("http://" + server.hostname + ":" + server.port)).toBeInstanceOf(Response); + server.stop(true); }); - expect(await fetch("http://" + server.hostname + ":" + server.port)).toBeInstanceOf(Response); - server.stop(true); -}); - -test("node-fetch.default fetches", async () => { - const server = Bun.serve({ - port: 0, - fetch(req, server) { - server.stop(); - return new Response(); - }, - }); - expect(await fetch2("http://" + server.hostname + ":" + server.port)).toBeInstanceOf(Response); - server.stop(true); -}); +} diff --git a/test/js/node/fs/repro-3931.js b/test/js/node/fs/repro-3931.js new file mode 100644 index 00000000000000..b6651127d5fc0a --- /dev/null +++ b/test/js/node/fs/repro-3931.js @@ -0,0 +1,4 @@ +import { readdir } from "fs/promises"; + +const files = await readdir(`/tmp`, {}); +console.log(files.map(a => a)); diff --git a/test/js/node/harness.ts b/test/js/node/harness.ts index 9cea1b7814a2c0..fcc74364b35d9c 100644 --- a/test/js/node/harness.ts +++ b/test/js/node/harness.ts @@ -109,6 +109,7 @@ export function createTest(path: string) { function mustNotCall(reason: string = "function should not have been called", optionalCb?: (err?: any) => void) { const localDone = createDone(); timers.push(setTimeout(() => localDone(), 200)); + return () => { closeTimers(); if (optionalCb) optionalCb.apply(undefined, reason ? [reason] : []); diff --git a/test/js/node/http/node-http.test.ts b/test/js/node/http/node-http.test.ts index 0e7b3ca13a1e49..e8fe4dae85def4 100644 --- a/test/js/node/http/node-http.test.ts +++ b/test/js/node/http/node-http.test.ts @@ -169,6 +169,18 @@ describe("node:http", () => { res.end("Hello World"); return; } + if (reqUrl.pathname === "/uploadFile") { + let requestData = Buffer.alloc(0); + req.on("data", chunk => { + requestData = Buffer.concat([requestData, chunk]); + }); + req.on("end", () => { + res.writeHead(200, { "Content-Type": "text/plain" }); + res.write(requestData); + res.end(); + }); + return; + } } res.writeHead(200, { "Content-Type": "text/plain" }); @@ -540,6 +552,49 @@ describe("node:http", () => { req.end(); }); }); + it("uploading file by 'formdata/multipart', issue#3116", done => { + runTest(done, (server, serverPort, done) => { + const boundary = "----FormBoundary" + Date.now(); + + const formDataBegin = `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="myfile.txt"\r\nContent-Type: application/octet-stream\r\n\r\n`; + const fileData = Buffer.from("80818283", "hex"); + const formDataEnd = `\r\n--${boundary}--`; + + const requestOptions = { + hostname: "localhost", + port: serverPort, + path: "/uploadFile", + method: "POST", + headers: { + "Content-Type": `multipart/form-data; boundary=${boundary}`, + }, + }; + + const req = request(requestOptions, res => { + let responseData = Buffer.alloc(0); + res.on("data", chunk => { + responseData = Buffer.concat([responseData, chunk]); + }); + res.on("end", () => { + try { + expect(responseData).toEqual( + Buffer.concat([Buffer.from(formDataBegin), fileData, Buffer.from(formDataEnd)]), + ); + } catch (e) { + return done(e); + } + done(); + }); + }); + req.on("error", err => { + done(err); + }); + req.write(formDataBegin); // string + req.write(fileData); // Buffer + req.write(formDataEnd); // string + req.end(); + }); + }); }); describe("signal", () => { diff --git a/test/js/node/missing-module.test.js b/test/js/node/missing-module.test.js new file mode 100644 index 00000000000000..fd772441a8a657 --- /dev/null +++ b/test/js/node/missing-module.test.js @@ -0,0 +1,7 @@ +import { expect, test } from "bun:test"; + +test("not implemented yet module masquerades as undefined and throws an error", () => { + const missingModule = "node:missing" + ""; + expect(() => require(missingModule)).toThrow(/^Cannot find package "node:missing" from "/); + expect(() => import(missingModule)).toThrow(/^Cannot find package "node:missing" from "/); +}); diff --git a/test/js/node/module/node-module-module.test.js b/test/js/node/module/node-module-module.test.js index fdde93d0e01816..08955a7b7cb23f 100644 --- a/test/js/node/module/node-module-module.test.js +++ b/test/js/node/module/node-module-module.test.js @@ -1,10 +1,10 @@ import { expect, test } from "bun:test"; -import { _nodeModulePaths, builtinModules, isBuiltin } from "module"; +import { _nodeModulePaths, builtinModules, isBuiltin, wrap } from "module"; import Module from "module"; test("builtinModules exists", () => { expect(Array.isArray(builtinModules)).toBe(true); - expect(builtinModules).toHaveLength(77); + expect(builtinModules).toHaveLength(76); }); test("isBuiltin() works", () => { @@ -26,6 +26,13 @@ test("Module exists", () => { expect(Module).toBeDefined(); }); +test("module.Module works", () => { + expect(Module.Module === Module).toBeTrue(); + + const m = new Module("asdf"); + expect(m.exports).toEqual({}); +}); + test("_nodeModulePaths() works", () => { expect(() => { _nodeModulePaths(); @@ -43,3 +50,10 @@ test("_nodeModulePaths() works", () => { ]); expect(_nodeModulePaths("/a/b/../d")).toEqual(["/a/d/node_modules", "/a/node_modules", "/node_modules"]); }); + +test("Module.wrap", () => { + var mod = { exports: {} }; + expect(eval(wrap("exports.foo = 1; return 42"))(mod.exports, mod)).toBe(42); + expect(mod.exports.foo).toBe(1); + expect(wrap()).toBe("(function (exports, require, module, __filename, __dirname) { undefined\n});"); +}); diff --git a/test/js/node/path/path.test.js b/test/js/node/path/path.test.js index 8f32bdb2cfdd49..3c8a04d7247790 100644 --- a/test/js/node/path/path.test.js +++ b/test/js/node/path/path.test.js @@ -15,10 +15,6 @@ const expectStrictEqual = (actual, expected) => { }; hideFromStackTrace(expectStrictEqual); -it("should not inherit Object.prototype", () => { - expect(path).not.toHaveProperty("toString"); -}); - describe("dirname", () => { it("path.dirname", () => { const fixtures = [ @@ -473,6 +469,14 @@ it("path.relative", () => { ["/baz", "/baz-quux", "../baz-quux"], ["/page1/page2/foo", "/", "../../.."], [process.cwd(), "foo", "foo"], + ["/webpack", "/webpack", ""], + ["/webpack/", "/webpack", ""], + ["/webpack", "/webpack/", ""], + ["/webpack/", "/webpack/", ""], + ["/webpack-hot-middleware", "/webpack/buildin/module.js", "../webpack/buildin/module.js"], + ["/webp4ck-hot-middleware", "/webpack/buildin/module.js", "../webpack/buildin/module.js"], + ["/webpack-hot-middleware", "/webp4ck/buildin/module.js", "../webp4ck/buildin/module.js"], + ["/var/webpack-hot-middleware", "/var/webpack/buildin/module.js", "../webpack/buildin/module.js"], ], ], ]; @@ -543,7 +547,6 @@ it("path.normalize", () => { // "..\\..\\..\\..\\baz" // ); // strictEqual(path.win32.normalize("foo/bar\\baz"), "foo\\bar\\baz"); - strictEqual(path.posix.normalize("./fixtures///b/../b/c.js"), "fixtures/b/c.js"); strictEqual(path.posix.normalize("/foo/../../../bar"), "/bar"); strictEqual(path.posix.normalize("a//b//../b"), "a/b"); @@ -563,6 +566,7 @@ it("path.normalize", () => { strictEqual(path.posix.normalize("../foobar/barfoo/foo/../../../bar/../../"), "../../"); strictEqual(path.posix.normalize("../.../../foobar/../../../bar/../../baz"), "../../../../baz"); strictEqual(path.posix.normalize("foo/bar\\baz"), "foo/bar\\baz"); + strictEqual(path.posix.normalize(""), "."); }); it("path.resolve", () => { @@ -623,76 +627,212 @@ it("path.resolve", () => { strictEqual(failures.length, 0, failures.join("\n")); }); -it("path.parse", () => { - expect(path.parse("/tmp")).toStrictEqual({ root: "/", dir: "/", base: "tmp", ext: "", name: "tmp" }); - - expect(path.parse("/tmp/test.txt")).toStrictEqual({ - root: "/", - dir: "/tmp", - base: "test.txt", - ext: ".txt", - name: "test", - }); - - expect(path.parse("/tmp/test/file.txt")).toStrictEqual({ - root: "/", - dir: "/tmp/test", - base: "file.txt", - ext: ".txt", - name: "file", - }); - - expect(path.parse("/tmp/test/dir")).toStrictEqual({ root: "/", dir: "/tmp/test", base: "dir", ext: "", name: "dir" }); - expect(path.parse("/tmp/test/dir/")).toStrictEqual({ - root: "/", - dir: "/tmp/test", - base: "dir", - ext: "", - name: "dir", - }); - - expect(path.parse(".")).toStrictEqual({ root: "", dir: "", base: ".", ext: "", name: "." }); - expect(path.parse("./")).toStrictEqual({ root: "", dir: "", base: ".", ext: "", name: "." }); - expect(path.parse("/.")).toStrictEqual({ root: "/", dir: "/", base: ".", ext: "", name: "." }); - expect(path.parse("/../")).toStrictEqual({ root: "/", dir: "/", base: "..", ext: ".", name: "." }); - - expect(path.parse("./file.txt")).toStrictEqual({ root: "", dir: ".", base: "file.txt", ext: ".txt", name: "file" }); - expect(path.parse("../file.txt")).toStrictEqual({ root: "", dir: "..", base: "file.txt", ext: ".txt", name: "file" }); - expect(path.parse("../test/file.txt")).toStrictEqual({ - root: "", - dir: "../test", - base: "file.txt", - ext: ".txt", - name: "file", - }); - expect(path.parse("test/file.txt")).toStrictEqual({ - root: "", - dir: "test", - base: "file.txt", - ext: ".txt", - name: "file", - }); +describe("path.parse and path.format", () => { + const testCases = [ + { + input: "/tmp/test.txt", + expected: { + root: "/", + dir: "/tmp", + base: "test.txt", + ext: ".txt", + name: "test", + }, + }, + { + input: "/tmp/test/file.txt", + expected: { + root: "/", + dir: "/tmp/test", + base: "file.txt", + ext: ".txt", + name: "file", + }, + }, + { + input: "/tmp/test/dir", + expected: { + root: "/", + dir: "/tmp/test", + base: "dir", + ext: "", + name: "dir", + }, + }, + { + input: "/tmp/test/dir/", + expected: { + root: "/", + dir: "/tmp/test", + base: "dir", + ext: "", + name: "dir", + }, + }, + { + input: ".", + expected: { + root: "", + dir: "", + base: ".", + ext: "", + name: ".", + }, + }, + { + input: "./", + expected: { + root: "", + dir: "", + base: ".", + ext: "", + name: ".", + }, + }, + { + input: "/.", + expected: { + root: "/", + dir: "/", + base: ".", + ext: "", + name: ".", + }, + }, + { + input: "/../", + expected: { + root: "/", + dir: "/", + base: "..", + ext: ".", + name: ".", + }, + }, + { + input: "./file.txt", + expected: { + root: "", + dir: ".", + base: "file.txt", + ext: ".txt", + name: "file", + }, + }, + { + input: "../file.txt", + expected: { + root: "", + dir: "..", + base: "file.txt", + ext: ".txt", + name: "file", + }, + }, + { + input: "../test/file.txt", + expected: { + root: "", + dir: "../test", + base: "file.txt", + ext: ".txt", + name: "file", + }, + }, + { + input: "test/file.txt", + expected: { + root: "", + dir: "test", + base: "file.txt", + ext: ".txt", + name: "file", + }, + }, + { + input: "test/dir", + expected: { + root: "", + dir: "test", + base: "dir", + ext: "", + name: "dir", + }, + }, + { + input: "test/dir/another_dir", + expected: { + root: "", + dir: "test/dir", + base: "another_dir", + ext: "", + name: "another_dir", + }, + }, + { + input: "./dir", + expected: { + root: "", + dir: ".", + base: "dir", + ext: "", + name: "dir", + }, + }, + { + input: "../dir", + expected: { + root: "", + dir: "..", + base: "dir", + ext: "", + name: "dir", + }, + }, + { + input: "../dir/another_dir", + expected: { + root: "", + dir: "../dir", + base: "another_dir", + ext: "", + name: "another_dir", + }, + }, + ]; + testCases.forEach(({ input, expected }) => { + it(`case ${input}`, () => { + const parsed = path.parse(input); + expect(parsed).toStrictEqual(expected); - expect(path.parse("test/dir")).toStrictEqual({ root: "", dir: "test", base: "dir", ext: "", name: "dir" }); - expect(path.parse("test/dir/another_dir")).toStrictEqual({ - root: "", - dir: "test/dir", - base: "another_dir", - ext: "", - name: "another_dir", + const formatted = path.format(parsed); + expect(formatted).toStrictEqual(input.slice(-1) === "/" ? input.slice(0, -1) : input); + }); }); - - expect(path.parse("./dir")).toStrictEqual({ root: "", dir: ".", base: "dir", ext: "", name: "dir" }); - expect(path.parse("../dir")).toStrictEqual({ root: "", dir: "..", base: "dir", ext: "", name: "dir" }); - expect(path.parse("../dir/another_dir")).toStrictEqual({ - root: "", - dir: "../dir", - base: "another_dir", - ext: "", - name: "another_dir", + it("empty string arguments, issue #4005", () => { + expect( + path.format({ + root: "", + dir: "", + base: "", + name: "foo", + ext: ".ts", + }), + ).toStrictEqual("foo.ts"); + expect( + path.format({ + name: "foo", + ext: ".ts", + }), + ).toStrictEqual("foo.ts"); }); }); test("path.format works for vite's example", () => { expect(path.format({ root: "", dir: "", name: "index", base: undefined, ext: ".css" })).toBe("index.css"); }); + +it("path.extname", () => { + expect(path.extname("index.js")).toBe(".js"); + expect(path.extname("make_plot.🔥")).toBe(".🔥"); +}); diff --git a/test/js/node/process/process.test.js b/test/js/node/process/process.test.js index 908485422a9e6d..04b823825ad551 100644 --- a/test/js/node/process/process.test.js +++ b/test/js/node/process/process.test.js @@ -66,7 +66,7 @@ it("process.hrtime.bigint()", () => { }); it("process.release", () => { - expect(process.release.name).toBe("bun"); + expect(process.release.name).toBe("node"); expect(process.release.sourceUrl).toContain( `https://github.com/oven-sh/bun/release/bun-v${process.versions.bun}/bun-${process.platform}-${ { arm64: "aarch64", x64: "x64" }[process.arch] || process.arch diff --git a/test/js/node/stream/node-stream.test.js b/test/js/node/stream/node-stream.test.js index 6bff28b94d2b4e..5f5b9d67a8d3e8 100644 --- a/test/js/node/stream/node-stream.test.js +++ b/test/js/node/stream/node-stream.test.js @@ -1,5 +1,8 @@ import { expect, describe, it } from "bun:test"; import { Readable, Writable, Duplex, Transform, PassThrough } from "node:stream"; +import { createReadStream } from "node:fs"; +import { tmpdir } from "node:os"; +import { writeFileSync } from "node:fs"; describe("Readable", () => { it("should be able to be created without _construct method defined", done => { @@ -38,6 +41,111 @@ describe("Readable", () => { readable.pipe(writable); }); + it("should be able to be piped via .pipe, issue #3607", done => { + const path = `${tmpdir()}/${Date.now()}.testReadStreamEmptyFile.txt`; + writeFileSync(path, ""); + const stream = createReadStream(path); + stream.on("error", err => { + done(err); + }); + + let called = false; + const writable = new Writable({ + write(chunk, encoding, callback) { + called = true; + callback(); + }, + }); + writable.on("finish", () => { + try { + expect(called).toBeFalse(); + } catch (err) { + return done(err); + } + done(); + }); + + stream.pipe(writable); + }); + it("should be able to be piped via .pipe, issue #3668", done => { + const path = `${tmpdir()}/${Date.now()}.testReadStream.txt`; + writeFileSync(path, "12345"); + const stream = createReadStream(path, { start: 0, end: 4 }); + + const writable = new Writable({ + write(chunk, encoding, callback) { + try { + expect(chunk.toString()).toBe("12345"); + } catch (err) { + done(err); + return; + } + callback(); + done(); + }, + }); + + stream.on("error", err => { + done(err); + }); + + stream.pipe(writable); + }); + it("should be able to be piped via .pipe, both start and end are 0", done => { + const path = `${tmpdir()}/${Date.now()}.testReadStream2.txt`; + writeFileSync(path, "12345"); + const stream = createReadStream(path, { start: 0, end: 0 }); + + const writable = new Writable({ + write(chunk, encoding, callback) { + try { + // Both start and end are inclusive and start counting at 0. + expect(chunk.toString()).toBe("1"); + } catch (err) { + done(err); + return; + } + callback(); + done(); + }, + }); + + stream.on("error", err => { + done(err); + }); + + stream.pipe(writable); + }); + it("should be able to be piped via .pipe with a large file", done => { + const length = 128 * 1024; + const data = "B".repeat(length); + const path = `${tmpdir()}/${Date.now()}.testReadStreamLargeFile.txt`; + writeFileSync(path, data); + const stream = createReadStream(path, { start: 0, end: length - 1 }); + + let res = ""; + let count = 0; + const writable = new Writable({ + write(chunk, encoding, callback) { + count += 1; + res += chunk; + callback(); + }, + }); + writable.on("finish", () => { + try { + expect(res).toEqual(data); + expect(count).toBeGreaterThan(1); + } catch (err) { + return done(err); + } + done(); + }); + stream.on("error", err => { + done(err); + }); + stream.pipe(writable); + }); }); describe("Duplex", () => { diff --git a/test/js/node/stubs.test.js b/test/js/node/stubs.test.js index 1025907abb8bf0..11d8edbd90e8ae 100644 --- a/test/js/node/stubs.test.js +++ b/test/js/node/stubs.test.js @@ -88,17 +88,6 @@ for (let specifier of specifiers) { const mod = await import(specifier); if ("default" in mod) { expect(mod).toHaveProperty("default"); - const cjs = mod.default[Symbol.for("CommonJS")]; - if (typeof cjs !== "undefined") { - if (cjs === 1) { - expect(typeof mod.default).toBe("function"); - } else if (cjs === true) { - expect(cjs).toBe(true); - if (typeof mod.default !== "undefined") { - expect(typeof mod.default).toBe("function"); - } - } - } } else { // TODO: uncomment this after node:module can be default imported // throw new Error(`Module ${specifier} has no default export`); diff --git a/test/js/node/tls/node-tls-connect.test.ts b/test/js/node/tls/node-tls-connect.test.ts index 79aac78be9590a..326b70c94e50c2 100644 --- a/test/js/node/tls/node-tls-connect.test.ts +++ b/test/js/node/tls/node-tls-connect.test.ts @@ -1,4 +1,5 @@ -import tls, { TLSSocket, connect, checkServerIdentity } from "tls"; +import tls, { TLSSocket, connect, checkServerIdentity, createServer, Server } from "tls"; +import { AddressInfo } from "ws"; it("should work with alpnProtocols", done => { try { @@ -31,6 +32,81 @@ it("should work with alpnProtocols", done => { } }); +it("should have peer certificate when using self asign certificate", async () => { + const COMMON_CERT = { + cert: "-----BEGIN CERTIFICATE-----\nMIIDXTCCAkWgAwIBAgIJAKLdQVPy90jjMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\nBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\naWRnaXRzIFB0eSBMdGQwHhcNMTkwMjAzMTQ0OTM1WhcNMjAwMjAzMTQ0OTM1WjBF\nMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\nZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEA7i7IIEdICTiSTVx+ma6xHxOtcbd6wGW3nkxlCkJ1UuV8NmY5ovMsGnGD\nhJJtUQ2j5ig5BcJUf3tezqCNW4tKnSOgSISfEAKvpn2BPvaFq3yx2Yjz0ruvcGKp\nDMZBXmB/AAtGyN/UFXzkrcfppmLHJTaBYGG6KnmU43gPkSDy4iw46CJFUOupc51A\nFIz7RsE7mbT1plCM8e75gfqaZSn2k+Wmy+8n1HGyYHhVISRVvPqkS7gVLSVEdTea\nUtKP1Vx/818/HDWk3oIvDVWI9CFH73elNxBkMH5zArSNIBTehdnehyAevjY4RaC/\nkK8rslO3e4EtJ9SnA4swOjCiqAIQEwIDAQABo1AwTjAdBgNVHQ4EFgQUv5rc9Smm\n9c4YnNf3hR49t4rH4yswHwYDVR0jBBgwFoAUv5rc9Smm9c4YnNf3hR49t4rH4ysw\nDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEATcL9CAAXg0u//eYUAlQa\nL+l8yKHS1rsq1sdmx7pvsmfZ2g8ONQGfSF3TkzkI2OOnCBokeqAYuyT8awfdNUtE\nEHOihv4ZzhK2YZVuy0fHX2d4cCFeQpdxno7aN6B37qtsLIRZxkD8PU60Dfu9ea5F\nDDynnD0TUabna6a0iGn77yD8GPhjaJMOz3gMYjQFqsKL252isDVHEDbpVxIzxPmN\nw1+WK8zRNdunAcHikeoKCuAPvlZ83gDQHp07dYdbuZvHwGj0nfxBLc9qt90XsBtC\n4IYR7c/bcLMmKXYf0qoQ4OzngsnPI5M+v9QEHvYWaKVwFY4CTcSNJEwfXw+BAeO5\nOA==\n-----END CERTIFICATE-----", + key: "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDuLsggR0gJOJJN\nXH6ZrrEfE61xt3rAZbeeTGUKQnVS5Xw2Zjmi8ywacYOEkm1RDaPmKDkFwlR/e17O\noI1bi0qdI6BIhJ8QAq+mfYE+9oWrfLHZiPPSu69wYqkMxkFeYH8AC0bI39QVfOSt\nx+mmYsclNoFgYboqeZTjeA+RIPLiLDjoIkVQ66lznUAUjPtGwTuZtPWmUIzx7vmB\n+pplKfaT5abL7yfUcbJgeFUhJFW8+qRLuBUtJUR1N5pS0o/VXH/zXz8cNaTegi8N\nVYj0IUfvd6U3EGQwfnMCtI0gFN6F2d6HIB6+NjhFoL+QryuyU7d7gS0n1KcDizA6\nMKKoAhATAgMBAAECggEAd5g/3o1MK20fcP7PhsVDpHIR9faGCVNJto9vcI5cMMqP\n6xS7PgnSDFkRC6EmiLtLn8Z0k2K3YOeGfEP7lorDZVG9KoyE/doLbpK4MfBAwBG1\nj6AHpbmd5tVzQrnNmuDjBBelbDmPWVbD0EqAFI6mphXPMqD/hFJWIz1mu52Kt2s6\n++MkdqLO0ORDNhKmzu6SADQEcJ9Suhcmv8nccMmwCsIQAUrfg3qOyqU4//8QB8ZM\njosO3gMUesihVeuF5XpptFjrAliPgw9uIG0aQkhVbf/17qy0XRi8dkqXj3efxEDp\n1LSqZjBFiqJlFchbz19clwavMF/FhxHpKIhhmkkRSQKBgQD9blaWSg/2AGNhRfpX\nYq+6yKUkUD4jL7pmX1BVca6dXqILWtHl2afWeUorgv2QaK1/MJDH9Gz9Gu58hJb3\nymdeAISwPyHp8euyLIfiXSAi+ibKXkxkl1KQSweBM2oucnLsNne6Iv6QmXPpXtro\nnTMoGQDS7HVRy1on5NQLMPbUBQKBgQDwmN+um8F3CW6ZV1ZljJm7BFAgNyJ7m/5Q\nYUcOO5rFbNsHexStrx/h8jYnpdpIVlxACjh1xIyJ3lOCSAWfBWCS6KpgeO1Y484k\nEYhGjoUsKNQia8UWVt+uWnwjVSDhQjy5/pSH9xyFrUfDg8JnSlhsy0oC0C/PBjxn\nhxmADSLnNwKBgQD2A51USVMTKC9Q50BsgeU6+bmt9aNMPvHAnPf76d5q78l4IlKt\nwMs33QgOExuYirUZSgjRwknmrbUi9QckRbxwOSqVeMOwOWLm1GmYaXRf39u2CTI5\nV9gTMHJ5jnKd4gYDnaA99eiOcBhgS+9PbgKSAyuUlWwR2ciL/4uDzaVeDQKBgDym\nvRSeTRn99bSQMMZuuD5N6wkD/RxeCbEnpKrw2aZVN63eGCtkj0v9LCu4gptjseOu\n7+a4Qplqw3B/SXN5/otqPbEOKv8Shl/PT6RBv06PiFKZClkEU2T3iH27sws2EGru\nw3C3GaiVMxcVewdg1YOvh5vH8ZVlxApxIzuFlDvnAoGAN5w+gukxd5QnP/7hcLDZ\nF+vesAykJX71AuqFXB4Wh/qFY92CSm7ImexWA/L9z461+NKeJwb64Nc53z59oA10\n/3o2OcIe44kddZXQVP6KTZBd7ySVhbtOiK3/pCy+BQRsrC7d71W914DxNWadwZ+a\njtwwKjDzmPwdIXDSQarCx0U=\n-----END PRIVATE KEY-----", + passphrase: "1234", + }; + + const server = Bun.serve({ + tls: { + cert: COMMON_CERT.cert, + key: COMMON_CERT.key, + passphrase: COMMON_CERT.passphrase, + }, + port: 0, + fetch() { + return new Response("Hello World"); + }, + }); + + const { promise: socketPromise, resolve: resolveSocket, reject: rejectSocket } = Promise.withResolvers(); + const socket = connect( + { + ALPNProtocols: ["http/1.1"], + host: server.hostname, + servername: "localhost", + port: server.port, + rejectUnauthorized: false, + requestCert: true, + }, + resolveSocket, + ).on("error", rejectSocket); + + await socketPromise; + + try { + expect(socket).toBeDefined(); + const cert = socket.getPeerCertificate(); + expect(cert).toBeDefined(); + expect(cert.subject).toMatchObject({ + C: "AU", + ST: "Some-State", + O: "Internet Widgits Pty Ltd", + }); + expect(cert.issuer).toBeDefined(); + expect(cert.issuer).toMatchObject({ + C: "AU", + ST: "Some-State", + O: "Internet Widgits Pty Ltd", + }); + expect(cert.subjectaltname).toBeUndefined(); + expect(cert.infoAccess).toBeUndefined(); + expect(cert.ca).toBeTrue(); + expect(cert.bits).toBe(2048); + expect(cert.modulus).toBe( + "EE2EC82047480938924D5C7E99AEB11F13AD71B77AC065B79E4C650A427552E57C366639A2F32C1A718384926D510DA3E6283905C2547F7B5ECEA08D5B8B4A9D23A048849F1002AFA67D813EF685AB7CB1D988F3D2BBAF7062A90CC6415E607F000B46C8DFD4157CE4ADC7E9A662C72536816061BA2A7994E3780F9120F2E22C38E8224550EBA9739D40148CFB46C13B99B4F5A6508CF1EEF981FA9A6529F693E5A6CBEF27D471B2607855212455BCFAA44BB8152D254475379A52D28FD55C7FF35F3F1C35A4DE822F0D5588F42147EF77A5371064307E7302B48D2014DE85D9DE87201EBE363845A0BF90AF2BB253B77B812D27D4A7038B303A30A2A8021013", + ); + expect(cert.exponent).toBe("0x10001"); + expect(cert.pubkey).toBeInstanceOf(Buffer); + expect(cert.valid_from).toBe("Feb 3 14:49:35 2019 GMT"); // yes this space is intentional + expect(cert.valid_to).toBe("Feb 3 14:49:35 2020 GMT"); + expect(cert.fingerprint).toBe("48:5F:4B:DB:FD:56:50:32:F0:27:84:3C:3F:B9:6C:DB:13:42:D2:D4"); + expect(cert.fingerprint256).toBe( + "40:F9:8C:B8:9D:3C:0D:93:09:C4:A7:96:B8:A4:69:03:6C:DB:1B:83:C9:0E:76:AE:4A:F4:16:1A:A6:13:50:B2", + ); + expect(cert.fingerprint512).toBe( + "98:56:9F:C0:A7:21:AD:BE:F3:11:AD:78:17:61:7C:36:AE:85:AB:AC:9E:1E:BF:AA:F2:92:0D:8B:36:50:07:CF:7B:C3:16:19:0F:1F:B9:09:C9:45:9D:EC:C9:44:66:72:EE:EA:CF:74:23:13:B5:FB:E1:88:52:51:D2:C6:B6:4D", + ); + expect(cert.serialNumber).toBe("A2DD4153F2F748E3"); + expect(cert.raw).toBeInstanceOf(Buffer); + } finally { + server.stop(); + socket.end(); + } +}); + it("should have peer certificate", async () => { const socket = (await new Promise((resolve, reject) => { const instance = connect( @@ -53,34 +129,25 @@ it("should have peer certificate", async () => { const cert = socket.getPeerCertificate(); expect(cert).toBeDefined(); expect(cert.subject).toBeDefined(); + // this should never change expect(cert.subject.CN).toBe("bun.sh"); - expect(cert.issuer).toBeDefined(); - expect(cert.issuer.C).toBe("US"); - expect(cert.issuer.O).toBe("Google Trust Services LLC"); - expect(cert.issuer.CN).toBe("GTS CA 1P5"); - expect(cert.subjectaltname).toBe("DNS:bun.sh, DNS:*.bun.sh"); + expect(cert.subjectaltname).toContain("DNS:bun.sh"); expect(cert.infoAccess).toBeDefined(); - + // we just check the types this can change over time const infoAccess = cert.infoAccess as NodeJS.Dict; expect(infoAccess["OCSP - URI"]).toBeDefined(); expect(infoAccess["CA Issuers - URI"]).toBeDefined(); expect(cert.ca).toBeFalse(); expect(cert.bits).toBe(2048); - expect(cert.modulus).toBe( - "A9F58B9925E08DD3393E4A5DFDBFD249A21C33AF0F38624FAF20D39EB3AC78400789CF3FCBE8C3B18B1F03B3C96B2455D88A60A8D7B2112D35159DB39A592624545CE52E6184D0504D59E6C81DD1025526DEBA547D89A47F16830AC55929C80888F65066D29517905DB1C7E8446580DC439D715C4452D03A97BB0DBC82970C8A3F7E8ABADBBA30FBF6475E2D1783793A4AC60BC57EF5E945C976CE54EECB4A3DA7920AC5C711D5FC8D6A235EFC7FA4024F3930EDDDD1680E6AEA9BD50C89394018761187B4838B07D70BF10E28E4A62F8E2FC4998BC3B9189CD50F61693D79FF761E2D4DEB3998578A6D6015926F60A4172125255FAD01485513DC3C1AE082EF", - ); - expect(cert.exponent).toBe("0x10001"); + expect(typeof cert.modulus).toBe("string"); + expect(typeof cert.exponent).toBe("string"); expect(cert.pubkey).toBeInstanceOf(Buffer); - expect(cert.valid_from).toBe("Jun 1 01:36:52 2023 GMT"); // yes this space is intentional - expect(cert.valid_to).toBe("Aug 30 01:36:51 2023 GMT"); - expect(cert.fingerprint).toBe("41:66:63:69:DC:31:95:B6:89:7C:54:72:80:19:EA:58:EE:26:FC:FA"); - expect(cert.fingerprint256).toBe( - "51:5D:10:ED:F9:F1:71:9C:03:EB:1D:17:37:2E:B0:CE:CA:8E:E7:E2:D7:D9:F0:9F:25:8D:4C:30:61:FE:86:3A", - ); - expect(cert.fingerprint512).toBe( - "61:C6:22:B6:19:B6:28:EC:5E:B1:B5:C7:A2:45:3B:A6:BA:D6:1D:A6:96:28:07:47:04:3B:04:3A:2D:A1:D7:8E:C4:55:83:B9:11:7F:6C:3B:EB:5A:66:C5:CC:E0:44:E8:4F:F1:6C:16:14:03:5B:71:76:F9:42:0C:04:5F:C0:F1", - ); - expect(cert.serialNumber).toBe("03E071FE809E66081139F0BDD02AC346"); + expect(typeof cert.valid_from).toBe("string"); + expect(typeof cert.valid_to).toBe("string"); + expect(typeof cert.fingerprint).toBe("string"); + expect(typeof cert.fingerprint256).toBe("string"); + expect(typeof cert.fingerprint512).toBe("string"); + expect(typeof cert.serialNumber).toBe("string"); expect(cert.raw).toBeInstanceOf(Buffer); } finally { socket.end(); diff --git a/test/js/node/tls/node-tls-internals.test.ts b/test/js/node/tls/node-tls-internals.test.ts new file mode 100644 index 00000000000000..f67c39e23acf7a --- /dev/null +++ b/test/js/node/tls/node-tls-internals.test.ts @@ -0,0 +1,42 @@ +import { createTest } from "node-harness"; +const { describe, expect, it } = createTest(import.meta.path); +//@ts-ignore +const $lazy = globalThis[Symbol.for("Bun.lazy")]; +const tlsInternals = $lazy("internal/tls"); + +describe("node/tls", () => { + // this is only exposed on debug builds so we skip on release builds + const test = tlsInternals ? it : it.skip; + + test("canonicalizeIP", () => { + const { canonicalizeIP } = tlsInternals; + expect(canonicalizeIP("127.0.0.1")).toBe("127.0.0.1"); + expect(canonicalizeIP("10.1.0.1")).toBe("10.1.0.1"); + expect(canonicalizeIP("::1")).toBe("::1"); + expect(canonicalizeIP("fe80:0:0:0:0:0:0:1")).toBe("fe80::1"); + expect(canonicalizeIP("fe80:0:0:0:0:0:0:0")).toBe("fe80::"); + expect(canonicalizeIP("fe80::0000:0010:0001")).toBe("fe80::10:1"); + expect(canonicalizeIP("0001:2222:3333:4444:5555:6666:7777:0088")).toBe("1:2222:3333:4444:5555:6666:7777:88"); + + expect(canonicalizeIP("0001:2222:3333:4444:5555:6666::")).toBe("1:2222:3333:4444:5555:6666::"); + + expect(canonicalizeIP("a002:B12:00Ba:4444:5555:6666:0:0")).toBe("a002:b12:ba:4444:5555:6666::"); + + // IPv4 address represented in IPv6 + expect(canonicalizeIP("0:0:0:0:0:ffff:c0a8:101")).toBe("::ffff:192.168.1.1"); + + expect(canonicalizeIP("::ffff:192.168.1.1")).toBe("::ffff:192.168.1.1"); + }); + + test("rootCertificates", () => { + const { rootCertificates } = tlsInternals; + expect(rootCertificates).toBeInstanceOf(Array); + expect(rootCertificates.length).toBeGreaterThan(0); + expect(typeof rootCertificates[0]).toBe("string"); + + for (const cert of rootCertificates) { + expect(cert).toStartWith("-----BEGIN CERTIFICATE-----"); + expect(cert).toEndWith("-----END CERTIFICATE-----"); + } + }); +}); diff --git a/test/js/node/watch/fixtures/relative.js b/test/js/node/watch/fixtures/relative.js index 26e09da1a03656..692d809ec94a9a 100644 --- a/test/js/node/watch/fixtures/relative.js +++ b/test/js/node/watch/fixtures/relative.js @@ -1,23 +1,28 @@ import fs from "fs"; -const watcher = fs.watch("relative.txt", { signal: AbortSignal.timeout(2000) }); +try { + const watcher = fs.watch("relative.txt", { signal: AbortSignal.timeout(2000) }); -watcher.on("change", function (event, filename) { - if (filename !== "relative.txt" && event !== "change") { - console.error("fail"); + watcher.on("change", function (event, filename) { + if (filename !== "relative.txt" && event !== "change") { + console.error("fail"); + clearInterval(interval); + watcher.close(); + process.exit(1); + } else { + clearInterval(interval); + watcher.close(); + } + }); + watcher.on("error", err => { clearInterval(interval); - watcher.close(); + console.error(err.message); process.exit(1); - } else { - clearInterval(interval); - watcher.close(); - } -}); -watcher.on("error", err => { - clearInterval(interval); + }); + + const interval = setInterval(() => { + fs.writeFileSync("relative.txt", "world"); + }, 10); +} catch (err) { console.error(err.message); process.exit(1); -}); - -const interval = setInterval(() => { - fs.writeFileSync("relative.txt", "world"); -}, 10); +} diff --git a/test/js/node/watch/fs.watch.test.ts b/test/js/node/watch/fs.watch.test.ts index aa7959bed5916f..5086ae1d8a059a 100644 --- a/test/js/node/watch/fs.watch.test.ts +++ b/test/js/node/watch/fs.watch.test.ts @@ -189,7 +189,7 @@ describe("fs.watch", () => { const interval = repeat(() => { fs.writeFileSync(filepath, "world"); }); - }); + }, 10000); test("should error on invalid path", done => { try { @@ -248,7 +248,7 @@ describe("fs.watch", () => { clearInterval(interval); watchers.forEach(watcher => watcher.close()); } - }); + }, 10000); test("should work with url", done => { const filepath = path.join(testDir, "url.txt"); @@ -373,6 +373,33 @@ describe("fs.watch", () => { }); expect(promise).resolves.toBe("change"); }); + + test("should throw if no permission to watch the directory", async () => { + const filepath = path.join(testDir, "permission-dir"); + fs.mkdirSync(filepath, { recursive: true }); + await fs.promises.chmod(filepath, 0o200); + try { + const watcher = fs.watch(filepath); + watcher.close(); + expect("unreacheable").toBe(false); + } catch (err: any) { + expect(err.message.indexOf("AccessDenied") !== -1).toBeTrue(); + } + }); + + test("should throw if no permission to watch the file", async () => { + const filepath = path.join(testDir, "permission-file"); + fs.writeFileSync(filepath, "hello.txt"); + await fs.promises.chmod(filepath, 0o200); + + try { + const watcher = fs.watch(filepath); + watcher.close(); + expect("unreacheable").toBe(false); + } catch (err: any) { + expect(err.message.indexOf("AccessDenied") !== -1).toBeTrue(); + } + }); }); describe("fs.promises.watch", () => { @@ -497,6 +524,64 @@ describe("fs.promises.watch", () => { })(); }); + test("should work with symlink -> symlink -> dir", async () => { + const filepath = path.join(testDir, "sym-symlink-indirect"); + const dest = path.join(testDir, "sym-symlink-dest"); + + fs.rmSync(filepath, { recursive: true, force: true }); + fs.rmSync(dest, { recursive: true, force: true }); + fs.mkdirSync(dest, { recursive: true }); + await fs.promises.symlink(dest, filepath); + const indirect_sym = path.join(testDir, "sym-symlink-to-symlink-dir"); + await fs.promises.symlink(filepath, indirect_sym); + + const watcher = fs.promises.watch(indirect_sym); + const interval = setInterval(() => { + fs.writeFileSync(path.join(indirect_sym, "hello.txt"), "hello"); + }, 10); + + const promise = (async () => { + try { + for await (const event of watcher) { + return event.eventType; + } + } catch { + expect("unreacheable").toBe(false); + } finally { + clearInterval(interval); + } + })(); + expect(promise).resolves.toBe("rename"); + }); + + test("should work with symlink dir", async () => { + const filepath = path.join(testDir, "sym-symlink-dir"); + const dest = path.join(testDir, "sym-symlink-dest"); + + fs.rmSync(filepath, { recursive: true, force: true }); + fs.rmSync(dest, { recursive: true, force: true }); + fs.mkdirSync(dest, { recursive: true }); + await fs.promises.symlink(dest, filepath); + + const watcher = fs.promises.watch(filepath); + const interval = setInterval(() => { + fs.writeFileSync(path.join(filepath, "hello.txt"), "hello"); + }, 10); + + const promise = (async () => { + try { + for await (const event of watcher) { + return event.eventType; + } + } catch { + expect("unreacheable").toBe(false); + } finally { + clearInterval(interval); + } + })(); + expect(promise).resolves.toBe("rename"); + }); + test("should work with symlink", async () => { const filepath = path.join(testDir, "sym-symlink.txt"); await fs.promises.symlink(path.join(testDir, "sym.txt"), filepath); @@ -520,3 +605,19 @@ describe("fs.promises.watch", () => { expect(promise).resolves.toBe("change"); }); }); + +describe("immediately closing", () => { + test("works correctly with files", async () => { + const filepath = path.join(testDir, "close.txt"); + for (let i = 0; i < 100; i++) fs.watch(filepath, { persistent: true }).close(); + for (let i = 0; i < 100; i++) fs.watch(filepath, { persistent: false }).close(); + }); + test("works correctly with directories", async () => { + for (let i = 0; i < 100; i++) fs.watch(testDir, { persistent: true }).close(); + for (let i = 0; i < 100; i++) fs.watch(testDir, { persistent: false }).close(); + }); + test("works correctly with recursive directories", async () => { + for (let i = 0; i < 100; i++) fs.watch(testDir, { persistent: true, recursive: true }).close(); + for (let i = 0; i < 100; i++) fs.watch(testDir, { persistent: false, recursive: false }).close(); + }); +}); diff --git a/test/js/node/worker_threads/worker.js b/test/js/node/worker_threads/worker.js new file mode 100644 index 00000000000000..e45b2e4b6ff758 --- /dev/null +++ b/test/js/node/worker_threads/worker.js @@ -0,0 +1,8 @@ +const wt = require("worker_threads"); + +wt.parentPort.on("message", e => { + let sharedBufferView = new Int32Array(e.sharedBuffer); + wt.workerData.postMessage("done!"); + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0, Infinity); +}); diff --git a/test/js/node/worker_threads/worker_threads.test.ts b/test/js/node/worker_threads/worker_threads.test.ts new file mode 100644 index 00000000000000..ae88add172d488 --- /dev/null +++ b/test/js/node/worker_threads/worker_threads.test.ts @@ -0,0 +1,109 @@ +import wt from "worker_threads"; +import { + getEnvironmentData, + isMainThread, + markAsUntransferable, + moveMessagePortToContext, + parentPort, + receiveMessageOnPort, + resourceLimits, + setEnvironmentData, + SHARE_ENV, + threadId, + workerData, + BroadcastChannel, + MessageChannel, + MessagePort, + Worker, +} from "worker_threads"; +test("all properties are present", () => { + expect(wt).toHaveProperty("getEnvironmentData"); + expect(wt).toHaveProperty("isMainThread"); + expect(wt).toHaveProperty("markAsUntransferable"); + expect(wt).toHaveProperty("moveMessagePortToContext"); + expect(wt).toHaveProperty("parentPort"); + expect(wt).toHaveProperty("receiveMessageOnPort"); + expect(wt).toHaveProperty("resourceLimits"); + expect(wt).toHaveProperty("SHARE_ENV"); + expect(wt).toHaveProperty("setEnvironmentData"); + expect(wt).toHaveProperty("threadId"); + expect(wt).toHaveProperty("workerData"); + expect(wt).toHaveProperty("BroadcastChannel"); + expect(wt).toHaveProperty("MessageChannel"); + expect(wt).toHaveProperty("MessagePort"); + expect(wt).toHaveProperty("Worker"); + + expect(getEnvironmentData).toBeDefined(); + expect(isMainThread).toBeDefined(); + expect(markAsUntransferable).toBeDefined(); + expect(moveMessagePortToContext).toBeDefined(); + expect(parentPort).toBeDefined(); + expect(receiveMessageOnPort).toBeDefined(); + expect(resourceLimits).toBeDefined(); + expect(SHARE_ENV).toBeDefined(); + expect(setEnvironmentData).toBeDefined(); + expect(threadId).toBeDefined(); + expect(workerData).toBeUndefined(); + expect(BroadcastChannel).toBeDefined(); + expect(MessageChannel).toBeDefined(); + expect(MessagePort).toBeDefined(); + expect(Worker).toBeDefined(); + + expect(() => { + // @ts-expect-error no args + wt.markAsUntransferable(); + }).toThrow("not yet implemented"); + + expect(() => { + // @ts-expect-error no args + wt.moveMessagePortToContext(); + }).toThrow("not yet implemented"); +}); + +test("receiveMessageOnPort works across threads", () => { + const { port1, port2 } = new MessageChannel(); + var worker = new wt.Worker(new URL("./worker.js", import.meta.url).href, { + workerData: port2, + transferList: [port2], + }); + let sharedBuffer = new SharedArrayBuffer(8); + let sharedBufferView = new Int32Array(sharedBuffer); + let msg = { sharedBuffer }; + worker.postMessage(msg); + Atomics.wait(sharedBufferView, 0, 0); + const message = receiveMessageOnPort(port1); + expect(message).toBeDefined(); + expect(message!.message).toBe("done!"); +}); + +test("receiveMessageOnPort works with FIFO", () => { + const { port1, port2 } = new wt.MessageChannel(); + + const message1 = { hello: "world" }; + const message2 = { foo: "bar" }; + + // Make sure receiveMessageOnPort() works in a FIFO way, the same way it does + // when we’re using events. + expect(receiveMessageOnPort(port2)).toBe(undefined); + port1.postMessage(message1); + port1.postMessage(message2); + expect(receiveMessageOnPort(port2)).toStrictEqual({ message: message1 }); + expect(receiveMessageOnPort(port2)).toStrictEqual({ message: message2 }); + expect(receiveMessageOnPort(port2)).toBe(undefined); + expect(receiveMessageOnPort(port2)).toBe(undefined); + + // Make sure message handlers aren’t called. + port2.on("message", () => { + expect().fail("message handler must not be called"); + }); + port1.postMessage(message1); + expect(receiveMessageOnPort(port2)).toStrictEqual({ message: message1 }); + port1.close(); + + for (const value of [null, 0, -1, {}, []]) { + expect(() => { + // @ts-ignore + receiveMessageOnPort(value); + }).toThrow(); + } +}); diff --git a/test/js/third_party/prisma/prisma.test.ts b/test/js/third_party/prisma/prisma.test.ts index d4e4b9cca39dc3..bc225e81bd875c 100644 --- a/test/js/third_party/prisma/prisma.test.ts +++ b/test/js/third_party/prisma/prisma.test.ts @@ -3,9 +3,8 @@ import { generateClient } from "./helper.ts"; import type { PrismaClient } from "./prisma/types.d.ts"; function* TestIDGenerator(): Generator { - let i = 0; while (true) { - yield i++; + yield Math.floor(1 + Math.random() * 2147483648); } } const test_id = TestIDGenerator(); @@ -109,14 +108,15 @@ async function cleanTestId(prisma: PrismaClient, testId: number) { expect(user?.testId).toBe(testId); const usersWithPosts = await prisma.user.findMany({ + where: { + testId, + }, include: { posts: true, }, }); expect(usersWithPosts.length).toBe(1); - expect(usersWithPosts[0]?.posts?.length).toBe(1); - expect(usersWithPosts[0]?.posts[0]?.title).toBe("Hello World"); expect(async () => await prisma.user.deleteMany({ where: { testId } })).toThrow(); diff --git a/test/js/web/broadcastchannel/broadcast-channel-worker-simple.ts b/test/js/web/broadcastchannel/broadcast-channel-worker-simple.ts new file mode 100644 index 00000000000000..057619f0810e0f --- /dev/null +++ b/test/js/web/broadcastchannel/broadcast-channel-worker-simple.ts @@ -0,0 +1,4 @@ +var bc = new BroadcastChannel("sleep"); +bc.onmessage = function (e) { + bc.postMessage("done!"); +}; diff --git a/test/js/web/broadcastchannel/broadcast-channel-worker.ts b/test/js/web/broadcastchannel/broadcast-channel-worker.ts new file mode 100644 index 00000000000000..12f32dbe889833 --- /dev/null +++ b/test/js/web/broadcastchannel/broadcast-channel-worker.ts @@ -0,0 +1,3 @@ +const bc = new BroadcastChannel("hello test"); +bc.postMessage("hello from worker"); +bc.close(); diff --git a/test/js/web/broadcastchannel/broadcast-channel.test.ts b/test/js/web/broadcastchannel/broadcast-channel.test.ts new file mode 100644 index 00000000000000..918bbd36b3d504 --- /dev/null +++ b/test/js/web/broadcastchannel/broadcast-channel.test.ts @@ -0,0 +1,197 @@ +test("postMessage results in correct event", done => { + let c1 = new BroadcastChannel("eventType"); + let c2 = new BroadcastChannel("eventType"); + + c2.onmessage = (e: MessageEvent) => { + expect(e).toBeInstanceOf(MessageEvent); + expect(e.target).toBe(c2); + expect(e.type).toBe("message"); + expect(e.origin).toBe(""); + expect(e.data).toBe("hello world"); + expect(e.source).toBe(null); + c1.close(); + c2.close(); + done(); + }; + + c1.postMessage("hello world"); +}); + +test("broadcast channel properties", () => { + let c1 = new BroadcastChannel("props"); + expect(c1.name).toBe("props"); + expect(c1.onmessage).toBe(null); + expect(c1.onmessageerror).toBe(null); + expect(c1.close).toBeInstanceOf(Function); + expect(c1.postMessage).toBeInstanceOf(Function); + expect(c1.ref).toBeInstanceOf(Function); + expect(c1.unref).toBeInstanceOf(Function); + c1.close(); +}); + +test("broadcast channel worker wait", done => { + var worker = new Worker(new URL("broadcast-channel-worker-simple.ts", import.meta.url).href); + worker.ref(); + Bun.sleepSync(500); + var bc = new BroadcastChannel("sleep"); + bc.onmessage = (e: MessageEvent) => { + expect(e.data).toBe("done!"); + bc.close(); + worker.unref(); + done(); + }; + bc.postMessage("rise and shine!"); +}); + +test("messages are delivered in port creation order", done => { + let c1 = new BroadcastChannel("order"); + let c2 = new BroadcastChannel("order"); + let c3 = new BroadcastChannel("order"); + + let events: MessageEvent[] = []; + let doneCount = 0; + let handler = (e: MessageEvent) => { + events.push(e); + if (e.data == "done") { + doneCount++; + if (doneCount == 2) { + expect(events.length).toBe(6); + expect(events[0].target).toBe(c2); + expect(events[0].data).toBe("from c1"); + expect(events[1].target).toBe(c3); + expect(events[1].data).toBe("from c1"); + expect(events[2].target).toBe(c1); + expect(events[2].data).toBe("from c3"); + expect(events[3].target).toBe(c2); + expect(events[3].data).toBe("from c3"); + expect(events[4].target).toBe(c1); + expect(events[4].data).toBe("done"); + expect(events[5].target).toBe(c3); + expect(events[5].data).toBe("done"); + c1.close(); + c2.close(); + c3.close(); + done(); + } + } + }; + + c1.onmessage = handler; + c2.onmessage = handler; + c3.onmessage = handler; + + c1.postMessage("from c1"); + c3.postMessage("from c3"); + c2.postMessage("done"); +}); + +test("messages aren't deliverd to a closed port.", done => { + let c1 = new BroadcastChannel("closed"); + let c2 = new BroadcastChannel("closed"); + let c3 = new BroadcastChannel("closed"); + + c2.onmessage = () => { + expect().fail(); + }; + c2.close(); + c3.onmessage = () => { + c1.close(); + c3.close(); + done(); + }; + c1.postMessage("test"); +}); + +test("close broadcast channel and create another with the same name", done => { + let c1 = new BroadcastChannel("close-and-create"); + c1.close(); + let c2 = new BroadcastChannel("close-and-create"); + let c3 = new BroadcastChannel("close-and-create"); + c2.onmessage = (e: MessageEvent) => { + expect(e.data).toBe("done"); + c2.close(); + c3.close(); + done(); + }; + c3.postMessage("done"); +}); + +test("messages aren't delivered to a port closed after calling postMessage.", done => { + let c1 = new BroadcastChannel("closed"); + let c2 = new BroadcastChannel("closed"); + let c3 = new BroadcastChannel("closed"); + + c2.onmessage = () => expect().fail(); + c3.onmessage = () => { + c1.close(); + c3.close(); + done(); + }; + c1.postMessage("test"); + c2.close(); +}); + +test("closing and creating channels during message delivery works correctly.", done => { + let c1 = new BroadcastChannel("create-in-onmessage"); + let c2 = new BroadcastChannel("create-in-onmessage"); + + c2.onmessage = (e: MessageEvent) => { + expect(e.data).toBe("first"); + c2.close(); + let c3 = new BroadcastChannel("create-in-onmessage"); + c3.onmessage = (event: MessageEvent) => { + expect(event.data).toBe("done"); + c1.close(); + c3.close(); + done(); + }; + c1.postMessage("done"); + }; + c1.postMessage("first"); + c2.postMessage("second"); +}); + +test("Closing a channel in onmessage prevents already queued tasks from firing onmessage events", done => { + let c1 = new BroadcastChannel("close-in-onmessage"); + let c2 = new BroadcastChannel("close-in-onmessage"); + let c3 = new BroadcastChannel("close-in-onmessage"); + + let events: string[] = []; + c1.onmessage = (e: MessageEvent) => events.push("c1: " + e.data); + c2.onmessage = (e: MessageEvent) => events.push("c2: " + e.data); + c3.onmessage = (e: MessageEvent) => events.push("c3: " + e.data); + + // c2 closes itself when it receives the first message + c2.addEventListener("message", (e: MessageEvent) => { + c2.close(); + }); + + c3.addEventListener("message", (e: MessageEvent) => { + if (e.data == "done") { + expect(events).toEqual(["c2: first", "c3: first", "c3: done"]); + c1.close(); + c3.close(); + done(); + } + }); + c1.postMessage("first"); + c1.postMessage("done"); +}); + +test("broadcast channel used with workers", done => { + var bc = new BroadcastChannel("hello test"); + var count = 0; + var workersCount = 100; + bc.onmessage = (e: MessageEvent) => { + expect(e).toBeInstanceOf(MessageEvent); + expect(e.target).toBe(bc); + expect(e.data).toBe("hello from worker"); + if (++count == workersCount) { + bc.close(); + done(); + } + }; + for (var i = 0; i < workersCount; i++) { + new Worker(new URL("./broadcast-channel-worker.ts", import.meta.url).href); + } +}); diff --git a/test/js/web/crypto/keeps-alive-fixture.js b/test/js/web/crypto/keeps-alive-fixture.js new file mode 100644 index 00000000000000..0740923a55d975 --- /dev/null +++ b/test/js/web/crypto/keeps-alive-fixture.js @@ -0,0 +1,12 @@ +const algorithms = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]; +const data = [ + "Hello World!", + "Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!", +]; +for (let bytes of data) { + for (const algorithm of algorithms) { + crypto.subtle.digest(algorithm, Buffer.from(bytes)).then(data => { + console.log(Buffer.from(data).toString("hex")); + }); + } +} diff --git a/test/js/web/crypto/web-crypto.test.ts b/test/js/web/crypto/web-crypto.test.ts index b8155c3ba26d0f..006d488513ed21 100644 --- a/test/js/web/crypto/web-crypto.test.ts +++ b/test/js/web/crypto/web-crypto.test.ts @@ -1,6 +1,31 @@ +import { spawnSync } from "bun"; import { describe, expect, it } from "bun:test"; +import { bunEnv, bunExe } from "harness"; describe("Web Crypto", () => { + // https://github.com/oven-sh/bun/issues/3795 + it("keeps event loop alive", () => { + const { stdout, exitCode } = spawnSync({ + cmd: [bunExe(), import.meta.resolveSync("./keeps-alive-fixture.js")], + env: bunEnv, + }); + + const lines = stdout.toString().trim().split("\n").sort(); + const results = [ + "2ef7bde608ce5404e97d5f042f95f89f1c232871", + "6b3e626d70787e3dc3f0bca509a7e1e5f6802643fde54a18d4353aa9b24ccb2fb874bbc8a70ff587df2bd6ed41471f82", + "7dc2af5ef620a4b1c8871371526b664512b82193", + "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", + "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8", + "bf6873609ce720ec489bb2f5ae116716058c06cda7dc9a7e1dadee90da98e71aee22519505af61adbecd5b94bbefa855c2ede623e8b383bb179b150e25861441", + "bfd76c0ebbd006fee583410547c1887b0292be76d582d96c242d2a792723e3fd6fd061f9d5cfd13b8f961358e6adba4a", + "e1061f7858d68c3818ec9967ea1f7bf8e3c65f5603af95004bdfcb64b9ea4148", + ]; + + expect(exitCode).toBe(0); + expect(lines).toStrictEqual(results); + }); + it("has globals", () => { expect(crypto.subtle !== undefined).toBe(true); expect(CryptoKey.name).toBe("CryptoKey"); diff --git a/test/js/web/fetch/body-stream.test.ts b/test/js/web/fetch/body-stream.test.ts index 64b3434e10b2cf..8e2baf92a5d24c 100644 --- a/test/js/web/fetch/body-stream.test.ts +++ b/test/js/web/fetch/body-stream.test.ts @@ -1,7 +1,6 @@ // @ts-nocheck -import { file, gc, serve, ServeOptions } from "bun"; -import { afterAll, afterEach, describe, expect, it, test } from "bun:test"; -import { readFileSync } from "fs"; +import { gc, ServeOptions } from "bun"; +import { afterAll, describe, expect, it, test } from "bun:test"; var port = 0; diff --git a/test/js/web/fetch/fetch-leak-test-fixture.js b/test/js/web/fetch/fetch-leak-test-fixture.js index 1767cdb041bdc0..a785d6d40fdc30 100644 --- a/test/js/web/fetch/fetch-leak-test-fixture.js +++ b/test/js/web/fetch/fetch-leak-test-fixture.js @@ -14,7 +14,8 @@ await (async function runAll() { for (let j = 0; j < 32; j++) { fetches.push(fetch(SERVER)); } - await Promise.all(fetches.slice(i, i + 32)); + await Promise.all(fetches); + fetches.length = 0; i += 32; } diff --git a/test/js/web/fetch/fetch.test.ts b/test/js/web/fetch/fetch.test.ts index 76881842098e91..a381cb3203228a 100644 --- a/test/js/web/fetch/fetch.test.ts +++ b/test/js/web/fetch/fetch.test.ts @@ -30,6 +30,123 @@ afterAll(() => { const payload = new Uint8Array(1024 * 1024 * 2); crypto.getRandomValues(payload); +it("new Request(invalid url) throws", () => { + expect(() => new Request("http")).toThrow(); + expect(() => new Request("")).toThrow(); + expect(() => new Request("http://[::1")).toThrow(); + expect(() => new Request("https://[::1")).toThrow(); + expect(() => new Request("!")).toThrow(); +}); + +describe("fetch data urls", () => { + it("basic", async () => { + var url = + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; + + var res = await fetch(url); + expect(res.status).toBe(200); + expect(res.statusText).toBe("OK"); + expect(res.ok).toBe(true); + + var blob = await res.blob(); + expect(blob.size).toBe(85); + expect(blob.type).toBe("image/png"); + }); + it("percent encoded", async () => { + var url = "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D"; + var res = await fetch(url); + expect(res.status).toBe(200); + expect(res.statusText).toBe("OK"); + expect(res.ok).toBe(true); + + var blob = await res.blob(); + expect(blob.size).toBe(13); + expect(blob.type).toBe("text/plain;charset=utf-8"); + expect(blob.text()).resolves.toBe("Hello, World!"); + }); + it("percent encoded (invalid)", async () => { + var url = "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3"; + expect(async () => { + await fetch(url); + }).toThrow("failed to fetch the data URL"); + }); + it("plain text", async () => { + var url = "data:,Hello%2C%20World!"; + var res = await fetch(url); + expect(res.status).toBe(200); + expect(res.statusText).toBe("OK"); + expect(res.ok).toBe(true); + + var blob = await res.blob(); + expect(blob.size).toBe(13); + expect(blob.type).toBe("text/plain;charset=utf-8"); + expect(blob.text()).resolves.toBe("Hello, World!"); + + url = "data:,helloworld!"; + res = await fetch(url); + expect(res.status).toBe(200); + expect(res.statusText).toBe("OK"); + expect(res.ok).toBe(true); + + blob = await res.blob(); + expect(blob.size).toBe(11); + expect(blob.type).toBe("text/plain;charset=utf-8"); + expect(blob.text()).resolves.toBe("helloworld!"); + }); + it("data url (invalid)", async () => { + var url = "data:Hello%2C%20World!"; + expect(async () => { + await fetch(url); + }).toThrow("failed to fetch the data URL"); + }); + it("emoji", async () => { + var url = "data:,😀"; + + var res = await fetch(url); + expect(res.status).toBe(200); + expect(res.statusText).toBe("OK"); + expect(res.ok).toBe(true); + + var blob = await res.blob(); + expect(blob.size).toBe(4); + expect(blob.type).toBe("text/plain;charset=utf-8"); + expect(blob.text()).resolves.toBe("😀"); + }); + it("should work with Request", async () => { + var req = new Request("data:,Hello%2C%20World!"); + var res = await fetch(req); + expect(res.status).toBe(200); + expect(res.statusText).toBe("OK"); + expect(res.ok).toBe(true); + + var blob = await res.blob(); + expect(blob.size).toBe(13); + expect(blob.type).toBe("text/plain;charset=utf-8"); + expect(blob.text()).resolves.toBe("Hello, World!"); + + req = new Request("data:,😀"); + res = await fetch(req); + expect(res.status).toBe(200); + expect(res.statusText).toBe("OK"); + expect(res.ok).toBe(true); + + blob = await res.blob(); + expect(blob.size).toBe(4); + expect(blob.type).toBe("text/plain;charset=utf-8"); + expect(blob.text()).resolves.toBe("😀"); + }); + it("should work with Request (invalid)", async () => { + var req = new Request("data:Hello%2C%20World!"); + expect(async () => { + await fetch(req); + }).toThrow("failed to fetch the data URL"); + req = new Request("data:Hello%345632"); + expect(async () => { + await fetch(req); + }).toThrow("failed to fetch the data URL"); + }); +}); + describe("AbortSignal", () => { beforeEach(() => { startServer({ @@ -226,11 +343,11 @@ describe("Headers", () => { ]); const actual = [...headers]; expect(actual).toEqual([ + ["x-bun", "abc, def"], ["set-cookie", "foo=bar"], ["set-cookie", "bar=baz"], - ["x-bun", "abc, def"], ]); - expect([...headers.values()]).toEqual(["foo=bar", "bar=baz", "abc, def"]); + expect([...headers.values()]).toEqual(["abc, def", "foo=bar", "bar=baz"]); }); it("Headers append multiple", () => { @@ -245,9 +362,9 @@ describe("Headers", () => { // we do not preserve the order // which is kind of bad expect(actual).toEqual([ + ["x-bun", "foo, bar"], ["set-cookie", "foo=bar"], ["set-cookie", "bar=baz"], - ["x-bun", "foo, bar"], ]); }); @@ -268,9 +385,17 @@ describe("Headers", () => { headers.set("set-Cookie", "foo=baz"); headers.set("set-cookie", "bar=qat"); const actual = [...headers]; + expect(actual).toEqual([["set-cookie", "bar=qat"]]); + }); + + it("should include set-cookie headers in array", () => { + const headers = new Headers(); + headers.append("Set-Cookie", "foo=bar"); + headers.append("Content-Type", "text/plain"); + const actual = [...headers]; expect(actual).toEqual([ - ["set-cookie", "foo=baz"], - ["set-cookie", "bar=qat"], + ["content-type", "text/plain"], + ["set-cookie", "foo=bar"], ]); }); }); @@ -1165,9 +1290,9 @@ it("should not be able to parse json from empty body", () => { }); it("#874", () => { - expect(new Request(new Request("https://example.com"), {}).url).toBe("https://example.com"); - expect(new Request(new Request("https://example.com")).url).toBe("https://example.com"); - expect(new Request({ url: "https://example.com" }).url).toBe("https://example.com"); + expect(new Request(new Request("https://example.com"), {}).url).toBe("https://example.com/"); + expect(new Request(new Request("https://example.com")).url).toBe("https://example.com/"); + expect(new Request({ url: "https://example.com" }).url).toBe("https://example.com/"); }); it("#2794", () => { @@ -1203,3 +1328,39 @@ it("new Request(https://example.com, otherRequest) uses url from left instead of expect(req2.url).toBe("http://localhost/def"); expect(req2.headers.get("foo")).toBe("bar"); }); + +it("fetch() file:// works", async () => { + expect(await (await fetch(import.meta.url)).text()).toEqual(await Bun.file(import.meta.path).text()); + expect(await (await fetch(new URL("fetch.test.ts", import.meta.url))).text()).toEqual( + await Bun.file(Bun.fileURLToPath(new URL("fetch.test.ts", import.meta.url))).text(), + ); + expect(await (await fetch(new URL("file with space in the name.txt", import.meta.url))).text()).toEqual( + await Bun.file(Bun.fileURLToPath(new URL("file with space in the name.txt", import.meta.url))).text(), + ); +}); + +it("cloned response headers are independent before accessing", () => { + const response = new Response("hello", { + headers: { + "content-type": "text/html; charset=utf-8", + }, + }); + const cloned = response.clone(); + cloned.headers.set("content-type", "text/plain"); + expect(response.headers.get("content-type")).toBe("text/html; charset=utf-8"); +}); + +it("cloned response headers are independent after accessing", () => { + const response = new Response("hello", { + headers: { + "content-type": "text/html; charset=utf-8", + }, + }); + + // create the headers + response.headers; + + const cloned = response.clone(); + cloned.headers.set("content-type", "text/plain"); + expect(response.headers.get("content-type")).toBe("text/html; charset=utf-8"); +}); diff --git a/test/js/web/fetch/file with space in the name.txt b/test/js/web/fetch/file with space in the name.txt new file mode 100644 index 00000000000000..3462721fd4da6b --- /dev/null +++ b/test/js/web/fetch/file with space in the name.txt @@ -0,0 +1 @@ +hello! \ No newline at end of file diff --git a/test/js/web/fetch/headers.test.ts b/test/js/web/fetch/headers.test.ts index 8ae17c11e162c0..6ac1b0671d9dfa 100644 --- a/test/js/web/fetch/headers.test.ts +++ b/test/js/web/fetch/headers.test.ts @@ -251,8 +251,7 @@ describe("Headers", () => { // @ts-expect-error expect(() => cookies.getAll("not-set-cookie")).toThrow(TypeError); }); - const it1 = "getSetCookie" in cookies ? test : test.skip; - it1("can get header with set-cookie using getSetCookie()", () => { + test("can get header with set-cookie using getSetCookie()", () => { // @ts-expect-error expect(cookies.getSetCookie()).toEqual([ "__Secure-ID=123; Secure; Domain=example.com", diff --git a/test/js/web/many-messages-event-loop.js b/test/js/web/many-messages-event-loop.js new file mode 100644 index 00000000000000..2eaba256864166 --- /dev/null +++ b/test/js/web/many-messages-event-loop.js @@ -0,0 +1,11 @@ +const worker = new Worker(new URL("worker-fixture-many-messages.js", import.meta.url).href); + +worker.postMessage("initial message"); +worker.addEventListener("message", ({ data }) => { + if (data.done) { + console.log("done"); + worker.terminate(); + } else { + worker.postMessage({ i: data.i + 1 }); + } +}); diff --git a/test/js/web/streams/streams.test.js b/test/js/web/streams/streams.test.js index 55843cb23bd510..7359009b792b5c 100644 --- a/test/js/web/streams/streams.test.js +++ b/test/js/web/streams/streams.test.js @@ -5,6 +5,48 @@ import { realpathSync, unlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "os"; +it("TransformStream", async () => { + // https://developer.mozilla.org/en-US/docs/Web/API/TransformStream + const TextEncoderStreamInterface = { + start() { + this.encoder = new TextEncoder(); + }, + transform(chunk, controller) { + controller.enqueue(this.encoder.encode(chunk)); + }, + }; + + let instances = new WeakMap(); + class JSTextEncoderStream extends TransformStream { + constructor() { + super(TextEncoderStreamInterface); + instances.set(this, TextEncoderStreamInterface); + } + get encoding() { + return instances.get(this).encoder.encoding; + } + } + + const stream = new JSTextEncoderStream(); + const { writable, readable } = stream; + + const writer = writable.getWriter(); + writer.write("hello"); + writer.write("world"); + writer.close(); + + const reader = readable.getReader(); + const chunks = []; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + } + reader.cancel(); + + expect(Buffer.concat(chunks).toString()).toEqual("helloworld"); +}); + describe("readableStreamToFormData", () => { const fixtures = { withTextFile: [ @@ -171,10 +213,7 @@ describe("WritableStream", () => { write(chunk, controller) { chunks.push(chunk); }, - close(er) { - console.log("closed"); - console.log(er); - }, + close(er) {}, abort(reason) { console.log("aborted!"); console.log(reason); diff --git a/test/js/web/worker-fixture-env.js b/test/js/web/worker-fixture-env.js new file mode 100644 index 00000000000000..203ed31419df23 --- /dev/null +++ b/test/js/web/worker-fixture-env.js @@ -0,0 +1,12 @@ +import * as worker_threads from "worker_threads"; + +if (worker_threads.isMainThread) throw new Error("worker_threads.isMainThread is wrong"); + +Bun.inspect(process.env); + +onmessage = ({}) => { + postMessage({ + env: process.env, + hello: process.env.hello, + }); +}; diff --git a/test/js/web/worker-fixture-many-messages.js b/test/js/web/worker-fixture-many-messages.js new file mode 100644 index 00000000000000..7a8f1d910935a8 --- /dev/null +++ b/test/js/web/worker-fixture-many-messages.js @@ -0,0 +1,12 @@ +addEventListener("message", e => { + const data = e.data; + // console.log("worker", data); + + if (data === "initial message") { + postMessage({ i: 0 }); + } else if (data.i > 50) { + postMessage({ done: true }); + } else { + postMessage({ i: data.i + 1 }); + } +}); diff --git a/test/js/web/worker-fixture-process-exit.js b/test/js/web/worker-fixture-process-exit.js new file mode 100644 index 00000000000000..0d93217d918701 --- /dev/null +++ b/test/js/web/worker-fixture-process-exit.js @@ -0,0 +1,3 @@ +setTimeout(() => { + process.exit(2); +}, 100); diff --git a/test/js/web/worker.test.ts b/test/js/web/worker.test.ts index 02d9af5d8368ef..34d5f6f06747c2 100644 --- a/test/js/web/worker.test.ts +++ b/test/js/web/worker.test.ts @@ -1,16 +1,173 @@ import { expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; +import path from "path"; +import * as wt from "worker_threads"; test("worker", done => { const worker = new Worker(new URL("worker-fixture.js", import.meta.url).href, { smol: true, }); + expect(worker.threadId).toBe(1); worker.postMessage("hello"); worker.onerror = e => { done(e.error); }; worker.onmessage = e => { - expect(e.data).toEqual("initial message"); + try { + expect(e.data).toEqual("initial message"); + } catch (e) { + done(e); + } finally { + worker.terminate(); + done(); + } worker.terminate(); done(); }; }); + +test("worker-env", done => { + const worker = new Worker(new URL("worker-fixture-env.js", import.meta.url).href, { + env: { + hello: "world", + another_key: 123 as any, + }, + }); + worker.postMessage("hello"); + worker.onerror = e => { + done(e.error); + }; + worker.onmessage = e => { + try { + expect(e.data).toEqual({ + env: { + hello: "world", + another_key: "123", + }, + hello: "world", + }); + } catch (e) { + done(e); + } finally { + worker.terminate(); + done(); + } + }; +}); + +test("worker-env with a lot of properties", done => { + const obj: any = {}; + + for (let i = 0; i < 1000; i++) { + obj["prop " + i] = Math.random().toString(); + } + + const worker = new Worker(new URL("worker-fixture-env.js", import.meta.url).href, { + env: obj, + }); + worker.postMessage("hello"); + worker.onerror = e => { + done(e.error); + }; + worker.onmessage = e => { + try { + expect(e.data).toEqual({ + env: obj, + hello: undefined, + }); + } catch (e) { + done(e); + } finally { + worker.terminate(); + done(); + } + }; +}); + +test("sending 50 messages should just work", done => { + const worker = new Worker(new URL("worker-fixture-many-messages.js", import.meta.url).href, {}); + + worker.postMessage("initial message"); + worker.addEventListener("message", ({ data }) => { + if (data.done) { + worker.terminate(); + done(); + } else { + worker.postMessage({ i: data.i + 1 }); + } + }); +}); + +test("worker by default will not close the event loop", done => { + const x = Bun.spawn({ + cmd: [bunExe(), path.join(import.meta.dir, "many-messages-event-loop.js")], + env: bunEnv, + stdio: ["inherit", "pipe", "inherit"], + }); + + const timer = setTimeout(() => { + x.kill(); + done(new Error("timeout")); + }, 1000); + + x.exited.then(async code => { + clearTimeout(timer); + if (code !== 0) { + done(new Error("exited with non-zero code")); + } else { + const text = await new Response(x.stdout).text(); + if (!text.includes("done")) { + console.log({ text }); + done(new Error("event loop killed early")); + } else { + done(); + } + } + }); +}); + +test("worker with process.exit", done => { + const worker = new Worker(new URL("worker-fixture-process-exit.js", import.meta.url).href, { + smol: true, + }); + worker.addEventListener("close", e => { + try { + expect(e.code).toBe(2); + } catch (e) { + done(e); + } + done(); + }); +}); + +test("worker_threads with process.exit", done => { + const worker = new wt.Worker(new URL("worker-fixture-process-exit.js", import.meta.url).href, { + smol: true, + }); + worker.on("exit", event => { + try { + console.log({ event }); + expect(event).toBe(2); + } catch (e) { + done(e); + } + done(); + }); +}); + +test.skip("worker_threads with process.exit and terminate", async () => { + const worker = new wt.Worker(new URL("worker-fixture-process-exit.js", import.meta.url).href, { + smol: true, + }); + const code = await worker.terminate(); + expect(code).toBe(2); +}); + +test.skip("worker_threads with process.exit (delay) and terminate", async () => { + const worker2 = new wt.Worker(new URL("worker-fixture-process-exit.js", import.meta.url).href, { + smol: true, + }); + await Bun.sleep(100); + const code2 = await worker2.terminate(); + expect(code2).toBe(2); +}); diff --git a/test/js/web/workers/create-port-worker.js b/test/js/web/workers/create-port-worker.js new file mode 100644 index 00000000000000..6e8709de079cf5 --- /dev/null +++ b/test/js/web/workers/create-port-worker.js @@ -0,0 +1,6 @@ +var channel = new MessageChannel(); +channel.port1.onmessage = e => { + channel.port1.postMessage("done!"); +}; + +postMessage(channel.port2, { transfer: [channel.port2] }); diff --git a/test/js/web/workers/message-channel.test.ts b/test/js/web/workers/message-channel.test.ts new file mode 100644 index 00000000000000..e0e31817207a52 --- /dev/null +++ b/test/js/web/workers/message-channel.test.ts @@ -0,0 +1,262 @@ +test("simple usage", done => { + var channel = new MessageChannel(); + var port1 = channel.port1; + var port2 = channel.port2; + + port2.onmessage = function (e) { + expect(e.data).toEqual("hello"); + done(); + }; + + port1.postMessage("hello"); +}); + +test("transfer message port", done => { + var channel = new MessageChannel(); + var anotherChannel = new MessageChannel(); + var port1 = channel.port1; + var port2 = channel.port2; + + port2.onmessage = function (e) { + expect(e.data).toEqual("hello"); + expect(e.ports).toHaveLength(1); + expect(e.ports[0]).toBeInstanceOf(MessagePort); + done(); + }; + + port1.postMessage("hello", [anotherChannel.port2]); +}); + +test("tranfer array buffer", done => { + var channel = new MessageChannel(); + var port1 = channel.port1; + var port2 = channel.port2; + + port2.onmessage = function (e) { + expect(e.data).toBeInstanceOf(ArrayBuffer); + expect(e.data.byteLength).toEqual(8); + done(); + }; + + const buffer = new ArrayBuffer(8); + + port1.postMessage(buffer, [buffer]); +}); + +test("non-transferable", () => { + var channel = new MessageChannel(); + channel.port2.onmessage = function (e) { + expect().fail("should not be reached"); + }; + expect(() => { + channel.port1.postMessage("hello", [channel.port1]); + }).toThrow(); + expect(() => { + channel.port1.postMessage("hello", [channel.port2]); + }).toThrow(); +}); + +test("transfer message ports and post messages", done => { + var c1 = new MessageChannel(); + var c2 = new MessageChannel(); + + c1.port1.onmessage = e => { + var port = e.ports[0]; + expect(port).toBeInstanceOf(MessagePort); + expect(e.data).toEqual("hello from channel 1 port 2"); + port.onmessage = e => { + expect(e.data).toEqual("hello from channel 1 port 2"); + done(); + }; + port.postMessage("hello from channel 1 port 1", [c1.port1]); + }; + + c1.port2.onmessage = e => { + var port = e.ports[0]; + expect(port).toBeInstanceOf(MessagePort); + expect(e.data).toEqual("hello from channel 2 port 1"); + port.postMessage("hello from channel 1 port 2"); + }; + + c2.port1.onmessage = e => { + var port = e.ports[0]; + expect(port).toBeInstanceOf(MessagePort); + expect(e.data).toEqual("hello from channel 1 port 1"); + port.postMessage("hello from channel 2 port 1", [c2.port1]); + }; + + c2.port2.onmessage = e => { + expect().fail("onmessage defined on c1.port1 should be called instead"); + }; + + c1.port2.postMessage("hello from channel 1 port 2", [c2.port2]); +}); + +test("message channel created on main thread", done => { + var worker = new Worker(new URL("receive-port-worker.js", import.meta.url).href); + worker.onerror = e => { + expect().fail(); + done(); + }; + var channel = new MessageChannel(); + channel.port1.onmessage = e => { + if (e.data === "done!") return done(); + expect(e.data).toEqual("received port!"); + channel.port1.postMessage("more message!"); + }; + worker.postMessage(channel.port2, { transfer: [channel.port2] }); +}); + +test("message channel created on other thread", done => { + var worker = new Worker(new URL("create-port-worker.js", import.meta.url).href); + worker.onerror = e => { + expect().fail(); + done(); + }; + worker.onmessage = e => { + expect(e.data).toBeInstanceOf(MessagePort); + var port = e.data; + port.onmessage = (e: MessageEvent) => { + expect(e.data).toEqual("done!"); + done(); + }; + port.postMessage("hello from main thread"); + }; +}); + +test("many message channels", done => { + var channel = new MessageChannel(); + var channel2 = new MessageChannel(); + var channel3 = new MessageChannel(); + var channel4 = new MessageChannel(); + + channel.port1.postMessage("noport"); + channel.port1.postMessage("zero ports", []); + channel.port1.postMessage("two ports", [channel2.port1, channel2.port2]); + + // Now test various failure cases + expect(() => { + channel.port1.postMessage("same port", [channel.port1]); + }).toThrow(); + expect(() => { + channel.port1.postMessage("entangled port", [channel.port2]); + }).toThrow(); + expect(() => { + // @ts-ignore + channel.port1.postMessage("null port", [channel3.port1, null, channel3.port2]); + }).toThrow(); + expect(() => { + // @ts-ignore + channel.port1.postMessage("notAPort", [channel3.port1, {}, channel3.port2]); + }).toThrow(); + expect(() => { + channel.port1.postMessage("duplicate port", [channel3.port1, channel3.port1]); + }).toThrow(); + + // Should be OK to send channel3.port1 (should not have been disentangled by the previous failed calls). + expect(() => { + channel.port1.postMessage("entangled ports", [channel3.port1, channel3.port2]); + }).not.toThrow(); + + expect(() => { + // @ts-ignore + channel.port1.postMessage("notAnArray", "foo"); + }).toThrow(); + expect(() => { + // @ts-ignore + channel.port1.postMessage("notASequence", [{ length: 3 }]); + }).toThrow(); + + // Should not crash (we should figure out that the array contains undefined + // entries). + var largePortArray: MessagePort[] = []; + largePortArray[1234567890] = channel4.port1; + expect(() => { + channel.port1.postMessage("largeSequence", largePortArray); + }).toThrow(); + + channel.port1.postMessage("done"); + + function testTransfers(done: any) { + var channel0 = new MessageChannel(); + + var c1 = new MessageChannel(); + channel0.port1.postMessage({ id: "send-port", port: c1.port1 }, [c1.port1]); + var c2 = new MessageChannel(); + channel0.port1.postMessage({ id: "send-port-twice", port0: c2.port1, port1: c2.port1 }, [c2.port1]); + var c3 = new MessageChannel(); + channel0.port1.postMessage({ id: "send-two-ports", port0: c3.port1, port1: c3.port2 }, [c3.port1, c3.port2]); + var c4 = new MessageChannel(); + + // Sending host objects should throw + expect(() => { + channel0.port1.postMessage({ id: "host-object", hostObject: c3, port: c4.port1 }, [c4.port1]); + }).toThrow(); + + // Sending Function object should throw + expect(() => { + var f1 = function () {}; + channel0.port1.postMessage({ id: "function-object", function: f1, port: c4.port1 }, [c4.port1]); + }).toThrow(); + + // Sending Error object should not throw + expect(() => { + var err = new Error(); + channel0.port1.postMessage({ id: "error-object", error: err, port: c4.port1 }, [c4.port1]); + }).not.toThrow(); + + c4.port1.postMessage("Should succeed"); + channel0.port1.postMessage({ id: "done" }); + + channel0.port2.onmessage = function (event) { + if (event.data.id == "send-port") { + expect(event.ports.length).toBeGreaterThan(0); + expect(event.ports[0]).toBe(event.data.port); + } else if (event.data.id == "error-object") { + expect(event.data.error).toBeInstanceOf(Error); + } else if (event.data.id == "send-port-twice") { + expect(event.ports).toBeDefined(); + expect(event.ports.length).toBe(1); + expect(event.ports[0]).toBe(event.data.port0); + expect(event.ports[0]).toBe(event.data.port1); + } else if (event.data.id == "send-two-ports") { + expect(event.ports).toBeDefined(); + expect(event.ports.length).toBe(2); + expect(event.ports[0]).toBe(event.data.port0); + expect(event.ports[1]).toBe(event.data.port1); + } else if (event.data.id == "done") { + done(); + } else { + expect().fail("branch should not be reached"); + } + }; + } + + channel.port2.onmessage = function (event) { + if (event.data == "noport") { + expect(event.ports).toBeDefined(); + expect(event.ports.length).toBe(0); + } else if (event.data == "zero ports") { + expect(event.ports).toBeDefined(); + expect(event.ports.length).toBe(0); + } else if (event.data == "two ports") { + expect(event.ports).toBeDefined(); + expect(event.ports.length).toBe(2); + } else if (event.data == "entangled ports") { + expect(event.ports).toBeDefined(); + expect(event.ports.length).toBe(2); + } else if (event.data == "done") { + testTransfers(done); + } else { + expect().fail("branch should not be reached"); + } + }; +}); + +test("gc", () => { + for (let i = 0; i < 1000; i++) { + var e = new MessageChannel(); + e.port1; + e.port2; + } +}); diff --git a/test/js/web/workers/receive-port-worker.js b/test/js/web/workers/receive-port-worker.js new file mode 100644 index 00000000000000..871fc4405bcea3 --- /dev/null +++ b/test/js/web/workers/receive-port-worker.js @@ -0,0 +1,9 @@ +onmessage = e => { + if (e.data instanceof MessagePort) { + var port = e.data; + port.onmessage = e => { + port.postMessage("done!"); + }; + port.postMessage("received port!"); + } +}; diff --git a/test/js/web/workers/structured-clone.test.ts b/test/js/web/workers/structured-clone.test.ts index 61a0c132060540..bdc7fcfea6c5ad 100644 --- a/test/js/web/workers/structured-clone.test.ts +++ b/test/js/web/workers/structured-clone.test.ts @@ -183,7 +183,7 @@ describe("structured clone", () => { }); }); - describe("transferrables", () => { + describe("transferables", () => { test("ArrayBuffer", () => { const buffer = Uint8Array.from([1]).buffer; const cloned = structuredClone(buffer, { transfer: [buffer] }); diff --git a/test/package.json b/test/package.json index 3ab8d5143f3bd3..5fecb838b79b5b 100644 --- a/test/package.json +++ b/test/package.json @@ -1,14 +1,15 @@ { "name": "test", "devDependencies": { - "@types/dedent": "0.7.0" + "@types/dedent": "0.7.0", + "@types/utf-8-validate": "5.0.0", + "@types/react": "18.0.28", + "@types/react-dom": "18.0.11", + "@types/supertest": "2.0.12" }, "dependencies": { "@prisma/client": "5.0.0", "@swc/core": "1.3.38", - "@types/react": "18.0.28", - "@types/react-dom": "18.0.11", - "@types/supertest": "2.0.12", "bktree-fast": "0.0.7", "body-parser": "1.20.2", "comlink": "4.4.1", diff --git a/test/regression/issue/4011.test.ts b/test/regression/issue/4011.test.ts new file mode 100644 index 00000000000000..a3db4270ddf9dc --- /dev/null +++ b/test/regression/issue/4011.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; + +test("running a missing script should return non zero exit code", () => { + const { stdout, exitCode } = Bun.spawnSync({ + cmd: [bunExe(), "run", "missing.ts"], + env: bunEnv, + stderr: "inherit", + }); + + expect(exitCode).toBe(1); +}); diff --git a/test/transpiler/async-transpiler-entry.js b/test/transpiler/async-transpiler-entry.js new file mode 100644 index 00000000000000..191c7c8a7656c6 --- /dev/null +++ b/test/transpiler/async-transpiler-entry.js @@ -0,0 +1,2 @@ +export { default } from "./async-transpiler-imported.js"; +export { default as hbs } from "./handlebars.hbs"; diff --git a/test/transpiler/async-transpiler-imported.js b/test/transpiler/async-transpiler-imported.js new file mode 100644 index 00000000000000..ed2f2249045991 --- /dev/null +++ b/test/transpiler/async-transpiler-imported.js @@ -0,0 +1,6 @@ +// @bun +export default 42; + +if (import.meta.main) { + console.log("Hello world!"); +} diff --git a/test/transpiler/decorators.test.ts b/test/transpiler/decorators.test.ts index 100ecc3bc9d431..885391800d08fd 100644 --- a/test/transpiler/decorators.test.ts +++ b/test/transpiler/decorators.test.ts @@ -998,3 +998,23 @@ test("export default class Named works", () => { test("export default class works (anonymous name)", () => { expect(new DecoratedAnonClass()["methoddecorated"]).toBe(true); }); + +test("decorator and declare", () => { + let counter = 0; + function d1(t) { + t(); + } + class A { + @d1(() => { + counter++; + }) + declare a: number; + + m() { + counter++; + } + } + + new A(); + expect(counter).toBe(1); +}); diff --git a/test/transpiler/handlebars.hbs b/test/transpiler/handlebars.hbs new file mode 100644 index 00000000000000..be58303575e8be --- /dev/null +++ b/test/transpiler/handlebars.hbs @@ -0,0 +1,6 @@ + + + + {{title}} + + \ No newline at end of file diff --git a/test/transpiler/macro-test.test.ts b/test/transpiler/macro-test.test.ts index 2390fac64a3100..f3df00c5b90e9a 100644 --- a/test/transpiler/macro-test.test.ts +++ b/test/transpiler/macro-test.test.ts @@ -1,4 +1,4 @@ -import { identity } from "./macro.ts" assert { type: "macro" }; +import { identity, escape, addStringsUTF16, addStrings } from "./macro.ts" assert { type: "macro" }; test("latin1 string", () => { expect(identity("©")).toBe("©"); @@ -8,6 +8,75 @@ test("ascii string", () => { expect(identity("abc")).toBe("abc"); }); +test("escaping", () => { + expect(identity("\\")).toBe("\\"); + expect(identity("\f")).toBe("\f"); + expect(identity("\n")).toBe("\n"); + expect(identity("\r")).toBe("\r"); + expect(identity("\t")).toBe("\t"); + expect(identity("\v")).toBe("\v"); + expect(identity("\0")).toBe("\0"); + expect(identity("'")).toBe("'"); + expect(identity('"')).toBe('"'); + expect(identity("`")).toBe("`"); + // prettier-ignore + expect(identity("\'")).toBe("\'"); + // prettier-ignore + expect(identity('\"')).toBe('\"'); + // prettier-ignore + expect(identity("\`")).toBe("\`"); + expect(identity("$")).toBe("$"); + expect(identity("\x00")).toBe("\x00"); + expect(identity("\x0B")).toBe("\x0B"); + expect(identity("\x0C")).toBe("\x0C"); + + expect(identity("\\")).toBe("\\"); + + expect(escape()).toBe("\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C"); + + expect(addStrings("abc")).toBe("abc\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\n")).toBe("\n\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\r")).toBe("\r\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\t")).toBe("\t\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("©")).toBe("©\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\x00")).toBe("\x00\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\x0B")).toBe("\x0B\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\x0C")).toBe("\x0C\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\\")).toBe("\\\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\f")).toBe("\f\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\v")).toBe("\v\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("\0")).toBe("\0\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("'")).toBe("'\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings('"')).toBe('"\\\f\n\r\t\v\0\'"`$\x00\x0B\x0C©'); + expect(addStrings("`")).toBe("`\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + expect(addStrings("😊")).toBe("😊\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C©"); + + expect(addStringsUTF16("abc")).toBe("abc\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\n")).toBe("\n\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\r")).toBe("\r\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\t")).toBe("\t\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("©")).toBe("©\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\x00")).toBe("\x00\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\x0B")).toBe("\x0B\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\x0C")).toBe("\x0C\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\\")).toBe("\\\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\f")).toBe("\f\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\v")).toBe("\v\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("\0")).toBe("\0\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("'")).toBe("'\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16('"')).toBe('"\\\f\n\r\t\v\0\'"`$\x00\x0B\x0C😊'); + expect(addStringsUTF16("`")).toBe("`\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); + expect(addStringsUTF16("😊")).toBe("😊\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C😊"); +}); + test("utf16 string", () => { expect(identity("😊 Smiling Face with Smiling Eyes Emoji")).toBe("😊 Smiling Face with Smiling Eyes Emoji"); }); + +// test("template string ascii", () => { +// expect(identity(`A${""}`)).toBe("A"); +// }); + +// test("template string latin1", () => { +// expect(identity(`©${""}`)).toBe("©"); +// }); diff --git a/test/transpiler/macro.ts b/test/transpiler/macro.ts index 8516d7d0df1887..fc747333cb64f5 100644 --- a/test/transpiler/macro.ts +++ b/test/transpiler/macro.ts @@ -1,3 +1,15 @@ export function identity(arg: any) { return arg; } + +export function escape() { + return "\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C"; +} + +export function addStrings(arg: string) { + return arg + "\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C" + "©"; +} + +export function addStringsUTF16(arg: string) { + return arg + "\\\f\n\r\t\v\0'\"`$\x00\x0B\x0C" + "😊"; +} diff --git a/test/transpiler/runtime-transpiler.test.ts b/test/transpiler/runtime-transpiler.test.ts new file mode 100644 index 00000000000000..c1881ee679c932 --- /dev/null +++ b/test/transpiler/runtime-transpiler.test.ts @@ -0,0 +1,32 @@ +import { beforeEach, describe, expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; + +describe("// @bun", () => { + beforeEach(() => { + delete require.cache[require.resolve("./async-transpiler-entry")]; + delete require.cache[require.resolve("./async-transpiler-imported")]; + }); + + test("async transpiler", async () => { + const { default: value, hbs } = await import("./async-transpiler-entry"); + expect(value).toBe(42); + expect(hbs).toBeString(); + }); + + test("require()", async () => { + const { default: value, hbs } = require("./async-transpiler-entry"); + expect(value).toBe(42); + expect(hbs).toBeString(); + }); + + test("synchronous", async () => { + const { stdout, exitCode } = Bun.spawnSync({ + cmd: [bunExe(), require.resolve("./async-transpiler-imported")], + cwd: import.meta.dir, + env: bunEnv, + stderr: "inherit", + }); + expect(stdout.toString()).toBe("Hello world!\n"); + expect(exitCode).toBe(0); + }); +}); diff --git a/test/tsconfig.json b/test/tsconfig.json index a5e77bf598ffb6..de9a0a544aea7c 100644 --- a/test/tsconfig.json +++ b/test/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true, "allowJs": true, "resolveJsonModule": true, + "noImplicitThis": false, "baseUrl": ".", "paths": { "harness": ["harness.ts"], diff --git a/tsconfig.json b/tsconfig.json index d8be0da039a5b6..fdef57bfe26673 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -20,5 +20,5 @@ "src/api/demo", "node_modules" ], - "files": ["src/js/builtins/builtins.d.ts"] + "files": ["src/js/builtins.d.ts"] }