diff options
author | 2022-01-19 02:29:07 -0800 | |
---|---|---|
committer | 2022-01-19 02:29:07 -0800 | |
commit | d3a93d527336af73df838d69ca42ad1b18adebb8 (patch) | |
tree | 726dad460bf4ee2608ffa9557943df11da56f8c3 | |
parent | ed9637de5056af4572ec5e0a75feee9ca858798e (diff) | |
download | bun-d3a93d527336af73df838d69ca42ad1b18adebb8.tar.gz bun-d3a93d527336af73df838d69ca42ad1b18adebb8.tar.zst bun-d3a93d527336af73df838d69ca42ad1b18adebb8.zip |
`fs.*Sync()`, `bun wiptest`, and More ™ (#106)
* very very wip
* almost ready to fix the errors
* Update identity_context.zig
* Update base.zig
* [bun test] It runs successfully
* Remove unnecessary call
* [Bun.js] Improve JS <> Zig unicode string interop
This fixes longstanding unicode bugs with `console.log` & `fetch`.
I believe @evanwashere reported this first awhile ago
* [Bun.js] Implement `Object.is()` binding and a way to set a timeout for script execution
* Update PLCrashReport.zig
* [Bun.js] Make `console.log` more closely match Node.js and Deno
* [Bun.js] Implement formatting specifier for console.*
* Implement `console.clear()`
* bug fix
* Support console.clear()
* Buffer stderr
* [bun test] Begin implementing Node.js `fs`
* Update darwin_c.zig
* Implement more of `fs`
* `mkdir`, `mkdir` recursive, `mkdtemp`
* `open`, `read` (and pread)
* Move some things into more files
* Implement readdir
* `readFile`, `readLink`, and `realpath`
* `writeFile`, `symlink`, `chown`, `rename`, `stat`, `unlink`, `truncate`
* `lutimes`
* Implement `SystemError` and begin wiring up the `fs` module
* `"fs"` - Most of the arguments / validation
* `fs` - Rest of the arguments / validations
* Begin wiring up the `fs` module
* Fix all the build errors
* support printing typed arrays in console.log
* It...works?
* Support `require("fs")`, `import fs from 'fs';`, `import * as fs from 'fs'`
* Fix a couple bugs
* get rid of the crash reporter for now
* Update fs.exports.js
* [bun.js] slight improvement to startup time
* [bun.js] Improve error message printing
* [Bun.js] Add `Bun.gc()` to run the garbage collector manually and report heap size
* [Bun.js] Add Bun.generateHeapSnapshot to return what JS types are using memory
* [Bun.js] Add `Bun.shrink()` to tell JSC to shrink the VM size
* Improve encoding reader
* [bun.js] Improve callback & microtask performance
* Update node_fs.zig
* Implement `console.assert`
* simple test
* [Bun.js] Prepare for multiple globals/realms to support testing
* Create callbacks-overhead.mjs
* Update http.zig
* [Bun.js] Implement `queueMicrotask`
* Add test for queueMicrotask
* :sleepy:
* [Bun.js] Implement `process.versions`, `process.pid`, `process.ppid`, `process.nextTick`, `process.versions`,
* Implement `process.env.toJSON()`
* [Bun.js] Improve performance of `fs.existsSync`
* :nail_care:
* [Bun.js] Implement `process.chdir(str)` and `process.cwd()`, support up to 4 args in `process.nextTick`
* Make creating Zig::Process lazy
* Split processi nto separte file
* [Bun.js] Node.js Streams - Part 1/?
* [Bun.js] Node.js streams 2/?
* WIP streams
* fix crash
* Reduce allocations in many places
* swap
* Make `bun` start 2ms faster
* Always use an apiLock()
* libBacktrace doesn't really work yet
* Fix crash in the upgrade checker
* Clean up code for importing the runtime when not bundling
* :camera:
* Update linker.zig
* 68!
* backtrace
* no, really backtrace
* Fix
* Linux fixes
* Fixes on Linux
* Update mimalloc
* [bun test] Automatically scan for {.test,_test,.spec,_spec}.{jsx,tsx,js,cts,mts,ts,cjs}
186 files changed, 17233 insertions, 2836 deletions
diff --git a/.gitmodules b/.gitmodules index ad817c2e0..9dd25dae9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -11,7 +11,7 @@ ignore = dirty [submodule "src/deps/mimalloc"] path = src/deps/mimalloc - url = https://github.com/microsoft/mimalloc.git + url = https://github.com/Jarred-Sumner/mimalloc.git ignore = dirty [submodule "src/deps/zlib"] path = src/deps/zlib @@ -24,4 +24,8 @@ [submodule "src/deps/boringssl"] path = src/deps/boringssl url = https://github.com/google/boringssl.git - ignore = dirty
\ No newline at end of file + ignore = dirty +[submodule "src/deps/libbacktrace"] + path = src/deps/libbacktrace + url = https://github.com/ianlancetaylor/libbacktrace + ignore = dirty diff --git a/.scripts/write-versions.sh b/.scripts/write-versions.sh new file mode 100644 index 000000000..af020f3f0 --- /dev/null +++ b/.scripts/write-versions.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -euxo pipefail + +WEBKIT_VERSION=$(git rev-parse HEAD:./src/javascript/jsc/WebKit) +MIMALLOC_VERSION=$(git rev-parse HEAD:./src/deps/mimalloc) +LIBARCHIVE_VERSION=$(git rev-parse HEAD:./src/deps/libarchive) +PICOHTTPPARSER_VERSION=$(git rev-parse HEAD:./src/deps/picohttpparser) +BORINGSSL_VERSION=$(git rev-parse HEAD:./src/deps/boringssl) +ZLIB_VERSION=$(git rev-parse HEAD:./src/deps/zlib) + +rm -rf src/generated_versions_list.zig +echo "// AUTO-GENERATED FILE. Created via .scripts/write-versions.sh" >src/generated_versions_list.zig +echo "" >>src/generated_versions_list.zig +echo "pub const webkit = \"$WEBKIT_VERSION\";" >>src/generated_versions_list.zig +echo "pub const mimalloc = \"$MIMALLOC_VERSION\";" >>src/generated_versions_list.zig +echo "pub const libarchive = \"$LIBARCHIVE_VERSION\";" >>src/generated_versions_list.zig +echo "pub const picohttpparser = \"$PICOHTTPPARSER_VERSION\";" >>src/generated_versions_list.zig +echo "pub const boringssl = \"$BORINGSSL_VERSION\";" >>src/generated_versions_list.zig +echo "pub const zlib = \"$ZLIB_VERSION\";" >>src/generated_versions_list.zig +echo "pub const zig = @import(\"std\").fmt.comptimePrint(\"{}\", .{@import(\"builtin\").zig_version});" >>src/generated_versions_list.zig +echo "" >>src/generated_versions_list.zig + +zig fmt src/generated_versions_list.zig diff --git a/.vscode/launch.json b/.vscode/launch.json index 54673976d..48d2a5d34 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,7 +1,6 @@ { "version": "0.2.0", "configurations": [ - { "type": "lldb", "request": "launch", @@ -61,8 +60,17 @@ "request": "launch", "name": "bun create debug", "program": "bun-debug", - "args": ["create", "hanford/trends", "foo"], - "cwd": "/tmp/", + "args": ["create", "next", "foo", "--open", "--force"], + "cwd": "/tmp", + "console": "internalConsole" + }, + { + "type": "lldb", + "request": "launch", + "name": "bun dev debug", + "program": "bun-debug", + "args": ["dev"], + "cwd": "/tmp/foo", "console": "internalConsole" }, { @@ -70,8 +78,9 @@ "request": "launch", "name": "bun run debug", "program": "bun-debug", - "args": ["paoskdpoasdk"], - "cwd": "/tmp/", + "args": ["run", "./integration/bunjs-only-snippets/some-fs.js"], + // "args": ["--version"], + "cwd": "${workspaceFolder}", "console": "internalConsole" }, { @@ -231,17 +240,49 @@ "request": "launch", "name": "Dazzle serve", "program": "bun-debug", - "args": ["--origin=http://localhost:5001", "--disable-bun.js", "--disable-hmr"], - "cwd": "/Users/jarred/Build/lattice/apps/dazzle", + "args": [ + "--origin=http://localhost:5001", + "--disable-bun.js", + "--disable-hmr" + ], + "cwd": "/Users/jarred/Build/big-app/apps/dazzle", "console": "internalConsole" }, { "type": "lldb", "request": "launch", - "name": "bun", + "name": "Dazzle bun", "program": "bun-debug", "args": ["bun", "--use=next"], - "cwd": "/Users/jarred/Build/lattice/apps/dazzle", + "cwd": "/Users/jarred/Build/big-app/apps/dazzle", + "console": "internalConsole", + "env": { "GOMAXPROCS": "1" } + }, + { + "type": "lldb", + "request": "launch", + "name": "bun run", + "program": "bun-debug", + "args": ["cat.js", "./node_modules/@babel/standalone/babel.js"], + "cwd": "/Users/jarred/Build/foobar", + "console": "internalConsole" + }, + { + "type": "lldb", + "request": "launch", + "name": "bun run callback bench", + "program": "bun-debug", + "args": ["/Users/jarred/Code/bun/bench/snippets/callbacks-overhead.mjs"], + "cwd": "/Users/jarred/Build/foobar", + "console": "internalConsole" + }, + { + "type": "lldb", + "request": "launch", + "name": "bun test", + "program": "bun-debug", + "args": ["wiptest", "import-meta"], + "cwd": "${workspaceFolder}", "console": "internalConsole" }, { @@ -367,9 +408,7 @@ "program": "bun-debug", "args": ["install", "--backend=clonefile", "--force"], "cwd": "/Users/jarred/Build/octokit-test", - "env": { - - }, + "env": {}, "console": "internalConsole" }, { @@ -379,8 +418,7 @@ "program": "bun-debug", "args": ["add", "typescript"], "cwd": "/tmp/wow-such-npm", - "env": { - }, + "env": {}, "console": "internalConsole" }, { @@ -390,8 +428,7 @@ "program": "bun-debug", "args": ["add", "react"], "cwd": "/tmp/wow-such-npm", - "env": { - }, + "env": {}, "console": "internalConsole" }, { @@ -401,8 +438,7 @@ "program": "bun-debug", "args": ["remove", "foo"], "cwd": "/Users/jarred/Build/athena.yarn", - "env": { - }, + "env": {}, "console": "internalConsole" }, { @@ -414,7 +450,6 @@ "cwd": "/tmp/wow-such-npm", "env": { "BUN_CONFIG_SKIP_SAVE_LOCKFILE": "1" - }, "console": "internalConsole" }, @@ -530,7 +565,6 @@ "cwd": "${workspaceFolder}/src/test/fixtures", "console": "internalConsole" }, - // { // "type": "lldb", diff --git a/.vscode/settings.json b/.vscode/settings.json index e7b921d79..bd7699e02 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -8,7 +8,7 @@ "search.useIgnoreFiles": true, "zig.buildOnSave": false, "[zig]": { - "editor.defaultFormatter": "tiehuis.zig" + "editor.defaultFormatter": "AugusteRame.zls-vscode" }, "[ts]": { "editor.defaultFormatter": "esbenp.prettier-vscode" @@ -11,6 +11,7 @@ endif MIN_MACOS_VERSION = 10.14 + MARCH_NATIVE = ARCH_NAME := @@ -73,7 +74,7 @@ OPENSSL_LINUX_DIR = $(BUN_DEPS_DIR)/openssl/openssl-OpenSSL_1_1_1l CMAKE_FLAGS_WITHOUT_RELEASE = -DCMAKE_C_COMPILER=$(CC) -DCMAKE_CXX_COMPILER=$(CXX) -DCMAKE_OSX_DEPLOYMENT_TARGET=$(MIN_MACOS_VERSION) CMAKE_FLAGS = $(CMAKE_FLAGS_WITHOUT_RELEASE) -DCMAKE_BUILD_TYPE=Release -CFLAGS = $(MACOS_MIN_FLAG) + LIBTOOL=libtoolize ifeq ($(OS_NAME),darwin) @@ -84,6 +85,8 @@ ifeq ($(OS_NAME),linux) LIBICONV_PATH = endif + +CFLAGS = $(MACOS_MIN_FLAG) $(MARCH_NATIVE) -ffunction-sections -fdata-sections -g -O3 BUN_TMP_DIR := /tmp/make-bun BUN_DEPLOY_DIR = /tmp/bun-v$(PACKAGE_JSON_VERSION)/$(PACKAGE_NAME) @@ -111,10 +114,12 @@ ZLIB_LIB_DIR ?= $(BUN_DEPS_DIR)/zlib JSC_FILES := $(JSC_LIB)/libJavaScriptCore.a $(JSC_LIB)/libWTF.a $(JSC_LIB)/libbmalloc.a +ENABLE_MIMALLOC ?= 1 + # https://github.com/microsoft/mimalloc/issues/512 # Linking mimalloc via object file on macOS x64 can cause heap corruption -MIMALLOC_FILE = libmimalloc.o -MIMALLOC_INPUT_PATH = CMakeFiles/mimalloc-obj.dir/src/static.c.o +_MIMALLOC_FILE = libmimalloc.o +_MIMALLOC_INPUT_PATH = CMakeFiles/mimalloc-obj.dir/src/static.c.o DEFAULT_LINKER_FLAGS = @@ -125,11 +130,23 @@ DEFAULT_LINKER_FLAGS= -pthread -ldl endif ifeq ($(OS_NAME),darwin) JSC_BUILD_STEPS += jsc-build-mac jsc-copy-headers - MIMALLOC_FILE = libmimalloc.a - MIMALLOC_INPUT_PATH = libmimalloc.a + _MIMALLOC_FILE = libmimalloc.a + _MIMALLOC_INPUT_PATH = libmimalloc.a +endif + +MIMALLOC_FILE= +MIMALLOC_INPUT_PATH= +MIMALLOC_FILE_PATH= +ifeq ($(ENABLE_MIMALLOC), 1) +MIMALLOC_FILE=$(_MIMALLOC_FILE) +MIMALLOC_FILE_PATH=$(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE) +MIMALLOC_INPUT_PATH=$(_MIMALLOC_INPUT_PATH) endif + + + MACOSX_DEPLOYMENT_TARGET=$(MIN_MACOS_VERSION) MACOS_MIN_FLAG= @@ -207,28 +224,34 @@ CLANG_FLAGS = $(INCLUDE_DIRS) \ -DENABLE_INSPECTOR_ALTERNATE_DISPATCHERS=0 \ -DBUILDING_JSCONLY__ \ -DASSERT_ENABLED=0 \ - -fPIE + -fvisibility=hidden \ + -fvisibility-inlines-hidden \ + -fno-omit-frame-pointer $(CFLAGS) # This flag is only added to webkit builds on Apple platforms # It has something to do with ICU ifeq ($(OS_NAME), darwin) CLANG_FLAGS += -DDU_DISABLE_RENAMING=1 \ - $(MACOS_MIN_FLAG) -lstdc++ + -lstdc++ \ + -ffunction-sections \ + -fdata-sections \ + -Wl,-no_eh_labels \ + -Wl,-dead_strip \ + -Wl,-dead_strip_dylibs \ + -force_flat_namespace endif -ARCHIVE_FILES_WITHOUT_LIBCRYPTO = $(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE) \ +ARCHIVE_FILES_WITHOUT_LIBCRYPTO = $(MIMALLOC_FILE_PATH) \ $(BUN_DEPS_OUT_DIR)/libz.a \ $(BUN_DEPS_OUT_DIR)/libarchive.a \ $(BUN_DEPS_OUT_DIR)/libssl.a \ $(BUN_DEPS_OUT_DIR)/picohttpparser.o \ + $(BUN_DEPS_OUT_DIR)/libbacktrace.a ARCHIVE_FILES = $(ARCHIVE_FILES_WITHOUT_LIBCRYPTO) $(BUN_DEPS_OUT_DIR)/libcrypto.boring.a -ifeq ($(OS_NAME), darwin) -ARCHIVE_FILES += $(BUN_DEPS_OUT_DIR)/libCrashReporter.a $(BUN_DEPS_OUT_DIR)/libCrashReporter.bindings.a -endif PLATFORM_LINKER_FLAGS = @@ -238,7 +261,6 @@ ifeq ($(OS_NAME), linux) PLATFORM_LINKER_FLAGS = \ -fuse-ld=lld \ -lc \ - -fno-omit-frame-pointer \ -Wl,-z,now \ -Wl,--as-needed \ -Wl,--gc-sections \ @@ -250,6 +272,11 @@ PLATFORM_LINKER_FLAGS = \ ${STATIC_MUSL_FLAG} endif +ifeq ($(OS_NAME), darwin) +PLATFORM_LINKER_FLAGS = \ + -Wl,-keep_private_externs +endif + BUN_LLD_FLAGS = $(OBJ_FILES) \ ${ICU_FLAGS} \ @@ -264,10 +291,10 @@ BUN_LLD_FLAGS = $(OBJ_FILES) \ bun: -vendor-without-check: api analytics node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp zlib boringssl libarchive pl-crash-report +vendor-without-check: api analytics node-fallbacks runtime_js fallback_decoder bun_error mimalloc picohttp zlib boringssl libarchive libbacktrace boringssl-build: - cd $(BUN_DEPS_DIR)/boringssl && mkdir -p build && cd build && cmake $(CMAKE_FLAGS) -GNinja .. && ninja + cd $(BUN_DEPS_DIR)/boringssl && mkdir -p build && cd build && CFLAGS="$(CFLAGS)" cmake $(CMAKE_FLAGS) -GNinja .. && ninja boringssl-copy: cp $(BUN_DEPS_DIR)/boringssl/build/ssl/libssl.a $(BUN_DEPS_OUT_DIR)/libssl.a @@ -275,32 +302,19 @@ boringssl-copy: boringssl: boringssl-build boringssl-copy -download-pl-crash-report: - rm -rf /tmp/PLCrashReporter.zip /tmp/PLCrashReporter - curl -L https://github.com/microsoft/plcrashreporter/releases/download/1.10.1/PLCrashReporter-Static-1.10.1.zip > /tmp/PLCrashReporter.zip - unzip /tmp/PLCrashReporter.zip -d /tmp - cp /tmp/PLCrashReporter/libCrashReporter-MacOSX-Static.a $(BUN_DEPS_OUT_DIR)/libCrashReporter.a - mkdir -p $(BUN_DEPS_DIR)/PLCrashReporter/include/PLCrashReporter - cp -r /tmp/PLCrashReporter/include/*.h $(BUN_DEPS_DIR)/PLCrashReporter/include/PLCrashReporter - -pl-crash-report: - -ifeq ($(OS_NAME), darwin) -pl-crash-report: pl-crash-report-mac -endif - -pl-crash-report-mac: download-pl-crash-report pl-crash-report-mac-compile - -pl-crash-report-mac-compile: - $(CC) $(MACOS_MIN_FLAG) -O3 -ObjC -I$(BUN_DEPS_DIR)/PLCrashReporter/include -I$(BUN_DEPS_DIR)/PLCrashReporter -c $(BUN_DEPS_DIR)/PLCrashReport.m \ - -g -o $(BUN_DEPS_OUT_DIR)/libCrashReporter.bindings.a +libbacktrace: + cd $(BUN_DEPS_DIR)/libbacktrace && \ + (make clean || echo "") && \ + CFLAGS="$(CFLAGS)" CC=$(CC) ./configure --disable-shared --enable-static --with-pic && \ + make -j$(CPUS) && \ + cp ./.libs/libbacktrace.a $(BUN_DEPS_OUT_DIR)/libbacktrace.a libarchive: cd $(BUN_DEPS_DIR)/libarchive; \ (make clean || echo ""); \ (./build/clean.sh || echo ""); \ ./build/autogen.sh; \ - CFLAGS=$(CFLAGS) CC=$(CC) ./configure --disable-shared --enable-static --with-pic --disable-bsdtar --disable-bsdcat --disable-rpath --enable-posix-regex-lib --without-xml2 --without-expat --without-openssl --without-iconv --without-zlib; \ + CFLAGS="$(CFLAGS)" CC=$(CC) ./configure --disable-shared --enable-static --with-pic --disable-bsdtar --disable-bsdcat --disable-rpath --enable-posix-regex-lib --without-xml2 --without-expat --without-openssl --without-iconv --without-zlib; \ make -j${CPUS}; \ cp ./.libs/libarchive.a $(BUN_DEPS_OUT_DIR)/libarchive.a; @@ -317,7 +331,7 @@ tgz-debug: vendor: require init-submodules vendor-without-check zlib: - cd $(BUN_DEPS_DIR)/zlib; cmake $(CMAKE_FLAGS) .; make CFLAGS=$(CFLAGS); + cd $(BUN_DEPS_DIR)/zlib; CFLAGS="$(CFLAGS)" cmake $(CMAKE_FLAGS) .; CFLAGS="$(CFLAGS)" make; cp $(BUN_DEPS_DIR)/zlib/libz.a $(BUN_DEPS_OUT_DIR)/libz.a docker-login: @@ -362,7 +376,7 @@ sign-macos-aarch64: cls: @echo "\n\n---\n\n" -release: all-js jsc-bindings-mac build-obj cls bun-link-lld-release release-bin-entitlements +release: all-js jsc-bindings-mac build-obj cls bun-link-lld-release bun-link-lld-release-dsym release-bin-entitlements jsc-check: @ls $(JSC_BASE_DIR) >/dev/null 2>&1 || (echo "Failed to access WebKit build. Please compile the WebKit submodule using the Dockerfile at $(shell pwd)/src/javascript/WebKit/Dockerfile and then copy from /output in the Docker container to $(JSC_BASE_DIR). You can override the directory via JSC_BASE_DIR. \n\n DOCKER_BUILDKIT=1 docker build -t bun-webkit $(shell pwd)/src/javascript/jsc/WebKit -f $(shell pwd)/src/javascript/jsc/WebKit/Dockerfile --progress=plain\n\n docker container create bun-webkit\n\n # Get the container ID\n docker container ls\n\n docker cp DOCKER_CONTAINER_ID_YOU_JUST_FOUND:/output $(JSC_BASE_DIR)" && exit 1) @@ -645,9 +659,30 @@ jsc-force-fastjit: $(SED) -i "s/USE(PTHREAD_JIT_PERMISSIONS_API)/CPU(ARM64)/g" $(WEBKIT_DIR)/Source/JavaScriptCore/jit/ExecutableAllocator.h $(SED) -i "s/USE(PTHREAD_JIT_PERMISSIONS_API)/CPU(ARM64)/g" $(WEBKIT_DIR)/Source/JavaScriptCore/assembler/FastJITPermissions.h $(SED) -i "s/USE(PTHREAD_JIT_PERMISSIONS_API)/CPU(ARM64)/g" $(WEBKIT_DIR)/Source/JavaScriptCore/jit/ExecutableAllocator.cpp + $(SED) -i "s/GIGACAGE_ENABLED/0/g" $(WEBKIT_DIR)/Source/JavaScriptCore/Gigacage.h jsc-build-mac-compile: - cd $(WEBKIT_DIR) && ICU_INCLUDE_DIRS="$(HOMEBREW_PREFIX)opt/icu4c/include" ./Tools/Scripts/build-jsc --jsc-only --cmakeargs="-DENABLE_STATIC_JSC=ON -DCMAKE_BUILD_TYPE=relwithdebinfo -DPTHREAD_JIT_PERMISSIONS_API=1 -DUSE_PTHREAD_JIT_PERMISSIONS_API=ON $(CMAKE_FLAGS_WITHOUT_RELEASE)" + mkdir -p $(WEBKIT_RELEASE_DIR) $(WEBKIT_DIR); + cd $(WEBKIT_RELEASE_DIR) && \ + ICU_INCLUDE_DIRS="$(HOMEBREW_PREFIX)opt/icu4c/include" \ + CMAKE_BUILD_TYPE=Release cmake \ + -DPORT="JSCOnly" \ + -DENABLE_STATIC_JSC=ON \ + -DCMAKE_BUILD_TYPE=Release \ + -DUSE_THIN_ARCHIVES=OFF \ + -DENABLE_FTL_JIT=ON \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ + -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + $(CMAKE_FLAGS_WITHOUT_RELEASE) \ + -DPTHREAD_JIT_PERMISSIONS_API=1 \ + -DUSE_PTHREAD_JIT_PERMISSIONS_API=ON \ + -DCMAKE_BUILD_TYPE=Release \ + $(WEBKIT_DIR) \ + $(WEBKIT_RELEASE_DIR) && \ + CFLAGS="$CFLAGS -ffat-lto-objects" CXXFLAGS="$CXXFLAGS -ffat-lto-objects" \ + cmake --build $(WEBKIT_RELEASE_DIR) --config Release --target jsc + jsc-build-linux-compile-config: mkdir -p $(WEBKIT_RELEASE_DIR) cd $(WEBKIT_RELEASE_DIR) && \ @@ -698,7 +733,7 @@ jsc-bindings-mac: $(OBJ_FILES) # mimalloc is built as object files so that it can overload the system malloc mimalloc: - cd $(BUN_DEPS_DIR)/mimalloc; cmake $(CMAKE_FLAGS) -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=ON .; make; + cd $(BUN_DEPS_DIR)/mimalloc; CFLAGS="$(CFLAGS)" cmake $(CMAKE_FLAGS) -DMI_SKIP_COLLECT_ON_EXIT=ON -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -DMI_BUILD_OBJECT=ON ${MIMALLOC_OVERRIDE_FLAG} -DMI_USE_CXX=ON .; make; cp $(BUN_DEPS_DIR)/mimalloc/$(MIMALLOC_INPUT_PATH) $(BUN_DEPS_OUT_DIR)/$(MIMALLOC_FILE) bun-link-lld-debug: @@ -712,7 +747,7 @@ bun-link-lld-debug: bun-relink-copy: cp /tmp/bun-$(PACKAGE_JSON_VERSION).o $(BUN_RELEASE_BIN).o -bun-relink: bun-relink-copy bun-link-lld-release + bun-link-lld-release: $(CXX) $(BUN_LLD_FLAGS) \ @@ -724,24 +759,40 @@ bun-link-lld-release: -O3 rm -rf $(BUN_RELEASE_BIN).dSYM cp $(BUN_RELEASE_BIN) $(BUN_RELEASE_BIN)-profile - $(DSYMUTIL) --flat $(BUN_RELEASE_BIN) -o $(BUN_RELEASE_BIN).dSYM + +ifeq ($(OS_NAME),darwin) +bun-link-lld-release-dsym: + $(DSYMUTIL) -o $(BUN_RELEASE_BIN).dSYM $(BUN_RELEASE_BIN) -$(STRIP) $(BUN_RELEASE_BIN) mv $(BUN_RELEASE_BIN).o /tmp/bun-$(PACKAGE_JSON_VERSION).o +endif + +ifeq ($(OS_NAME),linux) +bun-link-lld-release-dsym: + -$(STRIP) $(BUN_RELEASE_BIN) + mv $(BUN_RELEASE_BIN).o /tmp/bun-$(PACKAGE_JSON_VERSION).o +endif + + +bun-relink: bun-relink-copy bun-link-lld-release bun-link-lld-release-dsym + + # We do this outside of build.zig for performance reasons # The C compilation stuff with build.zig is really slow and we don't need to run this as often as the rest $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(CXX) -c -o $@ $< \ $(CLANG_FLAGS) $(PLATFORM_LINKER_FLAGS) \ - -O3 \ - -w + -O1 \ + -fvectorize \ + -w -g sizegen: $(CXX) src/javascript/jsc/headergen/sizegen.cpp -o $(BUN_TMP_DIR)/sizegen $(CLANG_FLAGS) -O1 $(BUN_TMP_DIR)/sizegen > src/javascript/jsc/bindings/sizes.zig picohttp: - $(CC) $(MARCH_NATIVE) $(MACOS_MIN_FLAG) -O3 -g -fPIE -c $(BUN_DEPS_DIR)/picohttpparser/picohttpparser.c -I$(BUN_DEPS_DIR) -o $(BUN_DEPS_OUT_DIR)/picohttpparser.o; cd ../../ + $(CC) $(CFLAGS) -O3 -g -fPIC -c $(BUN_DEPS_DIR)/picohttpparser/picohttpparser.c -I$(BUN_DEPS_DIR) -o $(BUN_DEPS_OUT_DIR)/picohttpparser.o; cd ../../ analytics: ./node_modules/.bin/peechy --schema src/analytics/schema.peechy --zig src/analytics/analytics_schema.zig diff --git a/bench/snippets/callbacks-overhead.mjs b/bench/snippets/callbacks-overhead.mjs new file mode 100644 index 000000000..65171145c --- /dev/null +++ b/bench/snippets/callbacks-overhead.mjs @@ -0,0 +1,78 @@ +const iterations = 1_000; + +export var report = { + async: 0, + callback: 0, + sync: 0, + then: 0, +}; + +const tests = { + callback(n, cb) { + if (n === iterations) return cb(); + tests.callback(1 + n, () => cb()); + }, + + sync(n) { + if (n === iterations) return; + + tests.sync(1 + n); + }, + + async async(n) { + if (n === iterations) return; + + await tests.async(1 + n); + }, + + then(n) { + if (n === iterations) return; + return Promise.resolve(1 + n).then(tests.then); + }, +}; + +async function test(log) { + { + const a = performance.now(); + await tests.async(0); + if (log) + console.log( + `async/await: ${(report.async = (performance.now() - a).toFixed(4))}ms` + ); + } + + { + const a = performance.now(); + tests.callback(0, function () { + if (log) + console.log( + `callback: ${(report.callback = (performance.now() - a).toFixed( + 4 + ))}ms` + ); + }); + } + + { + const a = performance.now(); + await tests.then(0); + if (log) + console.log( + `then: ${(report.then = (performance.now() - a).toFixed(4))}ms` + ); + } + + { + const a = performance.now(); + tests.sync(0); + if (log) + console.log( + `sync: ${(report.sync = (performance.now() - a).toFixed(4))}ms` + ); + } +} + +let warmup = 10; +while (warmup--) await test(); + +await test(true); diff --git a/bench/snippets/exists.js b/bench/snippets/exists.js new file mode 100644 index 000000000..1d1d6cfe0 --- /dev/null +++ b/bench/snippets/exists.js @@ -0,0 +1,6 @@ +const { existsSync } = require("fs"); +const cwd = process.cwd(); + +const count = parseInt(process.env.ITERATIONS || "1", 10) || 1; + +for (let i = 0; i < count; i++) existsSync(cwd); @@ -1 +1 @@ -67 +68 @@ -51,14 +51,9 @@ fn addInternalPackages(step: *std.build.LibExeObjStep, _: std.mem.Allocator, tar .path = pkgPath("src/thread_pool.zig"), }; - var crash_reporter_mac: std.build.Pkg = .{ + var crash_reporter: std.build.Pkg = .{ .name = "crash_reporter", - .path = pkgPath("src/deps/PLCrashReport.zig"), - }; - - var crash_reporter_linux: std.build.Pkg = .{ - .name = "crash_reporter", - .path = pkgPath("src/deps/crash_reporter_linux.zig"), + .path = pkgPath("src/deps/backtrace.zig"), }; var picohttp: std.build.Pkg = .{ @@ -80,11 +75,6 @@ fn addInternalPackages(step: *std.build.LibExeObjStep, _: std.mem.Allocator, tar else io_linux; - var crash_reporter = if (target.isDarwin()) - crash_reporter_mac - else - crash_reporter_linux; - var strings: std.build.Pkg = .{ .name = "strings", .path = pkgPath("src/string_immutable.zig"), @@ -104,7 +94,7 @@ fn addInternalPackages(step: *std.build.LibExeObjStep, _: std.mem.Allocator, tar .name = "javascript_core", .path = pkgPath("src/jsc.zig"), }; - javascript_core.dependencies = &.{ http, strings, picohttp }; + javascript_core.dependencies = &.{ http, strings, picohttp, io }; http.dependencies = &.{ strings, picohttp, @@ -283,6 +273,7 @@ pub fn build(b: *std.build.Builder) !void { obj.strip = false; obj.bundle_compiler_rt = true; + obj.omit_frame_pointer = false; b.default_step.dependOn(&obj.step); @@ -292,6 +283,7 @@ pub fn build(b: *std.build.Builder) !void { obj.link_eh_frame_hdr = true; obj.link_function_sections = true; } + var log_step = b.addLog("Destination: {s}/{s}\n", .{ output_dir, bun_executable_name }); log_step.step.dependOn(&obj.step); } @@ -422,8 +414,7 @@ pub fn linkObjectFiles(b: *std.build.Builder, obj: *std.build.LibExeObjStep, tar .{ "libJavaScriptCore.a", "libJavaScriptCore.a" }, .{ "libWTF.a", "libWTF.a" }, .{ "libbmalloc.a", "libbmalloc.a" }, - .{ "libCrashReporter.a", "libCrashReporter.a" }, - .{ "libCrashReporter.bindings.a", "libCrashReporter.bindings.a" }, + .{ "libbacktrace.a", "libbacktrace.a" }, }); for (dirs_to_search.slice()) |deps_path| { diff --git a/fs-test/writeFileSync.txt b/fs-test/writeFileSync.txt new file mode 100644 index 000000000..b1759f75a --- /dev/null +++ b/fs-test/writeFileSync.txt @@ -0,0 +1 @@ +utf8
\ No newline at end of file diff --git a/integration/bunjs-only-snippets/console-log.js b/integration/bunjs-only-snippets/console-log.js new file mode 100644 index 000000000..e8aa200ac --- /dev/null +++ b/integration/bunjs-only-snippets/console-log.js @@ -0,0 +1,58 @@ +console.log("Hello World!"); +console.log(123); +console.log(-123); +console.log(123.567); +console.log(-123.567); +console.log(true); +console.log(false); +console.log(null); +console.log(undefined); +console.log(Symbol("Symbol Description")); +console.log(new Date(2021, 12, 30, 666, 777, 888, 999)); +console.log([123, 456, 789]); +console.log({ a: 123, b: 456, c: 789 }); +console.log({ + a: { + b: { + c: 123, + }, + bacon: true, + }, +}); + +console.log(new Promise(() => {})); + +class Foo {} + +console.log(() => {}); +console.log(Foo); +console.log(new Foo()); +console.log(function foooo() {}); + +console.log(/FooRegex/); + +console.error("uh oh"); +console.time("Check"); + +console.log( + "Is it a bug or a feature that formatting numbers like %d is colored", + 123 +); +console.log(globalThis); + +console.log( + "String %s should be 2nd word, 456 == %s and percent s %s == %s", + "123", + "456", + "%s", + "What", + "okay" +); + +const infinteLoop = { + foo: {}, + bar: {}, +}; + +infinteLoop.bar = infinteLoop; +console.log(infinteLoop, "am"); diff --git a/integration/bunjs-only-snippets/fetch.js b/integration/bunjs-only-snippets/fetch.js new file mode 100644 index 000000000..cc83b5af4 --- /dev/null +++ b/integration/bunjs-only-snippets/fetch.js @@ -0,0 +1,14 @@ +import fs from "fs"; + +const response = await fetch("http://example.com/"); +const text = await response.text(); + +if ( + fs.readFileSync( + import.meta.path.substring(0, import.meta.path.lastIndexOf("/")) + + "/fetch.js.txt", + "utf8" + ) !== text +) { + throw new Error("Expected fetch.js.txt to match snapshot"); +} diff --git a/integration/bunjs-only-snippets/fetch.js.txt b/integration/bunjs-only-snippets/fetch.js.txt new file mode 100644 index 000000000..5a9b52fcf --- /dev/null +++ b/integration/bunjs-only-snippets/fetch.js.txt @@ -0,0 +1,46 @@ +<!doctype html> +<html> +<head> + <title>Example Domain</title> + + <meta charset="utf-8" /> + <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <style type="text/css"> + body { + background-color: #f0f0f2; + margin: 0; + padding: 0; + font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + + } + div { + width: 600px; + margin: 5em auto; + padding: 2em; + background-color: #fdfdff; + border-radius: 0.5em; + box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02); + } + a:link, a:visited { + color: #38488f; + text-decoration: none; + } + @media (max-width: 700px) { + div { + margin: 0 auto; + width: auto; + } + } + </style> +</head> + +<body> +<div> + <h1>Example Domain</h1> + <p>This domain is for use in illustrative examples in documents. You may use this + domain in literature without prior coordination or asking for permission.</p> + <p><a href="https://www.iana.org/domains/example">More information...</a></p> +</div> +</body> +</html> diff --git a/integration/bunjs-only-snippets/fs-stream.js b/integration/bunjs-only-snippets/fs-stream.js new file mode 100644 index 000000000..4b71c95b7 --- /dev/null +++ b/integration/bunjs-only-snippets/fs-stream.js @@ -0,0 +1,23 @@ +import { createReadStream, createWriteStream, readFileSync } from "fs"; + +await new Promise((resolve, reject) => { + createReadStream("fs-stream.js") + .pipe(createWriteStream("/tmp/fs-stream.copy.js")) + .once("error", (err) => reject(err)) + .once("finish", () => { + try { + const copied = readFileSync("/tmp/fs-stream.copy.js", "utf8"); + const real = readFileSync("/tmp/fs-stream.js", "utf8"); + if (copied !== real) { + reject( + new Error("fs-stream.js is not the same as fs-stream.copy.js") + ); + return; + } + + resolve(true); + } catch (err) { + reject(err); + } + }); +}); diff --git a/integration/bunjs-only-snippets/fs.test.js b/integration/bunjs-only-snippets/fs.test.js new file mode 100644 index 000000000..4fc5c9e91 --- /dev/null +++ b/integration/bunjs-only-snippets/fs.test.js @@ -0,0 +1,35 @@ +import { describe, it, expect } from "bun:test"; +import { + mkdirSync, + existsSync, + readFileSync, + mkdtempSync, + writeFileSync, +} from "node:fs"; + +const tmp = mkdtempSync("fs-test"); + +describe("mkdirSync", () => { + it("should create a directory", () => { + const tempdir = `${tmp}/1234/hi`; + expect(existsSync(tempdir)).toBe(false); + expect(tempdir.includes(mkdirSync(tempdir, { recursive: true }))).toBe( + true + ); + expect(existsSync(tempdir)).toBe(true); + }); +}); + +describe("readFileSync", () => { + it("works", () => { + const text = readFileSync(import.meta.dir + "/readFileSync.txt", "utf8"); + expect(text).toBe("File read successfully"); + }); +}); + +describe("writeFileSync", () => { + it("works", () => { + const text = writeFileSync(`${tmp}/writeFileSync.txt`, "utf8"); + expect(text).toBe("File read successfully"); + }); +}); diff --git a/integration/bunjs-only-snippets/import-meta.test.js b/integration/bunjs-only-snippets/import-meta.test.js new file mode 100644 index 000000000..226dd396b --- /dev/null +++ b/integration/bunjs-only-snippets/import-meta.test.js @@ -0,0 +1,13 @@ +import { it, expect } from "bun:test"; + +const { path, dir } = import.meta; + +it("import.meta.dir", () => { + expect(dir.endsWith("/bun/integration/bunjs-only-snippets")).toBe(true); +}); + +it("import.meta.path", () => { + expect( + path.endsWith("/bun/integration/bunjs-only-snippets/import-meta.test.js") + ).toBe(true); +}); diff --git a/integration/bunjs-only-snippets/microtask.js b/integration/bunjs-only-snippets/microtask.js new file mode 100644 index 000000000..c5acfd578 --- /dev/null +++ b/integration/bunjs-only-snippets/microtask.js @@ -0,0 +1,76 @@ +// You can verify this test is correct by copy pasting this into a browser's console and checking it doesn't throw an error. +var run = 0; + +await new Promise((resolve, reject) => { + queueMicrotask(() => { + if (run++ != 0) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + queueMicrotask(() => { + if (run++ != 3) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + }); + }); + queueMicrotask(() => { + if (run++ != 1) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + queueMicrotask(() => { + if (run++ != 4) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + + queueMicrotask(() => { + if (run++ != 6) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + }); + }); + }); + queueMicrotask(() => { + if (run++ != 2) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + queueMicrotask(() => { + if (run++ != 5) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + + queueMicrotask(() => { + if (run++ != 7) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + resolve(true); + }); + }); + }); +}); + +{ + var passed = false; + try { + queueMicrotask(1234); + } catch (exception) { + passed = exception instanceof TypeError; + } + + if (!passed) + throw new Error( + "queueMicrotask should throw a TypeError if the argument is not a function" + ); +} + +{ + var passed = false; + try { + queueMicrotask(); + } catch (exception) { + passed = exception instanceof TypeError; + } + + if (!passed) + throw new Error( + "queueMicrotask should throw a TypeError if the argument is empty" + ); +} diff --git a/integration/bunjs-only-snippets/process-nexttick.js b/integration/bunjs-only-snippets/process-nexttick.js new file mode 100644 index 000000000..337977c0a --- /dev/null +++ b/integration/bunjs-only-snippets/process-nexttick.js @@ -0,0 +1,91 @@ +// You can verify this test is correct by copy pasting this into a browser's console and checking it doesn't throw an error. +var run = 0; + +var queueMicrotask = process.nextTick; + +await new Promise((resolve, reject) => { + queueMicrotask(() => { + if (run++ != 0) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + queueMicrotask(() => { + if (run++ != 3) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + }); + }); + queueMicrotask(() => { + if (run++ != 1) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + queueMicrotask(() => { + if (run++ != 4) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + + queueMicrotask(() => { + if (run++ != 6) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + }); + }); + }); + queueMicrotask(() => { + if (run++ != 2) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + queueMicrotask(() => { + if (run++ != 5) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + + queueMicrotask(() => { + if (run++ != 7) { + reject(new Error("Microtask execution order is wrong: " + run)); + } + resolve(true); + }); + }); + }); +}); + +{ + var passed = false; + try { + queueMicrotask(1234); + } catch (exception) { + passed = exception instanceof TypeError; + } + + if (!passed) + throw new Error( + "queueMicrotask should throw a TypeError if the argument is not a function" + ); +} + +{ + var passed = false; + try { + queueMicrotask(); + } catch (exception) { + passed = exception instanceof TypeError; + } + + if (!passed) + throw new Error( + "queueMicrotask should throw a TypeError if the argument is empty" + ); +} + +await new Promise((resolve, reject) => { + process.nextTick( + (first, second) => { + console.log(first, second); + if (first !== 12345 || second !== "hello") + reject(new Error("process.nextTick called with wrong arguments")); + resolve(true); + }, + 12345, + "hello" + ); +}); diff --git a/integration/bunjs-only-snippets/process.js b/integration/bunjs-only-snippets/process.js new file mode 100644 index 000000000..486d20f46 --- /dev/null +++ b/integration/bunjs-only-snippets/process.js @@ -0,0 +1,48 @@ +// this property isn't implemented yet but it should at least return a string +const isNode = !process.isBun; + +if (!isNode && process.title !== "bun") + throw new Error("process.title is not 'bun'"); + +if (typeof process.env.USER !== "string") + throw new Error("process.env is not an object"); + +if (process.env.USER.length === 0) + throw new Error("process.env is missing a USER property"); + +if (process.platform !== "darwin" && process.platform !== "linux") + throw new Error("process.platform is invalid"); + +if (isNode) throw new Error("process.isBun is invalid"); + +// partially to test it doesn't crash due to various strange types +process.env.BACON = "yummy"; +if (process.env.BACON !== "yummy") { + throw new Error("process.env is not writable"); +} + +delete process.env.BACON; +if (typeof process.env.BACON !== "undefined") { + throw new Error("process.env is not deletable"); +} + +process.env.BACON = "yummy"; +if (process.env.BACON !== "yummy") { + throw new Error("process.env is not re-writable"); +} + +if (JSON.parse(JSON.stringify(process.env)).BACON !== "yummy") { + throw new Error("process.env is not serializable"); +} + +if (typeof JSON.parse(JSON.stringify(process.env)).toJSON !== "undefined") { + throw new Error("process.env should call toJSON to hide its internal state"); +} + +var { env, ...proces } = process; +console.log(JSON.stringify(proces, null, 2)); +console.log(proces); + +console.log("CWD", process.cwd()); +console.log("SET CWD", process.chdir("../")); +console.log("CWD", process.cwd()); diff --git a/integration/bunjs-only-snippets/readFileSync.txt b/integration/bunjs-only-snippets/readFileSync.txt new file mode 100644 index 000000000..ddc94b988 --- /dev/null +++ b/integration/bunjs-only-snippets/readFileSync.txt @@ -0,0 +1 @@ +File read successfully
\ No newline at end of file diff --git a/integration/bunjs-only-snippets/readdir.js b/integration/bunjs-only-snippets/readdir.js new file mode 100644 index 000000000..18c111d0a --- /dev/null +++ b/integration/bunjs-only-snippets/readdir.js @@ -0,0 +1,9 @@ +const { readdirSync } = require("fs"); + +const count = parseInt(process.env.ITERATIONS || "1", 10) || 1; + +for (let i = 0; i < count; i++) { + readdirSync("."); +} + +console.log(readdirSync(".")); diff --git a/integration/bunjs-only-snippets/sleep.js b/integration/bunjs-only-snippets/sleep.js index 9a62201c5..080597424 100644 --- a/integration/bunjs-only-snippets/sleep.js +++ b/integration/bunjs-only-snippets/sleep.js @@ -1,7 +1,7 @@ -const interval = 0.5; +const interval = 0.01; const now = performance.now(); console.time("Slept"); -Bun.sleep(interval); +Bun.sleepSync(interval); const elapsed = performance.now() - now; if (elapsed < interval) { throw new Error("Didn't sleep"); diff --git a/integration/bunjs-only-snippets/some-fs.js b/integration/bunjs-only-snippets/some-fs.js new file mode 100644 index 000000000..e6b31f162 --- /dev/null +++ b/integration/bunjs-only-snippets/some-fs.js @@ -0,0 +1,51 @@ +const { mkdirSync, existsSync } = require("fs"); + +var performance = globalThis.performance; +if (!performance) { + try { + performance = require("perf_hooks").performance; + } catch (e) {} +} + +const count = parseInt(process.env.ITERATIONS || "1", 10) || 1; +var tempdir = `/tmp/some-fs-test/dir/${Date.now()}/hi`; + +for (let i = 0; i < count; i++) { + tempdir += `/${i.toString(36)}`; +} + +if (existsSync(tempdir)) { + throw new Error( + `existsSync reports ${tempdir} exists, but it probably does not` + ); +} + +var origTempDir = tempdir; +var iterations = new Array(count * count).fill(""); +var total = 0; +for (let i = 0; i < count; i++) { + for (let j = 0; j < count; j++) { + iterations[total++] = `${origTempDir}/${j.toString(36)}-${i.toString(36)}`; + } +} +tempdir = origTempDir; +mkdirSync(origTempDir, { recursive: true }); +const recurse = { recursive: false }; +const start = performance.now(); +for (let i = 0; i < total; i++) { + mkdirSync(iterations[i], recurse); +} + +console.log("MKDIR " + total + " depth took:", performance.now() - start, "ms"); + +if (!existsSync(tempdir)) { + throw new Error( + "Expected directory to exist after mkdirSync, but it doesn't" + ); +} + +if (mkdirSync(tempdir, { recursive: true })) { + throw new Error( + "mkdirSync shouldn't return directory name on existing directories" + ); +} diff --git a/integration/scripts/bun.js b/integration/scripts/bun.js index d22785787..f8e4d2fa0 100644 --- a/integration/scripts/bun.js +++ b/integration/scripts/bun.js @@ -1,84 +1,85 @@ -import snippets from "./snippets.json"; +const fail = true; +// import snippets from "./snippets.json"; -globalThis.console.assert = (condition, ...content) => { - if (!condition) { - throw new Error(content.join(" ")); - } -}; -globalThis.getModuleScriptSrc = async (name) => { - const response = await fetch(name, { - cache: "force-cache", - }); +// globalThis.console.assert = (condition, ...content) => { +// if (!condition) { +// throw new Error(content.join(" ")); +// } +// }; +// globalThis.getModuleScriptSrc = async (name) => { +// const response = await fetch(name, { +// cache: "force-cache", +// }); - if (response.ok) { - return await response.text(); - } else { - throw new Error(`Failed to get module script ${name}`); - } -}; +// if (response.ok) { +// return await response.text(); +// } else { +// throw new Error(`Failed to get module script ${name}`); +// } +// }; -globalThis.runTest = async (name) => { - testSuccess = false; - var Namespace = await import(name); - var testFunction = Namespace.test; +// globalThis.runTest = async (name) => { +// testSuccess = false; +// var Namespace = await import(name); +// var testFunction = Namespace.test; - if ( - !("test" in Namespace) && - "default" in Namespace && - typeof Namespace.default === "function" - ) { - Namespace = Namespace.default(); - testFunction = Namespace.test; - } +// if ( +// !("test" in Namespace) && +// "default" in Namespace && +// typeof Namespace.default === "function" +// ) { +// Namespace = Namespace.default(); +// testFunction = Namespace.test; +// } - if (!testFunction) { - throw new Error("No test function found in " + name); - } +// if (!testFunction) { +// throw new Error("No test function found in " + name); +// } - if (typeof testFunction !== "function") { - throw new Error( - `Expected (await import(\"${name}\"")) to have a test function.\nReceived: ${Object.keys( - Namespace - ).join(", ")} ` - ); - } +// if (typeof testFunction !== "function") { +// throw new Error( +// `Expected (await import(\"${name}\"")) to have a test function.\nReceived: ${Object.keys( +// Namespace +// ).join(", ")} ` +// ); +// } - if (globalThis.BUN_DEBUG_MODE) { - try { - await testFunction(); - if (!testSuccess) { - throw new Error("Test failed"); - } - } catch (exception) { - console.error(exception); - debugger; - throw exception; - } - } else { - await testFunction(); - if (!testSuccess) { - throw new Error("Test failed"); - } - } -}; +// if (globalThis.BUN_DEBUG_MODE) { +// try { +// await testFunction(); +// if (!testSuccess) { +// throw new Error("Test failed"); +// } +// } catch (exception) { +// console.error(exception); +// debugger; +// throw exception; +// } +// } else { +// await testFunction(); +// if (!testSuccess) { +// throw new Error("Test failed"); +// } +// } +// }; -var testSuccess = false; -globalThis.testDone = () => { - testSuccess = true; -}; +// var testSuccess = false; +// globalThis.testDone = () => { +// testSuccess = true; +// }; -let fail = 0; -for (let snippet of snippets) { - try { - await runTest("../snippets/" + snippet.substring(1)); - console.log("✅", snippet); - } catch (exception) { - console.error(`❌ ${snippet}`); - console.error(exception); +// let fail = 0; +// for (let snippet of snippets) { +// try { +// await runTest("../snippets/" + snippet.substring(1)); +// console.log("✅", snippet); +// } catch (exception) { +// console.error(`❌ ${snippet}`); +// console.error(exception); - fail++; - } -} +// fail++; +// } +// } if (fail) throw new Error(`❌ browser test failed (${fail})`); diff --git a/integration/scripts/bun.lockb b/integration/scripts/bun.lockb Binary files differindex 557f98ef6..1af6fbf69 100755 --- a/integration/scripts/bun.lockb +++ b/integration/scripts/bun.lockb diff --git a/integration/snapshots/array-args-with-default-values.hmr.debug.js b/integration/snapshots/array-args-with-default-values.hmr.debug.js index 58e8b47bf..f55cb290e 100644 --- a/integration/snapshots/array-args-with-default-values.hmr.debug.js +++ b/integration/snapshots/array-args-with-default-values.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(3474597122, "array-args-with-default-values.js"), exports = hmr.exports; diff --git a/integration/snapshots/array-args-with-default-values.hmr.js b/integration/snapshots/array-args-with-default-values.hmr.js index aae356eed..5c67d0c6c 100644 --- a/integration/snapshots/array-args-with-default-values.hmr.js +++ b/integration/snapshots/array-args-with-default-values.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(3474597122, "array-args-with-default-values.js"), exports = hmr.exports; diff --git a/integration/snapshots/bundled-entry-point.debug.js b/integration/snapshots/bundled-entry-point.debug.js index 04f92d63a..0ffe267f1 100644 --- a/integration/snapshots/bundled-entry-point.debug.js +++ b/integration/snapshots/bundled-entry-point.debug.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var hello = null ?? "world"; diff --git a/integration/snapshots/bundled-entry-point.hmr.debug.js b/integration/snapshots/bundled-entry-point.hmr.debug.js index fd211daa2..4b62d3dbc 100644 --- a/integration/snapshots/bundled-entry-point.hmr.debug.js +++ b/integration/snapshots/bundled-entry-point.hmr.debug.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; Bun.activate(true); diff --git a/integration/snapshots/bundled-entry-point.hmr.js b/integration/snapshots/bundled-entry-point.hmr.js index f3008327a..b04c38495 100644 --- a/integration/snapshots/bundled-entry-point.hmr.js +++ b/integration/snapshots/bundled-entry-point.hmr.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; Bun.activate(false); diff --git a/integration/snapshots/bundled-entry-point.js b/integration/snapshots/bundled-entry-point.js index 04f92d63a..0ffe267f1 100644 --- a/integration/snapshots/bundled-entry-point.js +++ b/integration/snapshots/bundled-entry-point.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var hello = null ?? "world"; diff --git a/integration/snapshots/caught-require.debug.js b/integration/snapshots/caught-require.debug.js index 690ec4db5..f4f12c29d 100644 --- a/integration/snapshots/caught-require.debug.js +++ b/integration/snapshots/caught-require.debug.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; try { require((() => { throw (new Error(`Cannot require module '"this-package-should-not-exist"'`)); } )()); diff --git a/integration/snapshots/caught-require.hmr.debug.js b/integration/snapshots/caught-require.hmr.debug.js index 25883fac7..2cd9f386d 100644 --- a/integration/snapshots/caught-require.hmr.debug.js +++ b/integration/snapshots/caught-require.hmr.debug.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(2398506918, "caught-require.js"), exports = hmr.exports; diff --git a/integration/snapshots/caught-require.hmr.js b/integration/snapshots/caught-require.hmr.js index ea7bccc2c..c57c6f90e 100644 --- a/integration/snapshots/caught-require.hmr.js +++ b/integration/snapshots/caught-require.hmr.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(2398506918, "caught-require.js"), exports = hmr.exports; diff --git a/integration/snapshots/caught-require.js b/integration/snapshots/caught-require.js index 690ec4db5..f4f12c29d 100644 --- a/integration/snapshots/caught-require.js +++ b/integration/snapshots/caught-require.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; try { require((() => { throw (new Error(`Cannot require module '"this-package-should-not-exist"'`)); } )()); diff --git a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js index 2ca15542e..c5aa62729 100644 --- a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js +++ b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import _login from "http://localhost:8080/_login.js"; import _auth from "http://localhost:8080/_auth.js"; import * as _loginReally from "http://localhost:8080/_login.js"; diff --git a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js index ef0bd004e..82d8617f0 100644 --- a/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js +++ b/integration/snapshots/cjs-transform-shouldnt-have-static-imports-in-cjs-function.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import _login from "http://localhost:8080/_login.js"; import _auth from "http://localhost:8080/_auth.js"; import * as _loginReally from "http://localhost:8080/_login.js"; diff --git a/integration/snapshots/code-simplification-neql-define.hmr.debug.js b/integration/snapshots/code-simplification-neql-define.hmr.debug.js index 80aedf8bb..860c514ba 100644 --- a/integration/snapshots/code-simplification-neql-define.hmr.debug.js +++ b/integration/snapshots/code-simplification-neql-define.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(726376257, "code-simplification-neql-define.js"), exports = hmr.exports; diff --git a/integration/snapshots/code-simplification-neql-define.hmr.js b/integration/snapshots/code-simplification-neql-define.hmr.js index 1e517c533..9fdd73d14 100644 --- a/integration/snapshots/code-simplification-neql-define.hmr.js +++ b/integration/snapshots/code-simplification-neql-define.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(726376257, "code-simplification-neql-define.js"), exports = hmr.exports; diff --git a/integration/snapshots/custom-emotion-jsx/file.debug.jsx b/integration/snapshots/custom-emotion-jsx/file.debug.jsx index b6be3371f..97987ff3f 100644 --- a/integration/snapshots/custom-emotion-jsx/file.debug.jsx +++ b/integration/snapshots/custom-emotion-jsx/file.debug.jsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx b/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx index c595a5957..bd299b2a8 100644 --- a/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx +++ b/integration/snapshots/custom-emotion-jsx/file.hmr.debug.jsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/custom-emotion-jsx/file.hmr.jsx b/integration/snapshots/custom-emotion-jsx/file.hmr.jsx index da190ef0d..ffc4f8c96 100644 --- a/integration/snapshots/custom-emotion-jsx/file.hmr.jsx +++ b/integration/snapshots/custom-emotion-jsx/file.hmr.jsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/custom-emotion-jsx/file.jsx b/integration/snapshots/custom-emotion-jsx/file.jsx index b6be3371f..97987ff3f 100644 --- a/integration/snapshots/custom-emotion-jsx/file.jsx +++ b/integration/snapshots/custom-emotion-jsx/file.jsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/@emotion/react/jsx-dev-runtime/dist/emotion-react-jsx-dev-runtime.browser.esm.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/export.hmr.debug.js b/integration/snapshots/export.hmr.debug.js index b5d3e0ad1..ed800afa1 100644 --- a/integration/snapshots/export.hmr.debug.js +++ b/integration/snapshots/export.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import what from "http://localhost:8080/_auth.js"; import * as where from "http://localhost:8080/_auth.js"; Bun.activate(true); diff --git a/integration/snapshots/export.hmr.js b/integration/snapshots/export.hmr.js index 6088ffd77..a7d1f9b31 100644 --- a/integration/snapshots/export.hmr.js +++ b/integration/snapshots/export.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import what from "http://localhost:8080/_auth.js"; import * as where from "http://localhost:8080/_auth.js"; Bun.activate(false); diff --git a/integration/snapshots/forbid-in-is-correct.hmr.debug.js b/integration/snapshots/forbid-in-is-correct.hmr.debug.js index 7014ea1e8..e38cadb7f 100644 --- a/integration/snapshots/forbid-in-is-correct.hmr.debug.js +++ b/integration/snapshots/forbid-in-is-correct.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(346837007, "forbid-in-is-correct.js"), exports = hmr.exports; diff --git a/integration/snapshots/forbid-in-is-correct.hmr.js b/integration/snapshots/forbid-in-is-correct.hmr.js index bd20b7b42..e44263095 100644 --- a/integration/snapshots/forbid-in-is-correct.hmr.js +++ b/integration/snapshots/forbid-in-is-correct.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(346837007, "forbid-in-is-correct.js"), exports = hmr.exports; diff --git a/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js b/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js index dace8fa7a..c2a6edc5f 100644 --- a/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js +++ b/integration/snapshots/global-is-remapped-to-globalThis.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(713665787, "global-is-remapped-to-globalThis.js"), exports = hmr.exports; diff --git a/integration/snapshots/global-is-remapped-to-globalThis.hmr.js b/integration/snapshots/global-is-remapped-to-globalThis.hmr.js index a5a3723a6..d1dd77003 100644 --- a/integration/snapshots/global-is-remapped-to-globalThis.hmr.js +++ b/integration/snapshots/global-is-remapped-to-globalThis.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(713665787, "global-is-remapped-to-globalThis.js"), exports = hmr.exports; diff --git a/integration/snapshots/jsx-entities.debug.jsx b/integration/snapshots/jsx-entities.debug.jsx index cfaf14c10..63128a105 100644 --- a/integration/snapshots/jsx-entities.debug.jsx +++ b/integration/snapshots/jsx-entities.debug.jsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/jsx-entities.hmr.debug.jsx b/integration/snapshots/jsx-entities.hmr.debug.jsx index 73f00bdef..5427483d3 100644 --- a/integration/snapshots/jsx-entities.hmr.debug.jsx +++ b/integration/snapshots/jsx-entities.hmr.debug.jsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/jsx-entities.hmr.jsx b/integration/snapshots/jsx-entities.hmr.jsx index 2ec3158d6..fee5ba0f3 100644 --- a/integration/snapshots/jsx-entities.hmr.jsx +++ b/integration/snapshots/jsx-entities.hmr.jsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/jsx-entities.jsx b/integration/snapshots/jsx-entities.jsx index cfaf14c10..63128a105 100644 --- a/integration/snapshots/jsx-entities.jsx +++ b/integration/snapshots/jsx-entities.jsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/jsx-spacing.debug.jsx b/integration/snapshots/jsx-spacing.debug.jsx index 0b1914722..29c8995d3 100644 --- a/integration/snapshots/jsx-spacing.debug.jsx +++ b/integration/snapshots/jsx-spacing.debug.jsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/jsx-spacing.hmr.debug.jsx b/integration/snapshots/jsx-spacing.hmr.debug.jsx index 8d45ec417..462469ba5 100644 --- a/integration/snapshots/jsx-spacing.hmr.debug.jsx +++ b/integration/snapshots/jsx-spacing.hmr.debug.jsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/jsx-spacing.hmr.jsx b/integration/snapshots/jsx-spacing.hmr.jsx index d41bc53c7..a17970a7d 100644 --- a/integration/snapshots/jsx-spacing.hmr.jsx +++ b/integration/snapshots/jsx-spacing.hmr.jsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/jsx-spacing.jsx b/integration/snapshots/jsx-spacing.jsx index 0b1914722..29c8995d3 100644 --- a/integration/snapshots/jsx-spacing.jsx +++ b/integration/snapshots/jsx-spacing.jsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js b/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js index f0e79c488..db7f60ee3 100644 --- a/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js +++ b/integration/snapshots/latin1-chars-in-regexp.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(1430071586, "latin1-chars-in-regexp.js"), exports = hmr.exports; diff --git a/integration/snapshots/latin1-chars-in-regexp.hmr.js b/integration/snapshots/latin1-chars-in-regexp.hmr.js index 03b9344e4..db6eec375 100644 --- a/integration/snapshots/latin1-chars-in-regexp.hmr.js +++ b/integration/snapshots/latin1-chars-in-regexp.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(1430071586, "latin1-chars-in-regexp.js"), exports = hmr.exports; diff --git a/integration/snapshots/lodash-regexp.debug.js b/integration/snapshots/lodash-regexp.debug.js index 6e0e6190a..dd6bca362 100644 --- a/integration/snapshots/lodash-regexp.debug.js +++ b/integration/snapshots/lodash-regexp.debug.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js"; var { shuffle} = require($60f52dc2); export function test() { diff --git a/integration/snapshots/lodash-regexp.hmr.debug.js b/integration/snapshots/lodash-regexp.hmr.debug.js index 3030e47c6..a66de3069 100644 --- a/integration/snapshots/lodash-regexp.hmr.debug.js +++ b/integration/snapshots/lodash-regexp.hmr.debug.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js"; var { shuffle} = require($60f52dc2); Bun.activate(true); diff --git a/integration/snapshots/lodash-regexp.hmr.js b/integration/snapshots/lodash-regexp.hmr.js index cd9ca40f7..357568704 100644 --- a/integration/snapshots/lodash-regexp.hmr.js +++ b/integration/snapshots/lodash-regexp.hmr.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js"; var { shuffle} = require($60f52dc2); Bun.activate(false); diff --git a/integration/snapshots/lodash-regexp.js b/integration/snapshots/lodash-regexp.js index 6e0e6190a..dd6bca362 100644 --- a/integration/snapshots/lodash-regexp.js +++ b/integration/snapshots/lodash-regexp.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $60f52dc2 from "http://localhost:8080/node_modules/lodash/lodash.js"; var { shuffle} = require($60f52dc2); export function test() { diff --git a/integration/snapshots/multiple-imports.debug.js b/integration/snapshots/multiple-imports.debug.js index a98366885..dcf7b6231 100644 --- a/integration/snapshots/multiple-imports.debug.js +++ b/integration/snapshots/multiple-imports.debug.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/multiple-imports.hmr.debug.js b/integration/snapshots/multiple-imports.hmr.debug.js index 3c40e88a6..78cf5bd0e 100644 --- a/integration/snapshots/multiple-imports.hmr.debug.js +++ b/integration/snapshots/multiple-imports.hmr.debug.js @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/multiple-imports.hmr.js b/integration/snapshots/multiple-imports.hmr.js index 03cfe9d1a..4f57d33b8 100644 --- a/integration/snapshots/multiple-imports.hmr.js +++ b/integration/snapshots/multiple-imports.hmr.js @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/multiple-imports.js b/integration/snapshots/multiple-imports.js index a98366885..dcf7b6231 100644 --- a/integration/snapshots/multiple-imports.js +++ b/integration/snapshots/multiple-imports.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/number-literal-bug.hmr.debug.js b/integration/snapshots/number-literal-bug.hmr.debug.js index e9d9f7b06..96e0dc96c 100644 --- a/integration/snapshots/number-literal-bug.hmr.debug.js +++ b/integration/snapshots/number-literal-bug.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(583570002, "number-literal-bug.js"), exports = hmr.exports; diff --git a/integration/snapshots/number-literal-bug.hmr.js b/integration/snapshots/number-literal-bug.hmr.js index 87cd08433..1d128538c 100644 --- a/integration/snapshots/number-literal-bug.hmr.js +++ b/integration/snapshots/number-literal-bug.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(583570002, "number-literal-bug.js"), exports = hmr.exports; diff --git a/integration/snapshots/optional-chain-with-function.hmr.debug.js b/integration/snapshots/optional-chain-with-function.hmr.debug.js index acd656901..f4c7a3641 100644 --- a/integration/snapshots/optional-chain-with-function.hmr.debug.js +++ b/integration/snapshots/optional-chain-with-function.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(3608848620, "optional-chain-with-function.js"), exports = hmr.exports; diff --git a/integration/snapshots/optional-chain-with-function.hmr.js b/integration/snapshots/optional-chain-with-function.hmr.js index 91666bf96..780c8b425 100644 --- a/integration/snapshots/optional-chain-with-function.hmr.js +++ b/integration/snapshots/optional-chain-with-function.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(3608848620, "optional-chain-with-function.js"), exports = hmr.exports; diff --git a/integration/snapshots/package-json-exports/index.debug.js b/integration/snapshots/package-json-exports/index.debug.js index 882f9d489..cfeee9a4a 100644 --- a/integration/snapshots/package-json-exports/index.debug.js +++ b/integration/snapshots/package-json-exports/index.debug.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js"; var InexactRoot = require($4068f25b); import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js"; diff --git a/integration/snapshots/package-json-exports/index.hmr.debug.js b/integration/snapshots/package-json-exports/index.hmr.debug.js index 26be6ac7b..8c23e74fc 100644 --- a/integration/snapshots/package-json-exports/index.hmr.debug.js +++ b/integration/snapshots/package-json-exports/index.hmr.debug.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js"; var InexactRoot = require($4068f25b); import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js"; diff --git a/integration/snapshots/package-json-exports/index.hmr.js b/integration/snapshots/package-json-exports/index.hmr.js index d4e1aff18..eaaad675c 100644 --- a/integration/snapshots/package-json-exports/index.hmr.js +++ b/integration/snapshots/package-json-exports/index.hmr.js @@ -1,12 +1,12 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js"; var InexactRoot = require($4068f25b); import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js"; diff --git a/integration/snapshots/package-json-exports/index.js b/integration/snapshots/package-json-exports/index.js index 882f9d489..cfeee9a4a 100644 --- a/integration/snapshots/package-json-exports/index.js +++ b/integration/snapshots/package-json-exports/index.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as $4068f25b from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/index.js"; var InexactRoot = require($4068f25b); import * as $d2a171d2 from "http://localhost:8080/package-json-exports/node_modules/inexact/browser/dir/file.js"; diff --git a/integration/snapshots/react-context-value-func.debug.tsx b/integration/snapshots/react-context-value-func.debug.tsx index 5d151afba..6ce4b09db 100644 --- a/integration/snapshots/react-context-value-func.debug.tsx +++ b/integration/snapshots/react-context-value-func.debug.tsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/react-context-value-func.hmr.debug.tsx b/integration/snapshots/react-context-value-func.hmr.debug.tsx index 9280a638d..4632802d4 100644 --- a/integration/snapshots/react-context-value-func.hmr.debug.tsx +++ b/integration/snapshots/react-context-value-func.hmr.debug.tsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/react-context-value-func.hmr.tsx b/integration/snapshots/react-context-value-func.hmr.tsx index c6313661e..5ad188422 100644 --- a/integration/snapshots/react-context-value-func.hmr.tsx +++ b/integration/snapshots/react-context-value-func.hmr.tsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/react-context-value-func.tsx b/integration/snapshots/react-context-value-func.tsx index 5d151afba..6ce4b09db 100644 --- a/integration/snapshots/react-context-value-func.tsx +++ b/integration/snapshots/react-context-value-func.tsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/spread_with_key.debug.tsx b/integration/snapshots/spread_with_key.debug.tsx index cb079bb95..25f380a8d 100644 --- a/integration/snapshots/spread_with_key.debug.tsx +++ b/integration/snapshots/spread_with_key.debug.tsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/spread_with_key.hmr.debug.tsx b/integration/snapshots/spread_with_key.hmr.debug.tsx index 7f5076f1a..78754d7dd 100644 --- a/integration/snapshots/spread_with_key.hmr.debug.tsx +++ b/integration/snapshots/spread_with_key.hmr.debug.tsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/spread_with_key.hmr.tsx b/integration/snapshots/spread_with_key.hmr.tsx index 4b5d9ccf6..9e4da7bf4 100644 --- a/integration/snapshots/spread_with_key.hmr.tsx +++ b/integration/snapshots/spread_with_key.hmr.tsx @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/spread_with_key.tsx b/integration/snapshots/spread_with_key.tsx index cb079bb95..25f380a8d 100644 --- a/integration/snapshots/spread_with_key.tsx +++ b/integration/snapshots/spread_with_key.tsx @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/string-escapes.debug.js b/integration/snapshots/string-escapes.debug.js index af9c53abf..9feb91e50 100644 --- a/integration/snapshots/string-escapes.debug.js +++ b/integration/snapshots/string-escapes.debug.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/string-escapes.hmr.debug.js b/integration/snapshots/string-escapes.hmr.debug.js index 19045846a..923c8b8b3 100644 --- a/integration/snapshots/string-escapes.hmr.debug.js +++ b/integration/snapshots/string-escapes.hmr.debug.js @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/string-escapes.hmr.js b/integration/snapshots/string-escapes.hmr.js index e1f38c7af..2ffed5df4 100644 --- a/integration/snapshots/string-escapes.hmr.js +++ b/integration/snapshots/string-escapes.hmr.js @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/string-escapes.js b/integration/snapshots/string-escapes.js index af9c53abf..9feb91e50 100644 --- a/integration/snapshots/string-escapes.js +++ b/integration/snapshots/string-escapes.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; import * as $bbcd215f from "http://localhost:8080/node_modules/react/index.js"; var JSXClassic = require($bbcd215f); diff --git a/integration/snapshots/styledcomponents-output.debug.js b/integration/snapshots/styledcomponents-output.debug.js index b99d434da..7dcaa3d08 100644 --- a/integration/snapshots/styledcomponents-output.debug.js +++ b/integration/snapshots/styledcomponents-output.debug.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/styledcomponents-output.hmr.debug.js b/integration/snapshots/styledcomponents-output.hmr.debug.js index dc9e2de7d..cecb4780e 100644 --- a/integration/snapshots/styledcomponents-output.hmr.debug.js +++ b/integration/snapshots/styledcomponents-output.hmr.debug.js @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/styledcomponents-output.hmr.js b/integration/snapshots/styledcomponents-output.hmr.js index 5f0d525a4..c9bd340d1 100644 --- a/integration/snapshots/styledcomponents-output.hmr.js +++ b/integration/snapshots/styledcomponents-output.hmr.js @@ -1,12 +1,12 @@ import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/styledcomponents-output.js b/integration/snapshots/styledcomponents-output.js index b99d434da..7dcaa3d08 100644 --- a/integration/snapshots/styledcomponents-output.js +++ b/integration/snapshots/styledcomponents-output.js @@ -1,6 +1,6 @@ import { __require as require -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import * as JSX from "http://localhost:8080/node_modules/react/jsx-dev-runtime.js"; var jsx = require(JSX).jsxDEV; diff --git a/integration/snapshots/template-literal.hmr.debug.js b/integration/snapshots/template-literal.hmr.debug.js index af93a6fa5..a603ab705 100644 --- a/integration/snapshots/template-literal.hmr.debug.js +++ b/integration/snapshots/template-literal.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(2201713056, "template-literal.js"), exports = hmr.exports; diff --git a/integration/snapshots/template-literal.hmr.js b/integration/snapshots/template-literal.hmr.js index d27857c77..b237b0ec5 100644 --- a/integration/snapshots/template-literal.hmr.js +++ b/integration/snapshots/template-literal.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(2201713056, "template-literal.js"), exports = hmr.exports; diff --git a/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js b/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js index c90ac6d25..1b2c6fbf2 100644 --- a/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js +++ b/integration/snapshots/ts-fallback-rewrite-works.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(421762902, "ts-fallback-rewrite-works.ts"), exports = hmr.exports; diff --git a/integration/snapshots/ts-fallback-rewrite-works.hmr.js b/integration/snapshots/ts-fallback-rewrite-works.hmr.js index e728c5f14..577275c99 100644 --- a/integration/snapshots/ts-fallback-rewrite-works.hmr.js +++ b/integration/snapshots/ts-fallback-rewrite-works.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(421762902, "ts-fallback-rewrite-works.ts"), exports = hmr.exports; diff --git a/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js b/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js index d3aa0919a..b9155a35f 100644 --- a/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js +++ b/integration/snapshots/tsx-fallback-rewrite-works.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(2117426367, "tsx-fallback-rewrite-works.tsx"), exports = hmr.exports; diff --git a/integration/snapshots/tsx-fallback-rewrite-works.hmr.js b/integration/snapshots/tsx-fallback-rewrite-works.hmr.js index 3f2f754e2..98449f355 100644 --- a/integration/snapshots/tsx-fallback-rewrite-works.hmr.js +++ b/integration/snapshots/tsx-fallback-rewrite-works.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(2117426367, "tsx-fallback-rewrite-works.tsx"), exports = hmr.exports; diff --git a/integration/snapshots/type-only-imports.hmr.debug.ts b/integration/snapshots/type-only-imports.hmr.debug.ts index c647843ea..c6ddfa45f 100644 --- a/integration/snapshots/type-only-imports.hmr.debug.ts +++ b/integration/snapshots/type-only-imports.hmr.debug.ts @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(650094581, "type-only-imports.ts"), exports = hmr.exports; diff --git a/integration/snapshots/type-only-imports.hmr.ts b/integration/snapshots/type-only-imports.hmr.ts index 84740d0d9..4c3d9b9bb 100644 --- a/integration/snapshots/type-only-imports.hmr.ts +++ b/integration/snapshots/type-only-imports.hmr.ts @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(650094581, "type-only-imports.ts"), exports = hmr.exports; diff --git a/integration/snapshots/unicode-identifiers.hmr.debug.js b/integration/snapshots/unicode-identifiers.hmr.debug.js index 894cd0fe5..81017ff5c 100644 --- a/integration/snapshots/unicode-identifiers.hmr.debug.js +++ b/integration/snapshots/unicode-identifiers.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(1398361736, "unicode-identifiers.js"), exports = hmr.exports; diff --git a/integration/snapshots/unicode-identifiers.hmr.js b/integration/snapshots/unicode-identifiers.hmr.js index f43fef51c..d85c42c72 100644 --- a/integration/snapshots/unicode-identifiers.hmr.js +++ b/integration/snapshots/unicode-identifiers.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(1398361736, "unicode-identifiers.js"), exports = hmr.exports; diff --git a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js index ebc46c9ba..fa25488ec 100644 --- a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js +++ b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.debug.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(true); var hmr = new HMR(635901064, "void-shouldnt-delete-call-expressions.js"), exports = hmr.exports; diff --git a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js index 239b40fbd..fb14bc53a 100644 --- a/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js +++ b/integration/snapshots/void-shouldnt-delete-call-expressions.hmr.js @@ -1,9 +1,9 @@ import { __HMRModule as HMR -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; import { __HMRClient as Bun -} from "http://localhost:8080/__runtime.js"; +} from "http://localhost:8080/bun:runtime"; Bun.activate(false); var hmr = new HMR(635901064, "void-shouldnt-delete-call-expressions.js"), exports = hmr.exports; diff --git a/misctools/readlink-getfd.zig b/misctools/readlink-getfd.zig index 3e7cba5b9..f7934f54a 100644 --- a/misctools/readlink-getfd.zig +++ b/misctools/readlink-getfd.zig @@ -22,7 +22,7 @@ pub fn main() anyerror!void { var args_buffer: [8096 * 2]u8 = undefined; var fixed_buffer = std.heap.FixedBufferAllocator.init(&args_buffer); - var allocator = &fixed_buffer.allocator; + var allocator = fixed_buffer.allocator(); var args = std.mem.span(try std.process.argsAlloc(allocator)); @@ -32,7 +32,7 @@ pub fn main() anyerror!void { var out_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var j: usize = 0; - while (j < 100000) : (j += 1) { + while (j < 1000) : (j += 1) { var parts = [1][]const u8{std.mem.span(to_resolve)}; var joined_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var joined = path_handler.joinAbsStringBuf( diff --git a/misctools/readlink-realpath.zig b/misctools/readlink-realpath.zig index cb7c7de2a..e88a2e883 100644 --- a/misctools/readlink-realpath.zig +++ b/misctools/readlink-realpath.zig @@ -22,17 +22,16 @@ pub fn main() anyerror!void { var args_buffer: [8096 * 2]u8 = undefined; var fixed_buffer = std.heap.FixedBufferAllocator.init(&args_buffer); - var allocator = &fixed_buffer.allocator; + var allocator = fixed_buffer.allocator(); var args = std.mem.span(try std.process.argsAlloc(allocator)); const to_resolve = args[args.len - 1]; - const cwd = try std.process.getCwdAlloc(allocator); var out_buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var path: []u8 = undefined; var j: usize = 0; - while (j < 100000) : (j += 1) { + while (j < 1000) : (j += 1) { path = try std.os.realpathZ(to_resolve, &out_buffer); } diff --git a/packages/bun-error/bun.lockb b/packages/bun-error/bun.lockb Binary files differindex 1e4f1c801..e61a4dd71 100755 --- a/packages/bun-error/bun.lockb +++ b/packages/bun-error/bun.lockb diff --git a/packages/bun-error/package-lock.json b/packages/bun-error/package-lock.json index c33780e18..29e3c4ab4 100644 --- a/packages/bun-error/package-lock.json +++ b/packages/bun-error/package-lock.json @@ -1,187 +1,141 @@ { "name": "bun-error", "version": "1.0.0", - "lockfileVersion": 2, + "lockfileVersion": 1, "requires": true, - "packages": { - "": { - "name": "bun-error", - "version": "1.0.0", - "license": "MIT", - "dependencies": { - "esbuild": "^0.12.26", - "preact": "^10.5.14", - "preact-compat": "^3.19.0", - "react": "^17.0.2", - "react-dom": "^17.0.2" - } - }, - "node_modules/esbuild": { - "version": "0.12.26", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.26.tgz", - "integrity": "sha512-YmTkhPKjvTJ+G5e96NyhGf69bP+hzO0DscqaVJTi5GM34uaD4Ecj7omu5lJO+NrxCUBRhy2chONLK1h/2LwoXA==", - "hasInstallScript": true, - "bin": { - "esbuild": "bin/esbuild" - } - }, - "node_modules/immutability-helper": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/immutability-helper/-/immutability-helper-2.9.1.tgz", - "integrity": "sha512-r/RmRG8xO06s/k+PIaif2r5rGc3j4Yhc01jSBfwPCXDLYZwp/yxralI37Df1mwmuzcCsen/E/ITKcTEvc1PQmQ==", - "dependencies": { - "invariant": "^2.2.0" - } - }, - "node_modules/invariant": { - "version": "2.2.4", - "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", - "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", - "dependencies": { - "loose-envify": "^1.0.0" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" - }, - "node_modules/loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "bin": { - "loose-envify": "cli.js" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/preact": { - "version": "10.5.14", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.5.14.tgz", - "integrity": "sha512-KojoltCrshZ099ksUZ2OQKfbH66uquFoxHSbnwKbTJHeQNvx42EmC7wQVWNuDt6vC5s3nudRHFtKbpY4ijKlaQ==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/preact" - } - }, - "node_modules/preact-compat": { - "version": "3.19.0", - "resolved": "https://registry.npmjs.org/preact-compat/-/preact-compat-3.19.0.tgz", - "integrity": "sha512-f83A4hIhH8Uzhb9GbIcGk8SM19ffWlwP9mDaYwQdRnMdekZwcCA7eIAbeV4EMQaV9C0Yuy8iKgBAtyTKPZQt/Q==", - "dependencies": { - "immutability-helper": "^2.7.1", - "preact-context": "^1.1.3", - "preact-render-to-string": "^3.8.2", - "preact-transition-group": "^1.1.1", - "prop-types": "^15.6.2", - "standalone-react-addons-pure-render-mixin": "^0.1.1" - }, - "peerDependencies": { - "preact": "<10" - } - }, - "node_modules/preact-context": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/preact-context/-/preact-context-1.1.4.tgz", - "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ==", - "peerDependencies": { - "preact": "^8.2.7" - } - }, - "node_modules/preact-render-to-string": { - "version": "3.8.2", - "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-3.8.2.tgz", - "integrity": "sha512-przuZPajiurStGgxMoJP0EJeC4xj5CgHv+M7GfF3YxAdhGgEWAkhOSE0xympAFN20uMayntBZpttIZqqLl77fw==", - "dependencies": { - "pretty-format": "^3.5.1" - }, - "peerDependencies": { - "preact": "*" - } - }, - "node_modules/preact-transition-group": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/preact-transition-group/-/preact-transition-group-1.1.1.tgz", - "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA=", - "peerDependencies": { - "preact": "*" - } - }, - "node_modules/pretty-format": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz", - "integrity": "sha1-v77VbV6ad2ZF9LH/eqGjrE+jw4U=" - }, - "node_modules/prop-types": { - "version": "15.7.2", - "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz", - "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==", - "dependencies": { - "loose-envify": "^1.4.0", - "object-assign": "^4.1.1", - "react-is": "^16.8.1" - } - }, - "node_modules/react": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz", - "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==", - "dependencies": { - "loose-envify": "^1.1.0", - "object-assign": "^4.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "17.0.2", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz", - "integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==", - "dependencies": { - "loose-envify": "^1.1.0", - "object-assign": "^4.1.1", - "scheduler": "^0.20.2" - }, - "peerDependencies": { - "react": "17.0.2" - } - }, - "node_modules/react-is": { - "version": "16.13.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", - "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" - }, - "node_modules/scheduler": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz", - "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==", - "dependencies": { - "loose-envify": "^1.1.0", - "object-assign": "^4.1.1" - } - }, - "node_modules/standalone-react-addons-pure-render-mixin": { - "version": "0.1.1", - "resolved": "https://registry.npmjs.org/standalone-react-addons-pure-render-mixin/-/standalone-react-addons-pure-render-mixin-0.1.1.tgz", - "integrity": "sha1-PHQJ9MecQN6axyxhbPZ5qZTzdVE=" - } - }, "dependencies": { "esbuild": { - "version": "0.12.26", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.26.tgz", - "integrity": "sha512-YmTkhPKjvTJ+G5e96NyhGf69bP+hzO0DscqaVJTi5GM34uaD4Ecj7omu5lJO+NrxCUBRhy2chONLK1h/2LwoXA==" + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.14.11.tgz", + "integrity": "sha512-xZvPtVj6yecnDeFb3KjjCM6i7B5TCAQZT77kkW/CpXTMnd6VLnRPKrUB1XHI1pSq6a4Zcy3BGueQ8VljqjDGCg==", + "requires": { + "esbuild-android-arm64": "0.14.11", + "esbuild-darwin-64": "0.14.11", + "esbuild-darwin-arm64": "0.14.11", + "esbuild-freebsd-64": "0.14.11", + "esbuild-freebsd-arm64": "0.14.11", + "esbuild-linux-32": "0.14.11", + "esbuild-linux-64": "0.14.11", + "esbuild-linux-arm": "0.14.11", + "esbuild-linux-arm64": "0.14.11", + "esbuild-linux-mips64le": "0.14.11", + "esbuild-linux-ppc64le": "0.14.11", + "esbuild-linux-s390x": "0.14.11", + "esbuild-netbsd-64": "0.14.11", + "esbuild-openbsd-64": "0.14.11", + "esbuild-sunos-64": "0.14.11", + "esbuild-windows-32": "0.14.11", + "esbuild-windows-64": "0.14.11", + "esbuild-windows-arm64": "0.14.11" + } + }, + "esbuild-android-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.14.11.tgz", + "integrity": "sha512-6iHjgvMnC/SzDH8TefL+/3lgCjYWwAd1LixYfmz/TBPbDQlxcuSkX0yiQgcJB9k+ibZ54yjVXziIwGdlc+6WNw==", + "optional": true + }, + "esbuild-darwin-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.14.11.tgz", + "integrity": "sha512-olq84ikh6TiBcrs3FnM4eR5VPPlcJcdW8BnUz/lNoEWYifYQ+Po5DuYV1oz1CTFMw4k6bQIZl8T3yxL+ZT2uvQ==", + "optional": true + }, + "esbuild-darwin-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.11.tgz", + "integrity": "sha512-Jj0ieWLREPBYr/TZJrb2GFH8PVzDqiQWavo1pOFFShrcmHWDBDrlDxPzEZ67NF/Un3t6sNNmeI1TUS/fe1xARg==", + "optional": true + }, + "esbuild-freebsd-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.11.tgz", + "integrity": "sha512-C5sT3/XIztxxz/zwDjPRHyzj/NJFOnakAanXuyfLDwhwupKPd76/PPHHyJx6Po6NI6PomgVp/zi6GRB8PfrOTA==", + "optional": true + }, + "esbuild-freebsd-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.11.tgz", + "integrity": "sha512-y3Llu4wbs0bk4cwjsdAtVOesXb6JkdfZDLKMt+v1U3tOEPBdSu6w8796VTksJgPfqvpX22JmPLClls0h5p+L9w==", + "optional": true + }, + "esbuild-linux-32": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.14.11.tgz", + "integrity": "sha512-Cg3nVsxArjyLke9EuwictFF3Sva+UlDTwHIuIyx8qpxRYAOUTmxr2LzYrhHyTcGOleLGXUXYsnUVwKqnKAgkcg==", + "optional": true + }, + "esbuild-linux-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.11.tgz", + "integrity": "sha512-oeR6dIrrojr8DKVrxtH3xl4eencmjsgI6kPkDCRIIFwv4p+K7ySviM85K66BN01oLjzthpUMvBVfWSJkBLeRbg==", + "optional": true + }, + "esbuild-linux-arm": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.14.11.tgz", + "integrity": "sha512-vcwskfD9g0tojux/ZaTJptJQU3a7YgTYsptK1y6LQ/rJmw7U5QJvboNawqM98Ca3ToYEucfCRGbl66OTNtp6KQ==", + "optional": true + }, + "esbuild-linux-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.11.tgz", + "integrity": "sha512-+e6ZCgTFQYZlmg2OqLkg1jHLYtkNDksxWDBWNtI4XG4WxuOCUErLqfEt9qWjvzK3XBcCzHImrajkUjO+rRkbMg==", + "optional": true + }, + "esbuild-linux-mips64le": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.11.tgz", + "integrity": "sha512-Rrs99L+p54vepmXIb87xTG6ukrQv+CzrM8eoeR+r/OFL2Rg8RlyEtCeshXJ2+Q66MXZOgPJaokXJZb9snq28bw==", + "optional": true + }, + "esbuild-linux-ppc64le": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.11.tgz", + "integrity": "sha512-JyzziGAI0D30Vyzt0HDihp4s1IUtJ3ssV2zx9O/c+U/dhUHVP2TmlYjzCfCr2Q6mwXTeloDcLS4qkyvJtYptdQ==", + "optional": true + }, + "esbuild-linux-s390x": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.11.tgz", + "integrity": "sha512-DoThrkzunZ1nfRGoDN6REwmo8ZZWHd2ztniPVIR5RMw/Il9wiWEYBahb8jnMzQaSOxBsGp0PbyJeVLTUatnlcw==", + "optional": true + }, + "esbuild-netbsd-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.11.tgz", + "integrity": "sha512-12luoRQz+6eihKYh1zjrw0CBa2aw3twIiHV/FAfjh2NEBDgJQOY4WCEUEN+Rgon7xmLh4XUxCQjnwrvf8zhACw==", + "optional": true + }, + "esbuild-openbsd-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.11.tgz", + "integrity": "sha512-l18TZDjmvwW6cDeR4fmizNoxndyDHamGOOAenwI4SOJbzlJmwfr0jUgjbaXCUuYVOA964siw+Ix+A+bhALWg8Q==", + "optional": true + }, + "esbuild-sunos-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.14.11.tgz", + "integrity": "sha512-bmYzDtwASBB8c+0/HVOAiE9diR7+8zLm/i3kEojUH2z0aIs6x/S4KiTuT5/0VKJ4zk69kXel1cNWlHBMkmavQg==", + "optional": true + }, + "esbuild-windows-32": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.14.11.tgz", + "integrity": "sha512-J1Ys5hMid8QgdY00OBvIolXgCQn1ARhYtxPnG6ESWNTty3ashtc4+As5nTrsErnv8ZGUcWZe4WzTP/DmEVX1UQ==", + "optional": true + }, + "esbuild-windows-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.14.11.tgz", + "integrity": "sha512-h9FmMskMuGeN/9G9+LlHPAoiQk9jlKDUn9yA0MpiGzwLa82E7r1b1u+h2a+InprbSnSLxDq/7p5YGtYVO85Mlg==", + "optional": true + }, + "esbuild-windows-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.11.tgz", + "integrity": "sha512-dZp7Krv13KpwKklt9/1vBFBMqxEQIO6ri7Azf8C+ob4zOegpJmha2XY9VVWP/OyQ0OWk6cEeIzMJwInRZrzBUQ==", + "optional": true }, "immutability-helper": { "version": "2.9.1", @@ -238,8 +192,7 @@ "preact-context": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/preact-context/-/preact-context-1.1.4.tgz", - "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ==", - "requires": {} + "integrity": "sha512-gcCjPJ65R0MiW9hDu8W/3WAmyTElIvwLyEO6oLQiM6/TbLKLxCpBCWV8GJjx52TTEyUr60HLDcmoCXZlslelzQ==" }, "preact-render-to-string": { "version": "3.8.2", @@ -252,8 +205,7 @@ "preact-transition-group": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/preact-transition-group/-/preact-transition-group-1.1.1.tgz", - "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA=", - "requires": {} + "integrity": "sha1-8KSTJ+pRXs406ivoZMSn0p5dbhA=" }, "pretty-format": { "version": "3.8.0", diff --git a/realpath.js b/realpath.js new file mode 100644 index 000000000..eabc112f3 --- /dev/null +++ b/realpath.js @@ -0,0 +1,2 @@ +for (let i = 0; i < 9999; i++) + require("fs").realpathSync("./node_modules/.bin/prettier"); diff --git a/src/allocators.zig b/src/allocators.zig index 16fe5deec..f956de4d0 100644 --- a/src/allocators.zig +++ b/src/allocators.zig @@ -68,11 +68,45 @@ pub const ItemStatus = enum(u3) { not_found, }; +fn OverflowGroup(comptime Block: type) type { + return struct { + const Overflow = @This(); + // 16 million files should be good enough for anyone + // ...right? + const max = 4095; + const UsedSize = std.math.IntFittingRange(0, max + 1); + const default_allocator = @import("./global.zig").default_allocator; + used: UsedSize = 0, + allocated: UsedSize = 0, + ptrs: [max]*Block = undefined, + + pub fn tail(this: *Overflow) *Block { + if (this.allocated > 0 and this.ptrs[this.used].isFull()) { + this.used +%= 1; + if (this.allocated > this.used) { + this.ptrs[this.used].used = 0; + } + } + + if (this.allocated <= this.used) { + this.ptrs[this.allocated] = default_allocator.create(Block) catch unreachable; + this.ptrs[this.allocated].* = Block{}; + this.allocated +%= 1; + } + + return this.ptrs[this.used]; + } + + pub inline fn slice(this: *Overflow) []*Block { + return this.ptrs[0..this.used]; + } + }; +} + pub fn OverflowList(comptime ValueType: type, comptime count: comptime_int) type { return struct { const This = @This(); const SizeType = std.math.IntFittingRange(0, count); - const default_allocator = @import("./global.zig").default_allocator; const Block = struct { used: SizeType = 0, @@ -90,37 +124,7 @@ pub fn OverflowList(comptime ValueType: type, comptime count: comptime_int) type return &block.items[index]; } }; - - const Overflow = struct { - // 16 million files should be good enough for anyone - // ...right? - const max = 4095; - const UsedSize = std.math.IntFittingRange(0, max + 1); - used: UsedSize = 0, - allocated: UsedSize = 0, - ptrs: [max]*Block = undefined, - - pub fn tail(this: *Overflow) *Block { - if (this.allocated > 0 and this.ptrs[this.used].isFull()) { - this.used +%= 1; - if (this.allocated > this.used) { - this.ptrs[this.used].used = 0; - } - } - - if (this.allocated <= this.used) { - this.ptrs[this.allocated] = default_allocator.create(Block) catch unreachable; - this.ptrs[this.allocated].* = Block{}; - this.allocated +%= 1; - } - - return this.ptrs[this.used]; - } - - pub inline fn slice(this: *Overflow) []*Block { - return this.ptrs[0..this.used]; - } - }; + const Overflow = OverflowGroup(Block); list: Overflow = Overflow{}, count: u31 = 0, diff --git a/src/ast/base.zig b/src/ast/base.zig index f2312677f..91e0bcafc 100644 --- a/src/ast/base.zig +++ b/src/ast/base.zig @@ -25,50 +25,54 @@ pub const NodeIndexNone = 4294967293; pub const RefHashCtx = struct { pub fn hash(_: @This(), key: Ref) u32 { - return @truncate(u32, std.hash.Wyhash.hash(0, std.mem.asBytes(&key))); + return key.hash(); } pub fn eql(_: @This(), ref: Ref, b: Ref) bool { - return std.mem.readIntNative(u64, std.mem.asBytes(&ref)) == std.mem.readIntNative(u64, std.mem.asBytes(&b)); + return ref.asBitInt() == b.asBitInt(); } }; pub const Ref = packed struct { - source_index: Int = std.math.maxInt(Ref.Int), + const max_ref_int = std.math.maxInt(Ref.Int); + pub const BitInt = std.meta.Int(.unsigned, @bitSizeOf(Ref)); + + source_index: Int = max_ref_int, inner_index: Int = 0, is_source_contents_slice: bool = false, + pub inline fn asBitInt(this: Ref) BitInt { + return @bitCast(BitInt, this); + } + // 2 bits of padding for whatever is the parent pub const Int = u30; pub const None = Ref{ - .inner_index = std.math.maxInt(Ref.Int), - .source_index = std.math.maxInt(Ref.Int), + .inner_index = max_ref_int, + .source_index = max_ref_int, }; pub const RuntimeRef = Ref{ - .inner_index = std.math.maxInt(Ref.Int), - .source_index = std.math.maxInt(Ref.Int) - 1, + .inner_index = max_ref_int, + .source_index = max_ref_int - 1, }; + pub fn toInt(int: anytype) Int { return @intCast(Int, int); } pub fn hash(key: Ref) u32 { - return @truncate(u32, std.hash.Wyhash.hash(0, std.mem.asBytes(&key))); + return @truncate(u32, std.hash.Wyhash.hash(0, &@bitCast([8]u8, @as(u64, key.asBitInt())))); } pub fn eql(ref: Ref, b: Ref) bool { - return std.mem.readIntNative(u64, std.mem.asBytes(&ref)) == std.mem.readIntNative(u64, std.mem.asBytes(&b)); + return asBitInt(ref) == b.asBitInt(); } pub fn isNull(self: *const Ref) bool { - return self.source_index == std.math.maxInt(Ref.Int) and self.inner_index == std.math.maxInt(Ref.Int); - } - - pub fn isSourceNull(self: *const Ref) bool { - return self.source_index == std.math.maxInt(Ref.Int); + return self.source_index == max_ref_int and self.inner_index == max_ref_int; } pub fn isSourceIndexNull(int: anytype) bool { - return int == std.math.maxInt(Ref.Int); + return int == max_ref_int; } pub fn jsonStringify(self: *const Ref, options: anytype, writer: anytype) !void { diff --git a/src/bindgen.zig b/src/bindgen.zig index e76a1ce6d..adca78331 100644 --- a/src/bindgen.zig +++ b/src/bindgen.zig @@ -1,3 +1,5 @@ pub const bindgen = true; pub const main = @import("./javascript/jsc/bindings/bindings-generator.zig").main; +pub export fn PLCrashReportHandler(_: ?*anyopaque) void {} +pub export fn mkdirp(_: ?*anyopaque) void {} diff --git a/src/bun_js.zig b/src/bun_js.zig index 5bfd27110..0915cc55c 100644 --- a/src/bun_js.zig +++ b/src/bun_js.zig @@ -29,6 +29,9 @@ const NodeModuleBundle = @import("node_module_bundle.zig").NodeModuleBundle; const DotEnv = @import("env_loader.zig"); const which = @import("which.zig").which; const VirtualMachine = @import("./javascript/jsc/javascript.zig").VirtualMachine; +const JSC = @import("javascript_core"); + +const OpaqueWrap = JSC.OpaqueWrap; pub const Run = struct { file: std.fs.File, @@ -48,8 +51,10 @@ pub const Run = struct { .entry_path = entry_path, }; + run.vm.argv = ctx.positionals; + run.vm.bundler.configureRouter(false) catch { - if (Output.enable_ansi_colors) { + if (Output.enable_ansi_colors_stderr) { run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; } else { run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; @@ -59,7 +64,7 @@ pub const Run = struct { std.os.exit(1); }; run.vm.bundler.configureDefines() catch { - if (Output.enable_ansi_colors) { + if (Output.enable_ansi_colors_stderr) { run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; } else { run.vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; @@ -69,11 +74,12 @@ pub const Run = struct { std.os.exit(1); }; - try run.start(); + var callback = OpaqueWrap(Run, Run.start); + run.vm.global.vm().holdAPILock(&run, callback); } - pub fn start(this: *Run) !void { - var promise = try this.vm.loadEntryPoint(this.entry_path); + pub fn start(this: *Run) void { + var promise = this.vm.loadEntryPoint(this.entry_path) catch return; this.vm.tick(); while (promise.status(this.vm.global.vm()) == .Pending) { diff --git a/src/bundler.zig b/src/bundler.zig index 00a37a555..8127a4dc5 100644 --- a/src/bundler.zig +++ b/src/bundler.zig @@ -1376,6 +1376,29 @@ pub const Bundler = struct { .module_id = package_json.hashModule(package_path), }; } + + // This is our last resort. + // The package is supposed to be bundled + // package.json says its' in packages/@foo/bar/index.js + // The file really is in packages/bar/index.js + // But we need the import path to contain the package path for bundling to work + // so we fake it + // we say "" + if (package_json.name[0] == '@') { + if (std.mem.indexOfScalar(u8, package_json.name, '/')) |at| { + const package_subpath = package_json.name[at + 1 ..]; + if (std.mem.lastIndexOf(u8, file_path, package_subpath)) |i| { + package_path = this.bundler.fs.dirname_store.print("{s}/{s}", .{ package_json.name, file_path[i + package_subpath.len ..] }) catch unreachable; + import_path = package_path[package_json.name.len + 1 ..]; + return BundledModuleData{ + .import_path = import_path, + .package_path = package_path, + .package = package_json, + .module_id = package_json.hashModule(package_path), + }; + } + } + } } unreachable; } @@ -1487,7 +1510,8 @@ pub const Bundler = struct { }; var file_path = (resolve.pathConst() orelse unreachable).*; const source_dir = file_path.sourceDir(); - const loader = this.bundler.options.loader(file_path.name.ext); + const loader = bundler.options.loader(file_path.name.ext); + const platform = bundler.options.platform; defer scan_pass_result.reset(); defer shared_buffer.reset(); @@ -1656,7 +1680,7 @@ pub const Bundler = struct { } else |err| { if (comptime Environment.isDebug) { if (!import_record.handles_import_errors) { - Output.prettyErrorln("\n<r><red>{s}<r> on resolving \"{s}\" from \"{s}\"", .{ + Output.prettyErrorln("\n<r><red>{s}<r> resolving \"{s}\" from \"{s}\"", .{ @errorName(err), import_record.path.text, file_path.text, @@ -1672,29 +1696,36 @@ pub const Bundler = struct { switch (err) { error.ModuleNotFound => { + const addError = logger.Log.addResolveErrorWithTextDupeMaybeWarn; + if (!import_record.handles_import_errors) { if (isPackagePath(import_record.path.text)) { - if (this.bundler.options.platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) { - try log.addResolveErrorWithTextDupe( + if (platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) { + try addError( + log, &source, import_record.range, this.allocator, "Could not resolve Node.js builtin: \"{s}\".", .{import_record.path.text}, import_record.kind, + platform.isBun(), ); } else { - try log.addResolveErrorWithTextDupe( + try addError( + log, &source, import_record.range, this.allocator, "Could not resolve: \"{s}\". Maybe you need to \"bun install\"?", .{import_record.path.text}, import_record.kind, + platform.isBun(), ); } } else { - try log.addResolveErrorWithTextDupe( + try addError( + log, &source, import_record.range, this.allocator, @@ -1703,6 +1734,7 @@ pub const Bundler = struct { import_record.path.text, }, import_record.kind, + platform.isBun(), ); } } @@ -2098,28 +2130,34 @@ pub const Bundler = struct { switch (err) { error.ModuleNotFound => { if (!import_record.handles_import_errors) { + const addError = logger.Log.addResolveErrorWithTextDupeMaybeWarn; if (isPackagePath(import_record.path.text)) { - if (this.bundler.options.platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) { - try log.addResolveErrorWithTextDupe( + if (platform.isWebLike() and options.ExternalModules.isNodeBuiltin(import_record.path.text)) { + try addError( + log, &source, import_record.range, this.allocator, "Could not resolve Node.js builtin: \"{s}\".", .{import_record.path.text}, import_record.kind, + platform.isBun(), ); } else { - try log.addResolveErrorWithTextDupe( + try addError( + log, &source, import_record.range, this.allocator, "Could not resolve: \"{s}\". Maybe you need to \"bun install\"?", .{import_record.path.text}, import_record.kind, + platform.isBun(), ); } } else { - try log.addResolveErrorWithTextDupe( + try addError( + log, &source, import_record.range, this.allocator, @@ -2128,6 +2166,7 @@ pub const Bundler = struct { import_record.path.text, }, import_record.kind, + platform.isBun(), ); } } @@ -2740,13 +2779,6 @@ pub const Bundler = struct { var path_to_use = path_to_use_; - if (strings.eqlComptime(path_to_use, "__runtime.js")) { - return ServeResult{ - .file = options.OutputFile.initBuf(runtime.Runtime.sourceContent(), "__runtime.js", .js), - .mime_type = MimeType.javascript, - }; - } - defer { js_ast.Expr.Data.Store.reset(); js_ast.Stmt.Data.Store.reset(); @@ -2915,8 +2947,6 @@ pub const Bundler = struct { } } - if (bundler.options.write and bundler.options.output_dir.len > 0) {} - // 100.00 µs std.fifo.LinearFifo(resolver.Result,std.fifo.LinearFifoBufferType { .Dynamic = {}}).writeItemAssumeCapacity if (bundler.options.resolve_mode != .lazy) { try bundler.resolve_queue.ensureUnusedCapacity(3); @@ -3003,7 +3033,7 @@ pub const Bundler = struct { if (bundler.linker.any_needs_runtime) { try bundler.output_files.append( - options.OutputFile.initBuf(runtime.Runtime.sourceContent(), bundler.linker.runtime_source_path, .js), + options.OutputFile.initBuf(runtime.Runtime.sourceContent(), Linker.runtime_source_path, .js), ); } @@ -3,6 +3,7 @@ const Enviroment = @import("./env.zig"); const PlatformSpecific = switch (@import("builtin").target.os.tag) { .macos => @import("./darwin_c.zig"), + .linux => @import("./linux_c.zig"), else => struct {}, }; pub usingnamespace PlatformSpecific; @@ -18,16 +19,23 @@ const errno = os.errno; const mode_t = C.mode_t; const libc_stat = C.Stat; const zeroes = mem.zeroes; - +pub const darwin = @import("./darwin_c.zig"); +pub const linux = @import("./linux_c.zig"); pub extern "c" fn chmod([*c]const u8, mode_t) c_int; pub extern "c" fn fchmod(std.c.fd_t, mode_t) c_int; pub extern "c" fn umask(mode_t) mode_t; pub extern "c" fn fchmodat(c_int, [*c]const u8, mode_t, c_int) c_int; pub extern "c" fn fchown(std.c.fd_t, std.c.uid_t, std.c.gid_t) c_int; +pub extern "c" fn lchown(path: [*:0]const u8, std.c.uid_t, std.c.gid_t) c_int; +pub extern "c" fn chown(path: [*:0]const u8, std.c.uid_t, std.c.gid_t) c_int; pub extern "c" fn lstat([*c]const u8, [*c]libc_stat) c_int; pub extern "c" fn lstat64([*c]const u8, [*c]libc_stat) c_int; +pub extern "c" fn lchmod(path: [*:0]const u8, mode: mode_t) c_int; +pub extern "c" fn truncate(path: [*:0]const u8, len: os.off_t) c_int; +pub extern "c" fn lutimes(path: [*:0]const u8, times: *const [2]std.os.timeval) c_int; +pub extern "c" fn mkdtemp(template: [*c]u8) ?[*:0]u8; -pub fn lstat_absolute(path: [:0]const u8) StatError!Stat { +pub fn lstat_absolute(path: [:0]const u8) !Stat { if (builtin.os.tag == .windows) { @compileError("Not implemented yet"); } @@ -35,6 +43,7 @@ pub fn lstat_absolute(path: [:0]const u8) StatError!Stat { var st = zeroes(libc_stat); switch (errno(lstat64(path.ptr, &st))) { .SUCCESS => {}, + .NOENT => return error.FileNotFound, // .EINVAL => unreachable, .BADF => unreachable, // Always a race condition. .NOMEM => return error.SystemResources, diff --git a/src/cli.zig b/src/cli.zig index b17dc8396..40b59b928 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -36,30 +36,35 @@ const Router = @import("./router.zig"); const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle; -const BunCommand = @import("./cli/bun_command.zig").BunCommand; -const DevCommand = @import("./cli/dev_command.zig").DevCommand; -const DiscordCommand = @import("./cli/discord_command.zig").DiscordCommand; +const AddCommand = @import("./cli/add_command.zig").AddCommand; const BuildCommand = @import("./cli/build_command.zig").BuildCommand; +const BunCommand = @import("./cli/bun_command.zig").BunCommand; const CreateCommand = @import("./cli/create_command.zig").CreateCommand; const CreateListExamplesCommand = @import("./cli/create_command.zig").CreateListExamplesCommand; -const RunCommand = @import("./cli/run_command.zig").RunCommand; -const UpgradeCommand = @import("./cli/upgrade_command.zig").UpgradeCommand; +const DevCommand = @import("./cli/dev_command.zig").DevCommand; +const DiscordCommand = @import("./cli/discord_command.zig").DiscordCommand; const InstallCommand = @import("./cli/install_command.zig").InstallCommand; -const AddCommand = @import("./cli/add_command.zig").AddCommand; -const RemoveCommand = @import("./cli/remove_command.zig").RemoveCommand; -const PackageManagerCommand = @import("./cli/package_manager_command.zig").PackageManagerCommand; const InstallCompletionsCommand = @import("./cli/install_completions_command.zig").InstallCompletionsCommand; +const PackageManagerCommand = @import("./cli/package_manager_command.zig").PackageManagerCommand; +const RemoveCommand = @import("./cli/remove_command.zig").RemoveCommand; +const RunCommand = @import("./cli/run_command.zig").RunCommand; const ShellCompletions = @import("./cli/shell_completions.zig"); +const TestCommand = @import("./cli/test_command.zig").TestCommand; +const UpgradeCommand = @import("./cli/upgrade_command.zig").UpgradeCommand; +const Reporter = @import("./report.zig"); var start_time: i128 = undefined; pub const Cli = struct { var wait_group: sync.WaitGroup = undefined; + var log_: logger.Log = undefined; pub fn startTransform(_: std.mem.Allocator, _: Api.TransformOptions, _: *logger.Log) anyerror!void {} - pub fn start(allocator: std.mem.Allocator, _: anytype, _: anytype, comptime MainPanicHandler: type) anyerror!void { + pub fn start(allocator: std.mem.Allocator, _: anytype, _: anytype, comptime MainPanicHandler: type) void { start_time = std.time.nanoTimestamp(); - var log = try allocator.create(logger.Log); - log.* = logger.Log.init(allocator); + log_ = logger.Log.init(allocator); + + var log = &log_; + var panicker = MainPanicHandler.init(log); MainPanicHandler.Singleton = &panicker; @@ -71,7 +76,14 @@ pub const Cli = struct { std.os.exit(1); }, else => { - return err; + // Always dump the logs + if (Output.enable_ansi_colors_stderr) { + log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; + } else { + log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; + } + + Reporter.globalError(err); }, } }; @@ -84,7 +96,13 @@ const LoaderMatcher = strings.ExactSizeMatcher(4); const ColonListType = @import("./cli/colon_list_type.zig").ColonListType; pub const LoaderColonList = ColonListType(Api.Loader, Arguments.loader_resolver); pub const DefineColonList = ColonListType(string, Arguments.noop_resolver); - +fn invalidPlatform(diag: *clap.Diagnostic, _platform: []const u8) noreturn { + @setCold(true); + diag.name.long = "--platform"; + diag.arg = _platform; + diag.report(Output.errorWriter(), error.InvalidPlatform) catch {}; + std.process.exit(1); +} pub const Arguments = struct { pub fn loader_resolver(in: string) !Api.Loader { const Matcher = strings.ExactSizeMatcher(4); @@ -199,11 +217,16 @@ pub const Arguments = struct { printVersionAndExit(); } - var cwd_paths = [_]string{args.option("--cwd") orelse try std.process.getCwdAlloc(allocator)}; - var cwd = try std.fs.path.resolve(allocator, &cwd_paths); + var cwd: []u8 = undefined; + if (args.option("--cwd")) |cwd_| { + var cwd_paths = [_]string{cwd_}; + cwd = try std.fs.path.resolve(allocator, &cwd_paths); + } else { + cwd = try std.process.getCwdAlloc(allocator); + } var defines_tuple = try DefineColonList.resolve(allocator, args.options("--define")); - var loader_tuple = try LoaderColonList.resolve(allocator, args.options("--define")); + var loader_tuple = try LoaderColonList.resolve(allocator, args.options("--loader")); var externals = std.mem.zeroes([][]u8); if (args.options("--external").len > 0) { externals = try allocator.alloc([]u8, args.options("--external").len); @@ -329,17 +352,19 @@ pub const Arguments = struct { else => true, }; - opts.node_modules_bundle_path = args.option("--bunfile") orelse brk: { - const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.bun"); + if (comptime Command.Tag.cares_about_bun_file.get(cmd)) { + opts.node_modules_bundle_path = args.option("--bunfile") orelse brk: { + const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.bun"); - break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null; - }; + break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null; + }; - opts.node_modules_bundle_path_server = args.option("--server-bunfile") orelse brk: { - const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.server.bun"); + opts.node_modules_bundle_path_server = args.option("--server-bunfile") orelse brk: { + const node_modules_bundle_path_absolute = resolve_path.joinAbs(cwd, .auto, "node_modules.server.bun"); - break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null; - }; + break :brk std.fs.realpathAlloc(allocator, node_modules_bundle_path_absolute) catch null; + }; + } switch (comptime cmd) { .AutoCommand, .DevCommand, .BuildCommand, .BunCommand => { @@ -387,23 +412,12 @@ pub const Arguments = struct { const PlatformMatcher = strings.ExactSizeMatcher(8); if (args.option("--platform")) |_platform| { - switch (PlatformMatcher.match(_platform)) { - PlatformMatcher.case("browser") => { - opts.platform = Api.Platform.browser; - }, - PlatformMatcher.case("node") => { - opts.platform = Api.Platform.node; - }, - PlatformMatcher.case("macro"), PlatformMatcher.case("bun") => { - opts.platform = Api.Platform.bun; - }, - else => { - diag.name.long = "--platform"; - diag.arg = _platform; - try diag.report(Output.errorWriter(), error.InvalidPlatform); - std.process.exit(1); - }, - } + opts.platform = switch (PlatformMatcher.match(_platform)) { + PlatformMatcher.case("browser") => Api.Platform.browser, + PlatformMatcher.case("node") => Api.Platform.node, + PlatformMatcher.case("macro"), PlatformMatcher.case("bun") => Api.Platform.bun, + else => invalidPlatform(&diag, _platform), + }; } if (jsx_factory != null or @@ -577,22 +591,26 @@ pub const Command = struct { pub const Context = struct { start_time: i128, - args: Api.TransformOptions = std.mem.zeroes(Api.TransformOptions), + args: Api.TransformOptions, log: *logger.Log, allocator: std.mem.Allocator, positionals: []const string = &[_]string{}, debug: DebugOptions = DebugOptions{}, + const _ctx = Command.Context{ + .args = std.mem.zeroes(Api.TransformOptions), + .log = undefined, + .start_time = 0, + .allocator = undefined, + }; + pub fn create(allocator: std.mem.Allocator, log: *logger.Log, comptime command: Command.Tag) anyerror!Context { Cli.cmd = command; - - var ctx = Command.Context{ - .args = std.mem.zeroes(Api.TransformOptions), - .log = log, - .start_time = start_time, - .allocator = allocator, - }; + var ctx = _ctx; + ctx.log = log; + ctx.start_time = start_time; + ctx.allocator = allocator; if (comptime Command.Tag.uses_global_options.get(command)) { ctx.args = try Arguments.parse(allocator, &ctx, command); @@ -602,8 +620,27 @@ pub const Command = struct { } }; - pub fn which(allocator: std.mem.Allocator) Tag { - var args_iter = std.process.args(); + // std.process.args allocates! + const ArgsIterator = struct { + buf: [][*:0]u8 = undefined, + i: u32 = 0, + + pub fn next(this: *ArgsIterator) ?[]const u8 { + if (this.buf.len <= this.i) { + return null; + } + const i = this.i; + this.i += 1; + return std.mem.span(this.buf[i]); + } + + pub fn skip(this: *ArgsIterator) bool { + return this.next() != null; + } + }; + + pub fn which() Tag { + var args_iter = ArgsIterator{ .buf = std.os.argv }; // first one is the executable name const skipped = args_iter.skip(); @@ -611,9 +648,9 @@ pub const Command = struct { return .AutoCommand; } - var next_arg = ((args_iter.next(allocator) catch null) orelse return .AutoCommand); + var next_arg = ((args_iter.next()) orelse return .AutoCommand); while (next_arg[0] == '-') { - next_arg = ((args_iter.next(allocator) catch null) orelse return .AutoCommand); + next_arg = ((args_iter.next()) orelse return .AutoCommand); } const first_arg_name = std.mem.span(next_arg); @@ -630,6 +667,8 @@ pub const Command = struct { RootCommandMatcher.case("i"), RootCommandMatcher.case("install") => .InstallCommand, RootCommandMatcher.case("c"), RootCommandMatcher.case("create") => .CreateCommand, + RootCommandMatcher.case(TestCommand.name) => .TestCommand, + RootCommandMatcher.case("pm") => .PackageManagerCommand, RootCommandMatcher.case("add"), RootCommandMatcher.case("update"), RootCommandMatcher.case("a") => .AddCommand, @@ -665,7 +704,7 @@ pub const Command = struct { }; pub fn start(allocator: std.mem.Allocator, log: *logger.Log) !void { - const tag = which(allocator); + const tag = which(); switch (tag) { .DiscordCommand => return try DiscordCommand.exec(allocator), .HelpCommand => return try HelpCommand.exec(allocator), @@ -717,6 +756,12 @@ pub const Command = struct { try PackageManagerCommand.exec(ctx); return; }, + .TestCommand => { + const ctx = try Command.Context.create(allocator, log, .TestCommand); + + try TestCommand.exec(ctx); + return; + }, .GetCompletionsCommand => { const ctx = try Command.Context.create(allocator, log, .GetCompletionsCommand); var filter = ctx.positionals; @@ -881,6 +926,21 @@ pub const Command = struct { const file_: std.fs.File.OpenError!std.fs.File = brk: { if (script_name_to_search[0] == std.fs.path.sep) { break :brk std.fs.openFileAbsolute(script_name_to_search, .{ .read = true }); + } else if (!strings.hasPrefix(script_name_to_search, "..") and script_name_to_search[0] != '~') { + const file_pathZ = brk2: { + if (!strings.hasPrefix(file_path, "./")) { + script_name_buf[0..2].* = "./".*; + @memcpy(script_name_buf[2..], file_path.ptr, file_path.len); + script_name_buf[file_path.len + 2] = 0; + break :brk2 script_name_buf[0 .. file_path.len + 2 :0]; + } else { + @memcpy(&script_name_buf, file_path.ptr, file_path.len); + script_name_buf[file_path.len] = 0; + break :brk2 script_name_buf[0..file_path.len :0]; + } + }; + + break :brk std.fs.cwd().openFileZ(file_pathZ, .{ .read = true }); } else { var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; const cwd = std.os.getcwd(&path_buf) catch break :possibly_open_with_bun_js; @@ -954,6 +1014,16 @@ pub const Command = struct { RunCommand, UpgradeCommand, PackageManagerCommand, + TestCommand, + + pub const cares_about_bun_file: std.EnumArray(Tag, bool) = std.EnumArray(Tag, bool).initDefault(false, .{ + .AutoCommand = true, + .BuildCommand = true, + .BunCommand = true, + .DevCommand = true, + .RunCommand = true, + .TestCommand = true, + }); pub const uses_global_options: std.EnumArray(Tag, bool) = std.EnumArray(Tag, bool).initDefault(true, .{ .CreateCommand = false, diff --git a/src/cli/colon_list_type.zig b/src/cli/colon_list_type.zig index 2dd5e2522..73a3f1299 100644 --- a/src/cli/colon_list_type.zig +++ b/src/cli/colon_list_type.zig @@ -26,7 +26,7 @@ pub fn ColonListType(comptime t: type, value_resolver: anytype) type { // Support either ":" or "=" as the separator, preferring whichever is first. // ":" is less confusing IMO because that syntax is used with flags // but "=" is what esbuild uses and I want this to be somewhat familiar for people using esbuild - const midpoint = std.math.min(strings.indexOfChar(str, ':') orelse std.math.maxInt(usize), strings.indexOfChar(str, '=') orelse std.math.maxInt(usize)); + const midpoint = @minimum(strings.indexOfChar(str, ':') orelse std.math.maxInt(usize), strings.indexOfChar(str, '=') orelse std.math.maxInt(usize)); if (midpoint == std.math.maxInt(usize)) { return error.InvalidSeparator; } diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig new file mode 100644 index 000000000..60d03392a --- /dev/null +++ b/src/cli/test_command.zig @@ -0,0 +1,397 @@ +const _global = @import("../global.zig"); +const string = _global.string; +const Output = _global.Output; +const Global = _global.Global; +const Environment = _global.Environment; +const strings = _global.strings; +const MutableString = _global.MutableString; +const stringZ = _global.stringZ; +const default_allocator = _global.default_allocator; +const C = _global.C; +const std = @import("std"); + +const lex = @import("../js_lexer.zig"); +const logger = @import("../logger.zig"); + +const FileSystem = @import("../fs.zig").FileSystem; +const options = @import("../options.zig"); +const js_parser = @import("../js_parser.zig"); +const json_parser = @import("../json_parser.zig"); +const js_printer = @import("../js_printer.zig"); +const js_ast = @import("../js_ast.zig"); +const linker = @import("../linker.zig"); +const panicky = @import("../panic_handler.zig"); +const sync = @import("../sync.zig"); +const Api = @import("../api/schema.zig").Api; +const resolve_path = @import("../resolver/resolve_path.zig"); +const configureTransformOptionsForBun = @import("../javascript/jsc/config.zig").configureTransformOptionsForBun; +const Command = @import("../cli.zig").Command; +const bundler = @import("../bundler.zig"); +const NodeModuleBundle = @import("../node_module_bundle.zig").NodeModuleBundle; +const DotEnv = @import("../env_loader.zig"); +const which = @import("../which.zig").which; +const Run = @import("../bun_js.zig").Run; +var path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; +var path_buf2: [std.fs.MAX_PATH_BYTES]u8 = undefined; +const PathString = _global.PathString; + +const JSC = @import("javascript_core"); +const Jest = JSC.Jest; +const TestRunner = JSC.Jest.TestRunner; +const Test = TestRunner.Test; +pub const CommandLineReporter = struct { + jest: TestRunner, + callback: TestRunner.Callback, + last_dot: u32 = 0, + summary: Summary = Summary{}, + + pub const Summary = struct { + pass: u32 = 0, + expectations: u32 = 0, + fail: u32 = 0, + }; + + const DotColorMap = std.EnumMap(TestRunner.Test.Status, string); + const dots: DotColorMap = brk: { + var map: DotColorMap = DotColorMap.init(.{}); + map.put(TestRunner.Test.Status.pending, Output.RESET ++ Output.ED ++ Output.color_map.get("yellow").? ++ "." ++ Output.RESET); + map.put(TestRunner.Test.Status.pass, Output.RESET ++ Output.ED ++ Output.color_map.get("green").? ++ "." ++ Output.RESET); + map.put(TestRunner.Test.Status.fail, Output.RESET ++ Output.ED ++ Output.color_map.get("red").? ++ "." ++ Output.RESET); + break :brk map; + }; + + fn updateDots(this: *CommandLineReporter) void { + const statuses = this.jest.tests.items(.status); + var writer = Output.errorWriter(); + writer.writeAll("\r") catch unreachable; + if (Output.enable_ansi_colors_stderr) { + for (statuses) |status| { + writer.writeAll(dots.get(status).?) catch unreachable; + } + } else { + for (statuses) |_| { + writer.writeAll(".") catch unreachable; + } + } + } + + pub fn handleUpdateCount(cb: *TestRunner.Callback, _: u32, _: u32) void { + _ = cb; + } + + pub fn handleTestStart(_: *TestRunner.Callback, _: Test.ID) void { + // var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb); + } + pub fn handleTestPass(cb: *TestRunner.Callback, _: Test.ID, expectations: u32) void { + var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb); + // this.updateDots(); + this.summary.pass += 1; + this.summary.expectations += expectations; + } + pub fn handleTestFail(cb: *TestRunner.Callback, test_id: Test.ID, _: string, _: string, _: u32) void { + // var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb); + var this: *CommandLineReporter = @fieldParentPtr(CommandLineReporter, "callback", cb); + // this.updateDots(); + this.summary.fail += 1; + _ = test_id; + } +}; + +const Scanner = struct { + const Fifo = std.fifo.LinearFifo(ScanEntry, .Dynamic); + exclusion_names: []const []const u8 = &.{}, + filter_names: []const []const u8 = &.{}, + dirs_to_scan: Fifo, + results: std.ArrayList(_global.PathString), + fs: *FileSystem, + open_dir_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined, + scan_dir_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined, + options: *options.BundleOptions, + has_iterated: bool = false, + + const ScanEntry = struct { + relative_dir: _global.StoredFileDescriptorType, + dir_path: string, + name: strings.StringOrTinyString, + }; + + fn readDirWithName(this: *Scanner, name: string, handle: ?std.fs.Dir) !*FileSystem.RealFS.EntriesOption { + return try this.fs.fs.readDirectoryWithIterator(name, handle, *Scanner, this); + } + + pub fn scan(this: *Scanner, path_literal: string) void { + var parts = &[_]string{ this.fs.top_level_dir, path_literal }; + const path = this.fs.absBuf(parts, &this.scan_dir_buf); + var root = this.readDirWithName(path, null) catch |err| { + if (err == error.NotDir) { + if (this.isTestFile(path)) { + this.results.append(_global.PathString.init(this.fs.filename_store.append(@TypeOf(path), path) catch unreachable)) catch unreachable; + } + } + + return; + }; + + // you typed "." and we already scanned it + if (!this.has_iterated) { + if (@as(FileSystem.RealFS.EntriesOption.Tag, root.*) == .entries) { + var iter = root.entries.data.iterator(); + const fd = root.entries.fd; + while (iter.next()) |entry| { + this.next(entry.value, fd); + } + } + } + + while (this.dirs_to_scan.readItem()) |entry| { + var dir = std.fs.Dir{ .fd = entry.relative_dir }; + var parts2 = &[_]string{ entry.dir_path, entry.name.slice() }; + var path2 = this.fs.absBuf(parts2, &this.open_dir_buf); + this.open_dir_buf[path2.len] = 0; + var pathZ = this.open_dir_buf[path2.len - entry.name.slice().len .. path2.len :0]; + var child_dir = dir.openDirZ(pathZ, .{ .iterate = true }) catch continue; + path2 = this.fs.dirname_store.append(string, path2) catch unreachable; + FileSystem.setMaxFd(child_dir.fd); + _ = this.readDirWithName(path2, child_dir) catch continue; + } + } + + const test_name_suffixes = [_]string{ + ".test", + "_test", + ".spec", + "_spec", + }; + + pub fn couldBeTestFile(this: *Scanner, name: string) bool { + const extname = std.fs.path.extension(name); + if (!this.options.loader(extname).isJavaScriptLike()) return false; + const name_without_extension = name[0 .. name.len - extname.len]; + inline for (test_name_suffixes) |suffix| { + if (strings.endsWithComptime(name_without_extension, suffix)) return true; + } + + return false; + } + + pub fn doesAbsolutePathMatchFilter(this: *Scanner, name: string) bool { + if (this.filter_names.len == 0) return true; + + for (this.filter_names) |filter_name| { + if (strings.contains(name, filter_name)) return true; + } + + return false; + } + + pub fn isTestFile(this: *Scanner, name: string) bool { + return this.couldBeTestFile(name) and this.doesAbsolutePathMatchFilter(name); + } + + pub fn next(this: *Scanner, entry: *FileSystem.Entry, fd: _global.StoredFileDescriptorType) void { + const name = entry.base_lowercase(); + this.has_iterated = true; + switch (entry.kind(&this.fs.fs)) { + .dir => { + if (strings.eqlComptime(name, "node_modules") or strings.eqlComptime(name, ".git")) { + return; + } + + for (this.exclusion_names) |exclude_name| { + if (strings.eql(exclude_name, name)) return; + } + + this.dirs_to_scan.writeItem(.{ + .relative_dir = fd, + .name = entry.base_, + .dir_path = entry.dir, + }) catch unreachable; + }, + .file => { + // already seen it! + if (!entry.abs_path.isEmpty()) return; + + if (!this.couldBeTestFile(name)) return; + + var parts = &[_]string{ entry.dir, entry.base() }; + const path = this.fs.absBuf(parts, &this.open_dir_buf); + + if (!this.doesAbsolutePathMatchFilter(path)) return; + + entry.abs_path = _global.PathString.init(this.fs.filename_store.append(@TypeOf(path), path) catch unreachable); + this.results.append(entry.abs_path) catch unreachable; + }, + } + } +}; + +pub const TestCommand = struct { + pub const name = "wiptest"; + pub fn exec(ctx: Command.Context) !void { + var env_loader = brk: { + var map = try ctx.allocator.create(DotEnv.Map); + map.* = DotEnv.Map.init(ctx.allocator); + + var loader = try ctx.allocator.create(DotEnv.Loader); + loader.* = DotEnv.Loader.init(map, ctx.allocator); + break :brk loader; + }; + JSC.C.JSCInitialize(); + var reporter = try ctx.allocator.create(CommandLineReporter); + reporter.* = CommandLineReporter{ + .jest = TestRunner{ + .allocator = ctx.allocator, + .log = ctx.log, + .callback = undefined, + }, + .callback = undefined, + }; + reporter.callback = TestRunner.Callback{ + .onUpdateCount = CommandLineReporter.handleUpdateCount, + .onTestStart = CommandLineReporter.handleTestStart, + .onTestPass = CommandLineReporter.handleTestPass, + .onTestFail = CommandLineReporter.handleTestFail, + }; + reporter.jest.callback = &reporter.callback; + Jest.Jest.runner = &reporter.jest; + + js_ast.Expr.Data.Store.create(default_allocator); + js_ast.Stmt.Data.Store.create(default_allocator); + var vm = try JSC.VirtualMachine.init(ctx.allocator, ctx.args, null, ctx.log, env_loader); + vm.argv = ctx.positionals; + + try vm.bundler.configureDefines(); + + var scanner = Scanner{ + .dirs_to_scan = Scanner.Fifo.init(ctx.allocator), + .options = &vm.bundler.options, + .fs = vm.bundler.fs, + .filter_names = ctx.positionals[1..], + .results = std.ArrayList(PathString).init(ctx.allocator), + }; + + scanner.scan(scanner.fs.top_level_dir); + scanner.dirs_to_scan.deinit(); + + const test_files = scanner.results.toOwnedSlice(); + + // vm.bundler.fs.fs.readDirectory(_dir: string, _handle: ?std.fs.Dir) + runAllTests(reporter, vm, test_files, ctx.allocator); + + Output.pretty("\n", .{}); + Output.flush(); + + Output.prettyError("\n", .{}); + + if (reporter.summary.pass > 0) { + Output.prettyError("<r><green>", .{}); + } + + Output.prettyError(" {d:5>} pass<r>\n", .{reporter.summary.pass}); + + if (reporter.summary.fail > 0) { + Output.prettyError("<r><red>", .{}); + } else { + Output.prettyError("<r><d>", .{}); + } + + Output.prettyError(" {d:5>} fail<r>\n", .{reporter.summary.fail}); + + if (reporter.summary.fail == 0 and reporter.summary.expectations > 0) { + Output.prettyError("<r><green>", .{}); + } else { + Output.prettyError("<r>", .{}); + } + Output.prettyError(" {d:5>} expectations\n", .{reporter.summary.expectations}); + + Output.prettyError( + \\ Ran {d} tests across {d} files + , .{ + reporter.summary.fail + reporter.summary.pass, + test_files.len, + }); + Output.printStartEnd(ctx.start_time, std.time.nanoTimestamp()); + Output.prettyError("\n", .{}); + + Output.flush(); + + if (reporter.summary.fail > 0) { + std.os.exit(1); + } + } + + pub fn runAllTests( + reporter_: *CommandLineReporter, + vm_: *JSC.VirtualMachine, + files_: []const PathString, + allocator_: std.mem.Allocator, + ) void { + const Context = struct { + reporter: *CommandLineReporter, + vm: *JSC.VirtualMachine, + files: []const PathString, + allocator: std.mem.Allocator, + pub fn begin(this: *@This()) void { + var reporter = this.reporter; + var vm = this.vm; + var files = this.files; + var allocator = this.allocator; + for (files) |file_name| { + TestCommand.run(reporter, vm, file_name.slice(), allocator) catch {}; + } + } + }; + var ctx = Context{ .reporter = reporter_, .vm = vm_, .files = files_, .allocator = allocator_ }; + vm_.runWithAPILock(Context, &ctx, Context.begin); + } + + pub fn run( + reporter: *CommandLineReporter, + vm: *JSC.VirtualMachine, + file_name: string, + _: std.mem.Allocator, + ) !void { + defer { + js_ast.Expr.Data.Store.reset(); + js_ast.Stmt.Data.Store.reset(); + + if (vm.log.errors > 0) { + if (Output.enable_ansi_colors) { + vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), true) catch {}; + } else { + vm.log.printForLogLevelWithEnableAnsiColors(Output.errorWriter(), false) catch {}; + } + vm.log.msgs.clearRetainingCapacity(); + vm.log.errors = 0; + } + + Output.flush(); + } + + var file_start = reporter.jest.files.len; + var resolution = try vm.bundler.resolveEntryPoint(file_name); + + var promise = try vm.loadEntryPoint(resolution.path_pair.primary.text); + + while (promise.status(vm.global.vm()) == .Pending) { + vm.tick(); + } + + var result = promise.result(vm.global.vm()); + if (result.isError() or + result.isAggregateError(vm.global) or + result.isException(vm.global.vm())) + { + vm.defaultErrorHandler(result, null); + } + + reporter.updateDots(); + + var modules: []*Jest.DescribeScope = reporter.jest.files.items(.module_scope)[file_start..]; + for (modules) |module| { + module.runTests(vm.global.ref()); + } + + reporter.updateDots(); + } +}; diff --git a/src/cli/upgrade_command.zig b/src/cli/upgrade_command.zig index 3f6a4840d..672afb8c4 100644 --- a/src/cli/upgrade_command.zig +++ b/src/cli/upgrade_command.zig @@ -91,13 +91,12 @@ pub const UpgradeCheckerThread = struct { Output.Source.configureThread(); NetworkThread.init() catch unreachable; + defer { js_ast.Expr.Data.Store.deinit(); js_ast.Stmt.Data.Store.deinit(); } - var arena = std.heap.ArenaAllocator.init(default_allocator); - defer arena.deinit(); - const version = (try UpgradeCommand.getLatestVersion(arena.allocator(), env_loader, undefined, undefined, true)) orelse return; + var version = (try UpgradeCommand.getLatestVersion(default_allocator, env_loader, undefined, undefined, true)) orelse return; if (!version.isCurrent()) { if (version.name()) |name| { @@ -105,6 +104,8 @@ pub const UpgradeCheckerThread = struct { Output.flush(); } } + + version.buf.deinit(); } fn run(env_loader: *DotEnv.Loader) void { @@ -118,7 +119,7 @@ pub const UpgradeCheckerThread = struct { pub const UpgradeCommand = struct { pub const timeout: u32 = 30000; - const default_github_headers = "Acceptapplication/vnd.github.v3+json"; + const default_github_headers: string = "Acceptapplication/vnd.github.v3+json"; var github_repository_url_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var current_executable_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var unzip_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; @@ -132,6 +133,12 @@ pub const UpgradeCommand = struct { comptime silent: bool, ) !?Version { var headers_buf: string = default_github_headers; + // gonna have to free memory myself like a goddamn caveman due to a thread safety issue with ArenaAllocator + defer { + if (comptime silent) { + if (headers_buf.ptr != default_github_headers.ptr) allocator.free(headers_buf); + } + } var header_entries: Headers.Entries = .{}; const accept = Headers.Kv{ @@ -139,6 +146,7 @@ pub const UpgradeCommand = struct { .value = Api.StringPointer{ .offset = @intCast(u32, "Accept".len), .length = @intCast(u32, "application/vnd.github.v3+json".len) }, }; try header_entries.append(allocator, accept); + defer if (comptime silent) header_entries.deinit(allocator); // Incase they're using a GitHub proxy in e.g. China var github_api_domain: string = "api.github.com"; @@ -196,6 +204,7 @@ pub const UpgradeCommand = struct { } var log = logger.Log.init(allocator); + defer if (comptime silent) log.deinit(); var source = logger.Source.initPathString("releases.json", metadata_body.list.items); initializeStore(); var expr = ParseJSON(&source, &log, allocator) catch |err| { @@ -326,8 +335,6 @@ pub const UpgradeCommand = struct { std.os.exit(0); } - version.buf.deinit(); - return null; } const exe_subpath = Version.folder_name ++ std.fs.path.sep_str ++ "bun"; diff --git a/src/darwin_c.zig b/src/darwin_c.zig index e227ee8bf..e92312d74 100644 --- a/src/darwin_c.zig +++ b/src/darwin_c.zig @@ -9,6 +9,62 @@ const off_t = std.c.off_t; const errno = os.errno; const zeroes = mem.zeroes; +pub extern "c" fn copyfile(from: [*:0]const u8, to: [*:0]const u8, state: ?std.c.copyfile_state_t, flags: u32) c_int; +pub const COPYFILE_STATE_SRC_FD = @as(c_int, 1); +pub const COPYFILE_STATE_SRC_FILENAME = @as(c_int, 2); +pub const COPYFILE_STATE_DST_FD = @as(c_int, 3); +pub const COPYFILE_STATE_DST_FILENAME = @as(c_int, 4); +pub const COPYFILE_STATE_QUARANTINE = @as(c_int, 5); +pub const COPYFILE_STATE_STATUS_CB = @as(c_int, 6); +pub const COPYFILE_STATE_STATUS_CTX = @as(c_int, 7); +pub const COPYFILE_STATE_COPIED = @as(c_int, 8); +pub const COPYFILE_STATE_XATTRNAME = @as(c_int, 9); +pub const COPYFILE_STATE_WAS_CLONED = @as(c_int, 10); +pub const COPYFILE_DISABLE_VAR = "COPYFILE_DISABLE"; +pub const COPYFILE_ACL = @as(c_int, 1) << @as(c_int, 0); +pub const COPYFILE_STAT = @as(c_int, 1) << @as(c_int, 1); +pub const COPYFILE_XATTR = @as(c_int, 1) << @as(c_int, 2); +pub const COPYFILE_DATA = @as(c_int, 1) << @as(c_int, 3); +pub const COPYFILE_SECURITY = COPYFILE_STAT | COPYFILE_ACL; +pub const COPYFILE_METADATA = COPYFILE_SECURITY | COPYFILE_XATTR; +pub const COPYFILE_ALL = COPYFILE_METADATA | COPYFILE_DATA; +/// Descend into hierarchies +pub const COPYFILE_RECURSIVE = @as(c_int, 1) << @as(c_int, 15); +/// return flags for xattr or acls if set +pub const COPYFILE_CHECK = @as(c_int, 1) << @as(c_int, 16); +/// fail if destination exists +pub const COPYFILE_EXCL = @as(c_int, 1) << @as(c_int, 17); +/// don't follow if source is a symlink +pub const COPYFILE_NOFOLLOW_SRC = @as(c_int, 1) << @as(c_int, 18); +/// don't follow if dst is a symlink +pub const COPYFILE_NOFOLLOW_DST = @as(c_int, 1) << @as(c_int, 19); +/// unlink src after copy +pub const COPYFILE_MOVE = @as(c_int, 1) << @as(c_int, 20); +/// unlink dst before copy +pub const COPYFILE_UNLINK = @as(c_int, 1) << @as(c_int, 21); +pub const COPYFILE_NOFOLLOW = COPYFILE_NOFOLLOW_SRC | COPYFILE_NOFOLLOW_DST; +pub const COPYFILE_PACK = @as(c_int, 1) << @as(c_int, 22); +pub const COPYFILE_UNPACK = @as(c_int, 1) << @as(c_int, 23); +pub const COPYFILE_CLONE = @as(c_int, 1) << @as(c_int, 24); +pub const COPYFILE_CLONE_FORCE = @as(c_int, 1) << @as(c_int, 25); +pub const COPYFILE_RUN_IN_PLACE = @as(c_int, 1) << @as(c_int, 26); +pub const COPYFILE_DATA_SPARSE = @as(c_int, 1) << @as(c_int, 27); +pub const COPYFILE_PRESERVE_DST_TRACKED = @as(c_int, 1) << @as(c_int, 28); +pub const COPYFILE_VERBOSE = @as(c_int, 1) << @as(c_int, 30); +pub const COPYFILE_RECURSE_ERROR = @as(c_int, 0); +pub const COPYFILE_RECURSE_FILE = @as(c_int, 1); +pub const COPYFILE_RECURSE_DIR = @as(c_int, 2); +pub const COPYFILE_RECURSE_DIR_CLEANUP = @as(c_int, 3); +pub const COPYFILE_COPY_DATA = @as(c_int, 4); +pub const COPYFILE_COPY_XATTR = @as(c_int, 5); +pub const COPYFILE_START = @as(c_int, 1); +pub const COPYFILE_FINISH = @as(c_int, 2); +pub const COPYFILE_ERR = @as(c_int, 3); +pub const COPYFILE_PROGRESS = @as(c_int, 4); +pub const COPYFILE_CONTINUE = @as(c_int, 0); +pub const COPYFILE_SKIP = @as(c_int, 1); +pub const COPYFILE_QUIT = @as(c_int, 2); + // int clonefileat(int src_dirfd, const char * src, int dst_dirfd, const char * dst, int flags); pub extern "c" fn clonefileat(c_int, [*c]const u8, c_int, [*c]const u8, uint32_t: c_int) c_int; // int fclonefileat(int srcfd, int dst_dirfd, const char * dst, int flags); @@ -117,3 +173,295 @@ pub fn preallocate_file(fd: os.fd_t, offset: off_t, len: off_t) !void { std.mem.doNotOptimizeAway(&fstore); } + +pub const SystemErrno = enum(u8) { + SUCCESS = 0, + EPERM = 1, + ENOENT = 2, + ESRCH = 3, + EINTR = 4, + EIO = 5, + ENXIO = 6, + E2BIG = 7, + ENOEXEC = 8, + EBADF = 9, + ECHILD = 10, + EDEADLK = 11, + ENOMEM = 12, + EACCES = 13, + EFAULT = 14, + ENOTBLK = 15, + EBUSY = 16, + EEXIST = 17, + EXDEV = 18, + ENODEV = 19, + ENOTDIR = 20, + EISDIR = 21, + EINVAL = 22, + ENFILE = 23, + EMFILE = 24, + ENOTTY = 25, + ETXTBSY = 26, + EFBIG = 27, + ENOSPC = 28, + ESPIPE = 29, + EROFS = 30, + EMLINK = 31, + EPIPE = 32, + EDOM = 33, + ERANGE = 34, + EAGAIN = 35, + EINPROGRESS = 36, + EALREADY = 37, + ENOTSOCK = 38, + EDESTADDRREQ = 39, + EMSGSIZE = 40, + EPROTOTYPE = 41, + ENOPROTOOPT = 42, + EPROTONOSUPPORT = 43, + ESOCKTNOSUPPORT = 44, + ENOTSUP = 45, + EPFNOSUPPORT = 46, + EAFNOSUPPORT = 47, + EADDRINUSE = 48, + EADDRNOTAVAIL = 49, + ENETDOWN = 50, + ENETUNREACH = 51, + ENETRESET = 52, + ECONNABORTED = 53, + ECONNRESET = 54, + ENOBUFS = 55, + EISCONN = 56, + ENOTCONN = 57, + ESHUTDOWN = 58, + ETOOMANYREFS = 59, + ETIMEDOUT = 60, + ECONNREFUSED = 61, + ELOOP = 62, + ENAMETOOLONG = 63, + EHOSTDOWN = 64, + EHOSTUNREACH = 65, + ENOTEMPTY = 66, + EPROCLIM = 67, + EUSERS = 68, + EDQUOT = 69, + ESTALE = 70, + EREMOTE = 71, + EBADRPC = 72, + ERPCMISMATCH = 73, + EPROGUNAVAIL = 74, + EPROGMISMATCH = 75, + EPROCUNAVAIL = 76, + ENOLCK = 77, + ENOSYS = 78, + EFTYPE = 79, + EAUTH = 80, + ENEEDAUTH = 81, + EPWROFF = 82, + EDEVERR = 83, + EOVERFLOW = 84, + EBADEXEC = 85, + EBADARCH = 86, + ESHLIBVERS = 87, + EBADMACHO = 88, + ECANCELED = 89, + EIDRM = 90, + ENOMSG = 91, + EILSEQ = 92, + ENOATTR = 93, + EBADMSG = 94, + EMULTIHOP = 95, + ENODATA = 96, + ENOLINK = 97, + ENOSR = 98, + ENOSTR = 99, + EPROTO = 100, + ETIME = 101, + EOPNOTSUPP = 102, + ENOPOLICY = 103, + ENOTRECOVERABLE = 104, + EOWNERDEAD = 105, + EQFULL = 106, + + pub const max = 107; + + const LabelMap = std.EnumMap(SystemErrno, []const u8); + pub const labels: LabelMap = brk: { + var map: LabelMap = LabelMap.initFull(""); + map.put(.E2BIG, "Argument list too long"); + map.put(.EACCES, "Permission denied"); + map.put(.EADDRINUSE, "Address already in use"); + map.put(.EADDRNOTAVAIL, "Can’t assign requested address"); + map.put(.EAFNOSUPPORT, "Address family not supported by protocol family"); + map.put(.EAGAIN, "non-blocking and interrupt i/o. Resource temporarily unavailable"); + map.put(.EALREADY, "Operation already in progress"); + map.put(.EAUTH, "Authentication error"); + map.put(.EBADARCH, "Bad CPU type in executable"); + map.put(.EBADEXEC, "Program loading errors. Bad executable"); + map.put(.EBADF, "Bad file descriptor"); + map.put(.EBADMACHO, "Malformed Macho file"); + map.put(.EBADMSG, "Bad message"); + map.put(.EBADRPC, "RPC struct is bad"); + map.put(.EBUSY, "Device / Resource busy"); + map.put(.ECANCELED, "Operation canceled"); + map.put(.ECHILD, "No child processes"); + map.put(.ECONNABORTED, "Software caused connection abort"); + map.put(.ECONNREFUSED, "Connection refused"); + map.put(.ECONNRESET, "Connection reset by peer"); + map.put(.EDEADLK, "Resource deadlock avoided"); + map.put(.EDESTADDRREQ, "Destination address required"); + map.put(.EDEVERR, "Device error, for example paper out"); + map.put(.EDOM, "math software. Numerical argument out of domain"); + map.put(.EDQUOT, "Disc quota exceeded"); + map.put(.EEXIST, "File or folder exists"); + map.put(.EFAULT, "Bad address"); + map.put(.EFBIG, "File too large"); + map.put(.EFTYPE, "Inappropriate file type or format"); + map.put(.EHOSTDOWN, "Host is down"); + map.put(.EHOSTUNREACH, "No route to host"); + map.put(.EIDRM, "Identifier removed"); + map.put(.EILSEQ, "Illegal byte sequence"); + map.put(.EINPROGRESS, "Operation now in progress"); + map.put(.EINTR, "Interrupted system call"); + map.put(.EINVAL, "Invalid argument"); + map.put(.EIO, "Input/output error"); + map.put(.EISCONN, "Socket is already connected"); + map.put(.EISDIR, "Is a directory"); + map.put(.ELOOP, "Too many levels of symbolic links"); + map.put(.EMFILE, "Too many open files"); + map.put(.EMLINK, "Too many links"); + map.put(.EMSGSIZE, "Message too long"); + map.put(.EMULTIHOP, "Reserved"); + map.put(.ENAMETOOLONG, "File name too long"); + map.put(.ENEEDAUTH, "Need authenticator"); + map.put(.ENETDOWN, "ipc/network software – operational errors Network is down"); + map.put(.ENETRESET, "Network dropped connection on reset"); + map.put(.ENETUNREACH, "Network is unreachable"); + map.put(.ENFILE, "Too many open files in system"); + map.put(.ENOATTR, "Attribute not found"); + map.put(.ENOBUFS, "No buffer space available"); + map.put(.ENODATA, "No message available on STREAM"); + map.put(.ENODEV, "Operation not supported by device"); + map.put(.ENOENT, "No such file or directory"); + map.put(.ENOEXEC, "Exec format error"); + map.put(.ENOLCK, "No locks available"); + map.put(.ENOLINK, "Reserved"); + map.put(.ENOMEM, "Cannot allocate memory"); + map.put(.ENOMSG, "No message of desired type"); + map.put(.ENOPOLICY, "No such policy registered"); + map.put(.ENOPROTOOPT, "Protocol not available"); + map.put(.ENOSPC, "No space left on device"); + map.put(.ENOSR, "No STREAM resources"); + map.put(.ENOSTR, "Not a STREAM"); + map.put(.ENOSYS, "Function not implemented"); + map.put(.ENOTBLK, "Block device required"); + map.put(.ENOTCONN, "Socket is not connected"); + map.put(.ENOTDIR, "Not a directory"); + map.put(.ENOTEMPTY, "Directory not empty"); + map.put(.ENOTRECOVERABLE, "State not recoverable"); + map.put(.ENOTSOCK, "ipc/network software – argument errors. Socket operation on non-socket"); + map.put(.ENOTSUP, "Operation not supported"); + map.put(.ENOTTY, "Inappropriate ioctl for device"); + map.put(.ENXIO, "Device not configured"); + map.put(.EOVERFLOW, "Value too large to be stored in data type"); + map.put(.EOWNERDEAD, "Previous owner died"); + map.put(.EPERM, "Operation not permitted"); + map.put(.EPFNOSUPPORT, "Protocol family not supported"); + map.put(.EPIPE, "Broken pipe"); + map.put(.EPROCLIM, "quotas & mush. Too many processes"); + map.put(.EPROCUNAVAIL, "Bad procedure for program"); + map.put(.EPROGMISMATCH, "Program version wrong"); + map.put(.EPROGUNAVAIL, "RPC prog. not avail"); + map.put(.EPROTO, "Protocol error"); + map.put(.EPROTONOSUPPORT, "Protocol not supported"); + map.put(.EPROTOTYPE, "Protocol wrong type for socket"); + map.put(.EPWROFF, "Intelligent device errors. Device power is off"); + map.put(.EQFULL, "Interface output queue is full"); + map.put(.ERANGE, "Result too large"); + map.put(.EREMOTE, "Too many levels of remote in path"); + map.put(.EROFS, "Read-only file system"); + map.put(.ERPCMISMATCH, "RPC version wrong"); + map.put(.ESHLIBVERS, "Shared library version mismatch"); + map.put(.ESHUTDOWN, "Can’t send after socket shutdown"); + map.put(.ESOCKTNOSUPPORT, "Socket type not supported"); + map.put(.ESPIPE, "Illegal seek"); + map.put(.ESRCH, "No such process"); + map.put(.ESTALE, "Network File System. Stale NFS file handle"); + map.put(.ETIME, "STREAM ioctl timeout"); + map.put(.ETIMEDOUT, "Operation timed out"); + map.put(.ETOOMANYREFS, "Too many references: can’t splice"); + map.put(.ETXTBSY, "Text file busy"); + map.put(.EUSERS, "Too many users"); + // map.put(.EWOULDBLOCK, "Operation would block"); + map.put(.EXDEV, "Cross-device link"); + break :brk map; + }; +}; + +// Courtesy of https://github.com/nodejs/node/blob/master/deps/uv/src/unix/darwin-stub.h +pub const struct_CFArrayCallBacks = opaque {}; +pub const CFIndex = c_long; +pub const struct_CFRunLoopSourceContext = extern struct { + version: CFIndex, + info: ?*anyopaque, + pad: [7]?*anyopaque, + perform: ?fn (?*anyopaque) callconv(.C) void, +}; +pub const struct_FSEventStreamContext = extern struct { + version: CFIndex, + info: ?*anyopaque, + pad: [3]?*anyopaque, +}; +pub const struct_CFRange = extern struct { + location: CFIndex, + length: CFIndex, +}; +pub const CFAbsoluteTime = f64; +pub const CFTimeInterval = f64; +pub const FSEventStreamEventFlags = c_int; +pub const OSStatus = c_int; +pub const CFArrayCallBacks = struct_CFArrayCallBacks; +pub const CFRunLoopSourceContext = struct_CFRunLoopSourceContext; +pub const FSEventStreamContext = struct_FSEventStreamContext; +pub const FSEventStreamCreateFlags = u32; +pub const FSEventStreamEventId = u64; +pub const CFStringEncoding = c_uint; +pub const CFAllocatorRef = ?*anyopaque; +pub const CFArrayRef = ?*anyopaque; +pub const CFBundleRef = ?*anyopaque; +pub const CFDataRef = ?*anyopaque; +pub const CFDictionaryRef = ?*anyopaque; +pub const CFMutableDictionaryRef = ?*anyopaque; +pub const CFRange = struct_CFRange; +pub const CFRunLoopRef = ?*anyopaque; +pub const CFRunLoopSourceRef = ?*anyopaque; +pub const CFStringRef = ?*anyopaque; +pub const CFTypeRef = ?*anyopaque; +pub const FSEventStreamRef = ?*anyopaque; +pub const IOOptionBits = u32; +pub const io_iterator_t = c_uint; +pub const io_object_t = c_uint; +pub const io_service_t = c_uint; +pub const io_registry_entry_t = c_uint; +pub const FSEventStreamCallback = ?fn (FSEventStreamRef, ?*anyopaque, c_int, ?*anyopaque, [*c]const FSEventStreamEventFlags, [*c]const FSEventStreamEventId) callconv(.C) void; +pub const kCFStringEncodingUTF8: CFStringEncoding = @bitCast(CFStringEncoding, @as(c_int, 134217984)); +pub const noErr: OSStatus = 0; +pub const kFSEventStreamEventIdSinceNow: FSEventStreamEventId = @bitCast(FSEventStreamEventId, @as(c_longlong, -@as(c_int, 1))); +pub const kFSEventStreamCreateFlagNoDefer: c_int = 2; +pub const kFSEventStreamCreateFlagFileEvents: c_int = 16; +pub const kFSEventStreamEventFlagEventIdsWrapped: c_int = 8; +pub const kFSEventStreamEventFlagHistoryDone: c_int = 16; +pub const kFSEventStreamEventFlagItemChangeOwner: c_int = 16384; +pub const kFSEventStreamEventFlagItemCreated: c_int = 256; +pub const kFSEventStreamEventFlagItemFinderInfoMod: c_int = 8192; +pub const kFSEventStreamEventFlagItemInodeMetaMod: c_int = 1024; +pub const kFSEventStreamEventFlagItemIsDir: c_int = 131072; +pub const kFSEventStreamEventFlagItemModified: c_int = 4096; +pub const kFSEventStreamEventFlagItemRemoved: c_int = 512; +pub const kFSEventStreamEventFlagItemRenamed: c_int = 2048; +pub const kFSEventStreamEventFlagItemXattrMod: c_int = 32768; +pub const kFSEventStreamEventFlagKernelDropped: c_int = 4; +pub const kFSEventStreamEventFlagMount: c_int = 64; +pub const kFSEventStreamEventFlagRootChanged: c_int = 32; +pub const kFSEventStreamEventFlagUnmount: c_int = 128; +pub const kFSEventStreamEventFlagUserDropped: c_int = 2; diff --git a/src/deps/PLCrashReport.bindings.h b/src/deps/PLCrashReport.bindings.h deleted file mode 100644 index 2fbfc9bac..000000000 --- a/src/deps/PLCrashReport.bindings.h +++ /dev/null @@ -1,10 +0,0 @@ -#include <stdbool.h> -#include <stdint.h> - -extern bool PLCrashReportStart(const char *version, const char *basePath); -extern void PLCrashReportHandler(void *context); - -extern void PLCrashReportGenerate(); -extern void *PLCrashReportLoadPending(); - -extern uint16_t copyCrashReportPath(char *buf[1024]); diff --git a/src/deps/PLCrashReport.m b/src/deps/PLCrashReport.m deleted file mode 100644 index ecd099424..000000000 --- a/src/deps/PLCrashReport.m +++ /dev/null @@ -1,74 +0,0 @@ -#include "PLCrashReport.bindings.h" - -#include <PLCrashReporter/PLCrashReporter.h> - -NSString *crash_folder; - -@interface PLCrashReporter (PrivateMethods) - -- (id)initWithApplicationIdentifier:(NSString *)applicationIdentifier - appVersion:(NSString *)applicationVersion - appMarketingVersion:(NSString *)applicationMarketingVersion - configuration:(PLCrashReporterConfig *)configuration; - -@end - -void pl_crash_reporter_post_crash_callback(siginfo_t *info, ucontext_t *uap, - void *context) { - PLCrashReportHandler(context); -} - -static PLCrashReporter *reporter; - -NSString *v; -NSString *basePath_; -static void *handler; -bool PLCrashReportStart(const char *version, const char *basePath) { - PLCrashReporterConfig *config; - basePath_ = [NSString stringWithUTF8String:basePath]; - - handler = &pl_crash_reporter_post_crash_callback; - PLCrashReporterCallbacks callbacks = { - .version = 0, .context = NULL, .handleSignal = handler}; - config = [[PLCrashReporterConfig alloc] - initWithSignalHandlerType:PLCrashReporterSignalHandlerTypeBSD - symbolicationStrategy: - PLCrashReporterSymbolicationStrategyNone - shouldRegisterUncaughtExceptionHandler:YES - basePath:basePath_]; - - v = [[NSString alloc] initWithBytesNoCopy:version - length:strlen(version) - encoding:NSUTF8StringEncoding - freeWhenDone:NO]; - reporter = [[PLCrashReporter alloc] initWithApplicationIdentifier:@"bun" - appVersion:v - appMarketingVersion:v - configuration:config]; - - [reporter setValue:basePath_ forKey:@"_crashReportDirectory"]; - [reporter setCrashCallbacks:&callbacks]; - - return [reporter enableCrashReporter]; -} - -void PLCrashReportGenerate() { [reporter generateLiveReport]; } -void *PLCrashReportLoadPending() { - return [reporter loadPendingCrashReportData]; -} - -uint16_t copyCrashReportPath(char *buf[1024]) { - NSString *crashReportPath = [reporter crashReportPath]; - [crashReportPath getBytes:buf - maxLength:(1024 - 1) - usedLength:NULL - encoding:NSUTF8StringEncoding - options:0 - range:NSMakeRange(0, [crashReportPath length]) - remainingRange:NULL]; - size_t len = [crashReportPath length]; - if (len > 1024) { - len = 0; - } - return (uint16_t)len; -} diff --git a/src/deps/PLCrashReport.zig b/src/deps/PLCrashReport.zig deleted file mode 100644 index 9625cf441..000000000 --- a/src/deps/PLCrashReport.zig +++ /dev/null @@ -1,42 +0,0 @@ -const root = @import("root"); -const std = @import("std"); - -extern fn PLCrashReportStart(version: [*:0]const u8, base_path: [*:0]const u8) bool; -extern fn PLCrashReportGenerate() void; -extern fn PLCrashReportLoadPending() ?*anyopaque; -extern fn copyCrashReportPath(buf: *[1024]u8) u16; - -pub export fn PLCrashReportHandler(_: ?*anyopaque) void { - root.PLCrashReportHandler(); -} - -pub fn start( - comptime version: [*:0]const u8, -) bool { - has_started = true; - var base_path_buf: [1024]u8 = undefined; - var base_path: [:0]const u8 = ""; - const crash_path = "/crash/" ++ version ++ "/"; - if (std.os.getenvZ("BUN_INSTALL")) |bun_install| { - @memcpy(&base_path_buf, bun_install.ptr, bun_install.len); - std.mem.copy(u8, base_path_buf[bun_install.len..], crash_path); - base_path_buf[bun_install.len + crash_path.len] = 0; - base_path = base_path_buf[0 .. bun_install.len + crash_path.len :0]; - } else { - base_path = "/tmp/bun" ++ crash_path; - base_path_buf["/tmp/bun".len + crash_path.len] = 0; - } - return PLCrashReportStart(version, base_path.ptr); -} - -pub fn generate() void { - return PLCrashReportGenerate(); -} -var has_started = false; - -pub fn crashReportPath(buf: *[1024]u8) []const u8 { - if (!has_started) return ""; - - const len = copyCrashReportPath(buf); - return buf[0..len]; -} diff --git a/src/deps/backtrace.zig b/src/deps/backtrace.zig new file mode 100644 index 000000000..8448642de --- /dev/null +++ b/src/deps/backtrace.zig @@ -0,0 +1,159 @@ +pub const backtrace_state = struct_backtrace_state; +pub const struct_backtrace_state = opaque {}; +pub const backtrace_error_callback = ?fn ( + ?*anyopaque, + [*c]const u8, + c_int, +) callconv(.C) void; +pub extern fn backtrace_create_state( + filename: [*c]const u8, + threaded: c_int, + error_callback: backtrace_error_callback, + data: ?*anyopaque, +) ?*struct_backtrace_state; +pub const backtrace_full_callback = ?fn ( + ?*anyopaque, + usize, + [*c]const u8, + c_int, + [*c]const u8, +) callconv(.C) c_int; +pub extern fn backtrace_full( + state: ?*struct_backtrace_state, + skip: c_int, + callback: backtrace_full_callback, + error_callback: backtrace_error_callback, + data: ?*anyopaque, +) c_int; +pub const backtrace_simple_callback = ?fn (?*anyopaque, usize) callconv(.C) c_int; +pub extern fn backtrace_simple( + state: ?*struct_backtrace_state, + skip: c_int, + callback: backtrace_simple_callback, + error_callback: backtrace_error_callback, + data: ?*anyopaque, +) c_int; +pub extern fn backtrace_print(state: ?*struct_backtrace_state, skip: c_int, [*c]anyopaque) void; +pub extern fn backtrace_pcinfo( + state: ?*struct_backtrace_state, + pc: usize, + callback: backtrace_full_callback, + error_callback: backtrace_error_callback, + data: ?*anyopaque, +) c_int; +pub const backtrace_syminfo_callback = ?fn (?*anyopaque, usize, [*c]const u8, usize, usize) callconv(.C) void; +pub extern fn backtrace_syminfo( + state: ?*struct_backtrace_state, + addr: usize, + callback: backtrace_syminfo_callback, + error_callback: backtrace_error_callback, + data: ?*anyopaque, +) c_int; + +pub const BACKTRACE_SUPPORTED = @as(c_int, 1); +pub const BACKTRACE_USES_MALLOC = @as(c_int, 0); +pub const BACKTRACE_SUPPORTS_THREADS = @as(c_int, 1); +pub const BACKTRACE_SUPPORTS_DATA = @as(c_int, 1); + +fn error_callback(data: *anyopaque, msg: [*c]u8, errnum: c_int) callconv(.C) void { + _ = data; + _ = msg; + _ = errnum; +} + +pub const StackFrame = struct { + pc: usize, + filename: []const u8, + function_name: []const u8, + line_number: c_int, +}; + +pub const PrintCallback = fn (ctx: ?*anyopaque, frame: StackFrame) void; + +var callback: PrintCallback = undefined; +var callback_ctx: ?*anyopaque = null; + +const std = @import("std"); + +noinline fn full_callback(_: ?*anyopaque, pc: usize, filename: [*c]const u8, line_number: c_int, function_name: [*c]const u8) callconv(.C) c_int { + var stack_frame = StackFrame{ + .pc = pc, + .line_number = line_number, + .function_name = if (function_name) |fn_| std.mem.span(fn_) else "", + .filename = if (filename) |fn_| std.mem.span(fn_) else "", + }; + callback(callback_ctx, stack_frame); + return 0; +} + +var state: ?*backtrace_state = null; +pub inline fn print() void { + state = backtrace_create_state(null, BACKTRACE_SUPPORTS_THREADS, null, null); + _ = backtrace_full(state, 2, full_callback, null, null); +} + +const builtin = @import("builtin"); +const ErrorCallback = fn (sig: i32, addr: usize) void; +var on_error: ?ErrorCallback = null; +noinline fn sigaction_handler(sig: i32, info: *const std.os.siginfo_t, _: ?*const anyopaque) callconv(.C) void { + // Prevent recursive calls + os.sigaction(os.SIG.ABRT, null, null); + os.sigaction(os.SIG.BUS, null, null); + os.sigaction(os.SIG.FPE, null, null); + os.sigaction(os.SIG.ILL, null, null); + os.sigaction(os.SIG.SEGV, null, null); + os.sigaction(os.SIG.TRAP, null, null); + + const addr = switch (comptime builtin.target.os.tag) { + .linux => @ptrToInt(info.fields.sigfault.addr), + .macos, .freebsd => @ptrToInt(info.addr), + .netbsd => @ptrToInt(info.info.reason.fault.addr), + .openbsd => @ptrToInt(info.data.fault.addr), + .solaris => @ptrToInt(info.reason.fault.addr), + else => unreachable, + }; + if (on_error) |handle| handle(sig, addr); +} + +pub fn reloadHandlers() void { + os.sigaction(os.SIG.ABRT, null, null); + os.sigaction(os.SIG.BUS, null, null); + os.sigaction(os.SIG.FPE, null, null); + os.sigaction(os.SIG.ILL, null, null); + os.sigaction(os.SIG.SEGV, null, null); + os.sigaction(os.SIG.TRAP, null, null); + + var act = os.Sigaction{ + .handler = .{ .sigaction = sigaction_handler }, + .mask = os.empty_sigset, + .flags = (os.SA.SIGINFO | os.SA.RESTART | os.SA.RESETHAND), + }; + + os.sigaction(os.SIG.ABRT, &act, null); + os.sigaction(os.SIG.BUS, &act, null); + os.sigaction(os.SIG.FPE, &act, null); + os.sigaction(os.SIG.ILL, &act, null); + os.sigaction(os.SIG.SEGV, &act, null); + os.sigaction(os.SIG.TRAP, &act, null); +} +const os = std.os; +pub fn start(ctx: ?*anyopaque, callback_: PrintCallback, onError: ErrorCallback) bool { + callback_ctx = ctx; + callback = callback_; + on_error = onError; + + var act = os.Sigaction{ + .handler = .{ .sigaction = sigaction_handler }, + .mask = os.empty_sigset, + .flags = (os.SA.SIGINFO | os.SA.RESTART | os.SA.RESETHAND), + }; + + os.sigaction(os.SIG.ABRT, &act, null); + os.sigaction(os.SIG.BUS, &act, null); + os.sigaction(os.SIG.FPE, &act, null); + os.sigaction(os.SIG.ILL, &act, null); + os.sigaction(os.SIG.SEGV, &act, null); + os.sigaction(os.SIG.TRAP, &act, null); + + return true; +} diff --git a/src/deps/libbacktrace b/src/deps/libbacktrace new file mode 160000 +Subproject d0f5e95a87a4d3e0a1ed6c069b5dae7cbab3ed2 diff --git a/src/deps/mimalloc b/src/deps/mimalloc -Subproject f412df7a2b64421e1f1d61fde6055a6ea288e8f +Subproject d2e727f0e871cd35305bdb7bc3983cf60744175 diff --git a/src/exact_size_matcher.zig b/src/exact_size_matcher.zig index 19fbb5138..011adb7f8 100644 --- a/src/exact_size_matcher.zig +++ b/src/exact_size_matcher.zig @@ -17,8 +17,37 @@ pub fn ExactSizeMatcher(comptime max_bytes: usize) type { pub fn match(str: anytype) T { switch (str.len) { 1...max_bytes - 1 => { - var tmp = std.mem.zeroes([max_bytes]u8); - std.mem.copy(u8, &tmp, str[0..str.len]); + var tmp: [max_bytes]u8 = undefined; + if (comptime std.meta.trait.isSlice(@TypeOf(str))) { + @memcpy(&tmp, str.ptr, str.len); + @memset(tmp[str.len..].ptr, 0, tmp[str.len..].len); + } else { + @memcpy(&tmp, str, str.len); + @memset(tmp[str.len..], 0, tmp[str.len..].len); + } + + return std.mem.readIntNative(T, &tmp); + }, + max_bytes => { + return std.mem.readIntSliceNative(T, str); + }, + 0 => { + return 0; + }, + else => { + return std.math.maxInt(T); + }, + } + } + + pub fn matchLower(str: anytype) T { + switch (str.len) { + 1...max_bytes - 1 => { + var tmp: [max_bytes]u8 = undefined; + for (str) |char, i| { + tmp[i] = std.ascii.toLower(char); + } + @memset(tmp[str.len..].ptr, 0, tmp[str.len..].len); return std.mem.readIntNative(T, &tmp); }, max_bytes => { @@ -58,7 +87,7 @@ test "ExactSizeMatcher 5 letter" { test "ExactSizeMatcher 4 letter" { const Four = ExactSizeMatcher(4); - const word = "from"; + var word = "from".*; try expect(Four.match(word) == Four.case("from")); try expect(Four.match(word) != Four.case("fro")); } diff --git a/src/feature_flags.zig b/src/feature_flags.zig index 42c1d1782..679ce2831 100644 --- a/src/feature_flags.zig +++ b/src/feature_flags.zig @@ -45,6 +45,8 @@ pub const allow_json_single_quotes = true; pub const react_specific_warnings = true; +pub const log_allocations = false; + pub const CSSInJSImportBehavior = enum { // When you import a .css file and you reference the import in JavaScript // Just return whatever the property key they referenced was @@ -86,3 +88,5 @@ pub const disable_compression_in_http_client = false; pub const use_libgit2 = true; pub const atomic_file_watcher = env.isLinux; + +pub const node_streams = env.isDebug or env.isTest; diff --git a/src/fs.zig b/src/fs.zig index f2b6073c2..694a6d3a2 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -78,6 +78,10 @@ pub const BytecodeCacheFetcher = struct { pub const FileSystem = struct { allocator: std.mem.Allocator, top_level_dir: string = "/", + + // used on subsequent updates + top_level_dir_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined, + fs: Implementation, dirname_store: *DirnameStore, @@ -170,7 +174,7 @@ pub const FileSystem = struct { } pub const DirEntry = struct { - pub const EntryMap = hash_map.StringHashMap(*Entry); + pub const EntryMap = hash_map.StringHashMapUnmanaged(*Entry); pub const EntryStore = allocators.BSSList(Entry, Preallocate.Counts.files); dir: string, fd: StoredFileDescriptorType = 0, @@ -180,7 +184,7 @@ pub const FileSystem = struct { // // dir.data.remove(name); // } - pub fn addEntry(dir: *DirEntry, entry: std.fs.Dir.Entry) !void { + pub fn addEntry(dir: *DirEntry, entry: std.fs.Dir.Entry, allocator: std.mem.Allocator, comptime Iterator: type, iterator: Iterator) !void { var _kind: Entry.Kind = undefined; switch (entry.kind) { .Directory => { @@ -228,7 +232,12 @@ pub const FileSystem = struct { const stored_name = stored.base(); - try dir.data.put(stored.base_lowercase(), stored); + try dir.data.put(allocator, stored.base_lowercase(), stored); + + if (comptime Iterator != void) { + iterator.next(stored, dir.fd); + } + if (comptime FeatureFlags.verbose_fs) { if (_kind == .dir) { Output.prettyln(" + {s}/", .{stored_name}); @@ -238,16 +247,12 @@ pub const FileSystem = struct { } } - pub fn empty(dir: string, allocator: std.mem.Allocator) DirEntry { - return DirEntry{ .dir = dir, .data = EntryMap.init(allocator) }; - } - - pub fn init(dir: string, allocator: std.mem.Allocator) DirEntry { + pub fn init(dir: string) DirEntry { if (comptime FeatureFlags.verbose_fs) { Output.prettyln("\n {s}", .{dir}); } - return DirEntry{ .dir = dir, .data = EntryMap.init(allocator) }; + return DirEntry{ .dir = dir, .data = EntryMap{} }; } pub const Err = struct { @@ -255,9 +260,9 @@ pub const FileSystem = struct { canonical_error: anyerror, }; - pub fn deinit(d: *DirEntry) void { - d.data.allocator.free(d.dir); - d.data.deinit(); + pub fn deinit(d: *DirEntry, allocator: std.mem.Allocator) void { + d.data.deinit(allocator); + allocator.free(d.dir); } pub fn get(entry: *const DirEntry, _query: string) ?Entry.Lookup { @@ -371,7 +376,8 @@ pub const FileSystem = struct { pub fn kind(entry: *Entry, fs: *Implementation) Kind { if (entry.need_stat) { entry.need_stat = false; - entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch unreachable; + // This is technically incorrect, but we are choosing not to handle errors here + entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch return entry.cache.kind; } return entry.cache.kind; } @@ -379,7 +385,9 @@ pub const FileSystem = struct { pub fn symlink(entry: *Entry, fs: *Implementation) string { if (entry.need_stat) { entry.need_stat = false; - entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch unreachable; + // This is technically incorrect, but we are choosing not to handle errors here + // This error can happen if the file was deleted between the time the directory was scanned and the time it was read + entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd) catch return ""; } return entry.cache.symlink.slice(); } @@ -747,10 +755,13 @@ pub const FileSystem = struct { fs: *RealFS, _dir: string, handle: std.fs.Dir, + comptime Iterator: type, + iterator: Iterator, ) !DirEntry { var iter: std.fs.Dir.Iterator = handle.iterate(); - var dir = DirEntry.init(_dir, fs.allocator); - errdefer dir.deinit(); + var dir = DirEntry.init(_dir); + const allocator = fs.allocator; + errdefer dir.deinit(allocator); if (FeatureFlags.store_file_descriptors) { FileSystem.setMaxFd(handle.fd); @@ -758,7 +769,7 @@ pub const FileSystem = struct { } while (try iter.next()) |_entry| { - try dir.addEntry(_entry); + try dir.addEntry(_entry, allocator, Iterator, iterator); } return dir; @@ -783,6 +794,10 @@ pub const FileSystem = struct { threadlocal var temp_entries_option: EntriesOption = undefined; pub fn readDirectory(fs: *RealFS, _dir: string, _handle: ?std.fs.Dir) !*EntriesOption { + return readDirectoryWithIterator(fs, _dir, _handle, void, void{}); + } + + pub fn readDirectoryWithIterator(fs: *RealFS, _dir: string, _handle: ?std.fs.Dir, comptime Iterator: type, iterator: Iterator) !*EntriesOption { var dir = _dir; var cache_result: ?allocators.Result = null; if (comptime FeatureFlags.enable_entry_cache) { @@ -821,6 +836,8 @@ pub const FileSystem = struct { var entries = fs.readdir( dir, handle, + Iterator, + iterator, ) catch |err| { return fs.readDirectoryError(dir, err) catch unreachable; }; @@ -1064,6 +1081,10 @@ pub const Path = struct { is_disabled: bool = false, is_symlink: bool = false, + pub fn isBun(this: *const Path) bool { + return strings.eqlComptime(this.namespace, "bun"); + } + pub const PackageRelative = struct { path: string, name: string, @@ -1213,6 +1234,12 @@ pub const Path = struct { } }; +// pub fn customRealpath(allocator: std.mem.Allocator, path: string) !string { +// var opened = try std.os.open(path, if (Environment.isLinux) std.os.O.PATH else std.os.O.RDONLY, 0); +// defer std.os.close(opened); + +// } + test "PathName.init" { var file = "/root/directory/file.ext".*; const res = PathName.init( diff --git a/src/generated_versions_list.zig b/src/generated_versions_list.zig new file mode 100644 index 000000000..5e2c720be --- /dev/null +++ b/src/generated_versions_list.zig @@ -0,0 +1,9 @@ +// AUTO-GENERATED FILE. Created via .scripts/write-versions.sh + +pub const webkit = "96e77eccfde8dc9c207520d8ced856d8bdb8d386"; +pub const mimalloc = "f412df7a2b64421e1f1d61fde6055a6ea288e8f5"; +pub const libarchive = "dc321febde83dd0f31158e1be61a7aedda65e7a2"; +pub const picohttpparser = "066d2b1e9ab820703db0837a7255d92d30f0c9f5"; +pub const boringssl = "b3ed071ecc4efb77afd0a025ea1078da19578bfd"; +pub const zlib = "959b4ea305821e753385e873ec4edfaa9a5d49b7"; +pub const zig = @import("std").fmt.comptimePrint("{}", .{@import("builtin").zig_version}); diff --git a/src/global.zig b/src/global.zig index 772e7b6fe..046496029 100644 --- a/src/global.zig +++ b/src/global.zig @@ -12,6 +12,7 @@ pub const C = @import("c.zig"); pub const FeatureFlags = @import("feature_flags.zig"); const root = @import("root"); +pub const meta = @import("./meta.zig"); pub const Output = struct { // These are threadlocal so we don't have stdout/stderr writing on top of each other @@ -215,6 +216,18 @@ pub const Output = struct { return source.stream.writer(); } + pub fn resetTerminal() void { + if (!enable_ansi_colors) { + return; + } + + if (enable_ansi_colors_stderr) { + _ = source.error_stream.write("\x1b[H\x1b[2J") catch 0; + } else { + _ = source.stream.write("\x1b[H\x1b[2J") catch 0; + } + } + pub fn flush() void { if (Environment.isNative and source_set) { source.buffered_stream.flush() catch {}; @@ -336,7 +349,7 @@ pub const Output = struct { // <d> - dim // </r> - reset // <r> - reset - const ED = "\x1b["; + pub const ED = "\x1b["; pub const color_map = std.ComptimeStringMap(string, .{ &.{ "black", ED ++ "30m" }, &.{ "blue", ED ++ "34m" }, @@ -349,7 +362,7 @@ pub const Output = struct { &.{ "white", ED ++ "37m" }, &.{ "yellow", ED ++ "33m" }, }); - + pub const RESET = "\x1b[0m"; pub fn prettyFmt(comptime fmt: string, comptime is_enabled: bool) string { comptime var new_fmt: [fmt.len * 4]u8 = undefined; comptime var new_fmt_i: usize = 0; @@ -415,7 +428,7 @@ pub const Output = struct { } if (is_reset) { - const reset_sequence = "\x1b[0m"; + const reset_sequence = RESET; orig = new_fmt_i; new_fmt_i += reset_sequence.len; std.mem.copy(u8, new_fmt[orig..new_fmt_i], reset_sequence); @@ -526,7 +539,10 @@ pub const Output = struct { source.error_stream.writer().print(fmt, args) catch unreachable; root.console_error(root.Uint8Array.fromSlice(source.err_buffer[0..source.error_stream.pos])); } else { - std.fmt.format(source.error_stream.writer(), fmt, args) catch unreachable; + if (enable_buffering) + std.fmt.format(source.buffered_error_stream.writer(), fmt, args) catch {} + else + std.fmt.format(source.error_stream.writer(), fmt, args) catch {}; } } }; @@ -548,12 +564,13 @@ pub const Global = struct { long_running: bool = false, }; - pub inline fn mimalloc_cleanup() void { + pub inline fn mimalloc_cleanup(force: bool) void { if (comptime use_mimalloc) { const Mimalloc = @import("./allocators/mimalloc.zig"); - Mimalloc.mi_collect(false); + Mimalloc.mi_collect(force); } } + pub const versions = @import("./generated_versions_list.zig"); // Enabling huge pages slows down bun by 8x or so // Keeping this code for: diff --git a/src/http.zig b/src/http.zig index 844e36ac0..243ad976c 100644 --- a/src/http.zig +++ b/src/http.zig @@ -25,6 +25,7 @@ const Options = @import("./options.zig"); const Fallback = @import("./runtime.zig").Fallback; const ErrorCSS = @import("./runtime.zig").ErrorCSS; const ErrorJS = @import("./runtime.zig").ErrorJS; +const Runtime = @import("./runtime.zig").Runtime; const Css = @import("css_scanner.zig"); const NodeModuleBundle = @import("./node_module_bundle.zig").NodeModuleBundle; const resolve_path = @import("./resolver/resolve_path.zig"); @@ -1069,6 +1070,9 @@ pub const RequestContext = struct { env_loader: *DotEnv.Loader, origin: ZigURL, client_bundler: Bundler, + vm: *JavaScript.VirtualMachine = undefined, + start_timer: std.time.Timer = undefined, + entry_point: string = "", pub fn handleJSError( this: *HandlerThread, @@ -1233,72 +1237,13 @@ pub const RequestContext = struct { _spawn(handler) catch {}; } - pub fn _spawn(handler: *HandlerThread) !void { + pub fn startJavaScript(handler: *HandlerThread) void { defer { javascript_disabled = true; } - var start_timer = std.time.Timer.start() catch unreachable; - - Output.Source.configureThread(); - @import("javascript/jsc/javascript_core_c_api.zig").JSCInitialize(); - - js_ast.Stmt.Data.Store.create(std.heap.c_allocator); - js_ast.Expr.Data.Store.create(std.heap.c_allocator); - - var vm = JavaScript.VirtualMachine.init( - std.heap.c_allocator, - handler.args, - handler.existing_bundle, - handler.log, - handler.env_loader, - ) catch |err| { - handler.handleJSError(.create_vm, err) catch {}; - return; - }; - vm.bundler.log = handler.log; - std.debug.assert(JavaScript.VirtualMachine.vm_loaded); - javascript_vm = vm; - vm.bundler.options.origin = handler.origin; - const boot = vm.bundler.options.framework.?.server.path; - std.debug.assert(boot.len > 0); - errdefer vm.deinit(); - vm.watcher = handler.watcher; + var vm = handler.vm; + const entry_point = handler.entry_point; { - defer vm.flush(); - vm.bundler.configureRouter(false) catch |err| { - handler.handleJSError(.configure_router, err) catch {}; - return; - }; - vm.bundler.configureDefines() catch |err| { - handler.handleJSError(.configure_defines, err) catch {}; - return; - }; - - var entry_point = boot; - if (!std.fs.path.isAbsolute(entry_point)) { - const resolved_entry_point = vm.bundler.resolver.resolve( - std.fs.path.dirname(boot) orelse vm.bundler.fs.top_level_dir, - vm.bundler.normalizeEntryPointPath(boot), - .entry_point, - ) catch |err| { - try handler.handleJSError( - .resolve_entry_point, - err, - ); - return; - }; - entry_point = (resolved_entry_point.pathConst() orelse { - handler.handleJSErrorFmt( - .resolve_entry_point, - error.EntryPointDisabled, - "<r>JavaScript VM failed to start due to disabled entry point: <r><b>\"{s}\"", - .{resolved_entry_point.path_pair.primary.text}, - ) catch {}; - - return; - }).text; - } - var load_result = vm.loadEntryPoint( entry_point, ) catch |err| { @@ -1308,6 +1253,7 @@ pub const RequestContext = struct { "<r>JavaScript VM failed to start.\n<red>{s}:<r> while loading <r><b>\"{s}\"", .{ @errorName(err), entry_point }, ) catch {}; + vm.flush(); return; }; @@ -1323,6 +1269,7 @@ pub const RequestContext = struct { "<r>JavaScript VM failed to start.\nwhile loading <r><b>\"{s}\"", .{entry_point}, ) catch {}; + vm.flush(); return; }, } @@ -1334,6 +1281,7 @@ pub const RequestContext = struct { "<r><red>error<r>: Framework didn't run <b><cyan>addEventListener(\"fetch\", callback)<r>, which means it can't accept HTTP requests.\nShutting down JS.", .{}, ) catch {}; + vm.flush(); return; } } @@ -1341,10 +1289,9 @@ pub const RequestContext = struct { js_ast.Stmt.Data.Store.reset(); js_ast.Expr.Data.Store.reset(); JavaScript.Bun.flushCSSImports(); - vm.flush(); - Output.printElapsed(@intToFloat(f64, (start_timer.read())) / std.time.ns_per_ms); + Output.printElapsed(@intToFloat(f64, (handler.start_timer.read())) / std.time.ns_per_ms); if (vm.bundler.options.framework.?.display_name.len > 0) { Output.prettyError( @@ -1362,10 +1309,85 @@ pub const RequestContext = struct { Output.flush(); - try runLoop( + runLoop( vm, handler, - ); + ) catch {}; + } + + pub fn _spawn(handler: *HandlerThread) !void { + handler.start_timer = std.time.Timer.start() catch unreachable; + + Output.Source.configureThread(); + @import("javascript/jsc/javascript_core_c_api.zig").JSCInitialize(); + + js_ast.Stmt.Data.Store.create(std.heap.c_allocator); + js_ast.Expr.Data.Store.create(std.heap.c_allocator); + + var vm = JavaScript.VirtualMachine.init( + std.heap.c_allocator, + handler.args, + handler.existing_bundle, + handler.log, + handler.env_loader, + ) catch |err| { + handler.handleJSError(.create_vm, err) catch {}; + javascript_disabled = true; + return; + }; + vm.is_from_devserver = true; + vm.bundler.log = handler.log; + std.debug.assert(JavaScript.VirtualMachine.vm_loaded); + javascript_vm = vm; + vm.bundler.options.origin = handler.origin; + const boot = vm.bundler.options.framework.?.server.path; + std.debug.assert(boot.len > 0); + errdefer vm.deinit(); + vm.watcher = handler.watcher; + { + vm.bundler.configureRouter(false) catch |err| { + handler.handleJSError(.configure_router, err) catch {}; + vm.flush(); + javascript_disabled = true; + return; + }; + vm.bundler.configureDefines() catch |err| { + handler.handleJSError(.configure_defines, err) catch {}; + vm.flush(); + javascript_disabled = true; + return; + }; + + var entry_point = boot; + if (!std.fs.path.isAbsolute(entry_point)) { + const resolved_entry_point = vm.bundler.resolver.resolve( + std.fs.path.dirname(boot) orelse vm.bundler.fs.top_level_dir, + vm.bundler.normalizeEntryPointPath(boot), + .entry_point, + ) catch |err| { + try handler.handleJSError( + .resolve_entry_point, + err, + ); + javascript_disabled = true; + return; + }; + entry_point = (resolved_entry_point.pathConst() orelse { + handler.handleJSErrorFmt( + .resolve_entry_point, + error.EntryPointDisabled, + "<r>JavaScript VM failed to start due to disabled entry point: <r><b>\"{s}\"", + .{resolved_entry_point.path_pair.primary.text}, + ) catch {}; + javascript_disabled = true; + return; + }).text; + } + + handler.entry_point = entry_point; + } + handler.vm = vm; + vm.global.vm().holdAPILock(handler, JavaScript.OpaqueWrap(HandlerThread, startJavaScript)); } var __arena: std.heap.ArenaAllocator = undefined; @@ -1395,7 +1417,7 @@ pub const RequestContext = struct { Output.flush(); JavaScript.VirtualMachine.vm.arena.deinit(); JavaScript.VirtualMachine.vm.has_loaded = false; - mimalloc.mi_collect(false); + Global.mimalloc_cleanup(false); } var handler: *JavaScriptHandler = try channel.readItem(); @@ -1944,7 +1966,7 @@ pub const RequestContext = struct { }; pub fn writeETag(this: *RequestContext, buffer: anytype) !bool { - const strong_etag = std.hash.Wyhash.hash(1, buffer); + const strong_etag = std.hash.Wyhash.hash(0, buffer); const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{}); this.appendHeader("ETag", etag_content_slice); @@ -2074,12 +2096,12 @@ pub const RequestContext = struct { // Always cache css & json files, even big ones // css is especially important because we want to try and skip having the browser parse it whenever we can if (buf.len < 16 * 16 * 16 * 16 or chunky._loader == .css or chunky._loader == .json) { - const strong_etag = std.hash.Wyhash.hash(1, buf); + const strong_etag = std.hash.Wyhash.hash(0, buf); const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{}); chunky.rctx.appendHeader("ETag", etag_content_slice); if (chunky.rctx.header("If-None-Match")) |etag_header| { - if (std.mem.eql(u8, etag_content_slice, etag_header)) { + if (strings.eqlLong(etag_content_slice, etag_header, true)) { try chunky.rctx.sendNotModified(); return; } @@ -2176,12 +2198,12 @@ pub const RequestContext = struct { .css => try ctx.sendNoContent(), .js, .jsx, .ts, .tsx, .json => { const buf = "export default {};"; - const strong_etag = comptime std.hash.Wyhash.hash(1, buf); + const strong_etag = comptime std.hash.Wyhash.hash(0, buf); const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{}); ctx.appendHeader("ETag", etag_content_slice); if (ctx.header("If-None-Match")) |etag_header| { - if (std.mem.eql(u8, etag_content_slice, etag_header)) { + if (strings.eqlLong(etag_content_slice, etag_header, true)) { try ctx.sendNotModified(); return; } @@ -2231,7 +2253,7 @@ pub const RequestContext = struct { // if (result.mime_type.category != .html) { // hash(absolute_file_path, size, mtime) - var weak_etag = std.hash.Wyhash.init(1); + var weak_etag = std.hash.Wyhash.init(0); weak_etag_buffer[0] = 'W'; weak_etag_buffer[1] = '/'; weak_etag.update(result.file.input.text); @@ -2249,7 +2271,7 @@ pub const RequestContext = struct { ctx.appendHeader("ETag", complete_weak_etag); if (ctx.header("If-None-Match")) |etag_header| { - if (strings.eql(complete_weak_etag, etag_header)) { + if (strings.eqlLong(complete_weak_etag, etag_header, true)) { try ctx.sendNotModified(); return; } @@ -2325,13 +2347,13 @@ pub const RequestContext = struct { const blob: Blob = brk: { // It could be a blob either for macros or for JS thread if (JavaScriptHandler.javascript_vm) |vm| { - if (vm.blobs.get(id)) |blob| { + if (vm.blobs.?.get(id)) |blob| { break :brk blob; } } if (JavaScript.VirtualMachine.vm_loaded) { - if (JavaScript.VirtualMachine.vm.blobs.get(id)) |blob| { + if (JavaScript.VirtualMachine.vm.blobs.?.get(id)) |blob| { break :brk blob; } } @@ -2366,6 +2388,9 @@ pub const RequestContext = struct { if (strings.eqlComptime(path, "error.js")) { const buffer = ErrorJS.sourceContent(); ctx.appendHeader("Content-Type", MimeType.javascript.value); + ctx.appendHeader("Cache-Control", "public, max-age=3600"); + ctx.appendHeader("Age", "0"); + if (FeatureFlags.strong_etags_for_built_files) { const did_send = ctx.writeETag(buffer) catch false; if (did_send) return; @@ -2386,6 +2411,9 @@ pub const RequestContext = struct { if (strings.eqlComptime(path, "erro.css")) { const buffer = ErrorCSS.sourceContent(); ctx.appendHeader("Content-Type", MimeType.css.value); + ctx.appendHeader("Cache-Control", "public, max-age=3600"); + ctx.appendHeader("Age", "0"); + if (FeatureFlags.strong_etags_for_built_files) { const did_send = ctx.writeETag(buffer) catch false; if (did_send) return; @@ -2418,6 +2446,28 @@ pub const RequestContext = struct { return; } + if (strings.eqlComptime(path, "runtime")) { + const buffer = Runtime.sourceContent(); + ctx.appendHeader("Content-Type", MimeType.javascript.value); + ctx.appendHeader("Cache-Control", "public, max-age=3600"); + ctx.appendHeader("Age", "0"); + if (FeatureFlags.strong_etags_for_built_files) { + const did_send = ctx.writeETag(buffer) catch false; + if (did_send) return; + } + + if (buffer.len == 0) { + return try ctx.sendNoContent(); + } + const send_body = ctx.method == .GET; + defer ctx.done(); + try ctx.writeStatus(200); + try ctx.prepareToSendBody(buffer.len, false); + if (!send_body) return; + _ = try ctx.writeSocket(buffer, SOCKET_FLAGS); + return; + } + try ctx.sendNotFound(); return; } diff --git a/src/identity_context.zig b/src/identity_context.zig index b28cac1cc..299907b34 100644 --- a/src/identity_context.zig +++ b/src/identity_context.zig @@ -12,7 +12,7 @@ pub fn IdentityContext(comptime Key: type) type { /// When storing hashes as keys in a hash table, we don't want to hash the hashes or else we increase the chance of collisions. This is also marginally faster since it means hashing less stuff. /// `ArrayIdentityContext` and `IdentityContext` are distinct because ArrayHashMap expects u32 hashes but HashMap expects u64 hashes. -const ArrayIdentityContext = struct { +pub const ArrayIdentityContext = struct { pub fn hash(_: @This(), key: u32) u32 { return key; } diff --git a/src/javascript/jsc/api/router.zig b/src/javascript/jsc/api/router.zig index 2e2588e5a..e8ef4dc09 100644 --- a/src/javascript/jsc/api/router.zig +++ b/src/javascript/jsc/api/router.zig @@ -39,17 +39,17 @@ script_src_buf_writer: ScriptSrcStream = undefined, pub fn importRoute( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, _: []const js.JSValueRef, _: js.ExceptionRef, ) js.JSObjectRef { - const prom = JSC.JSModuleLoader.loadAndEvaluateModule(VirtualMachine.vm.global, &ZigString.init(this.route.file_path)); + const prom = JSC.JSModuleLoader.loadAndEvaluateModule(ctx.ptr(), &ZigString.init(this.route.file_path)); VirtualMachine.vm.tick(); - return prom.result(VirtualMachine.vm.global.vm()).asRef(); + return prom.result(ctx.ptr().vm()).asRef(); } pub fn match( @@ -69,9 +69,9 @@ pub fn match( return matchFetchEvent(ctx, To.Zig.ptr(FetchEvent, arguments[0]), exception); } - if (js.JSValueIsString(ctx, arguments[0])) { - return matchPathName(ctx, arguments[0], exception); - } + // if (js.JSValueIsString(ctx, arguments[0])) { + // return matchPathName(ctx, arguments[0], exception); + // } if (js.JSValueIsObjectOfClass(ctx, arguments[0], Request.Class.get().*)) { return matchRequest(ctx, To.Zig.ptr(Request, arguments[0]), exception); @@ -88,20 +88,6 @@ fn matchRequest( return createRouteObject(ctx, request.request_context, exception); } -fn matchPathNameString( - _: js.JSContextRef, - _: string, - _: js.ExceptionRef, -) js.JSObjectRef {} - -fn matchPathName( - _: js.JSContextRef, - _: js.JSStringRef, - _: js.ExceptionRef, -) js.JSObjectRef { - return null; -} - fn matchFetchEvent( ctx: js.JSContextRef, fetch_event: *const FetchEvent, @@ -274,12 +260,12 @@ pub const Instance = NewClass( pub fn getFilePath( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.route.file_path).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.route.file_path).toValue(ctx.ptr()).asRef(); } pub fn finalize( @@ -292,22 +278,22 @@ pub fn finalize( pub fn getPathname( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.route.pathname).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.route.pathname).toValue(ctx.ptr()).asRef(); } pub fn getRoute( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.route.name).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.route.name).toValue(ctx.ptr()).asRef(); } const KindEnum = struct { @@ -332,17 +318,17 @@ const KindEnum = struct { pub fn getKind( this: *Router, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return KindEnum.init(this.route.name).toValue(VirtualMachine.vm.global).asRef(); + return KindEnum.init(this.route.name).toValue(ctx.ptr()).asRef(); } threadlocal var query_string_values_buf: [256]string = undefined; threadlocal var query_string_value_refs_buf: [256]ZigString = undefined; -pub fn createQueryObject(_: js.JSContextRef, map: *QueryStringMap, _: js.ExceptionRef) callconv(.C) js.JSValueRef { +pub fn createQueryObject(ctx: js.JSContextRef, map: *QueryStringMap, _: js.ExceptionRef) callconv(.C) js.JSValueRef { const QueryObjectCreator = struct { query: *QueryStringMap, pub fn create(this: *@This(), obj: *JSObject, global: *JSGlobalObject) void { @@ -369,7 +355,7 @@ pub fn createQueryObject(_: js.JSContextRef, map: *QueryStringMap, _: js.Excepti var creator = QueryObjectCreator{ .query = map }; - var value = JSObject.createWithInitializer(QueryObjectCreator, &creator, VirtualMachine.vm.global, map.getNameCount()); + var value = JSObject.createWithInitializer(QueryObjectCreator, &creator, ctx.ptr(), map.getNameCount()); return value.asRef(); } @@ -440,7 +426,7 @@ pub fn getParams( if (this.param_map) |*map| { return createQueryObject(ctx, map, exception); } else { - return JSValue.createEmptyObject(VirtualMachine.vm.global, 0).asRef(); + return JSValue.createEmptyObject(ctx.ptr(), 0).asRef(); } } @@ -473,6 +459,6 @@ pub fn getQuery( if (this.query_string_map) |*map| { return createQueryObject(ctx, map, exception); } else { - return JSValue.createEmptyObject(VirtualMachine.vm.global, 0).asRef(); + return JSValue.createEmptyObject(ctx.ptr(), 0).asRef(); } } diff --git a/src/javascript/jsc/base.zig b/src/javascript/jsc/base.zig index f51eb86d9..cf2ed1bad 100644 --- a/src/javascript/jsc/base.zig +++ b/src/javascript/jsc/base.zig @@ -13,7 +13,9 @@ const C = _global.C; const JavaScript = @import("./javascript.zig"); const ResolveError = JavaScript.ResolveError; const BuildError = JavaScript.BuildError; +const JSC = @import("../../jsc.zig"); const WebCore = @import("./webcore/response.zig"); +const Test = @import("./test/jest.zig"); const Fetch = WebCore.Fetch; const Response = WebCore.Response; const Request = WebCore.Request; @@ -128,6 +130,190 @@ pub const To = struct { }; } + pub fn withType(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return withTypeClone(Type, value, context, exception, false); + } + + pub fn withTypeClone(comptime Type: type, value: Type, context: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef, clone: bool) JSC.C.JSValueRef { + if (comptime std.meta.trait.isNumber(Type)) { + return JSC.JSValue.jsNumberWithType(Type, value).asRef(); + } + + var zig_str: JSC.ZigString = undefined; + + return switch (comptime Type) { + void => JSC.C.JSValueMakeUndefined(context), + bool => JSC.C.JSValueMakeBoolean(context, value), + []const u8, [:0]const u8, [*:0]const u8, []u8, [:0]u8, [*:0]u8 => brk: { + zig_str = ZigString.init(value); + const val = zig_str.toValueAuto(context.ptr()); + + break :brk val.asObjectRef(); + }, + []const PathString, []const []const u8, []const []u8, [][]const u8, [][:0]const u8, [][:0]u8 => { + var zig_strings_buf: [32]ZigString = undefined; + var zig_strings: []ZigString = if (value.len < 32) + &zig_strings_buf + else + (_global.default_allocator.alloc(ZigString, value.len) catch unreachable); + defer if (zig_strings.ptr != &zig_strings_buf) + _global.default_allocator.free(zig_strings); + + for (value) |path_string, i| { + if (comptime Type == []const PathString) { + zig_strings[i] = ZigString.init(path_string.slice()); + } else { + zig_strings[i] = ZigString.init(path_string); + } + } + + var array = JSC.JSValue.createStringArray(context.ptr(), zig_strings.ptr, zig_strings.len, clone).asObjectRef(); + + if (clone) { + for (value) |path_string| { + if (comptime Type == []const PathString) { + _global.default_allocator.free(path_string.slice()); + } else { + _global.default_allocator.free(path_string); + } + } + _global.default_allocator.free(value); + } + + return array; + }, + + JSC.C.JSValueRef => value, + + else => { + const Info: std.builtin.TypeInfo = comptime @typeInfo(Type); + if (comptime Info == .Enum) { + const Enum: std.builtin.TypeInfo.Enum = Info.Enum; + if (comptime !std.meta.trait.isNumber(Enum.tag_type)) { + zig_str = JSC.ZigString.init(@tagName(value)); + return zig_str.toValue(context.ptr()).asObjectRef(); + } + } + + // 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 = @minimum(@intCast(u8, 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 = _global.default_allocator.alloc(JSC.C.JSValueRef, value.len) catch unreachable; + defer _global.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); + } + + if (exception.* != null) { + return null; + } + + // 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; + } + } + + if (comptime std.meta.trait.isZigString(Type)) { + zig_str = JSC.ZigString.init(value); + return zig_str.toValue(context.ptr()).asObjectRef(); + } + + if (comptime Info == .Pointer) { + const Child = comptime std.meta.Child(Type); + if (comptime std.meta.trait.isContainer(Child) and @hasDecl(Child, "Class") and @hasDecl(Child.Class, "isJavaScriptCoreClass")) { + return Child.Class.make(context, value); + } + } + + if (comptime Info == .Struct) { + if (comptime @hasDecl(Type, "Class") and @hasDecl(Type.Class, "isJavaScriptCoreClass")) { + if (comptime !@hasDecl(Type, "finalize")) { + @compileError(comptime std.fmt.comptimePrint("JSC class {s} must implement finalize to prevent memory leaks", .{Type.Class.name})); + } + + if (comptime !@hasDecl(Type, "toJS")) { + var val = _global.default_allocator.create(Type) catch unreachable; + val.* = value; + return Type.Class.make(context, val); + } + } + } + + const res = value.toJS(context, exception); + + if (@TypeOf(res) == JSC.C.JSValueRef) { + return res; + } else if (@TypeOf(res) == JSC.JSValue) { + return res.asObjectRef(); + } + }, + }; + } + + pub fn PropertyGetter( + comptime Type: type, + ) type { + return comptime fn ( + this: ObjectPtrType(Type), + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + exception: js.ExceptionRef, + ) js.JSValueRef; + } + + pub fn Getter(comptime Type: type, comptime field: std.meta.FieldEnum(Type)) PropertyGetter(Type) { + return struct { + pub fn rfn( + this: ObjectPtrType(Type), + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + exception: js.ExceptionRef, + ) js.JSValueRef { + return withType(std.meta.fieldInfo(Type, field).field_type, @field(this, @tagName(field)), ctx, exception); + } + }.rfn; + } + pub fn Callback( comptime ZigContextType: type, comptime ctxfn: fn ( @@ -150,7 +336,7 @@ pub const To = struct { ) callconv(.C) js.JSValueRef { if (comptime ZigContextType == anyopaque) { return ctxfn( - js.JSObjectGetPrivate(function) or js.jsObjectGetPrivate(thisObject), + js.JSObjectGetPrivate(function) orelse js.JSObjectGetPrivate(thisObject) orelse undefined, ctx, function, thisObject, @@ -232,86 +418,12 @@ pub const Properties = struct { pub const follow = "follow"; }; - pub const UTF16 = struct { - pub const module: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.module); - pub const globalThis: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.globalThis); - pub const exports: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.exports); - pub const log: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.log); - pub const debug: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.debug); - pub const info: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.info); - pub const error_: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.error_); - pub const warn: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.warn); - pub const console: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.console); - pub const require: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.require); - pub const description: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.description); - pub const name: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.name); - pub const initialize_bundled_module = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.initialize_bundled_module); - pub const load_module_function: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.load_module_function); - pub const window: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.window); - pub const default: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.default); - pub const include: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.include); - - pub const GET: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.GET); - pub const PUT: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.PUT); - pub const POST: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.POST); - pub const PATCH: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.PATCH); - pub const HEAD: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.HEAD); - pub const OPTIONS: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.OPTIONS); - - pub const navigate: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.navigate); - pub const follow: []c_ushort = std.unicode.utf8ToUtf16LeStringLiteral(UTF8.follow); - }; - pub const Refs = struct { - pub var filepath: js.JSStringRef = undefined; - - pub var module: js.JSStringRef = undefined; - pub var globalThis: js.JSStringRef = undefined; - pub var exports: js.JSStringRef = undefined; - pub var log: js.JSStringRef = undefined; - pub var debug: js.JSStringRef = undefined; - pub var info: js.JSStringRef = undefined; - pub var error_: js.JSStringRef = undefined; - pub var warn: js.JSStringRef = undefined; - pub var console: js.JSStringRef = undefined; - pub var require: js.JSStringRef = undefined; - pub var description: js.JSStringRef = undefined; - pub var name: js.JSStringRef = undefined; - pub var initialize_bundled_module: js.JSStringRef = undefined; - pub var load_module_function: js.JSStringRef = undefined; - pub var window: js.JSStringRef = undefined; - pub var default: js.JSStringRef = undefined; - pub var include: js.JSStringRef = undefined; - pub var GET: js.JSStringRef = undefined; - pub var PUT: js.JSStringRef = undefined; - pub var POST: js.JSStringRef = undefined; - pub var PATCH: js.JSStringRef = undefined; - pub var HEAD: js.JSStringRef = undefined; - pub var OPTIONS: js.JSStringRef = undefined; - pub var empty_string_ptr = [_]u8{0}; pub var empty_string: js.JSStringRef = undefined; - - pub var navigate: js.JSStringRef = undefined; - pub var follow: js.JSStringRef = undefined; - - pub const env: js.JSStringRef = undefined; }; pub fn init() void { - inline for (std.meta.fieldNames(UTF8)) |name| { - @field(Refs, name) = js.JSStringCreateStatic( - @field(UTF8, name).ptr, - @field(UTF8, name).len, - ); - - if (comptime Environment.isDebug) { - std.debug.assert( - js.JSStringIsEqualToString(@field(Refs, name), @field(UTF8, name).ptr, @field(UTF8, name).len), - ); - } - } - Refs.empty_string = js.JSStringCreateWithUTF8CString(&Refs.empty_string_ptr); } }; @@ -720,6 +832,8 @@ pub const ClassOptions = struct { ts: d.ts.decl = d.ts.decl{ .empty = 0 }, }; +// work around a comptime bug + pub fn NewClass( comptime ZigType: type, comptime options: ClassOptions, @@ -728,13 +842,16 @@ pub fn NewClass( ) type { const read_only = options.read_only; const singleton = options.singleton; + _ = read_only; return struct { const name = options.name; + pub const isJavaScriptCoreClass = true; const ClassDefinitionCreator = @This(); const function_names = std.meta.fieldNames(@TypeOf(staticFunctions)); const function_name_literals = function_names; var function_name_refs: [function_names.len]js.JSStringRef = undefined; + var function_name_refs_set = false; var class_name_str = name[0.. :0].ptr; var static_functions = brk: { @@ -750,24 +867,10 @@ pub fn NewClass( ); break :brk funcs; }; - var instance_functions = std.mem.zeroes([function_names.len]js.JSObjectRef); const property_names = std.meta.fieldNames(@TypeOf(properties)); - var property_name_refs = std.mem.zeroes([property_names.len]js.JSStringRef); + var property_name_refs: [property_names.len]js.JSStringRef = undefined; + var property_name_refs_set: bool = false; const property_name_literals = property_names; - var static_properties = brk: { - var props: [property_names.len + 1]js.JSStaticValue = undefined; - std.mem.set( - js.JSStaticValue, - &props, - js.JSStaticValue{ - .name = @intToPtr([*c]const u8, 0), - .getProperty = null, - .setProperty = null, - .attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone, - }, - ); - break :brk props; - }; pub var ref: js.JSClassRef = null; pub var loaded = false; @@ -822,8 +925,6 @@ pub fn NewClass( pub const Constructor = ConstructorWrapper.rfn; - pub const static_value_count = static_properties.len; - pub fn get() callconv(.C) [*c]js.JSClassRef { if (!loaded) { loaded = true; @@ -883,39 +984,6 @@ pub fn NewClass( return ClassGetter; } - pub fn getPropertyCallback( - ctx: js.JSContextRef, - obj: js.JSObjectRef, - prop: js.JSStringRef, - exception: js.ExceptionRef, - ) callconv(.C) js.JSValueRef { - var pointer = GetJSPrivateData(ZigType, obj) orelse return js.JSValueMakeUndefined(ctx); - - if (singleton) { - inline for (function_names) |_, i| { - if (js.JSStringIsEqual(prop, function_name_refs[i])) { - return instance_functions[i]; - } - } - unreachable; - } else { - inline for (property_names) |propname, i| { - if (js.JSStringIsEqual(prop, property_name_refs[i])) { - return @field( - properties, - propname, - )(pointer, ctx, obj, exception); - } - } - - if (comptime std.meta.trait.hasFn("onMissingProperty")(ZigType)) { - return pointer.onMissingProperty(ctx, obj, prop, exception); - } - } - - return js.JSValueMakeUndefined(ctx); - } - fn StaticProperty(comptime id: usize) type { return struct { pub fn getter( @@ -943,6 +1011,13 @@ pub fn NewClass( ); }, .Struct => { + comptime { + if (!@hasField(@TypeOf(@field(properties, property_names[id])), "get")) { + @compileError( + "Cannot get static property " ++ property_names[id] ++ " of " ++ name ++ " because it is a struct without a getter", + ); + } + } const func = @field( @field( properties, @@ -988,7 +1063,7 @@ pub fn NewClass( value: js.JSValueRef, exception: js.ExceptionRef, ) callconv(.C) bool { - var this = GetJSPrivateData(ZigType, obj) orelse return js.JSValueMakeUndefined(ctx); + var this = GetJSPrivateData(ZigType, obj) orelse return false; switch (comptime @typeInfo(@TypeOf(@field( properties, @@ -1180,6 +1255,41 @@ pub fn NewClass( return decl; } + pub fn getPropertyNames( + _: js.JSContextRef, + _: js.JSObjectRef, + props: js.JSPropertyNameAccumulatorRef, + ) callconv(.C) void { + if (comptime property_name_refs.len > 0) { + comptime var i: usize = 0; + if (!property_name_refs_set) { + property_name_refs_set =true; + inline while (i < property_name_refs.len) : (i += 1) { + property_name_refs[i] = js.JSStringCreateStatic(property_names[i].ptr, property_names[i].len); + } + comptime i = 0; + } + inline while (i < property_name_refs.len) : (i += 1) { + js.JSPropertyNameAccumulatorAddName(props, property_name_refs[i]); + } + } + + if (comptime function_name_refs.len > 0) { + comptime var j: usize = 0; + if (!function_name_refs_set) { + function_name_refs_set = true; + inline while (j < function_name_refs.len) : (j += 1) { + function_name_refs[j] = js.JSStringCreateStatic(function_names[j].ptr, function_names[j].len); + } + comptime j = 0; + } + + inline while (j < function_name_refs.len) : (j += 1) { + js.JSPropertyNameAccumulatorAddName(props, function_name_refs[j]); + } + } + } + // This should only be run at comptime pub fn typescriptClassDeclaration() d.ts.class { comptime var class = options.ts.class; @@ -1301,11 +1411,26 @@ pub fn NewClass( return comptime class; } + var static_properties = brk: { + var props: [property_names.len + 1]js.JSStaticValue = undefined; + std.mem.set( + js.JSStaticValue, + &props, + js.JSStaticValue{ + .name = @intToPtr([*c]const u8, 0), + .getProperty = null, + .setProperty = null, + .attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone, + }, + ); + break :brk props; + }; + pub fn define() js.JSClassDefinition { var def = js.JSClassDefinition{ .version = 0, .attributes = js.JSClassAttributes.kJSClassAttributeNone, - .className = class_name_str, + .className = name.ptr[0..name.len :0], .parentClass = null, .staticValues = null, .staticFunctions = null, @@ -1322,58 +1447,59 @@ pub fn NewClass( .convertToType = null, }; - if (static_functions.len > 0) { - std.mem.set(js.JSStaticFunction, &static_functions, std.mem.zeroes(js.JSStaticFunction)); - var count: usize = 0; - inline for (function_name_literals) |_, i| { - switch (comptime @typeInfo(@TypeOf(@field(staticFunctions, function_names[i])))) { + // These workaround stage1 compiler bugs + var JSStaticValue_empty = std.mem.zeroes(js.JSStaticValue); + var count: usize = 0; + + if (comptime static_functions.len > 0) { + inline for (function_name_literals) |function_name_literal, i| { + _ = i; + switch (comptime @typeInfo(@TypeOf(@field(staticFunctions, function_name_literal)))) { .Struct => { - if (comptime strings.eqlComptime(function_names[i], "constructor")) { + if (comptime strings.eqlComptime(function_name_literal, "constructor")) { def.callAsConstructor = To.JS.Constructor(staticFunctions.constructor.rfn).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "finalize")) { + } else if (comptime strings.eqlComptime(function_name_literal, "finalize")) { def.finalize = To.JS.Finalize(ZigType, staticFunctions.finalize.rfn).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "call")) { + } else if (comptime strings.eqlComptime(function_name_literal, "call")) { def.callAsFunction = To.JS.Callback(ZigType, staticFunctions.call.rfn).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "callAsFunction")) { - const ctxfn = @field(staticFunctions, function_names[i]).rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "callAsFunction")) { + const ctxfn = @field(staticFunctions, function_name_literal).rfn; const Func: std.builtin.TypeInfo.Fn = @typeInfo(@TypeOf(ctxfn)).Fn; const PointerType = std.meta.Child(Func.args[0].arg_type.?); - var callback = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( + def.callAsFunction = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( PointerType, ctxfn, ).rfn; - - def.callAsFunction = callback; - } else if (comptime strings.eqlComptime(function_names[i], "hasProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "hasProperty")) { def.hasProperty = @field(staticFunctions, "hasProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "getProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "getProperty")) { def.getProperty = @field(staticFunctions, "getProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "setProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "setProperty")) { def.setProperty = @field(staticFunctions, "setProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "deleteProperty")) { + } else if (comptime strings.eqlComptime(function_name_literal, "deleteProperty")) { def.deleteProperty = @field(staticFunctions, "deleteProperty").rfn; - } else if (comptime strings.eqlComptime(function_names[i], "getPropertyNames")) { + } else if (comptime strings.eqlComptime(function_name_literal, "getPropertyNames")) { def.getPropertyNames = @field(staticFunctions, "getPropertyNames").rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "convertToType")) { + def.convertToType = @field(staticFunctions, "convertToType").rfn; } else { - const CtxField = @field(staticFunctions, function_names[i]); + const CtxField = comptime @field(staticFunctions, function_name_literal); if (comptime !@hasField(@TypeOf(CtxField), "rfn")) { - @compileError("Expected " ++ options.name ++ "." ++ function_names[i] ++ " to have .rfn"); + @compileError("Expected " ++ options.name ++ "." ++ function_name_literal ++ " to have .rfn"); } const ctxfn = CtxField.rfn; const Func: std.builtin.TypeInfo.Fn = @typeInfo(@TypeOf(ctxfn)).Fn; const PointerType = if (Func.args[0].arg_type.? == void) void else std.meta.Child(Func.args[0].arg_type.?); - var callback = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( - PointerType, - ctxfn, - ).rfn; - static_functions[count] = js.JSStaticFunction{ .name = (function_names[i][0.. :0]).ptr, - .callAsFunction = callback, + .callAsFunction = if (Func.calling_convention == .C) ctxfn else To.JS.Callback( + PointerType, + ctxfn, + ).rfn, .attributes = comptime if (read_only) js.JSPropertyAttributes.kJSPropertyAttributeReadOnly else js.JSPropertyAttributes.kJSPropertyAttributeNone, }; @@ -1381,27 +1507,30 @@ pub fn NewClass( } }, .Fn => { - if (comptime strings.eqlComptime(function_names[i], "constructor")) { + if (comptime strings.eqlComptime(function_name_literal, "constructor")) { def.callAsConstructor = To.JS.Constructor(staticFunctions.constructor).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "finalize")) { + } else if (comptime strings.eqlComptime(function_name_literal, "finalize")) { def.finalize = To.JS.Finalize(ZigType, staticFunctions.finalize).rfn; - } else if (comptime strings.eqlComptime(function_names[i], "call")) { + } else if (comptime strings.eqlComptime(function_name_literal, "call")) { def.callAsFunction = To.JS.Callback(ZigType, staticFunctions.call).rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "getPropertyNames")) { + def.getPropertyNames = To.JS.Callback(ZigType, staticFunctions.getPropertyNames).rfn; + } else if (comptime strings.eqlComptime(function_name_literal, "hasInstance")) { + def.hasInstance = staticFunctions.hasInstance; } else { - var callback = To.JS.Callback( - ZigType, - @field(staticFunctions, function_names[i]), - ).rfn; static_functions[count] = js.JSStaticFunction{ .name = (function_names[i][0.. :0]).ptr, - .callAsFunction = callback, + .callAsFunction = To.JS.Callback( + ZigType, + @field(staticFunctions, function_name_literal), + ).rfn, .attributes = comptime if (read_only) js.JSPropertyAttributes.kJSPropertyAttributeReadOnly else js.JSPropertyAttributes.kJSPropertyAttributeNone, }; count += 1; } }, - else => unreachable, + else => {}, } // if (singleton) { @@ -1413,13 +1542,9 @@ pub fn NewClass( def.staticFunctions = static_functions[0..count].ptr; } - if (property_names.len > 0) { - inline for (comptime property_name_literals) |prop_name, i| { - property_name_refs[i] = js.JSStringCreateStatic( - prop_name.ptr, - prop_name.len, - ); - static_properties[i] = std.mem.zeroes(js.JSStaticValue); + if (comptime property_names.len > 0) { + inline for (property_name_literals) |_, i| { + static_properties[i] = JSStaticValue_empty; static_properties[i].getProperty = StaticProperty(i).getter; const field = comptime @field(properties, property_names[i]); @@ -1429,7 +1554,7 @@ pub fn NewClass( } static_properties[i].name = property_names[i][0.. :0].ptr; } - def.staticValues = (&static_properties); + def.staticValues = &static_properties; } def.className = class_name_str; @@ -1443,38 +1568,97 @@ pub fn NewClass( def.callAsFunction = throwInvalidFunctionError; } - if (!singleton) + if (def.getPropertyNames == null) { + def.getPropertyNames = getPropertyNames; + } + + if (!singleton and def.hasInstance == null) def.hasInstance = customHasInstance; return def; } }; } +const JSValue = JSC.JSValue; +const ZigString = JSC.ZigString; + +pub const PathString = _global.PathString; + threadlocal var error_args: [1]js.JSValueRef = undefined; pub fn JSError( - allocator: std.mem.Allocator, + _: std.mem.Allocator, comptime fmt: string, args: anytype, ctx: js.JSContextRef, exception: ExceptionValueRef, ) void { + @setCold(true); + if (comptime std.meta.fields(@TypeOf(args)).len == 0) { - var message = js.JSStringCreateWithUTF8CString(fmt[0.. :0]); - defer js.JSStringRelease(message); - error_args[0] = js.JSValueMakeString(ctx, message); + var zig_str = JSC.ZigString.init(fmt); + zig_str.detectEncoding(); + error_args[0] = zig_str.toValueAuto(ctx.ptr()).asObjectRef(); exception.* = js.JSObjectMakeError(ctx, 1, &error_args, null); } else { - var buf = std.fmt.allocPrintZ(allocator, fmt, args) catch unreachable; - defer allocator.free(buf); + var buf = std.fmt.allocPrint(default_allocator, fmt, args) catch unreachable; + var zig_str = JSC.ZigString.init(buf); + zig_str.detectEncoding(); - var message = js.JSStringCreateWithUTF8CString(buf); - defer js.JSStringRelease(message); - - error_args[0] = js.JSValueMakeString(ctx, message); + error_args[0] = zig_str.toValueGC(ctx.ptr()).asObjectRef(); exception.* = js.JSObjectMakeError(ctx, 1, &error_args, null); } } +pub fn throwTypeError( + code: JSC.Node.ErrorCode, + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, + exception: ExceptionValueRef, +) void { + exception.* = toTypeError(code, fmt, args, ctx).asObjectRef(); +} + +pub fn toTypeError( + code: JSC.Node.ErrorCode, + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, +) JSC.JSValue { + @setCold(true); + var zig_str: JSC.ZigString = undefined; + if (comptime std.meta.fields(@TypeOf(args)).len == 0) { + zig_str = JSC.ZigString.init(fmt); + zig_str.detectEncoding(); + } else { + var buf = std.fmt.allocPrint(default_allocator, fmt, args) catch unreachable; + zig_str = JSC.ZigString.init(buf); + zig_str.detectEncoding(); + zig_str.mark(); + } + const code_str = ZigString.init(@tagName(code)); + return JSC.JSValue.createTypeError(&zig_str, &code_str, ctx.ptr()); +} + +pub fn throwInvalidArguments( + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, + exception: ExceptionValueRef, +) void { + @setCold(true); + return throwTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx, exception); +} + +pub fn toInvalidArguments( + comptime fmt: string, + args: anytype, + ctx: js.JSContextRef, +) JSC.JSValue { + @setCold(true); + return toTypeError(JSC.Node.ErrorCode.ERR_INVALID_ARG_TYPE, fmt, args, ctx); +} + pub fn getAllocator(_: js.JSContextRef) std.mem.Allocator { return default_allocator; } @@ -1491,14 +1675,78 @@ pub const ArrayBuffer = struct { typed_array_type: js.JSTypedArrayType, - pub inline fn slice(this: *const ArrayBuffer) []u8 { + encoding: JSC.Node.Encoding = JSC.Node.Encoding.utf8, + + pub const Stream = std.io.FixedBufferStream([]u8); + + pub inline fn stream(this: ArrayBuffer) Stream { + return Stream{ .pos = 0, .buf = this.slice() }; + } + + pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ArrayBuffer { + return ArrayBuffer{ + .byte_len = @truncate(u32, JSC.C.JSObjectGetTypedArrayByteLength(ctx, value.asObjectRef(), exception)), + .offset = @truncate(u32, JSC.C.JSObjectGetTypedArrayByteOffset(ctx, value.asObjectRef(), exception)), + .ptr = @ptrCast([*]u8, JSC.C.JSObjectGetTypedArrayBytesPtr(ctx, value.asObjectRef(), exception).?), + // TODO + .typed_array_type = js.JSTypedArrayType.kJSTypedArrayTypeUint8Array, + .len = @truncate(u32, JSC.C.JSObjectGetTypedArrayLength(ctx, value.asObjectRef(), exception)), + }; + } + + pub fn fromArrayBuffer(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ArrayBuffer { + var buffer = ArrayBuffer{ + .byte_len = @truncate(u32, JSC.C.JSObjectGetArrayBufferByteLength(ctx, value.asObjectRef(), exception)), + .ptr = @ptrCast([*]u8, JSC.C.JSObjectGetArrayBufferBytesPtr(ctx, value.asObjectRef(), exception).?), + // TODO + .typed_array_type = js.JSTypedArrayType.kJSTypedArrayTypeUint8Array, + .len = 0, + .offset = 0, + }; + buffer.len = buffer.byte_len; + return buffer; + } + + pub inline fn slice(this: *const @This()) []u8 { return this.ptr[this.offset .. this.offset + this.byte_len]; } }; pub const MarkedArrayBuffer = struct { buffer: ArrayBuffer, - allocator: std.mem.Allocator, + allocator: ?std.mem.Allocator = null, + + pub const Stream = ArrayBuffer.Stream; + + pub inline fn stream(this: *MarkedArrayBuffer) Stream { + return this.buffer.stream(); + } + + pub fn fromTypedArray(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) MarkedArrayBuffer { + return MarkedArrayBuffer{ + .allocator = null, + .buffer = ArrayBuffer.fromTypedArray(ctx, value, exception), + }; + } + pub fn fromArrayBuffer(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) MarkedArrayBuffer { + return MarkedArrayBuffer{ + .allocator = null, + .buffer = ArrayBuffer.fromArrayBuffer(ctx, value, exception), + }; + } + + pub fn fromString(str: []const u8, allocator: std.mem.Allocator) !MarkedArrayBuffer { + var buf = try allocator.dupe(u8, str); + return MarkedArrayBuffer.fromBytes(buf, allocator, js.JSTypedArrayType.kJSTypedArrayTypeUint8Array); + } + + pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?MarkedArrayBuffer { + return switch (value.jsType()) { + JSC.JSValue.JSType.Uint16Array, JSC.JSValue.JSType.Uint32Array, JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.DataView => fromTypedArray(global.ref(), value, exception), + JSC.JSValue.JSType.ArrayBuffer => fromArrayBuffer(global.ref(), value, exception), + else => null, + }; + } pub fn fromBytes(bytes: []u8, allocator: std.mem.Allocator, typed_array_type: js.JSTypedArrayType) MarkedArrayBuffer { return MarkedArrayBuffer{ @@ -1507,10 +1755,16 @@ pub const MarkedArrayBuffer = struct { }; } + pub inline fn slice(this: *const @This()) []u8 { + return this.buffer.slice(); + } + pub fn destroy(this: *MarkedArrayBuffer) void { const content = this.*; - content.allocator.free(content.buffer.slice()); - content.allocator.destroy(this); + if (this.allocator) |allocator| { + allocator.free(content.buffer.slice()); + allocator.destroy(this); + } } pub fn init(allocator: std.mem.Allocator, size: u32, typed_array_type: js.JSTypedArrayType) !*MarkedArrayBuffer { @@ -1520,9 +1774,11 @@ pub const MarkedArrayBuffer = struct { return container; } - pub fn toJSObjectRef(this: *MarkedArrayBuffer, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef { - return js.JSObjectMakeTypedArrayWithBytesNoCopy(ctx, this.buffer.typed_array_type, this.buffer.ptr, this.buffer.byte_len, MarkedArrayBuffer_deallocator, this, exception); + pub fn toJSObjectRef(this: *const MarkedArrayBuffer, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef { + return js.JSObjectMakeTypedArrayWithBytesNoCopy(ctx, this.buffer.typed_array_type, this.buffer.ptr, this.buffer.byte_len, MarkedArrayBuffer_deallocator, @intToPtr([*]u8, @ptrToInt(this)), exception); } + + pub const toJS = toJSObjectRef; }; export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, ctx_: *anyopaque) void { @@ -1535,10 +1791,19 @@ export fn MarkedArrayBuffer_deallocator(bytes_: *anyopaque, ctx_: *anyopaque) vo pub fn castObj(obj: js.JSObjectRef, comptime Type: type) *Type { return JSPrivateDataPtr.from(js.JSObjectGetPrivate(obj)).as(Type); } + const JSNode = @import("../../js_ast.zig").Macro.JSNode; const LazyPropertiesObject = @import("../../js_ast.zig").Macro.LazyPropertiesObject; const ModuleNamespace = @import("../../js_ast.zig").Macro.ModuleNamespace; const FetchTaskletContext = Fetch.FetchTasklet.FetchTaskletContext; +const Expect = Test.Expect; +const DescribeScope = Test.DescribeScope; +const TestScope = Test.TestScope; +const ExpectPrototype = Test.ExpectPrototype; +const NodeFS = JSC.Node.NodeFS; +const DirEnt = JSC.Node.DirEnt; +const Stats = JSC.Node.Stats; +const BigIntStats = JSC.Node.BigIntStats; pub const JSPrivateDataPtr = TaggedPointerUnion(.{ ResolveError, BuildError, @@ -1552,6 +1817,13 @@ pub const JSPrivateDataPtr = TaggedPointerUnion(.{ LazyPropertiesObject, ModuleNamespace, FetchTaskletContext, + DescribeScope, + Expect, + ExpectPrototype, + NodeFS, + Stats, + BigIntStats, + DirEnt, }); pub inline fn GetJSPrivateData(comptime Type: type, ref: js.JSObjectRef) ?*Type { @@ -1567,6 +1839,7 @@ pub const JSPropertyNameIterator = struct { if (this.i >= this.count) return null; const i = this.i; this.i += 1; + return js.JSPropertyNameArrayGetNameAtIndex(this.array, i); } }; diff --git a/src/javascript/jsc/bindings/BunBuiltinNames.h b/src/javascript/jsc/bindings/BunBuiltinNames.h new file mode 100644 index 000000000..7a666df61 --- /dev/null +++ b/src/javascript/jsc/bindings/BunBuiltinNames.h @@ -0,0 +1,85 @@ +// clang-format off + +#pragma once + +#include "helpers.h" +#include "root.h" +#include <JavaScriptCore/BuiltinUtils.h> + + +namespace Bun { + +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(filePath) \ + macro(syscall) \ + macro(errno) \ + macro(code) \ + macro(path) \ + macro(dir) \ + macro(versions) \ + macro(argv) \ + macro(execArgv) \ + macro(nextTick) \ + macro(version) \ + macro(title) \ + macro(pid) \ + macro(ppid) \ + macro(chdir) \ + macro(cwd) \ + macro(process) \ + macro(map) \ + macro(addEventListener) \ + macro(removeEventListener) \ + macro(prependEventListener) \ + macro(write) \ + macro(end) \ + macro(close) \ + macro(destroy) \ + macro(cork) \ + macro(uncork) \ + macro(isPaused) \ + macro(read) \ + macro(pipe) \ + macro(unpipe) \ + macro(once) \ + macro(on) \ + macro(unshift) \ + macro(resume) \ + macro(pause) \ + BUN_ADDITIONAL_PRIVATE_IDENTIFIERS(macro) \ + +class BunBuiltinNames { +public: + // FIXME: Remove the __attribute__((nodebug)) when <rdar://68246686> is fixed. +#if COMPILER(CLANG) + __attribute__((nodebug)) +#endif + explicit BunBuiltinNames(JSC::VM& vm) + : m_vm(vm) + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(INITIALIZE_BUILTIN_NAMES) + { +#define EXPORT_NAME(name) m_vm.propertyNames->appendExternalName(name##PublicName(), name##PrivateName()); + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(EXPORT_NAME) +#undef EXPORT_NAME + } + + + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(DECLARE_BUILTIN_IDENTIFIER_ACCESSOR) + +private: + JSC::VM& m_vm; + BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(DECLARE_BUILTIN_NAMES) +}; + +} // namespace Bun + diff --git a/src/javascript/jsc/bindings/BunClientData.cpp b/src/javascript/jsc/bindings/BunClientData.cpp new file mode 100644 index 000000000..a86720a85 --- /dev/null +++ b/src/javascript/jsc/bindings/BunClientData.cpp @@ -0,0 +1,33 @@ + +#include "BunClientData.h" +#include "root.h" + +#include <JavaScriptCore/FastMallocAlignedMemoryAllocator.h> +#include <JavaScriptCore/HeapInlines.h> +#include <JavaScriptCore/IsoHeapCellType.h> +#include <JavaScriptCore/JSDestructibleObjectHeapCellType.h> +#include <JavaScriptCore/MarkingConstraint.h> +#include <JavaScriptCore/SubspaceInlines.h> +#include <JavaScriptCore/VM.h> +#include <wtf/MainThread.h> + +// #include "BunGCOutputConstraint.h" + +namespace Bun { +using namespace JSC; + +JSVMClientData::JSVMClientData(VM &vm) : m_builtinNames(vm) {} + +JSVMClientData::~JSVMClientData() {} + +void JSVMClientData::create(VM *vm) { + JSVMClientData *clientData = new JSVMClientData(*vm); + vm->clientData = clientData; // ~VM deletes this pointer. + + // vm->heap.addMarkingConstraint(makeUnique<BunGCOutputConstraint>(*vm, *clientData)); + + // vm->m_typedArrayController = adoptRef(new WebCoreTypedArrayController( + // type == WorkerThreadType::DedicatedWorker || type == WorkerThreadType::Worklet)); +} + +} // namespace Bun
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/BunClientData.h b/src/javascript/jsc/bindings/BunClientData.h new file mode 100644 index 000000000..cd506365f --- /dev/null +++ b/src/javascript/jsc/bindings/BunClientData.h @@ -0,0 +1,41 @@ +#pragma once + +#include "BunBuiltinNames.h" +#include "root.h" +#include <JavaScriptCore/BuiltinUtils.h> +#include <wtf/HashSet.h> +#include <wtf/RefPtr.h> + +namespace Bun { +using namespace JSC; + +class JSVMClientData : public JSC::VM::ClientData { + WTF_MAKE_NONCOPYABLE(JSVMClientData); + WTF_MAKE_FAST_ALLOCATED; + + public: + explicit JSVMClientData(JSC::VM &); + + virtual ~JSVMClientData(); + + static void create(JSC::VM *); + + BunBuiltinNames &builtinNames() { return m_builtinNames; } + + // Vector<JSC::IsoSubspace *> &outputConstraintSpaces() { return m_outputConstraintSpaces; } + + // template <typename Func> void forEachOutputConstraintSpace(const Func &func) { + // for (auto *space : m_outputConstraintSpaces) func(*space); + // } + + private: + BunBuiltinNames m_builtinNames; + + // Vector<JSC::IsoSubspace *> m_outputConstraintSpaces; +}; + +static JSVMClientData *clientData(JSC::VM &vm) { + return static_cast<Bun::JSVMClientData *>(vm.clientData); +} + +} // namespace Bun diff --git a/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp b/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp new file mode 100644 index 000000000..bc99ef2e2 --- /dev/null +++ b/src/javascript/jsc/bindings/BunGCOutputConstraint.cpp @@ -0,0 +1,47 @@ + + +// #include "BunGCOutputConstraint.h" + +// #include "BunClientData.h" +// #include <JavaScriptCore/BlockDirectoryInlines.h> +// #include <JavaScriptCore/HeapInlines.h> +// #include <JavaScriptCore/MarkedBlockInlines.h> +// #include <JavaScriptCore/MarkingConstraint.h> +// #include <JavaScriptCore/SubspaceInlines.h> +// #include <JavaScriptCore/VM.h> + +// namespace Bun { + +// using namespace JSC; + +// BunGCOutputConstraint::BunGCOutputConstraint(VM &vm, Bun::JSVMClientData &clientData) +// : MarkingConstraint("Domo", "DOM Output", ConstraintVolatility::SeldomGreyed, +// ConstraintConcurrency::Concurrent, ConstraintParallelism::Parallel), +// m_vm(vm), +// m_clientData(clientData), +// m_lastExecutionVersion(vm.heap.mutatorExecutionVersion()) {} + +// template <typename Visitor> void BunGCOutputConstraint::executeImplImpl(Visitor &visitor) { +// Heap &heap = m_vm.heap; + +// if (heap.mutatorExecutionVersion() == m_lastExecutionVersion) return; + +// m_lastExecutionVersion = heap.mutatorExecutionVersion(); + +// m_clientData.forEachOutputConstraintSpace([&](Subspace &subspace) { +// auto func = [](Visitor &visitor, HeapCell *heapCell, HeapCell::Kind) { +// SetRootMarkReasonScope rootScope(visitor, RootMarkReason::DOMGCOutput); +// JSCell *cell = static_cast<JSCell *>(heapCell); +// cell->methodTable(visitor.vm())->visitOutputConstraints(cell, visitor); +// }; + +// RefPtr<SharedTask<void(Visitor &)>> task = +// subspace.template forEachMarkedCellInParallel<Visitor>(func); +// visitor.addParallelConstraintTask(task); +// }); +// } + +// void BunGCOutputConstraint::executeImpl(AbstractSlotVisitor &visitor) { executeImplImpl(visitor); +// } void BunGCOutputConstraint::executeImpl(SlotVisitor &visitor) { executeImplImpl(visitor); } + +// } // namespace Bun diff --git a/src/javascript/jsc/bindings/BunGCOutputConstraint.h b/src/javascript/jsc/bindings/BunGCOutputConstraint.h new file mode 100644 index 000000000..521b0da8c --- /dev/null +++ b/src/javascript/jsc/bindings/BunGCOutputConstraint.h @@ -0,0 +1,34 @@ + +// #pragma once + +// #include "root.h" +// #include <JavaScriptCore/MarkingConstraint.h> + +// namespace JSC { +// class VM; +// } + +// namespace Bun { + +// class JSVMClientData; + +// class BunGCOutputConstraint : public JSC::MarkingConstraint { +// WTF_MAKE_FAST_ALLOCATED; + +// public: +// BunGCOutputConstraint(JSC::VM &, Bun::JSVMClientData &); +// ~BunGCOutputConstraint(){}; + +// protected: +// void executeImpl(JSC::AbstractSlotVisitor &) override; +// void executeImpl(JSC::SlotVisitor &) override; + +// private: +// template <typename Visitor> void executeImplImpl(Visitor &); + +// JSC::VM &m_vm; +// JSVMClientData &m_clientData; +// uint64_t m_lastExecutionVersion; +// }; + +// } // namespace Bun diff --git a/src/javascript/jsc/bindings/BunStream.cpp b/src/javascript/jsc/bindings/BunStream.cpp new file mode 100644 index 000000000..8c45feb40 --- /dev/null +++ b/src/javascript/jsc/bindings/BunStream.cpp @@ -0,0 +1,485 @@ +#include "BunStream.h" +#include <JavaScriptCore/JSMicrotask.h> +#include <JavaScriptCore/ObjectConstructor.h> + +namespace Bun { +using JSGlobalObject = JSC::JSGlobalObject; +using Exception = JSC::Exception; +using JSValue = JSC::JSValue; +using JSString = JSC::JSString; +using JSModuleLoader = JSC::JSModuleLoader; +using JSModuleRecord = JSC::JSModuleRecord; +using Identifier = JSC::Identifier; +using SourceOrigin = JSC::SourceOrigin; +using JSObject = JSC::JSObject; +using JSNonFinalObject = JSC::JSNonFinalObject; +namespace JSCastingHelpers = JSC::JSCastingHelpers; + +static ReadableEvent getReadableEvent(const WTF::String &eventName); +static ReadableEvent getReadableEvent(const WTF::String &eventName) { + if (eventName == "close") + return ReadableEvent__Close; + else if (eventName == "data") + return ReadableEvent__Data; + else if (eventName == "end") + return ReadableEvent__End; + else if (eventName == "error") + return ReadableEvent__Error; + else if (eventName == "pause") + return ReadableEvent__Pause; + else if (eventName == "readable") + return ReadableEvent__Readable; + else if (eventName == "resume") + return ReadableEvent__Resume; + else if (eventName == "open") + return ReadableEvent__Open; + else + return ReadableEventUser; +} + +static WritableEvent getWritableEvent(const WTF::String &eventName); +static WritableEvent getWritableEvent(const WTF::String &eventName) { + if (eventName == "close") + return WritableEvent__Close; + else if (eventName == "drain") + return WritableEvent__Drain; + else if (eventName == "error") + return WritableEvent__Error; + else if (eventName == "finish") + return WritableEvent__Finish; + else if (eventName == "pipe") + return WritableEvent__Pipe; + else if (eventName == "unpipe") + return WritableEvent__Unpipe; + else if (eventName == "open") + return WritableEvent__Open; + else + return WritableEventUser; +} + +// clang-format off +#define DEFINE_CALLBACK_FUNCTION_BODY(TypeName, ZigFunction) JSC::VM& vm = globalObject->vm(); \ + auto* thisObject = JSC::jsDynamicCast<TypeName*>(vm, callFrame->thisValue()); \ + auto scope = DECLARE_THROW_SCOPE(vm); \ + if (!thisObject) \ + return throwVMTypeError(globalObject, scope); \ + auto argCount = static_cast<uint16_t>(callFrame->argumentCount()); \ + WTF::Vector<JSC::EncodedJSValue, 16> arguments; \ + arguments.reserveInitialCapacity(argCount); \ + if (argCount) { \ + for (uint16_t i = 0; i < argCount; ++i) { \ + arguments.uncheckedAppend(JSC::JSValue::encode(callFrame->uncheckedArgument(i))); \ + } \ + } \ + JSC::JSValue result = JSC::JSValue::decode( \ + ZigFunction(thisObject->state, globalObject, arguments.data(), argCount) \ + ); \ + JSC::JSObject *obj = result.getObject(); \ + if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) { \ + scope.throwException(globalObject, obj); \ + return JSC::JSValue::encode(JSC::jsUndefined()); \ + } \ + if (UNLIKELY(scope.exception())) \ + return JSC::JSValue::encode(JSC::jsUndefined()); \ + return JSC::JSValue::encode(result); + +// clang-format on +// static JSC_DECLARE_HOST_FUNCTION(Writable__addEventListener); +// static JSC_DECLARE_HOST_FUNCTION(Readable__addEventListener); +// static JSC_DECLARE_HOST_FUNCTION(Writable__prependListener); +// static JSC_DECLARE_HOST_FUNCTION(Readable__prependListener); +// static JSC_DECLARE_HOST_FUNCTION(Writable__prependOnceListener); +// static JSC_DECLARE_HOST_FUNCTION(Readable__prependOnceListener); +// static JSC_DECLARE_HOST_FUNCTION(Writable__setMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Readable__setMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Writable__getMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Readable__getMaxListeners); +// static JSC_DECLARE_HOST_FUNCTION(Readable__setDefaultEncoding); +static JSC_DECLARE_HOST_FUNCTION(Readable__on); +// static JSC_DECLARE_HOST_FUNCTION(Readable__off); +static JSC_DECLARE_HOST_FUNCTION(Readable__once); +static JSC_DECLARE_HOST_FUNCTION(Readable__pause); +static JSC_DECLARE_HOST_FUNCTION(Readable__pipe); +static JSC_DECLARE_HOST_FUNCTION(Readable__read); +static JSC_DECLARE_HOST_FUNCTION(Readable__resume); +static JSC_DECLARE_HOST_FUNCTION(Readable__unpipe); +static JSC_DECLARE_HOST_FUNCTION(Readable__unshift); + +static JSC_DECLARE_HOST_FUNCTION(Writable__close); +// static JSC_DECLARE_HOST_FUNCTION(Writable__off); +static JSC_DECLARE_HOST_FUNCTION(Writable__cork); +static JSC_DECLARE_HOST_FUNCTION(Writable__destroy); +static JSC_DECLARE_HOST_FUNCTION(Writable__end); +static JSC_DECLARE_HOST_FUNCTION(Writable__on); +static JSC_DECLARE_HOST_FUNCTION(Writable__once); +static JSC_DECLARE_HOST_FUNCTION(Writable__uncork); +static JSC_DECLARE_HOST_FUNCTION(Writable__write); + +static JSC_DEFINE_HOST_FUNCTION(Readable__on, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Readable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + ReadableEvent event = getReadableEvent(eventName->value(globalObject)); + if (event == ReadableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Readable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), true); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +extern "C" Bun__Readable *JSC__JSValue__getReadableStreamState(JSC__JSValue value, JSC__VM *vm) { + auto *thisObject = JSC::jsDynamicCast<Bun::Readable *>(*vm, JSC::JSValue::decode(value)); + if (UNLIKELY(!thisObject)) { return nullptr; } + return thisObject->state; +} +extern "C" Bun__Writable *JSC__JSValue__getWritableStreamState(JSC__JSValue value, JSC__VM *vm) { + auto *thisObject = JSC::jsDynamicCast<Bun::Writable *>(*vm, JSC::JSValue::decode(value)); + if (UNLIKELY(!thisObject)) { return nullptr; } + return thisObject->state; +} + +const JSC::ClassInfo Readable::s_info = {"Readable", &Base::s_info, nullptr, nullptr, + CREATE_METHOD_TABLE(Readable)}; + +const JSC::ClassInfo Writable::s_info = {"Writable", &Base::s_info, nullptr, nullptr, + CREATE_METHOD_TABLE(Writable)}; + +static JSC_DEFINE_HOST_FUNCTION(Readable__once, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Readable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + ReadableEvent event = getReadableEvent(eventName->value(globalObject)); + if (event == ReadableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Readable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), true); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DEFINE_HOST_FUNCTION(Writable__on, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Writable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + WritableEvent event = getWritableEvent(eventName->value(globalObject)); + if (event == WritableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Writable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), false); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DEFINE_HOST_FUNCTION(Writable__once, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + if (callFrame->argumentCount() < 2) { return JSC::JSValue::encode(JSC::jsUndefined()); } + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + + auto thisObject = JSC::jsDynamicCast<Bun::Writable *>(vm, callFrame->thisValue()); + if (UNLIKELY(!thisObject)) { + scope.release(); + JSC::throwVMTypeError(globalObject, scope); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto eventName = callFrame->argument(0).toStringOrNull(globalObject); + if (UNLIKELY(!eventName)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + WritableEvent event = getWritableEvent(eventName->value(globalObject)); + if (event == WritableEventUser) { + // TODO: + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + auto listener = callFrame->argument(1); + JSC::JSObject *object = listener.getObject(); + if (UNLIKELY(!object) || !listener.isCallable(vm)) { + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); + } + + Bun__Writable__addEventListener(thisObject->state, globalObject, event, + JSC::JSValue::encode(listener), true); + + scope.release(); + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DEFINE_HOST_FUNCTION(Readable__read, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__read); +} + +static JSC_DEFINE_HOST_FUNCTION(Readable__pipe, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__pipe); +} + +static JSC_DEFINE_HOST_FUNCTION(Readable__resume, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__resume); +} +static JSC_DEFINE_HOST_FUNCTION(Readable__unpipe, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__unpipe); +} +static JSC_DEFINE_HOST_FUNCTION(Readable__pause, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__pause); +} +static JSC_DEFINE_HOST_FUNCTION(Readable__unshift, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Readable, Bun__Readable__unshift); +} + +// static JSC_DECLARE_HOST_FUNCTION(Readable__isPaused); +// static JSC_DECLARE_HOST_FUNCTION(Writable__setDefaultEncoding); + +// static DEFINE_CALLBACK_FUNCTION(Writable__setDefaultEncoding, Bun::Writable, +// Bun__Writable__setDefaultEncoding); + +static JSC_DEFINE_HOST_FUNCTION(Writable__write, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__write); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__end, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__end); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__close, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__close); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__destroy, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__destroy); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__cork, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__cork); +} +static JSC_DEFINE_HOST_FUNCTION(Writable__uncork, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + DEFINE_CALLBACK_FUNCTION_BODY(Bun::Writable, Bun__Writable__uncork); +} + +extern "C" JSC__JSValue Bun__Readable__create(Bun__Readable *state, + JSC__JSGlobalObject *globalObject) { + JSC::JSValue result = JSC::JSValue(Readable::create( + globalObject->vm(), state, + Readable::createStructure(globalObject->vm(), globalObject, globalObject->objectPrototype()))); + + return JSC::JSValue::encode(result); +} +extern "C" JSC__JSValue Bun__Writable__create(Bun__Writable *state, + JSC__JSGlobalObject *globalObject) { + JSC::JSValue result = JSC::JSValue(Writable::create( + globalObject->vm(), state, + Writable::createStructure(globalObject->vm(), globalObject, globalObject->objectPrototype()))); + + return JSC::JSValue::encode(result); +} + +Readable::~Readable() { + if (this->state) { Bun__Readable__deinit(this->state); } +} + +Writable::~Writable() { + if (this->state) { Bun__Writable__deinit(this->state); } +} + +void Readable::finishCreation(JSC::VM &vm) { + Base::finishCreation(vm); + auto clientData = Bun::clientData(vm); + auto *globalObject = this->globalObject(); + + putDirect(vm, clientData->builtinNames().onPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().onPublicName().string(), Readable__on), + 0); + putDirect(vm, clientData->builtinNames().oncePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().oncePublicName().string(), + Readable__once), + 0); + putDirect(vm, clientData->builtinNames().pausePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().pausePublicName().string(), + Readable__pause), + 0); + putDirect(vm, clientData->builtinNames().pipePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().pipePublicName().string(), + Readable__pipe), + 0); + putDirect(vm, clientData->builtinNames().readPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().readPublicName().string(), + Readable__read), + 0); + putDirect(vm, clientData->builtinNames().resumePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().resumePublicName().string(), + Readable__resume), + 0); + putDirect(vm, clientData->builtinNames().unpipePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().unpipePublicName().string(), + Readable__unpipe), + 0); + putDirect(vm, clientData->builtinNames().unshiftPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().unshiftPublicName().string(), + Readable__unshift), + 0); +} + +void Writable::finishCreation(JSC::VM &vm) { + Base::finishCreation(vm); + auto clientData = Bun::clientData(vm); + + auto *globalObject = this->globalObject(); + + putDirect(vm, clientData->builtinNames().onPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().onPublicName().string(), Writable__on), + 0); + + putDirect(vm, clientData->builtinNames().oncePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().oncePublicName().string(), + Writable__once), + 0); + + putDirect(vm, clientData->builtinNames().closePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().closePublicName().string(), + Writable__close), + 0); + putDirect(vm, clientData->builtinNames().corkPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().corkPublicName().string(), + Writable__cork), + 0); + putDirect(vm, clientData->builtinNames().destroyPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().destroyPublicName().string(), + Writable__destroy), + 0); + putDirect(vm, clientData->builtinNames().endPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().endPublicName().string(), Writable__end), + 0); + putDirect(vm, clientData->builtinNames().onPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().onPublicName().string(), Writable__on), + 0); + putDirect(vm, clientData->builtinNames().oncePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().oncePublicName().string(), + Writable__once), + 0); + putDirect(vm, clientData->builtinNames().uncorkPublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().uncorkPublicName().string(), + Writable__uncork), + 0); + putDirect(vm, clientData->builtinNames().writePublicName(), + JSFunction::create(vm, globalObject, 2, + clientData->builtinNames().writePublicName().string(), + Writable__write), + 0); +} + +} // namespace Bun
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/BunStream.h b/src/javascript/jsc/bindings/BunStream.h new file mode 100644 index 000000000..37762d689 --- /dev/null +++ b/src/javascript/jsc/bindings/BunStream.h @@ -0,0 +1,82 @@ +#pragma once + +#include "BunBuiltinNames.h" +#include "BunClientData.h" +#include "root.h" + +namespace Bun { + +using namespace JSC; + +class Readable : public JSC::JSNonFinalObject { + using Base = JSC::JSNonFinalObject; + + public: + Bun__Readable *state; + Readable(JSC::VM &vm, Bun__Readable *readable, JSC::Structure *structure) : Base(vm, structure) { + state = readable; + } + + ~Readable(); + + DECLARE_INFO; + + static constexpr unsigned StructureFlags = Base::StructureFlags; + + template <typename CellType, JSC::SubspaceAccess> + static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) { + return &vm.cellSpace; + } + + 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 Readable *create(JSC::VM &vm, Bun__Readable *state, JSC::Structure *structure) { + Readable *accessor = + new (NotNull, JSC::allocateCell<Bun::Readable>(vm.heap)) Readable(vm, state, structure); + accessor->finishCreation(vm); + return accessor; + } + + void finishCreation(JSC::VM &vm); +}; + +class Writable : public JSC::JSNonFinalObject { + using Base = JSC::JSNonFinalObject; + + public: + Bun__Writable *state; + Writable(JSC::VM &vm, Bun__Writable *writable, JSC::Structure *structure) : Base(vm, structure) { + state = writable; + } + + DECLARE_INFO; + + static constexpr unsigned StructureFlags = Base::StructureFlags; + + template <typename CellType, JSC::SubspaceAccess> + static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) { + return &vm.cellSpace; + } + + 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 Writable *create(JSC::VM &vm, Bun__Writable *state, JSC::Structure *structure) { + Writable *accessor = + new (NotNull, JSC::allocateCell<Writable>(vm.heap)) Writable(vm, state, structure); + accessor->finishCreation(vm); + return accessor; + } + ~Writable(); + + void finishCreation(JSC::VM &vm); +}; + +} // namespace Bun
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/Process.cpp b/src/javascript/jsc/bindings/Process.cpp new file mode 100644 index 000000000..754c1d96b --- /dev/null +++ b/src/javascript/jsc/bindings/Process.cpp @@ -0,0 +1,340 @@ +#include "Process.h" +#include <JavaScriptCore/JSMicrotask.h> +#include <JavaScriptCore/ObjectConstructor.h> + +#pragma mark - Node.js Process + +namespace Zig { + +using JSGlobalObject = JSC::JSGlobalObject; +using Exception = JSC::Exception; +using JSValue = JSC::JSValue; +using JSString = JSC::JSString; +using JSModuleLoader = JSC::JSModuleLoader; +using JSModuleRecord = JSC::JSModuleRecord; +using Identifier = JSC::Identifier; +using SourceOrigin = JSC::SourceOrigin; +using JSObject = JSC::JSObject; +using JSNonFinalObject = JSC::JSNonFinalObject; +namespace JSCastingHelpers = JSC::JSCastingHelpers; + +static JSC_DECLARE_CUSTOM_SETTER(Process_setTitle); +static JSC_DECLARE_CUSTOM_GETTER(Process_getArgv); +static JSC_DECLARE_CUSTOM_SETTER(Process_setArgv); +static JSC_DECLARE_CUSTOM_GETTER(Process_getTitle); +static JSC_DECLARE_CUSTOM_GETTER(Process_getVersionsLazy); +static JSC_DECLARE_CUSTOM_SETTER(Process_setVersionsLazy); + +static JSC_DECLARE_CUSTOM_GETTER(Process_getPID); +static JSC_DECLARE_CUSTOM_GETTER(Process_getPPID); + +static JSC_DECLARE_HOST_FUNCTION(Process_functionCwd); + +static JSC_DECLARE_HOST_FUNCTION(Process_functionNextTick); +static JSC_DEFINE_HOST_FUNCTION(Process_functionNextTick, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + auto argCount = callFrame->argumentCount(); + if (argCount == 0) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "nextTick requires 1 argument (a function)"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + JSC::JSValue job = callFrame->uncheckedArgument(0); + + if (!job.isObject() || !job.getObject()->isCallable(vm)) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "nextTick expects a function"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + switch (argCount) { + + case 1: { + // This is a JSC builtin function + globalObject->queueMicrotask(JSC::createJSMicrotask(vm, job)); + break; + } + + case 2: + case 3: + case 4: + case 5: { + JSC::JSValue argument0 = callFrame->uncheckedArgument(1); + JSC::JSValue argument1 = argCount > 2 ? callFrame->uncheckedArgument(2) : JSC::JSValue{}; + JSC::JSValue argument2 = argCount > 3 ? callFrame->uncheckedArgument(3) : JSC::JSValue{}; + JSC::JSValue argument3 = argCount > 4 ? callFrame->uncheckedArgument(4) : JSC::JSValue{}; + globalObject->queueMicrotask( + JSC::createJSMicrotask(vm, job, argument0, argument1, argument2, argument3)); + break; + } + + default: { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, + "nextTick doesn't support more than 4 arguments currently"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + + break; + } + + // JSC::MarkedArgumentBuffer args; + // for (unsigned i = 1; i < callFrame->argumentCount(); i++) { + // args.append(callFrame->uncheckedArgument(i)); + // } + + // JSC::ArgList argsList(args); + // JSC::gcProtect(job); + // JSC::JSFunction *callback = JSC::JSNativeStdFunction::create( + // vm, globalObject, 0, String(), + // [job, &argsList](JSC::JSGlobalObject *globalObject, JSC::CallFrame *callFrame) { + // JSC::VM &vm = globalObject->vm(); + // auto callData = getCallData(vm, job); + + // return JSC::JSValue::encode(JSC::call(globalObject, job, callData, job, argsList)); + // }); + + // globalObject->queueMicrotask(JSC::createJSMicrotask(vm, JSC::JSValue(callback))); + } + + return JSC::JSValue::encode(JSC::jsUndefined()); +} + +static JSC_DECLARE_HOST_FUNCTION(Process_functionChdir); + +static JSC_DEFINE_HOST_FUNCTION(Process_functionChdir, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + + ZigString str = ZigString{nullptr, 0}; + if (callFrame->argumentCount() > 0) { + str = Zig::toZigString(callFrame->uncheckedArgument(0).toWTFString(globalObject)); + } + + JSC::JSValue result = JSC::JSValue::decode(Bun__Process__setCwd(globalObject, &str)); + JSC::JSObject *obj = result.getObject(); + if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) { + scope.throwException(globalObject, obj); + return JSValue::encode(JSC::jsUndefined()); + } + + return JSC::JSValue::encode(result); +} + +void Process::finishCreation(JSC::VM &vm) { + Base::finishCreation(vm); + auto clientData = Bun::clientData(vm); + + putDirectCustomAccessor(vm, clientData->builtinNames().pidPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getPID, nullptr), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + putDirectCustomAccessor(vm, clientData->builtinNames().ppidPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getPPID, nullptr), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + putDirectCustomAccessor(vm, clientData->builtinNames().titlePublicName(), + JSC::CustomGetterSetter::create(vm, Process_getTitle, Process_setTitle), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + putDirectCustomAccessor(vm, clientData->builtinNames().argvPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getArgv, Process_setArgv), + static_cast<unsigned>(JSC::PropertyAttribute::CustomValue)); + + this->putDirect(vm, clientData->builtinNames().nextTickPublicName(), + JSC::JSFunction::create(vm, JSC::jsCast<JSC::JSGlobalObject *>(globalObject()), 0, + WTF::String("nextTick"), Process_functionNextTick), + 0); + + this->putDirect(vm, clientData->builtinNames().cwdPublicName(), + JSC::JSFunction::create(vm, JSC::jsCast<JSC::JSGlobalObject *>(globalObject()), 0, + WTF::String("cwd"), Process_functionCwd), + 0); + + this->putDirect(vm, clientData->builtinNames().chdirPublicName(), + JSC::JSFunction::create(vm, JSC::jsCast<JSC::JSGlobalObject *>(globalObject()), 0, + WTF::String("chdir"), Process_functionChdir), + 0); + + putDirectCustomAccessor( + vm, clientData->builtinNames().versionsPublicName(), + JSC::CustomGetterSetter::create(vm, Process_getVersionsLazy, Process_setVersionsLazy), 0); + // this should be transpiled out, but just incase + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "browser"), + JSC::JSValue(false)); + + this->putDirect(this->vm(), clientData->builtinNames().versionPublicName(), + JSC::jsString(this->vm(), WTF::String(Bun__version))); + + // this gives some way of identifying at runtime whether the SSR is happening in node or not. + // this should probably be renamed to what the name of the bundler is, instead of "notNodeJS" + // but it must be something that won't evaluate to truthy in Node.js + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "isBun"), JSC::JSValue(true)); +#if defined(__APPLE__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), + JSC::jsString(this->vm(), WTF::String("darwin"))); +#else + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), + JSC::jsString(this->vm(), WTF::String("linux"))); +#endif + +#if defined(__x86_64__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("x64"))); +#elif defined(__i386__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("x86"))); +#elif defined(__arm__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("arm"))); +#elif defined(__aarch64__) + this->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "arch"), + JSC::jsString(this->vm(), WTF::String("arm64"))); +#endif +} + +const JSC::ClassInfo Process::s_info = {"Process", &Base::s_info, nullptr, nullptr, + CREATE_METHOD_TABLE(Process)}; + +JSC_DEFINE_CUSTOM_GETTER(Process_getTitle, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + ZigString str; + Bun__Process__getTitle(globalObject, &str); + return JSValue::encode(Zig::toJSStringValue(str, globalObject)); +} + +JSC_DEFINE_CUSTOM_SETTER(Process_setTitle, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + + JSC::JSObject *thisObject = JSC::jsDynamicCast<JSC::JSObject *>(vm, JSValue::decode(thisValue)); + JSC::JSString *jsString = JSC::jsDynamicCast<JSC::JSString *>(vm, JSValue::decode(value)); + if (!thisObject || !jsString) { return false; } + + ZigString str = Zig::toZigString(jsString, globalObject); + Bun__Process__setTitle(globalObject, &str); + + return true; +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getArgv, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + + Zig::Process *thisObject = JSC::jsDynamicCast<Zig::Process *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); } + auto clientData = Bun::clientData(vm); + + if (JSC::JSValue argv = thisObject->getIfPropertyExists( + globalObject, clientData->builtinNames().argvPrivateName())) { + return JSValue::encode(argv); + } + + JSC::EncodedJSValue argv_ = Bun__Process__getArgv(globalObject); + thisObject->putDirect(vm, clientData->builtinNames().argvPrivateName(), + JSC::JSValue::decode(argv_)); + + return argv_; +} + +JSC_DEFINE_CUSTOM_SETTER(Process_setArgv, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + + JSC::JSObject *thisObject = JSC::jsDynamicCast<JSC::JSObject *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return false; } + + auto clientData = Bun::clientData(vm); + + return thisObject->putDirect(vm, clientData->builtinNames().argvPrivateName(), + JSC::JSValue::decode(value)); +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getPID, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + return JSC::JSValue::encode(JSC::JSValue(getpid())); +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getPPID, (JSC::JSGlobalObject * globalObject, + JSC::EncodedJSValue thisValue, JSC::PropertyName)) { + return JSC::JSValue::encode(JSC::JSValue(getppid())); +} + +JSC_DEFINE_CUSTOM_GETTER(Process_getVersionsLazy, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::PropertyName)) { + JSC::VM &vm = globalObject->vm(); + auto clientData = Bun::clientData(vm); + + Zig::Process *thisObject = JSC::jsDynamicCast<Zig::Process *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); } + + if (JSC::JSValue argv = thisObject->getIfPropertyExists( + globalObject, clientData->builtinNames().versionsPrivateName())) { + return JSValue::encode(argv); + } + + JSC::JSObject *object = + JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 9); + + object->putDirect(vm, JSC::Identifier::fromString(vm, "node"), + JSC::JSValue(JSC::jsString(vm, WTF::String("17.0.0")))); + object->putDirect( + vm, JSC::Identifier::fromString(vm, "bun"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__version + 1 /* prefix with v */)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "webkit"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_webkit)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "mimalloc"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_mimalloc)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "libarchive"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_libarchive)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "picohttpparser"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_picohttpparser)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "boringssl"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_boringssl)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "zlib"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_zlib)))); + object->putDirect(vm, JSC::Identifier::fromString(vm, "zig"), + JSC::JSValue(JSC::jsString(vm, WTF::String(Bun__versions_zig)))); + + object->putDirect(vm, JSC::Identifier::fromString(vm, "modules"), + JSC::JSValue(JSC::jsString(vm, WTF::String("67")))); + + thisObject->putDirect(vm, clientData->builtinNames().versionsPrivateName(), object); + return JSC::JSValue::encode(object); +} +JSC_DEFINE_CUSTOM_SETTER(Process_setVersionsLazy, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + + JSC::VM &vm = globalObject->vm(); + auto clientData = Bun::clientData(vm); + + Zig::Process *thisObject = JSC::jsDynamicCast<Zig::Process *>(vm, JSValue::decode(thisValue)); + if (!thisObject) { return JSValue::encode(JSC::jsUndefined()); } + + thisObject->putDirect(vm, clientData->builtinNames().versionsPrivateName(), + JSC::JSValue::decode(value)); + + return true; +} + +static JSC_DEFINE_HOST_FUNCTION(Process_functionCwd, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::JSValue result = JSC::JSValue::decode(Bun__Process__getCwd(globalObject)); + JSC::JSObject *obj = result.getObject(); + if (UNLIKELY(obj != nullptr && obj->isErrorInstance())) { + scope.throwException(globalObject, obj); + return JSValue::encode(JSC::jsUndefined()); + } + + return JSC::JSValue::encode(result); +} + +} // namespace Zig
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/Process.h b/src/javascript/jsc/bindings/Process.h new file mode 100644 index 000000000..7e025bc3a --- /dev/null +++ b/src/javascript/jsc/bindings/Process.h @@ -0,0 +1,39 @@ +#pragma once + +#include "BunBuiltinNames.h" +#include "BunClientData.h" +#include "root.h" + +namespace Zig { + +class Process : public JSC::JSNonFinalObject { + using Base = JSC::JSNonFinalObject; + + public: + Process(JSC::VM &vm, JSC::Structure *structure) : Base(vm, structure) {} + + DECLARE_INFO; + + static constexpr unsigned StructureFlags = Base::StructureFlags; + + template <typename CellType, JSC::SubspaceAccess> + static JSC::CompleteSubspace *subspaceFor(JSC::VM &vm) { + return &vm.cellSpace; + } + + 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 Process *create(JSC::VM &vm, JSC::Structure *structure) { + Process *accessor = new (NotNull, JSC::allocateCell<Process>(vm.heap)) Process(vm, structure); + accessor->finishCreation(vm); + return accessor; + } + + void finishCreation(JSC::VM &vm); +}; + +} // namespace Zig
\ No newline at end of file diff --git a/src/javascript/jsc/bindings/ZigGlobalObject.cpp b/src/javascript/jsc/bindings/ZigGlobalObject.cpp index e113e4df2..0329024a4 100644 --- a/src/javascript/jsc/bindings/ZigGlobalObject.cpp +++ b/src/javascript/jsc/bindings/ZigGlobalObject.cpp @@ -26,6 +26,7 @@ #include <JavaScriptCore/JSCallbackObject.h> #include <JavaScriptCore/JSCast.h> #include <JavaScriptCore/JSClassRef.h> +#include <JavaScriptCore/JSMicrotask.h> // #include <JavaScriptCore/JSContextInternal.h> #include <JavaScriptCore/CatchScope.h> #include <JavaScriptCore/JSInternalPromise.h> @@ -51,6 +52,7 @@ #include <JavaScriptCore/VM.h> #include <JavaScriptCore/VMEntryScope.h> #include <JavaScriptCore/WasmFaultSignalHandler.h> +#include <unistd.h> #include <wtf/Gigacage.h> #include <wtf/StdLibExtras.h> #include <wtf/URL.h> @@ -68,6 +70,8 @@ #include <JavaScriptCore/JSCallbackObject.h> #include <JavaScriptCore/JSClassRef.h> +#include "BunClientData.h" + #include "ZigSourceProvider.h" using JSGlobalObject = JSC::JSGlobalObject; @@ -82,21 +86,20 @@ using JSObject = JSC::JSObject; using JSNonFinalObject = JSC::JSNonFinalObject; namespace JSCastingHelpers = JSC::JSCastingHelpers; -bool has_loaded_jsc = false; +static bool has_loaded_jsc = false; extern "C" void JSCInitialize() { if (has_loaded_jsc) return; + has_loaded_jsc = true; + JSC::Options::useSourceProviderCache() = true; JSC::Options::useUnlinkedCodeBlockJettisoning() = false; JSC::Options::exposeInternalModuleLoader() = true; JSC::Options::useSharedArrayBuffer() = true; // JSC::Options::useAtMethod() = true; - // std::set_terminate([]() { Zig__GlobalObject__onCrash(); }); WTF::initializeMainThread(); JSC::initialize(); - // Gigacage::disablePrimitiveGigacage(); - has_loaded_jsc = true; } extern "C" JSC__JSGlobalObject *Zig__GlobalObject__create(JSClassRef *globalObjectClass, int count, @@ -104,6 +107,8 @@ extern "C" JSC__JSGlobalObject *Zig__GlobalObject__create(JSClassRef *globalObje auto heapSize = JSC::LargeHeap; JSC::VM &vm = JSC::VM::create(heapSize).leakRef(); + Bun::JSVMClientData::create(&vm); + vm.heap.acquireAccess(); #if ENABLE(WEBASSEMBLY) JSC::Wasm::enableFastMemory(); @@ -257,33 +262,80 @@ void GlobalObject::setConsole(void *console) { this->setConsoleClient(makeWeakPtr(m_console)); } +#pragma mark - Globals + +static JSC_DECLARE_CUSTOM_SETTER(property_lazyProcessSetter); +static JSC_DECLARE_CUSTOM_GETTER(property_lazyProcessGetter); + +JSC_DEFINE_CUSTOM_SETTER(property_lazyProcessSetter, + (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, + JSC::EncodedJSValue value, JSC::PropertyName)) { + return false; +} + +static JSClassRef dot_env_class_ref; +JSC_DEFINE_CUSTOM_GETTER(property_lazyProcessGetter, + (JSC::JSGlobalObject * _globalObject, JSC::EncodedJSValue thisValue, + JSC::PropertyName)) { + Zig::GlobalObject *globalObject = reinterpret_cast<Zig::GlobalObject *>(_globalObject); + if (LIKELY(globalObject->m_process)) + return JSValue::encode(JSC::JSValue(globalObject->m_process)); + + JSC::VM &vm = globalObject->vm(); + + globalObject->m_process = Zig::Process::create( + vm, Zig::Process::createStructure(vm, globalObject, globalObject->objectPrototype())); + + { + auto jsClass = dot_env_class_ref; + + JSC::JSCallbackObject<JSNonFinalObject> *object = + JSC::JSCallbackObject<JSNonFinalObject>::create( + globalObject, globalObject->callbackObjectStructure(), jsClass, nullptr); + if (JSObject *prototype = jsClass->prototype(globalObject)) + object->setPrototypeDirect(vm, prototype); + + globalObject->m_process->putDirect(vm, JSC::Identifier::fromString(vm, "env"), + JSC::JSValue(object), + JSC::PropertyAttribute::DontDelete | 0); + } + + return JSC::JSValue::encode(JSC::JSValue(globalObject->m_process)); +} + +static JSC_DECLARE_HOST_FUNCTION(functionQueueMicrotask); + +static JSC_DEFINE_HOST_FUNCTION(functionQueueMicrotask, + (JSC::JSGlobalObject * globalObject, JSC::CallFrame *callFrame)) { + JSC::VM &vm = globalObject->vm(); + + if (callFrame->argumentCount() == 0) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "queueMicrotask requires 1 argument (a function)"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + JSC::JSValue job = callFrame->argument(0); + + if (!job.isObject() || !job.getObject()->isCallable(vm)) { + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSC::throwTypeError(globalObject, scope, "queueMicrotask expects a function"_s); + return JSC::JSValue::encode(JSC::JSValue{}); + } + + // This is a JSC builtin function + globalObject->queueMicrotask(JSC::createJSMicrotask(vm, job)); + + return JSC::JSValue::encode(JSC::jsUndefined()); +} + // This is not a publicly exposed API currently. // This is used by the bundler to make Response, Request, FetchEvent, // and any other objects available globally. void GlobalObject::installAPIGlobals(JSClassRef *globals, int count) { WTF::Vector<GlobalPropertyInfo> extraStaticGlobals; - extraStaticGlobals.reserveCapacity((size_t)count + 2); - - // This is not nearly a complete implementation. It's just enough to make some npm packages that - // were compiled with Webpack to run without crashing in this environment. - JSC::JSObject *process = JSC::constructEmptyObject(this, this->objectPrototype(), 4); - - // this should be transpiled out, but just incase - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "browser"), - JSC::JSValue(false)); - - // this gives some way of identifying at runtime whether the SSR is happening in node or not. - // this should probably be renamed to what the name of the bundler is, instead of "notNodeJS" - // but it must be something that won't evaluate to truthy in Node.js - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "isBun"), - JSC::JSValue(true)); -#if defined(__APPLE__) - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), - JSC::jsString(this->vm(), WTF::String("darwin"))); -#else - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "platform"), - JSC::jsString(this->vm(), WTF::String("linux"))); -#endif + extraStaticGlobals.reserveCapacity((size_t)count + 3); + int i = 0; for (; i < count - 1; i++) { auto jsClass = globals[i]; @@ -300,23 +352,38 @@ void GlobalObject::installAPIGlobals(JSClassRef *globals, int count) { // The last one must be "process.env" // Runtime-support is for if they change - { - auto jsClass = globals[i]; + dot_env_class_ref = globals[i]; - JSC::JSCallbackObject<JSNonFinalObject> *object = - JSC::JSCallbackObject<JSNonFinalObject>::create(this, this->callbackObjectStructure(), - jsClass, nullptr); - if (JSObject *prototype = jsClass->prototype(this)) object->setPrototypeDirect(vm(), prototype); + // // The last one must be "process.env" + // // Runtime-support is for if they change + // { + // auto jsClass = globals[i]; - process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "env"), - JSC::JSValue(object), JSC::PropertyAttribute::DontDelete | 0); - } + // JSC::JSCallbackObject<JSNonFinalObject> *object = + // JSC::JSCallbackObject<JSNonFinalObject>::create(this, this->callbackObjectStructure(), + // jsClass, nullptr); + // if (JSObject *prototype = jsClass->prototype(this)) object->setPrototypeDirect(vm(), + // prototype); + + // process->putDirect(this->vm(), JSC::Identifier::fromString(this->vm(), "env"), + // JSC::JSValue(object), JSC::PropertyAttribute::DontDelete | 0); + // } + JSC::Identifier queueMicrotaskIdentifier = JSC::Identifier::fromString(vm(), "queueMicrotask"_s); extraStaticGlobals.uncheckedAppend( - GlobalPropertyInfo{JSC::Identifier::fromString(vm(), "process"), JSC::JSValue(process), + GlobalPropertyInfo{queueMicrotaskIdentifier, + JSC::JSFunction::create(vm(), JSC::jsCast<JSC::JSGlobalObject *>(this), 0, + "queueMicrotask", functionQueueMicrotask), JSC::PropertyAttribute::DontDelete | 0}); + auto clientData = Bun::clientData(vm()); + this->addStaticGlobals(extraStaticGlobals.data(), extraStaticGlobals.size()); + putDirectCustomAccessor( + vm(), clientData->builtinNames().processPublicName(), + JSC::CustomGetterSetter::create(vm(), property_lazyProcessGetter, property_lazyProcessSetter), + JSC::PropertyAttribute::CustomValue | 0); + extraStaticGlobals.releaseBuffer(); } @@ -418,7 +485,6 @@ JSC::JSObject *GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObje JSModuleRecord *record, JSValue val) { - ZigString specifier = Zig::toZigString(key, globalObject); JSC::VM &vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); @@ -426,7 +492,16 @@ JSC::JSObject *GlobalObject::moduleLoaderCreateImportMetaProperties(JSGlobalObje JSC::constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure()); RETURN_IF_EXCEPTION(scope, nullptr); - metaProperties->putDirect(vm, Identifier::fromString(vm, "filePath"), key); + auto clientData = Bun::clientData(vm); + JSString *keyString = key.toStringOrNull(globalObject); + if (UNLIKELY(!keyString)) { return metaProperties; } + auto view = keyString->value(globalObject); + auto index = view.reverseFind('/', view.length()); + if (index != WTF::notFound) { + metaProperties->putDirect(vm, clientData->builtinNames().dirPublicName(), + JSC::jsSubstring(globalObject, keyString, 0, index)); + } + metaProperties->putDirect(vm, clientData->builtinNames().pathPublicName(), key); RETURN_IF_EXCEPTION(scope, nullptr); // metaProperties->putDirect(vm, Identifier::fromString(vm, "resolve"), diff --git a/src/javascript/jsc/bindings/ZigGlobalObject.h b/src/javascript/jsc/bindings/ZigGlobalObject.h index 64ece0c64..3d5d389e0 100644 --- a/src/javascript/jsc/bindings/ZigGlobalObject.h +++ b/src/javascript/jsc/bindings/ZigGlobalObject.h @@ -9,11 +9,13 @@ class Identifier; } // namespace JSC +#include "Process.h" #include "ZigConsoleClient.h" #include <JavaScriptCore/CatchScope.h> #include <JavaScriptCore/JSGlobalObject.h> #include <JavaScriptCore/JSTypeInfo.h> #include <JavaScriptCore/Structure.h> + namespace Zig { class GlobalObject : public JSC::JSGlobalObject { @@ -22,7 +24,7 @@ class GlobalObject : public JSC::JSGlobalObject { public: DECLARE_EXPORT_INFO; static const JSC::GlobalObjectMethodTable s_globalObjectMethodTable; - + Zig::Process *m_process; static constexpr bool needsDestruction = true; template <typename CellType, JSC::SubspaceAccess mode> static JSC::IsoSubspace *subspaceFor(JSC::VM &vm) { @@ -74,17 +76,14 @@ class JSMicrotaskCallback : public RefCounted<JSMicrotaskCallback> { public: static Ref<JSMicrotaskCallback> create(JSC::JSGlobalObject &globalObject, Ref<JSC::Microtask> &&task) { - return adoptRef(*new JSMicrotaskCallback(globalObject, WTFMove(task))); + return adoptRef(*new JSMicrotaskCallback(globalObject, WTFMove(task).leakRef())); } void call() { auto protectedThis{makeRef(*this)}; JSC::VM &vm = m_globalObject->vm(); - JSC::JSLockHolder lock(vm); - auto scope = DECLARE_CATCH_SCOPE(vm); auto task = &m_task.get(); task->run(m_globalObject.get()); - scope.assertNoExceptionExceptTermination(); } private: diff --git a/src/javascript/jsc/bindings/bindings.cpp b/src/javascript/jsc/bindings/bindings.cpp index 60b6a442e..7af7d3a25 100644 --- a/src/javascript/jsc/bindings/bindings.cpp +++ b/src/javascript/jsc/bindings/bindings.cpp @@ -1,3 +1,4 @@ +#include "BunClientData.h" #include "ZigGlobalObject.h" #include "helpers.h" #include "root.h" @@ -6,8 +7,10 @@ #include <JavaScriptCore/CodeBlock.h> #include <JavaScriptCore/Completion.h> #include <JavaScriptCore/ErrorInstance.h> +#include <JavaScriptCore/ExceptionHelpers.h> #include <JavaScriptCore/ExceptionScope.h> #include <JavaScriptCore/FunctionConstructor.h> +#include <JavaScriptCore/HeapSnapshotBuilder.h> #include <JavaScriptCore/Identifier.h> #include <JavaScriptCore/IteratorOperations.h> #include <JavaScriptCore/JSArray.h> @@ -20,6 +23,7 @@ #include <JavaScriptCore/JSModuleLoader.h> #include <JavaScriptCore/JSModuleRecord.h> #include <JavaScriptCore/JSNativeStdFunction.h> +#include <JavaScriptCore/JSONObject.h> #include <JavaScriptCore/JSObject.h> #include <JavaScriptCore/JSSet.h> #include <JavaScriptCore/JSString.h> @@ -31,6 +35,7 @@ #include <JavaScriptCore/StackVisitor.h> #include <JavaScriptCore/VM.h> #include <JavaScriptCore/WasmFaultSignalHandler.h> +#include <JavaScriptCore/Watchdog.h> #include <wtf/text/ExternalStringImpl.h> #include <wtf/text/StringCommon.h> #include <wtf/text/StringImpl.h> @@ -39,6 +44,62 @@ extern "C" { +JSC__JSValue SystemError__toErrorInstance(const SystemError *arg0, + JSC__JSGlobalObject *globalObject) { + + static const char *system_error_name = "SystemError"; + SystemError err = *arg0; + + JSC::VM &vm = globalObject->vm(); + + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::JSValue message = JSC::jsUndefined(); + if (err.message.len > 0) { message = Zig::toJSString(err.message, globalObject); } + + JSC::JSValue options = JSC::jsUndefined(); + + JSC::Structure *errorStructure = globalObject->errorStructure(); + JSC::JSObject *result = + JSC::ErrorInstance::create(globalObject, errorStructure, message, options); + + auto clientData = Bun::clientData(vm); + + if (err.code.len > 0) { + JSC::JSValue code = Zig::toJSString(err.code, globalObject); + result->putDirect(vm, clientData->builtinNames().codePublicName(), code, + JSC::PropertyAttribute::DontDelete | 0); + + result->putDirect(vm, vm.propertyNames->name, code, JSC::PropertyAttribute::DontEnum | 0); + } else { + + result->putDirect( + vm, vm.propertyNames->name, + JSC::JSValue(JSC::jsOwnedString( + vm, WTF::String(WTF::StringImpl::createWithoutCopying(system_error_name, 11)))), + JSC::PropertyAttribute::DontEnum | 0); + } + + if (err.path.len > 0) { + JSC::JSValue path = JSC::JSValue(Zig::toJSStringGC(err.path, globalObject)); + result->putDirect(vm, clientData->builtinNames().pathPublicName(), path, + JSC::PropertyAttribute::DontDelete | 0); + } + + if (err.syscall.len > 0) { + JSC::JSValue syscall = JSC::JSValue(Zig::toJSString(err.syscall, globalObject)); + result->putDirect(vm, clientData->builtinNames().syscallPublicName(), syscall, + JSC::PropertyAttribute::DontDelete | 0); + } + + result->putDirect(vm, clientData->builtinNames().errnoPublicName(), JSC::JSValue(err.errno_), + JSC::PropertyAttribute::DontDelete | 0); + + RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue())); + scope.release(); + + return JSC::JSValue::encode(JSC::JSValue(result)); +} + JSC__JSValue JSC__JSObject__create(JSC__JSGlobalObject *globalObject, size_t initialCapacity, void *arg2, void (*ArgFn3)(void *arg0, JSC__JSObject *arg1, JSC__JSGlobalObject *arg2)) { @@ -147,6 +208,19 @@ void JSC__JSValue__putRecord(JSC__JSValue objectValue, JSC__JSGlobalObject *glob scope.release(); } +void JSC__JSValue__jsonStringify(JSC__JSValue JSValue0, JSC__JSGlobalObject *arg1, uint32_t arg2, + ZigString *arg3) { + JSC::JSValue value = JSC::JSValue::decode(JSValue0); + WTF::String str = JSC::JSONStringify(arg1, value, (unsigned)arg2); + *arg3 = Zig::toZigString(str); +} +unsigned char JSC__JSValue__jsType(JSC__JSValue JSValue0) { + JSC::JSValue jsValue = JSC::JSValue::decode(JSValue0); + if (!jsValue.isCell()) return 0; + + return jsValue.asCell()->type(); +} + // This is very naive! JSC__JSInternalPromise *JSC__VM__reloadModule(JSC__VM *vm, JSC__JSGlobalObject *arg1, ZigString arg2) { @@ -175,6 +249,12 @@ JSC__JSInternalPromise *JSC__VM__reloadModule(JSC__VM *vm, JSC__JSGlobalObject * // return nullptr; } +bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1, + JSC__JSGlobalObject *globalObject) { + return JSC::sameValue(globalObject, JSC::JSValue::decode(JSValue0), + JSC::JSValue::decode(JSValue1)); +} + // This is the same as the C API version, except it returns a JSValue which may be a *Exception // We want that so we can return stack traces. JSC__JSValue JSObjectCallAsFunctionReturnValue(JSContextRef ctx, JSObjectRef object, @@ -211,6 +291,44 @@ JSC__JSValue JSObjectCallAsFunctionReturnValue(JSContextRef ctx, JSObjectRef obj return JSC::JSValue::encode(result); } +JSC__JSValue JSObjectCallAsFunctionReturnValueHoldingAPILock(JSContextRef ctx, JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef *arguments); + +JSC__JSValue JSObjectCallAsFunctionReturnValueHoldingAPILock(JSContextRef ctx, JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef *arguments) { + JSC::JSGlobalObject *globalObject = toJS(ctx); + JSC::VM &vm = globalObject->vm(); + + JSC::JSLockHolder lock(vm); + + if (!object) return JSC::JSValue::encode(JSC::JSValue()); + + JSC::JSObject *jsObject = toJS(object); + JSC::JSObject *jsThisObject = toJS(thisObject); + + if (!jsThisObject) jsThisObject = globalObject->globalThis(); + + JSC::MarkedArgumentBuffer argList; + for (size_t i = 0; i < argumentCount; i++) argList.append(toJS(globalObject, arguments[i])); + + auto callData = getCallData(vm, jsObject); + if (callData.type == JSC::CallData::Type::None) return JSC::JSValue::encode(JSC::JSValue()); + + NakedPtr<JSC::Exception> returnedException = nullptr; + auto result = + JSC::call(globalObject, jsObject, callData, jsThisObject, argList, returnedException); + + if (returnedException.get()) { + return JSC::JSValue::encode(JSC::JSValue(returnedException.get())); + } + + return JSC::JSValue::encode(result); +} + #pragma mark - JSC::Exception JSC__Exception *JSC__Exception__create(JSC__JSGlobalObject *arg0, JSC__JSObject *arg1, @@ -236,10 +354,10 @@ JSC__JSValue JSC__JSObject__getIndex(JSC__JSValue jsValue, JSC__JSGlobalObject * return JSC::JSValue::encode(JSC::JSValue::decode(jsValue).toObject(arg1)->getIndex(arg1, arg3)); } JSC__JSValue JSC__JSObject__getDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, - const ZigString * arg2) { + const ZigString *arg2) { return JSC::JSValue::encode(arg0->getDirect(arg1->vm(), Zig::toIdentifier(*arg2, arg1))); } -void JSC__JSObject__putDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, const ZigString * key, +void JSC__JSObject__putDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, const ZigString *key, JSC__JSValue value) { auto prop = Zig::toIdentifier(*key, arg1); @@ -348,10 +466,85 @@ static JSC::JSValue doLink(JSC__JSGlobalObject *globalObject, JSC::JSValue modul return JSC::linkAndEvaluateModule(globalObject, moduleKey, JSC::JSValue()); } +JSC__JSValue JSC__JSValue__createRangeError(const ZigString *message, const ZigString *arg1, + JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + ZigString code = *arg1; + JSC::JSObject *rangeError = Zig::getErrorInstance(message, globalObject).asCell()->getObject(); + static const char *range_error_name = "RangeError"; + + rangeError->putDirect( + vm, vm.propertyNames->name, + JSC::JSValue(JSC::jsOwnedString( + vm, WTF::String(WTF::StringImpl::createWithoutCopying(range_error_name, 10)))), + 0); + + if (code.len > 0) { + auto clientData = Bun::clientData(vm); + JSC::JSValue codeValue = Zig::toJSStringValue(code, globalObject); + rangeError->putDirect(vm, clientData->builtinNames().codePublicName(), codeValue, + JSC::PropertyAttribute::ReadOnly | 0); + } + + return JSC::JSValue::encode(rangeError); +} +JSC__JSValue JSC__JSValue__createTypeError(const ZigString *message, const ZigString *arg1, + JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + ZigString code = *arg1; + JSC::JSObject *typeError = Zig::getErrorInstance(message, globalObject).asCell()->getObject(); + static const char *range_error_name = "TypeError"; + + typeError->putDirect( + vm, vm.propertyNames->name, + JSC::JSValue(JSC::jsOwnedString( + vm, WTF::String(WTF::StringImpl::createWithoutCopying(range_error_name, 10)))), + 0); + + if (code.len > 0) { + auto clientData = Bun::clientData(vm); + JSC::JSValue codeValue = Zig::toJSStringValue(code, globalObject); + typeError->putDirect(vm, clientData->builtinNames().codePublicName(), codeValue, 0); + } + + return JSC::JSValue::encode(typeError); +} + +JSC__JSValue JSC__JSValue__fromEntries(JSC__JSGlobalObject *globalObject, ZigString *keys, + ZigString *values, size_t initialCapacity, bool clone) { + JSC::VM &vm = globalObject->vm(); + auto scope = DECLARE_THROW_SCOPE(vm); + if (initialCapacity == 0) { + return JSC::JSValue::encode(JSC::constructEmptyObject(globalObject)); + } + + JSC::JSObject *object = nullptr; + { + JSC::ObjectInitializationScope initializationScope(vm); + object = + JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), initialCapacity); + + if (!clone) { + for (size_t i = 0; i < initialCapacity; ++i) { + object->putDirect( + vm, JSC::PropertyName(JSC::Identifier::fromString(vm, Zig::toString(keys[i]))), + Zig::toJSStringValueGC(values[i], globalObject), 0); + } + } else { + for (size_t i = 0; i < initialCapacity; ++i) { + object->putDirect(vm, JSC::PropertyName(Zig::toIdentifier(keys[i], globalObject)), + Zig::toJSStringValueGC(values[i], globalObject), 0); + } + } + } + + return JSC::JSValue::encode(object); +} JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, ZigString *arg1, - size_t arg2) { + size_t arg2, bool clone) { JSC::VM &vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); + if (arg2 == 0) { return JSC::JSValue::encode(JSC::JSArray::create(vm, 0)); } JSC::JSArray *array = nullptr; { @@ -361,8 +554,14 @@ JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, globalObject->arrayStructureForIndexingTypeDuringAllocation(JSC::ArrayWithContiguous), arg2))) { - for (size_t i = 0; i < arg2; ++i) { - array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toStringCopy(arg1[i]))); + if (!clone) { + for (size_t i = 0; i < arg2; ++i) { + array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toString(arg1[i]))); + } + } else { + for (size_t i = 0; i < arg2; ++i) { + array->putDirectIndex(globalObject, i, JSC::jsString(vm, Zig::toStringCopy(arg1[i]))); + } } } } @@ -376,7 +575,7 @@ JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject *globalObject, JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *globalObject, void **errors, uint16_t errors_count, - const ZigString * arg3) { + const ZigString *arg3) { JSC::VM &vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); @@ -411,34 +610,34 @@ JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *glob // static JSC::JSNativeStdFunction* rejecterFunction; // static bool resolverFunctionInitialized = false; -JSC__JSValue ZigString__toValue(const ZigString * arg0, JSC__JSGlobalObject *arg1) { +JSC__JSValue ZigString__toValue(const ZigString *arg0, JSC__JSGlobalObject *arg1) { return JSC::JSValue::encode(JSC::JSValue(JSC::jsOwnedString(arg1->vm(), Zig::toString(*arg0)))); } -JSC__JSValue ZigString__toValueGC(const ZigString * arg0, JSC__JSGlobalObject *arg1) { +JSC__JSValue ZigString__to16BitValue(const ZigString *arg0, JSC__JSGlobalObject *arg1) { + auto str = WTF::String::fromUTF8(arg0->ptr, arg0->len); + return JSC::JSValue::encode(JSC::JSValue(JSC::jsString(arg1->vm(), str))); +} + +JSC__JSValue ZigString__toValueGC(const ZigString *arg0, JSC__JSGlobalObject *arg1) { return JSC::JSValue::encode( - JSC::JSValue(JSC::jsMakeNontrivialString(arg1->vm(), Zig::toString(*arg0)))); + JSC::JSValue(JSC::jsMakeNontrivialString(arg1->vm(), Zig::toStringCopy(*arg0)))); } void JSC__JSValue__toZigString(JSC__JSValue JSValue0, ZigString *arg1, JSC__JSGlobalObject *arg2) { JSC::JSValue value = JSC::JSValue::decode(JSValue0); auto str = value.toWTFString(arg2); - arg1->ptr = str.characters8(); + if (str.is8Bit()) { + arg1->ptr = str.characters8(); + } else { + arg1->ptr = Zig::taggedUTF16Ptr(str.characters16()); + } + arg1->len = str.length(); } -JSC__JSValue ZigString__toErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) { - JSC::VM &vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - JSC::JSValue message = Zig::toJSString(*str, globalObject); - JSC::JSValue options = JSC::jsUndefined(); - JSC::Structure *errorStructure = globalObject->errorStructure(); - JSC::JSObject *result = - JSC::ErrorInstance::create(globalObject, errorStructure, message, options); - RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue())); - scope.release(); - - return JSC::JSValue::encode(JSC::JSValue(result)); +JSC__JSValue ZigString__toErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) { + return JSC::JSValue::encode(Zig::getErrorInstance(str, globalObject)); } static JSC::EncodedJSValue resolverFunctionCallback(JSC::JSGlobalObject *globalObject, @@ -447,7 +646,8 @@ static JSC::EncodedJSValue resolverFunctionCallback(JSC::JSGlobalObject *globalO } JSC__JSInternalPromise * -JSC__JSModuleLoader__loadAndEvaluateModule(JSC__JSGlobalObject *globalObject, const ZigString * arg1) { +JSC__JSModuleLoader__loadAndEvaluateModule(JSC__JSGlobalObject *globalObject, + const ZigString *arg1) { globalObject->vm().drainMicrotasks(); auto name = Zig::toString(*arg1); name.impl()->ref(); @@ -768,6 +968,22 @@ bWTF__String JSC__JSFunction__calculatedDisplayName(JSC__JSFunction *arg0, JSC__ }; #pragma mark - JSC::JSGlobalObject +JSC__JSValue JSC__JSGlobalObject__generateHeapSnapshot(JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + + JSC::JSLockHolder lock(vm); + // JSC::DeferTermination deferScope(vm); + auto scope = DECLARE_THROW_SCOPE(vm); + + JSC::HeapSnapshotBuilder snapshotBuilder(vm.ensureHeapProfiler()); + snapshotBuilder.buildSnapshot(); + + WTF::String jsonString = snapshotBuilder.json(); + JSC::EncodedJSValue result = JSC::JSValue::encode(JSONParse(globalObject, jsonString)); + scope.releaseAssertNoException(); + return result; +} + JSC__ArrayIteratorPrototype * JSC__JSGlobalObject__arrayIteratorPrototype(JSC__JSGlobalObject *arg0) { return arg0->arrayIteratorPrototype(); @@ -1006,6 +1222,45 @@ JSC__JSValue JSC__JSValue__jsNumberFromUint64(uint64_t arg0) { return JSC::JSValue::encode(JSC::jsNumber(arg0)); }; +JSC__JSValue JSC__JSValue__createObject2(JSC__JSGlobalObject *globalObject, const ZigString *arg1, + const ZigString *arg2, JSC__JSValue JSValue3, + JSC__JSValue JSValue4) { + JSC::JSObject *object = JSC::constructEmptyObject(globalObject); + auto key1 = Zig::toIdentifier(*arg1, globalObject); + JSC::PropertyDescriptor descriptor1; + JSC::PropertyDescriptor descriptor2; + + descriptor1.setEnumerable(1); + descriptor1.setConfigurable(1); + descriptor1.setWritable(1); + descriptor1.setValue(JSC::JSValue::decode(JSValue3)); + + auto key2 = Zig::toIdentifier(*arg2, globalObject); + + descriptor2.setEnumerable(1); + descriptor2.setConfigurable(1); + descriptor2.setWritable(1); + descriptor2.setValue(JSC::JSValue::decode(JSValue4)); + + object->methodTable(globalObject->vm()) + ->defineOwnProperty(object, globalObject, key2, descriptor2, true); + object->methodTable(globalObject->vm()) + ->defineOwnProperty(object, globalObject, key1, descriptor1, true); + + return JSC::JSValue::encode(object); +} + +JSC__JSValue JSC__JSValue__getIfPropertyExistsImpl(JSC__JSValue JSValue0, + JSC__JSGlobalObject *globalObject, + const unsigned char *arg1, uint32_t arg2) { + + JSC::VM &vm = globalObject->vm(); + JSC::JSObject *object = JSC::JSValue::decode(JSValue0).asCell()->getObject(); + auto propertyName = JSC::PropertyName( + JSC::Identifier::fromString(vm, reinterpret_cast<const LChar *>(arg1), (int)arg2)); + return JSC::JSValue::encode(object->getIfPropertyExists(globalObject, propertyName)); +} + bool JSC__JSValue__toBoolean(JSC__JSValue JSValue0) { return JSC::JSValue::decode(JSValue0).asBoolean(); } @@ -1274,9 +1529,10 @@ static void fromErrorInstance(ZigException *except, JSC::JSGlobalObject *global, if (err->isStackOverflowError()) { except->code = 253; } if (err->isOutOfMemoryError()) { except->code = 8; } - if (obj->hasProperty(global, global->vm().propertyNames->message)) { - except->message = Zig::toZigString( - obj->getDirect(global->vm(), global->vm().propertyNames->message).toWTFString(global)); + if (JSC::JSValue message = + obj->getIfPropertyExists(global, global->vm().propertyNames->message)) { + + except->message = Zig::toZigString(message, global); } else { except->message = Zig::toZigString(err->sanitizedMessageString(global)); @@ -1284,19 +1540,40 @@ static void fromErrorInstance(ZigException *except, JSC::JSGlobalObject *global, except->name = Zig::toZigString(err->sanitizedNameString(global)); except->runtime_type = err->runtimeTypeForCause(); + auto clientData = Bun::clientData(global->vm()); + + if (JSC::JSValue syscall = + obj->getIfPropertyExists(global, clientData->builtinNames().syscallPublicName())) { + except->syscall = Zig::toZigString(syscall, global); + } + + if (JSC::JSValue code = + obj->getIfPropertyExists(global, clientData->builtinNames().codePublicName())) { + except->code_ = Zig::toZigString(code, global); + } + + if (JSC::JSValue path = + obj->getIfPropertyExists(global, clientData->builtinNames().pathPublicName())) { + except->path = Zig::toZigString(path, global); + } + + if (JSC::JSValue errno_ = + obj->getIfPropertyExists(global, clientData->builtinNames().errnoPublicName())) { + except->errno_ = errno_.toInt32(global); + } + if (getFromSourceURL) { - if (obj->hasProperty(global, global->vm().propertyNames->sourceURL)) { - except->stack.frames_ptr[0].source_url = Zig::toZigString( - obj->getDirect(global->vm(), global->vm().propertyNames->sourceURL).toWTFString(global)); + if (JSC::JSValue sourceURL = + obj->getIfPropertyExists(global, global->vm().propertyNames->sourceURL)) { + except->stack.frames_ptr[0].source_url = Zig::toZigString(sourceURL, global); - if (obj->hasProperty(global, global->vm().propertyNames->line)) { - except->stack.frames_ptr[0].position.line = - obj->getDirect(global->vm(), global->vm().propertyNames->line).toInt32(global); + if (JSC::JSValue line = obj->getIfPropertyExists(global, global->vm().propertyNames->line)) { + except->stack.frames_ptr[0].position.line = line.toInt32(global); } - if (obj->hasProperty(global, global->vm().propertyNames->column)) { - except->stack.frames_ptr[0].position.column_start = - obj->getDirect(global->vm(), global->vm().propertyNames->column).toInt32(global); + if (JSC::JSValue column = + obj->getIfPropertyExists(global, global->vm().propertyNames->column)) { + except->stack.frames_ptr[0].position.column_start = column.toInt32(global); } except->stack.frames_len = 1; } @@ -1469,8 +1746,36 @@ const WTF__StringImpl *JSC__PropertyName__uid(JSC__PropertyName *arg0) { return #pragma mark - JSC::VM +JSC__JSValue JSC__VM__runGC(JSC__VM *vm, bool sync) { + JSC::JSLockHolder lock(vm); + + if (sync) { + vm->heap.collectNow(JSC::Sync, JSC::CollectionScope::Full); + } else { + vm->heap.collectSync(JSC::CollectionScope::Full); + } + + return JSC::JSValue::encode(JSC::jsNumber(vm->heap.sizeAfterLastFullCollection())); +} + bool JSC__VM__isJITEnabled() { return JSC::Options::useJIT(); } +void JSC__VM__clearExecutionTimeLimit(JSC__VM *vm) { + JSC::JSLockHolder locker(vm); + if (vm->watchdog()) vm->watchdog()->setTimeLimit(JSC::Watchdog::noTimeLimit); +} +void JSC__VM__setExecutionTimeLimit(JSC__VM *vm, double limit) { + JSC::JSLockHolder locker(vm); + JSC::Watchdog &watchdog = vm->ensureWatchdog(); + watchdog.setTimeLimit(WTF::Seconds{limit}); +} + +bool JSC__JSValue__isTerminationException(JSC__JSValue JSValue0, JSC__VM *arg1) { + JSC::Exception *exception = + JSC::jsDynamicCast<JSC::Exception *>(*arg1, JSC::JSValue::decode(JSValue0)); + return exception != NULL && arg1->isTerminationException(exception); +} + void JSC__VM__shrinkFootprint(JSC__VM *arg0) { arg0->shrinkFootprintWhenIdle(); }; void JSC__VM__whenIdle(JSC__VM *arg0, void (*ArgFn1)()) { arg0->whenIdle(ArgFn1); }; @@ -1485,6 +1790,11 @@ JSC__VM *JSC__VM__create(unsigned char HeapType0) { return vm; } +void JSC__VM__holdAPILock(JSC__VM *arg0, void *ctx, void (*callback)(void *arg0)) { + JSC::JSLockHolder locker(arg0); + callback(ctx); +} + void JSC__VM__deleteAllCode(JSC__VM *arg1, JSC__JSGlobalObject *globalObject) { JSC::JSLockHolder locker(globalObject->vm()); diff --git a/src/javascript/jsc/bindings/bindings.zig b/src/javascript/jsc/bindings/bindings.zig index 971782e0b..a28717400 100644 --- a/src/javascript/jsc/bindings/bindings.zig +++ b/src/javascript/jsc/bindings/bindings.zig @@ -7,7 +7,7 @@ const hasRef = std.meta.trait.hasField("ref"); const C_API = @import("../../../jsc.zig").C; const StringPointer = @import("../../../api/schema.zig").Api.StringPointer; const Exports = @import("./exports.zig"); - +const strings = _global.strings; const ErrorableZigString = Exports.ErrorableZigString; const ErrorableResolvedSource = Exports.ErrorableResolvedSource; const ZigException = Exports.ZigException; @@ -71,15 +71,6 @@ pub const JSObject = extern struct { }); } - pub fn putDirect(this: *JSObject, globalThis: *JSGlobalObject, prop: *const ZigString, value: JSValue) void { - return cppFn("putDirect", .{ - this, - globalThis, - prop, - value, - }); - } - pub const Extern = [_][]const u8{ "putRecord", "create", @@ -87,18 +78,28 @@ pub const JSObject = extern struct { "getIndex", "putAtIndex", "getDirect", - "putDirect", }; }; pub const ZigString = extern struct { + // TODO: align this to align(2) + // That would improve perf a bit ptr: [*]const u8, len: usize, + pub const shim = Shimmer("", "ZigString", @This()); pub const name = "ZigString"; pub const namespace = ""; + pub inline fn is16Bit(this: *const ZigString) bool { + return (@ptrToInt(this.ptr) & (1 << 63)) != 0; + } + + pub inline fn utf16Slice(this: *const ZigString) []align(1) const u16 { + return @ptrCast([*]align(1) const u16, this.ptr)[0..this.len]; + } + pub fn fromStringPointer(ptr: StringPointer, buf: string, to: *ZigString) void { to.* = ZigString{ .len = ptr.length, @@ -110,6 +111,32 @@ pub const ZigString = extern struct { return ZigString{ .ptr = slice_.ptr, .len = slice_.len }; } + pub fn detectEncoding(this: *ZigString) void { + for (this.slice()) |char| { + if (char > 127) { + this.ptr = @intToPtr([*]const u8, @ptrToInt(this.ptr) | (1 << 63)); + return; + } + } + } + + pub inline fn isGloballyAllocated(this: *ZigString) bool { + return (@ptrToInt(this.ptr) & (1 << 62)) != 0; + } + + pub inline fn mark(this: *ZigString) void { + this.ptr = @intToPtr([*]const u8, @ptrToInt(this.ptr) | (1 << 62)); + } + + pub fn format(self: ZigString, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + if (self.is16Bit()) { + try strings.formatUTF16(self.utf16Slice(), writer); + return; + } + + try writer.writeAll(self.slice()); + } + pub inline fn toRef(slice_: []const u8, global: *JSGlobalObject) C_API.JSValueRef { return init(slice_).toValue(global).asRef(); } @@ -117,7 +144,11 @@ pub const ZigString = extern struct { pub const Empty = ZigString{ .ptr = "", .len = 0 }; pub fn slice(this: *const ZigString) []const u8 { - return this.ptr[0..std.math.min(this.len, 4096)]; + return this.ptr[0..@minimum(this.len, std.math.maxInt(u32))]; + } + + pub fn sliceZBuf(this: ZigString, buf: *[std.fs.MAX_PATH_BYTES]u8) ![:0]const u8 { + return try std.fmt.bufPrintZ(buf, "{}", .{this}); } pub inline fn full(this: *const ZigString) []const u8 { @@ -125,13 +156,25 @@ pub const ZigString = extern struct { } pub fn trimmedSlice(this: *const ZigString) []const u8 { - return std.mem.trim(u8, this.ptr[0..std.math.min(this.len, 4096)], " \r\n"); + return std.mem.trim(u8, this.ptr[0..@minimum(this.len, std.math.maxInt(u32))], " \r\n"); + } + + pub fn toValueAuto(this: *const ZigString, global: *JSGlobalObject) JSValue { + if (!this.is16Bit()) { + return this.toValue(global); + } else { + return this.to16BitValue(global); + } } pub fn toValue(this: *const ZigString, global: *JSGlobalObject) JSValue { return shim.cppFn("toValue", .{ this, global }); } + pub fn to16BitValue(this: *const ZigString, global: *JSGlobalObject) JSValue { + return shim.cppFn("to16BitValue", .{ this, global }); + } + pub fn toValueGC(this: *const ZigString, global: *JSGlobalObject) JSValue { return shim.cppFn("toValueGC", .{ this, global }); } @@ -141,7 +184,10 @@ pub const ZigString = extern struct { return undefined; } - return C_API.JSStringCreateStatic(this.ptr, this.len); + return if (this.is16Bit()) + C_API.JSStringCreateWithCharactersNoCopy(@ptrCast([*]const u16, @alignCast(@alignOf([*]const u16), this.ptr)), this.len) + else + C_API.JSStringCreateStatic(this.ptr, this.len); } pub fn toErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue { @@ -150,11 +196,34 @@ pub const ZigString = extern struct { pub const Extern = [_][]const u8{ "toValue", + "to16BitValue", "toValueGC", "toErrorInstance", }; }; +pub const SystemError = extern struct { + errno: c_int = 0, + /// label for errno + code: ZigString = ZigString.init(""), + message: ZigString = ZigString.init(""), + path: ZigString = ZigString.init(""), + syscall: ZigString = ZigString.init(""), + + pub const shim = Shimmer("", "SystemError", @This()); + + pub const name = "SystemError"; + pub const namespace = ""; + + pub fn toErrorInstance(this: *const SystemError, global: *JSGlobalObject) JSValue { + return shim.cppFn("toErrorInstance", .{ this, global }); + } + + pub const Extern = [_][]const u8{ + "toErrorInstance", + }; +}; + pub const ReturnableException = *?*Exception; pub const JSCell = extern struct { @@ -935,6 +1004,10 @@ pub const JSGlobalObject = extern struct { return cppFn("createAggregateError", .{ globalObject, errors, errors_len, message }); } + pub fn generateHeapSnapshot(this: *JSGlobalObject) JSValue { + return cppFn("generateHeapSnapshot", .{this}); + } + pub fn vm(this: *JSGlobalObject) *VM { return cppFn("vm", .{this}); } @@ -966,6 +1039,7 @@ pub const JSGlobalObject = extern struct { "asyncGeneratorPrototype", "asyncGeneratorFunctionPrototype", "vm", + "generateHeapSnapshot", // "createError", // "throwError", }; @@ -1230,11 +1304,181 @@ pub const JSValue = enum(i64) { pub const include = "<JavaScriptCore/JSValue.h>"; pub const name = "JSC::JSValue"; pub const namespace = "JSC"; + pub const JSType = enum(u8) { + // The Cell value must come before any JS that is a JSCell. + Cell, + String, + HeapBigInt, + Symbol, + + GetterSetter, + CustomGetterSetter, + APIValueWrapper, + + NativeExecutable, + + ProgramExecutable, + ModuleProgramExecutable, + EvalExecutable, + FunctionExecutable, + + UnlinkedFunctionExecutable, + + UnlinkedProgramCodeBlock, + UnlinkedModuleProgramCodeBlock, + UnlinkedEvalCodeBlock, + UnlinkedFunctionCodeBlock, + + CodeBlock, + + JSImmutableButterfly, + JSSourceCode, + JSScriptFetcher, + JSScriptFetchParameters, + + // The Object value must come before any JS that is a subclass of JSObject. + Object, + FinalObject, + JSCallee, + JSFunction, + InternalFunction, + NullSetterFunction, + BooleanObject, + NumberObject, + ErrorInstance, + PureForwardingProxy, + DirectArguments, + ScopedArguments, + ClonedArguments, + + // Start JSArray types. + Array, + DerivedArray, + // End JSArray types. + + ArrayBuffer, + + // Start JSArrayBufferView types. Keep in sync with the order of FOR_EACH_TYPED_ARRAY_TYPE_EXCLUDING_DATA_VIEW. + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array, + DataView, + // End JSArrayBufferView types. + + // JSScope <- JSWithScope + // <- StrictEvalActivation + // <- JSSymbolTableObject <- JSLexicalEnvironment <- JSModuleEnvironment + // <- JSSegmentedVariableObject <- JSGlobalLexicalEnvironment + // <- JSGlobalObject + // Start JSScope types. + // Start environment record types. + GlobalObject, + GlobalLexicalEnvironment, + LexicalEnvironment, + ModuleEnvironment, + StrictEvalActivation, + // End environment record types. + WithScope, + // End JSScope types. + + ModuleNamespaceObject, + RegExpObject, + JSDate, + ProxyObject, + JSGenerator, + JSAsyncGenerator, + JSArrayIterator, + JSMapIterator, + JSSetIterator, + JSStringIterator, + JSPromise, + JSMap, + JSSet, + JSWeakMap, + JSWeakSet, + WebAssemblyModule, + // Start StringObject types. + StringObject, + DerivedStringObject, + // End StringObject types. + + MaxJS = 0b11111111, + _, + + pub fn isHidden(this: JSType) bool { + return switch (this) { + .APIValueWrapper, + .NativeExecutable, + .ProgramExecutable, + .ModuleProgramExecutable, + .EvalExecutable, + .FunctionExecutable, + .UnlinkedFunctionExecutable, + .UnlinkedProgramCodeBlock, + .UnlinkedModuleProgramCodeBlock, + .UnlinkedEvalCodeBlock, + .UnlinkedFunctionCodeBlock, + .CodeBlock, + .JSImmutableButterfly, + .JSSourceCode, + .JSScriptFetcher, + .InternalFunction, + .JSScriptFetchParameters, + => true, + else => false, + }; + } + + pub const LastMaybeFalsyCellPrimitive = JSType.HeapBigInt; + pub const LastJSCObject = JSType.DerivedStringObject; // This is the last "JSC" Object type. After this, we have embedder's (e.g., WebCore) extended object types. + + pub inline fn isStringLike(this: JSType) bool { + return switch (this) { + .String, .StringObject, .DerivedStringObject => true, + else => false, + }; + } + }; pub inline fn cast(ptr: anytype) JSValue { return @intToEnum(JSValue, @intCast(i64, @ptrToInt(ptr))); } + pub fn to(this: JSValue, comptime T: type) T { + return switch (comptime T) { + u32 => toU32(this), + u16 => toU16(this), + c_uint => @intCast(c_uint, toU32(this)), + c_int => @intCast(c_int, toInt32(this)), + + // TODO: BigUint64? + u64 => @as(u64, toU32(this)), + + u8 => @truncate(u8, toU32(this)), + i16 => @truncate(i16, toInt32(this)), + i8 => @truncate(i8, toInt32(this)), + i32 => @truncate(i32, toInt32(this)), + + // TODO: BigInt64 + i64 => @as(i64, toInt32(this)), + else => @compileError("Not implemented yet"), + }; + } + + pub fn jsType( + this: JSValue, + ) JSType { + return cppFn("jsType", .{this}); + } + pub fn createEmptyObject(global: *JSGlobalObject, len: usize) JSValue { return cppFn("createEmptyObject", .{ global, len }); } @@ -1243,21 +1487,47 @@ pub const JSValue = enum(i64) { return cppFn("putRecord", .{ value, global, key, values, values_len }); } + /// Create an object with exactly two properties + pub fn createObject2(global: *JSGlobalObject, key1: *const ZigString, key2: *const ZigString, value1: JSValue, value2: JSValue) JSValue { + return cppFn("createObject2", .{ global, key1, key2, value1, value2 }); + } + pub fn getErrorsProperty(this: JSValue, globalObject: *JSGlobalObject) JSValue { return cppFn("getErrorsProperty", .{ this, globalObject }); } - pub fn jsNumber(number: anytype) JSValue { - return switch (@TypeOf(number)) { + + pub fn jsNumberWithType(comptime Number: type, number: Type) JSValue { + return switch (Number) { f64 => @call(.{ .modifier = .always_inline }, jsNumberFromDouble, .{number}), u8 => @call(.{ .modifier = .always_inline }, jsNumberFromChar, .{number}), u16 => @call(.{ .modifier = .always_inline }, jsNumberFromU16, .{number}), - i32 => @call(.{ .modifier = .always_inline }, jsNumberFromInt32, .{number}), - i64 => @call(.{ .modifier = .always_inline }, jsNumberFromInt64, .{number}), - u64 => @call(.{ .modifier = .always_inline }, jsNumberFromUint64, .{number}), - else => @compileError("Type transformation missing for number of type: " ++ @typeName(@TypeOf(number))), + i32 => @call(.{ .modifier = .always_inline }, jsNumberFromInt32, .{@truncate(i32, number)}), + c_int, i64 => if (number > std.math.maxInt(i32)) + jsNumberFromInt64(@truncate(i64, number)) + else + jsNumberFromInt32(@intCast(i32, number)), + + c_uint, u32 => if (number < std.math.maxInt(i32)) + jsNumberFromInt32(@intCast(i32, number)) + else + jsNumberFromUint64(@as(u64, number)), + + else => @compileError("Type transformation missing for number of type: " ++ @typeName(Number)), }; } + pub fn jsNumber(number: anytype) JSValue { + return jsNumberWithType(@TypeOf(number), number); + } + + pub fn getReadableStreamState(value: JSValue, vm: *VM) ?*Exports.NodeReadableStream { + return cppFn("getReadableStreamState", .{ value, vm }); + } + + pub fn getWritableStreamState(value: JSValue, vm: *VM) ?*Exports.NodeWritableStream { + return cppFn("getWritableStreamState", .{ value, vm }); + } + pub fn jsNull() JSValue { return cppFn("jsNull", .{}); } @@ -1274,11 +1544,22 @@ pub const JSValue = enum(i64) { return cppFn("jsDoubleNumber", .{i}); } - pub fn createStringArray(globalThis: *JSGlobalObject, str: [*c]ZigString, strings_count: usize) JSValue { + pub fn createStringArray(globalThis: *JSGlobalObject, str: [*c]ZigString, strings_count: usize, clone: bool) JSValue { return cppFn("createStringArray", .{ globalThis, str, strings_count, + clone, + }); + } + + pub fn fromEntries(globalThis: *JSGlobalObject, keys: [*c]ZigString, values: [*c]ZigString, strings_count: usize, clone: bool) JSValue { + return cppFn("fromEntries", .{ + globalThis, + keys, + values, + strings_count, + clone, }); } @@ -1392,6 +1673,10 @@ pub const JSValue = enum(i64) { return cppFn("isException", .{ this, vm }); } + pub fn isTerminationException(this: JSValue, vm: *VM) bool { + return cppFn("isTerminationException", .{ this, vm }); + } + pub fn toZigException(this: JSValue, global: *JSGlobalObject, exception: *ZigException) void { return cppFn("toZigException", .{ this, global, exception }); } @@ -1415,6 +1700,10 @@ pub const JSValue = enum(i64) { return cppFn("toWTFString", .{ this, globalThis }); } + pub fn jsonStringify(this: JSValue, globalThis: *JSGlobalObject, indent: u32, out: *ZigString) void { + return cppFn("jsonStringify", .{ this, globalThis, indent, out }); + } + // On exception, this returns null, to make exception checks faster. pub fn toStringOrNull(this: JSValue, globalThis: *JSGlobalObject) *JSString { return cppFn("toStringOrNull", .{ this, globalThis }); @@ -1441,6 +1730,31 @@ pub const JSValue = enum(i64) { return cppFn("eqlCell", .{ this, other }); } + // intended to be more lightweight than ZigString + pub fn getIfPropertyExistsImpl(this: JSValue, global: *JSGlobalObject, ptr: [*]const u8, len: u32) JSValue { + return cppFn("getIfPropertyExistsImpl", .{ this, global, ptr, len }); + } + + pub fn getIfPropertyExists(this: JSValue, global: *JSGlobalObject, property: []const u8) ?JSValue { + const value = getIfPropertyExistsImpl(this, global, property.ptr, @intCast(u32, property.len)); + return if (@enumToInt(value) != 0) value else return null; + } + + pub fn createTypeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue { + return cppFn("createTypeError", .{ message, code, global }); + } + + pub fn createRangeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue { + return cppFn("createRangeError", .{ message, code, global }); + } + + /// Object.is() + /// This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽. + /// https://tc39.es/ecma262/#sec-samevalue + pub fn isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool { + return cppFn("isSameValue", .{ this, other, global }); + } + pub fn asString(this: JSValue) *JSString { return cppFn("asString", .{ this, @@ -1476,7 +1790,7 @@ pub const JSValue = enum(i64) { } pub inline fn toU32(this: JSValue) u32 { - return @intCast(u32, this.toInt32()); + return @intCast(u32, @maximum(this.toInt32(), 0)); } pub fn getLengthOfArray(this: JSValue, globalThis: *JSGlobalObject) u32 { @@ -1514,10 +1828,10 @@ pub const JSValue = enum(i64) { } pub inline fn asVoid(this: JSValue) *anyopaque { - return @intToPtr(*anyopaque, @intCast(usize, @enumToInt(this))); + return @intToPtr(*anyopaque, @bitCast(u64, @enumToInt(this))); } - pub const Extern = [_][]const u8{ "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" }; + pub const Extern = [_][]const u8{ "getReadableStreamState", "getWritableStreamState", "fromEntries", "createTypeError", "createRangeError", "createObject2", "getIfPropertyExistsImpl", "jsType", "jsonStringify", "kind_", "isTerminationException", "isSameValue", "getLengthOfArray", "toZigString", "createStringArray", "createEmptyObject", "putRecord", "asPromise", "isClass", "getNameProperty", "getClassName", "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" }; }; extern "c" fn Microtask__run(*Microtask, *JSGlobalObject) void; @@ -1653,6 +1967,10 @@ pub const VM = extern struct { return cppFn("isJITEnabled", .{}); } + pub fn holdAPILock(this: *VM, ctx: ?*anyopaque, callback: fn (ctx: ?*anyopaque) callconv(.C) void) void { + cppFn("holdAPILock", .{ this, ctx, callback }); + } + pub fn deleteAllCode( vm: *VM, global_object: *JSGlobalObject, @@ -1675,10 +1993,25 @@ pub const VM = extern struct { }); } + pub fn runGC(vm: *VM, sync: bool) JSValue { + return cppFn("runGC", .{ + vm, + sync, + }); + } + pub fn setExecutionForbidden(vm: *VM, forbidden: bool) void { cppFn("setExecutionForbidden", .{ vm, forbidden }); } + pub fn setExecutionTimeLimit(vm: *VM, timeout: f64) void { + return cppFn("setExecutionTimeLimit", .{ vm, timeout }); + } + + pub fn clearExecutionTimeLimit(vm: *VM) void { + return cppFn("clearExecutionTimeLimit", .{vm}); + } + pub fn executionForbidden(vm: *VM) bool { return cppFn("executionForbidden", .{ vm, @@ -1717,7 +2050,7 @@ pub const VM = extern struct { }); } - pub const Extern = [_][]const u8{ "isJITEnabled", "deleteAllCode", "apiLock", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint" }; + pub const Extern = [_][]const u8{ "holdAPILock", "runGC", "generateHeapSnapshot", "isJITEnabled", "deleteAllCode", "apiLock", "create", "deinit", "setExecutionForbidden", "executionForbidden", "isEntered", "throwError", "drainMicrotasks", "whenIdle", "shrinkFootprint", "setExecutionTimeLimit", "clearExecutionTimeLimit" }; }; pub const ThrowScope = extern struct { diff --git a/src/javascript/jsc/bindings/exports.zig b/src/javascript/jsc/bindings/exports.zig index ee5878319..190b505b6 100644 --- a/src/javascript/jsc/bindings/exports.zig +++ b/src/javascript/jsc/bindings/exports.zig @@ -1,4 +1,4 @@ -const JSC = @import("./bindings.zig"); +const JSC = @import("../../../jsc.zig"); const Fs = @import("../../../fs.zig"); const CAPI = @import("../../../jsc.zig").C; const JS = @import("../javascript.zig"); @@ -26,6 +26,7 @@ const JSModuleLoader = JSC.JSModuleLoader; const JSModuleRecord = JSC.JSModuleRecord; const Microtask = JSC.Microtask; const JSPrivateDataPtr = @import("../base.zig").JSPrivateDataPtr; +const Backtrace = @import("../../../deps/backtrace.zig"); pub const ZigGlobalObject = extern struct { pub const shim = Shimmer("Zig", "GlobalObject", @This()); @@ -37,7 +38,9 @@ pub const ZigGlobalObject = extern struct { pub const Interface: type = NewGlobalObject(JS.VirtualMachine); pub fn create(class_ref: [*]CAPI.JSClassRef, count: i32, console: *anyopaque) *JSGlobalObject { - return shim.cppFn("create", .{ class_ref, count, console }); + var global = shim.cppFn("create", .{ class_ref, count, console }); + Backtrace.reloadHandlers(); + return global; } pub fn getModuleRegistryMap(global: *JSGlobalObject) *anyopaque { @@ -169,6 +172,11 @@ pub const ZigErrorType = extern struct { } }; +/// do not use this reference directly, use JSC.Node.Readable +pub const NodeReadableStream = JSC.Node.Readable.State; +/// do not use this reference directly, use JSC.Node.Writable +pub const NodeWritableStream = JSC.Node.Writable.State; + pub fn Errorable(comptime Type: type) type { return extern struct { result: Result, @@ -301,6 +309,54 @@ pub const ZigStackFrameCode = enum(u8) { } }; +pub const Process = extern struct { + pub const shim = Shimmer("Bun", "Process", @This()); + pub const name = "Process"; + pub const namespace = shim.namespace; + const _bun: string = "bun"; + + pub fn getTitle(_: *JSGlobalObject, title: *ZigString) callconv(.C) void { + title.* = ZigString.init(_bun); + } + + // TODO: https://github.com/nodejs/node/blob/master/deps/uv/src/unix/darwin-proctitle.c + pub fn setTitle(globalObject: *JSGlobalObject, _: *ZigString) callconv(.C) JSValue { + return ZigString.init(_bun).toValue(globalObject); + } + + pub const getArgv = JSC.Node.Process.getArgv; + pub const getCwd = JSC.Node.Process.getCwd; + pub const setCwd = JSC.Node.Process.setCwd; + + pub const Export = shim.exportFunctions(.{ + .@"getTitle" = getTitle, + .@"setTitle" = setTitle, + .@"getArgv" = getArgv, + .@"getCwd" = getCwd, + .@"setCwd" = setCwd, + }); + + comptime { + if (!is_bindgen) { + @export(getTitle, .{ + .name = Export[0].symbol_name, + }); + @export(setTitle, .{ + .name = Export[1].symbol_name, + }); + @export(getArgv, .{ + .name = Export[2].symbol_name, + }); + @export(getCwd, .{ + .name = Export[3].symbol_name, + }); + @export(setCwd, .{ + .name = Export[4].symbol_name, + }); + } + } +}; + pub const ZigStackTrace = extern struct { source_lines_ptr: [*c]ZigString, source_lines_numbers: [*c]i32, @@ -428,15 +484,18 @@ pub const ZigStackFrame = extern struct { source_url: ZigString, position: ZigStackFramePosition, enable_color: bool, - origin: *const ZigURL, + origin: ?*const ZigURL, + root_path: string = "", pub fn format(this: SourceURLFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { - try writer.writeAll(this.origin.displayProtocol()); - try writer.writeAll("://"); - try writer.writeAll(this.origin.displayHostname()); - try writer.writeAll(":"); - try writer.writeAll(this.origin.port); - try writer.writeAll("/blob:"); + if (this.origin) |origin| { + try writer.writeAll(origin.displayProtocol()); + try writer.writeAll("://"); + try writer.writeAll(origin.displayHostname()); + try writer.writeAll(":"); + try writer.writeAll(origin.port); + try writer.writeAll("/blob:"); + } var source_slice = this.source_url.slice(); if (strings.startsWith(source_slice, this.root_path)) { @@ -505,7 +564,7 @@ pub const ZigStackFrame = extern struct { return NameFormatter{ .function_name = this.function_name, .code_type = this.code_type, .enable_color = enable_color }; } - pub fn sourceURLFormatter(this: *const ZigStackFrame, root_path: string, origin: *const ZigURL, comptime enable_color: bool) SourceURLFormatter { + pub fn sourceURLFormatter(this: *const ZigStackFrame, root_path: string, origin: ?*const ZigURL, comptime enable_color: bool) SourceURLFormatter { return SourceURLFormatter{ .source_url = this.source_url, .origin = origin, .root_path = root_path, .position = this.position, .enable_color = enable_color }; } }; @@ -538,6 +597,16 @@ pub const ZigStackFramePosition = extern struct { pub const ZigException = extern struct { code: JSErrorCode, runtime_type: JSRuntimeType, + + /// SystemError only + errno: c_int = 0, + /// SystemError only + syscall: ZigString = ZigString.Empty, + /// SystemError only + system_code: ZigString = ZigString.Empty, + /// SystemError only + path: ZigString = ZigString.Empty, + name: ZigString, message: ZigString, stack: ZigStackTrace, @@ -675,15 +744,40 @@ pub const ZigConsoleClient = struct { }; } - /// TODO: support %s %d %f %o %O + pub const MessageLevel = enum(u32) { + Log = 0, + Warning = 1, + Error = 2, + Debug = 3, + Info = 4, + _, + }; + + pub const MessageType = enum(u32) { + Log = 0, + Dir = 1, + DirXML = 2, + Table = 3, + Trace = 4, + StartGroup = 5, + StartGroupCollapsed = 6, + EndGroup = 7, + Clear = 8, + Assert = 9, + Timing = 10, + Profile = 11, + ProfileEnd = 12, + Image = 13, + _, + }; + /// https://console.spec.whatwg.org/#formatter pub fn messageWithTypeAndLevel( //console_: ZigConsoleClient.Type, _: ZigConsoleClient.Type, - //message_type: u32, - _: u32, + message_type: MessageType, //message_level: u32, - _: u32, + level: MessageLevel, global: *JSGlobalObject, vals: [*]JSValue, len: usize, @@ -693,130 +787,728 @@ pub const ZigConsoleClient = struct { } var console = JS.VirtualMachine.vm.console; - var i: usize = 0; - var buffered_writer = console.writer; + + if (message_type == .Clear) { + Output.resetTerminal(); + return; + } + + if (message_type == .Assert and len == 0) { + const text = if (Output.enable_ansi_colors_stderr) + Output.prettyFmt("<r><red>Assertion failed<r>\n", true) + else + "Assertion failed\n"; + console.error_writer.unbuffered_writer.writeAll(text) catch unreachable; + return; + } + + const enable_colors = if (level == .Warning or level == .Error) + Output.enable_ansi_colors_stderr + else + Output.enable_ansi_colors_stdout; + var buffered_writer = if (level == .Warning or level == .Error) + console.error_writer + else + console.writer; var writer = buffered_writer.writer(); + const BufferedWriterType = @TypeOf(writer); + + var fmt: Formatter = undefined; + defer { + if (fmt.map_node) |node| { + node.data = fmt.map; + node.data.clearRetainingCapacity(); + node.release(); + } + } + if (len == 1) { - if (Output.enable_ansi_colors) { - FormattableType.format( - @TypeOf(buffered_writer.unbuffered_writer), - buffered_writer.unbuffered_writer, - vals[0], - global, - true, - ) catch {}; + fmt = Formatter{ .remaining_values = &[_]JSValue{} }; + const tag = Formatter.Tag.get(vals[0], global); + + var unbuffered_writer = buffered_writer.unbuffered_writer.context.writer(); + const UnbufferedWriterType = @TypeOf(unbuffered_writer); + + if (tag.tag == .String) { + if (enable_colors) { + if (level == .Error) { + unbuffered_writer.writeAll(comptime Output.prettyFmt("<r><red>", true)) catch unreachable; + } + fmt.format( + tag, + UnbufferedWriterType, + unbuffered_writer, + vals[0], + global, + true, + ); + if (level == .Error) { + unbuffered_writer.writeAll(comptime Output.prettyFmt("<r>", true)) catch unreachable; + } + } else { + fmt.format( + tag, + UnbufferedWriterType, + unbuffered_writer, + vals[0], + global, + false, + ); + } + _ = unbuffered_writer.write("\n") catch 0; } else { - FormattableType.format( - @TypeOf(buffered_writer.unbuffered_writer), - buffered_writer.unbuffered_writer, - vals[0], - global, - false, - ) catch {}; + defer buffered_writer.flush() catch {}; + if (enable_colors) { + fmt.format( + tag, + BufferedWriterType, + writer, + vals[0], + global, + true, + ); + } else { + fmt.format( + tag, + BufferedWriterType, + writer, + vals[0], + global, + false, + ); + } + _ = writer.write("\n") catch 0; } - _ = buffered_writer.unbuffered_writer.write("\n") catch 0; - return; } - var values = vals[0..len]; defer buffered_writer.flush() catch {}; - if (Output.enable_ansi_colors) { - while (i < len) : (i += 1) { - _ = if (i > 0) (writer.write(" ") catch 0); + var this_value: JSValue = vals[0]; + fmt = Formatter{ .remaining_values = vals[0..len][1..] }; + var tag: Formatter.Tag.Result = undefined; + + var any = false; + if (enable_colors) { + if (level == .Error) { + writer.writeAll(comptime Output.prettyFmt("<r><red>", true)) catch unreachable; + } + while (true) { + if (any) { + _ = writer.write(" ") catch 0; + } + any = true; + + tag = Formatter.Tag.get(this_value, global); + if (tag.tag == .String and fmt.remaining_values.len > 0) { + tag.tag = .StringPossiblyFormatted; + } + + fmt.format(tag, BufferedWriterType, writer, this_value, global, true); + if (fmt.remaining_values.len == 0) { + break; + } - FormattableType.format(@TypeOf(writer), writer, values[i], global, true) catch {}; + this_value = fmt.remaining_values[0]; + fmt.remaining_values = fmt.remaining_values[1..]; + } + if (level == .Error) { + writer.writeAll(comptime Output.prettyFmt("<r>", true)) catch unreachable; } } else { - while (i < len) : (i += 1) { - _ = if (i > 0) (writer.write(" ") catch 0); + while (true) { + if (any) { + _ = writer.write(" ") catch 0; + } + any = true; + tag = Formatter.Tag.get(this_value, global); + if (tag.tag == .String and fmt.remaining_values.len > 0) { + tag.tag = .StringPossiblyFormatted; + } + + fmt.format(tag, BufferedWriterType, writer, this_value, global, false); + if (fmt.remaining_values.len == 0) + break; - FormattableType.format(@TypeOf(writer), writer, values[i], global, false) catch {}; + this_value = fmt.remaining_values[0]; + fmt.remaining_values = fmt.remaining_values[1..]; } } _ = writer.write("\n") catch 0; } - const FormattableType = enum { - Error, - String, - Undefined, - Double, - Integer, - Null, - Boolean, - const CellType = CAPI.CellType; - threadlocal var name_buf: [512]u8 = undefined; - pub fn format(comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) anyerror!void { - if (comptime @hasDecl(@import("root"), "bindgen")) { - return; + pub const Formatter = struct { + remaining_values: []JSValue, + map: Visited.Map = undefined, + map_node: ?*Visited.Pool.Node = null, + hide_native: bool = false, + + // For detecting circular references + pub const Visited = struct { + const ObjectPool = @import("../../../pool.zig").ObjectPool; + pub const Map = std.AutoHashMap(i64, void); + pub const Pool = ObjectPool( + Map, + struct { + pub fn init(allocator: std.mem.Allocator) anyerror!Map { + return Map.init(allocator); + } + }.init, + true, + ); + }; + + pub const Tag = enum { + StringPossiblyFormatted, + String, + Undefined, + Double, + Integer, + Null, + Boolean, + Array, + Object, + Function, + Class, + Error, + TypedArray, + Map, + Set, + Symbol, + BigInt, + + GlobalObject, + Private, + Promise, + + JSON, + NativeCode, + ArrayBuffer, + + pub inline fn canHaveCircularReferences(tag: Tag) bool { + return tag == .Array or tag == .Object or tag == .Map or tag == .Set; } - if (value.isCell()) { - if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| { - const priv_data = JSPrivateDataPtr.from(private_data_ptr); - switch (priv_data.tag()) { - .BuildError => { - const build_error = priv_data.as(JS.BuildError); - try build_error.msg.formatWriter(Writer, writer, enable_ansi_colors); - return; - }, - .ResolveError => { - const resolve_error = priv_data.as(JS.ResolveError); - try resolve_error.msg.formatWriter(Writer, writer, enable_ansi_colors); - return; - }, - else => {}, + const Result = struct { + tag: Tag, + cell: JSValue.JSType = JSValue.JSType.Cell, + }; + + pub fn get(value: JSValue, globalThis: *JSGlobalObject) Result { + if (value.isInt32()) { + return .{ + .tag = .Integer, + }; + } else if (value.isNumber()) { + return .{ + .tag = .Double, + }; + } else if (value.isUndefined()) { + return .{ + .tag = .Undefined, + }; + } else if (value.isNull()) { + return .{ + .tag = .Null, + }; + } else if (value.isBoolean()) { + return .{ + .tag = .Boolean, + }; + } + + const js_type = value.jsType(); + + if (js_type.isHidden()) return .{ .tag = .NativeCode }; + + if (CAPI.JSObjectGetPrivate(value.asObjectRef()) != null) + return .{ + .tag = .Private, + }; + + // If we check an Object has a method table and it does not + // it will crash + const callable = js_type != .Object and value.isCallable(globalThis.vm()); + + if (value.isClass(globalThis) and !callable) { + // Temporary workaround + // console.log(process.env) shows up as [class JSCallbackObject] + // We want to print it like an object + if (CAPI.JSValueIsObjectOfClass(globalThis.ref(), value.asObjectRef(), JSC.Bun.EnvironmentVariables.Class.get().?[0])) { + return .{ + .tag = .Object, + }; } + return .{ + .tag = .Class, + }; } - switch (@intToEnum(CellType, value.asCell().getType())) { - CellType.ErrorInstanceType => { - JS.VirtualMachine.printErrorlikeObject(JS.VirtualMachine.vm, value, null, null, enable_ansi_colors); - return; + if (callable) { + return .{ + .tag = .Function, + }; + } + + return .{ + .tag = switch (js_type) { + JSValue.JSType.ErrorInstance => .Error, + JSValue.JSType.NumberObject => .Double, + JSValue.JSType.DerivedArray, JSValue.JSType.Array => .Array, + JSValue.JSType.DerivedStringObject, JSValue.JSType.String, JSValue.JSType.StringObject => .String, + JSValue.JSType.RegExpObject, + JSValue.JSType.Symbol, + => .String, + JSValue.JSType.BooleanObject => .Boolean, + JSValue.JSType.JSFunction => .Function, + JSValue.JSType.JSWeakMap, JSValue.JSType.JSMap => .Map, + JSValue.JSType.JSWeakSet, JSValue.JSType.JSSet => .Set, + JSValue.JSType.JSDate => .JSON, + JSValue.JSType.JSPromise => .Promise, + JSValue.JSType.Object, JSValue.JSType.FinalObject => .Object, + + JSValue.JSType.Int8Array, + JSValue.JSType.Uint8Array, + JSValue.JSType.Uint8ClampedArray, + JSValue.JSType.Int16Array, + JSValue.JSType.Uint16Array, + JSValue.JSType.Int32Array, + JSValue.JSType.Uint32Array, + JSValue.JSType.Float32Array, + JSValue.JSType.Float64Array, + JSValue.JSType.BigInt64Array, + JSValue.JSType.BigUint64Array, + => .TypedArray, + + // None of these should ever exist here + // But we're going to check anyway + .GetterSetter, + .CustomGetterSetter, + .APIValueWrapper, + .NativeExecutable, + .ProgramExecutable, + .ModuleProgramExecutable, + .EvalExecutable, + .FunctionExecutable, + .UnlinkedFunctionExecutable, + .UnlinkedProgramCodeBlock, + .UnlinkedModuleProgramCodeBlock, + .UnlinkedEvalCodeBlock, + .UnlinkedFunctionCodeBlock, + .CodeBlock, + .JSImmutableButterfly, + .JSSourceCode, + .JSScriptFetcher, + .JSScriptFetchParameters, + .JSCallee, + .GlobalLexicalEnvironment, + .LexicalEnvironment, + .ModuleEnvironment, + .StrictEvalActivation, + .WithScope, + => .NativeCode, + else => .JSON, }, + .cell = js_type, + }; + } + }; - CellType.GlobalObjectType => { - _ = try writer.write("[globalThis]"); - return; + const CellType = CAPI.CellType; + threadlocal var name_buf: [512]u8 = undefined; + + fn writeWithFormatting( + this: *Formatter, + comptime Writer: type, + writer_: Writer, + comptime Slice: type, + slice_: Slice, + globalThis: *JSGlobalObject, + comptime enable_ansi_colors: bool, + ) void { + var writer = WrappedWriter(Writer){ .ctx = writer_ }; + var slice = slice_; + var i: u32 = 0; + var len: u32 = @truncate(u32, slice.len); + while (i < len) : (i += 1) { + switch (slice[i]) { + '%' => { + i += 1; + if (i >= len) + break; + + const token = switch (slice[i]) { + 's' => Tag.String, + 'f' => Tag.Double, + 'o' => Tag.Undefined, + 'O' => Tag.Object, + 'd', 'i' => Tag.Integer, + else => continue, + }; + + // Flush everything up to the % + const end = slice[0 .. i - 1]; + writer.writeAll(end); + slice = slice[@minimum(slice.len, i + 1)..]; + i = 0; + len = @truncate(u32, slice.len); + const next_value = this.remaining_values[0]; + this.remaining_values = this.remaining_values[1..]; + switch (token) { + Tag.String => this.printAs(Tag.String, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + Tag.Double => this.printAs(Tag.Double, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + Tag.Object => this.printAs(Tag.Object, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + Tag.Integer => this.printAs(Tag.Integer, Writer, writer_, next_value, globalThis, next_value.jsType(), enable_ansi_colors), + + // undefined is overloaded to mean the '%o" field + Tag.Undefined => this.format(Tag.get(next_value, globalThis), Writer, writer_, next_value, globalThis, enable_ansi_colors), + + else => unreachable, + } + if (this.remaining_values.len == 0) break; + }, + '\\' => { + i += 1; + if (i >= len) + break; + if (slice[i] == '%') i += 2; }, else => {}, } } - if (value.isInt32()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.toInt32()}); - } else if (value.isNumber()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.asNumber()}); - } else if (value.isUndefined()) { - try writer.print(comptime Output.prettyFmt("<r><d>undefined<r>", enable_ansi_colors), .{}); - } else if (value.isNull()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>null<r>", enable_ansi_colors), .{}); - } else if (value.isBoolean()) { - if (value.toBoolean()) { - try writer.print(comptime Output.prettyFmt("<r><yellow>true<r>", enable_ansi_colors), .{}); - } else { - try writer.print(comptime Output.prettyFmt("<r><yellow>false<r>", enable_ansi_colors), .{}); + if (slice.len > 0) writer.writeAll(slice); + } + + pub fn WrappedWriter(comptime Writer: type) type { + return struct { + ctx: Writer, + + pub fn print(self: *@This(), comptime fmt: string, args: anytype) void { + self.ctx.print(fmt, args) catch unreachable; } - // } else if (value.isSymbol()) { - // try writer.print(comptime Output.prettyFmt("<r><yellow>Symbol(\"{s}\")<r>", enable_ansi_colors), .{ value.getDescriptionProperty() }); - } else if (value.isClass(globalThis)) { - var printable = ZigString.init(&name_buf); - value.getClassName(globalThis, &printable); - try writer.print("[class {s}]", .{printable.slice()}); - } else if (value.isCallable(globalThis.vm())) { - var printable = ZigString.init(&name_buf); - value.getNameProperty(globalThis, &printable); - try writer.print("[Function {s}]", .{printable.slice()}); - } else { - var str = value.toWTFString(JS.VirtualMachine.vm.global); - _ = try writer.write(str.slice()); + + pub inline fn writeAll(self: *@This(), buf: []const u8) void { + self.ctx.writeAll(buf) catch unreachable; + } + }; + } + + pub fn printAs( + this: *Formatter, + comptime Format: Formatter.Tag, + comptime Writer: type, + writer_: Writer, + value: JSValue, + globalThis: *JSGlobalObject, + jsType: JSValue.JSType, + comptime enable_ansi_colors: bool, + ) void { + var writer = WrappedWriter(Writer){ .ctx = writer_ }; + + if (comptime Format.canHaveCircularReferences()) { + if (this.map_node == null) { + this.map_node = Visited.Pool.get(default_allocator); + this.map_node.?.data.clearRetainingCapacity(); + this.map = this.map_node.?.data; + } + + var entry = this.map.getOrPut(@enumToInt(value)) catch unreachable; + if (entry.found_existing) { + writer.writeAll(comptime Output.prettyFmt("<r><cyan>[Circular]<r>", enable_ansi_colors)); + return; + } + } + + switch (comptime Format) { + .StringPossiblyFormatted => { + var str = ZigString.init(""); + value.toZigString(&str, globalThis); + + if (!str.is16Bit()) { + const slice = str.slice(); + this.writeWithFormatting(Writer, writer_, @TypeOf(slice), slice, globalThis, enable_ansi_colors); + } else { + // TODO: UTF16 + writer.print("{}", .{str}); + } + }, + .String => { + var str = ZigString.init(""); + value.toZigString(&str, globalThis); + if (jsType == .RegExpObject) { + writer.print(comptime Output.prettyFmt("<r><red>", enable_ansi_colors), .{}); + } + + writer.print("{}", .{str}); + + if (jsType == .RegExpObject) { + writer.print(comptime Output.prettyFmt("<r>", enable_ansi_colors), .{}); + } + }, + .Integer => { + writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.toInt32()}); + }, + .Double => { + writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.asNumber()}); + }, + .Undefined => { + writer.print(comptime Output.prettyFmt("<r><d>undefined<r>", enable_ansi_colors), .{}); + }, + .Null => { + writer.print(comptime Output.prettyFmt("<r><yellow>null<r>", enable_ansi_colors), .{}); + }, + .Error => { + JS.VirtualMachine.printErrorlikeObject(JS.VirtualMachine.vm, value, null, null, enable_ansi_colors); + }, + .Class => { + var printable = ZigString.init(&name_buf); + value.getClassName(globalThis, &printable); + if (printable.len == 0) { + writer.print(comptime Output.prettyFmt("[class]", enable_ansi_colors), .{}); + } else { + writer.print(comptime Output.prettyFmt("[class <cyan>{}<r>]", enable_ansi_colors), .{printable}); + } + }, + .Function => { + var printable = ZigString.init(&name_buf); + value.getNameProperty(globalThis, &printable); + + if (printable.len == 0) { + writer.print(comptime Output.prettyFmt("<cyan>[Function]<r>", enable_ansi_colors), .{}); + } else { + writer.print(comptime Output.prettyFmt("<cyan>[Function<d>:<r> <cyan>{}]<r>", enable_ansi_colors), .{printable}); + } + }, + .Array => { + const len = value.getLengthOfArray(globalThis); + if (len == 0) { + writer.writeAll("[]"); + return; + } + + writer.writeAll("[ "); + var i: u32 = 0; + var ref = value.asObjectRef(); + while (i < len) : (i += 1) { + if (i > 0) { + writer.writeAll(", "); + } + + const element = JSValue.fromRef(CAPI.JSObjectGetPropertyAtIndex(globalThis.ref(), ref, i, null)); + const tag = Tag.get(element, globalThis); + + if (tag.cell.isStringLike()) { + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r><green>", true)); + } + writer.writeAll("\""); + } + + this.format(tag, Writer, writer_, element, globalThis, enable_ansi_colors); + + if (tag.cell.isStringLike()) { + writer.writeAll("\""); + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r>", true)); + } + } + } + + writer.writeAll(" ]"); + }, + .Private => { + if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| { + const priv_data = JSPrivateDataPtr.from(private_data_ptr); + switch (priv_data.tag()) { + .BuildError => { + const build_error = priv_data.as(JS.BuildError); + build_error.msg.formatWriter(Writer, writer_, enable_ansi_colors) catch {}; + return; + }, + .ResolveError => { + const resolve_error = priv_data.as(JS.ResolveError); + resolve_error.msg.formatWriter(Writer, writer_, enable_ansi_colors) catch {}; + return; + }, + else => {}, + } + } + + writer.writeAll("[native code]"); + }, + .NativeCode => { + writer.writeAll("[native code]"); + }, + .Promise => { + writer.writeAll("Promise { " ++ comptime Output.prettyFmt("<r><cyan>", enable_ansi_colors)); + + switch (JSPromise.status(@ptrCast(*JSPromise, value.asObjectRef().?), globalThis.vm())) { + JSPromise.Status.Pending => { + writer.writeAll("<pending>"); + }, + JSPromise.Status.Fulfilled => { + writer.writeAll("<resolved>"); + }, + JSPromise.Status.Rejected => { + writer.writeAll("<rejected>"); + }, + } + + writer.writeAll(comptime Output.prettyFmt("<r>", enable_ansi_colors) ++ " }"); + }, + .Boolean => { + if (value.toBoolean()) { + writer.writeAll(comptime Output.prettyFmt("<r><yellow>true<r>", enable_ansi_colors)); + } else { + writer.writeAll(comptime Output.prettyFmt("<r><yellow>false<r>", enable_ansi_colors)); + } + }, + .GlobalObject => { + writer.writeAll(comptime Output.prettyFmt("<cyan>[globalThis]<r>", enable_ansi_colors)); + }, + .Map => {}, + .Set => {}, + .JSON => { + var str = ZigString.init(""); + value.jsonStringify(globalThis, 0, &str); + if (jsType == JSValue.JSType.JSDate) { + // in the code for printing dates, it never exceeds this amount + var iso_string_buf: [36]u8 = undefined; + var out_buf: []const u8 = std.fmt.bufPrint(&iso_string_buf, "{}", .{str}) catch ""; + if (out_buf.len > 2) { + // trim the quotes + out_buf = out_buf[1 .. out_buf.len - 1]; + } + + writer.print(comptime Output.prettyFmt("<r><magenta>{s}<r>", enable_ansi_colors), .{out_buf}); + return; + } + + writer.print("{}", .{str}); + }, + .Object => { + var object = value.asObjectRef(); + var array = CAPI.JSObjectCopyPropertyNames(globalThis.ref(), object); + defer CAPI.JSPropertyNameArrayRelease(array); + const count_ = CAPI.JSPropertyNameArrayGetCount(array); + var i: usize = 0; + + var name_str = ZigString.init(""); + value.getPrototype(globalThis).getNameProperty(globalThis, &name_str); + + if (name_str.len > 0 and !strings.eqlComptime(name_str.slice(), "Object")) { + writer.print("{} ", .{name_str}); + } + + if (count_ == 0) { + writer.writeAll("{ }"); + return; + } + + writer.writeAll("{ "); + + while (i < count_) : (i += 1) { + var property_name_ref = CAPI.JSPropertyNameArrayGetNameAtIndex(array, i); + defer CAPI.JSStringRelease(property_name_ref); + var prop = CAPI.JSStringGetCharacters8Ptr(property_name_ref)[0..CAPI.JSStringGetLength(property_name_ref)]; + + var property_value = CAPI.JSObjectGetProperty(globalThis.ref(), object, property_name_ref, null); + const tag = Tag.get(JSValue.fromRef(property_value), globalThis); + + if (tag.cell.isHidden()) continue; + + writer.print( + comptime Output.prettyFmt("{s}<d>:<r> ", enable_ansi_colors), + .{prop[0..@minimum(prop.len, 128)]}, + ); + + if (tag.cell.isStringLike()) { + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r><green>", true)); + } + writer.writeAll("\""); + } + + this.format(tag, Writer, writer_, JSValue.fromRef(property_value), globalThis, enable_ansi_colors); + + if (tag.cell.isStringLike()) { + writer.writeAll("\""); + if (comptime enable_ansi_colors) { + writer.writeAll(comptime Output.prettyFmt("<r>", true)); + } + } + + if (i + 1 < count_) { + writer.writeAll(", "); + } + } + + writer.writeAll(" }"); + }, + .TypedArray => { + const len = value.getLengthOfArray(globalThis); + if (len == 0) { + writer.writeAll("[]"); + return; + } + + writer.writeAll("[ "); + var i: u32 = 0; + var buffer = JSC.Buffer.fromJS(globalThis, value, null).?; + const slice = buffer.slice(); + while (i < len) : (i += 1) { + if (i > 0) { + writer.writeAll(", "); + } + + writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{slice[i]}); + } + + writer.writeAll(" ]"); + }, + else => {}, } } + + pub fn format(this: *Formatter, result: Tag.Result, comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) void { + if (comptime @hasDecl(@import("root"), "bindgen")) { + return; + } + + // This looks incredibly redudant. We make the Formatter.Tag a + // comptime var so we have to repeat it here. The rationale there is + // it _should_ limit the stack usage because each version of the + // function will be relatively small + return switch (result.tag) { + .StringPossiblyFormatted => this.printAs(.StringPossiblyFormatted, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .String => this.printAs(.String, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Undefined => this.printAs(.Undefined, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Double => this.printAs(.Double, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Integer => this.printAs(.Integer, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Null => this.printAs(.Null, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Boolean => this.printAs(.Boolean, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Array => this.printAs(.Array, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Object => this.printAs(.Object, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Function => this.printAs(.Function, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Class => this.printAs(.Class, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Error => this.printAs(.Error, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .TypedArray => this.printAs(.TypedArray, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Map => this.printAs(.Map, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Set => this.printAs(.Set, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Symbol => this.printAs(.Symbol, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .BigInt => this.printAs(.BigInt, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .GlobalObject => this.printAs(.GlobalObject, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Private => this.printAs(.Private, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .Promise => this.printAs(.Promise, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .JSON => this.printAs(.JSON, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .NativeCode => this.printAs(.NativeCode, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + .ArrayBuffer => this.printAs(.ArrayBuffer, Writer, writer, value, globalThis, result.cell, enable_ansi_colors), + }; + } }; pub fn count( @@ -926,12 +1618,16 @@ pub const ZigConsoleClient = struct { // console _: ZigConsoleClient.Type, // global - _: *JSGlobalObject, + globalThis: *JSGlobalObject, // chars _: [*]const u8, // len _: usize, - ) callconv(.C) void {} + ) callconv(.C) void { + // TODO: this does an extra JSONStringify and we don't need it to! + var snapshot: [1]JSValue = .{globalThis.generateHeapSnapshot()}; + ZigConsoleClient.messageWithTypeAndLevel(undefined, MessageType.Log, MessageLevel.Debug, globalThis, &snapshot, 1); + } pub fn timeStamp( // console _: ZigConsoleClient.Type, @@ -1120,3 +1816,12 @@ comptime { @export(ErrorCode.ParserError, .{ .name = "Zig_ErrorCodeParserError" }); @export(ErrorCode.JSErrorObject, .{ .name = "Zig_ErrorCodeJSErrorObject" }); } + +comptime { + if (!is_bindgen) { + _ = Process.getTitle; + _ = Process.setTitle; + std.testing.refAllDecls(NodeReadableStream); + std.testing.refAllDecls(NodeWritableStream); + } +} diff --git a/src/javascript/jsc/bindings/header-gen.zig b/src/javascript/jsc/bindings/header-gen.zig index bdf1778ad..9a9b9314f 100644 --- a/src/javascript/jsc/bindings/header-gen.zig +++ b/src/javascript/jsc/bindings/header-gen.zig @@ -103,7 +103,7 @@ pub const C_Generator = struct { pub fn gen_func( self: *Self, comptime name: []const u8, - comptime func: FnDecl, + comptime func: anytype, comptime meta: FnMeta, comptime _: []const []const u8, comptime rewrite_return: bool, @@ -121,16 +121,21 @@ pub const C_Generator = struct { .export_zig => self.write("ZIG_DECL "), } + const return_type: type = comptime if (@TypeOf(func.return_type) == ?type) + (func.return_type orelse void) + else + func.return_type; + if (comptime rewrite_return) { self.writeType(void); } else { - self.writeType(comptime func.return_type); + self.writeType(comptime return_type); } self.write(" " ++ name ++ "("); if (comptime rewrite_return) { - self.writeType(comptime func.return_type); + self.writeType(comptime return_type); self.write("_buf ret_value"); if (comptime meta.args.len > 0) { @@ -515,9 +520,15 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp pub fn processStaticExport(comptime _: Self, _: anytype, gen: *C_Generator, comptime static_export: StaticExport) void { const fn_meta = comptime @typeInfo(static_export.Type).Fn; + const DeclData = static_export.Decl().data; + gen.gen_func( comptime static_export.symbol_name, - comptime static_export.Decl().data.Fn, + comptime switch (DeclData) { + .Fn => |Fn| Fn, + .Var => |Var| @typeInfo(Var).Fn, + else => unreachable, + }, comptime fn_meta, comptime std.mem.zeroes([]const []const u8), false, diff --git a/src/javascript/jsc/bindings/headers-cpp.h b/src/javascript/jsc/bindings/headers-cpp.h index 4ea0be1a6..470feff87 100644 --- a/src/javascript/jsc/bindings/headers-cpp.h +++ b/src/javascript/jsc/bindings/headers-cpp.h @@ -1,4 +1,4 @@ -//-- AUTOGENERATED FILE -- 1640933554 +//-- AUTOGENERATED FILE -- 1642473926 // clang-format off #pragma once @@ -216,6 +216,22 @@ extern "C" const size_t WTF__StringView_object_align_ = alignof(WTF::StringView) extern "C" const size_t Zig__GlobalObject_object_size_ = sizeof(Zig::GlobalObject); extern "C" const size_t Zig__GlobalObject_object_align_ = alignof(Zig::GlobalObject); +#ifndef INCLUDED_BunStream_h +#define INCLUDED_BunStream_h +#include BunStream.h +#endif + +extern "C" const size_t Bun__Readable_object_size_ = sizeof(Bun__Readable); +extern "C" const size_t Bun__Readable_object_align_ = alignof(Bun__Readable); + +#ifndef INCLUDED_BunStream_h +#define INCLUDED_BunStream_h +#include BunStream.h +#endif + +extern "C" const size_t Bun__Writable_object_size_ = sizeof(Bun__Writable); +extern "C" const size_t Bun__Writable_object_align_ = alignof(Bun__Writable); + #ifndef INCLUDED__ZigConsoleClient_h_ #define INCLUDED__ZigConsoleClient_h_ #include "ZigConsoleClient.h" @@ -224,8 +240,8 @@ extern "C" const size_t Zig__GlobalObject_object_align_ = alignof(Zig::GlobalObj extern "C" const size_t Zig__ConsoleClient_object_size_ = sizeof(Zig::ConsoleClient); extern "C" const size_t Zig__ConsoleClient_object_align_ = alignof(Zig::ConsoleClient); -const size_t sizes[26] = {sizeof(JSC::JSObject), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(Inspector::ScriptArguments), sizeof(JSC::JSModuleLoader), sizeof(JSC::JSModuleRecord), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::SourceOrigin), sizeof(JSC::SourceCode), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(WTF::URL), sizeof(WTF::String), sizeof(JSC::JSValue), sizeof(JSC::PropertyName), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(JSC::CallFrame), sizeof(JSC::Identifier), sizeof(WTF::StringImpl), sizeof(WTF::ExternalStringImpl), sizeof(WTF::StringView), sizeof(Zig::GlobalObject)}; +const size_t sizes[29] = {sizeof(JSC::JSObject), sizeof(SystemError), sizeof(JSC::JSCell), sizeof(JSC::JSString), sizeof(Inspector::ScriptArguments), sizeof(JSC::JSModuleLoader), sizeof(JSC::JSModuleRecord), sizeof(JSC::JSPromise), sizeof(JSC::JSInternalPromise), sizeof(JSC::SourceOrigin), sizeof(JSC::SourceCode), sizeof(JSC::JSFunction), sizeof(JSC::JSGlobalObject), sizeof(WTF::URL), sizeof(WTF::String), sizeof(JSC::JSValue), sizeof(JSC::PropertyName), sizeof(JSC::Exception), sizeof(JSC::VM), sizeof(JSC::ThrowScope), sizeof(JSC::CatchScope), sizeof(JSC::CallFrame), sizeof(JSC::Identifier), sizeof(WTF::StringImpl), sizeof(WTF::ExternalStringImpl), sizeof(WTF::StringView), sizeof(Zig::GlobalObject), sizeof(Bun__Readable), sizeof(Bun__Writable)}; -const char* names[26] = {"JSC__JSObject", "JSC__JSCell", "JSC__JSString", "Inspector__ScriptArguments", "JSC__JSModuleLoader", "JSC__JSModuleRecord", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__SourceOrigin", "JSC__SourceCode", "JSC__JSFunction", "JSC__JSGlobalObject", "WTF__URL", "WTF__String", "JSC__JSValue", "JSC__PropertyName", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "JSC__CallFrame", "JSC__Identifier", "WTF__StringImpl", "WTF__ExternalStringImpl", "WTF__StringView", "Zig__GlobalObject"}; +const char* names[29] = {"JSC__JSObject", "SystemError", "JSC__JSCell", "JSC__JSString", "Inspector__ScriptArguments", "JSC__JSModuleLoader", "JSC__JSModuleRecord", "JSC__JSPromise", "JSC__JSInternalPromise", "JSC__SourceOrigin", "JSC__SourceCode", "JSC__JSFunction", "JSC__JSGlobalObject", "WTF__URL", "WTF__String", "JSC__JSValue", "JSC__PropertyName", "JSC__Exception", "JSC__VM", "JSC__ThrowScope", "JSC__CatchScope", "JSC__CallFrame", "JSC__Identifier", "WTF__StringImpl", "WTF__ExternalStringImpl", "WTF__StringView", "Zig__GlobalObject", "Bun__Readable", "Bun__Writable"}; -const size_t aligns[26] = {alignof(JSC::JSObject), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(Inspector::ScriptArguments), alignof(JSC::JSModuleLoader), alignof(JSC::JSModuleRecord), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::SourceOrigin), alignof(JSC::SourceCode), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(WTF::URL), alignof(WTF::String), alignof(JSC::JSValue), alignof(JSC::PropertyName), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(JSC::CallFrame), alignof(JSC::Identifier), alignof(WTF::StringImpl), alignof(WTF::ExternalStringImpl), alignof(WTF::StringView), alignof(Zig::GlobalObject)}; +const size_t aligns[29] = {alignof(JSC::JSObject), alignof(SystemError), alignof(JSC::JSCell), alignof(JSC::JSString), alignof(Inspector::ScriptArguments), alignof(JSC::JSModuleLoader), alignof(JSC::JSModuleRecord), alignof(JSC::JSPromise), alignof(JSC::JSInternalPromise), alignof(JSC::SourceOrigin), alignof(JSC::SourceCode), alignof(JSC::JSFunction), alignof(JSC::JSGlobalObject), alignof(WTF::URL), alignof(WTF::String), alignof(JSC::JSValue), alignof(JSC::PropertyName), alignof(JSC::Exception), alignof(JSC::VM), alignof(JSC::ThrowScope), alignof(JSC::CatchScope), alignof(JSC::CallFrame), alignof(JSC::Identifier), alignof(WTF::StringImpl), alignof(WTF::ExternalStringImpl), alignof(WTF::StringView), alignof(Zig::GlobalObject), alignof(Bun__Readable), alignof(Bun__Writable)}; diff --git a/src/javascript/jsc/bindings/headers-handwritten.h b/src/javascript/jsc/bindings/headers-handwritten.h index e07eca6b6..cf7c87e4f 100644 --- a/src/javascript/jsc/bindings/headers-handwritten.h +++ b/src/javascript/jsc/bindings/headers-handwritten.h @@ -35,6 +35,14 @@ typedef struct ErrorableResolvedSource { bool success; } ErrorableResolvedSource; +typedef struct SystemError { + int errno_; + ZigString code; + ZigString message; + ZigString path; + ZigString syscall; +} SystemError; + typedef uint8_t ZigStackFrameCode; const ZigStackFrameCode ZigStackFrameCodeNone = 0; const ZigStackFrameCode ZigStackFrameCodeEval = 1; @@ -74,6 +82,10 @@ typedef struct ZigStackTrace { typedef struct ZigException { unsigned char code; uint16_t runtime_type; + int errno_; + ZigString syscall; + ZigString code_; + ZigString path; ZigString name; ZigString message; ZigStackTrace stack; @@ -93,9 +105,83 @@ const JSErrorCode JSErrorCodeOutOfMemoryError = 8; const JSErrorCode JSErrorCodeStackOverflow = 253; const JSErrorCode JSErrorCodeUserErrorCode = 254; +#pragma mark - Stream + +typedef uint8_t Encoding; +const Encoding Encoding__utf8 = 0; +const Encoding Encoding__ucs2 = 1; +const Encoding Encoding__utf16le = 2; +const Encoding Encoding__latin1 = 3; +const Encoding Encoding__ascii = 4; +const Encoding Encoding__base64 = 5; +const Encoding Encoding__base64url = 6; +const Encoding Encoding__hex = 7; +const Encoding Encoding__buffer = 8; + +typedef uint8_t WritableEvent; +const WritableEvent WritableEvent__Close = 0; +const WritableEvent WritableEvent__Drain = 1; +const WritableEvent WritableEvent__Error = 2; +const WritableEvent WritableEvent__Finish = 3; +const WritableEvent WritableEvent__Pipe = 4; +const WritableEvent WritableEvent__Unpipe = 5; +const WritableEvent WritableEvent__Open = 6; +const WritableEvent WritableEventUser = 254; + +typedef uint8_t ReadableEvent; + +const ReadableEvent ReadableEvent__Close = 0; +const ReadableEvent ReadableEvent__Data = 1; +const ReadableEvent ReadableEvent__End = 2; +const ReadableEvent ReadableEvent__Error = 3; +const ReadableEvent ReadableEvent__Pause = 4; +const ReadableEvent ReadableEvent__Readable = 5; +const ReadableEvent ReadableEvent__Resume = 6; +const ReadableEvent ReadableEvent__Open = 7; +const ReadableEvent ReadableEventUser = 254; + +typedef struct { + uint32_t highwater_mark; + Encoding encoding; + int32_t start; + int32_t end; + bool readable; + bool aborted; + bool did_read; + bool ended; + uint8_t flowing; + bool emit_close; + bool emit_end; +} Bun__Readable; + +typedef struct { + uint32_t highwater_mark; + Encoding encoding; + uint32_t start; + bool destroyed; + bool ended; + bool corked; + bool finished; + bool emit_close; +} Bun__Writable; + #ifdef __cplusplus + extern "C" ZigErrorCode Zig_ErrorCodeParserError; extern "C" void ZigString__free(const unsigned char *ptr, size_t len, void *allocator); extern "C" void Microtask__run(void *ptr, void *global); + +// Used in process.version +extern "C" const char *Bun__version; + +// Used in process.versions +extern "C" const char *Bun__versions_webkit; +extern "C" const char *Bun__versions_mimalloc; +extern "C" const char *Bun__versions_libarchive; +extern "C" const char *Bun__versions_picohttpparser; +extern "C" const char *Bun__versions_boringssl; +extern "C" const char *Bun__versions_zlib; +extern "C" const char *Bun__versions_zig; + #endif diff --git a/src/javascript/jsc/bindings/headers-replacements.zig b/src/javascript/jsc/bindings/headers-replacements.zig index e45f0348d..96c058d56 100644 --- a/src/javascript/jsc/bindings/headers-replacements.zig +++ b/src/javascript/jsc/bindings/headers-replacements.zig @@ -53,4 +53,8 @@ pub const ZigStackTrace = bindings.ZigStackTrace; pub const ReturnableException = bindings.ReturnableException; pub const struct_Zig__JSMicrotaskCallback = bindings.Microtask; pub const bZig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; +pub const SystemError = bindings.SystemError; const JSClassRef = bindings.C.JSClassRef; +pub const JSC__CatchScope = bindings.CatchScope; +pub const Bun__Readable = bindings.NodeReadableStream; +pub const Bun__Writable = bindings.NodeWritableStream; diff --git a/src/javascript/jsc/bindings/headers.h b/src/javascript/jsc/bindings/headers.h index 6ae0dae83..9db733c02 100644 --- a/src/javascript/jsc/bindings/headers.h +++ b/src/javascript/jsc/bindings/headers.h @@ -1,5 +1,5 @@ // clang-format: off -//-- AUTOGENERATED FILE -- 1640933554 +//-- AUTOGENERATED FILE -- 1642473926 #pragma once #include <stddef.h> @@ -78,55 +78,58 @@ typedef void* JSClassRef; typedef char* bJSC__Identifier_buf; #ifndef __cplusplus - typedef struct JSC__RegExpPrototype JSC__RegExpPrototype; // JSC::RegExpPrototype + typedef bJSC__CatchScope JSC__CatchScope; // JSC::CatchScope typedef struct JSC__GeneratorPrototype JSC__GeneratorPrototype; // JSC::GeneratorPrototype typedef struct JSC__ArrayIteratorPrototype JSC__ArrayIteratorPrototype; // JSC::ArrayIteratorPrototype - typedef struct JSC__StringPrototype JSC__StringPrototype; // JSC::StringPrototype - typedef bWTF__StringView WTF__StringView; // WTF::StringView + typedef ErrorableResolvedSource ErrorableResolvedSource; typedef struct JSC__JSPromisePrototype JSC__JSPromisePrototype; // JSC::JSPromisePrototype - typedef bJSC__CatchScope JSC__CatchScope; // JSC::CatchScope - typedef bJSC__ThrowScope JSC__ThrowScope; // JSC::ThrowScope + typedef ErrorableZigString ErrorableZigString; typedef bJSC__PropertyName JSC__PropertyName; // JSC::PropertyName typedef bJSC__JSObject JSC__JSObject; // JSC::JSObject - typedef ErrorableResolvedSource ErrorableResolvedSource; - typedef ErrorableZigString ErrorableZigString; typedef bWTF__ExternalStringImpl WTF__ExternalStringImpl; // WTF::ExternalStringImpl typedef struct JSC__AsyncIteratorPrototype JSC__AsyncIteratorPrototype; // JSC::AsyncIteratorPrototype - typedef bWTF__StringImpl WTF__StringImpl; // WTF::StringImpl typedef bJSC__JSLock JSC__JSLock; // JSC::JSLock typedef bJSC__JSModuleLoader JSC__JSModuleLoader; // JSC::JSModuleLoader - typedef bJSC__VM JSC__VM; // JSC::VM - typedef JSClassRef JSClassRef; typedef struct JSC__AsyncGeneratorPrototype JSC__AsyncGeneratorPrototype; // JSC::AsyncGeneratorPrototype typedef struct JSC__AsyncGeneratorFunctionPrototype JSC__AsyncGeneratorFunctionPrototype; // JSC::AsyncGeneratorFunctionPrototype - typedef bJSC__JSGlobalObject JSC__JSGlobalObject; // JSC::JSGlobalObject - typedef bJSC__JSFunction JSC__JSFunction; // JSC::JSFunction - typedef struct JSC__ArrayPrototype JSC__ArrayPrototype; // JSC::ArrayPrototype - typedef struct JSC__AsyncFunctionPrototype JSC__AsyncFunctionPrototype; // JSC::AsyncFunctionPrototype typedef bJSC__Identifier JSC__Identifier; // JSC::Identifier + typedef struct JSC__ArrayPrototype JSC__ArrayPrototype; // JSC::ArrayPrototype + typedef struct Zig__JSMicrotaskCallback Zig__JSMicrotaskCallback; // Zig::JSMicrotaskCallback typedef bJSC__JSPromise JSC__JSPromise; // JSC::JSPromise - typedef ZigException ZigException; typedef struct JSC__SetIteratorPrototype JSC__SetIteratorPrototype; // JSC::SetIteratorPrototype - typedef bJSC__SourceCode JSC__SourceCode; // JSC::SourceCode - typedef struct Zig__JSMicrotaskCallback Zig__JSMicrotaskCallback; // Zig::JSMicrotaskCallback + typedef SystemError SystemError; typedef bJSC__JSCell JSC__JSCell; // JSC::JSCell - typedef struct JSC__BigIntPrototype JSC__BigIntPrototype; // JSC::BigIntPrototype - typedef struct JSC__GeneratorFunctionPrototype JSC__GeneratorFunctionPrototype; // JSC::GeneratorFunctionPrototype typedef bJSC__SourceOrigin JSC__SourceOrigin; // JSC::SourceOrigin - typedef ZigString ZigString; typedef bJSC__JSModuleRecord JSC__JSModuleRecord; // JSC::JSModuleRecord typedef bWTF__String WTF__String; // WTF::String typedef bWTF__URL WTF__URL; // WTF::URL - typedef int64_t JSC__JSValue; typedef struct JSC__IteratorPrototype JSC__IteratorPrototype; // JSC::IteratorPrototype + typedef Bun__Readable Bun__Readable; typedef bJSC__JSInternalPromise JSC__JSInternalPromise; // JSC::JSInternalPromise + typedef Bun__Writable Bun__Writable; + typedef struct JSC__RegExpPrototype JSC__RegExpPrototype; // JSC::RegExpPrototype + typedef bJSC__CallFrame JSC__CallFrame; // JSC::CallFrame + typedef struct JSC__MapIteratorPrototype JSC__MapIteratorPrototype; // JSC::MapIteratorPrototype + typedef bWTF__StringView WTF__StringView; // WTF::StringView + typedef bJSC__ThrowScope JSC__ThrowScope; // JSC::ThrowScope + typedef bWTF__StringImpl WTF__StringImpl; // WTF::StringImpl + typedef bJSC__VM JSC__VM; // JSC::VM + typedef JSClassRef JSClassRef; + typedef bJSC__JSGlobalObject JSC__JSGlobalObject; // JSC::JSGlobalObject + typedef bJSC__JSFunction JSC__JSFunction; // JSC::JSFunction + typedef struct JSC__AsyncFunctionPrototype JSC__AsyncFunctionPrototype; // JSC::AsyncFunctionPrototype + typedef ZigException ZigException; + typedef bJSC__SourceCode JSC__SourceCode; // JSC::SourceCode + typedef struct JSC__BigIntPrototype JSC__BigIntPrototype; // JSC::BigIntPrototype + typedef struct JSC__GeneratorFunctionPrototype JSC__GeneratorFunctionPrototype; // JSC::GeneratorFunctionPrototype + typedef ZigString ZigString; + typedef int64_t JSC__JSValue; typedef struct JSC__FunctionPrototype JSC__FunctionPrototype; // JSC::FunctionPrototype typedef bInspector__ScriptArguments Inspector__ScriptArguments; // Inspector::ScriptArguments typedef bJSC__Exception JSC__Exception; // JSC::Exception typedef bJSC__JSString JSC__JSString; // JSC::JSString typedef struct JSC__ObjectPrototype JSC__ObjectPrototype; // JSC::ObjectPrototype - typedef bJSC__CallFrame JSC__CallFrame; // JSC::CallFrame - typedef struct JSC__MapIteratorPrototype JSC__MapIteratorPrototype; // JSC::MapIteratorPrototype + typedef struct JSC__StringPrototype JSC__StringPrototype; // JSC::StringPrototype #endif @@ -134,8 +137,8 @@ typedef void* JSClassRef; namespace JSC { class JSCell; class Exception; - class StringPrototype; class JSPromisePrototype; + class StringPrototype; class GeneratorFunctionPrototype; class ArrayPrototype; class JSString; @@ -149,9 +152,9 @@ typedef void* JSClassRef; class CatchScope; class VM; class BigIntPrototype; - class SetIteratorPrototype; - class ThrowScope; class SourceOrigin; + class ThrowScope; + class SetIteratorPrototype; class AsyncGeneratorPrototype; class PropertyName; class MapIteratorPrototype; @@ -185,14 +188,17 @@ typedef void* JSClassRef; typedef ErrorableResolvedSource ErrorableResolvedSource; typedef ErrorableZigString ErrorableZigString; + typedef SystemError SystemError; + typedef Bun__Readable Bun__Readable; + typedef Bun__Writable Bun__Writable; typedef JSClassRef JSClassRef; typedef ZigException ZigException; typedef ZigString ZigString; typedef int64_t JSC__JSValue; using JSC__JSCell = JSC::JSCell; using JSC__Exception = JSC::Exception; - using JSC__StringPrototype = JSC::StringPrototype; using JSC__JSPromisePrototype = JSC::JSPromisePrototype; + using JSC__StringPrototype = JSC::StringPrototype; using JSC__GeneratorFunctionPrototype = JSC::GeneratorFunctionPrototype; using JSC__ArrayPrototype = JSC::ArrayPrototype; using JSC__JSString = JSC::JSString; @@ -206,9 +212,9 @@ typedef void* JSClassRef; using JSC__CatchScope = JSC::CatchScope; using JSC__VM = JSC::VM; using JSC__BigIntPrototype = JSC::BigIntPrototype; - using JSC__SetIteratorPrototype = JSC::SetIteratorPrototype; - using JSC__ThrowScope = JSC::ThrowScope; using JSC__SourceOrigin = JSC::SourceOrigin; + using JSC__ThrowScope = JSC::ThrowScope; + using JSC__SetIteratorPrototype = JSC::SetIteratorPrototype; using JSC__AsyncGeneratorPrototype = JSC::AsyncGeneratorPrototype; using JSC__PropertyName = JSC::PropertyName; using JSC__MapIteratorPrototype = JSC::MapIteratorPrototype; @@ -242,11 +248,12 @@ CPP_DECL JSC__JSValue JSC__JSObject__create(JSC__JSGlobalObject* arg0, size_t ar CPP_DECL size_t JSC__JSObject__getArrayLength(JSC__JSObject* arg0); CPP_DECL JSC__JSValue JSC__JSObject__getDirect(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, const ZigString* arg2); CPP_DECL JSC__JSValue JSC__JSObject__getIndex(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, uint32_t arg2); -CPP_DECL void JSC__JSObject__putDirect(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, const ZigString* arg2, JSC__JSValue JSValue3); CPP_DECL void JSC__JSObject__putRecord(JSC__JSObject* arg0, JSC__JSGlobalObject* arg1, ZigString* arg2, ZigString* arg3, size_t arg4); +CPP_DECL JSC__JSValue ZigString__to16BitValue(const ZigString* arg0, JSC__JSGlobalObject* arg1); CPP_DECL JSC__JSValue ZigString__toErrorInstance(const ZigString* arg0, JSC__JSGlobalObject* arg1); CPP_DECL JSC__JSValue ZigString__toValue(const ZigString* arg0, JSC__JSGlobalObject* arg1); CPP_DECL JSC__JSValue ZigString__toValueGC(const ZigString* arg0, JSC__JSGlobalObject* arg1); +CPP_DECL JSC__JSValue SystemError__toErrorInstance(const SystemError* arg0, JSC__JSGlobalObject* arg1); #pragma mark - JSC::JSCell @@ -352,6 +359,7 @@ CPP_DECL JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObj CPP_DECL JSC__JSObject* JSC__JSGlobalObject__datePrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__JSObject* JSC__JSGlobalObject__errorPrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__FunctionPrototype* JSC__JSGlobalObject__functionPrototype(JSC__JSGlobalObject* arg0); +CPP_DECL JSC__JSValue JSC__JSGlobalObject__generateHeapSnapshot(JSC__JSGlobalObject* arg0); CPP_DECL JSC__GeneratorFunctionPrototype* JSC__JSGlobalObject__generatorFunctionPrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__GeneratorPrototype* JSC__JSGlobalObject__generatorPrototype(JSC__JSGlobalObject* arg0); CPP_DECL JSC__IteratorPrototype* JSC__JSGlobalObject__iteratorPrototype(JSC__JSGlobalObject* arg0); @@ -422,15 +430,22 @@ CPP_DECL double JSC__JSValue__asNumber(JSC__JSValue JSValue0); CPP_DECL bJSC__JSObject JSC__JSValue__asObject(JSC__JSValue JSValue0); CPP_DECL JSC__JSString* JSC__JSValue__asString(JSC__JSValue JSValue0); CPP_DECL JSC__JSValue JSC__JSValue__createEmptyObject(JSC__JSGlobalObject* arg0, size_t arg1); -CPP_DECL JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject* arg0, ZigString* arg1, size_t arg2); +CPP_DECL JSC__JSValue JSC__JSValue__createObject2(JSC__JSGlobalObject* arg0, const ZigString* arg1, const ZigString* arg2, JSC__JSValue JSValue3, JSC__JSValue JSValue4); +CPP_DECL JSC__JSValue JSC__JSValue__createRangeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); +CPP_DECL JSC__JSValue JSC__JSValue__createStringArray(JSC__JSGlobalObject* arg0, ZigString* arg1, size_t arg2, bool arg3); +CPP_DECL JSC__JSValue JSC__JSValue__createTypeError(const ZigString* arg0, const ZigString* arg1, JSC__JSGlobalObject* arg2); CPP_DECL bool JSC__JSValue__eqlCell(JSC__JSValue JSValue0, JSC__JSCell* arg1); CPP_DECL bool JSC__JSValue__eqlValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1); CPP_DECL void JSC__JSValue__forEach(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, void (* ArgFn2)(JSC__VM* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue JSValue2)); +CPP_DECL JSC__JSValue JSC__JSValue__fromEntries(JSC__JSGlobalObject* arg0, ZigString* arg1, ZigString* arg2, size_t arg3, bool arg4); CPP_DECL void JSC__JSValue__getClassName(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2); CPP_DECL JSC__JSValue JSC__JSValue__getErrorsProperty(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); +CPP_DECL JSC__JSValue JSC__JSValue__getIfPropertyExistsImpl(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, uint32_t arg3); CPP_DECL uint32_t JSC__JSValue__getLengthOfArray(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); CPP_DECL void JSC__JSValue__getNameProperty(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2); CPP_DECL JSC__JSValue JSC__JSValue__getPrototype(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); +CPP_DECL Bun__Readable* JSC__JSValue__getReadableStreamState(JSC__JSValue JSValue0, JSC__VM* arg1); +CPP_DECL Bun__Writable* JSC__JSValue__getWritableStreamState(JSC__JSValue JSValue0, JSC__VM* arg1); CPP_DECL bool JSC__JSValue__isAggregateError(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1); CPP_DECL bool JSC__JSValue__isAnyInt(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isBigInt(JSC__JSValue JSValue0); @@ -451,8 +466,10 @@ CPP_DECL bool JSC__JSValue__isNull(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isNumber(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isObject(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isPrimitive(JSC__JSValue JSValue0); +CPP_DECL bool JSC__JSValue__isSameValue(JSC__JSValue JSValue0, JSC__JSValue JSValue1, JSC__JSGlobalObject* arg2); CPP_DECL bool JSC__JSValue__isString(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isSymbol(JSC__JSValue JSValue0); +CPP_DECL bool JSC__JSValue__isTerminationException(JSC__JSValue JSValue0, JSC__VM* arg1); CPP_DECL bool JSC__JSValue__isUInt32AsAnyInt(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isUndefined(JSC__JSValue JSValue0); CPP_DECL bool JSC__JSValue__isUndefinedOrNull(JSC__JSValue JSValue0); @@ -465,7 +482,9 @@ CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromInt32(int32_t arg0); CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromInt64(int64_t arg0); CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromU16(uint16_t arg0); CPP_DECL JSC__JSValue JSC__JSValue__jsNumberFromUint64(uint64_t arg0); +CPP_DECL void JSC__JSValue__jsonStringify(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, uint32_t arg2, ZigString* arg3); CPP_DECL JSC__JSValue JSC__JSValue__jsTDZValue(); +CPP_DECL unsigned char JSC__JSValue__jsType(JSC__JSValue JSValue0); CPP_DECL JSC__JSValue JSC__JSValue__jsUndefined(); CPP_DECL void JSC__JSValue__putRecord(JSC__JSValue JSValue0, JSC__JSGlobalObject* arg1, ZigString* arg2, ZigString* arg3, size_t arg4); CPP_DECL bool JSC__JSValue__toBoolean(JSC__JSValue JSValue0); @@ -496,14 +515,18 @@ CPP_DECL JSC__JSValue JSC__Exception__value(JSC__Exception* arg0); #pragma mark - JSC::VM CPP_DECL JSC__JSLock* JSC__VM__apiLock(JSC__VM* arg0); +CPP_DECL void JSC__VM__clearExecutionTimeLimit(JSC__VM* arg0); CPP_DECL JSC__VM* JSC__VM__create(unsigned char HeapType0); CPP_DECL void JSC__VM__deinit(JSC__VM* arg0, JSC__JSGlobalObject* arg1); CPP_DECL void JSC__VM__deleteAllCode(JSC__VM* arg0, JSC__JSGlobalObject* arg1); CPP_DECL void JSC__VM__drainMicrotasks(JSC__VM* arg0); CPP_DECL bool JSC__VM__executionForbidden(JSC__VM* arg0); +CPP_DECL void JSC__VM__holdAPILock(JSC__VM* arg0, void* arg1, void (* ArgFn2)(void* arg0)); CPP_DECL bool JSC__VM__isEntered(JSC__VM* arg0); CPP_DECL bool JSC__VM__isJITEnabled(); +CPP_DECL JSC__JSValue JSC__VM__runGC(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); CPP_DECL bool JSC__VM__throwError(JSC__VM* arg0, JSC__JSGlobalObject* arg1, JSC__ThrowScope* arg2, const unsigned char* arg3, size_t arg4); CPP_DECL void JSC__VM__whenIdle(JSC__VM* arg0, void (* ArgFn1)()); @@ -604,6 +627,54 @@ ZIG_DECL void Zig__GlobalObject__resolve(ErrorableZigString* arg0, JSC__JSGlobal ZIG_DECL bool Zig__ErrorType__isPrivateData(void* arg0); #endif + +#pragma mark - Bun__Readable + +CPP_DECL JSC__JSValue Bun__Readable__create(Bun__Readable* arg0, JSC__JSGlobalObject* arg1); + +#ifdef __cplusplus + +ZIG_DECL void Bun__Readable__addEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL void Bun__Readable__deinit(Bun__Readable* arg0); +ZIG_DECL JSC__JSValue Bun__Readable__pause(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Readable__pipe(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL void Bun__Readable__prependEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL JSC__JSValue Bun__Readable__read(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL bool Bun__Readable__removeEventListener(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3); +ZIG_DECL JSC__JSValue Bun__Readable__resume(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Readable__unpipe(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Readable__unshift(Bun__Readable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); + +#endif + +#pragma mark - Bun__Writable + +CPP_DECL JSC__JSValue Bun__Writable__create(Bun__Writable* arg0, JSC__JSGlobalObject* arg1); + +#ifdef __cplusplus + +ZIG_DECL void Bun__Writable__addEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL JSC__JSValue Bun__Writable__close(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Writable__cork(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL void Bun__Writable__deinit(Bun__Writable* arg0); +ZIG_DECL JSC__JSValue Bun__Writable__destroy(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Writable__end(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL void Bun__Writable__prependEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3, bool arg4); +ZIG_DECL bool Bun__Writable__removeEventListener(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, unsigned char Events2, JSC__JSValue JSValue3); +ZIG_DECL JSC__JSValue Bun__Writable__uncork(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); +ZIG_DECL JSC__JSValue Bun__Writable__write(Bun__Writable* arg0, JSC__JSGlobalObject* arg1, JSC__JSValue* arg2, uint16_t arg3); + +#endif + +#ifdef __cplusplus + +ZIG_DECL JSC__JSValue Bun__Process__getArgv(JSC__JSGlobalObject* arg0); +ZIG_DECL JSC__JSValue Bun__Process__getCwd(JSC__JSGlobalObject* arg0); +ZIG_DECL void Bun__Process__getTitle(JSC__JSGlobalObject* arg0, ZigString* arg1); +ZIG_DECL JSC__JSValue Bun__Process__setCwd(JSC__JSGlobalObject* arg0, ZigString* arg1); +ZIG_DECL JSC__JSValue Bun__Process__setTitle(JSC__JSGlobalObject* arg0, ZigString* arg1); + +#endif CPP_DECL ZigException ZigException__fromException(JSC__Exception* arg0); #pragma mark - Zig::ConsoleClient @@ -613,7 +684,7 @@ CPP_DECL ZigException ZigException__fromException(JSC__Exception* arg0); ZIG_DECL void Zig__ConsoleClient__count(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); ZIG_DECL void Zig__ConsoleClient__countReset(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); -ZIG_DECL void Zig__ConsoleClient__messageWithTypeAndLevel(void* arg0, uint32_t arg1, uint32_t arg2, JSC__JSGlobalObject* arg3, JSC__JSValue* arg4, size_t arg5); +ZIG_DECL void Zig__ConsoleClient__messageWithTypeAndLevel(void* arg0, uint32_t MessageType1, uint32_t MessageLevel2, JSC__JSGlobalObject* arg3, JSC__JSValue* arg4, size_t arg5); ZIG_DECL void Zig__ConsoleClient__profile(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); ZIG_DECL void Zig__ConsoleClient__profileEnd(void* arg0, JSC__JSGlobalObject* arg1, const unsigned char* arg2, size_t arg3); ZIG_DECL void Zig__ConsoleClient__record(void* arg0, JSC__JSGlobalObject* arg1, Inspector__ScriptArguments* arg2); diff --git a/src/javascript/jsc/bindings/headers.zig b/src/javascript/jsc/bindings/headers.zig index f5ab2f69a..061fe3d17 100644 --- a/src/javascript/jsc/bindings/headers.zig +++ b/src/javascript/jsc/bindings/headers.zig @@ -53,7 +53,11 @@ pub const ZigStackTrace = bindings.ZigStackTrace; pub const ReturnableException = bindings.ReturnableException; pub const struct_Zig__JSMicrotaskCallback = bindings.Microtask; pub const bZig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; +pub const SystemError = bindings.SystemError; const JSClassRef = bindings.C.JSClassRef; +pub const JSC__CatchScope = bindings.CatchScope; +pub const Bun__Readable = bindings.NodeReadableStream; +pub const Bun__Writable = bindings.NodeWritableStream; // GENERATED CODE - DO NOT MODIFY BY HAND pub const ptrdiff_t = c_long; @@ -68,49 +72,31 @@ pub const __mbstate_t = extern union { _mbstateL: c_longlong, }; -pub const JSC__RegExpPrototype = struct_JSC__RegExpPrototype; - pub const JSC__GeneratorPrototype = struct_JSC__GeneratorPrototype; pub const JSC__ArrayIteratorPrototype = struct_JSC__ArrayIteratorPrototype; -pub const JSC__StringPrototype = struct_JSC__StringPrototype; -pub const WTF__StringView = bWTF__StringView; - pub const JSC__JSPromisePrototype = struct_JSC__JSPromisePrototype; -pub const JSC__CatchScope = bJSC__CatchScope; -pub const JSC__ThrowScope = bJSC__ThrowScope; pub const JSC__PropertyName = bJSC__PropertyName; pub const JSC__JSObject = bJSC__JSObject; pub const WTF__ExternalStringImpl = bWTF__ExternalStringImpl; pub const JSC__AsyncIteratorPrototype = struct_JSC__AsyncIteratorPrototype; -pub const WTF__StringImpl = bWTF__StringImpl; pub const JSC__JSLock = bJSC__JSLock; pub const JSC__JSModuleLoader = bJSC__JSModuleLoader; -pub const JSC__VM = bJSC__VM; pub const JSC__AsyncGeneratorPrototype = struct_JSC__AsyncGeneratorPrototype; pub const JSC__AsyncGeneratorFunctionPrototype = struct_JSC__AsyncGeneratorFunctionPrototype; -pub const JSC__JSGlobalObject = bJSC__JSGlobalObject; -pub const JSC__JSFunction = bJSC__JSFunction; +pub const JSC__Identifier = bJSC__Identifier; pub const JSC__ArrayPrototype = struct_JSC__ArrayPrototype; -pub const JSC__AsyncFunctionPrototype = struct_JSC__AsyncFunctionPrototype; -pub const JSC__Identifier = bJSC__Identifier; +pub const Zig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; pub const JSC__JSPromise = bJSC__JSPromise; pub const JSC__SetIteratorPrototype = struct_JSC__SetIteratorPrototype; -pub const JSC__SourceCode = bJSC__SourceCode; - -pub const Zig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; pub const JSC__JSCell = bJSC__JSCell; - -pub const JSC__BigIntPrototype = struct_JSC__BigIntPrototype; - -pub const JSC__GeneratorFunctionPrototype = struct_JSC__GeneratorFunctionPrototype; pub const JSC__SourceOrigin = bJSC__SourceOrigin; pub const JSC__JSModuleRecord = bJSC__JSModuleRecord; pub const WTF__String = bWTF__String; @@ -119,24 +105,42 @@ pub const WTF__URL = bWTF__URL; pub const JSC__IteratorPrototype = struct_JSC__IteratorPrototype; pub const JSC__JSInternalPromise = bJSC__JSInternalPromise; +pub const JSC__RegExpPrototype = struct_JSC__RegExpPrototype; +pub const JSC__CallFrame = bJSC__CallFrame; + +pub const JSC__MapIteratorPrototype = struct_JSC__MapIteratorPrototype; +pub const WTF__StringView = bWTF__StringView; +pub const JSC__ThrowScope = bJSC__ThrowScope; +pub const WTF__StringImpl = bWTF__StringImpl; +pub const JSC__VM = bJSC__VM; +pub const JSC__JSGlobalObject = bJSC__JSGlobalObject; +pub const JSC__JSFunction = bJSC__JSFunction; + +pub const JSC__AsyncFunctionPrototype = struct_JSC__AsyncFunctionPrototype; +pub const JSC__SourceCode = bJSC__SourceCode; + +pub const JSC__BigIntPrototype = struct_JSC__BigIntPrototype; + +pub const JSC__GeneratorFunctionPrototype = struct_JSC__GeneratorFunctionPrototype; + pub const JSC__FunctionPrototype = struct_JSC__FunctionPrototype; pub const Inspector__ScriptArguments = bInspector__ScriptArguments; pub const JSC__Exception = bJSC__Exception; pub const JSC__JSString = bJSC__JSString; pub const JSC__ObjectPrototype = struct_JSC__ObjectPrototype; -pub const JSC__CallFrame = bJSC__CallFrame; -pub const JSC__MapIteratorPrototype = struct_JSC__MapIteratorPrototype; +pub const JSC__StringPrototype = struct_JSC__StringPrototype; pub extern fn JSC__JSObject__create(arg0: [*c]JSC__JSGlobalObject, arg1: usize, arg2: ?*anyopaque, ArgFn3: ?fn (?*anyopaque, [*c]JSC__JSObject, [*c]JSC__JSGlobalObject) callconv(.C) void) JSC__JSValue; pub extern fn JSC__JSObject__getArrayLength(arg0: [*c]JSC__JSObject) usize; pub extern fn JSC__JSObject__getDirect(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const ZigString) JSC__JSValue; pub extern fn JSC__JSObject__getIndex(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: u32) JSC__JSValue; -pub extern fn JSC__JSObject__putDirect(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const ZigString, JSValue3: JSC__JSValue) void; pub extern fn JSC__JSObject__putRecord(arg0: [*c]JSC__JSObject, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString, arg3: [*c]ZigString, arg4: usize) void; +pub extern fn ZigString__to16BitValue(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigString__toErrorInstance(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigString__toValue(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigString__toValueGC(arg0: [*c]const ZigString, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn SystemError__toErrorInstance(arg0: [*c]const SystemError, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSCell__getObject(arg0: [*c]JSC__JSCell) [*c]JSC__JSObject; pub extern fn JSC__JSCell__getString(arg0: [*c]JSC__JSCell, arg1: [*c]JSC__JSGlobalObject) bWTF__String; pub extern fn JSC__JSCell__getType(arg0: [*c]JSC__JSCell) u8; @@ -209,6 +213,7 @@ pub extern fn JSC__JSGlobalObject__createAggregateError(arg0: [*c]JSC__JSGlobalO pub extern fn JSC__JSGlobalObject__datePrototype(arg0: [*c]JSC__JSGlobalObject) [*c]JSC__JSObject; pub extern fn JSC__JSGlobalObject__errorPrototype(arg0: [*c]JSC__JSGlobalObject) [*c]JSC__JSObject; pub extern fn JSC__JSGlobalObject__functionPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__FunctionPrototype; +pub extern fn JSC__JSGlobalObject__generateHeapSnapshot(arg0: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSGlobalObject__generatorFunctionPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__GeneratorFunctionPrototype; pub extern fn JSC__JSGlobalObject__generatorPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__GeneratorPrototype; pub extern fn JSC__JSGlobalObject__iteratorPrototype(arg0: [*c]JSC__JSGlobalObject) ?*JSC__IteratorPrototype; @@ -270,15 +275,22 @@ pub extern fn JSC__JSValue__asNumber(JSValue0: JSC__JSValue) f64; pub extern fn JSC__JSValue__asObject(JSValue0: JSC__JSValue) bJSC__JSObject; pub extern fn JSC__JSValue__asString(JSValue0: JSC__JSValue) [*c]JSC__JSString; pub extern fn JSC__JSValue__createEmptyObject(arg0: [*c]JSC__JSGlobalObject, arg1: usize) JSC__JSValue; -pub extern fn JSC__JSValue__createStringArray(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: usize) JSC__JSValue; +pub extern fn JSC__JSValue__createObject2(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]const ZigString, arg2: [*c]const ZigString, JSValue3: JSC__JSValue, JSValue4: JSC__JSValue) JSC__JSValue; +pub extern fn JSC__JSValue__createRangeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn JSC__JSValue__createStringArray(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: usize, arg3: bool) JSC__JSValue; +pub extern fn JSC__JSValue__createTypeError(arg0: [*c]const ZigString, arg1: [*c]const ZigString, arg2: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn JSC__JSValue__eqlCell(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSCell) bool; pub extern fn JSC__JSValue__eqlValue(JSValue0: JSC__JSValue, JSValue1: JSC__JSValue) bool; pub extern fn JSC__JSValue__forEach(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, ArgFn2: ?fn ([*c]JSC__VM, [*c]JSC__JSGlobalObject, JSC__JSValue) callconv(.C) void) void; +pub extern fn JSC__JSValue__fromEntries(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]ZigString, arg2: [*c]ZigString, arg3: usize, arg4: bool) JSC__JSValue; pub extern fn JSC__JSValue__getClassName(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString) void; pub extern fn JSC__JSValue__getErrorsProperty(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn JSC__JSValue__getIfPropertyExistsImpl(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]const u8, arg3: u32) JSC__JSValue; pub extern fn JSC__JSValue__getLengthOfArray(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) u32; pub extern fn JSC__JSValue__getNameProperty(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString) void; pub extern fn JSC__JSValue__getPrototype(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn JSC__JSValue__getReadableStreamState(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) [*c]Bun__Readable; +pub extern fn JSC__JSValue__getWritableStreamState(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) [*c]Bun__Writable; pub extern fn JSC__JSValue__isAggregateError(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject) bool; pub extern fn JSC__JSValue__isAnyInt(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isBigInt(JSValue0: JSC__JSValue) bool; @@ -299,8 +311,10 @@ pub extern fn JSC__JSValue__isNull(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isNumber(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isObject(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isPrimitive(JSValue0: JSC__JSValue) bool; +pub extern fn JSC__JSValue__isSameValue(JSValue0: JSC__JSValue, JSValue1: JSC__JSValue, arg2: [*c]JSC__JSGlobalObject) bool; pub extern fn JSC__JSValue__isString(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isSymbol(JSValue0: JSC__JSValue) bool; +pub extern fn JSC__JSValue__isTerminationException(JSValue0: JSC__JSValue, arg1: [*c]JSC__VM) bool; pub extern fn JSC__JSValue__isUInt32AsAnyInt(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isUndefined(JSValue0: JSC__JSValue) bool; pub extern fn JSC__JSValue__isUndefinedOrNull(JSValue0: JSC__JSValue) bool; @@ -313,7 +327,9 @@ pub extern fn JSC__JSValue__jsNumberFromInt32(arg0: i32) JSC__JSValue; pub extern fn JSC__JSValue__jsNumberFromInt64(arg0: i64) JSC__JSValue; pub extern fn JSC__JSValue__jsNumberFromU16(arg0: u16) JSC__JSValue; pub extern fn JSC__JSValue__jsNumberFromUint64(arg0: u64) JSC__JSValue; +pub extern fn JSC__JSValue__jsonStringify(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: u32, arg3: [*c]ZigString) void; pub extern fn JSC__JSValue__jsTDZValue(...) JSC__JSValue; +pub extern fn JSC__JSValue__jsType(JSValue0: JSC__JSValue) u8; pub extern fn JSC__JSValue__jsUndefined(...) JSC__JSValue; pub extern fn JSC__JSValue__putRecord(JSValue0: JSC__JSValue, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]ZigString, arg3: [*c]ZigString, arg4: usize) void; pub extern fn JSC__JSValue__toBoolean(JSValue0: JSC__JSValue) bool; @@ -334,14 +350,18 @@ pub extern fn JSC__Exception__create(arg0: [*c]JSC__JSGlobalObject, arg1: [*c]JS pub extern fn JSC__Exception__getStackTrace(arg0: [*c]JSC__Exception, arg1: [*c]ZigStackTrace) void; pub extern fn JSC__Exception__value(arg0: [*c]JSC__Exception) JSC__JSValue; pub extern fn JSC__VM__apiLock(arg0: [*c]JSC__VM) [*c]JSC__JSLock; +pub extern fn JSC__VM__clearExecutionTimeLimit(arg0: [*c]JSC__VM) void; pub extern fn JSC__VM__create(HeapType0: u8) [*c]JSC__VM; pub extern fn JSC__VM__deinit(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject) void; pub extern fn JSC__VM__deleteAllCode(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject) void; pub extern fn JSC__VM__drainMicrotasks(arg0: [*c]JSC__VM) void; pub extern fn JSC__VM__executionForbidden(arg0: [*c]JSC__VM) bool; +pub extern fn JSC__VM__holdAPILock(arg0: [*c]JSC__VM, arg1: ?*anyopaque, ArgFn2: ?fn (?*anyopaque) callconv(.C) void) void; pub extern fn JSC__VM__isEntered(arg0: [*c]JSC__VM) bool; pub extern fn JSC__VM__isJITEnabled(...) bool; +pub extern fn JSC__VM__runGC(arg0: [*c]JSC__VM, arg1: bool) JSC__JSValue; pub extern fn JSC__VM__setExecutionForbidden(arg0: [*c]JSC__VM, arg1: bool) void; +pub extern fn JSC__VM__setExecutionTimeLimit(arg0: [*c]JSC__VM, arg1: f64) void; pub extern fn JSC__VM__shrinkFootprint(arg0: [*c]JSC__VM) void; pub extern fn JSC__VM__throwError(arg0: [*c]JSC__VM, arg1: [*c]JSC__JSGlobalObject, arg2: [*c]JSC__ThrowScope, arg3: [*c]const u8, arg4: usize) bool; pub extern fn JSC__VM__whenIdle(arg0: [*c]JSC__VM, ArgFn1: ?fn (...) callconv(.C) void) void; @@ -399,4 +419,6 @@ pub extern fn WTF__StringView__length(arg0: [*c]const WTF__StringView) usize; pub extern fn Zig__GlobalObject__create(arg0: [*c]JSClassRef, arg1: i32, arg2: ?*anyopaque) [*c]JSC__JSGlobalObject; pub extern fn Zig__GlobalObject__getModuleRegistryMap(arg0: [*c]JSC__JSGlobalObject) ?*anyopaque; pub extern fn Zig__GlobalObject__resetModuleRegistryMap(arg0: [*c]JSC__JSGlobalObject, arg1: ?*anyopaque) bool; +pub extern fn Bun__Readable__create(arg0: [*c]Bun__Readable, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; +pub extern fn Bun__Writable__create(arg0: [*c]Bun__Writable, arg1: [*c]JSC__JSGlobalObject) JSC__JSValue; pub extern fn ZigException__fromException(arg0: [*c]JSC__Exception) ZigException; diff --git a/src/javascript/jsc/bindings/helpers.h b/src/javascript/jsc/bindings/helpers.h index 73582d1dc..1c1237969 100644 --- a/src/javascript/jsc/bindings/helpers.h +++ b/src/javascript/jsc/bindings/helpers.h @@ -1,3 +1,5 @@ +#pragma once + #include "headers.h" #include "root.h" @@ -10,8 +12,6 @@ #include <JavaScriptCore/ThrowScope.h> #include <JavaScriptCore/VM.h> -#pragma once - template <class CppType, typename ZigType> class Wrap { public: Wrap(){}; @@ -72,46 +72,90 @@ static const JSC::Identifier toIdentifier(ZigString str, JSC::JSGlobalObject *gl return JSC::Identifier::fromString(global->vm(), str.ptr, str.len); } +static bool isTaggedUTF16Ptr(const unsigned char *ptr) { + return (reinterpret_cast<uintptr_t>(ptr) & (static_cast<uint64_t>(1) << 63)) != 0; +} + +static bool isTaggedExternalPtr(const unsigned char *ptr) { + return (reinterpret_cast<uintptr_t>(ptr) & (static_cast<uint64_t>(1) << 62)) != 0; +} + static const WTF::String toString(ZigString str) { if (str.len == 0 || str.ptr == nullptr) { return WTF::String(); } - return WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len)); + return !isTaggedUTF16Ptr(str.ptr) + ? WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len)) + : WTF::String(WTF::StringImpl::createWithoutCopying( + reinterpret_cast<const UChar *>(str.ptr), str.len)); } static const WTF::String toStringCopy(ZigString str) { if (str.len == 0 || str.ptr == nullptr) { return WTF::String(); } - return WTF::String(WTF::StringImpl::create(str.ptr, str.len)); + return !isTaggedUTF16Ptr(str.ptr) ? WTF::String(WTF::StringImpl::create(str.ptr, str.len)) + : WTF::String(WTF::StringImpl::create( + reinterpret_cast<const UChar *>(str.ptr), str.len)); } static WTF::String toStringNotConst(ZigString str) { if (str.len == 0 || str.ptr == nullptr) { return WTF::String(); } - return WTF::String(WTF::StringImpl::createWithoutCopying(str.ptr, str.len)); + return !isTaggedUTF16Ptr(str.ptr) ? WTF::String(WTF::StringImpl::create(str.ptr, str.len)) + : WTF::String(WTF::StringImpl::create( + reinterpret_cast<const UChar *>(str.ptr), str.len)); } static const JSC::JSString *toJSString(ZigString str, JSC::JSGlobalObject *global) { return JSC::jsOwnedString(global->vm(), toString(str)); } +static const JSC::JSValue toJSStringValue(ZigString str, JSC::JSGlobalObject *global) { + return JSC::JSValue(toJSString(str, global)); +} + +static const JSC::JSString *toJSStringGC(ZigString str, JSC::JSGlobalObject *global) { + return JSC::jsString(global->vm(), toStringCopy(str)); +} + +static const JSC::JSValue toJSStringValueGC(ZigString str, JSC::JSGlobalObject *global) { + return JSC::JSValue(toJSString(str, global)); +} + static const ZigString ZigStringEmpty = ZigString{nullptr, 0}; static const unsigned char __dot_char = '.'; static const ZigString ZigStringCwd = ZigString{&__dot_char, 1}; +static const unsigned char *taggedUTF16Ptr(const UChar *ptr) { + return reinterpret_cast<const unsigned char *>(reinterpret_cast<uintptr_t>(ptr) | + (static_cast<uint64_t>(1) << 63)); +} + static ZigString toZigString(WTF::String str) { - return str.isEmpty() ? ZigStringEmpty : ZigString{str.characters8(), str.length()}; + return str.isEmpty() + ? ZigStringEmpty + : ZigString{str.is8Bit() ? str.characters8() : taggedUTF16Ptr(str.characters16()), + str.length()}; } static ZigString toZigString(WTF::String *str) { - return str->isEmpty() ? ZigStringEmpty : ZigString{str->characters8(), str->length()}; + return str->isEmpty() + ? ZigStringEmpty + : ZigString{str->is8Bit() ? str->characters8() : taggedUTF16Ptr(str->characters16()), + str->length()}; } static ZigString toZigString(WTF::StringImpl &str) { - return str.isEmpty() ? ZigStringEmpty : ZigString{str.characters8(), str.length()}; + return str.isEmpty() + ? ZigStringEmpty + : ZigString{str.is8Bit() ? str.characters8() : taggedUTF16Ptr(str.characters16()), + str.length()}; } static ZigString toZigString(WTF::StringView &str) { - return str.isEmpty() ? ZigStringEmpty : ZigString{str.characters8(), str.length()}; + return str.isEmpty() + ? ZigStringEmpty + : ZigString{str.is8Bit() ? str.characters8() : taggedUTF16Ptr(str.characters16()), + str.length()}; } static ZigString toZigString(JSC::JSString &str, JSC::JSGlobalObject *global) { @@ -152,4 +196,19 @@ static ZigString toZigString(JSC::JSValue val, JSC::JSGlobalObject *global) { return toZigString(str); } +static JSC::JSValue getErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) { + JSC::VM &vm = globalObject->vm(); + + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::JSValue message = Zig::toJSString(*str, globalObject); + JSC::JSValue options = JSC::jsUndefined(); + JSC::Structure *errorStructure = globalObject->errorStructure(); + JSC::JSObject *result = + JSC::ErrorInstance::create(globalObject, errorStructure, message, options); + RETURN_IF_EXCEPTION(scope, JSC::JSValue()); + scope.release(); + + return JSC::JSValue(result); +} + }; // namespace Zig diff --git a/src/javascript/jsc/fs.exports.js b/src/javascript/jsc/fs.exports.js new file mode 100644 index 000000000..923ef9801 --- /dev/null +++ b/src/javascript/jsc/fs.exports.js @@ -0,0 +1,77 @@ +var fs = Bun.fs(); +export default fs; +export var access = fs.access.bind(fs); +export var appendFile = fs.appendFile.bind(fs); +export var close = fs.close.bind(fs); +export var copyFile = fs.copyFile.bind(fs); +export var exists = fs.exists.bind(fs); +export var chown = fs.chown.bind(fs); +export var chmod = fs.chmod.bind(fs); +export var fchmod = fs.fchmod.bind(fs); +export var fchown = fs.fchown.bind(fs); +export var fstat = fs.fstat.bind(fs); +export var fsync = fs.fsync.bind(fs); +export var ftruncate = fs.ftruncate.bind(fs); +export var futimes = fs.futimes.bind(fs); +export var lchmod = fs.lchmod.bind(fs); +export var lchown = fs.lchown.bind(fs); +export var link = fs.link.bind(fs); +export var lstat = fs.lstat.bind(fs); +export var mkdir = fs.mkdir.bind(fs); +export var mkdtemp = fs.mkdtemp.bind(fs); +export var open = fs.open.bind(fs); +export var read = fs.read.bind(fs); +export var write = fs.write.bind(fs); +export var readdir = fs.readdir.bind(fs); +export var readFile = fs.readFile.bind(fs); +export var writeFile = fs.writeFile.bind(fs); +export var readlink = fs.readlink.bind(fs); +export var realpath = fs.realpath.bind(fs); +export var rename = fs.rename.bind(fs); +export var stat = fs.stat.bind(fs); +export var symlink = fs.symlink.bind(fs); +export var truncate = fs.truncate.bind(fs); +export var unlink = fs.unlink.bind(fs); +export var utimes = fs.utimes.bind(fs); +export var lutimes = fs.lutimes.bind(fs); +export var accessSync = fs.accessSync.bind(fs); +export var appendFileSync = fs.appendFileSync.bind(fs); +export var closeSync = fs.closeSync.bind(fs); +export var copyFileSync = fs.copyFileSync.bind(fs); +export var existsSync = fs.existsSync.bind(fs); +export var chownSync = fs.chownSync.bind(fs); +export var chmodSync = fs.chmodSync.bind(fs); +export var fchmodSync = fs.fchmodSync.bind(fs); +export var fchownSync = fs.fchownSync.bind(fs); +export var fstatSync = fs.fstatSync.bind(fs); +export var fsyncSync = fs.fsyncSync.bind(fs); +export var ftruncateSync = fs.ftruncateSync.bind(fs); +export var futimesSync = fs.futimesSync.bind(fs); +export var lchmodSync = fs.lchmodSync.bind(fs); +export var lchownSync = fs.lchownSync.bind(fs); +export var linkSync = fs.linkSync.bind(fs); +export var lstatSync = fs.lstatSync.bind(fs); +export var mkdirSync = fs.mkdirSync.bind(fs); +export var mkdtempSync = fs.mkdtempSync.bind(fs); +export var openSync = fs.openSync.bind(fs); +export var readSync = fs.readSync.bind(fs); +export var writeSync = fs.writeSync.bind(fs); +export var readdirSync = fs.readdirSync.bind(fs); +export var readFileSync = fs.readFileSync.bind(fs); +export var writeFileSync = fs.writeFileSync.bind(fs); +export var readlinkSync = fs.readlinkSync.bind(fs); +export var realpathSync = fs.realpathSync.bind(fs); +export var renameSync = fs.renameSync.bind(fs); +export var statSync = fs.statSync.bind(fs); +export var symlinkSync = fs.symlinkSync.bind(fs); +export var truncateSync = fs.truncateSync.bind(fs); +export var unlinkSync = fs.unlinkSync.bind(fs); +export var utimesSync = fs.utimesSync.bind(fs); +export var lutimesSync = fs.lutimesSync.bind(fs); + +export var createReadStream = fs.createReadStream.bind(fs); +export var createWriteStream = fs.createWriteStream.bind(fs); + +// lol +realpath.native = realpath; +realpathSync.native = realpathSync; diff --git a/src/javascript/jsc/javascript.zig b/src/javascript/jsc/javascript.zig index d571def15..64147bc5c 100644 --- a/src/javascript/jsc/javascript.zig +++ b/src/javascript/jsc/javascript.zig @@ -36,7 +36,7 @@ const http = @import("../../http.zig"); const NodeFallbackModules = @import("../../node_fallbacks.zig"); const ImportKind = ast.ImportKind; const Analytics = @import("../../analytics/analytics_thread.zig"); -const ZigString = @import("javascript_core").ZigString; +const ZigString = @import("../../jsc.zig").ZigString; const Runtime = @import("../../runtime.zig"); const Router = @import("./api/router.zig"); const ImportRecord = ast.ImportRecord; @@ -44,36 +44,37 @@ const DotEnv = @import("../../env_loader.zig"); const ParseResult = @import("../../bundler.zig").ParseResult; const PackageJSON = @import("../../resolver/package_json.zig").PackageJSON; const MacroRemap = @import("../../resolver/package_json.zig").MacroMap; -const WebCore = @import("javascript_core").WebCore; +const WebCore = @import("../../jsc.zig").WebCore; const Request = WebCore.Request; const Response = WebCore.Response; const Headers = WebCore.Headers; const Fetch = WebCore.Fetch; const FetchEvent = WebCore.FetchEvent; -const js = @import("javascript_core").C; +const js = @import("../../jsc.zig").C; const JSError = @import("./base.zig").JSError; const d = @import("./base.zig").d; const MarkedArrayBuffer = @import("./base.zig").MarkedArrayBuffer; const getAllocator = @import("./base.zig").getAllocator; -const JSValue = @import("javascript_core").JSValue; +const JSValue = @import("../../jsc.zig").JSValue; const NewClass = @import("./base.zig").NewClass; -const Microtask = @import("javascript_core").Microtask; -const JSGlobalObject = @import("javascript_core").JSGlobalObject; -const ExceptionValueRef = @import("javascript_core").ExceptionValueRef; -const JSPrivateDataPtr = @import("javascript_core").JSPrivateDataPtr; -const ZigConsoleClient = @import("javascript_core").ZigConsoleClient; -const ZigException = @import("javascript_core").ZigException; -const ZigStackTrace = @import("javascript_core").ZigStackTrace; -const ErrorableResolvedSource = @import("javascript_core").ErrorableResolvedSource; -const ResolvedSource = @import("javascript_core").ResolvedSource; -const JSPromise = @import("javascript_core").JSPromise; -const JSInternalPromise = @import("javascript_core").JSInternalPromise; -const JSModuleLoader = @import("javascript_core").JSModuleLoader; -const JSPromiseRejectionOperation = @import("javascript_core").JSPromiseRejectionOperation; -const Exception = @import("javascript_core").Exception; -const ErrorableZigString = @import("javascript_core").ErrorableZigString; -const ZigGlobalObject = @import("javascript_core").ZigGlobalObject; -const VM = @import("javascript_core").VM; +const Microtask = @import("../../jsc.zig").Microtask; +const JSGlobalObject = @import("../../jsc.zig").JSGlobalObject; +const ExceptionValueRef = @import("../../jsc.zig").ExceptionValueRef; +const JSPrivateDataPtr = @import("../../jsc.zig").JSPrivateDataPtr; +const ZigConsoleClient = @import("../../jsc.zig").ZigConsoleClient; +const Node = @import("../../jsc.zig").Node; +const ZigException = @import("../../jsc.zig").ZigException; +const ZigStackTrace = @import("../../jsc.zig").ZigStackTrace; +const ErrorableResolvedSource = @import("../../jsc.zig").ErrorableResolvedSource; +const ResolvedSource = @import("../../jsc.zig").ResolvedSource; +const JSPromise = @import("../../jsc.zig").JSPromise; +const JSInternalPromise = @import("../../jsc.zig").JSInternalPromise; +const JSModuleLoader = @import("../../jsc.zig").JSModuleLoader; +const JSPromiseRejectionOperation = @import("../../jsc.zig").JSPromiseRejectionOperation; +const Exception = @import("../../jsc.zig").Exception; +const ErrorableZigString = @import("../../jsc.zig").ErrorableZigString; +const ZigGlobalObject = @import("../../jsc.zig").ZigGlobalObject; +const VM = @import("../../jsc.zig").VM; const Config = @import("./config.zig"); const URL = @import("../../query_string_map.zig").URL; pub const GlobalClasses = [_]type{ @@ -92,6 +93,8 @@ pub const GlobalClasses = [_]type{ Bun.EnvironmentVariables.Class, }; const Blob = @import("../../blob.zig"); +pub const Buffer = MarkedArrayBuffer; +const Lock = @import("../../lock.zig").Lock; pub const Bun = struct { threadlocal var css_imports_list_strings: [512]ZigString = undefined; @@ -183,22 +186,22 @@ pub const Bun = struct { pub fn getCWD( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.bundler.fs.top_level_dir).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.bundler.fs.top_level_dir).toValue(ctx.ptr()).asRef(); } pub fn getOrigin( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.origin.origin).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.origin.origin).toValue(ctx.ptr()).asRef(); } pub fn enableANSIColors( @@ -212,22 +215,22 @@ pub const Bun = struct { } pub fn getMain( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.main).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.main).toValue(ctx.ptr()).asRef(); } pub fn getAssetPrefix( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(VirtualMachine.vm.bundler.options.routes.asset_prefix_path).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.bundler.options.routes.asset_prefix_path).toValue(ctx.ptr()).asRef(); } pub fn getArgv( @@ -249,7 +252,7 @@ pub const Bun = struct { argv[i] = ZigString.init(std.mem.span(arg)); } - return JSValue.createStringArray(VirtualMachine.vm.global, argv.ptr, argv.len).asObjectRef(); + return JSValue.createStringArray(ctx.ptr(), argv.ptr, argv.len, true).asObjectRef(); } pub fn getRoutesDir( @@ -263,7 +266,7 @@ pub const Bun = struct { return js.JSValueMakeUndefined(ctx); } - return ZigString.init(VirtualMachine.vm.bundler.options.routes.dir).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(VirtualMachine.vm.bundler.options.routes.dir).toValue(ctx.ptr()).asRef(); } pub fn getFilePath(ctx: js.JSContextRef, arguments: []const js.JSValueRef, buf: []u8, exception: js.ExceptionRef) ?string { @@ -275,7 +278,7 @@ pub const Bun = struct { const value = arguments[0]; if (js.JSValueIsString(ctx, value)) { var out = ZigString.Empty; - JSValue.toZigString(JSValue.fromRef(value), &out, VirtualMachine.vm.global); + JSValue.toZigString(JSValue.fromRef(value), &out, ctx.ptr()); var out_slice = out.slice(); // The dots are kind of unnecessary. They'll be normalized. @@ -298,7 +301,7 @@ pub const Bun = struct { } } - var iter = JSValue.fromRef(value).arrayIterator(VirtualMachine.vm.global); + var iter = JSValue.fromRef(value).arrayIterator(ctx.ptr()); while (iter.next()) |item| { if (temp_strings_list_len >= temp_strings_list.len) { break; @@ -310,7 +313,7 @@ pub const Bun = struct { } var out = ZigString.Empty; - JSValue.toZigString(item, &out, VirtualMachine.vm.global); + JSValue.toZigString(item, &out, ctx.ptr()); const out_slice = out.slice(); temp_strings_list[temp_strings_list_len] = out_slice; @@ -348,7 +351,7 @@ pub const Bun = struct { return js.JSObjectMakeArray(ctx, 0, null, null); } - return JSValue.createStringArray(VirtualMachine.vm.global, styles.ptr, styles.len).asRef(); + return JSValue.createStringArray(ctx.ptr(), styles.ptr, styles.len, true).asRef(); } pub fn readFileAsStringCallback( @@ -450,7 +453,7 @@ pub const Bun = struct { routes_list_strings[i] = ZigString.init(list[i]); } - const ref = JSValue.createStringArray(VirtualMachine.vm.global, &routes_list_strings, list.len).asRef(); + const ref = JSValue.createStringArray(ctx.ptr(), &routes_list_strings, list.len, true).asRef(); return ref; } @@ -471,7 +474,7 @@ pub const Bun = struct { routes_list_strings[i] = ZigString.init(list[i]); } - const ref = JSValue.createStringArray(VirtualMachine.vm.global, &routes_list_strings, list.len).asRef(); + const ref = JSValue.createStringArray(ctx.ptr(), &routes_list_strings, list.len, true).asRef(); return ref; } @@ -534,32 +537,85 @@ pub const Bun = struct { _: js.ExceptionRef, ) js.JSValueRef { if (js.JSValueIsNumber(ctx, arguments[0])) { - const ms = JSValue.fromRef(arguments[0]).asNumber(); - if (ms > 0 and std.math.isFinite(ms)) std.time.sleep(@floatToInt(u64, @floor(@floatCast(f128, ms) * std.time.ns_per_ms))); + const seconds = JSValue.fromRef(arguments[0]).asNumber(); + if (seconds > 0 and std.math.isFinite(seconds)) std.time.sleep(@floatToInt(u64, seconds * 1000) * std.time.ns_per_ms); } return js.JSValueMakeUndefined(ctx); } + pub fn createNodeFS( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + return Node.NodeFSBindings.make( + ctx, + VirtualMachine.vm.node_fs orelse brk: { + VirtualMachine.vm.node_fs = _global.default_allocator.create(Node.NodeFS) catch unreachable; + VirtualMachine.vm.node_fs.?.* = Node.NodeFS{ .async_io = undefined }; + break :brk VirtualMachine.vm.node_fs.?; + }, + ); + } + + pub fn generateHeapSnapshot( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + return ctx.ptr().generateHeapSnapshot().asObjectRef(); + } + + pub fn runGC( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + Global.mimalloc_cleanup(true); + return ctx.ptr().vm().runGC(arguments.len > 0 and JSValue.fromRef(arguments[0]).toBoolean()).asRef(); + } + + pub fn shrink( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + ctx.ptr().vm().shrinkFootprint(); + return JSValue.jsUndefined().asRef(); + } + var public_path_temp_str: [std.fs.MAX_PATH_BYTES]u8 = undefined; pub fn getPublicPathJS( _: void, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, arguments: []const js.JSValueRef, _: js.ExceptionRef, ) js.JSValueRef { var zig_str: ZigString = ZigString.Empty; - JSValue.toZigString(JSValue.fromRef(arguments[0]), &zig_str, VirtualMachine.vm.global); + JSValue.toZigString(JSValue.fromRef(arguments[0]), &zig_str, ctx.ptr()); const to = zig_str.slice(); var stream = std.io.fixedBufferStream(&public_path_temp_str); var writer = stream.writer(); getPublicPath(to, VirtualMachine.vm.origin, @TypeOf(&writer), &writer); - return ZigString.init(stream.buffer[0..stream.pos]).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(stream.buffer[0..stream.pos]).toValueGC(ctx.ptr()).asRef(); } pub const Class = NewClass( @@ -579,6 +635,9 @@ pub const Bun = struct { .rfn = Router.match, .ts = Router.match_type_definition, }, + .__debug__doSegfault = .{ + .rfn = Bun.__debug__doSegfault, + }, .sleepSync = .{ .rfn = sleepSync, }, @@ -635,6 +694,26 @@ pub const Bun = struct { .@"return" = "undefined", }, }, + .fs = .{ + .rfn = Bun.createNodeFS, + .ts = d.ts{}, + }, + .jest = .{ + .rfn = @import("./test/jest.zig").Jest.call, + .ts = d.ts{}, + }, + .gc = .{ + .rfn = Bun.runGC, + .ts = d.ts{}, + }, + .generateHeapSnapshot = .{ + .rfn = Bun.generateHeapSnapshot, + .ts = d.ts{}, + }, + .shrink = .{ + .rfn = Bun.shrink, + .ts = d.ts{}, + }, }, .{ .main = .{ @@ -670,6 +749,21 @@ pub const Bun = struct { }, ); + // For testing the segfault handler + pub fn __debug__doSegfault( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + _ = ctx; + var seggy: *VirtualMachine = undefined; + seggy.printErrorInstance(undefined, undefined, false) catch unreachable; + return JSValue.jsUndefined().asRef(); + } + /// EnvironmentVariables is runtime defined. /// Also, you can't iterate over process.env normally since it only exists at build-time otherwise // This is aliased to Bun.env @@ -684,12 +778,23 @@ pub const Bun = struct { .getProperty = .{ .rfn = getProperty, }, - // .hasProperty = .{ - // .rfn = hasProperty, - // }, + .setProperty = .{ + .rfn = setProperty, + }, + .deleteProperty = .{ + .rfn = deleteProperty, + }, + .convertToType = .{ .rfn = convertToType }, + .hasProperty = .{ + .rfn = hasProperty, + }, .getPropertyNames = .{ .rfn = getPropertyNames, }, + .toJSON = .{ + .rfn = toJSON, + .name = "toJSON", + }, }, .{}, ); @@ -719,19 +824,87 @@ pub const Bun = struct { var ptr = js.JSStringGetCharacters8Ptr(propertyName); var name = ptr[0..len]; if (VirtualMachine.vm.bundler.env.map.get(name)) |value| { - return ZigString.toRef(value, VirtualMachine.vm.global); + return ZigString.toRef(value, ctx.ptr()); } if (Output.enable_ansi_colors) { // https://github.com/chalk/supports-color/blob/main/index.js if (strings.eqlComptime(name, "FORCE_COLOR")) { - return ZigString.toRef(BooleanString.@"true", VirtualMachine.vm.global); + return ZigString.toRef(BooleanString.@"true", ctx.ptr()); } } return js.JSValueMakeUndefined(ctx); } + pub fn toJSON( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + _: []const js.JSValueRef, + _: js.ExceptionRef, + ) js.JSValueRef { + var map = VirtualMachine.vm.bundler.env.map.map; + var keys = map.keys(); + var values = map.values(); + const StackFallback = std.heap.StackFallbackAllocator(32 * 2 * @sizeOf(ZigString)); + var stack = StackFallback{ + .buffer = undefined, + .fallback_allocator = _global.default_allocator, + .fixed_buffer_allocator = undefined, + }; + var allocator = stack.get(); + var key_strings_ = allocator.alloc(ZigString, keys.len * 2) catch unreachable; + var key_strings = key_strings_[0..keys.len]; + var value_strings = key_strings_[keys.len..]; + + for (keys) |key, i| { + key_strings[i] = ZigString.init(key); + key_strings[i].detectEncoding(); + value_strings[i] = ZigString.init(values[i]); + value_strings[i].detectEncoding(); + } + + var result = JSValue.fromEntries(ctx.ptr(), key_strings.ptr, value_strings.ptr, keys.len, false).asObjectRef(); + allocator.free(key_strings_); + return result; + // } + // ZigConsoleClient.Formatter.format(this: *Formatter, result: Tag.Result, comptime Writer: type, writer: Writer, value: JSValue, globalThis: *JSGlobalObject, comptime enable_ansi_colors: bool) + } + + pub fn deleteProperty( + _: js.JSContextRef, + _: js.JSObjectRef, + propertyName: js.JSStringRef, + _: js.ExceptionRef, + ) callconv(.C) bool { + const len = js.JSStringGetLength(propertyName); + var ptr = js.JSStringGetCharacters8Ptr(propertyName); + var name = ptr[0..len]; + _ = VirtualMachine.vm.bundler.env.map.map.swapRemove(name); + return true; + } + + pub fn setProperty( + ctx: js.JSContextRef, + _: js.JSObjectRef, + propertyName: js.JSStringRef, + value: js.JSValueRef, + exception: js.ExceptionRef, + ) callconv(.C) bool { + const len = js.JSStringGetLength(propertyName); + var ptr = js.JSStringGetCharacters8Ptr(propertyName); + var name = ptr[0..len]; + var val = ZigString.init(""); + JSValue.fromRef(value).toZigString(&val, ctx.ptr()); + if (exception.* != null) return false; + var result = std.fmt.allocPrint(VirtualMachine.vm.allocator, "{}", .{val}) catch unreachable; + VirtualMachine.vm.bundler.env.map.put(name, result) catch unreachable; + + return true; + } + pub fn hasProperty( _: js.JSContextRef, _: js.JSObjectRef, @@ -743,6 +916,14 @@ pub const Bun = struct { return VirtualMachine.vm.bundler.env.map.get(name) != null or (Output.enable_ansi_colors and strings.eqlComptime(name, "FORCE_COLOR")); } + pub fn convertToType(ctx: js.JSContextRef, obj: js.JSObjectRef, kind: js.JSType, exception: js.ExceptionRef) callconv(.C) js.JSValueRef { + _ = ctx; + _ = obj; + _ = kind; + _ = exception; + return obj; + } + pub fn getPropertyNames( _: js.JSContextRef, _: js.JSObjectRef, @@ -758,6 +939,16 @@ pub const Bun = struct { }; }; +pub const OpaqueCallback = fn (current: ?*anyopaque) callconv(.C) void; +pub fn OpaqueWrap(comptime Context: type, comptime Function: fn (this: *Context) void) OpaqueCallback { + return struct { + pub fn callback(ctx: ?*anyopaque) callconv(.C) void { + var context: *Context = @ptrCast(*Context, @alignCast(@alignOf(Context), ctx.?)); + @call(.{}, Function, .{context}); + } + }.callback; +} + pub const Performance = struct { pub const Class = NewClass( void, @@ -801,6 +992,7 @@ const TaggedPointerUnion = @import("../../tagged_pointer.zig").TaggedPointerUnio pub const Task = TaggedPointerUnion(.{ FetchTasklet, Microtask, + // TimeoutTasklet, }); // If you read JavascriptCore/API/JSVirtualMachine.mm - https://github.com/WebKit/WebKit/blob/acff93fb303baa670c055cb24c2bad08691a01a0/Source/JavaScriptCore/API/JSVirtualMachine.mm#L101 @@ -817,10 +1009,11 @@ pub const VirtualMachine = struct { event_listeners: EventListenerMixin.Map, main: string = "", process: js.JSObjectRef = null, - blobs: *Blob.Group = undefined, + blobs: ?*Blob.Group = null, flush_list: std.ArrayList(string), entry_point: ServerEntryPoint = undefined, origin: URL = URL{}, + node_fs: ?*Node.NodeFS = null, arena: *std.heap.ArenaAllocator = undefined, has_loaded: bool = false, @@ -834,79 +1027,108 @@ pub const VirtualMachine = struct { macro_mode: bool = false, has_any_macro_remappings: bool = false, + is_from_devserver: bool = false, + has_enabled_macro_mode: bool = false, + argv: []const []const u8 = &[_][]const u8{"bun"}, origin_timer: std.time.Timer = undefined, macro_event_loop: EventLoop = EventLoop{}, regular_event_loop: EventLoop = EventLoop{}, + event_loop: *EventLoop = undefined, pub inline fn eventLoop(this: *VirtualMachine) *EventLoop { - return if (this.macro_mode) - return &this.macro_event_loop - else - return &this.regular_event_loop; + return this.event_loop; } const EventLoop = struct { ready_tasks_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), pending_tasks_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), - tasks: std.ArrayList(Task) = std.ArrayList(Task).init(default_allocator), + io_tasks_count: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0), + tasks: Queue = undefined, + concurrent_tasks: Queue = undefined, + concurrent_lock: Lock = Lock.init(), + pub const Queue = std.fifo.LinearFifo(Task, .Dynamic); pub fn tickWithCount(this: *EventLoop) u32 { var finished: u32 = 0; - var i: usize = 0; var global = VirtualMachine.vm.global; - while (i < this.tasks.items.len) { - var task: Task = this.tasks.items[i]; + while (this.tasks.readItem()) |task| { switch (task.tag()) { .Microtask => { - var micro: *Microtask = task.get(Microtask).?; - _ = this.tasks.swapRemove(i); - _ = this.pending_tasks_count.fetchSub(1, .Monotonic); + var micro: *Microtask = task.as(Microtask); micro.run(global); - finished += 1; - continue; }, .FetchTasklet => { var fetch_task: *Fetch.FetchTasklet = task.get(Fetch.FetchTasklet).?; - if (fetch_task.status == .done) { - _ = this.ready_tasks_count.fetchSub(1, .Monotonic); - _ = this.pending_tasks_count.fetchSub(1, .Monotonic); - _ = this.tasks.swapRemove(i); - fetch_task.onDone(); - finished += 1; - continue; - } + fetch_task.onDone(); + finished += 1; }, else => unreachable, } - i += 1; } + + if (finished > 0) { + _ = this.pending_tasks_count.fetchSub(finished, .Monotonic); + } + return finished; } + pub fn tickConcurrent(this: *EventLoop) void { + if (this.ready_tasks_count.load(.Monotonic) > 0) { + this.concurrent_lock.lock(); + defer this.concurrent_lock.unlock(); + var add: u32 = 0; + + // TODO: optimzie + this.tasks.ensureUnusedCapacity(this.concurrent_tasks.readableLength()) catch unreachable; + while (this.concurrent_tasks.readItem()) |task| { + this.tasks.writeItemAssumeCapacity(task); + } + _ = this.pending_tasks_count.fetchAdd(add, .Monotonic); + _ = this.ready_tasks_count.fetchSub(add, .Monotonic); + } + } pub fn tick(this: *EventLoop) void { + this.tickConcurrent(); + while (this.tickWithCount() > 0) {} } pub fn waitForTasks(this: *EventLoop) void { - while (this.pending_tasks_count.load(.Monotonic) > 0 or this.ready_tasks_count.load(.Monotonic) > 0) { + this.tickConcurrent(); + + while (this.pending_tasks_count.load(.Monotonic) > 0) { while (this.tickWithCount() > 0) {} } } - pub fn enqueueTask(this: *EventLoop, task: Task) !void { + pub fn enqueueTask(this: *EventLoop, task: Task) void { _ = this.pending_tasks_count.fetchAdd(1, .Monotonic); - try this.tasks.append(task); + this.tasks.writeItem(task) catch unreachable; + } + + pub fn enqueueTaskConcurrent(this: *EventLoop, task: Task) void { + this.concurrent_lock.lock(); + defer this.concurrent_lock.unlock(); + this.concurrent_tasks.writeItem(task) catch unreachable; + _ = this.ready_tasks_count.fetchAdd(1, .Monotonic); } }; - pub inline fn enqueueTask(this: *VirtualMachine, task: Task) !void { - try this.eventLoop().enqueueTask(task); + pub inline fn enqueueTask(this: *VirtualMachine, task: Task) void { + this.eventLoop().enqueueTask(task); + } + + pub inline fn enqueueTaskConcurrent(this: *VirtualMachine, task: Task) void { + this.eventLoop().enqueueTaskConcurrent(task); } pub fn tick(this: *VirtualMachine) void { + this.eventLoop().tickConcurrent(); + while (this.eventLoop().tickWithCount() > 0) {} } @@ -920,9 +1142,16 @@ pub const VirtualMachine = struct { pub threadlocal var vm: *VirtualMachine = undefined; pub fn enableMacroMode(this: *VirtualMachine) void { + if (!this.has_enabled_macro_mode) { + this.has_enabled_macro_mode = true; + this.macro_event_loop.tasks = EventLoop.Queue.init(default_allocator); + this.macro_event_loop.concurrent_tasks = EventLoop.Queue.init(default_allocator); + } + this.bundler.options.platform = .bun_macro; this.bundler.resolver.caches.fs.is_macro_mode = true; this.macro_mode = true; + this.event_loop = &this.macro_event_loop; Analytics.Features.macros = true; } @@ -930,6 +1159,7 @@ pub const VirtualMachine = struct { this.bundler.options.platform = .bun; this.bundler.resolver.caches.fs.is_macro_mode = false; this.macro_mode = false; + this.event_loop = &this.regular_event_loop; } pub fn init( @@ -967,13 +1197,18 @@ pub const VirtualMachine = struct { .node_modules = bundler.options.node_modules_bundle, .log = log, .flush_list = std.ArrayList(string).init(allocator), - .blobs = try Blob.Group.init(allocator), + .blobs = if (_args.serve orelse false) try Blob.Group.init(allocator) else null, .origin = bundler.options.origin, .macros = MacroMap.init(allocator), .macro_entry_points = @TypeOf(VirtualMachine.vm.macro_entry_points).init(allocator), .origin_timer = std.time.Timer.start() catch @panic("Please don't mess with timers."), }; + + VirtualMachine.vm.regular_event_loop.tasks = EventLoop.Queue.init(default_allocator); + VirtualMachine.vm.regular_event_loop.concurrent_tasks = EventLoop.Queue.init(default_allocator); + VirtualMachine.vm.event_loop = &VirtualMachine.vm.regular_event_loop; + vm.bundler.macro_context = null; VirtualMachine.vm.bundler.configureLinker(); @@ -1017,7 +1252,7 @@ pub const VirtualMachine = struct { pub fn preflush(this: *VirtualMachine) void { // We flush on the next tick so that if there were any errors you can still see them - this.blobs.temporary.reset() catch {}; + this.blobs.?.temporary.reset() catch {}; } pub fn flush(this: *VirtualMachine) void { @@ -1031,13 +1266,12 @@ pub const VirtualMachine = struct { } inline fn _fetch( - global: *JSGlobalObject, + _: *JSGlobalObject, _specifier: string, _: string, log: *logger.Log, ) !ResolvedSource { std.debug.assert(VirtualMachine.vm_loaded); - std.debug.assert(VirtualMachine.vm.global == global); if (vm.node_modules != null and strings.eqlComptime(_specifier, bun_file_import_path)) { // We kind of need an abstraction around this. @@ -1145,6 +1379,15 @@ pub const VirtualMachine = struct { .bytecodecache_fd = 0, }; } + } else if (strings.eqlComptime(_specifier, "node:fs")) { + return ResolvedSource{ + .allocator = null, + .source_code = ZigString.init(@embedFile("fs.exports.js")), + .specifier = ZigString.init("node:fs"), + .source_url = ZigString.init("node:fs"), + .hash = 0, + .bytecodecache_fd = 0, + }; } const specifier = normalizeSpecifier(_specifier); @@ -1282,14 +1525,13 @@ pub const VirtualMachine = struct { path: string, }; - fn _resolve(ret: *ResolveFunctionResult, global: *JSGlobalObject, specifier: string, source: string) !void { + fn _resolve(ret: *ResolveFunctionResult, _: *JSGlobalObject, specifier: string, source: string) !void { std.debug.assert(VirtualMachine.vm_loaded); - std.debug.assert(VirtualMachine.vm.global == global); if (vm.node_modules == null and strings.eqlComptime(std.fs.path.basename(specifier), Runtime.Runtime.Imports.alt_name)) { ret.path = Runtime.Runtime.Imports.Name; return; - } else if (vm.node_modules != null and strings.eql(specifier, bun_file_import_path)) { + } else if (vm.node_modules != null and strings.eqlComptime(specifier, bun_file_import_path)) { ret.path = bun_file_import_path; return; } else if (strings.eqlComptime(specifier, main_file_name)) { @@ -1304,6 +1546,10 @@ pub const VirtualMachine = struct { ret.result = null; ret.path = specifier; return; + } else if (strings.eqlComptime(specifier, "fs") or strings.eqlComptime(specifier, "node:fs")) { + ret.result = null; + ret.path = "node:fs"; + return; } const is_special_source = strings.eqlComptime(source, main_file_name) or js_ast.Macro.isMacroPath(source); @@ -1370,13 +1616,12 @@ pub const VirtualMachine = struct { ret.path = result_path.text; } pub fn queueMicrotaskToEventLoop( - global: *JSGlobalObject, + _: *JSGlobalObject, microtask: *Microtask, ) void { std.debug.assert(VirtualMachine.vm_loaded); - std.debug.assert(VirtualMachine.vm.global == global); - vm.enqueueTask(Task.init(microtask)) catch unreachable; + vm.enqueueTask(Task.init(microtask)); } pub fn resolve(res: *ErrorableZigString, global: *JSGlobalObject, specifier: ZigString, source: ZigString) void { var result = ResolveFunctionResult{ .path = "", .result = null }; @@ -1403,7 +1648,7 @@ pub const VirtualMachine = struct { }; { - res.* = ErrorableZigString.err(err, @ptrCast(*anyopaque, ResolveError.create(vm.allocator, msg, source.slice()))); + res.* = ErrorableZigString.err(err, @ptrCast(*anyopaque, ResolveError.create(global, vm.allocator, msg, source.slice()))); } return; @@ -1412,6 +1657,8 @@ pub const VirtualMachine = struct { res.* = ErrorableZigString.ok(ZigString.init(result.path)); } pub fn normalizeSpecifier(slice_: string) string { + var vm_ = VirtualMachine.vm; + var slice = slice_; if (slice.len == 0) return slice; var was_http = false; @@ -1425,23 +1672,23 @@ pub const VirtualMachine = struct { was_http = true; } - if (strings.hasPrefix(slice, VirtualMachine.vm.origin.host)) { - slice = slice[VirtualMachine.vm.origin.host.len..]; + if (strings.hasPrefix(slice, vm_.origin.host)) { + slice = slice[vm_.origin.host.len..]; } else if (was_http) { if (strings.indexOfChar(slice, '/')) |i| { slice = slice[i..]; } } - if (VirtualMachine.vm.origin.path.len > 1) { - if (strings.hasPrefix(slice, VirtualMachine.vm.origin.path)) { - slice = slice[VirtualMachine.vm.origin.path.len..]; + if (vm_.origin.path.len > 1) { + if (strings.hasPrefix(slice, vm_.origin.path)) { + slice = slice[vm_.origin.path.len..]; } } - if (VirtualMachine.vm.bundler.options.routes.asset_prefix_path.len > 0) { - if (strings.hasPrefix(slice, VirtualMachine.vm.bundler.options.routes.asset_prefix_path)) { - slice = slice[VirtualMachine.vm.bundler.options.routes.asset_prefix_path.len..]; + if (vm_.bundler.options.routes.asset_prefix_path.len > 0) { + if (strings.hasPrefix(slice, vm_.bundler.options.routes.asset_prefix_path)) { + slice = slice[vm_.bundler.options.routes.asset_prefix_path.len..]; } } @@ -1460,12 +1707,12 @@ pub const VirtualMachine = struct { var log = logger.Log.init(vm.bundler.allocator); const spec = specifier.slice(); const result = _fetch(global, spec, source.slice(), &log) catch |err| { - processFetchLog(specifier, source, &log, ret, err); + processFetchLog(global, specifier, source, &log, ret, err); return; }; if (log.errors > 0) { - processFetchLog(specifier, source, &log, ret, error.LinkError); + processFetchLog(global, specifier, source, &log, ret, error.LinkError); return; } @@ -1488,30 +1735,32 @@ pub const VirtualMachine = struct { ret.result.value = result; - const specifier_blob = brk: { - if (strings.startsWith(spec, VirtualMachine.vm.bundler.fs.top_level_dir)) { - break :brk spec[VirtualMachine.vm.bundler.fs.top_level_dir.len..]; - } - break :brk spec; - }; + if (vm.blobs) |blobs| { + const specifier_blob = brk: { + if (strings.hasPrefix(spec, VirtualMachine.vm.bundler.fs.top_level_dir)) { + break :brk spec[VirtualMachine.vm.bundler.fs.top_level_dir.len..]; + } + break :brk spec; + }; - if (vm.has_loaded) { - vm.blobs.temporary.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; - } else { - vm.blobs.persistent.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; + if (vm.has_loaded) { + blobs.temporary.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; + } else { + blobs.persistent.put(specifier_blob, .{ .ptr = result.source_code.ptr, .len = result.source_code.len }) catch {}; + } } ret.success = true; } - fn processFetchLog(specifier: ZigString, referrer: ZigString, log: *logger.Log, ret: *ErrorableResolvedSource, err: anyerror) void { + fn processFetchLog(globalThis: *JSGlobalObject, specifier: ZigString, referrer: ZigString, log: *logger.Log, ret: *ErrorableResolvedSource, err: anyerror) void { switch (log.msgs.items.len) { 0 => { const msg = logger.Msg{ .data = logger.rangeData(null, logger.Range.None, std.fmt.allocPrint(vm.allocator, "{s} while building {s}", .{ @errorName(err), specifier.slice() }) catch unreachable), }; { - ret.* = ErrorableResolvedSource.err(err, @ptrCast(*anyopaque, BuildError.create(vm.bundler.allocator, msg))); + ret.* = ErrorableResolvedSource.err(err, @ptrCast(*anyopaque, BuildError.create(globalThis, vm.bundler.allocator, msg))); } return; }, @@ -1519,8 +1768,9 @@ pub const VirtualMachine = struct { 1 => { const msg = log.msgs.items[0]; ret.* = ErrorableResolvedSource.err(err, switch (msg.metadata) { - .build => BuildError.create(vm.bundler.allocator, msg).?, + .build => BuildError.create(globalThis, vm.bundler.allocator, msg).?, .resolve => ResolveError.create( + globalThis, vm.bundler.allocator, msg, referrer.slice(), @@ -1529,12 +1779,13 @@ pub const VirtualMachine = struct { return; }, else => { - var errors = errors_stack[0..std.math.min(log.msgs.items.len, errors_stack.len)]; + var errors = errors_stack[0..@minimum(log.msgs.items.len, errors_stack.len)]; for (log.msgs.items) |msg, i| { errors[i] = switch (msg.metadata) { - .build => BuildError.create(vm.bundler.allocator, msg).?, + .build => BuildError.create(globalThis, vm.bundler.allocator, msg).?, .resolve => ResolveError.create( + globalThis, vm.bundler.allocator, msg, referrer.slice(), @@ -1544,13 +1795,17 @@ pub const VirtualMachine = struct { ret.* = ErrorableResolvedSource.err( err, - vm.global.createAggregateError( + globalThis.createAggregateError( errors.ptr, @intCast(u16, errors.len), - &ZigString.init(std.fmt.allocPrint(vm.bundler.allocator, "{d} errors building \"{s}\"", .{ errors.len, specifier.slice() }) catch unreachable), + &ZigString.init( + std.fmt.allocPrint(vm.bundler.allocator, "{d} errors building \"{s}\"", .{ + errors.len, + specifier.slice(), + }) catch unreachable, + ), ).asVoid(), ); - return; }, } } @@ -1624,9 +1879,35 @@ pub const VirtualMachine = struct { } var entry_point = entry_point_entry.value_ptr.*; + var loader = MacroEntryPointLoader{ + .path = entry_point.source.path.text, + }; + + this.runWithAPILock(MacroEntryPointLoader, &loader, MacroEntryPointLoader.load); + return loader.promise; + } + + /// A subtlelty of JavaScriptCore: + /// JavaScriptCore has many release asserts that check an API lock is currently held + /// We cannot hold it from Zig code because it relies on C++ ARIA to automatically release the lock + /// and it is not safe to copy the lock itself + /// So we have to wrap entry points to & from JavaScript with an API lock that calls out to C++ + pub inline fn runWithAPILock(this: *VirtualMachine, comptime Context: type, ctx: *Context, comptime function: fn (ctx: *Context) void) void { + this.global.vm().holdAPILock(ctx, OpaqueWrap(Context, function)); + } + + const MacroEntryPointLoader = struct { + path: string, + promise: *JSInternalPromise = undefined, + pub fn load(this: *MacroEntryPointLoader) void { + this.promise = vm._loadMacroEntryPoint(this.path); + } + }; + + pub inline fn _loadMacroEntryPoint(this: *VirtualMachine, entry_path: string) *JSInternalPromise { var promise: *JSInternalPromise = undefined; - promise = JSModuleLoader.loadAndEvaluateModule(this.global, &ZigString.init(entry_point.source.path.text)); + promise = JSModuleLoader.loadAndEvaluateModule(this.global, &ZigString.init(entry_path)); this.tick(); @@ -1721,6 +2002,7 @@ pub const VirtualMachine = struct { if (!build_error.logged) { var writer = Output.errorWriter(); build_error.msg.formatWriter(@TypeOf(writer), writer, allow_ansi_color) catch {}; + writer.writeAll("\n") catch {}; build_error.logged = true; } this.had_errors = this.had_errors or build_error.msg.kind == .err; @@ -1768,6 +2050,8 @@ pub const VirtualMachine = struct { const stack = trace.frames(); if (stack.len > 0) { var i: i16 = 0; + const origin: ?*const URL = if (vm.is_from_devserver) &vm.origin else null; + const dir = vm.bundler.fs.top_level_dir; while (i < stack.len) : (i += 1) { const frame = stack[@intCast(usize, i)]; @@ -1785,8 +2069,8 @@ pub const VirtualMachine = struct { allow_ansi_colors, ), frame.sourceURLFormatter( - vm.bundler.fs.top_level_dir, - &vm.origin, + dir, + origin, allow_ansi_colors, ), }, @@ -1879,8 +2163,8 @@ pub const VirtualMachine = struct { ) catch unreachable; } - const name = exception.name.slice(); - const message = exception.message.slice(); + const name = exception.name; + const message = exception.message; var did_print_name = false; if (source_lines.next()) |source| { if (source.text.len > 0 and exception.stack.frames()[0].position.isInvalid()) { @@ -1898,14 +2182,14 @@ pub const VirtualMachine = struct { ) catch unreachable; if (name.len > 0 and message.len > 0) { - writer.print(comptime Output.prettyFmt(" <r><red><b>{s}<r><d>:<r> <b>{s}<r>\n", allow_ansi_color), .{ + writer.print(comptime Output.prettyFmt(" <r><red><b>{}<r><d>:<r> <b>{}<r>\n", allow_ansi_color), .{ name, message, }) catch unreachable; } else if (name.len > 0) { - writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{name}) catch unreachable; + writer.print(comptime Output.prettyFmt(" <r><b>{}<r>\n", allow_ansi_color), .{name}) catch unreachable; } else if (message.len > 0) { - writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{message}) catch unreachable; + writer.print(comptime Output.prettyFmt(" <r><b>{}<r>\n", allow_ansi_color), .{message}) catch unreachable; } } else if (source.text.len > 0) { defer did_print_name = true; @@ -1978,6 +2262,56 @@ pub const VirtualMachine = struct { } } + var add_extra_line = false; + + const Show = struct { + system_code: bool = false, + syscall: bool = false, + errno: bool = false, + path: bool = false, + }; + + var show = Show{ + .system_code = exception.system_code.len > 0 and !strings.eql(exception.system_code.slice(), name.slice()), + .syscall = exception.syscall.len > 0, + .errno = exception.errno < 0, + .path = exception.path.len > 0, + }; + + if (show.path) { + if (show.syscall) { + writer.writeAll(" ") catch unreachable; + } else if (show.errno) { + writer.writeAll(" ") catch unreachable; + } + writer.print(comptime Output.prettyFmt(" path<d>: <r><cyan>\"{s}\"<r>\n", allow_ansi_color), .{exception.path}) catch unreachable; + } + + if (show.system_code) { + if (show.syscall) { + writer.writeAll(" ") catch unreachable; + } else if (show.errno) { + writer.writeAll(" ") catch unreachable; + } + writer.print(comptime Output.prettyFmt(" code<d>: <r><cyan>\"{s}\"<r>\n", allow_ansi_color), .{exception.system_code}) catch unreachable; + add_extra_line = true; + } + + if (show.syscall) { + writer.print(comptime Output.prettyFmt("syscall<d>: <r><cyan>\"{s}\"<r>\n", allow_ansi_color), .{exception.syscall}) catch unreachable; + add_extra_line = true; + } + + if (show.errno) { + if (show.syscall) { + writer.writeAll(" ") catch unreachable; + } + writer.print(comptime Output.prettyFmt("errno<d>: <r><yellow>{d}<r>\n", allow_ansi_color), .{exception.errno}) catch unreachable; + add_extra_line = true; + } + + if (add_extra_line) writer.writeAll("\n") catch unreachable; + try printStackTrace(@TypeOf(writer), writer, exception.stack, allow_ansi_color); } }; @@ -2210,6 +2544,7 @@ pub const ResolveError = struct { ); pub fn create( + globalThis: *JSGlobalObject, allocator: std.mem.Allocator, msg: logger.Msg, referrer: string, @@ -2220,8 +2555,8 @@ pub const ResolveError = struct { .allocator = allocator, .referrer = Fs.Path.init(referrer), }; - var ref = Class.make(VirtualMachine.vm.global.ctx(), resolve_error); - js.JSValueProtect(VirtualMachine.vm.global.ref(), ref); + var ref = Class.make(globalThis.ref(), resolve_error); + js.JSValueProtect(globalThis.ref(), ref); return ref; } @@ -2237,32 +2572,32 @@ pub const ResolveError = struct { pub fn getMessage( this: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.msg.data.text).toValue(ctx.ptr()).asRef(); } pub fn getSpecifier( this: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.msg.metadata.resolve.specifier.slice(this.msg.data.text)).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.msg.metadata.resolve.specifier.slice(this.msg.data.text)).toValue(ctx.ptr()).asRef(); } pub fn getImportKind( this: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(@tagName(this.msg.metadata.resolve.import_kind)).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(@tagName(this.msg.metadata.resolve.import_kind)).toValue(ctx.ptr()).asRef(); } pub fn getReferrer( @@ -2273,7 +2608,7 @@ pub const ResolveError = struct { _: js.ExceptionRef, ) js.JSValueRef { if (this.referrer) |referrer| { - return ZigString.init(referrer.text).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(referrer.text).toValue(ctx.ptr()).asRef(); } else { return js.JSValueMakeNull(ctx); } @@ -2282,12 +2617,12 @@ pub const ResolveError = struct { const BuildErrorName = "ResolveError"; pub fn getName( _: *ResolveError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(BuildErrorName).toValue(ctx.ptr()).asRef(); } }; @@ -2322,6 +2657,7 @@ pub const BuildError = struct { ); pub fn create( + globalThis: *JSGlobalObject, allocator: std.mem.Allocator, msg: logger.Msg, // resolve_result: *const Resolver.Result, @@ -2333,8 +2669,8 @@ pub const BuildError = struct { .allocator = allocator, }; - var ref = Class.make(VirtualMachine.vm.global.ref(), build_error); - js.JSValueProtect(VirtualMachine.vm.global.ref(), ref); + var ref = Class.make(globalThis.ref(), build_error); + js.JSValueProtect(globalThis.ref(), ref); return ref; } @@ -2474,23 +2810,23 @@ pub const BuildError = struct { pub fn getMessage( this: *BuildError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(this.msg.data.text).toValue(ctx.ptr()).asRef(); } const BuildErrorName = "BuildError"; pub fn getName( _: *BuildError, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global).asRef(); + return ZigString.init(BuildErrorName).toValue(ctx.ptr()).asRef(); } }; diff --git a/src/javascript/jsc/javascript_core_c_api.zig b/src/javascript/jsc/javascript_core_c_api.zig index ecd37c44a..0ae0a10e9 100644 --- a/src/javascript/jsc/javascript_core_c_api.zig +++ b/src/javascript/jsc/javascript_core_c_api.zig @@ -1,10 +1,14 @@ const cpp = @import("./bindings/bindings.zig"); -const generic = opaque {}; +const generic = opaque { + pub inline fn ptr(this: *@This()) *cpp.JSGlobalObject { + return @ptrCast(*cpp.JSGlobalObject, @alignCast(@alignOf(*cpp.JSGlobalObject), this)); + } +}; pub const Private = anyopaque; pub const struct_OpaqueJSContextGroup = generic; pub const JSContextGroupRef = ?*const struct_OpaqueJSContextGroup; pub const struct_OpaqueJSContext = generic; -pub const JSContextRef = ?*const struct_OpaqueJSContext; +pub const JSContextRef = *struct_OpaqueJSContext; pub const JSGlobalContextRef = ?*struct_OpaqueJSContext; pub const struct_OpaqueJSString = generic; pub const JSStringRef = ?*struct_OpaqueJSString; @@ -246,6 +250,7 @@ pub const OpaqueJSPropertyNameAccumulator = struct_OpaqueJSPropertyNameAccumulat // This function lets us use the C API but returns a plain old JSValue // allowing us to have exceptions that include stack traces pub extern "c" fn JSObjectCallAsFunctionReturnValue(ctx: JSContextRef, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef) cpp.JSValue; +pub extern "c" fn JSObjectCallAsFunctionReturnValueHoldingAPILock(ctx: JSContextRef, object: JSObjectRef, thisObject: JSObjectRef, argumentCount: usize, arguments: [*c]const JSValueRef) cpp.JSValue; pub extern fn JSRemoteInspectorDisableAutoStart() void; pub extern fn JSRemoteInspectorStart() void; diff --git a/src/javascript/jsc/node/buffer.js b/src/javascript/jsc/node/buffer.js new file mode 100644 index 000000000..faee19655 --- /dev/null +++ b/src/javascript/jsc/node/buffer.js @@ -0,0 +1,97 @@ +"use strict"; + +function createBuffer(BufferPrototype, BufferStatic, Realm) { + "use strict"; + + var Uint8ArraySubarray = Realm.Uint8Array.prototype.subarray; + var isUint8Array = (value) => value instanceof Realm.Uint8Array; + var SymbolToPrimitive = Realm.Symbol.toPrimitive; + var isArray = Realm.Array.isArray; + var isArrayBufferLike = + "SharedArrayBuffer" in Realm + ? () => + value instanceof Realm.ArrayBuffer || + value instanceof Realm.SharedArrayBuffer + : () => value instanceof Realm.ArrayBuffer; + + var BufferInstance = class BufferInstance extends Realm.Uint8Array { + constructor(bufferOrLength, byteOffset, length) { + super(bufferOrLength, byteOffset, length); + } + + static isBuffer(obj) { + return obj instanceof BufferInstance; + } + + static from(value, encodingOrOffset, length) { + switch (typeof value) { + case "string": { + return BufferStatic.fromString(value, encodingOrOffset, length); + } + case "object": { + if (isUint8Array(value)) { + return BufferStatic.fromUint8Array(value, encodingOrOffset, length); + } + + if (isArrayBufferLike(value)) { + return new BufferInstance(value, 0, length); + } + + const valueOf = value.valueOf && value.valueOf(); + if ( + valueOf != null && + valueOf !== value && + (typeof valueOf === "string" || typeof valueOf === "object") + ) { + return BufferInstance.from(valueOf, encodingOrOffset, length); + } + + if (typeof value[SymbolToPrimitive] === "function") { + const primitive = value[SymbolToPrimitive]("string"); + if (typeof primitive === "string") { + return BufferStatic.fromString(primitive, encodingOrOffset); + } + } + + if (isArray(value)) { + return BufferStatic.fromArray(value, encodingOrOffset, length); + } + } + } + + throw new TypeError( + "First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object." + ); + } + + slice(start, end) { + return Uint8ArraySubarray.call(this, start, end); + } + + static get poolSize() { + return BufferStatic._poolSize; + } + + static set poolSize(value) { + BufferStatic._poolSize = value; + } + + get parent() { + return this.buffer; + } + + get offset() { + return this.byteOffset; + } + }; + + Object.assign(BufferInstance, BufferStatic); + Object.assign(BufferInstance.prototype, BufferPrototype); + Object.defineProperty(BufferInstance, "name", { + value: "Buffer", + configurable: false, + enumerable: false, + }); + + return BufferInstance; +} diff --git a/src/javascript/jsc/node/buffer.zig b/src/javascript/jsc/node/buffer.zig new file mode 100644 index 000000000..efe9ace13 --- /dev/null +++ b/src/javascript/jsc/node/buffer.zig @@ -0,0 +1,553 @@ +const std = @import("std"); +const _global = @import("../../../global.zig"); +const strings = _global.strings; +const string = _global.string; +const AsyncIO = @import("io"); +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; +const Environment = _global.Environment; +const C = _global.C; +const Syscall = @import("./syscall.zig"); +const os = std.os; +const Buffer = JSC.ArrayBuffer; + +const JSGlobalObject = JSC.JSGlobalObject; +const ArgumentsSlice = JSC.Node.ArgumentsSlice; + +const BufferStaticFunctionEnum = JSC.Node.DeclEnum(BufferStatic); + +fn BufferStatic_wrap(comptime FunctionEnum: BufferStaticFunctionEnum) NodeFSFunction { + const Function = @field(BufferStatic, @tagName(BufferStaticFunctionEnum)); + const FunctionType = @TypeOf(Function); + + const function: std.builtin.TypeInfo.Fn = comptime @typeInfo(FunctionType).Fn; + comptime if (function.args.len != 3) @compileError("Expected 3 arguments"); + const Arguments = comptime function.args[1].arg_type.?; + const FormattedName = comptime [1]u8{std.ascii.toUpper(@tagName(BufferStaticFunctionEnum)[0])} ++ @tagName(BufferStaticFunctionEnum)[1..]; + const Result = JSC.JSValue; + + const NodeBindingClosure = struct { + pub fn bind( + _: void, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + arguments: []const JSC.C.JSValueRef, + exception: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + var slice = ArgumentsSlice.init(@ptrCast([*]const JSC.JSValue, arguments.ptr)[0..arguments.len]); + + defer { + // TODO: fix this + for (arguments) |arg| { + JSC.C.JSValueUnprotect(ctx, arg); + } + slice.arena.deinit(); + } + + const args = if (comptime Arguments != void) + (Arguments.fromJS(ctx, &slice, exception) orelse return null) + else + Arguments{}; + if (exception.* != null) return null; + + const result: Result = Function( + ctx.ptr(), + args, + exception, + ); + if (exception.* != null) { + return null; + } + + return result.asObjectRef(); + } + }; + + return NodeBindingClosure.bind; +} + +pub const BufferStatic = struct { + pub const Arguments = struct { + pub const Alloc = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Alloc {} + }; + pub const AllocUnsafe = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?AllocUnsafe {} + }; + pub const AllocUnsafeSlow = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?AllocUnsafeSlow {} + }; + pub const Compare = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Compare {} + }; + pub const Concat = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Concat {} + }; + pub const IsEncoding = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?IsEncoding {} + }; + }; + pub fn alloc(globalThis: *JSGlobalObject, args: Arguments.Alloc, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn allocUnsafe(globalThis: *JSGlobalObject, args: Arguments.AllocUnsafe, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn allocUnsafeSlow(globalThis: *JSGlobalObject, args: Arguments.AllocUnsafeSlow, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn compare(globalThis: *JSGlobalObject, args: Arguments.Compare, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn concat(globalThis: *JSGlobalObject, args: Arguments.Concat, exception: JSC.C.ExceptionRef) JSC.JSValue {} + pub fn isEncoding(globalThis: *JSGlobalObject, args: Arguments.IsEncoding, exception: JSC.C.ExceptionRef) JSC.JSValue {} + + pub const Class = JSC.NewClass( + void, + .{ .name = "Buffer" }, + .{ + .alloc = .{ .name = "alloc", .rfn = BufferStatic_wrap(.alloc) }, + .allocUnsafe = .{ .name = "allocUnsafe", .rfn = BufferStatic_wrap(.allocUnsafe) }, + .allocUnsafeSlow = .{ .name = "allocUnsafeSlow", .rfn = BufferStatic_wrap(.allocUnsafeSlow) }, + .compare = .{ .name = "compare", .rfn = BufferStatic_wrap(.compare) }, + .concat = .{ .name = "concat", .rfn = BufferStatic_wrap(.concat) }, + .isEncoding = .{ .name = "isEncoding", .rfn = BufferStatic_wrap(.isEncoding) }, + }, + .{ ._poolSize = .{ .name = "_poolSize", .get = .{ .name = "get", .rfn = BufferStatic.getPoolSize }, .set = .{ .name = "set", .rfn = BufferStatic.setPoolSize } } }, + ); +}; + +pub const BufferPrototype = struct { + const Arguments = struct { + pub const Compare = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Compare { + return null; + } + }; + pub const Copy = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Copy { + return null; + } + }; + pub const Equals = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Equals { + return null; + } + }; + pub const Fill = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fill { + return null; + } + }; + pub const Includes = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Includes { + return null; + } + }; + pub const IndexOf = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?IndexOf { + return null; + } + }; + pub const LastIndexOf = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?LastIndexOf { + return null; + } + }; + pub const Swap16 = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Swap16 { + return null; + } + }; + pub const Swap32 = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Swap32 { + return null; + } + }; + pub const Swap64 = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Swap64 { + return null; + } + }; + pub const Write = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Write { + return null; + } + }; + pub const Read = struct { + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Read { + return null; + } + }; + + pub fn WriteInt(comptime kind: Int) type { + return struct { + const This = @This(); + const Value = Int.native.get(kind); + }; + } + pub fn ReadInt(comptime kind: Int) type { + return struct { + const This = @This(); + const Value = Int.native.get(kind); + }; + } + }; + pub fn compare(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Compare) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn copy(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Copy) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn equals(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Equals) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn fill(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Fill) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn includes(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Includes) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn indexOf(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.IndexOf) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn lastIndexOf(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.LastIndexOf) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn swap16(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Swap16) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn swap32(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Swap32) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn swap64(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Swap64) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn write(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Write) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + pub fn read(this: *Buffer, globalThis: *JSC.JSGlobalObject, args: Arguments.Read) JSC.JSValue { + _ = this; + _ = globalThis; + _ = args; + return JSC.JSValue.jsUndefined(); + } + + fn writeIntAny(this: *Buffer, comptime kind: Int, args: Arguments.WriteInt(kind)) JSC.JSValue {} + fn readIntAny(this: *Buffer, comptime kind: Int, args: Arguments.ReadInt(kind)) JSC.JSValue {} + + pub const Class = JSC.NewClass( + void, + .{ .name = "Buffer" }, + .{ + .compare = .{ + .name = "compare", + .rfn = wrap(BufferPrototype.compare), + }, + .copy = .{ + .name = "copy", + .rfn = wrap(BufferPrototype.copy), + }, + .equals = .{ + .name = "equals", + .rfn = wrap(BufferPrototype.equals), + }, + .fill = .{ + .name = "fill", + .rfn = wrap(BufferPrototype.fill), + }, + .includes = .{ + .name = "includes", + .rfn = wrap(BufferPrototype.includes), + }, + .indexOf = .{ + .name = "indexOf", + .rfn = wrap(BufferPrototype.indexOf), + }, + .lastIndexOf = .{ + .name = "lastIndexOf", + .rfn = wrap(BufferPrototype.lastIndexOf), + }, + .swap16 = .{ + .name = "swap16", + .rfn = wrap(BufferPrototype.swap16), + }, + .swap32 = .{ + .name = "swap32", + .rfn = wrap(BufferPrototype.swap32), + }, + .swap64 = .{ + .name = "swap64", + .rfn = wrap(BufferPrototype.swap64), + }, + .write = .{ + .name = "write", + .rfn = wrap(BufferPrototype.write), + }, + .read = .{ + .name = "read", + .rfn = wrap(BufferPrototype.read), + }, + + // -- Write -- + .writeBigInt64BE = .{ + .name = "writeBigInt64BE", + .rfn = writeWrap(Int.BigInt64BE), + }, + .writeBigInt64LE = .{ + .name = "writeBigInt64LE", + .rfn = writeWrap(Int.BigInt64LE), + }, + .writeBigUInt64BE = .{ + .name = "writeBigUInt64BE", + .rfn = writeWrap(Int.BigUInt64BE), + }, + .writeBigUInt64LE = .{ + .name = "writeBigUInt64LE", + .rfn = writeWrap(Int.BigUInt64LE), + }, + .writeDoubleBE = .{ + .name = "writeDoubleBE", + .rfn = writeWrap(Int.DoubleBE), + }, + .writeDoubleLE = .{ + .name = "writeDoubleLE", + .rfn = writeWrap(Int.DoubleLE), + }, + .writeFloatBE = .{ + .name = "writeFloatBE", + .rfn = writeWrap(Int.FloatBE), + }, + .writeFloatLE = .{ + .name = "writeFloatLE", + .rfn = writeWrap(Int.FloatLE), + }, + .writeInt8 = .{ + .name = "writeInt8", + .rfn = writeWrap(Int.Int8), + }, + .writeInt16BE = .{ + .name = "writeInt16BE", + .rfn = writeWrap(Int.Int16BE), + }, + .writeInt16LE = .{ + .name = "writeInt16LE", + .rfn = writeWrap(Int.Int16LE), + }, + .writeInt32BE = .{ + .name = "writeInt32BE", + .rfn = writeWrap(Int.Int32BE), + }, + .writeInt32LE = .{ + .name = "writeInt32LE", + .rfn = writeWrap(Int.Int32LE), + }, + .writeIntBE = .{ + .name = "writeIntBE", + .rfn = writeWrap(Int.IntBE), + }, + .writeIntLE = .{ + .name = "writeIntLE", + .rfn = writeWrap(Int.IntLE), + }, + .writeUInt8 = .{ + .name = "writeUInt8", + .rfn = writeWrap(Int.UInt8), + }, + .writeUInt16BE = .{ + .name = "writeUInt16BE", + .rfn = writeWrap(Int.UInt16BE), + }, + .writeUInt16LE = .{ + .name = "writeUInt16LE", + .rfn = writeWrap(Int.UInt16LE), + }, + .writeUInt32BE = .{ + .name = "writeUInt32BE", + .rfn = writeWrap(Int.UInt32BE), + }, + .writeUInt32LE = .{ + .name = "writeUInt32LE", + .rfn = writeWrap(Int.UInt32LE), + }, + .writeUIntBE = .{ + .name = "writeUIntBE", + .rfn = writeWrap(Int.UIntBE), + }, + .writeUIntLE = .{ + .name = "writeUIntLE", + .rfn = writeWrap(Int.UIntLE), + }, + + // -- Read -- + .readBigInt64BE = .{ + .name = "readBigInt64BE", + .rfn = readWrap(Int.BigInt64BE), + }, + .readBigInt64LE = .{ + .name = "readBigInt64LE", + .rfn = readWrap(Int.BigInt64LE), + }, + .readBigUInt64BE = .{ + .name = "readBigUInt64BE", + .rfn = readWrap(Int.BigUInt64BE), + }, + .readBigUInt64LE = .{ + .name = "readBigUInt64LE", + .rfn = readWrap(Int.BigUInt64LE), + }, + .readDoubleBE = .{ + .name = "readDoubleBE", + .rfn = readWrap(Int.DoubleBE), + }, + .readDoubleLE = .{ + .name = "readDoubleLE", + .rfn = readWrap(Int.DoubleLE), + }, + .readFloatBE = .{ + .name = "readFloatBE", + .rfn = readWrap(Int.FloatBE), + }, + .readFloatLE = .{ + .name = "readFloatLE", + .rfn = readWrap(Int.FloatLE), + }, + .readInt8 = .{ + .name = "readInt8", + .rfn = readWrap(Int.Int8), + }, + .readInt16BE = .{ + .name = "readInt16BE", + .rfn = readWrap(Int.Int16BE), + }, + .readInt16LE = .{ + .name = "readInt16LE", + .rfn = readWrap(Int.Int16LE), + }, + .readInt32BE = .{ + .name = "readInt32BE", + .rfn = readWrap(Int.Int32BE), + }, + .readInt32LE = .{ + .name = "readInt32LE", + .rfn = readWrap(Int.Int32LE), + }, + .readIntBE = .{ + .name = "readIntBE", + .rfn = readWrap(Int.IntBE), + }, + .readIntLE = .{ + .name = "readIntLE", + .rfn = readWrap(Int.IntLE), + }, + .readUInt8 = .{ + .name = "readUInt8", + .rfn = readWrap(Int.UInt8), + }, + .readUInt16BE = .{ + .name = "readUInt16BE", + .rfn = readWrap(Int.UInt16BE), + }, + .readUInt16LE = .{ + .name = "readUInt16LE", + .rfn = readWrap(Int.UInt16LE), + }, + .readUInt32BE = .{ + .name = "readUInt32BE", + .rfn = readWrap(Int.UInt32BE), + }, + .readUInt32LE = .{ + .name = "readUInt32LE", + .rfn = readWrap(Int.UInt32LE), + }, + .readUIntBE = .{ + .name = "readUIntBE", + .rfn = readWrap(Int.UIntBE), + }, + .readUIntLE = .{ + .name = "readUIntLE", + .rfn = readWrap(Int.UIntLE), + }, + }, + .{}, + ); +}; + +const Int = enum { + BigInt64BE, + BigInt64LE, + BigUInt64BE, + BigUInt64LE, + DoubleBE, + DoubleLE, + FloatBE, + FloatLE, + Int8, + Int16BE, + Int16LE, + Int32BE, + Int32LE, + IntBE, + IntLE, + UInt8, + UInt16BE, + UInt16LE, + UInt32BE, + UInt32LE, + UIntBE, + UIntLE, + + const NativeMap = std.EnumArray(Int, type); + pub const native: NativeMap = brk: { + var map = NativeMap.initUndefined(); + map.set(.BigInt64BE, i64); + map.set(.BigInt64LE, i64); + map.set(.BigUInt64BE, u64); + map.set(.BigUInt64LE, u64); + map.set(.DoubleBE, f64); + map.set(.DoubleLE, f64); + map.set(.FloatBE, f32); + map.set(.FloatLE, f32); + map.set(.Int8, i8); + map.set(.Int16BE, i16); + map.set(.Int16LE, i16); + map.set(.Int32BE, u32); + map.set(.Int32LE, u32); + map.set(.IntBE, i32); + map.set(.IntLE, i32); + map.set(.UInt8, u8); + map.set(.UInt16BE, u16); + map.set(.UInt16LE, u16); + map.set(.UInt32BE, u32); + map.set(.UInt32LE, u32); + map.set(.UIntBE, u32); + map.set(.UIntLE, u32); + break :brk map; + }; +}; diff --git a/src/javascript/jsc/node/dir_iterator.zig b/src/javascript/jsc/node/dir_iterator.zig new file mode 100644 index 000000000..f4c8b6d4a --- /dev/null +++ b/src/javascript/jsc/node/dir_iterator.zig @@ -0,0 +1,347 @@ +// This is copied from std.fs.Dir.Iterator +// The differences are: +// - it returns errors in the expected format +// - doesn't mark BADF as unreachable +// - It uses PathString instead of []const u8 + +const builtin = @import("builtin"); +const std = @import("std"); +const os = std.os; + +const Dir = std.fs.Dir; +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; + +const IteratorError = error{ AccessDenied, SystemResources } || os.UnexpectedError; +const mem = std.mem; +const strings = @import("../../../global.zig").strings; +const Maybe = JSC.Node.Maybe; +const File = std.fs.File; +const Result = Maybe(?Entry); + +const Entry = JSC.Node.DirEnt; + +pub const Iterator = switch (builtin.os.tag) { + .macos, .ios, .freebsd, .netbsd, .dragonfly, .openbsd, .solaris => struct { + dir: Dir, + seek: i64, + buf: [8192]u8, // TODO align(@alignOf(os.system.dirent)), + index: usize, + end_index: usize, + + const Self = @This(); + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + const next = switch (builtin.os.tag) { + .macos, .ios => nextDarwin, + // .freebsd, .netbsd, .dragonfly, .openbsd => nextBsd, + // .solaris => nextSolaris, + else => @compileError("unimplemented"), + }; + + fn nextDarwin(self: *Self) Result { + start_over: while (true) { + if (self.index >= self.end_index) { + const rc = os.system.__getdirentries64( + self.dir.fd, + &self.buf, + self.buf.len, + &self.seek, + ); + + if (rc < 1) { + if (rc == 0) return Result{ .result = null }; + if (Result.errnoSys(rc, .getdirentries64)) |err| { + return err; + } + } + + self.index = 0; + self.end_index = @intCast(usize, rc); + } + const darwin_entry = @ptrCast(*align(1) os.system.dirent, &self.buf[self.index]); + const next_index = self.index + darwin_entry.reclen(); + self.index = next_index; + + const name = @ptrCast([*]u8, &darwin_entry.d_name)[0..darwin_entry.d_namlen]; + + if (strings.eqlComptime(name, ".") or strings.eqlComptime(name, "..") or (darwin_entry.d_ino == 0)) { + continue :start_over; + } + + const entry_kind = switch (darwin_entry.d_type) { + os.DT.BLK => Entry.Kind.BlockDevice, + os.DT.CHR => Entry.Kind.CharacterDevice, + os.DT.DIR => Entry.Kind.Directory, + os.DT.FIFO => Entry.Kind.NamedPipe, + os.DT.LNK => Entry.Kind.SymLink, + os.DT.REG => Entry.Kind.File, + os.DT.SOCK => Entry.Kind.UnixDomainSocket, + os.DT.WHT => Entry.Kind.Whiteout, + else => Entry.Kind.Unknown, + }; + return .{ + .result = Entry{ + .name = PathString.init(name), + .kind = entry_kind, + }, + }; + } + } + }, + + .linux => struct { + dir: Dir, + // The if guard is solely there to prevent compile errors from missing `linux.dirent64` + // definition when compiling for other OSes. It doesn't do anything when compiling for Linux. + buf: [8192]u8 align(if (builtin.os.tag != .linux) 1 else @alignOf(linux.dirent64)), + index: usize, + end_index: usize, + + const Self = @This(); + const linux = os.linux; + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + pub fn next(self: *Self) Result { + start_over: while (true) { + if (self.index >= self.end_index) { + const rc = linux.getdents64(self.dir.fd, &self.buf, self.buf.len); + if (Result.errnoSys(rc, .getdents64)) |err| return err; + if (rc == 0) return .{ .result = null }; + self.index = 0; + self.end_index = rc; + } + const linux_entry = @ptrCast(*align(1) linux.dirent64, &self.buf[self.index]); + const next_index = self.index + linux_entry.reclen(); + self.index = next_index; + + const name = mem.sliceTo(@ptrCast([*:0]u8, &linux_entry.d_name), 0); + + // skip . and .. entries + if (strings.eqlComptime(name, ".") or strings.eqlComptime(name, "..")) { + continue :start_over; + } + + const entry_kind = switch (linux_entry.d_type) { + linux.DT.BLK => Entry.Kind.BlockDevice, + linux.DT.CHR => Entry.Kind.CharacterDevice, + linux.DT.DIR => Entry.Kind.Directory, + linux.DT.FIFO => Entry.Kind.NamedPipe, + linux.DT.LNK => Entry.Kind.SymLink, + linux.DT.REG => Entry.Kind.File, + linux.DT.SOCK => Entry.Kind.UnixDomainSocket, + else => Entry.Kind.Unknown, + }; + return .{ + .result = Entry{ + .name = PathString.init(name), + .kind = entry_kind, + }, + }; + } + } + }, + .windows => struct { + dir: Dir, + buf: [8192]u8 align(@alignOf(os.windows.FILE_BOTH_DIR_INFORMATION)), + index: usize, + end_index: usize, + first: bool, + name_data: [256]u8, + + const Self = @This(); + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + pub fn next(self: *Self) Result { + while (true) { + const w = os.windows; + if (self.index >= self.end_index) { + var io: w.IO_STATUS_BLOCK = undefined; + const rc = w.ntdll.NtQueryDirectoryFile( + self.dir.fd, + null, + null, + null, + &io, + &self.buf, + self.buf.len, + .FileBothDirectoryInformation, + w.FALSE, + null, + if (self.first) @as(w.BOOLEAN, w.TRUE) else @as(w.BOOLEAN, w.FALSE), + ); + self.first = false; + if (io.Information == 0) return .{ .result = null }; + self.index = 0; + self.end_index = io.Information; + switch (rc) { + .SUCCESS => {}, + .ACCESS_DENIED => return error.AccessDenied, // Double-check that the Dir was opened with iteration ability + + else => return w.unexpectedStatus(rc), + } + } + + const aligned_ptr = @alignCast(@alignOf(w.FILE_BOTH_DIR_INFORMATION), &self.buf[self.index]); + const dir_info = @ptrCast(*w.FILE_BOTH_DIR_INFORMATION, aligned_ptr); + if (dir_info.NextEntryOffset != 0) { + self.index += dir_info.NextEntryOffset; + } else { + self.index = self.buf.len; + } + + const name_utf16le = @ptrCast([*]u16, &dir_info.FileName)[0 .. dir_info.FileNameLength / 2]; + + if (mem.eql(u16, name_utf16le, &[_]u16{'.'}) or mem.eql(u16, name_utf16le, &[_]u16{ '.', '.' })) + continue; + // Trust that Windows gives us valid UTF-16LE + const name_utf8_len = std.unicode.utf16leToUtf8(self.name_data[0..], name_utf16le) catch unreachable; + const name_utf8 = self.name_data[0..name_utf8_len]; + const kind = blk: { + const attrs = dir_info.FileAttributes; + if (attrs & w.FILE_ATTRIBUTE_DIRECTORY != 0) break :blk Entry.Kind.Directory; + if (attrs & w.FILE_ATTRIBUTE_REPARSE_POINT != 0) break :blk Entry.Kind.SymLink; + break :blk Entry.Kind.File; + }; + return .{ + .result = Entry{ + .name = PathString.init(name_utf8), + .kind = kind, + }, + }; + } + } + }, + .wasi => struct { + dir: Dir, + buf: [8192]u8, // TODO align(@alignOf(os.wasi.dirent_t)), + cookie: u64, + index: usize, + end_index: usize, + + const Self = @This(); + + pub const Error = IteratorError; + + /// Memory such as file names referenced in this returned entry becomes invalid + /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized. + pub fn next(self: *Self) Result { + // We intentinally use fd_readdir even when linked with libc, + // since its implementation is exactly the same as below, + // and we avoid the code complexity here. + const w = os.wasi; + start_over: while (true) { + if (self.index >= self.end_index) { + var bufused: usize = undefined; + switch (w.fd_readdir(self.dir.fd, &self.buf, self.buf.len, self.cookie, &bufused)) { + .SUCCESS => {}, + .BADF => unreachable, // Dir is invalid or was opened without iteration ability + .FAULT => unreachable, + .NOTDIR => unreachable, + .INVAL => unreachable, + .NOTCAPABLE => return error.AccessDenied, + else => |err| return os.unexpectedErrno(err), + } + if (bufused == 0) return null; + self.index = 0; + self.end_index = bufused; + } + const entry = @ptrCast(*align(1) w.dirent_t, &self.buf[self.index]); + const entry_size = @sizeOf(w.dirent_t); + const name_index = self.index + entry_size; + const name = mem.span(self.buf[name_index .. name_index + entry.d_namlen]); + + const next_index = name_index + entry.d_namlen; + self.index = next_index; + self.cookie = entry.d_next; + + // skip . and .. entries + if (strings.eqlComptime(name, ".") or strings.eqlComptime(name, "..")) { + continue :start_over; + } + + const entry_kind = switch (entry.d_type) { + .BLOCK_DEVICE => Entry.Kind.BlockDevice, + .CHARACTER_DEVICE => Entry.Kind.CharacterDevice, + .DIRECTORY => Entry.Kind.Directory, + .SYMBOLIC_LINK => Entry.Kind.SymLink, + .REGULAR_FILE => Entry.Kind.File, + .SOCKET_STREAM, .SOCKET_DGRAM => Entry.Kind.UnixDomainSocket, + else => Entry.Kind.Unknown, + }; + return Entry{ + .name = name, + .kind = entry_kind, + }; + } + } + }, + else => @compileError("unimplemented"), +}; + +const WrappedIterator = struct { + iter: Iterator, + const Self = @This(); + + pub const Error = IteratorError; + + pub inline fn next(self: *Self) Result { + return self.iter.next(); + } +}; + +pub fn iterate(self: Dir) WrappedIterator { + return WrappedIterator{ + .iter = _iterate(self), + }; +} + +fn _iterate(self: Dir) Iterator { + switch (builtin.os.tag) { + .macos, + .ios, + .freebsd, + .netbsd, + .dragonfly, + .openbsd, + .solaris, + => return Iterator{ + .dir = self, + .seek = 0, + .index = 0, + .end_index = 0, + .buf = undefined, + }, + .linux, .haiku => return Iterator{ + .dir = self, + .index = 0, + .end_index = 0, + .buf = undefined, + }, + .windows => return Iterator{ + .dir = self, + .index = 0, + .end_index = 0, + .first = true, + .buf = undefined, + .name_data = undefined, + }, + .wasi => return Iterator{ + .dir = self, + .cookie = os.wasi.DIRCOOKIE_START, + .index = 0, + .end_index = 0, + .buf = undefined, + }, + else => @compileError("unimplemented"), + } +} diff --git a/src/javascript/jsc/node/node_fs.zig b/src/javascript/jsc/node/node_fs.zig new file mode 100644 index 000000000..a89eb190f --- /dev/null +++ b/src/javascript/jsc/node/node_fs.zig @@ -0,0 +1,3726 @@ +// This file contains the underlying implementation for sync & async functions +// for interacting with the filesystem from JavaScript. +// The top-level functions assume the arguments are already validated +const std = @import("std"); +const _global = @import("../../../global.zig"); +const strings = _global.strings; +const string = _global.string; +const AsyncIO = @import("io"); +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; +const Environment = _global.Environment; +const C = _global.C; +const Flavor = JSC.Node.Flavor; +const system = std.os.system; +const Maybe = JSC.Node.Maybe; +const Encoding = JSC.Node.Encoding; +const Syscall = @import("./syscall.zig"); +const builtin = @import("builtin"); +const os = @import("std").os; +const darwin = os.darwin; +const linux = os.linux; +const PathOrBuffer = JSC.Node.PathOrBuffer; +const PathLike = JSC.Node.PathLike; +const PathOrFileDescriptor = JSC.Node.PathOrFileDescriptor; +const FileDescriptor = JSC.Node.FileDescriptor; +const DirIterator = @import("./dir_iterator.zig"); +const Path = @import("../../../resolver/resolve_path.zig"); +const FileSystem = @import("../../../fs.zig").FileSystem; +const StringOrBuffer = JSC.Node.StringOrBuffer; +const ArgumentsSlice = JSC.Node.ArgumentsSlice; +const TimeLike = JSC.Node.TimeLike; +const Mode = JSC.Node.Mode; + +const uid_t = std.os.uid_t; +const gid_t = std.os.gid_t; + +/// u63 to allow one null bit +const ReadPosition = u63; + +const Stats = JSC.Node.Stats; +const BigIntStats = JSC.Node.BigIntStats; +const DirEnt = JSC.Node.DirEnt; + +pub const FlavoredIO = struct { + io: *AsyncIO, +}; + +const ArrayBuffer = JSC.MarkedArrayBuffer; +const Buffer = JSC.Buffer; +const FileSystemFlags = JSC.Node.FileSystemFlags; + +// 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 +// This would reduce stack size, at the cost of instruction cache misses +const Arguments = struct { + pub const Rename = struct { + old_path: PathLike, + new_path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Rename { + const old_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "oldPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const new_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "newPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + return Rename{ .old_path = old_path, .new_path = new_path }; + } + }; + + pub const Truncate = struct { + /// Passing a file descriptor is deprecated and may result in an error being thrown in the future. + path: PathOrFileDescriptor, + len: u32 = 0, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Truncate { + const path = PathOrFileDescriptor.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const len: u32 = brk: { + const len_value = arguments.next() orelse break :brk 0; + + if (len_value.isNumber()) { + arguments.eat(); + break :brk len_value.toU32(); + } + + break :brk 0; + }; + + return Truncate{ .path = path, .len = len }; + } + }; + + pub const FTruncate = struct { + fd: FileDescriptor, + len: ?u32 = null, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FTruncate { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + if (exception.* != null) return null; + + const len: u32 = brk: { + const len_value = arguments.next() orelse break :brk 0; + if (len_value.isNumber()) { + arguments.eat(); + break :brk len_value.toU32(); + } + + break :brk 0; + }; + + return FTruncate{ .fd = fd, .len = len }; + } + }; + + pub const Chown = struct { + path: PathLike, + uid: uid_t = 0, + gid: gid_t = 0, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Chown { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const uid: uid_t = brk: { + const uid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "uid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(uid_t, uid_value.toInt32()); + }; + + const gid: gid_t = brk: { + const gid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "gid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(gid_t, gid_value.toInt32()); + }; + + return Chown{ .path = path, .uid = uid, .gid = gid }; + } + }; + + pub const Fchown = struct { + fd: FileDescriptor, + uid: uid_t, + gid: gid_t, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fchown { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const uid: uid_t = brk: { + const uid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "uid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(uid_t, uid_value.toInt32()); + }; + + const gid: gid_t = brk: { + const gid_value = arguments.next() orelse break :brk { + if (exception.* == null) { + JSC.throwInvalidArguments( + "gid is required", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + break :brk @intCast(gid_t, gid_value.toInt32()); + }; + + return Fchown{ .fd = fd, .uid = uid, .gid = gid }; + } + }; + + pub const LChown = Chown; + + pub const Lutimes = struct { + path: PathLike, + atime: TimeLike, + mtime: TimeLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Lutimes { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const atime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime is required", + .{}, + ctx, + exception, + ); + } + + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime must be a number or a Date", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + const mtime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime is required", + .{}, + ctx, + exception, + ); + } + + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime must be a number or a Date", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + return Lutimes{ .path = path, .atime = atime, .mtime = mtime }; + } + }; + + pub const Chmod = struct { + path: PathLike, + mode: Mode = 0x777, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Chmod { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + const mode: Mode = JSC.Node.modeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode must be a string or integer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + return Chmod{ .path = path, .mode = mode }; + } + }; + + pub const FChmod = struct { + fd: FileDescriptor, + mode: Mode = 0x777, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FChmod { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + arguments.eat(); + + const mode: Mode = JSC.Node.modeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mode must be a string or integer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + return FChmod{ .fd = fd, .mode = mode }; + } + }; + + pub const LCHmod = Chmod; + + pub const Stat = struct { + path: PathLike, + big_int: bool = false, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Stat { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const big_int = brk: { + if (arguments.next()) |next_val| { + if (next_val.isObject()) { + if (next_val.isCallable(ctx.ptr().vm())) break :brk false; + arguments.eat(); + + if (next_val.getIfPropertyExists(ctx.ptr(), "bigint")) |big_int| { + break :brk big_int.toBoolean(); + } + } + } + break :brk false; + }; + + if (exception.* != null) return null; + + return Stat{ .path = path, .big_int = big_int }; + } + }; + + pub const Fstat = struct { + fd: FileDescriptor, + big_int: bool = false, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fstat { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "file descriptor must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const big_int = brk: { + if (arguments.next()) |next_val| { + if (next_val.isObject()) { + if (next_val.isCallable(ctx.ptr().vm())) break :brk false; + arguments.eat(); + + if (next_val.getIfPropertyExists(ctx.ptr(), "bigint")) |big_int| { + break :brk big_int.toBoolean(); + } + } + } + break :brk false; + }; + + if (exception.* != null) return null; + + return Fstat{ .fd = fd, .big_int = big_int }; + } + }; + + pub const Lstat = Stat; + + pub const Link = struct { + old_path: PathLike, + new_path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Link { + const old_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "oldPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const new_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "newPath must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Link{ .old_path = old_path, .new_path = new_path }; + } + }; + + pub const Symlink = struct { + old_path: PathLike, + new_path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Symlink { + const old_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "target must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const new_path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + if (arguments.next()) |next_val| { + // The type argument is only available on Windows and + // ignored on other platforms. It can be set to 'dir', + // 'file', or 'junction'. If the type argument is not set, + // Node.js will autodetect target type and use 'file' or + // 'dir'. If the target does not exist, 'file' will be used. + // Windows junction points require the destination path to + // be absolute. When using 'junction', the target argument + // will automatically be normalized to absolute path. + if (next_val.isString()) { + comptime if (Environment.isWindows) @compileError("Add support for type argument on Windows"); + arguments.eat(); + } + } + + return Symlink{ .old_path = old_path, .new_path = new_path }; + } + }; + + pub const Readlink = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Readlink { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + var encoding = Encoding.utf8; + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + } + }, + } + } + + return Readlink{ .path = path, .encoding = encoding }; + } + }; + + pub const Realpath = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Realpath { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + var encoding = Encoding.utf8; + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + } + }, + } + } + + return Realpath{ .path = path, .encoding = encoding }; + } + }; + + pub const Unlink = struct { + path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Unlink { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Unlink{ + .path = path, + }; + } + }; + + pub const Rm = struct { + path: PathLike, + force: bool = false, + max_retries: u32 = 0, + recursive: bool = false, + retry_delay: c_uint = 100, + }; + + pub const RmDir = struct { + path: PathLike, + + max_retries: u32 = 0, + recursive: bool = false, + retry_delay: c_uint = 100, + }; + + /// https://github.com/nodejs/node/blob/master/lib/fs.js#L1285 + pub const Mkdir = struct { + path: PathLike, + /// Indicates whether parent folders should be created. + /// If a folder was created, the path to the first created folder will be returned. + /// @default false + recursive: bool = false, + /// A file mode. If a string is passed, it is parsed as an octal integer. If not specified + /// @default + mode: Mode = 0o777, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Mkdir { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var recursive = false; + var mode: Mode = 0o777; + + if (arguments.next()) |val| { + arguments.eat(); + + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "recursive")) |recursive_| { + recursive = recursive_.toBoolean(); + } + + if (val.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse mode; + } + } + } + + return Mkdir{ + .path = path, + .recursive = recursive, + .mode = mode, + }; + } + }; + + const MkdirTemp = struct { + prefix: string = "", + encoding: Encoding = Encoding.utf8, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?MkdirTemp { + const prefix_value = arguments.next() orelse return MkdirTemp{}; + + var prefix = JSC.ZigString.Empty; + prefix_value.toZigString(&prefix, ctx.ptr()); + + if (exception.* != null) return null; + + arguments.eat(); + + var encoding = Encoding.utf8; + + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + } + }, + } + } + + return MkdirTemp{ + .prefix = prefix.slice(), + .encoding = encoding, + }; + } + }; + + pub const Readdir = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + with_file_types: bool = false, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Readdir { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var encoding = Encoding.utf8; + var with_file_types = false; + + if (arguments.next()) |val| { + arguments.eat(); + + switch (val.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject => { + encoding = Encoding.fromStringValue(val, ctx.ptr()) orelse Encoding.utf8; + }, + else => { + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse Encoding.utf8; + } + + if (val.getIfPropertyExists(ctx.ptr(), "withFileTypes")) |with_file_types_| { + with_file_types = with_file_types_.toBoolean(); + } + } + }, + } + } + + return Readdir{ + .path = path, + .encoding = encoding, + .with_file_types = with_file_types, + }; + } + }; + + pub const Close = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Close { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Close{ + .fd = fd, + }; + } + }; + + pub const Open = struct { + path: PathLike, + flags: FileSystemFlags = FileSystemFlags.@"r", + mode: Mode = 0o666, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Open { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var flags = FileSystemFlags.@"r"; + var mode: Mode = 0o666; + + if (arguments.next()) |val| { + arguments.eat(); + + if (val.isObject()) { + if (val.getIfPropertyExists(ctx.ptr(), "flags")) |flags_| { + flags = FileSystemFlags.fromJS(ctx, flags_, exception) orelse flags; + } + + if (val.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse mode; + } + } + } + + if (exception.* != null) return null; + + return Open{ + .path = path, + .flags = flags, + .mode = mode, + }; + } + }; + + /// Change the file system timestamps of the object referenced by `path`. + /// + /// The `atime` and `mtime` arguments follow these rules: + /// + /// * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + /// * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + /// @since v0.4.2 + pub const Utimes = Lutimes; + + pub const Futimes = struct { + fd: FileDescriptor, + atime: TimeLike, + mtime: TimeLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Futimes { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + arguments.eat(); + if (exception.* != null) return null; + + const atime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "atime must be a number, Date or string", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const mtime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "mtime must be a number, Date or string", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Futimes{ + .fd = fd, + .atime = atime, + .mtime = mtime, + }; + } + }; + + pub const FSync = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FSync { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return FSync{ + .fd = fd, + }; + } + }; + + /// Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it + /// must have an own `toString` function property. + /// + /// `offset` determines the part of the buffer to be written, and `length` is + /// an integer specifying the number of bytes to write. + /// + /// `position` refers to the offset from the beginning of the file where this data + /// should be written. If `typeof position !== 'number'`, the data will be written + /// at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + /// + /// The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + /// + /// If this method is invoked as its `util.promisify()` ed version, it returns + /// a promise for an `Object` with `bytesWritten` and `buffer` properties. + /// + /// It is unsafe to use `fs.write()` multiple times on the same file without waiting + /// for the callback. For this scenario, {@link createWriteStream} is + /// recommended. + /// + /// On Linux, positional writes don't work when the file is opened in append mode. + /// The kernel ignores the position argument and always appends the data to + /// the end of the file. + /// @since v0.0.2 + /// + pub const Write = struct { + fd: FileDescriptor, + buffer: StringOrBuffer, + offset: u64 = 0, + length: u64 = std.math.maxInt(u64), + position: ?ReadPosition = null, + encoding: Encoding = Encoding.buffer, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Write { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + if (exception.* != null) return null; + + const buffer = StringOrBuffer.fromJS(ctx.ptr(), arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + if (exception.* != null) return null; + + arguments.eat(); + + var args = Write{ + .fd = fd, + .buffer = buffer, + .encoding = switch (buffer) { + .string => Encoding.utf8, + .buffer => Encoding.buffer, + }, + }; + + // TODO: make this faster by passing argument count at comptime + if (arguments.next()) |current_| { + parse: { + var current = current_; + switch (buffer) { + // fs.write(fd, string[, position[, encoding]], callback) + .string => { + if (current.isNumber()) { + args.position = current.toU32(); + arguments.eat(); + current = arguments.next() orelse break :parse; + } + + if (current.isString()) { + args.encoding = Encoding.fromStringValue(current, ctx.ptr()) orelse Encoding.utf8; + arguments.eat(); + } + }, + // fs.write(fd, buffer[, offset[, length[, position]]], callback) + .buffer => { + if (!current.isNumber()) { + break :parse; + } + + if (!current.isNumber()) break :parse; + args.offset = current.toU32(); + arguments.eat(); + current = arguments.next() orelse break :parse; + + if (!current.isNumber()) break :parse; + args.length = current.toU32(); + arguments.eat(); + current = arguments.next() orelse break :parse; + + if (!current.isNumber()) break :parse; + args.position = current.toU32(); + arguments.eat(); + }, + } + } + } + + return args; + } + }; + + pub const Read = struct { + fd: FileDescriptor, + buffer: Buffer, + offset: u64 = 0, + length: u64 = std.math.maxInt(u64), + position: ?ReadPosition = null, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Read { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + arguments.eat(); + + if (exception.* != null) return null; + + const buffer = Buffer.fromJS(ctx.ptr(), arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "buffer is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "buffer must be a Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + arguments.eat(); + + var args = Read{ + .fd = fd, + .buffer = buffer, + }; + + if (arguments.next()) |current| { + arguments.eat(); + if (current.isNumber()) { + args.offset = current.toU32(); + arguments.eat(); + + if (arguments.remaining.len < 2) { + JSC.throwInvalidArguments( + "length and position are required", + .{}, + ctx, + exception, + ); + + return null; + } + + args.length = arguments.remaining[0].toU32(); + + if (args.length == 0) { + JSC.throwInvalidArguments( + "length must be greater than 0", + .{}, + ctx, + exception, + ); + + return null; + } + + const position: i32 = if (arguments.remaining[1].isNumber()) + arguments.remaining[1].toInt32() + else + -1; + + args.position = if (position > -1) @intCast(ReadPosition, position) else null; + arguments.remaining = arguments.remaining[2..]; + } else if (current.isObject()) { + if (current.getIfPropertyExists(ctx.ptr(), "offset")) |num| { + args.offset = num.toU32(); + } + + if (current.getIfPropertyExists(ctx.ptr(), "length")) |num| { + args.length = num.toU32(); + } + + if (current.getIfPropertyExists(ctx.ptr(), "position")) |num| { + const position: i32 = if (num.isUndefinedOrNull()) -1 else num.toInt32(); + if (position > -1) { + args.position = @intCast(ReadPosition, position); + } + } + } + } + + return args; + } + }; + + /// Asynchronously reads the entire contents of a file. + /// @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + /// If a file descriptor is provided, the underlying file will _not_ be closed automatically. + /// @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + /// If a flag is not provided, it defaults to `'r'`. + pub const ReadFile = struct { + path: PathOrFileDescriptor, + encoding: Encoding = Encoding.utf8, + + flag: FileSystemFlags = FileSystemFlags.@"r", + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?ReadFile { + const path = PathOrFileDescriptor.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or a file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var encoding = Encoding.buffer; + var flag = FileSystemFlags.@"r"; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + if (!encoding_.isUndefinedOrNull()) { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flag")) |flag_| { + flag = FileSystemFlags.fromJS(ctx, flag_, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid flag", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + } + + // Note: Signal is not implemented + return ReadFile{ + .path = path, + .encoding = encoding, + .flag = flag, + }; + } + }; + + pub const WriteFile = struct { + encoding: Encoding = Encoding.utf8, + flag: FileSystemFlags = FileSystemFlags.@"w", + mode: Mode = 0o666, + file: PathOrFileDescriptor, + data: StringOrBuffer, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?WriteFile { + const file = PathOrFileDescriptor.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or a file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const data = StringOrBuffer.fromJS(ctx.ptr(), arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "data must be a string or Buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + arguments.eat(); + + var encoding = Encoding.buffer; + var flag = FileSystemFlags.@"w"; + var mode: Mode = 0o666; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + if (!encoding_.isUndefinedOrNull()) { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flag")) |flag_| { + flag = FileSystemFlags.fromJS(ctx, flag_, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid flag", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid flag", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + } + + // Note: Signal is not implemented + return WriteFile{ + .file = file, + .encoding = encoding, + .flag = flag, + .mode = mode, + .data = data, + }; + } + }; + + pub const AppendFile = WriteFile; + + pub const OpenDir = struct { + path: PathLike, + encoding: Encoding = Encoding.utf8, + + /// Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. Default: 32 + buffer_size: c_int = 32, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?OpenDir { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or a file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var encoding = Encoding.buffer; + var buffer_size: c_int = 32; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding_| { + if (!encoding_.isUndefinedOrNull()) { + encoding = Encoding.fromStringValue(encoding_, ctx.ptr()) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + if (arg.getIfPropertyExists(ctx.ptr(), "bufferSize")) |buffer_size_| { + buffer_size = buffer_size_.toInt32(); + if (buffer_size < 0) { + if (exception.* == null) { + JSC.throwInvalidArguments( + "bufferSize must be > 0", + .{}, + ctx, + exception, + ); + } + return null; + } + } + } + } + + return OpenDir{ + .path = path, + .encoding = encoding, + .buffer_size = buffer_size, + }; + } + }; + pub const Exists = struct { + path: PathLike, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Exists { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Exists{ + .path = path, + }; + } + }; + + pub const Access = struct { + path: PathLike, + mode: FileSystemFlags = FileSystemFlags.@"r", + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Access { + const path = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "path must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var mode = FileSystemFlags.@"r"; + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + mode = FileSystemFlags.fromJS(ctx, arg, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "Invalid mode", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + } + + return Access{ + .path = path, + .mode = mode, + }; + } + }; + + pub const CreateReadStream = struct { + file: PathOrFileDescriptor, + flags: FileSystemFlags = FileSystemFlags.@"r", + encoding: Encoding = Encoding.utf8, + mode: Mode = 0o666, + autoClose: bool = true, + emitClose: bool = true, + start: i32 = 0, + end: i32 = std.math.maxInt(i32), + highwater_mark: u32 = 64 * 1024, + global_object: *JSC.JSGlobalObject, + + pub fn copyToState(this: CreateReadStream, state: *JSC.Node.Readable.State) void { + state.encoding = this.encoding; + state.highwater_mark = this.highwater_mark; + state.start = this.start; + state.end = this.end; + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?CreateReadStream { + var path = PathLike.fromJS(ctx, arguments, exception); + if (exception.* != null) return null; + if (path == null) arguments.eat(); + + var stream = CreateReadStream{ + .file = undefined, + .global_object = ctx.ptr(), + }; + var fd: FileDescriptor = std.math.maxInt(FileDescriptor); + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + stream.encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + stream.mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid mode", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding| { + stream.encoding = Encoding.fromStringValue(encoding, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flags")) |flags| { + stream.flags = FileSystemFlags.fromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid flags", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "fd")) |flags| { + fd = JSC.Node.fileDescriptorFromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "autoClose")) |autoClose| { + stream.autoClose = autoClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "emitClose")) |emitClose| { + stream.emitClose = emitClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "start")) |start| { + stream.start = start.toInt32(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "end")) |end| { + stream.end = end.toInt32(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "highwaterMark")) |highwaterMark| { + stream.highwater_mark = highwaterMark.toU32(); + } + } + } + + if (fd != std.math.maxInt(FileDescriptor)) { + stream.file = .{ .fd = fd }; + } else if (path) |path_| { + stream.file = .{ .path = path_ }; + } else { + JSC.throwInvalidArguments("Missing path or file descriptor", .{}, ctx, exception); + return null; + } + return stream; + } + }; + + pub const CreateWriteStream = struct { + file: PathOrFileDescriptor, + flags: FileSystemFlags = FileSystemFlags.@"w", + encoding: Encoding = Encoding.utf8, + mode: Mode = 0o666, + autoClose: bool = true, + emitClose: bool = true, + start: i32 = 0, + highwater_mark: u32 = 256 * 1024, + global_object: *JSC.JSGlobalObject, + + pub fn copyToState(this: CreateWriteStream, state: *JSC.Node.Writable.State) void { + state.encoding = this.encoding; + state.highwater_mark = this.highwater_mark; + state.start = this.start; + state.emit_close = this.emitClose; + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?CreateWriteStream { + var path = PathLike.fromJS(ctx, arguments, exception); + if (exception.* != null) return null; + if (path == null) arguments.eat(); + + var stream = CreateWriteStream{ + .file = undefined, + .global_object = ctx.ptr(), + }; + var fd: FileDescriptor = std.math.maxInt(FileDescriptor); + + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isString()) { + stream.encoding = Encoding.fromStringValue(arg, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } else if (arg.isObject()) { + if (arg.getIfPropertyExists(ctx.ptr(), "mode")) |mode_| { + stream.mode = JSC.Node.modeFromJS(ctx, mode_, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid mode", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "encoding")) |encoding| { + stream.encoding = Encoding.fromStringValue(encoding, ctx.ptr()) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid encoding", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "flags")) |flags| { + stream.flags = FileSystemFlags.fromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid flags", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "fd")) |flags| { + fd = JSC.Node.fileDescriptorFromJS(ctx, flags, exception) orelse { + if (exception.* != null) { + JSC.throwInvalidArguments( + "Invalid file descriptor", + .{}, + ctx, + exception, + ); + } + return null; + }; + } + + if (arg.getIfPropertyExists(ctx.ptr(), "autoClose")) |autoClose| { + stream.autoClose = autoClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "emitClose")) |emitClose| { + stream.emitClose = emitClose.toBoolean(); + } + + if (arg.getIfPropertyExists(ctx.ptr(), "start")) |start| { + stream.start = start.toInt32(); + } + } + } + + if (fd != std.math.maxInt(FileDescriptor)) { + stream.file = .{ .fd = fd }; + } else if (path) |path_| { + stream.file = .{ .path = path_ }; + } else { + JSC.throwInvalidArguments("Missing path or file descriptor", .{}, ctx, exception); + return null; + } + return stream; + } + }; + + pub const FdataSync = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?FdataSync { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return FdataSync{ + .fd = fd, + }; + } + }; + + pub const CopyFile = struct { + src: PathLike, + dest: PathLike, + mode: Constants.Copyfile, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?CopyFile { + const src = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "src must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + const dest = PathLike.fromJS(ctx, arguments, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "dest must be a string or buffer", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + var mode: i32 = 0; + if (arguments.next()) |arg| { + arguments.eat(); + if (arg.isNumber()) { + mode = arg.toInt32(); + } + } + + return CopyFile{ + .src = src, + .dest = dest, + .mode = @intToEnum(Constants.Copyfile, mode), + }; + } + }; + + pub const WriteEv = struct { + fd: FileDescriptor, + buffers: []const ArrayBuffer, + position: ReadPosition, + }; + + pub const ReadEv = struct { + fd: FileDescriptor, + buffers: []ArrayBuffer, + position: ReadPosition, + }; + + pub const Copy = struct { + pub const FilterCallback = fn (source: string, destination: string) bool; + /// Dereference symlinks + /// @default false + dereference: bool = false, + + /// When `force` is `false`, and the destination + /// exists, throw an error. + /// @default false + errorOnExist: bool = false, + + /// Function to filter copied files/directories. Return + /// `true` to copy the item, `false` to ignore it. + filter: ?FilterCallback = null, + + /// Overwrite existing file or directory. _The copy + /// operation will ignore errors if you set this to false and the destination + /// exists. Use the `errorOnExist` option to change this behavior. + /// @default true + force: bool = true, + + /// When `true` timestamps from `src` will + /// be preserved. + /// @default false + preserve_timestamps: bool = false, + + /// Copy directories recursively. + /// @default false + recursive: bool = false, + }; + + pub const UnwatchFile = void; + pub const Watch = void; + pub const WatchFile = void; + pub const Fsync = struct { + fd: FileDescriptor, + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?Fsync { + const fd = JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "File descriptor is required", + .{}, + ctx, + exception, + ); + } + return null; + }, exception) orelse { + if (exception.* == null) { + JSC.throwInvalidArguments( + "fd must be a number", + .{}, + ctx, + exception, + ); + } + return null; + }; + + if (exception.* != null) return null; + + return Fsync{ + .fd = fd, + }; + } + }; +}; + +const Constants = struct { + // File Access Constants + /// Constant for fs.access(). File is visible to the calling process. + pub const F_OK = std.os.F_OK; + /// Constant for fs.access(). File can be read by the calling process. + pub const R_OK = std.os.R_OK; + /// Constant for fs.access(). File can be written by the calling process. + pub const W_OK = std.os.W_OK; + /// Constant for fs.access(). File can be executed by the calling process. + pub const X_OK = std.os.X_OK; + // File Copy Constants + + pub const Copyfile = enum(i32) { + _, + pub const exclusive = 1; + pub const clone = 2; + pub const force = 4; + + pub inline fn isForceClone(this: Copyfile) bool { + return (@enumToInt(this) & COPYFILE_FICLONE_FORCE) != 0; + } + + pub inline fn shouldntOverwrite(this: Copyfile) bool { + return (@enumToInt(this) & COPYFILE_EXCL) != 0; + } + + pub inline fn canUseClone(this: Copyfile) bool { + _ = this; + return Environment.isMac; + // return (@enumToInt(this) | COPYFILE_FICLONE) != 0; + } + }; + + /// Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. + pub const COPYFILE_EXCL: i32 = 1 << Copyfile.exclusive; + + /// + /// Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + /// If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + pub const COPYFILE_FICLONE: i32 = 1 << Copyfile.clone; + /// + /// Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + /// If the underlying platform does not support copy-on-write, then the operation will fail with an error. + pub const COPYFILE_FICLONE_FORCE: i32 = 1 << Copyfile.force; + // File Open Constants + /// Constant for fs.open(). Flag indicating to open a file for read-only access. + pub const O_RDONLY = std.os.O.RDONLY; + /// Constant for fs.open(). Flag indicating to open a file for write-only access. + pub const O_WRONLY = std.os.O.WRONLY; + /// Constant for fs.open(). Flag indicating to open a file for read-write access. + pub const O_RDWR = std.os.O.RDWR; + /// Constant for fs.open(). Flag indicating to create the file if it does not already exist. + pub const O_CREAT = std.os.O.CREAT; + /// Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. + pub const O_EXCL = std.os.O.EXCL; + + /// + /// Constant for fs.open(). Flag indicating that if path identifies a terminal device, + /// opening the path shall not cause that terminal to become the controlling terminal for the process + /// (if the process does not already have one). + pub const O_NOCTTY = std.os.O.NOCTTY; + /// Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. + pub const O_TRUNC = std.os.O.TRUNC; + /// Constant for fs.open(). Flag indicating that data will be appended to the end of the file. + pub const O_APPEND = std.os.O.APPEND; + /// Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. + pub const O_DIRECTORY = std.os.O.DIRECTORY; + + /// + /// constant for fs.open(). + /// Flag indicating reading accesses to the file system will no longer result in + /// an update to the atime information associated with the file. + /// This flag is available on Linux operating systems only. + pub const O_NOATIME = std.os.O.NOATIME; + /// Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. + pub const O_NOFOLLOW = std.os.O.NOFOLLOW; + /// Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. + pub const O_SYNC = std.os.O.SYNC; + /// Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. + pub const O_DSYNC = std.os.O.DSYNC; + /// Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. + pub const O_SYMLINK = std.os.O.SYMLINK; + /// Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. + pub const O_DIRECT = std.os.O.DIRECT; + /// Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. + pub const O_NONBLOCK = std.os.O.NONBLOCK; + // File Type Constants + /// Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. + pub const S_IFMT = std.os.S.IFMT; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. + pub const S_IFREG = std.os.S.IFREG; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. + pub const S_IFDIR = std.os.S.IFDIR; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. + pub const S_IFCHR = std.os.S.IFCHR; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. + pub const S_IFBLK = std.os.S.IFBLK; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. + pub const S_IFIFO = std.os.S.IFIFO; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. + pub const S_IFLNK = std.os.S.IFLNK; + /// Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. + pub const S_IFSOCK = std.os.S.IFSOCK; + // File Mode Constants + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. + pub const S_IRWXU = std.os.S.IRWXU; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. + pub const S_IRUSR = std.os.S.IRUSR; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. + pub const S_IWUSR = std.os.S.IWUSR; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. + pub const S_IXUSR = std.os.S.IXUSR; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. + pub const S_IRWXG = std.os.S.IRWXG; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. + pub const S_IRGRP = std.os.S.IRGRP; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. + pub const S_IWGRP = std.os.S.IWGRP; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. + pub const S_IXGRP = std.os.S.IXGRP; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. + pub const S_IRWXO = std.os.S.IRWXO; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. + pub const S_IROTH = std.os.S.IROTH; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. + pub const S_IWOTH = std.os.S.IWOTH; + /// Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. + pub const S_IXOTH = std.os.S.IXOTH; + + /// + /// When set, a memory file mapping is used to access the file. This flag + /// is available on Windows operating systems only. On other operating systems, + /// this flag is ignored. + pub const UV_FS_O_FILEMAP = 49152; +}; + +const Return = struct { + pub const Access = void; + pub const AppendFile = void; + pub const Close = void; + pub const CopyFile = void; + pub const Exists = bool; + pub const Fchmod = void; + pub const Chmod = void; + pub const Fchown = void; + pub const Fdatasync = void; + pub const Fstat = Stats; + pub const Rm = void; + pub const Fsync = void; + pub const Ftruncate = void; + pub const Futimes = void; + pub const Lchmod = void; + pub const Lchown = void; + pub const Link = void; + pub const Lstat = Stats; + pub const Mkdir = string; + pub const Mkdtemp = PathString; + pub const Open = FileDescriptor; + pub const WriteFile = void; + pub const Read = struct { + bytes_read: u32, + buffer: Buffer, + const fields = .{ + .@"bytesRead" = JSC.ZigString.init("bytesRead"), + .@"buffer" = JSC.ZigString.init("buffer"), + }; + // Excited for the issue that's like "cannot read file bigger than 2 GB" + pub fn toJS(this: Read, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return JSC.JSValue.createObject2( + ctx.ptr(), + &fields.bytesRead, + &fields.buffer, + JSC.JSValue.jsNumberFromInt32(@intCast(i32, @minimum(std.math.maxInt(i32), this.bytes_read))), + JSC.JSValue.fromRef(this.buffer.toJS(ctx, exception)), + ).asObjectRef(); + } + }; + pub const Write = struct { + bytes_written: u32, + buffer: StringOrBuffer, + const fields = .{ + .@"bytesWritten" = JSC.ZigString.init("bytesWritten"), + .@"buffer" = JSC.ZigString.init("buffer"), + }; + + // Excited for the issue that's like "cannot read file bigger than 2 GB" + pub fn toJS(this: Write, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return JSC.JSValue.createObject2( + ctx.ptr(), + &fields.bytesWritten, + &fields.buffer, + JSC.JSValue.jsNumberFromInt32(@intCast(i32, @minimum(std.math.maxInt(i32), this.bytes_written))), + JSC.JSValue.fromRef(this.buffer.toJS(ctx, exception)), + ).asObjectRef(); + } + }; + + pub const Readdir = union(Tag) { + with_file_types: []const DirEnt, + buffers: []const Buffer, + files: []const PathString, + + pub const Tag = enum { + with_file_types, + buffers, + files, + }; + + 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.withTypeClone([]const PathString, this.files, ctx, exception, true), + }; + } + }; + pub const ReadFile = StringOrBuffer; + pub const Readlink = StringOrBuffer; + pub const Realpath = StringOrBuffer; + pub const RealpathNative = Realpath; + pub const Rename = void; + pub const Rmdir = void; + pub const Stat = Stats; + + pub const Symlink = void; + pub const Truncate = void; + pub const Unlink = void; + pub const UnwatchFile = void; + pub const Watch = void; + pub const WatchFile = void; + pub const Utimes = void; + + pub const CreateReadStream = *JSC.Node.Stream; + pub const CreateWriteStream = *JSC.Node.Stream; + pub const Chown = void; + pub const Lutimes = void; +}; + +/// Bun's implementation of the Node.js "fs" module +/// https://nodejs.org/api/fs.html +/// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/fs.d.ts +pub const NodeFS = struct { + async_io: *AsyncIO, + + /// Buffer to store a temporary file path that might appear in a returned error message. + /// + /// We want to avoid allocating a new path buffer for every error message so that JSC can clone + GC it. + /// That means a stack-allocated buffer won't suffice. Instead, we re-use + /// the heap allocated buffer on the NodefS struct + sync_error_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined, + + pub const ReturnType = Return; + + pub fn access(this: *NodeFS, args: Arguments.Access, comptime _: Flavor) Maybe(Return.Access) { + var path = args.path.sliceZ(&this.sync_error_buf); + const rc = Syscall.system.access(path, @enumToInt(args.mode)); + return Maybe(Return.Access).errnoSysP(rc, .access, path) orelse Maybe(Return.Access).success; + } + + pub fn appendFile(this: *NodeFS, args: Arguments.AppendFile, comptime flavor: Flavor) Maybe(Return.AppendFile) { + var data = args.data.slice(); + + switch (args.file) { + .fd => |fd| { + switch (comptime flavor) { + .sync => { + while (data.len > 0) { + const written = switch (Syscall.write(fd, data)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + data = data[written..]; + } + + return Maybe(Return.AppendFile).success; + }, + else => { + _ = this; + @compileError("Not implemented yet"); + }, + } + }, + .path => |path_| { + const path = path_.sliceZ(&this.sync_error_buf); + switch (comptime flavor) { + .sync => { + const fd = switch (Syscall.open(path, @enumToInt(FileSystemFlags.@"a"), 000666)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + + defer { + _ = Syscall.close(fd); + } + + while (data.len > 0) { + const written = switch (Syscall.write(fd, data)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + data = data[written..]; + } + + return Maybe(Return.AppendFile).success; + }, + else => { + _ = this; + @compileError("Not implemented yet"); + }, + } + }, + } + + return Maybe(Return.AppendFile).todo; + } + + pub fn close(this: *NodeFS, args: Arguments.Close, comptime flavor: Flavor) Maybe(Return.Close) { + switch (comptime flavor) { + .sync => { + return if (Syscall.close(args.fd)) |err| .{ .err = err } else Maybe(Return.Close).success; + }, + else => { + _ = this; + }, + } + + return .{ .err = Syscall.Error.todo }; + } + + /// https://github.com/libuv/libuv/pull/2233 + /// https://github.com/pnpm/pnpm/issues/2761 + /// https://github.com/libuv/libuv/pull/2578 + /// https://github.com/nodejs/node/issues/34624 + pub fn copyFile(this: *NodeFS, args: Arguments.CopyFile, comptime flavor: Flavor) Maybe(Return.CopyFile) { + const ret = Maybe(Return.CopyFile); + + switch (comptime flavor) { + .sync => { + var src_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var dest_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var src = args.src.sliceZ(&src_buf); + var dest = args.dest.sliceZ(&dest_buf); + + if (comptime Environment.isMac) { + if (args.mode.isForceClone()) { + // https://www.manpagez.com/man/2/clonefile/ + return ret.errnoSysP(C.clonefile(src, dest, 0), .clonefile, src) orelse ret.success; + } + + var mode: Mode = C.darwin.COPYFILE_ACL | C.darwin.COPYFILE_DATA; + if (args.mode.shouldntOverwrite()) { + mode |= C.darwin.COPYFILE_EXCL; + } + + return ret.errnoSysP(C.copyfile(src, dest, null, mode), .copyfile, src) orelse ret.success; + } + + if (comptime Environment.isLinux) { + const src_fd = switch (Syscall.open(src, std.os.O.RDONLY, 0644)) { + .result => |result| result, + .err => |err| return .{ .err = err }, + }; + defer { + _ = Syscall.close(src_fd); + } + + const stat_: linux.Stat = switch (Syscall.fstat(src_fd)) { + .result => |result| result, + .err => |err| return Maybe(Return.CopyFile){ .err = err }, + }; + + if (!os.S.ISREG(stat_.mode)) { + return Maybe(Return.CopyFile){ .err = .{ .errno = @enumToInt(C.SystemErrno.ENOTSUP) } }; + } + + var flags: Mode = std.os.O.CREAT | std.os.O.WRONLY | std.os.O.TRUNC; + if (args.mode.shouldntOverwrite()) { + flags |= std.os.O.EXCL; + } + + const dest_fd = switch (Syscall.open(dest, flags, flags)) { + .result => |result| result, + .err => |err| return Maybe(Return.CopyFile){ .err = err }, + }; + defer { + _ = Syscall.close(dest_fd); + } + + var off_in_copy = @bitCast(i64, @as(u64, 0)); + var off_out_copy = @bitCast(i64, @as(u64, 0)); + + // https://manpages.debian.org/testing/manpages-dev/ioctl_ficlone.2.en.html + if (args.mode.isForceClone()) { + return Maybe(Return.CopyFile).todo; + } + + var size = @intCast(usize, @maximum(stat_.size, 0)); + while (size > 0) { + // Linux Kernel 5.3 or later + const written = linux.copy_file_range(src_fd, &off_in_copy, dest_fd, &off_out_copy, size, 0); + if (ret.errnoSysP(written, .copy_file_range, dest)) |err| return err; + // wrote zero bytes means EOF + if (written == 0) break; + size -|= written; + } + + return ret.success; + } + }, + else => { + _ = args; + _ = this; + _ = flavor; + }, + } + + return Maybe(Return.CopyFile).todo; + } + pub fn exists(this: *NodeFS, args: Arguments.Exists, comptime flavor: Flavor) Maybe(Return.Exists) { + const Ret = Maybe(Return.Exists); + const path = args.path.sliceZ(&this.sync_error_buf); + switch (comptime flavor) { + .sync => { + // access() may not work correctly on NFS file systems with UID + // mapping enabled, because UID mapping is done on the server and + // hidden from the client, which checks permissions. Similar + // problems can occur to FUSE mounts. + const rc = (system.access(path, std.os.F_OK)); + return Ret{ .result = rc == 0 }; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Ret.todo; + } + + pub fn chown(this: *NodeFS, args: Arguments.Chown, comptime flavor: Flavor) Maybe(Return.Chown) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => return Syscall.chown(path, args.uid, args.gid), + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Chown).todo; + } + + /// This should almost never be async + pub fn chmod(this: *NodeFS, args: Arguments.Chmod, comptime flavor: Flavor) Maybe(Return.Chmod) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Chmod).errnoSysP(C.chmod(path, args.mode), .chmod, path) orelse + Maybe(Return.Chmod).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Chmod).todo; + } + + /// This should almost never be async + pub fn fchmod(this: *NodeFS, args: Arguments.FChmod, comptime flavor: Flavor) Maybe(Return.Fchmod) { + switch (comptime flavor) { + .sync => { + return Syscall.fchmod(args.fd, args.mode); + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fchmod).todo; + } + pub fn fchown(this: *NodeFS, args: Arguments.Fchown, comptime flavor: Flavor) Maybe(Return.Fchown) { + switch (comptime flavor) { + .sync => { + return Maybe(Return.Fchown).errnoSys(C.fchown(args.fd, args.uid, args.gid), .fchown) orelse + Maybe(Return.Fchown).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fchown).todo; + } + pub fn fdatasync(this: *NodeFS, args: Arguments.FdataSync, comptime flavor: Flavor) Maybe(Return.Fdatasync) { + switch (comptime flavor) { + .sync => return Maybe(Return.Fdatasync).errnoSys(system.fdatasync(args.fd), .fdatasync) orelse + Maybe(Return.Fdatasync).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fdatasync).todo; + } + pub fn fstat(this: *NodeFS, args: Arguments.Fstat, comptime flavor: Flavor) Maybe(Return.Fstat) { + if (args.big_int) return Maybe(Return.Fstat).todo; + + switch (comptime flavor) { + .sync => { + return switch (Syscall.fstat(args.fd)) { + .result => |result| Maybe(Return.Fstat){ .result = Stats.init(result) }, + .err => |err| Maybe(Return.Fstat){ .err = err }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fstat).todo; + } + + pub fn fsync(this: *NodeFS, args: Arguments.Fsync, comptime flavor: Flavor) Maybe(Return.Fsync) { + switch (comptime flavor) { + .sync => return Maybe(Return.Fsync).errnoSys(system.fsync(args.fd), .fsync) orelse + Maybe(Return.Fsync).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Fsync).todo; + } + + pub fn ftruncate(this: *NodeFS, args: Arguments.FTruncate, comptime flavor: Flavor) Maybe(Return.Ftruncate) { + switch (comptime flavor) { + .sync => return Maybe(Return.Ftruncate).errnoSys(system.ftruncate(args.fd, args.len orelse 0), .ftruncate) orelse + Maybe(Return.Ftruncate).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Ftruncate).todo; + } + pub fn futimes(this: *NodeFS, args: Arguments.Futimes, comptime flavor: Flavor) Maybe(Return.Futimes) { + var times = [2]std.os.timespec{ + .{ + .tv_sec = args.mtime, + .tv_nsec = 0, + }, + .{ + .tv_sec = args.atime, + .tv_nsec = 0, + }, + }; + + switch (comptime flavor) { + .sync => return if (Maybe(Return.Futimes).errnoSys(system.futimens(args.fd, ×), .futimens)) |err| + err + else + Maybe(Return.Futimes).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Futimes).todo; + } + + pub fn lchmod(this: *NodeFS, args: Arguments.LCHmod, comptime flavor: Flavor) Maybe(Return.Lchmod) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Lchmod).errnoSysP(C.lchmod(path, args.mode), .lchmod, path) orelse + Maybe(Return.Lchmod).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lchmod).todo; + } + + pub fn lchown(this: *NodeFS, args: Arguments.LChown, comptime flavor: Flavor) Maybe(Return.Lchown) { + const path = args.path.sliceZ(&this.sync_error_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Lchown).errnoSysP(C.lchown(path, args.uid, args.gid), .lchown, path) orelse + Maybe(Return.Lchown).success; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lchown).todo; + } + pub fn link(this: *NodeFS, args: Arguments.Link, comptime flavor: Flavor) Maybe(Return.Link) { + var new_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + const from = args.old_path.sliceZ(&this.sync_error_buf); + const to = args.new_path.sliceZ(&new_path_buf); + + switch (comptime flavor) { + .sync => { + return Maybe(Return.Link).errnoSysP(system.link(from, to, 0), .link, from) orelse + Maybe(Return.Link).success; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Link).todo; + } + pub fn lstat(this: *NodeFS, args: Arguments.Lstat, comptime flavor: Flavor) Maybe(Return.Lstat) { + 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 = Return.Lstat.init(result) }, + .err => |err| Maybe(Return.Lstat){ .err = err }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lstat).todo; + } + + pub fn mkdir(this: *NodeFS, args: Arguments.Mkdir, comptime flavor: Flavor) Maybe(Return.Mkdir) { + return if (args.recursive) mkdirRecursive(this, args, flavor) else mkdirNonRecursive(this, args, flavor); + } + // Node doesn't absolute the path so we don't have to either + fn mkdirNonRecursive(this: *NodeFS, args: Arguments.Mkdir, comptime flavor: Flavor) Maybe(Return.Mkdir) { + switch (comptime flavor) { + .sync => { + const path = args.path.sliceZ(&this.sync_error_buf); + return switch (Syscall.mkdir(path, args.mode)) { + .result => Maybe(Return.Mkdir){ .result = "" }, + .err => |err| Maybe(Return.Mkdir){ .err = err }, + }; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Mkdir).todo; + } + + // TODO: windows + // TODO: verify this works correctly with unicode codepoints + fn mkdirRecursive(this: *NodeFS, args: Arguments.Mkdir, comptime flavor: Flavor) Maybe(Return.Mkdir) { + const Option = Maybe(Return.Mkdir); + if (comptime Environment.isWindows) @compileError("This needs to be implemented on Windows."); + + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + const path = args.path.sliceZWithForceCopy(&buf, true); + const len = @truncate(u16, path.len); + + // First, attempt to create the desired directory + // If that fails, then walk back up the path until we have a match + switch (Syscall.mkdir(path, args.mode)) { + .err => |err| { + switch (err.getErrno()) { + else => { + @memcpy(&this.sync_error_buf, path.ptr, len); + return .{ .err = err.withPath(this.sync_error_buf[0..len]) }; + }, + + .EXIST => { + return Option{ .result = "" }; + }, + // continue + .NOENT => {}, + } + }, + .result => { + return Option{ .result = args.path.slice() }; + }, + } + + var working_mem = &this.sync_error_buf; + @memcpy(working_mem, path.ptr, len); + + var i: u16 = len - 1; + + // iterate backwards until creating the directory works successfully + while (i > 0) : (i -= 1) { + if (path[i] == std.fs.path.sep) { + working_mem[i] = 0; + var parent: [:0]u8 = working_mem[0..i :0]; + + switch (Syscall.mkdir(parent, args.mode)) { + .err => |err| { + working_mem[i] = std.fs.path.sep; + switch (err.getErrno()) { + .EXIST => { + // Handle race condition + break; + }, + .NOENT => { + continue; + }, + else => return .{ .err = err.withPath(parent) }, + } + }, + .result => { + // We found a parent that worked + working_mem[i] = std.fs.path.sep; + break; + }, + } + } + } + var first_match: u16 = i; + i += 1; + // after we find one that works, we go forward _after_ the first working directory + while (i < len) : (i += 1) { + if (path[i] == std.fs.path.sep) { + working_mem[i] = 0; + var parent: [:0]u8 = working_mem[0..i :0]; + + switch (Syscall.mkdir(parent, args.mode)) { + .err => |err| { + working_mem[i] = std.fs.path.sep; + switch (err.getErrno()) { + .EXIST => { + std.debug.assert(false); + continue; + }, + else => return .{ .err = err }, + } + }, + + .result => { + working_mem[i] = std.fs.path.sep; + }, + } + } + } + + // Our final directory will not have a trailing separator + // so we have to create it once again + switch (Syscall.mkdir(working_mem[0..len :0], args.mode)) { + .err => |err| { + switch (err.getErrno()) { + // handle the race condition + .EXIST => { + var display_path: []const u8 = ""; + if (first_match != std.math.maxInt(u16)) { + // TODO: this leaks memory + display_path = _global.default_allocator.dupe(u8, display_path[0..first_match]) catch unreachable; + } + return Option{ .result = display_path }; + }, + + // NOENT shouldn't happen here + else => return .{ + .err = err.withPath(path), + }, + } + }, + .result => { + var display_path = args.path.slice(); + if (first_match != std.math.maxInt(u16)) { + // TODO: this leaks memory + display_path = _global.default_allocator.dupe(u8, display_path[0..first_match]) catch unreachable; + } + return Option{ .result = display_path }; + }, + } + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Mkdir).todo; + } + + pub fn mkdtemp(this: *NodeFS, args: Arguments.MkdirTemp, comptime flavor: Flavor) Maybe(Return.Mkdtemp) { + var prefix_buf = &this.sync_error_buf; + prefix_buf[0] = 0; + const len = args.prefix.len; + if (len > 0) { + @memcpy(prefix_buf, args.prefix.ptr, len); + prefix_buf[len] = 0; + } + + const rc = C.mkdtemp(prefix_buf); + switch (std.c.getErrno(@ptrToInt(rc))) { + .SUCCESS => {}, + else => |errno| return .{ .err = Syscall.Error{ .errno = @truncate(Syscall.Error.Int, @enumToInt(errno)), .syscall = .mkdtemp } }, + } + + _ = this; + _ = flavor; + return .{ + .result = PathString.init(_global.default_allocator.dupe(u8, std.mem.span(rc.?)) catch unreachable), + }; + } + pub fn open(this: *NodeFS, args: Arguments.Open, comptime flavor: Flavor) Maybe(Return.Open) { + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + const path = args.path.sliceZ(&this.sync_error_buf); + return switch (Syscall.open(path, @enumToInt(args.flags), args.mode)) { + .err => |err| .{ + .err = err.withPath(args.path.slice()), + }, + .result => |fd| .{ .result = fd }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Open).todo; + } + pub fn openDir(this: *NodeFS, args: Arguments.OpenDir, comptime flavor: Flavor) Maybe(Return.OpenDir) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.OpenDir).todo; + } + + fn _read(this: *NodeFS, args: Arguments.Read, comptime flavor: Flavor) Maybe(Return.Read) { + _ = args; + _ = this; + _ = flavor; + std.debug.assert(args.position == null); + + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(buf.len, args.length)]; + + return switch (Syscall.read(args.fd, buf)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ + .result = .{ .bytes_read = @truncate(u32, amt), .buffer = args.buffer }, + }, + }; + }, + else => {}, + } + + return Maybe(Return.Read).todo; + } + + fn _pread(this: *NodeFS, args: Arguments.Read, comptime flavor: Flavor) Maybe(Return.Read) { + _ = args; + _ = this; + _ = flavor; + + switch (comptime flavor) { + // The sync version does no allocation except when returning the path + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(buf.len, args.length)]; + + return switch (Syscall.pread(args.fd, buf, args.position.?)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ + .result = .{ .bytes_read = @truncate(u32, amt), .buffer = args.buffer }, + }, + }; + }, + else => {}, + } + + return Maybe(Return.Read).todo; + } + + pub fn read(this: *NodeFS, args: Arguments.Read, comptime flavor: Flavor) Maybe(Return.Read) { + return if (args.position != null) + this._pread( + args, + comptime flavor, + ) + else + this._read( + args, + comptime flavor, + ); + } + + pub fn write(this: *NodeFS, args: Arguments.Write, comptime flavor: Flavor) Maybe(Return.Write) { + return if (args.position != null) _pwrite(this, args, flavor) else _write(this, args, flavor); + } + fn _write(this: *NodeFS, args: Arguments.Write, comptime flavor: Flavor) Maybe(Return.Write) { + _ = args; + _ = this; + _ = flavor; + + switch (comptime flavor) { + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(buf.len, args.length)]; + + return switch (Syscall.write(args.fd, buf)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ + .result = .{ .bytes_written = @truncate(u32, amt), .buffer = args.buffer }, + }, + }; + }, + else => {}, + } + + return Maybe(Return.Write).todo; + } + + fn _pwrite(this: *NodeFS, args: Arguments.Write, comptime flavor: Flavor) Maybe(Return.Write) { + _ = args; + _ = this; + _ = flavor; + + const position = args.position.?; + + switch (comptime flavor) { + .sync => { + var buf = args.buffer.slice(); + buf = buf[@minimum(args.offset, buf.len)..]; + buf = buf[0..@minimum(args.length, buf.len)]; + + return switch (Syscall.pwrite(args.fd, buf, position)) { + .err => |err| .{ + .err = err, + }, + .result => |amt| .{ .result = .{ .bytes_written = @truncate(u32, amt), .buffer = args.buffer } }, + }; + }, + else => {}, + } + + return Maybe(Return.Write).todo; + } + + pub fn readdir(this: *NodeFS, args: Arguments.Readdir, comptime flavor: Flavor) Maybe(Return.Readdir) { + return switch (args.encoding) { + .buffer => _readdir( + this, + args, + Buffer, + flavor, + ), + else => { + if (!args.with_file_types) { + return _readdir( + this, + args, + PathString, + flavor, + ); + } + + return _readdir( + this, + args, + DirEnt, + flavor, + ); + }, + }; + } + + pub fn _readdir( + this: *NodeFS, + args: Arguments.Readdir, + comptime ExpectedType: type, + comptime flavor: Flavor, + ) Maybe(Return.Readdir) { + const file_type = comptime switch (ExpectedType) { + DirEnt => "with_file_types", + PathString => "files", + Buffer => "buffers", + 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(_global.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 => { + _global.default_allocator.free(item.name.slice()); + }, + Buffer => { + item.destroy(); + }, + PathString => { + _global.default_allocator.free(item.slice()); + }, + else => unreachable, + } + } + + entries.deinit(); + + return .{ + .err = err.withPath(args.path.slice()), + }; + }, + .result => |ent| ent, + }) |current| : (entry = iterator.next()) { + switch (comptime ExpectedType) { + DirEnt => { + entries.append(.{ + .name = PathString.init(_global.default_allocator.dupe(u8, current.name.slice()) catch unreachable), + .kind = current.kind, + }) catch unreachable; + }, + Buffer => { + const slice = current.name.slice(); + entries.append(Buffer.fromString(slice, _global.default_allocator) catch unreachable) catch unreachable; + }, + PathString => { + entries.append( + PathString.init(_global.default_allocator.dupe(u8, current.name.slice()) catch unreachable), + ) catch unreachable; + }, + else => unreachable, + } + } + + return .{ .result = @unionInit(Return.Readdir, file_type, entries.items) }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Readdir).todo; + } + pub fn readFile(this: *NodeFS, args: Arguments.ReadFile, comptime flavor: Flavor) Maybe(Return.ReadFile) { + 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); + 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)) { + .err => |err| return .{ + .err = err, + }, + .result => |stat_| stat_, + }; + + const size = @intCast(u64, @maximum(stat_.size, 0)); + var buf = std.ArrayList(u8).init(_global.default_allocator); + buf.ensureTotalCapacity(size + 16) catch unreachable; + buf.expandToCapacity(); + var total: usize = 0; + + while (total < size) { + switch (Syscall.read(fd, buf.items[total..])) { + .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(512384) catch unreachable; + buf.expandToCapacity(); + continue; + } + + if (amt == 0) { + break; + } + }, + } + } + buf.items.len = total; + return switch (args.encoding) { + .buffer => .{ + .result = .{ + .buffer = Buffer.fromBytes(buf.items, _global.default_allocator, JSC.C.JSTypedArrayType.kJSTypedArrayTypeUint8Array), + }, + }, + else => .{ + .result = .{ + .string = buf.items, + }, + }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.ReadFile).todo; + } + + pub fn writeFile(this: *NodeFS, args: Arguments.WriteFile, comptime flavor: Flavor) Maybe(Return.WriteFile) { + var path: [:0]const u8 = undefined; + + switch (comptime flavor) { + .sync => { + const fd = switch (args.file) { + .path => brk: { + path = args.file.path.sliceZ(&this.sync_error_buf); + break :brk switch (Syscall.open( + path, + @enumToInt(args.flag) | os.O.NOCTTY, + args.mode, + )) { + .err => |err| return .{ + .err = err.withPath(path), + }, + .result => |fd_| fd_, + }; + }, + .fd => |_fd| _fd, + }; + + defer { + if (args.file == .path) + _ = Syscall.close(fd); + } + + var buf = args.data.slice(); + + while (buf.len > 0) { + switch (Syscall.write(fd, buf)) { + .err => |err| return .{ + .err = err, + }, + .result => |amt| { + buf = buf[amt..]; + if (amt == 0) { + break; + } + }, + } + } + return Maybe(Return.WriteFile).success; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.WriteFile).todo; + } + + pub fn readlink(this: *NodeFS, args: Arguments.Readlink, comptime flavor: Flavor) Maybe(Return.Readlink) { + var outbuf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var inbuf = &this.sync_error_buf; + switch (comptime flavor) { + .sync => { + const path = args.path.sliceZ(inbuf); + + const len = switch (Syscall.readlink(path, &outbuf)) { + .err => |err| return .{ + .err = err.withPath(args.path.slice()), + }, + .result => |buf_| buf_, + }; + + return .{ + .result = switch (args.encoding) { + .buffer => .{ + .buffer = Buffer.fromString(outbuf[0..len], _global.default_allocator) catch unreachable, + }, + else => .{ + .string = _global.default_allocator.dupe(u8, outbuf[0..len]) catch unreachable, + }, + }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Readlink).todo; + } + pub fn realpath(this: *NodeFS, args: Arguments.Realpath, comptime flavor: Flavor) Maybe(Return.Realpath) { + var outbuf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + var inbuf = &this.sync_error_buf; + if (comptime Environment.allow_assert) std.debug.assert(FileSystem.instance_loaded); + + switch (comptime flavor) { + .sync => { + var path_slice = args.path.slice(); + + var parts = [_]string{ FileSystem.instance.top_level_dir, path_slice }; + var path_ = FileSystem.instance.absBuf(&parts, inbuf); + inbuf[path_.len] = 0; + var path: [:0]u8 = inbuf[0..path_.len :0]; + + const flags = if (comptime Environment.isLinux) + // O_PATH is faster + std.os.O.PATH + else + std.os.O.RDONLY; + + const fd = switch (Syscall.open(path, flags, 0)) { + .err => |err| return .{ + .err = err.withPath(path), + }, + .result => |fd_| fd_, + }; + + defer { + _ = Syscall.close(fd); + } + + const buf = switch (Syscall.getFdPath(fd, &outbuf)) { + .err => |err| return .{ + .err = err.withPath(path), + }, + .result => |buf_| buf_, + }; + + return .{ + .result = switch (args.encoding) { + .buffer => .{ + .buffer = Buffer.fromString(buf, _global.default_allocator) catch unreachable, + }, + else => .{ + .string = _global.default_allocator.dupe(u8, buf) catch unreachable, + }, + }, + }; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Realpath).todo; + } + pub const realpathNative = realpath; + // pub fn realpathNative(this: *NodeFS, args: Arguments.Realpath, comptime flavor: Flavor) Maybe(Return.Realpath) { + // _ = args; + // _ = this; + // _ = flavor; + // return error.NotImplementedYet; + // } + pub fn rename(this: *NodeFS, args: Arguments.Rename, comptime flavor: Flavor) Maybe(Return.Rename) { + var from_buf = &this.sync_error_buf; + var to_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + + switch (comptime flavor) { + .sync => { + var from = args.old_path.sliceZ(from_buf); + var to = args.new_path.sliceZ(&to_buf); + return Syscall.rename(from, to); + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Rename).todo; + } + pub fn rmdir(this: *NodeFS, args: Arguments.RmDir, comptime flavor: Flavor) Maybe(Return.Rmdir) { + switch (comptime flavor) { + .sync => { + var dir = args.old_path.sliceZ(&this.sync_error_buf); + _ = dir; + }, + else => {}, + } + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Rmdir).todo; + } + pub fn rm(this: *NodeFS, args: Arguments.RmDir, comptime flavor: Flavor) Maybe(Return.Rm) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Rm).todo; + } + pub fn stat(this: *NodeFS, args: Arguments.Stat, comptime flavor: Flavor) Maybe(Return.Stat) { + 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 = Return.Stat.init(result) }, + .err => |err| Maybe(Return.Stat){ .err = err }, + }); + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Stat).todo; + } + + pub fn symlink(this: *NodeFS, args: Arguments.Symlink, comptime flavor: Flavor) Maybe(Return.Symlink) { + var to_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + + switch (comptime flavor) { + .sync => { + return Syscall.symlink( + args.old_path.sliceZ(&this.sync_error_buf), + args.new_path.sliceZ(&to_buf), + ); + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Symlink).todo; + } + fn _truncate(this: *NodeFS, path: PathLike, len: u32, comptime flavor: Flavor) Maybe(Return.Truncate) { + switch (comptime flavor) { + .sync => { + return Maybe(Return.Truncate).errno(C.truncate(path.sliceZ(&this.sync_error_buf), len)) orelse + Maybe(Return.Truncate).success; + }, + else => {}, + } + + _ = this; + _ = flavor; + return Maybe(Return.Truncate).todo; + } + pub fn truncate(this: *NodeFS, args: Arguments.Truncate, comptime flavor: Flavor) Maybe(Return.Truncate) { + return switch (args.path) { + .fd => |fd| this.ftruncate( + Arguments.FTruncate{ .fd = fd, .len = args.len }, + flavor, + ), + .path => this._truncate( + args.path.path, + args.len, + flavor, + ), + }; + } + pub fn unlink(this: *NodeFS, args: Arguments.Unlink, comptime flavor: Flavor) Maybe(Return.Unlink) { + switch (comptime flavor) { + .sync => { + return Maybe(Return.Unlink).errnoSysP(system.unlink(args.path.sliceZ(&this.sync_error_buf)), .unlink, args.path.slice()) orelse + Maybe(Return.Unlink).success; + }, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Unlink).todo; + } + pub fn unwatchFile(this: *NodeFS, args: Arguments.UnwatchFile, comptime flavor: Flavor) Maybe(Return.UnwatchFile) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.UnwatchFile).todo; + } + pub fn utimes(this: *NodeFS, args: Arguments.Utimes, comptime flavor: Flavor) Maybe(Return.Utimes) { + var times = [2]std.c.timeval{ + .{ + .tv_sec = args.mtime, + // TODO: is this correct? + .tv_usec = 0, + }, + .{ + .tv_sec = args.atime, + // TODO: is this correct? + .tv_usec = 0, + }, + }; + + switch (comptime flavor) { + // futimes uses the syscall version + // we use libc because here, not for a good reason + // just missing from the linux syscall interface in zig and I don't want to modify that right now + .sync => return if (Maybe(Return.Utimes).errnoSysP(std.c.utimes(args.path.sliceZ(&this.sync_error_buf), ×), .utimes, args.path.slice())) |err| + err + else + Maybe(Return.Utimes).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Utimes).todo; + } + + pub fn lutimes(this: *NodeFS, args: Arguments.Lutimes, comptime flavor: Flavor) Maybe(Return.Lutimes) { + var times = [2]std.c.timeval{ + .{ + .tv_sec = args.mtime, + // TODO: is this correct? + .tv_usec = 0, + }, + .{ + .tv_sec = args.atime, + // TODO: is this correct? + .tv_usec = 0, + }, + }; + + switch (comptime flavor) { + // futimes uses the syscall version + // we use libc because here, not for a good reason + // just missing from the linux syscall interface in zig and I don't want to modify that right now + .sync => return if (Maybe(Return.Lutimes).errnoSysP(C.lutimes(args.path.sliceZ(&this.sync_error_buf), ×), .lutimes, args.path.slice())) |err| + err + else + Maybe(Return.Lutimes).success, + else => {}, + } + + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Lutimes).todo; + } + pub fn watch(this: *NodeFS, args: Arguments.Watch, comptime flavor: Flavor) Maybe(Return.Watch) { + _ = args; + _ = this; + _ = flavor; + return Maybe(Return.Watch).todo; + } + pub fn createReadStream(this: *NodeFS, args: Arguments.CreateReadStream, comptime flavor: Flavor) Maybe(Return.CreateReadStream) { + _ = args; + _ = this; + _ = flavor; + var stream = _global.default_allocator.create(JSC.Node.Stream) catch unreachable; + stream.* = JSC.Node.Stream{ + .sink = .{ + .readable = JSC.Node.Readable{ + .stream = stream, + .globalObject = args.global_object, + }, + }, + .sink_type = .readable, + .content = undefined, + .content_type = undefined, + .allocator = _global.default_allocator, + }; + + args.file.copyToStream(args.flags, args.autoClose, args.mode, _global.default_allocator, stream) catch unreachable; + args.copyToState(&stream.sink.readable.state); + return Maybe(Return.CreateReadStream){ .result = stream }; + } + pub fn createWriteStream(this: *NodeFS, args: Arguments.CreateWriteStream, comptime flavor: Flavor) Maybe(Return.CreateWriteStream) { + _ = args; + _ = this; + _ = flavor; + var stream = _global.default_allocator.create(JSC.Node.Stream) catch unreachable; + stream.* = JSC.Node.Stream{ + .sink = .{ + .writable = JSC.Node.Writable{ + .stream = stream, + .globalObject = args.global_object, + }, + }, + .sink_type = .writable, + .content = undefined, + .content_type = undefined, + .allocator = _global.default_allocator, + }; + args.file.copyToStream(args.flags, args.autoClose, args.mode, _global.default_allocator, stream) catch unreachable; + args.copyToState(&stream.sink.writable.state); + return Maybe(Return.CreateWriteStream){ .result = stream }; + } +}; diff --git a/src/javascript/jsc/node/node_fs_binding.zig b/src/javascript/jsc/node/node_fs_binding.zig new file mode 100644 index 000000000..ae29f202a --- /dev/null +++ b/src/javascript/jsc/node/node_fs_binding.zig @@ -0,0 +1,429 @@ +const JSC = @import("../../../jsc.zig"); +const std = @import("std"); +const Flavor = JSC.Node.Flavor; +const ArgumentsSlice = JSC.Node.ArgumentsSlice; +const system = std.os.system; +const Maybe = JSC.Node.Maybe; +const Encoding = JSC.Node.Encoding; +const FeatureFlags = @import("../../../global.zig").FeatureFlags; +const Args = JSC.Node.NodeFS.Arguments; + +const NodeFSFunction = fn ( + *JSC.Node.NodeFS, + JSC.C.JSContextRef, + JSC.C.JSObjectRef, + JSC.C.JSObjectRef, + []const JSC.C.JSValueRef, + JSC.C.ExceptionRef, +) JSC.C.JSValueRef; + +pub const toJSTrait = std.meta.trait.hasFn("toJS"); +pub const fromJSTrait = std.meta.trait.hasFn("fromJS"); +const NodeFSFunctionEnum = JSC.Node.DeclEnum(JSC.Node.NodeFS); + +fn callSync(comptime FunctionEnum: NodeFSFunctionEnum) NodeFSFunction { + const Function = @field(JSC.Node.NodeFS, @tagName(FunctionEnum)); + const FunctionType = @TypeOf(Function); + + const function: std.builtin.TypeInfo.Fn = comptime @typeInfo(FunctionType).Fn; + comptime if (function.args.len != 3) @compileError("Expected 3 arguments"); + const Arguments = comptime function.args[1].arg_type.?; + const FormattedName = comptime [1]u8{std.ascii.toUpper(@tagName(FunctionEnum)[0])} ++ @tagName(FunctionEnum)[1..]; + const Result = comptime JSC.Node.Maybe(@field(JSC.Node.NodeFS.ReturnType, FormattedName)); + + const NodeBindingClosure = struct { + pub fn bind( + this: *JSC.Node.NodeFS, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + arguments: []const JSC.C.JSValueRef, + exception: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + var slice = ArgumentsSlice.init(@ptrCast([*]const JSC.JSValue, arguments.ptr)[0..arguments.len]); + + defer { + // TODO: fix this + for (arguments) |arg| { + JSC.C.JSValueUnprotect(ctx, arg); + } + slice.arena.deinit(); + } + + const args = if (comptime Arguments != void) + (Arguments.fromJS(ctx, &slice, exception) orelse return null) + else + Arguments{}; + if (exception.* != null) return null; + + const result: Result = Function( + this, + args, + comptime Flavor.sync, + ); + return switch (result) { + .err => |err| brk: { + exception.* = err.toJS(ctx); + break :brk null; + }, + .result => |res| if (comptime Result.ReturnType != void) + JSC.To.JS.withType(Result.ReturnType, res, ctx, exception) + else + JSC.C.JSValueMakeUndefined(ctx), + }; + } + }; + + return NodeBindingClosure.bind; +} + +fn call(comptime Function: NodeFSFunctionEnum) NodeFSFunction { + // const FunctionType = @TypeOf(Function); + _ = Function; + + // const function: std.builtin.TypeInfo.Fn = comptime @typeInfo(FunctionType).Fn; + // comptime if (function.args.len != 3) @compileError("Expected 3 arguments"); + // const Arguments = comptime function.args[2].arg_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)})); + const NodeBindingClosure = struct { + pub fn bind( + this: *JSC.Node.NodeFS, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + arguments: []const JSC.C.JSValueRef, + exception: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + _ = this; + _ = ctx; + _ = arguments; + var err = JSC.SystemError{}; + exception.* = err.toErrorInstance(ctx.ptr()).asObjectRef(); + return null; + // var slice = ArgumentsSlice.init(arguments); + + // defer { + // for (arguments.len) |arg| { + // JSC.C.JSValueUnprotect(ctx, arg); + // } + // slice.arena.deinit(); + // } + + // const args = if (comptime Arguments != void) + // Arguments.fromJS(ctx, &slice, exception) + // else + // Arguments{}; + // if (exception.* != null) return null; + + // const result: Maybe(Result) = Function(this, comptime Flavor.sync, args); + // switch (result) { + // .err => |err| { + // exception.* = err.toJS(ctx); + // return null; + // }, + // .result => |res| { + // return switch (comptime Result) { + // void => JSC.JSValue.jsUndefined().asRef(), + // else => res.toJS(ctx), + // }; + // }, + // } + // unreachable; + } + }; + return NodeBindingClosure.bind; +} + +pub const NodeFSBindings = JSC.NewClass( + JSC.Node.NodeFS, + .{ .name = "fs" }, + + .{ + .access = .{ + .name = "access", + .rfn = call(.access), + }, + .appendFile = .{ + .name = "appendFile", + .rfn = call(.appendFile), + }, + .close = .{ + .name = "close", + .rfn = call(.close), + }, + .copyFile = .{ + .name = "copyFile", + .rfn = call(.copyFile), + }, + .exists = .{ + .name = "exists", + .rfn = call(.exists), + }, + .chown = .{ + .name = "chown", + .rfn = call(.chown), + }, + .chmod = .{ + .name = "chmod", + .rfn = call(.chmod), + }, + .fchmod = .{ + .name = "fchmod", + .rfn = call(.fchmod), + }, + .fchown = .{ + .name = "fchown", + .rfn = call(.fchown), + }, + .fstat = .{ + .name = "fstat", + .rfn = call(.fstat), + }, + .fsync = .{ + .name = "fsync", + .rfn = call(.fsync), + }, + .ftruncate = .{ + .name = "ftruncate", + .rfn = call(.ftruncate), + }, + .futimes = .{ + .name = "futimes", + .rfn = call(.futimes), + }, + .lchmod = .{ + .name = "lchmod", + .rfn = call(.lchmod), + }, + .lchown = .{ + .name = "lchown", + .rfn = call(.lchown), + }, + .link = .{ + .name = "link", + .rfn = call(.link), + }, + .lstat = .{ + .name = "lstat", + .rfn = call(.lstat), + }, + .mkdir = .{ + .name = "mkdir", + .rfn = call(.mkdir), + }, + .mkdtemp = .{ + .name = "mkdtemp", + .rfn = call(.mkdtemp), + }, + .open = .{ + .name = "open", + .rfn = call(.open), + }, + .read = .{ + .name = "read", + .rfn = call(.read), + }, + .write = .{ + .name = "write", + .rfn = call(.write), + }, + .readdir = .{ + .name = "readdir", + .rfn = call(.readdir), + }, + .readFile = .{ + .name = "readFile", + .rfn = call(.readFile), + }, + .writeFile = .{ + .name = "writeFile", + .rfn = call(.writeFile), + }, + .readlink = .{ + .name = "readlink", + .rfn = call(.readlink), + }, + .realpath = .{ + .name = "realpath", + .rfn = call(.realpath), + }, + .rename = .{ + .name = "rename", + .rfn = call(.rename), + }, + .stat = .{ + .name = "stat", + .rfn = call(.stat), + }, + .symlink = .{ + .name = "symlink", + .rfn = call(.symlink), + }, + .truncate = .{ + .name = "truncate", + .rfn = call(.truncate), + }, + .unlink = .{ + .name = "unlink", + .rfn = call(.unlink), + }, + .utimes = .{ + .name = "utimes", + .rfn = call(.utimes), + }, + .lutimes = .{ + .name = "lutimes", + .rfn = call(.lutimes), + }, + + .createReadStream = .{ + .name = "createReadStream", + .rfn = if (FeatureFlags.node_streams) callSync(.createReadStream) else call(.createReadStream), + }, + + .createWriteStream = .{ + .name = "createWriteStream", + .rfn = if (FeatureFlags.node_streams) callSync(.createWriteStream) else call(.createWriteStream), + }, + + .accessSync = .{ + .name = "accessSync", + .rfn = callSync(.access), + }, + .appendFileSync = .{ + .name = "appendFileSync", + .rfn = callSync(.appendFile), + }, + .closeSync = .{ + .name = "closeSync", + .rfn = callSync(.close), + }, + .copyFileSync = .{ + .name = "copyFileSync", + .rfn = callSync(.copyFile), + }, + .existsSync = .{ + .name = "existsSync", + .rfn = callSync(.exists), + }, + .chownSync = .{ + .name = "chownSync", + .rfn = callSync(.chown), + }, + .chmodSync = .{ + .name = "chmodSync", + .rfn = callSync(.chmod), + }, + .fchmodSync = .{ + .name = "fchmodSync", + .rfn = callSync(.fchmod), + }, + .fchownSync = .{ + .name = "fchownSync", + .rfn = callSync(.fchown), + }, + .fstatSync = .{ + .name = "fstatSync", + .rfn = callSync(.fstat), + }, + .fsyncSync = .{ + .name = "fsyncSync", + .rfn = callSync(.fsync), + }, + .ftruncateSync = .{ + .name = "ftruncateSync", + .rfn = callSync(.ftruncate), + }, + .futimesSync = .{ + .name = "futimesSync", + .rfn = callSync(.futimes), + }, + .lchmodSync = .{ + .name = "lchmodSync", + .rfn = callSync(.lchmod), + }, + .lchownSync = .{ + .name = "lchownSync", + .rfn = callSync(.lchown), + }, + .linkSync = .{ + .name = "linkSync", + .rfn = callSync(.link), + }, + .lstatSync = .{ + .name = "lstatSync", + .rfn = callSync(.lstat), + }, + .mkdirSync = .{ + .name = "mkdirSync", + .rfn = callSync(.mkdir), + }, + .mkdtempSync = .{ + .name = "mkdtempSync", + .rfn = callSync(.mkdtemp), + }, + .openSync = .{ + .name = "openSync", + .rfn = callSync(.open), + }, + .readSync = .{ + .name = "readSync", + .rfn = callSync(.read), + }, + .writeSync = .{ + .name = "writeSync", + .rfn = callSync(.write), + }, + .readdirSync = .{ + .name = "readdirSync", + .rfn = callSync(.readdir), + }, + .readFileSync = .{ + .name = "readFileSync", + .rfn = callSync(.readFile), + }, + .writeFileSync = .{ + .name = "writeFileSync", + .rfn = callSync(.writeFile), + }, + .readlinkSync = .{ + .name = "readlinkSync", + .rfn = callSync(.readlink), + }, + .realpathSync = .{ + .name = "realpathSync", + .rfn = callSync(.realpath), + }, + .renameSync = .{ + .name = "renameSync", + .rfn = callSync(.rename), + }, + .statSync = .{ + .name = "statSync", + .rfn = callSync(.stat), + }, + .symlinkSync = .{ + .name = "symlinkSync", + .rfn = callSync(.symlink), + }, + .truncateSync = .{ + .name = "truncateSync", + .rfn = callSync(.truncate), + }, + .unlinkSync = .{ + .name = "unlinkSync", + .rfn = callSync(.unlink), + }, + .utimesSync = .{ + .name = "utimesSync", + .rfn = callSync(.utimes), + }, + .lutimesSync = .{ + .name = "lutimesSync", + .rfn = callSync(.lutimes), + }, + }, + .{}, +); diff --git a/src/javascript/jsc/node/nodejs_error_code.zig b/src/javascript/jsc/node/nodejs_error_code.zig new file mode 100644 index 000000000..5c54791ee --- /dev/null +++ b/src/javascript/jsc/node/nodejs_error_code.zig @@ -0,0 +1,1097 @@ +/// https://nodejs.org/api/errors.html#nodejs-error-codes +pub const Code = enum { + /// Used when an operation has been aborted (typically using an AbortController). + /// APIs not using AbortSignals typically do not raise an error with this code. + /// This code does not use the regular ERR_* convention Node.js errors use in order to be compatible with the web platform's AbortError. + /// Added in: v15.0.0 + ABORT_ERR, + + /// A function argument is being used in a way that suggests that the function signature may be misunderstood. This is thrown by the assert module when the message parameter in assert.throws(block, message) matches the error message thrown by block because that usage suggests that the user believes message is the expected message rather than the message the AssertionError will display if block does not throw. + ERR_AMBIGUOUS_ARGUMENT, + + /// An iterable argument (i.e. a value that works with for...of loops) was required, but not provided to a Node.js API. + ERR_ARG_NOT_ITERABLE, + + /// A special type of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the assert module. + ERR_ASSERTION, + + /// An attempt was made to register something that is not a function as an AsyncHooks callback. + ERR_ASYNC_CALLBACK, + + /// The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API. + ERR_ASYNC_TYPE, + + /// Data passed to a Brotli stream was not successfully compressed. + ERR_BROTLI_COMPRESSION_FAILED, + + /// An invalid parameter key was passed during construction of a Brotli stream. + ERR_BROTLI_INVALID_PARAM, + + /// When encountering this error, a possible alternative to creating a Buffer instance is to create a normal Uint8Array, which only differs in the prototype of the resulting object. Uint8Arrays are generally accepted in all Node.js core APIs where Buffers are; they are available in all Contexts. + /// An attempt was made to create a Node.js Buffer instance from addon or embedder code, while in a JS engine Context that is not associated with a Node.js instance. The data passed to the Buffer method will have been released by the time the method returns. + ERR_BUFFER_CONTEXT_NOT_AVAILABLE, + + /// An operation outside the bounds of a Buffer was attempted. + ERR_BUFFER_OUT_OF_BOUNDS, + + /// An attempt has been made to create a Buffer larger than the maximum allowed size. + ERR_BUFFER_TOO_LARGE, + + /// Node.js was unable to watch for the SIGINT signal. + ERR_CANNOT_WATCH_SIGINT, + + /// A child process was closed before the parent received a reply. + ERR_CHILD_CLOSED_BEFORE_REPLY, + + /// Used when a child process is being forked without specifying an IPC channel. + ERR_CHILD_PROCESS_IPC_REQUIRED, + + /// Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the maxBuffer option. + ERR_CHILD_PROCESS_STDIO_MAXBUFFER, + + /// There was an attempt to use a MessagePort instance in a closed state, usually after .close() has been called. + ERR_CLOSED_MESSAGE_PORT, + + /// Console was instantiated without stdout stream, or Console has a non-writable stdout or stderr stream. + ERR_CONSOLE_WRITABLE_STREAM, + + /// A class constructor was called that is not callable. + ERR_CONSTRUCT_CALL_INVALID, + + /// A constructor for a class was called without new. + ERR_CONSTRUCT_CALL_REQUIRED, + + /// The vm context passed into the API is not yet initialized. This could happen when an error occurs (and is caught) during the creation of the context, for example, when the allocation fails or the maximum call stack size is reached when the context is created. + ERR_CONTEXT_NOT_INITIALIZED, + + /// A client certificate engine was requested that is not supported by the version of OpenSSL being used. + ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED, + + /// An invalid value for the format argument was passed to the crypto.ECDH() class getPublicKey() method. + ERR_CRYPTO_ECDH_INVALID_FORMAT, + + /// An invalid value for the key argument has been passed to the crypto.ECDH() class computeSecret() method. It means that the public key lies outside of the elliptic curve. + ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY, + + /// An invalid crypto engine identifier was passed to require('crypto').setEngine(). + ERR_CRYPTO_ENGINE_UNKNOWN, + + /// The --force-fips command-line argument was used but there was an attempt to enable or disable FIPS mode in the crypto module. + ERR_CRYPTO_FIPS_FORCED, + + /// An attempt was made to enable or disable FIPS mode, but FIPS mode was not available. + ERR_CRYPTO_FIPS_UNAVAILABLE, + + /// hash.digest() was called multiple times. The hash.digest() method must be called no more than one time per instance of a Hash object. + ERR_CRYPTO_HASH_FINALIZED, + + /// hash.update() failed for any reason. This should rarely, if ever, happen. + ERR_CRYPTO_HASH_UPDATE_FAILED, + + /// The given crypto keys are incompatible with the attempted operation. + ERR_CRYPTO_INCOMPATIBLE_KEY, + + /// The selected public or private key encoding is incompatible with other options. + ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS, + + /// Added in: v15.0.0 + /// Initialization of the crypto subsystem failed. + ERR_CRYPTO_INITIALIZATION_FAILED, + + /// Added in: v15.0.0 + /// An invalid authentication tag was provided. + ERR_CRYPTO_INVALID_AUTH_TAG, + + /// Added in: v15.0.0 + /// An invalid counter was provided for a counter-mode cipher. + ERR_CRYPTO_INVALID_COUNTER, + + /// An invalid elliptic-curve was provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_CURVE, + + /// An invalid crypto digest algorithm was specified. + ERR_CRYPTO_INVALID_DIGEST, + + /// Added in: v15.0.0 + /// An invalid initialization vector was provided. + ERR_CRYPTO_INVALID_IV, + + /// Added in: v15.0.0 + /// An invalid JSON Web Key was provided. + ERR_CRYPTO_INVALID_JWK, + + /// The given crypto key object's type is invalid for the attempted operation. + ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE, + + /// Added in: v15.0.0 + /// An invalid key length was provided. + ERR_CRYPTO_INVALID_KEYLEN, + + /// An invalid key pair was provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_KEYPAIR, + + /// An invalid key type was provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_KEYTYPE, + + /// Added in: v15.0.0 + /// An invalid message length was provided. + ERR_CRYPTO_INVALID_MESSAGELEN, + + /// Invalid scrypt algorithm parameters were provided. + /// Added in: v15.0.0 + ERR_CRYPTO_INVALID_SCRYPT_PARAMS, + + /// A crypto method was used on an object that was in an invalid state. For instance, calling cipher.getAuthTag() before calling cipher.final(). + ERR_CRYPTO_INVALID_STATE, + + /// Added in: v15.0.0 + /// An invalid authentication tag length was provided. + ERR_CRYPTO_INVALID_TAG_LENGTH, + + /// Added in: v15.0.0 + //// Initialization of an asynchronous crypto operation failed. + ERR_CRYPTO_JOB_INIT_FAILED, + + /// Key's Elliptic Curve is not registered for use in the JSON Web Key Elliptic Curve Registry. + ERR_CRYPTO_JWK_UNSUPPORTED_CURVE, + + /// Key's Asymmetric Key Type is not registered for use in the JSON Web Key Types Registry. + ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE, + + /// A crypto operation failed for an otherwise unspecified reason. + /// Added in: v15.0.0 + ERR_CRYPTO_OPERATION_FAILED, + + /// The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js. + ERR_CRYPTO_PBKDF2_ERROR, + + /// One or more crypto.scrypt() or crypto.scryptSync() parameters are outside their legal range. + ERR_CRYPTO_SCRYPT_INVALID_PARAMETER, + + /// Node.js was compiled without scrypt support. Not possible with the official release binaries but can happen with custom builds, including distro builds. + ERR_CRYPTO_SCRYPT_NOT_SUPPORTED, + + /// A signing key was not provided to the sign.sign() method. + ERR_CRYPTO_SIGN_KEY_REQUIRED, + + /// crypto.timingSafeEqual() was called with Buffer, TypedArray, or DataView arguments of different lengths. + ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH, + + /// An unknown cipher was specified. + ERR_CRYPTO_UNKNOWN_CIPHER, + + /// An unknown Diffie-Hellman group name was given. See crypto.getDiffieHellman() for a list of valid group names. + ERR_CRYPTO_UNKNOWN_DH_GROUP, + + /// Added in: v15.0.0, v14.18.0 + /// An attempt to invoke an unsupported crypto operation was made. + ERR_CRYPTO_UNSUPPORTED_OPERATION, + + /// An error occurred with the debugger. + /// Added in: v16.4.0, v14.17.4 + ERR_DEBUGGER_ERROR, + + /// Added in: v16.4.0, v14.17.4 + /// The debugger timed out waiting for the required host/port to be free. + ERR_DEBUGGER_STARTUP_ERROR, + + /// Added in: v16.10.0 + /// Loading native addons has been disabled using --no-addons. + ERR_DLOPEN_DISABLED, + + /// Added in: v15.0.0 + /// A call to process.dlopen() failed. + ERR_DLOPEN_FAILED, + + /// The fs.Dir was previously closed. + ERR_DIR_CLOSED, + + /// A synchronous read or close call was attempted on an fs.Dir which has ongoing asynchronous operations. + /// Added in: v14.3.0 + ERR_DIR_CONCURRENT_OPERATION, + + /// c-ares failed to set the DNS server. + ERR_DNS_SET_SERVERS_FAILED, + + /// The domain module was not usable since it could not establish the required error handling hooks, because process.setUncaughtExceptionCaptureCallback() had been called at an earlier point in time. + ERR_DOMAIN_CALLBACK_NOT_AVAILABLE, + + /// process.setUncaughtExceptionCaptureCallback() could not be called because the domain module has been loaded at an earlier point in time. + /// The stack trace is extended to include the point in time at which the domain module had been loaded. + ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE, + + /// Data provided to TextDecoder() API was invalid according to the encoding provided. + ERR_ENCODING_INVALID_ENCODED_DATA, + + /// Encoding provided to TextDecoder() API was not one of the WHATWG Supported Encodings. + ERR_ENCODING_NOT_SUPPORTED, + + /// --print cannot be used with ESM input. + ERR_EVAL_ESM_CANNOT_PRINT, + + /// Thrown when an attempt is made to recursively dispatch an event on EventTarget. + ERR_EVENT_RECURSION, + + /// The JS execution context is not associated with a Node.js environment. This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly. + ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE, + + /// A Promise that was callbackified via util.callbackify() was rejected with a falsy value. + ERR_FALSY_VALUE_REJECTION, + + /// Added in: v14.0.0 + /// Used when a feature that is not available to the current platform which is running Node.js is used. + ERR_FEATURE_UNAVAILABLE_ON_PLATFORM, + + /// An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using fs.cp(). + ERR_FS_CP_DIR_TO_NON_DIR, + + /// An attempt was made to copy over a file that already existed with fs.cp(), with the force and errorOnExist set to true. + ERR_FS_CP_EEXIST, + + /// When using fs.cp(), src or dest pointed to an invalid path. + ERR_FS_CP_EINVAL, + + /// An attempt was made to copy a named pipe with fs.cp(). + ERR_FS_CP_FIFO_PIPE, + + /// An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using fs.cp(). + ERR_FS_CP_NON_DIR_TO_DIR, + + /// An attempt was made to copy to a socket with fs.cp(). + ERR_FS_CP_SOCKET, + + /// When using fs.cp(), a symlink in dest pointed to a subdirectory of src. + ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY, + + /// An attempt was made to copy to an unknown file type with fs.cp(). + ERR_FS_CP_UNKNOWN, + + /// Path is a directory. + ERR_FS_EISDIR, + + /// An attempt has been made to read a file whose size is larger than the maximum allowed size for a Buffer. + ERR_FS_FILE_TOO_LARGE, + + /// An invalid symlink type was passed to the fs.symlink() or fs.symlinkSync() methods. + ERR_FS_INVALID_SYMLINK_TYPE, + + /// An attempt was made to add more headers after the headers had already been sent. + ERR_HTTP_HEADERS_SENT, + + /// An invalid HTTP header value was specified. + ERR_HTTP_INVALID_HEADER_VALUE, + + /// Status code was outside the regular status code range (100-999). + ERR_HTTP_INVALID_STATUS_CODE, + + /// The client has not sent the entire request within the allowed time. + ERR_HTTP_REQUEST_TIMEOUT, + + /// Changing the socket encoding is not allowed per RFC 7230 Section 3. + ERR_HTTP_SOCKET_ENCODING, + + /// The Trailer header was set even though the transfer encoding does not support that. + ERR_HTTP_TRAILER_INVALID, + + /// HTTP/2 ALTSVC frames require a valid origin. + ERR_HTTP2_ALTSVC_INVALID_ORIGIN, + + /// HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes. + ERR_HTTP2_ALTSVC_LENGTH, + + /// For HTTP/2 requests using the CONNECT method, the :authority pseudo-header is required. + ERR_HTTP2_CONNECT_AUTHORITY, + + /// For HTTP/2 requests using the CONNECT method, the :path pseudo-header is forbidden. + ERR_HTTP2_CONNECT_PATH, + + /// For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is forbidden. + ERR_HTTP2_CONNECT_SCHEME, + + /// A non-specific HTTP/2 error has occurred. + ERR_HTTP2_ERROR, + + /// New HTTP/2 Streams may not be opened after the Http2Session has received a GOAWAY frame from the connected peer. + ERR_HTTP2_GOAWAY_SESSION, + + /// Multiple values were provided for an HTTP/2 header field that was required to have only a single value. + ERR_HTTP2_HEADER_SINGLE_VALUE, + + /// An additional headers was specified after an HTTP/2 response was initiated. + ERR_HTTP2_HEADERS_AFTER_RESPOND, + + /// An attempt was made to send multiple response headers. + ERR_HTTP2_HEADERS_SENT, + + /// Informational HTTP status codes (1xx) may not be set as the response status code on HTTP/2 responses. + ERR_HTTP2_INFO_STATUS_NOT_ALLOWED, + + /// HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses. + ERR_HTTP2_INVALID_CONNECTION_HEADERS, + + /// An invalid HTTP/2 header value was specified. + ERR_HTTP2_INVALID_HEADER_VALUE, + + /// An invalid HTTP informational status code has been specified. Informational status codes must be an integer between 100 and 199 (inclusive). + ERR_HTTP2_INVALID_INFO_STATUS, + + /// HTTP/2 ORIGIN frames require a valid origin. + ERR_HTTP2_INVALID_ORIGIN, + + /// Input Buffer and Uint8Array instances passed to the http2.getUnpackedSettings() API must have a length that is a multiple of six. + ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH, + + /// Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme, and :method) may be used. + ERR_HTTP2_INVALID_PSEUDOHEADER, + + /// An action was performed on an Http2Session object that had already been destroyed. + ERR_HTTP2_INVALID_SESSION, + + /// An invalid value has been specified for an HTTP/2 setting. + ERR_HTTP2_INVALID_SETTING_VALUE, + + /// An operation was performed on a stream that had already been destroyed. + ERR_HTTP2_INVALID_STREAM, + + /// Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new SETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may be sent at any given time. This error code is used when that limit has been reached. + ERR_HTTP2_MAX_PENDING_SETTINGS_ACK, + + /// An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted. + ERR_HTTP2_NESTED_PUSH, + + /// Out of memory when using the http2session.setLocalWindowSize(windowSize) API. + ERR_HTTP2_NO_MEM, + + /// An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an Http2Session. + ERR_HTTP2_NO_SOCKET_MANIPULATION, + + /// HTTP/2 ORIGIN frames are limited to a length of 16382 bytes. + ERR_HTTP2_ORIGIN_LENGTH, + + /// The number of streams created on a single HTTP/2 session reached the maximum limit. + ERR_HTTP2_OUT_OF_STREAMS, + + /// A message payload was specified for an HTTP response code for which a payload is forbidden. + ERR_HTTP2_PAYLOAD_FORBIDDEN, + + /// An HTTP/2 ping was canceled. + ERR_HTTP2_PING_CANCEL, + + /// HTTP/2 ping payloads must be exactly 8 bytes in length. + ERR_HTTP2_PING_LENGTH, + + /// An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the : prefix. + ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, + + /// An attempt was made to create a push stream, which had been disabled by the client. + ERR_HTTP2_PUSH_DISABLED, + + /// An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send a directory. + ERR_HTTP2_SEND_FILE, + + /// An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send something other than a regular file, but offset or length options were provided. + ERR_HTTP2_SEND_FILE_NOSEEK, + + /// The Http2Session closed with a non-zero error code. + ERR_HTTP2_SESSION_ERROR, + + /// The Http2Session settings canceled. + ERR_HTTP2_SETTINGS_CANCEL, + + /// An attempt was made to connect a Http2Session object to a net.Socket or tls.TLSSocket that had already been bound to another Http2Session object. + ERR_HTTP2_SOCKET_BOUND, + + /// An attempt was made to use the socket property of an Http2Session that has already been closed. + ERR_HTTP2_SOCKET_UNBOUND, + + /// Use of the 101 Informational status code is forbidden in HTTP/2. + ERR_HTTP2_STATUS_101, + + /// An invalid HTTP status code has been specified. Status codes must be an integer between 100 and 599 (inclusive). + ERR_HTTP2_STATUS_INVALID, + + /// An Http2Stream was destroyed before any data was transmitted to the connected peer. + ERR_HTTP2_STREAM_CANCEL, + + /// A non-zero error code was been specified in an RST_STREAM frame. + ERR_HTTP2_STREAM_ERROR, + + /// When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself. + ERR_HTTP2_STREAM_SELF_DEPENDENCY, + + /// The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the maxSessionInvalidFrames option, has been exceeded. + ERR_HTTP2_TOO_MANY_INVALID_FRAMES, + + /// Trailing headers have already been sent on the Http2Stream. + ERR_HTTP2_TRAILERS_ALREADY_SENT, + + /// The http2stream.sendTrailers() method cannot be called until after the 'wantTrailers' event is emitted on an Http2Stream object. The 'wantTrailers' event will only be emitted if the waitForTrailers option is set for the Http2Stream. + ERR_HTTP2_TRAILERS_NOT_READY, + + /// http2.connect() was passed a URL that uses any protocol other than http: or https:. + ERR_HTTP2_UNSUPPORTED_PROTOCOL, + + /// An attempt was made to construct an object using a non-public constructor. + ERR_ILLEGAL_CONSTRUCTOR, + + /// An import assertion has failed, preventing the specified module to be imported. + /// Added in: v17.1.0 + ERR_IMPORT_ASSERTION_TYPE_FAILED, + + /// An import assertion is missing, preventing the specified module to be imported. + /// Added in: v17.1.0 + ERR_IMPORT_ASSERTION_TYPE_MISSING, + + /// An import assertion is not supported by this version of Node.js. + /// Added in: v17.1.0 + ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED, + + /// An option pair is incompatible with each other and cannot be used at the same time. + ERR_INCOMPATIBLE_OPTION_PAIR, + + /// Stability: 1 - Experimental + ERR_INPUT_TYPE_NOT_ALLOWED, + + /// The --input-type flag was used to attempt to execute a file. This flag can only be used with input via --eval, --print or STDIN. + /// While using the inspector module, an attempt was made to activate the inspector when it already started to listen on a port. Use inspector.close() before activating it on a different address. + ERR_INSPECTOR_ALREADY_ACTIVATED, + + /// While using the inspector module, an attempt was made to connect when the inspector was already connected. + ERR_INSPECTOR_ALREADY_CONNECTED, + + /// While using the inspector module, an attempt was made to use the inspector after the session had already closed. + ERR_INSPECTOR_CLOSED, + + /// An error occurred while issuing a command via the inspector module. + ERR_INSPECTOR_COMMAND, + + /// The inspector is not active when inspector.waitForDebugger() is called. + ERR_INSPECTOR_NOT_ACTIVE, + + /// The inspector module is not available for use. + ERR_INSPECTOR_NOT_AVAILABLE, + + /// While using the inspector module, an attempt was made to use the inspector before it was connected. + ERR_INSPECTOR_NOT_CONNECTED, + + /// An API was called on the main thread that can only be used from the worker thread. + ERR_INSPECTOR_NOT_WORKER, + + /// There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at https://github.com/nodejs/node/issues. + ERR_INTERNAL_ASSERTION, + + /// The provided address family is not understood by the Node.js API. + ERR_INVALID_ADDRESS_FAMILY, + + /// An argument of the wrong type was passed to a Node.js API. + ERR_INVALID_ARG_TYPE, + + /// An invalid or unsupported value was passed for a given argument. + ERR_INVALID_ARG_VALUE, + + /// An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id less than -1 should never happen. + ERR_INVALID_ASYNC_ID, + + /// A swap was performed on a Buffer but its size was not compatible with the operation. + ERR_INVALID_BUFFER_SIZE, + + /// A callback function was required but was not been provided to a Node.js API. + ERR_INVALID_CALLBACK, + + /// Invalid characters were detected in headers. + ERR_INVALID_CHAR, + + /// A cursor on a given stream cannot be moved to a specified row without a specified column. + ERR_INVALID_CURSOR_POS, + + /// A file descriptor ('fd') was not valid (e.g. it was a negative value). + ERR_INVALID_FD, + + /// A file descriptor ('fd') type was not valid. + ERR_INVALID_FD_TYPE, + + /// A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible host. This situation can only occur on Unix-like systems where only localhost or an empty host is supported. + ERR_INVALID_FILE_URL_HOST, + + /// A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible path. The exact semantics for determining whether a path can be used is platform-dependent. + ERR_INVALID_FILE_URL_PATH, + + /// An attempt was made to send an unsupported "handle" over an IPC communication channel to a child process. See subprocess.send() and process.send() for more information. + ERR_INVALID_HANDLE_TYPE, + + /// An invalid HTTP token was supplied. + ERR_INVALID_HTTP_TOKEN, + + /// An IP address is not valid. + ERR_INVALID_IP_ADDRESS, + + /// Added in: v15.0.0, v14.18.0 + /// An attempt was made to load a module that does not exist or was otherwise not valid. + ERR_INVALID_MODULE, + + /// The imported module string is an invalid URL, package name, or package subpath specifier. + ERR_INVALID_MODULE_SPECIFIER, + + /// An invalid package.json file failed parsing. + ERR_INVALID_PACKAGE_CONFIG, + + /// The package.json "exports" field contains an invalid target mapping value for the attempted module resolution. + ERR_INVALID_PACKAGE_TARGET, + + /// While using the Performance Timing API (perf_hooks), a performance mark is invalid. + ERR_INVALID_PERFORMANCE_MARK, + + /// An invalid options.protocol was passed to http.request(). + ERR_INVALID_PROTOCOL, + + /// Both breakEvalOnSigint and eval options were set in the REPL config, which is not supported. + ERR_INVALID_REPL_EVAL_CONFIG, + + /// The input may not be used in the REPL. The conditions under which this error is used are described in the REPL documentation. + ERR_INVALID_REPL_INPUT, + + /// Thrown in case a function option does not provide a valid value for one of its returned object properties on execution. + ERR_INVALID_RETURN_PROPERTY, + + /// Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution. + ERR_INVALID_RETURN_PROPERTY_VALUE, + + /// Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise. + ERR_INVALID_RETURN_VALUE, + + /// Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be performing another operation. + /// Added in: v15.0.0 + ERR_INVALID_STATE, + + /// A Buffer, TypedArray, DataView or string was provided as stdio input to an asynchronous fork. See the documentation for the child_process module for more information. + ERR_INVALID_SYNC_FORK_INPUT, + + /// A Node.js API function was called with an incompatible this value. + /// ```js + /// const urlSearchParams = new URLSearchParams('foo=bar&baz=new'); + /// const buf = Buffer.alloc(1); + /// urlSearchParams.has.call(buf, 'foo'); + /// ``` + /// Throws a TypeError with code 'ERR_INVALID_THIS' + ERR_INVALID_THIS, + + /// An invalid transfer object was passed to postMessage(). + ERR_INVALID_TRANSFER_OBJECT, + + /// An element in the iterable provided to the WHATWG URLSearchParams constructor did not represent a [name, value] tuple – that is, if an element is not iterable, or does not consist of exactly two elements. + ERR_INVALID_TUPLE, + + /// An invalid URI was passed. + ERR_INVALID_URI, + + /// An invalid URL was passed to the WHATWG URL constructor or the legacy url.parse() to be parsed. The thrown error object typically has an additional property 'input' that contains the URL that failed to parse. + ERR_INVALID_URL, + + /// An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the WHATWG URL API support in the fs module (which only accepts URLs with 'file' scheme), but may be used in other Node.js APIs as well in the future. + ERR_INVALID_URL_SCHEME, + + /// An attempt was made to use an IPC communication channel that was already closed. + ERR_IPC_CHANNEL_CLOSED, + + /// An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the child_process module for more information. + ERR_IPC_DISCONNECTED, + + /// An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the child_process module for more information. + ERR_IPC_ONE_PIPE, + + /// An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the child_process module for more information. + ERR_IPC_SYNC_FORK, + + /// An attempt was made to load a resource, but the resource did not match the integrity defined by the policy manifest. See the documentation for policy manifests for more information. + ERR_MANIFEST_ASSERT_INTEGRITY, + + /// An attempt was made to load a resource, but the resource was not listed as a dependency from the location that attempted to load it. See the documentation for policy manifests for more information. + ERR_MANIFEST_DEPENDENCY_MISSING, + + /// An attempt was made to load a policy manifest, but the manifest had multiple entries for a resource which did not match each other. Update the manifest entries to match in order to resolve this error. See the documentation for policy manifests for more information. + ERR_MANIFEST_INTEGRITY_MISMATCH, + + /// A policy manifest resource had an invalid value for one of its fields. Update the manifest entry to match in order to resolve this error. See the documentation for policy manifests for more information. + ERR_MANIFEST_INVALID_RESOURCE_FIELD, + + /// A policy manifest resource had an invalid value for one of its dependency mappings. Update the manifest entry to match to resolve this error. See the documentation for policy manifests for more information. + ERR_MANIFEST_INVALID_SPECIFIER, + + /// An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for policy manifests for more information. + ERR_MANIFEST_PARSE_POLICY, + + /// An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js. + ERR_MANIFEST_TDZ, + + /// A policy manifest was loaded, but had an unknown value for its "onerror" behavior. See the documentation for policy manifests for more information. + ERR_MANIFEST_UNKNOWN_ONERROR, + + /// An attempt was made to allocate memory (usually in the C++ layer) but it failed. + ERR_MEMORY_ALLOCATION_FAILED, + + /// Added in: v14.5.0, v12.19.0 + /// A message posted to a MessagePort could not be deserialized in the target vm Context. Not all Node.js objects can be successfully instantiated in any context at this time, and attempting to transfer them using postMessage() can fail on the receiving side in that case. + ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE, + + /// A method is required but not implemented. + ERR_METHOD_NOT_IMPLEMENTED, + + /// A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept func(undefined) but not func()). In most native Node.js APIs, func(undefined) and func() are treated identically, and the ERR_INVALID_ARG_TYPE error code may be used instead. + ERR_MISSING_ARGS, + + /// For APIs that accept options objects, some options might be mandatory. This code is thrown if a required option is missing. + ERR_MISSING_OPTION, + + /// An attempt was made to read an encrypted key without specifying a passphrase. + ERR_MISSING_PASSPHRASE, + + /// The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js. + ERR_MISSING_PLATFORM_FOR_WORKER, + + /// Added in: v15.0.0 + /// An object that needs to be explicitly listed in the transferList argument is in the object passed to a postMessage() call, but is not provided in the transferList for that call. Usually, this is a MessagePort. + /// In Node.js versions prior to v15.0.0, the error code being used here was ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST. However, the set of transferable object types has been expanded to cover more types than MessagePort. + ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST, + + /// Stability: 1 - Experimental + /// An ES Module could not be resolved. + ERR_MODULE_NOT_FOUND, + + /// A callback was called more than once. + /// A callback is almost always meant to only be called once as the query can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once. + ERR_MULTIPLE_CALLBACK, + + /// While using Node-API, a constructor passed was not a function. + ERR_NAPI_CONS_FUNCTION, + + /// While calling napi_create_dataview(), a given offset was outside the bounds of the dataview or offset + length was larger than a length of given buffer. + ERR_NAPI_INVALID_DATAVIEW_ARGS, + + /// While calling napi_create_typedarray(), the provided offset was not a multiple of the element size. + ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT, + + /// While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer. + ERR_NAPI_INVALID_TYPEDARRAY_LENGTH, + + /// An error occurred while invoking the JavaScript portion of the thread-safe function. + ERR_NAPI_TSFN_CALL_JS, + + /// An error occurred while attempting to retrieve the JavaScript undefined value. + ERR_NAPI_TSFN_GET_UNDEFINED, + + /// On the main thread, values are removed from the queue associated with the thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop. + ERR_NAPI_TSFN_START_IDLE_LOOP, + + /// Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop. + ERR_NAPI_TSFN_STOP_IDLE_LOOP, + + /// An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support. + ERR_NO_CRYPTO, + + /// An attempt was made to use features that require ICU, but Node.js was not compiled with ICU support. + ERR_NO_ICU, + + /// A non-context-aware native addon was loaded in a process that disallows them. + ERR_NON_CONTEXT_AWARE_DISABLED, + + /// A given value is out of the accepted range. + ERR_OUT_OF_RANGE, + + /// The package.json "imports" field does not define the given internal package specifier mapping. + ERR_PACKAGE_IMPORT_NOT_DEFINED, + + /// The package.json "exports" field does not export the requested subpath. Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL. + ERR_PACKAGE_PATH_NOT_EXPORTED, + + /// An invalid timestamp value was provided for a performance mark or measure. + ERR_PERFORMANCE_INVALID_TIMESTAMP, + + /// Invalid options were provided for a performance measure. + ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS, + + /// Accessing Object.prototype.__proto__ has been forbidden using --disable-proto=throw. Object.getPrototypeOf and Object.setPrototypeOf should be used to get and set the prototype of an object. + ERR_PROTO_ACCESS, + + /// Stability: 1 - Experimental + /// An attempt was made to require() an ES Module. + ERR_REQUIRE_ESM, + + /// Script execution was interrupted by SIGINT (For example, Ctrl+C was pressed.) + ERR_SCRIPT_EXECUTION_INTERRUPTED, + + /// Script execution timed out, possibly due to bugs in the script being executed. + ERR_SCRIPT_EXECUTION_TIMEOUT, + + /// The server.listen() method was called while a net.Server was already listening. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances. + ERR_SERVER_ALREADY_LISTEN, + + /// The server.close() method was called when a net.Server was not running. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances. + ERR_SERVER_NOT_RUNNING, + + /// An attempt was made to bind a socket that has already been bound. + ERR_SOCKET_ALREADY_BOUND, + + /// An invalid (negative) size was passed for either the recvBufferSize or sendBufferSize options in dgram.createSocket(). + ERR_SOCKET_BAD_BUFFER_SIZE, + + /// An API function expecting a port >= 0 and < 65536 received an invalid value. + ERR_SOCKET_BAD_PORT, + + /// An API function expecting a socket type (udp4 or udp6) received an invalid value. + ERR_SOCKET_BAD_TYPE, + + /// While using dgram.createSocket(), the size of the receive or send Buffer could not be determined. + ERR_SOCKET_BUFFER_SIZE, + + /// An attempt was made to operate on an already closed socket. + ERR_SOCKET_CLOSED, + + /// A dgram.connect() call was made on an already connected socket. + ERR_SOCKET_DGRAM_IS_CONNECTED, + + /// A dgram.disconnect() or dgram.remoteAddress() call was made on a disconnected socket. + ERR_SOCKET_DGRAM_NOT_CONNECTED, + + /// A call was made and the UDP subsystem was not running. + ERR_SOCKET_DGRAM_NOT_RUNNING, + + /// A string was provided for a Subresource Integrity check, but was unable to be parsed. Check the format of integrity attributes by looking at the Subresource Integrity specification. + ERR_SRI_PARSE, + + /// A stream method was called that cannot complete because the stream was finished. + ERR_STREAM_ALREADY_FINISHED, + + /// An attempt was made to call stream.pipe() on a Writable stream. + ERR_STREAM_CANNOT_PIPE, + + /// A stream method was called that cannot complete because the stream was destroyed using stream.destroy(). + ERR_STREAM_DESTROYED, + + /// An attempt was made to call stream.write() with a null chunk. + ERR_STREAM_NULL_VALUES, + + /// An error returned by stream.finished() and stream.pipeline(), when a stream or a pipeline ends non gracefully with no explicit error. + ERR_STREAM_PREMATURE_CLOSE, + + /// An attempt was made to call stream.push() after a null(EOF) had been pushed to the stream. + ERR_STREAM_PUSH_AFTER_EOF, + + /// An attempt was made to call stream.unshift() after the 'end' event was emitted. + ERR_STREAM_UNSHIFT_AFTER_END_EVENT, + + /// Prevents an abort if a string decoder was set on the Socket or if the decoder is in objectMode. + /// const Socket = require('net').Socket; + /// const instance = new Socket(); + /// instance.setEncoding('utf8'); + ERR_STREAM_WRAP, + + /// An attempt was made to call stream.write() after stream.end() has been called. + ERR_STREAM_WRITE_AFTER_END, + + /// An attempt has been made to create a string longer than the maximum allowed length. + ERR_STRING_TOO_LONG, + + /// An artificial error object used to capture the call stack for diagnostic reports. + ERR_SYNTHETIC, + + /// An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an err.info object property with additional details. + ERR_SYSTEM_ERROR, + + /// This error is thrown by checkServerIdentity if a user-supplied subjectaltname property violates encoding rules. Certificate objects produced by Node.js itself always comply with encoding rules and will never cause this error. + ERR_TLS_CERT_ALTNAME_FORMAT, + + /// While using TLS, the host name/IP of the peer did not match any of the subjectAltNames in its certificate. + ERR_TLS_CERT_ALTNAME_INVALID, + + /// While using TLS, the parameter offered for the Diffie-Hellman (DH) key-agreement protocol is too small. By default, the key length must be greater than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security. + ERR_TLS_DH_PARAM_SIZE, + + /// A TLS/SSL handshake timed out. In this case, the server must also abort the connection. + ERR_TLS_HANDSHAKE_TIMEOUT, + + /// The context must be a SecureContext. + /// Added in: v13.3.0 + ERR_TLS_INVALID_CONTEXT, + + /// The specified secureProtocol method is invalid. It is either unknown, or disabled because it is insecure. + ERR_TLS_INVALID_PROTOCOL_METHOD, + + /// Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'. + ERR_TLS_INVALID_PROTOCOL_VERSION, + + /// The TLS socket must be connected and securily established. Ensure the 'secure' event is emitted before continuing. + /// Added in: v13.10.0, v12.17.0 + ERR_TLS_INVALID_STATE, + + /// Attempting to set a TLS protocol minVersion or maxVersion conflicts with an attempt to set the secureProtocol explicitly. Use one mechanism or the other. + ERR_TLS_PROTOCOL_VERSION_CONFLICT, + + /// Failed to set PSK identity hint. Hint may be too long. + ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED, + + /// An attempt was made to renegotiate TLS on a socket instance with TLS disabled. + ERR_TLS_RENEGOTIATION_DISABLED, + + /// While using TLS, the server.addContext() method was called without providing a host name in the first parameter. + ERR_TLS_REQUIRED_SERVER_NAME, + + /// An excessive amount of TLS renegotiations is detected, which is a potential vector for denial-of-service attacks. + ERR_TLS_SESSION_ATTACK, + + /// An attempt was made to issue Server Name Indication from a TLS server-side socket, which is only valid from a client. + ERR_TLS_SNI_FROM_SERVER, + + /// The trace_events.createTracing() method requires at least one trace event category. + ERR_TRACE_EVENTS_CATEGORY_REQUIRED, + + /// The trace_events module could not be loaded because Node.js was compiled with the --without-v8-platform flag. + ERR_TRACE_EVENTS_UNAVAILABLE, + + /// A Transform stream finished while it was still transforming. + ERR_TRANSFORM_ALREADY_TRANSFORMING, + + /// A Transform stream finished with data still in the write buffer. + ERR_TRANSFORM_WITH_LENGTH_0, + + /// The initialization of a TTY failed due to a system error. + ERR_TTY_INIT_FAILED, + + /// Function was called within a process.on('exit') handler that shouldn't be called within process.on('exit') handler. + ERR_UNAVAILABLE_DURING_EXIT, + + /// process.setUncaughtExceptionCaptureCallback() was called twice, without first resetting the callback to null. + /// This error is designed to prevent accidentally overwriting a callback registered from another module. + ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET, + + /// A string that contained unescaped characters was received. + ERR_UNESCAPED_CHARACTERS, + + /// An unhandled error occurred (for instance, when an 'error' event is emitted by an EventEmitter but an 'error' handler is not registered). + ERR_UNHANDLED_ERROR, + + /// Used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an internal bug within the Node.js binary itself. + ERR_UNKNOWN_BUILTIN_MODULE, + + /// A Unix group or user identifier that does not exist was passed. + ERR_UNKNOWN_CREDENTIAL, + + /// An invalid or unknown encoding option was passed to an API. + ERR_UNKNOWN_ENCODING, + + /// Stability: 1 - Experimental + /// An attempt was made to load a module with an unknown or unsupported file extension. + ERR_UNKNOWN_FILE_EXTENSION, + + /// An attempt was made to load a module with an unknown or unsupported format. + ERR_UNKNOWN_MODULE_FORMAT, + + /// An invalid or unknown process signal was passed to an API expecting a valid signal (such as subprocess.kill()). + ERR_UNKNOWN_SIGNAL, + + /// import a directory URL is unsupported. Instead, self-reference a package using its name and define a custom subpath in the "exports" field of the package.json file. + /// ```js + /// import './'; // unsupported + /// import './index.js'; // supported + /// import 'package-name'; // supported + /// ``` + ERR_UNSUPPORTED_DIR_IMPORT, + + /// import with URL schemes other than file and data is unsupported. + ERR_UNSUPPORTED_ESM_URL_SCHEME, + + /// While using the Performance Timing API (perf_hooks), no valid performance entry types are found. + ERR_VALID_PERFORMANCE_ENTRY_TYPE, + + /// A dynamic import callback was not specified. + ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, + + /// The module attempted to be linked is not eligible for linking, because of one of the following reasons: + /// - It has already been linked (linkingStatus is 'linked') + /// - It is being linked (linkingStatus is 'linking') + /// - Linking has failed for this module (linkingStatus is 'errored') + ERR_VM_MODULE_ALREADY_LINKED, + + /// The cachedData option passed to a module constructor is invalid. + ERR_VM_MODULE_CACHED_DATA_REJECTED, + + /// Cached data cannot be created for modules which have already been evaluated. + ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA, + + /// The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context. + ERR_VM_MODULE_DIFFERENT_CONTEXT, + + /// The linker function returned a module for which linking has failed. + ERR_VM_MODULE_LINKING_ERRORED, + + /// The module was unable to be linked due to a failure. + ERR_VM_MODULE_LINK_FAILURE, + + /// The fulfilled value of a linking promise is not a vm.Module object. + ERR_VM_MODULE_NOT_MODULE, + + /// The current module's status does not allow for this operation. The specific meaning of the error depends on the specific function. + ERR_VM_MODULE_STATUS, + + /// The WASI instance has already started. + ERR_WASI_ALREADY_STARTED, + + /// The WASI instance has not been started. + ERR_WASI_NOT_STARTED, + + /// The Worker initialization failed. + ERR_WORKER_INIT_FAILED, + + /// The execArgv option passed to the Worker constructor contains invalid flags. + ERR_WORKER_INVALID_EXEC_ARGV, + + /// An operation failed because the Worker instance is not currently running. + ERR_WORKER_NOT_RUNNING, + + /// The Worker instance terminated because it reached its memory limit. + ERR_WORKER_OUT_OF_MEMORY, + + /// The path for the main script of a worker is neither an absolute path nor a relative path starting with ./ or ../. + ERR_WORKER_PATH, + + /// All attempts at serializing an uncaught exception from a worker thread failed. + ERR_WORKER_UNSERIALIZABLE_ERROR, + + /// The requested functionality is not supported in worker threads. + ERR_WORKER_UNSUPPORTED_OPERATION, + + /// Creation of a zlib object failed due to incorrect configuration. + ERR_ZLIB_INITIALIZATION_FAILED, + + /// Too much HTTP header data was received. In order to protect against malicious or malconfigured clients, if more than 8 KB of HTTP header data is received then HTTP parsing will abort without a request or response object being created, and an Error with this code will be emitted. + HPE_HEADER_OVERFLOW, + + /// Server is sending both a Content-Length header and Transfer-Encoding: chunked. + /// Transfer-Encoding: chunked allows the server to maintain an HTTP persistent connection for dynamically generated content. In this case, the Content-Length HTTP header cannot be used. + /// Use Content-Length or Transfer-Encoding: chunked. + HPE_UNEXPECTED_CONTENT_LENGTH, + + /// History + /// A module file could not be resolved while attempting a require() or import operation. + MODULE_NOT_FOUND, + + // -- Deprecated --- + + /// The value passed to postMessage() contained an object that is not supported for transferring. + ERR_CANNOT_TRANSFER_OBJECT, + + /// The UTF-16 encoding was used with hash.digest(). While the hash.digest() method does allow an encoding argument to be passed in, causing the method to return a string rather than a Buffer, the UTF-16 encoding (e.g. ucs or utf16le) is not supported. + /// Added in: v9.0.0Removed in: v12.12.0 + ERR_CRYPTO_HASH_DIGEST_NO_UTF16, + + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_FRAME_ERROR, + + /// Used when a failure occurs sending an individual frame on the HTTP/2 session. + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_HEADERS_OBJECT, + + /// Used when an HTTP/2 Headers Object is expected. + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when a required header is missing in an HTTP/2 message. + ERR_HTTP2_HEADER_REQUIRED, + + /// HTTP/2 informational headers must only be sent prior to calling the Http2Stream.prototype.respond() method. + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND, + + /// Used when an action has been performed on an HTTP/2 Stream that has already been closed. + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_HTTP2_STREAM_CLOSED, + + /// Used when an invalid character is found in an HTTP response status message (reason phrase). + /// Added in: v10.0.0Removed in: v11.0.0 + ERR_HTTP_INVALID_CHAR, + + /// A given index was out of the accepted range (e.g. negative offsets). + /// Added in: v8.0.0Removed in: v15.0.0 + ERR_INDEX_OUT_OF_RANGE, + + /// An invalid or unexpected value was passed in an options object. + ERR_INVALID_OPT_VALUE, + + /// Added in: v9.0.0Removed in: v15.0.0 + /// An invalid or unknown file encoding was passed. + ERR_INVALID_OPT_VALUE_ENCODING, + + /// Removed in: v15.0.0 + /// This error code was replaced by ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST in Node.js v15.0.0, because it is no longer accurate as other types of transferable objects also exist now. + ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used by the Node-API when Constructor.prototype is not an object. + ERR_NAPI_CONS_PROTOTYPE_OBJECT, + + /// A Node.js API was called in an unsupported manner, such as Buffer.write(string, encoding, offset[, length]). + ERR_NO_LONGER_SUPPORTED, + + /// An operation failed. This is typically used to signal the general failure of an asynchronous operation. + /// Added in: v15.0.0 + ERR_OPERATION_FAILED, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used generically to identify that an operation caused an out of memory condition. + ERR_OUTOFMEMORY, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// The repl module was unable to parse data from the REPL history file. + ERR_PARSE_HISTORY_DATA, + + /// Data could not be sent on a socket. + ERR_SOCKET_CANNOT_SEND, + + /// An attempt was made to close the process.stderr stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code. + ERR_STDERR_CLOSE, + + /// An attempt was made to close the process.stdout stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code. + ERR_STDOUT_CLOSE, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when an attempt is made to use a readable stream that has not implemented readable._read(). + ERR_STREAM_READ_NOT_IMPLEMENTED, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when a TLS renegotiation request has failed in a non-specific way. + /// Added in: v10.5.0Removed in: v14.0.0 + ERR_TLS_RENEGOTIATION_FAILED, + + /// A SharedArrayBuffer whose memory is not managed by the JavaScript engine or by Node.js was encountered during serialization. Such a SharedArrayBuffer cannot be serialized. + /// This can only happen when native addons create SharedArrayBuffers in "externalized" mode, or put existing SharedArrayBuffer into externalized mode. + ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER, + + /// Added in: v8.0.0Removed in: v11.7.0 + /// An attempt was made to launch a Node.js process with an unknown stdin file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it. + ERR_UNKNOWN_STDIN_TYPE, + + /// Added in: v8.0.0Removed in: v11.7.0 + /// An attempt was made to launch a Node.js process with an unknown stdout or stderr file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it. + ERR_UNKNOWN_STREAM_TYPE, + + /// The V8 BreakIterator API was used but the full ICU data set is not installed. + ERR_V8BREAKITERATOR, + + /// Added in: v9.0.0Removed in: v10.0.0 + /// Used when a given value is out of the accepted range. + ERR_VALUE_OUT_OF_RANGE, + + /// The module must be successfully linked before instantiation. + ERR_VM_MODULE_NOT_LINKED, + + /// Added in: v11.0.0Removed in: v16.9.0 + /// The pathname used for the main script of a worker has an unknown file extension. + ERR_WORKER_UNSUPPORTED_EXTENSION, + + /// Added in: v9.0.0Removed in: v10.0.0 + ERR_ZLIB_BINDING_CLOSED, + + /// Used when an attempt is made to use a zlib object after it has already been closed. + /// CPU USAGE + ERR_CPU_USAGE, +}; diff --git a/src/javascript/jsc/node/syscall.zig b/src/javascript/jsc/node/syscall.zig new file mode 100644 index 000000000..7dee85736 --- /dev/null +++ b/src/javascript/jsc/node/syscall.zig @@ -0,0 +1,465 @@ +// This file is entirely based on Zig's std.os +// The differences are in error handling +const std = @import("std"); +const os = std.os; +const builtin = @import("builtin"); + +const Syscall = @This(); +const Environment = @import("../../../global.zig").Environment; +const default_allocator = @import("../../../global.zig").default_allocator; +const JSC = @import("../../../jsc.zig"); +const SystemError = JSC.SystemError; +const darwin = os.darwin; +const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES; +const fd_t = std.os.fd_t; +const C = @import("../../../global.zig").C; +const linux = os.linux; +const Maybe = JSC.Node.Maybe; + +pub const system = if (Environment.isLinux) linux else darwin; +const libc = std.os.system; + +pub const Tag = enum(u8) { + TODO, + + access, + chmod, + chown, + clonefile, + close, + copy_file_range, + copyfile, + fchmod, + fchown, + fcntl, + fdatasync, + fstat, + fsync, + ftruncate, + futimens, + getdents64, + getdirentries64, + lchmod, + lchown, + link, + lseek, + lstat, + lutimes, + mkdir, + mkdtemp, + open, + pread, + pwrite, + read, + readlink, + rename, + stat, + symlink, + unlink, + utimes, + write, + getcwd, + chdir, + fcopyfile, + + pub var strings = std.EnumMap(Tag, JSC.C.JSStringRef).initFull(null); +}; +const PathString = @import("../../../global.zig").PathString; + +const mode_t = os.mode_t; + +const open_sym = system.open; + +const fstat_sym = if (builtin.os.tag == .linux and builtin.link_libc) + libc.fstat64 +else + libc.fstat; + +const mem = std.mem; + +pub fn getcwd(buf: *[std.fs.MAX_PATH_BYTES]u8) Maybe([]const u8) { + const Result = Maybe([]const u8); + buf[0] = 0; + const rc = std.c.getcwd(buf, std.fs.MAX_PATH_BYTES); + return if (rc != null) + Result{ .result = std.mem.sliceTo(rc.?[0..std.fs.MAX_PATH_BYTES], 0) } + else + Result.errnoSys(0, .getcwd).?; +} + +pub fn fchmod(fd: JSC.Node.FileDescriptor, mode: JSC.Node.Mode) Maybe(void) { + return Maybe(void).errnoSys(C.fchmod(fd, mode), .fchmod) orelse + Maybe(void).success; +} + +pub fn chdir(destination: [:0]const u8) Maybe(void) { + const rc = libc.chdir(destination); + return Maybe(void).errnoSys(rc, .chdir) orelse Maybe(void).success; +} + +pub fn stat(path: [:0]const u8) Maybe(os.Stat) { + var stat_ = mem.zeroes(os.Stat); + if (Maybe(os.Stat).errnoSys(libc.stat(path, &stat_), .stat)) |err| return err; + return Maybe(os.Stat){ .result = stat_ }; +} + +pub fn lstat(path: [:0]const u8) Maybe(os.Stat) { + var stat_ = mem.zeroes(os.Stat); + if (Maybe(os.Stat).errnoSys(C.lstat(path, &stat_), .lstat)) |err| return err; + return Maybe(os.Stat){ .result = stat_ }; +} + +pub fn fstat(fd: JSC.Node.FileDescriptor) Maybe(os.Stat) { + var stat_ = mem.zeroes(os.Stat); + if (Maybe(os.Stat).errnoSys(fstat_sym(fd, &stat_), .fstat)) |err| return err; + return Maybe(os.Stat){ .result = stat_ }; +} + +pub fn mkdir(file_path: [:0]const u8, flags: JSC.Node.Mode) Maybe(void) { + if (comptime Environment.isMac) { + return Maybe(void).errnoSysP(darwin.mkdir(file_path, flags), .mkdir, file_path) orelse Maybe(void).success; + } + + if (comptime Environment.isLinux) { + return Maybe(void).errnoSysP(linux.mkdir(file_path, flags), .mkdir, file_path) orelse Maybe(void).success; + } +} + +pub fn getErrno(rc: anytype) std.os.E { + if (comptime Environment.isMac) return std.os.errno(rc); + const Type = @TypeOf(rc); + + return switch (Type) { + comptime_int, usize => std.os.linux.getErrno(@as(usize, rc)), + i32, c_int, isize => std.os.linux.getErrno(@bitCast(usize, @as(isize, rc))), + else => @compileError("Not implemented yet for type " ++ @typeName(Type)), + }; +} + +pub fn open(file_path: [:0]const u8, flags: JSC.Node.Mode, perm: JSC.Node.Mode) Maybe(JSC.Node.FileDescriptor) { + while (true) { + const rc = Syscall.system.open(file_path, flags, perm); + return switch (Syscall.getErrno(rc)) { + .SUCCESS => .{ .result = @intCast(JSC.Node.FileDescriptor, rc) }, + .INTR => continue, + else => |err| { + return Maybe(std.os.fd_t){ + .err = .{ + .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), + .syscall = .open, + }, + }; + }, + }; + } + + unreachable; +} + +// The zig standard library marks BADF as unreachable +// That error is not unreachable for us +pub fn close(fd: std.os.fd_t) ?Syscall.Error { + if (comptime Environment.isMac) { + // This avoids the EINTR problem. + return switch (darwin.getErrno(darwin.@"close$NOCANCEL"(fd))) { + .BADF => Syscall.Error{ .errno = @enumToInt(os.E.BADF), .syscall = .close }, + else => null, + }; + } + + if (comptime Environment.isLinux) { + return switch (linux.getErrno(linux.close(fd))) { + .BADF => Syscall.Error{ .errno = @enumToInt(os.E.BADF), .syscall = .close }, + else => null, + }; + } + + @compileError("Not implemented yet"); +} + +const max_count = switch (builtin.os.tag) { + .linux => 0x7ffff000, + .macos, .ios, .watchos, .tvos => std.math.maxInt(i32), + else => std.math.maxInt(isize), +}; + +pub fn write(fd: os.fd_t, bytes: []const u8) Maybe(usize) { + const adjusted_len = @minimum(max_count, bytes.len); + + while (true) { + const rc = libc.write(fd, bytes.ptr, adjusted_len); + if (Maybe(usize).errnoSys(rc, .write)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +const pread_sym = if (builtin.os.tag == .linux and builtin.link_libc) + libc.pread64 +else + libc.pread; + +pub fn pread(fd: os.fd_t, buf: []u8, offset: i64) Maybe(usize) { + const adjusted_len = @minimum(buf.len, max_count); + + const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned + while (true) { + const rc = pread_sym(fd, buf.ptr, adjusted_len, ioffset); + if (Maybe(usize).errnoSys(rc, .pread)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +const pwrite_sym = if (builtin.os.tag == .linux and builtin.link_libc) + libc.pwrite64 +else + libc.pwrite; + +pub fn pwrite(fd: os.fd_t, bytes: []const u8, offset: i64) Maybe(usize) { + const adjusted_len = @minimum(bytes.len, max_count); + + const ioffset = @bitCast(i64, offset); // the OS treats this as unsigned + while (true) { + const rc = pwrite_sym(fd, bytes.ptr, adjusted_len, ioffset); + return if (Maybe(usize).errnoSys(rc, .pwrite)) |err| { + switch (err.getErrno()) { + .INTR => continue, + else => return err, + } + } else Maybe(usize){ .result = @intCast(usize, rc) }; + } + + unreachable; +} + +pub fn read(fd: os.fd_t, buf: []u8) Maybe(usize) { + const adjusted_len = @minimum(buf.len, max_count); + while (true) { + const rc = libc.read(fd, buf.ptr, adjusted_len); + if (Maybe(usize).errnoSys(rc, .read)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +pub fn readlink(in: [:0]const u8, buf: []u8) Maybe(usize) { + while (true) { + const rc = libc.readlink(in, buf.ptr, buf.len); + + if (Maybe(usize).errnoSys(rc, .readlink)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(usize){ .result = @intCast(usize, rc) }; + } + unreachable; +} + +pub fn rename(from: [:0]const u8, to: [:0]const u8) Maybe(void) { + while (true) { + if (Maybe(void).errnoSys(libc.rename(from, to), .rename)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn chown(path: [:0]const u8, uid: os.uid_t, gid: os.gid_t) Maybe(void) { + while (true) { + if (Maybe(void).errnoSys(C.chown(path, uid, gid), .chown)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn symlink(from: [:0]const u8, to: [:0]const u8) Maybe(void) { + while (true) { + if (Maybe(void).errnoSys(libc.symlink(from, to), .symlink)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn clonefile(from: [:0]const u8, to: [:0]const u8) Maybe(void) { + if (comptime !Environment.isMac) @compileError("macOS only"); + + while (true) { + if (Maybe(void).errnoSys(C.darwin.clonefile(from, to, 0), .clonefile)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn copyfile(from: [:0]const u8, to: [:0]const u8, flags: c_int) Maybe(void) { + if (comptime !Environment.isMac) @compileError("macOS only"); + + while (true) { + if (Maybe(void).errnoSys(C.darwin.copyfile(from, to, null, flags), .copyfile)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn fcopyfile(fd_in: std.os.fd_t, fd_out: std.os.fd_t, flags: c_int) Maybe(void) { + if (comptime !Environment.isMac) @compileError("macOS only"); + + while (true) { + if (Maybe(void).errnoSys(darwin.fcopyfile(fd_in, fd_out, null, flags), .fcopyfile)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn unlink(from: [:0]const u8) Maybe(void) { + while (true) { + if (Maybe(void).errno(libc.unlink(from), .unlink)) |err| { + if (err.getErrno() == .INTR) continue; + return err; + } + return Maybe(void).success; + } + unreachable; +} + +pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) Maybe([]u8) { + switch (comptime builtin.os.tag) { + .windows => { + const windows = std.os.windows; + var wide_buf: [windows.PATH_MAX_WIDE]u16 = undefined; + const wide_slice = windows.GetFinalPathNameByHandle(fd, .{}, wide_buf[0..]) catch { + return Maybe([]u8){ .err = .{ .errno = .EBADF } }; + }; + + // Trust that Windows gives us valid UTF-16LE. + const end_index = std.unicode.utf16leToUtf8(out_buffer, wide_slice) catch unreachable; + return .{ .result = out_buffer[0..end_index] }; + }, + .macos, .ios, .watchos, .tvos => { + // On macOS, we can use F.GETPATH fcntl command to query the OS for + // the path to the file descriptor. + @memset(out_buffer, 0, MAX_PATH_BYTES); + if (Maybe([]u8).errnoSys(darwin.fcntl(fd, os.F.GETPATH, out_buffer), .fcntl)) |err| { + return err; + } + const len = mem.indexOfScalar(u8, out_buffer[0..], @as(u8, 0)) orelse MAX_PATH_BYTES; + return .{ .result = out_buffer[0..len] }; + }, + .linux => { + var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined; + const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/fd/{d}\x00", .{fd}) catch unreachable; + + return switch (readlink(proc_path, out_buffer)) { + .err => |err| return .{ .err = err }, + .result => |len| return .{ .result = out_buffer[0..len] }, + }; + }, + // .solaris => { + // var procfs_buf: ["/proc/self/path/-2147483648".len:0]u8 = undefined; + // const proc_path = std.fmt.bufPrintZ(procfs_buf[0..], "/proc/self/path/{d}", .{fd}) catch unreachable; + + // const target = readlinkZ(proc_path, out_buffer) catch |err| switch (err) { + // error.UnsupportedReparsePointType => unreachable, + // error.NotLink => unreachable, + // else => |e| return e, + // }; + // return target; + // }, + else => @compileError("querying for canonical path of a handle is unsupported on this host"), + } +} + +pub const Error = struct { + const max_errno_value = brk: { + const errno_values = std.enums.values(os.E); + var err = @enumToInt(os.E.SUCCESS); + for (errno_values) |errn| { + err = @maximum(err, @enumToInt(errn)); + } + break :brk err; + }; + pub const Int: type = std.math.IntFittingRange(0, max_errno_value + 5); + + errno: Int, + syscall: Syscall.Tag = @intToEnum(Syscall.Tag, 0), + path: []const u8 = "", + + pub inline fn getErrno(this: Error) os.E { + return @intToEnum(os.E, this.errno); + } + + pub inline fn withPath(this: Error, path: anytype) Error { + return Error{ + .errno = this.errno, + .syscall = this.syscall, + .path = std.mem.span(path), + }; + } + + pub inline fn withSyscall(this: Error, syscall: Syscall) Error { + return Error{ + .errno = this.errno, + .syscall = syscall, + .path = this.path, + }; + } + + pub const todo_errno = std.math.maxInt(Int) - 1; + pub const todo = Error{ .errno = todo_errno }; + + pub fn toSystemError(this: Error) SystemError { + var sys = SystemError{ + .errno = @as(c_int, this.errno) * -1, + .syscall = JSC.ZigString.init(@tagName(this.syscall)), + }; + + // errno label + if (this.errno > 0 and this.errno < C.SystemErrno.max) { + const system_errno = @intToEnum(C.SystemErrno, this.errno); + sys.code = JSC.ZigString.init(@tagName(system_errno)); + if (C.SystemErrno.labels.get(system_errno)) |label| { + sys.message = JSC.ZigString.init(label); + } + } + + if (this.path.len > 0) { + sys.path = JSC.ZigString.init(this.path); + } + + return sys; + } + + pub fn toJS(this: Error, ctx: JSC.C.JSContextRef) JSC.C.JSObjectRef { + return this.toSystemError().toErrorInstance(ctx.ptr()).asObjectRef(); + } + + pub fn toJSC(this: Error, ptr: *JSC.JSGlobalObject) JSC.JSValue { + return this.toSystemError().toErrorInstance(ptr); + } +}; diff --git a/src/javascript/jsc/node/types.zig b/src/javascript/jsc/node/types.zig new file mode 100644 index 000000000..664df0d04 --- /dev/null +++ b/src/javascript/jsc/node/types.zig @@ -0,0 +1,2065 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const _global = @import("../../../global.zig"); +const strings = _global.strings; +const string = _global.string; +const AsyncIO = @import("io"); +const JSC = @import("../../../jsc.zig"); +const PathString = JSC.PathString; +const Environment = _global.Environment; +const C = _global.C; +const Syscall = @import("./syscall.zig"); +const os = std.os; +const Buffer = JSC.MarkedArrayBuffer; +const IdentityContext = @import("../../../identity_context.zig").IdentityContext; +const logger = @import("../../../logger.zig"); +const Shimmer = @import("../bindings/shimmer.zig").Shimmer; +const is_bindgen: bool = std.meta.globalOption("bindgen", bool) orelse false; +const meta = _global.meta; + +/// Time in seconds. Not nanos! +pub const TimeLike = c_int; +pub const Mode = if (Environment.isLinux) u32 else std.os.mode_t; +const heap_allocator = _global.default_allocator; +pub fn DeclEnum(comptime T: type) type { + const fieldInfos = std.meta.declarations(T); + var enumFields: [fieldInfos.len]std.builtin.TypeInfo.EnumField = undefined; + var decls = [_]std.builtin.TypeInfo.Declaration{}; + inline for (fieldInfos) |field, i| { + enumFields[i] = .{ + .name = field.name, + .value = i, + }; + } + return @Type(.{ + .Enum = .{ + .layout = .Auto, + .tag_type = std.math.IntFittingRange(0, fieldInfos.len - 1), + .fields = &enumFields, + .decls = &decls, + .is_exhaustive = true, + }, + }); +} + +pub const FileDescriptor = os.fd_t; +pub const Flavor = enum { + sync, + promise, + callback, + + pub fn Wrap(comptime this: Flavor, comptime Type: type) type { + return comptime brk: { + switch (this) { + .sync => break :brk Type, + // .callback => { + // const Callback = CallbackTask(Type); + // }, + else => @compileError("Not implemented yet"), + } + }; + } +}; + +/// Node.js expects the error to include contextual information +/// - "syscall" +/// - "path" +/// - "errno" +pub fn Maybe(comptime ResultType: type) type { + return union(Tag) { + pub const ReturnType = ResultType; + + err: Syscall.Error, + result: ReturnType, + + pub const Tag = enum { err, result }; + + pub const success: @This() = @This(){ + .result = std.mem.zeroes(ReturnType), + }; + + pub const todo: @This() = @This(){ .err = Syscall.Error.todo }; + + pub inline fn getErrno(this: @This()) os.E { + return switch (this) { + .result => os.E.SUCCESS, + .err => |err| @intToEnum(os.E, err.errno), + }; + } + + pub inline fn errno(rc: anytype) ?@This() { + return switch (Syscall.getErrno(rc)) { + .SUCCESS => null, + else => |err| @This(){ + // always truncate + .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)) }, + }, + }; + } + + pub inline fn errnoSys(rc: anytype, syscall: Syscall.Tag) ?@This() { + return switch (Syscall.getErrno(rc)) { + .SUCCESS => null, + else => |err| @This(){ + // always truncate + .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), .syscall = syscall }, + }, + }; + } + + pub inline fn errnoSysP(rc: anytype, syscall: Syscall.Tag, path: anytype) ?@This() { + return switch (Syscall.getErrno(rc)) { + .SUCCESS => null, + else => |err| @This(){ + // always truncate + .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), .syscall = syscall, .path = std.mem.span(path) }, + }, + }; + } + }; +} + +pub const StringOrBuffer = union(Tag) { + string: string, + buffer: Buffer, + + pub const Tag = enum { string, buffer }; + + pub fn slice(this: StringOrBuffer) []const u8 { + return switch (this) { + .string => this.string, + .buffer => this.buffer.slice(), + }; + } + + pub export fn external_string_finalizer(_: ?*anyopaque, _: JSC.C.JSStringRef, buffer: *anyopaque, byteLength: usize) void { + _global.default_allocator.free(@ptrCast([*]const u8, buffer)[0..byteLength]); + } + + pub fn toJS(this: StringOrBuffer, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return switch (this) { + .string => { + var external = JSC.C.JSStringCreateExternal(this.string.ptr, this.string.len, null, external_string_finalizer); + return JSC.C.JSValueMakeString(ctx, external); + }, + .buffer => this.buffer.toJSObjectRef(ctx, exception), + }; + } + + pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?StringOrBuffer { + return switch (value.jsType()) { + JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject, JSC.JSValue.JSType.Object => { + var zig_str = JSC.ZigString.init(""); + value.toZigString(&zig_str, global); + if (zig_str.len == 0) { + JSC.throwInvalidArguments("Expected string to have length > 0", .{}, global.ref(), exception); + return null; + } + + return StringOrBuffer{ + .string = zig_str.slice(), + }; + }, + JSC.JSValue.JSType.ArrayBuffer => StringOrBuffer{ + .buffer = Buffer.fromArrayBuffer(global.ref(), value, exception), + }, + JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.DataView => StringOrBuffer{ + .buffer = Buffer.fromArrayBuffer(global.ref(), value, exception), + }, + else => null, + }; + } +}; +pub const ErrorCode = @import("./nodejs_error_code.zig").Code; + +// We can't really use Zig's error handling for syscalls because Node.js expects the "real" errno to be returned +// and various issues with std.os that make it too unstable for arbitrary user input (e.g. how .BADF is marked as unreachable) + +/// https://github.com/nodejs/node/blob/master/lib/buffer.js#L587 +pub const Encoding = enum(u8) { + utf8, + ucs2, + utf16le, + latin1, + ascii, + base64, + base64url, + hex, + + /// Refer to the buffer's encoding + buffer, + + const Eight = strings.ExactSizeMatcher(8); + /// Caller must verify the value is a string + pub fn fromStringValue(value: JSC.JSValue, global: *JSC.JSGlobalObject) ?Encoding { + var str = JSC.ZigString.Empty; + value.toZigString(&str, global); + const slice = str.slice(); + return switch (slice.len) { + 0...2 => null, + else => switch (Eight.matchLower(slice)) { + Eight.case("utf-8"), Eight.case("utf8") => Encoding.utf8, + Eight.case("ucs-2"), Eight.case("ucs2") => Encoding.ucs2, + Eight.case("utf16-le"), Eight.case("utf16le") => Encoding.utf16le, + Eight.case("latin1") => Encoding.latin1, + Eight.case("ascii") => Encoding.ascii, + Eight.case("base64") => Encoding.base64, + Eight.case("hex") => Encoding.hex, + Eight.case("buffer") => Encoding.buffer, + else => null, + }, + "base64url".len => brk: { + if (strings.eqlCaseInsensitiveASCII(slice, "base64url", false)) { + break :brk Encoding.base64url; + } + break :brk null; + }, + }; + } +}; + +const PathOrBuffer = union(Tag) { + path: PathString, + buffer: Buffer, + + pub const Tag = enum { path, buffer }; + + pub inline fn slice(this: PathOrBuffer) []const u8 { + return this.path.slice(); + } +}; + +pub fn CallbackTask(comptime Result: type) type { + return struct { + callback: JSC.C.JSObjectRef, + option: Option, + success: bool = false, + completion: AsyncIO.Completion, + + pub const Option = union { + err: JSC.SystemError, + result: Result, + }; + }; +} + +pub const PathLike = union(Tag) { + string: PathString, + buffer: Buffer, + url: void, + + pub const Tag = enum { string, buffer, url }; + + pub inline fn slice(this: PathLike) string { + return switch (this) { + .string => this.string.slice(), + .buffer => this.buffer.slice(), + else => unreachable, // TODO: + }; + } + + pub fn sliceZWithForceCopy(this: PathLike, buf: *[std.fs.MAX_PATH_BYTES]u8, comptime force: bool) [:0]const u8 { + var sliced = this.slice(); + + if (sliced.len == 0) return ""; + + if (comptime !force) { + if (sliced[sliced.len - 1] == 0) { + var sliced_ptr = sliced.ptr; + return sliced_ptr[0 .. sliced.len - 1 :0]; + } + } + + @memcpy(buf, sliced.ptr, sliced.len); + buf[sliced.len] = 0; + return buf[0..sliced.len :0]; + } + + pub inline fn sliceZ(this: PathLike, buf: *[std.fs.MAX_PATH_BYTES]u8) [:0]const u8 { + return sliceZWithForceCopy(this, buf, false); + } + + pub fn toJS(this: PathLike, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return switch (this) { + .string => this.string.toJS(ctx, exception), + .buffer => this.buffer.toJSObjectRef(ctx, exception), + else => unreachable, + }; + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?PathLike { + const arg = arguments.next() orelse return null; + switch (arg.jsType()) { + JSC.JSValue.JSType.Uint8Array, + JSC.JSValue.JSType.DataView, + => { + const buffer = Buffer.fromTypedArray(ctx, arg, exception); + if (exception.* != null) return null; + if (!Valid.pathBuffer(buffer, ctx, exception)) return null; + + JSC.C.JSValueProtect(ctx, arg.asObjectRef()); + arguments.eat(); + return PathLike{ .buffer = buffer }; + }, + + JSC.JSValue.JSType.ArrayBuffer => { + const buffer = Buffer.fromArrayBuffer(ctx, arg, exception); + if (exception.* != null) return null; + if (!Valid.pathBuffer(buffer, ctx, exception)) return null; + + JSC.C.JSValueProtect(ctx, arg.asObjectRef()); + arguments.eat(); + + return PathLike{ .buffer = buffer }; + }, + + JSC.JSValue.JSType.String, + JSC.JSValue.JSType.StringObject, + JSC.JSValue.JSType.DerivedStringObject, + => { + var zig_str = JSC.ZigString.init(""); + arg.toZigString(&zig_str, ctx.ptr()); + + if (!Valid.pathString(zig_str, ctx, exception)) return null; + + JSC.C.JSValueProtect(ctx, arg.asObjectRef()); + arguments.eat(); + + if (zig_str.is16Bit()) { + var printed = std.mem.span(std.fmt.allocPrintZ(arguments.arena.allocator(), "{}", .{zig_str}) catch unreachable); + return PathLike{ .string = PathString.init(printed.ptr[0 .. printed.len + 1]) }; + } + + return PathLike{ .string = PathString.init(zig_str.slice()) }; + }, + else => return null, + } + } +}; + +pub const Valid = struct { + pub fn fileDescriptor(fd: FileDescriptor, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) bool { + if (fd < 0) { + JSC.throwInvalidArguments("Invalid file descriptor, must not be negative number", .{}, ctx, exception); + return false; + } + + return true; + } + + pub fn pathString(zig_str: JSC.ZigString, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) bool { + switch (zig_str.len) { + 0 => { + JSC.throwInvalidArguments("Invalid path string: can't be empty", .{}, ctx, exception); + return false; + }, + 1...std.fs.MAX_PATH_BYTES => return true, + else => { + // TODO: should this be an EINVAL? + JSC.throwInvalidArguments( + comptime std.fmt.comptimePrint("Invalid path string: path is too long (max: {d})", .{std.fs.MAX_PATH_BYTES}), + .{}, + ctx, + exception, + ); + return false; + }, + } + + unreachable; + } + + pub fn pathBuffer(buffer: Buffer, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) bool { + const slice = buffer.slice(); + switch (slice.len) { + 0 => { + JSC.throwInvalidArguments("Invalid path buffer: can't be empty", .{}, ctx, exception); + return false; + }, + + else => { + + // TODO: should this be an EINVAL? + JSC.throwInvalidArguments( + comptime std.fmt.comptimePrint("Invalid path buffer: path is too long (max: {d})", .{std.fs.MAX_PATH_BYTES}), + .{}, + ctx, + exception, + ); + return false; + }, + 1...std.fs.MAX_PATH_BYTES => return true, + } + + unreachable; + } +}; + +pub const ArgumentsSlice = struct { + remaining: []const JSC.JSValue, + arena: std.heap.ArenaAllocator = std.heap.ArenaAllocator.init(_global.default_allocator), + all: []const JSC.JSValue, + + pub fn init(arguments: []const JSC.JSValue) ArgumentsSlice { + return ArgumentsSlice{ + .remaining = arguments, + .all = arguments, + }; + } + + pub inline fn len(this: *const ArgumentsSlice) u16 { + return @truncate(u16, this.remaining.len); + } + pub fn eat(this: *ArgumentsSlice) void { + if (this.remaining.len == 0) { + return; + } + + this.remaining = this.remaining[1..]; + } + + pub fn next(this: *ArgumentsSlice) ?JSC.JSValue { + if (this.remaining.len == 0) { + return null; + } + + return this.remaining[0]; + } +}; + +pub fn fileDescriptorFromJS(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?FileDescriptor { + if (!value.isNumber() or value.isBigInt()) return null; + const fd = value.toInt32(); + if (!Valid.fileDescriptor(fd, ctx, exception)) { + return null; + } + + return @truncate(FileDescriptor, fd); +} + +var _get_time_prop_string: ?JSC.C.JSStringRef = null; +pub fn timeLikeFromJS(ctx: JSC.C.JSContextRef, value_: JSC.JSValue, exception: JSC.C.ExceptionRef) ?TimeLike { + var value = value_; + if (JSC.C.JSValueIsDate(ctx, value.asObjectRef())) { + // TODO: make this faster + var get_time_prop = _get_time_prop_string orelse brk: { + var str = JSC.C.JSStringCreateStatic("getTime", "getTime".len); + _get_time_prop_string = str; + break :brk str; + }; + + var getTimeFunction = JSC.C.JSObjectGetProperty(ctx, value.asObjectRef(), get_time_prop, exception); + if (exception.* != null) return null; + value = JSC.JSValue.fromRef(JSC.C.JSObjectCallAsFunction(ctx, getTimeFunction, value.asObjectRef(), 0, null, exception) orelse return null); + if (exception.* != null) return null; + } + + const seconds = value.asNumber(); + if (!std.math.isFinite(seconds)) { + return null; + } + + return @floatToInt(TimeLike, @maximum(@floor(seconds), std.math.minInt(TimeLike))); +} + +pub fn modeFromJS(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?Mode { + const mode_int = if (value.isNumber()) + @truncate(Mode, value.to(Mode)) + else brk: { + if (value.isUndefinedOrNull()) return null; + + // An easier method of constructing the mode is to use a sequence of + // three octal digits (e.g. 765). The left-most digit (7 in the example), + // specifies the permissions for the file owner. The middle digit (6 in + // the example), specifies permissions for the group. The right-most + // digit (5 in the example), specifies the permissions for others. + + var zig_str = JSC.ZigString.init(""); + value.toZigString(&zig_str, ctx.ptr()); + var slice = zig_str.slice(); + if (strings.hasPrefix(slice, "0o")) { + slice = slice[2..]; + } + + break :brk std.fmt.parseInt(Mode, slice, 8) catch { + JSC.throwInvalidArguments("Invalid mode string: must be an octal number", .{}, ctx, exception); + return null; + }; + }; + + if (mode_int < 0 or mode_int > 0o777) { + JSC.throwInvalidArguments("Invalid mode: must be an octal number", .{}, ctx, exception); + return null; + } + + return mode_int; +} + +pub const PathOrFileDescriptor = union(Tag) { + path: PathLike, + fd: FileDescriptor, + + pub const Tag = enum { fd, path }; + + pub fn copyToStream(this: PathOrFileDescriptor, flags: FileSystemFlags, auto_close: bool, mode: Mode, allocator: std.mem.Allocator, stream: *Stream) !void { + switch (this) { + .fd => |fd| { + stream.content = Stream.Content{ + .file = .{ + .fd = fd, + .flags = flags, + .mode = mode, + }, + }; + stream.content_type = .file; + }, + .path => |path| { + stream.content = Stream.Content{ + .file_path = .{ + .path = PathString.init(std.mem.span(try allocator.dupeZ(u8, path.slice()))), + .auto_close = auto_close, + .file = .{ + .fd = std.math.maxInt(FileDescriptor), + .flags = flags, + .mode = mode, + }, + .opened = false, + }, + }; + stream.content_type = .file_path; + }, + } + } + + pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice, exception: JSC.C.ExceptionRef) ?PathOrFileDescriptor { + const first = arguments.next() orelse return null; + + if (fileDescriptorFromJS(ctx, first, exception)) |fd| { + arguments.eat(); + return PathOrFileDescriptor{ .fd = fd }; + } + + if (exception.* != null) return null; + + return PathOrFileDescriptor{ .path = PathLike.fromJS(ctx, arguments, exception) orelse return null }; + } + + pub fn toJS(this: PathOrFileDescriptor, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + return switch (this) { + .path => this.path.toJS(ctx, exception), + .fd => JSC.JSValue.jsNumberFromInt32(@intCast(i32, this.fd)).asRef(), + }; + } +}; + +pub const FileSystemFlags = enum(Mode) { + /// Open file for appending. The file is created if it does not exist. + @"a" = std.os.O.APPEND, + /// Like 'a' but fails if the path exists. + // @"ax" = std.os.O.APPEND | std.os.O.EXCL, + /// Open file for reading and appending. The file is created if it does not exist. + // @"a+" = std.os.O.APPEND | std.os.O.RDWR, + /// Like 'a+' but fails if the path exists. + // @"ax+" = std.os.O.APPEND | std.os.O.RDWR | std.os.O.EXCL, + /// Open file for appending in synchronous mode. The file is created if it does not exist. + // @"as" = std.os.O.APPEND, + /// Open file for reading and appending in synchronous mode. The file is created if it does not exist. + // @"as+" = std.os.O.APPEND | std.os.O.RDWR, + /// Open file for reading. An exception occurs if the file does not exist. + @"r" = std.os.O.RDONLY, + /// Open file for reading and writing. An exception occurs if the file does not exist. + // @"r+" = std.os.O.RDWR, + /// Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. + /// This is primarily useful for opening files on NFS mounts as it allows skipping the potentially stale local cache. It has a very real impact on I/O performance so using this flag is not recommended unless it is needed. + /// This doesn't turn fs.open() or fsPromises.open() into a synchronous blocking call. If synchronous operation is desired, something like fs.openSync() should be used. + // @"rs+" = std.os.O.RDWR, + /// Open file for writing. The file is created (if it does not exist) or truncated (if it exists). + @"w" = std.os.O.WRONLY | std.os.O.CREAT, + /// Like 'w' but fails if the path exists. + // @"wx" = std.os.O.WRONLY | std.os.O.TRUNC, + // /// Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). + // @"w+" = std.os.O.RDWR | std.os.O.CREAT, + // /// Like 'w+' but fails if the path exists. + // @"wx+" = std.os.O.RDWR | std.os.O.EXCL, + + _, + + const O_RDONLY: Mode = std.os.O.RDONLY; + const O_RDWR: Mode = std.os.O.RDWR; + const O_APPEND: Mode = std.os.O.APPEND; + const O_CREAT: Mode = std.os.O.CREAT; + const O_WRONLY: Mode = std.os.O.WRONLY; + const O_EXCL: Mode = std.os.O.EXCL; + const O_SYNC: Mode = 0; + const O_TRUNC: Mode = std.os.O.TRUNC; + + pub fn fromJS(ctx: JSC.C.JSContextRef, val: JSC.JSValue, exception: JSC.C.ExceptionRef) ?FileSystemFlags { + if (val.isUndefinedOrNull()) { + return @intToEnum(FileSystemFlags, O_RDONLY); + } + + if (val.isNumber()) { + const number = val.toInt32(); + if (!(number > 0o000 and number < 0o777)) { + JSC.throwInvalidArguments( + "Invalid integer mode: must be a number between 0o000 and 0o777", + .{}, + ctx, + exception, + ); + return null; + } + return @intToEnum(FileSystemFlags, number); + } + + const jsType = val.jsType(); + if (jsType.isStringLike()) { + var zig_str = JSC.ZigString.init(""); + val.toZigString(&zig_str, ctx.ptr()); + + var buf: [4]u8 = .{ 0, 0, 0, 0 }; + @memcpy(&buf, zig_str.ptr, @minimum(buf.len, zig_str.len)); + const Matcher = strings.ExactSizeMatcher(4); + + // https://github.com/nodejs/node/blob/8c3637cd35cca352794e2c128f3bc5e6b6c41380/lib/internal/fs/utils.js#L565 + const flags = switch (Matcher.match(buf[0..4])) { + Matcher.case("r") => O_RDONLY, + Matcher.case("rs"), Matcher.case("sr") => O_RDONLY | O_SYNC, + Matcher.case("r+") => O_RDWR, + Matcher.case("rs+"), Matcher.case("sr+") => O_RDWR | O_SYNC, + + Matcher.case("w") => O_TRUNC | O_CREAT | O_WRONLY, + Matcher.case("wx"), Matcher.case("xw") => O_TRUNC | O_CREAT | O_WRONLY | O_EXCL, + + Matcher.case("w+") => O_TRUNC | O_CREAT | O_RDWR, + Matcher.case("wx+"), Matcher.case("xw+") => O_TRUNC | O_CREAT | O_RDWR | O_EXCL, + + Matcher.case("a") => O_APPEND | O_CREAT | O_WRONLY, + Matcher.case("ax"), Matcher.case("xa") => O_APPEND | O_CREAT | O_WRONLY | O_EXCL, + Matcher.case("as"), Matcher.case("sa") => O_APPEND | O_CREAT | O_WRONLY | O_SYNC, + + Matcher.case("a+") => O_APPEND | O_CREAT | O_RDWR, + Matcher.case("ax+"), Matcher.case("xa+") => O_APPEND | O_CREAT | O_RDWR | O_EXCL, + Matcher.case("as+"), Matcher.case("sa+") => O_APPEND | O_CREAT | O_RDWR | O_SYNC, + + Matcher.case("") => { + JSC.throwInvalidArguments( + "Invalid flag: string can't be empty", + .{}, + ctx, + exception, + ); + return null; + }, + else => { + JSC.throwInvalidArguments( + "Invalid flag. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", + .{}, + ctx, + exception, + ); + return null; + }, + }; + + return @intToEnum(FileSystemFlags, flags); + } + + return null; + } +}; + +/// Milliseconds precision +pub const Date = enum(u64) { + _, + + pub fn toJS(this: Date, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef { + const seconds = @floatCast(f64, @intToFloat(f128, @enumToInt(this)) * 1000.0); + const unix_timestamp = JSC.C.JSValueMakeNumber(ctx, seconds); + const array: [1]JSC.C.JSValueRef = .{unix_timestamp}; + const obj = JSC.C.JSObjectMakeDate(ctx, 1, &array, exception); + return obj; + } +}; + +fn StatsLike(comptime name: string, comptime T: type) type { + return struct { + const This = @This(); + + pub const Class = JSC.NewClass( + This, + .{ .name = name }, + .{}, + .{ + .dev = .{ + .get = JSC.To.JS.Getter(This, .dev), + .name = "dev", + }, + .ino = .{ + .get = JSC.To.JS.Getter(This, .ino), + .name = "ino", + }, + .mode = .{ + .get = JSC.To.JS.Getter(This, .mode), + .name = "mode", + }, + .nlink = .{ + .get = JSC.To.JS.Getter(This, .nlink), + .name = "nlink", + }, + .uid = .{ + .get = JSC.To.JS.Getter(This, .uid), + .name = "uid", + }, + .gid = .{ + .get = JSC.To.JS.Getter(This, .gid), + .name = "gid", + }, + .rdev = .{ + .get = JSC.To.JS.Getter(This, .rdev), + .name = "rdev", + }, + .size = .{ + .get = JSC.To.JS.Getter(This, .size), + .name = "size", + }, + .blksize = .{ + .get = JSC.To.JS.Getter(This, .blksize), + .name = "blksize", + }, + .blocks = .{ + .get = JSC.To.JS.Getter(This, .blocks), + .name = "blocks", + }, + .atime = .{ + .get = JSC.To.JS.Getter(This, .atime), + .name = "atime", + }, + .mtime = .{ + .get = JSC.To.JS.Getter(This, .mtime), + .name = "mtime", + }, + .ctime = .{ + .get = JSC.To.JS.Getter(This, .ctime), + .name = "ctime", + }, + .birthtime = .{ + .get = JSC.To.JS.Getter(This, .birthtime), + .name = "birthtime", + }, + .atime_ms = .{ + .get = JSC.To.JS.Getter(This, .atime_ms), + .name = "atimeMs", + }, + .mtime_ms = .{ + .get = JSC.To.JS.Getter(This, .mtime_ms), + .name = "mtimeMs", + }, + .ctime_ms = .{ + .get = JSC.To.JS.Getter(This, .ctime_ms), + .name = "ctimeMs", + }, + .birthtime_ms = .{ + .get = JSC.To.JS.Getter(This, .birthtime_ms), + .name = "birthtimeMs", + }, + }, + ); + + dev: T, + ino: T, + mode: T, + nlink: T, + uid: T, + gid: T, + rdev: T, + size: T, + blksize: T, + blocks: T, + atime_ms: T, + mtime_ms: T, + ctime_ms: T, + birthtime_ms: T, + atime: Date, + mtime: Date, + ctime: Date, + birthtime: Date, + + pub fn init(stat_: os.Stat) @This() { + const atime = stat_.atime(); + const mtime = stat_.mtime(); + const ctime = stat_.ctime(); + return @This(){ + .dev = @truncate(T, @intCast(i64, stat_.dev)), + .ino = @truncate(T, @intCast(i64, stat_.ino)), + .mode = @truncate(T, @intCast(i64, stat_.mode)), + .nlink = @truncate(T, @intCast(i64, stat_.nlink)), + .uid = @truncate(T, @intCast(i64, stat_.uid)), + .gid = @truncate(T, @intCast(i64, stat_.gid)), + .rdev = @truncate(T, @intCast(i64, stat_.rdev)), + .size = @truncate(T, @intCast(i64, stat_.size)), + .blksize = @truncate(T, @intCast(i64, stat_.blksize)), + .blocks = @truncate(T, @intCast(i64, stat_.blocks)), + .atime_ms = @truncate(T, @intCast(i64, if (atime.tv_nsec > 0) (@intCast(usize, atime.tv_nsec) / std.time.ns_per_ms) else 0)), + .mtime_ms = @truncate(T, @intCast(i64, if (mtime.tv_nsec > 0) (@intCast(usize, mtime.tv_nsec) / std.time.ns_per_ms) else 0)), + .ctime_ms = @truncate(T, @intCast(i64, if (ctime.tv_nsec > 0) (@intCast(usize, ctime.tv_nsec) / std.time.ns_per_ms) else 0)), + .atime = @intToEnum(Date, @intCast(u64, @maximum(atime.tv_sec, 0))), + .mtime = @intToEnum(Date, @intCast(u64, @maximum(mtime.tv_sec, 0))), + .ctime = @intToEnum(Date, @intCast(u64, @maximum(ctime.tv_sec, 0))), + + // Linux doesn't include this info in stat + // maybe it does in statx, but do you really need birthtime? If you do please file an issue. + .birthtime_ms = if (Environment.isLinux) + 0 + else + @truncate(T, @intCast(i64, if (stat_.birthtimensec > 0) (@intCast(usize, stat_.birthtimensec) / std.time.ns_per_ms) else 0)), + + .birthtime = if (Environment.isLinux) + @intToEnum(Date, 0) + else + @intToEnum(Date, @intCast(u64, @maximum(stat_.birthtimesec, 0))), + }; + } + + pub fn toJS(this: Stats, ctx: JSC.C.JSContextRef, _: JSC.C.ExceptionRef) JSC.C.JSValueRef { + var _this = _global.default_allocator.create(Stats) catch unreachable; + _this.* = this; + return Class.make(ctx, _this); + } + + pub fn finalize(this: *Stats) void { + _global.default_allocator.destroy(this); + } + }; +} + +pub const Stats = StatsLike("Stats", i32); +pub const BigIntStats = StatsLike("BigIntStats", i64); + +/// A class representing a directory stream. +/// +/// Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. +/// +/// ```js +/// import { opendir } from 'fs/promises'; +/// +/// try { +/// const dir = await opendir('./'); +/// for await (const dirent of dir) +/// console.log(dirent.name); +/// } catch (err) { +/// console.error(err); +/// } +/// ``` +/// +/// When using the async iterator, the `fs.Dir` object will be automatically +/// closed after the iterator exits. +/// @since v12.12.0 +pub const DirEnt = struct { + name: PathString, + // not publicly exposed + kind: Kind, + + pub const Kind = std.fs.File.Kind; + + pub fn isBlockDevice( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.BlockDevice); + } + pub fn isCharacterDevice( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.CharacterDevice); + } + pub fn isDirectory( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.Directory); + } + pub fn isFIFO( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.NamedPipe or this.kind == std.fs.File.Kind.EventPort); + } + pub fn isFile( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.File); + } + pub fn isSocket( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.UnixDomainSocket); + } + pub fn isSymbolicLink( + this: *DirEnt, + ctx: JSC.C.JSContextRef, + _: JSC.C.JSObjectRef, + _: JSC.C.JSObjectRef, + _: []const JSC.C.JSValueRef, + _: JSC.C.ExceptionRef, + ) JSC.C.JSValueRef { + return JSC.C.JSValueMakeBoolean(ctx, this.kind == std.fs.File.Kind.SymLink); + } + + pub const Class = JSC.NewClass(DirEnt, .{ .name = "DirEnt" }, .{ + .isBlockDevice = .{ + .name = "isBlockDevice", + .rfn = isBlockDevice, + }, + .isCharacterDevice = .{ + .name = "isCharacterDevice", + .rfn = isCharacterDevice, + }, + .isDirectory = .{ + .name = "isDirectory", + .rfn = isDirectory, + }, + .isFIFO = .{ + .name = "isFIFO", + .rfn = isFIFO, + }, + .isFile = .{ + .name = "isFile", + .rfn = isFile, + }, + .isSocket = .{ + .name = "isSocket", + .rfn = isSocket, + }, + .isSymbolicLink = .{ + .name = "isSymbolicLink", + .rfn = isSymbolicLink, + }, + }, .{ + .name = .{ + .get = JSC.To.JS.Getter(DirEnt, .name), + .name = "name", + }, + }); + + pub fn finalize(this: *DirEnt) void { + _global.default_allocator.free(this.name.slice()); + _global.default_allocator.destroy(this); + } +}; + +pub const Emitter = struct { + pub const Listener = struct { + once: bool = false, + callback: JSC.JSValue, + + pub const List = struct { + pub const ArrayList = std.MultiArrayList(Listener); + list: ArrayList = ArrayList{}, + once_count: u32 = 0, + + pub fn append(this: *List, allocator: std.mem.Allocator, ctx: JSC.C.JSContextRef, listener: Listener) !void { + JSC.C.JSValueProtect(ctx, listener.callback.asObjectRef()); + try this.list.append(allocator, listener); + this.once_count +|= @as(u32, @boolToInt(listener.once)); + } + + pub fn prepend(this: *List, allocator: std.mem.Allocator, ctx: JSC.C.JSContextRef, listener: Listener) !void { + JSC.C.JSValueProtect(ctx, listener.callback.asObjectRef()); + try this.list.ensureUnusedCapacity(allocator, 1); + this.list.insertAssumeCapacity(0, listener); + this.once_count +|= @as(u32, @boolToInt(listener.once)); + } + + // removeListener() will remove, at most, one instance of a listener from the + // listener array. If any single listener has been added multiple times to the + // listener array for the specified eventName, then removeListener() must be + // called multiple times to remove each instance. + pub fn remove(this: *List, ctx: JSC.C.JSContextRef, callback: JSC.JSValue) bool { + const callbacks = this.list.items(.callback); + + for (callbacks) |item, i| { + if (callback.eqlValue(item)) { + JSC.C.JSValueUnprotect(ctx, callback.asObjectRef()); + this.once_count -|= @as(u32, @boolToInt(this.list.items(.once)[i])); + this.list.orderedRemove(i); + return true; + } + } + + return false; + } + + pub fn emit(this: *List, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) void { + var i: usize = 0; + outer: while (true) { + var slice = this.list.slice(); + var callbacks = slice.items(.callback); + var once = slice.items(.once); + while (i < callbacks.len) : (i += 1) { + const callback = callbacks[i]; + + globalThis.enqueueMicrotask1( + callback, + value, + ); + + if (once[i]) { + this.once_count -= 1; + JSC.C.JSValueUnprotect(globalThis.ref(), callback.asObjectRef()); + this.list.orderedRemove(i); + slice = this.list.slice(); + callbacks = slice.items(.callback); + once = slice.items(.once); + continue :outer; + } + } + + return; + } + } + }; + }; + + pub fn New(comptime EventType: type) type { + return struct { + const EventEmitter = @This(); + pub const Map = std.enums.EnumArray(EventType, Listener.List); + listeners: Map = Map.initFill(Listener.List{}), + + pub fn addListener(this: *EventEmitter, ctx: JSC.C.JSContextRef, event: EventType, listener: Emitter.Listener) !void { + try this.listeners.getPtr(event).append(_global.default_allocator, ctx, listener); + } + + pub fn prependListener(this: *EventEmitter, ctx: JSC.C.JSContextRef, event: EventType, listener: Emitter.Listener) !void { + try this.listeners.getPtr(event).prepend(_global.default_allocator, ctx, listener); + } + + pub fn emit(this: *EventEmitter, event: EventType, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) void { + this.listeners.getPtr(event).emit(globalThis, value); + } + + pub fn removeListener(this: *EventEmitter, ctx: JSC.C.JSContextRef, event: EventType, callback: JSC.JSValue) bool { + return this.listeners.getPtr(event).remove(ctx, callback); + } + }; + } +}; + +// pub fn Untag(comptime Union: type) type { +// const info: std.builtin.TypeInfo.Union = @typeInfo(Union); +// const tag = info.tag_type orelse @compileError("Must be tagged"); +// return struct { +// pub const Tag = tag; +// pub const Union = +// }; +// } + +pub const Stream = struct { + sink_type: Sink.Type, + sink: Sink, + content: Content, + content_type: Content.Type, + allocator: std.mem.Allocator, + + pub fn open(this: *Stream) ?JSC.Node.Syscall.Error { + switch (Syscall.open(this.content.file_path.path.sliceAssumeZ(), @enumToInt(this.content.file_path.file.flags))) { + .err => |err| { + return err.withPath(this.content.file_path.path.slice()); + }, + .result => |fd| { + this.content.file_path.file.fd = fd; + this.content.file_path.opened = true; + this.emit(.open); + return null; + }, + } + } + + pub fn getFd(this: *Stream) FileDescriptor { + return switch (this.content_type) { + .file => this.content.file.fd, + .file_path => if (comptime Environment.allow_assert) brk: { + std.debug.assert(this.content.file_path.opened); + break :brk this.content.file_path.file.fd; + } else this.content.file_path.file.fd, + else => unreachable, + }; + } + + pub fn close(this: *Stream) ?JSC.Node.Syscall.Error { + const fd = this.getFd(); + + // Don't ever close stdin, stdout, or stderr + // we are assuming that these are always 0 1 2, which is not strictly true in some cases + if (fd <= 2) { + return null; + } + + if (Syscall.close(fd)) |err| { + return err; + } + + switch (this.content_type) { + .file_path => { + this.content.file_path.opened = false; + this.content.file_path.file.fd = std.math.maxInt(FileDescriptor); + }, + .file => { + this.content.file.fd = std.math.maxInt(FileDescriptor); + }, + else => {}, + } + + this.emit(.Close); + } + + const CommonEvent = enum { Error, Open, Close }; + pub fn emit(this: *Stream, comptime event: CommonEvent) void { + switch (this.sink_type) { + .readable => { + switch (comptime event) { + .Open => this.sink.readable.emit(.Open), + .Close => this.sink.readable.emit(.Close), + else => unreachable, + } + }, + .writable => { + switch (comptime event) { + .Open => this.sink.writable.emit(.Open), + .Close => this.sink.writable.emit(.Close), + else => unreachable, + } + }, + } + } + + // This allocates a new stream object + pub fn toJS(this: *Stream, ctx: JSC.C.JSContextRef, _: JSC.C.ExceptionRef) JSC.C.JSValueRef { + switch (this.sink_type) { + .readable => { + var readable = &this.sink.readable.state; + return readable.create( + ctx.ptr(), + ).asObjectRef(); + }, + .writable => { + var writable = &this.sink.writable.state; + return writable.create( + ctx.ptr(), + ).asObjectRef(); + }, + } + } + + pub fn deinit(this: *Stream) void { + this.allocator.destroy(this); + } + + pub const Sink = union { + readable: Readable, + writable: Writable, + + pub const Type = enum(u8) { + readable, + writable, + }; + }; + + pub const Consumed = u52; + + const Response = struct { + bytes: [8]u8 = std.mem.zeroes([8]u8), + }; + + const Error = union(Type) { + Syscall: Syscall.Error, + JavaScript: JSC.JSValue, + Internal: anyerror, + + pub const Type = enum { + Syscall, + JavaScript, + Internal, + }; + }; + + pub const Content = union { + file: File, + file_path: FilePath, + socket: Socket, + buffer: *Buffer, + stream: *Stream, + javascript: JSC.JSValue, + + pub fn getFile(this: *Content, content_type: Content.Type) *File { + return switch (content_type) { + .file => &this.file, + .file_path => &this.file_path.file, + else => unreachable, + }; + } + + pub const File = struct { + fd: FileDescriptor, + flags: FileSystemFlags, + mode: Mode, + size: Consumed = std.math.maxInt(Consumed), + + // pub fn read(this: *File, comptime chunk_type: Content.Type, chunk: Source.Type.of(chunk_type)) Response {} + + pub inline fn setPermissions(this: File) meta.ReturnOf(Syscall.fchmod) { + return Syscall.fchmod(this.fd, this.mode); + } + }; + + pub const FilePath = struct { + path: PathString, + auto_close: bool = false, + file: File = File{ .fd = std.math.maxInt(FileDescriptor), .mode = 0o666, .flags = FileSystemFlags.@"r" }, + opened: bool = false, + + // pub fn read(this: *File, comptime chunk_type: Content.Type, chunk: Source.Type.of(chunk_type)) Response {} + }; + + pub const Socket = struct { + fd: FileDescriptor, + flags: FileSystemFlags, + + // pub fn write(this: *File, comptime chunk_type: Source.Type, chunk: Source.Type.of(chunk_type)) Response {} + // pub fn read(this: *File, comptime chunk_type: Source.Type, chunk: Source.Type.of(chunk_type)) Response {} + }; + + pub const Type = enum(u8) { + file, + file_path, + socket, + buffer, + stream, + javascript, + }; + }; +}; + +pub const Writable = struct { + state: State = State{}, + emitter: EventEmitter = EventEmitter{}, + + connection: ?*Stream = null, + globalObject: ?*JSC.JSGlobalObject = null, + + // workaround https://github.com/ziglang/zig/issues/6611 + stream: *Stream = undefined, + pipeline: Pipeline = Pipeline{}, + started: bool = false, + + pub const Chunk = struct { + data: StringOrBuffer, + encoding: Encoding = Encoding.utf8, + }; + + pub const Pipe = struct { + source: *Stream, + destination: *Stream, + chunk: ?*Chunk = null, + // Might be the end of the stream + // or it might just be another stream + next: ?*Pipe = null, + + pub fn start(this: *Pipe, pipeline: *Pipeline, chunk: ?*Chunk) void { + this.run(pipeline, chunk, null); + } + + var disable_clonefile = false; + + fn runCloneFileWithFallback(pipeline: *Pipeline, source: *Stream.Content, destination: *Stream.Content) void { + switch (Syscall.clonefile(source.path.sliceAssumeZ(), destination.path.sliceAssumeZ())) { + .result => return, + .err => |err| { + switch (err.getErrno()) { + // these are retryable + .ENOTSUP, .EXDEV, .EXIST, .EIO, .ENOTDIR => |call| { + if (call == .ENOTSUP) { + disable_clonefile = true; + } + + return runCopyfile( + false, + pipeline, + source, + .file_path, + destination, + .file_path, + ); + }, + else => { + pipeline.err = err; + return; + }, + } + }, + } + } + + fn runCopyfile( + must_open_files: bool, + pipeline: *Pipeline, + source: *Stream.Content, + source_type: Stream.Content.Type, + destination: *Stream.Content, + destination_type: Stream.Content.Type, + is_end: bool, + ) void { + do_the_work: { + // fallback-only + if (destination_type == .file_path and source_type == .file_path and !destination.file_path.opened and !must_open_files) { + switch (Syscall.copyfile(source.path.sliceAssumeZ(), destination.path.sliceAssumeZ(), 0)) { + .err => |err| { + pipeline.err = err; + + return; + }, + .result => break :do_the_work, + } + } + + defer { + if (source_type == .file_path and source.file_path.auto_close and source.file_path.opened) { + if (source.stream.close()) |err| { + if (pipeline.err == null) { + pipeline.err = err; + } + } + } + + if (is_end and destination_type == .file_path and destination.file_path.auto_close and destination.file_path.opened) { + if (destination.stream.close()) |err| { + if (pipeline.err == null) { + pipeline.err = err; + } + } + } + } + + if (source_type == .file_path and !source.file_path.opened) { + if (source.stream.open()) |err| { + pipeline.err = err; + return; + } + } + + const source_fd = if (source_type == .file_path) + source.file_path.file.fd + else + source.file.fd; + + if (destination == .file_path and !destination.file_path.opened) { + if (destination.stream.open()) |err| { + pipeline.err = err; + return; + } + } + + const dest_fd = if (destination_type == .file_path) + destination.file_path.file.fd + else + destination.file.fd; + + switch (Syscall.fcopyfile(source_fd, dest_fd, 0)) { + .err => |err| { + pipeline.err = err; + return; + }, + .result => break :do_the_work, + } + } + + switch (destination.getFile(destination_type).setPermissions()) { + .err => |err| { + destination.stream.emitError(err); + pipeline.err = err; + return; + }, + .result => return, + } + } + + pub fn run(this: *Pipe, pipeline: *Pipeline) void { + var source = this.source; + var destination = this.destination; + const source_content_type = source.content_type; + const destination_content_type = destination.content_type; + + if (pipeline.err != null) return; + + switch (FastPath.get( + source_content_type, + destination_content_type, + pipeline.head == this, + pipeline.tail == this, + )) { + .clonefile => { + if (comptime !Environment.isMac) unreachable; + if (destination.content.file_path.opened) { + runCopyfile( + // Can we skip sending a .open event? + (!source.content.file_path.auto_close and !source.content.file_path.opened) or (!destination.content.file_path.auto_close and !destination.content.file_path.opened), + pipeline, + &source.content, + .file_path, + &destination.content, + .file_path, + this.next == null, + ); + } else { + runCloneFileWithFallback(pipeline, source.content.file_path, destination.content.file_path); + } + }, + .copyfile => { + if (comptime !Environment.isMac) unreachable; + runCopyfile( + // Can we skip sending a .open event? + (!source.content.file_path.auto_close and !source.content.file_path.opened) or (!destination.content.file_path.auto_close and !destination.content.file_path.opened), + pipeline, + &source.content, + source_content_type, + &destination.content, + destination_content_type, + this.next == null, + ); + }, + else => {}, + } + } + + pub const FastPath = enum { + none, + clonefile, + sendfile, + copyfile, + copy_file_range, + + pub fn get(source: Stream.Content.Type, destination: Stream.Content.Type, is_head: bool, is_tail: bool) FastPath { + _ = is_tail; + if (comptime Environment.isMac) { + if (is_head) { + if (source == .file_path and destination == .file_path and !disable_clonefile) + return .clonefile; + + if ((source == .file or source == .file_path) and (destination == .file or destination == .file_path)) { + return .copyfile; + } + } + } + + return FastPath.none; + } + }; + }; + + pub const Pipeline = struct { + head: ?*Pipe = null, + tail: ?*Pipe = null, + + // Preallocate a single pipe so that + preallocated_tail_pipe: Pipe = undefined, + + /// Does the data exit at any point to JavaScript? + closed_loop: bool = true, + + // If there is a pending error, this is the error + err: ?Syscall.Error = null, + + pub const StartTask = struct { + writable: *Writable, + pub fn run(this: *StartTask) void { + var writable = this.writable; + var head = writable.pipeline.head orelse return; + if (writable.started) { + return; + } + writable.started = true; + + head.start(&writable.pipeline, null); + } + }; + }; + + pub fn appendReadable(this: *Writable, readable: *Stream) void { + if (comptime Environment.allow_assert) { + std.debug.assert(readable.sink_type == .readable); + } + + if (this.pipeline.tail == null) { + this.pipeline.head = &this.pipeline.preallocated_tail_pipe; + this.pipeline.head.?.* = Pipe{ + .destination = this.stream, + .source = readable, + }; + this.pipeline.tail = this.pipeline.head; + return; + } + + var pipe = readable.allocator.create(Pipe) catch unreachable; + pipe.* = Pipe{ + .source = readable, + .destination = this.stream, + }; + this.pipeline.tail.?.next = pipe; + this.pipeline.tail = pipe; + } + + pub const EventEmitter = Emitter.New(Events); + + pub fn emit(this: *Writable, event: Events, value: JSC.JSValue) void { + if (this.shouldSkipEvent(event)) return; + + this.emitter.emit(event, this.globalObject.?, value); + } + + pub inline fn shouldEmitEvent(this: *const Writable, event: Events) bool { + return switch (event) { + .Close => this.state.emit_close and this.emitter.listeners.get(.Close).list.len > 0, + .Drain => this.emitter.listeners.get(.Drain).list.len > 0, + .Error => this.emitter.listeners.get(.Error).list.len > 0, + .Finish => this.emitter.listeners.get(.Finish).list.len > 0, + .Pipe => this.emitter.listeners.get(.Pipe).list.len > 0, + .Unpipe => this.emitter.listeners.get(.Unpipe).list.len > 0, + .Open => this.emitter.listeners.get(.Open).list.len > 0, + }; + } + + pub const State = extern struct { + highwater_mark: u32 = 256_000, + encoding: Encoding = Encoding.utf8, + start: i32 = 0, + destroyed: bool = false, + ended: bool = false, + corked: bool = false, + finished: bool = false, + emit_close: bool = true, + + pub fn deinit(state: *State) callconv(.C) void { + if (comptime is_bindgen) return; + + var stream = state.getStream(); + stream.deinit(); + } + + pub fn create(state: *State, globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { + return shim.cppFn("create", .{ state, globalObject }); + } + + // i know. + pub inline fn getStream(state: *State) *Stream { + return getWritable(state).stream; + } + + pub inline fn getWritable(state: *State) *Writable { + return @fieldParentPtr(Writable, "state", state); + } + + pub fn addEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var writable = state.getWritable(); + writable.emitter.addListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn removeEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue) callconv(.C) bool { + if (comptime is_bindgen) return true; + var writable = state.getWritable(); + return writable.emitter.removeListener(global.ref(), event, callback); + } + + pub fn prependEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var writable = state.getWritable(); + writable.emitter.prependListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn write(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn end(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn close(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn destroy(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn cork(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + pub fn uncork(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub const Flowing = enum(u8) { + pending, + yes, + paused, + }; + + pub const shim = Shimmer("Bun", "Writable", @This()); + pub const name = "Bun__Writable"; + pub const include = "BunStream.h"; + pub const namespace = shim.namespace; + + pub const Export = shim.exportFunctions(.{ + .@"deinit" = deinit, + .@"addEventListener" = addEventListener, + .@"removeEventListener" = removeEventListener, + .@"prependEventListener" = prependEventListener, + .@"write" = write, + .@"end" = end, + .@"close" = close, + .@"destroy" = destroy, + .@"cork" = cork, + .@"uncork" = uncork, + }); + + pub const Extern = [_][]const u8{"create"}; + + comptime { + if (!is_bindgen) { + @export(deinit, .{ .name = Export[0].symbol_name }); + @export(addEventListener, .{ .name = Export[1].symbol_name }); + @export(removeEventListener, .{ .name = Export[2].symbol_name }); + @export(prependEventListener, .{ .name = Export[3].symbol_name }); + @export(write, .{ .name = Export[4].symbol_name }); + @export(end, .{ .name = Export[5].symbol_name }); + @export(close, .{ .name = Export[6].symbol_name }); + @export(destroy, .{ .name = Export[7].symbol_name }); + @export(cork, .{ .name = Export[8].symbol_name }); + @export(uncork, .{ .name = Export[9].symbol_name }); + } + } + }; + + pub const Events = enum(u8) { + Close, + Drain, + Error, + Finish, + Pipe, + Unpipe, + Open, + + pub const name = "WritableEvent"; + }; +}; + +pub const Readable = struct { + state: State = State{}, + emitter: EventEmitter = EventEmitter{}, + stream: *Stream = undefined, + destination: ?*Writable = null, + globalObject: ?*JSC.JSGlobalObject = null, + + pub const EventEmitter = Emitter.New(Events); + + pub fn emit(this: *Readable, event: Events, comptime ValueType: type, value: JSC.JSValue) void { + _ = ValueType; + if (this.shouldEmitEvent(event)) return; + + this.emitter.emit(event, this.globalObject.?, value); + } + + pub fn shouldEmitEvent(this: *Readable, event: Events) bool { + return switch (event) { + .Close => this.state.emit_close and this.emitter.listeners.get(.Close).list.len > 0, + .Data => this.emitter.listeners.get(.Data).list.len > 0, + .End => this.state.emit_end and this.emitter.listeners.get(.End).list.len > 0, + .Error => this.emitter.listeners.get(.Error).list.len > 0, + .Pause => this.emitter.listeners.get(.Pause).list.len > 0, + .Readable => this.emitter.listeners.get(.Readable).list.len > 0, + .Resume => this.emitter.listeners.get(.Resume).list.len > 0, + .Open => this.emitter.listeners.get(.Open).list.len > 0, + }; + } + + pub const Events = enum(u8) { + Close, + Data, + End, + Error, + Pause, + Readable, + Resume, + Open, + + pub const name = "ReadableEvent"; + }; + + // This struct is exposed to JavaScript + pub const State = extern struct { + highwater_mark: u32 = 256_000, + encoding: Encoding = Encoding.utf8, + + start: i32 = 0, + end: i32 = std.math.maxInt(i32), + + readable: bool = false, + aborted: bool = false, + did_read: bool = false, + ended: bool = false, + flowing: Flowing = Flowing.pending, + + emit_close: bool = true, + emit_end: bool = true, + + // i know. + pub inline fn getStream(state: *State) *Stream { + return getReadable(state).stream; + } + + pub inline fn getReadable(state: *State) *Readable { + return @fieldParentPtr(Readable, "state", state); + } + + pub const Flowing = enum(u8) { + pending, + yes, + paused, + }; + + pub const shim = Shimmer("Bun", "Readable", @This()); + pub const name = "Bun__Readable"; + pub const include = "BunStream.h"; + pub const namespace = shim.namespace; + + pub fn create( + state: *State, + globalObject: *JSC.JSGlobalObject, + ) callconv(.C) JSC.JSValue { + return shim.cppFn("create", .{ state, globalObject }); + } + + pub fn deinit(state: *State) callconv(.C) void { + if (comptime is_bindgen) return; + var stream = state.getStream(); + stream.deinit(); + } + + pub fn addEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var readable = state.getReadable(); + + readable.emitter.addListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn removeEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue) callconv(.C) bool { + if (comptime is_bindgen) return true; + var readable = state.getReadable(); + return readable.emitter.removeListener(global.ref(), event, callback); + } + + pub fn prependEventListener(state: *State, global: *JSC.JSGlobalObject, event: Events, callback: JSC.JSValue, is_once: bool) callconv(.C) void { + if (comptime is_bindgen) return; + var readable = state.getReadable(); + readable.emitter.prependListener(global.ref(), event, .{ + .once = is_once, + .callback = callback, + }) catch unreachable; + } + + pub fn pipe(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + if (len < 1) { + return JSC.toInvalidArguments("Writable is required", .{}, global.ref()); + } + const args: []const JSC.JSValue = args_ptr[0..len]; + var writable_state: *Writable.State = args[0].getWritableStreamState(global.vm()) orelse { + return JSC.toInvalidArguments("Expected Writable but didn't receive it", .{}, global.ref()); + }; + writable_state.getWritable().appendReadable(state.getStream()); + return JSC.JSValue.jsUndefined(); + } + + pub fn unpipe(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn unshift(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn read(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn pause(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub fn @"resume"(state: *State, global: *JSC.JSGlobalObject, args_ptr: [*]const JSC.JSValue, len: u16) callconv(.C) JSC.JSValue { + if (comptime is_bindgen) return JSC.JSValue.jsUndefined(); + _ = state; + _ = global; + _ = args_ptr; + _ = len; + + return JSC.JSValue.jsUndefined(); + } + + pub const Export = shim.exportFunctions(.{ + .@"deinit" = deinit, + .@"addEventListener" = addEventListener, + .@"removeEventListener" = removeEventListener, + .@"prependEventListener" = prependEventListener, + .@"pipe" = pipe, + .@"unpipe" = unpipe, + .@"unshift" = unshift, + .@"read" = read, + .@"pause" = pause, + .@"resume" = State.@"resume", + }); + + pub const Extern = [_][]const u8{"create"}; + + comptime { + if (!is_bindgen) { + @export(deinit, .{ + .name = Export[0].symbol_name, + }); + @export(addEventListener, .{ + .name = Export[1].symbol_name, + }); + @export(removeEventListener, .{ + .name = Export[2].symbol_name, + }); + @export(prependEventListener, .{ + .name = Export[3].symbol_name, + }); + @export( + pipe, + .{ .name = Export[4].symbol_name }, + ); + @export( + unpipe, + .{ .name = Export[5].symbol_name }, + ); + @export( + unshift, + .{ .name = Export[6].symbol_name }, + ); + @export( + read, + .{ .name = Export[7].symbol_name }, + ); + @export( + pause, + .{ .name = Export[8].symbol_name }, + ); + @export( + State.@"resume", + .{ .name = Export[9].symbol_name }, + ); + } + } + }; +}; + +pub const Process = struct { + pub fn getArgv(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { + if (JSC.VirtualMachine.vm.argv.len == 0) + return JSC.JSValue.createStringArray(globalObject, null, 0, false); + + // Allocate up to 32 strings in stack + var stack_fallback_allocator = std.heap.stackFallback( + 32 * @sizeOf(JSC.ZigString), + heap_allocator, + ); + var allocator = stack_fallback_allocator.get(); + + // If it was launched with bun run or bun test, skip it + var skip: usize = 0; + if (JSC.VirtualMachine.vm.argv.len > 1 and (strings.eqlComptime(JSC.VirtualMachine.vm.argv[0], "run") or strings.eqlComptime(JSC.VirtualMachine.vm.argv[0], "test"))) { + skip += 1; + } + const count = JSC.VirtualMachine.vm.argv.len + 1; + var args = allocator.alloc( + JSC.ZigString, + count - skip, + ) catch unreachable; + defer allocator.free(args); + + // https://github.com/yargs/yargs/blob/adb0d11e02c613af3d9427b3028cc192703a3869/lib/utils/process-argv.ts#L1 + args[0] = JSC.ZigString.init(std.mem.span(std.os.argv[0])); + + if (JSC.VirtualMachine.vm.argv.len > skip) { + for (JSC.VirtualMachine.vm.argv[skip..]) |arg, i| { + args[i + 1] = JSC.ZigString.init(arg); + args[i + 1].detectEncoding(); + } + } + + return JSC.JSValue.createStringArray(globalObject, args.ptr, args.len, true); + } + + pub fn getCwd(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { + var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; + switch (Syscall.getcwd(&buffer)) { + .err => |err| { + return err.toJSC(globalObject); + }, + .result => |result| { + var zig_str = JSC.ZigString.init(result); + zig_str.detectEncoding(); + + const value = zig_str.toValueGC(globalObject); + + return value; + }, + } + } + pub fn setCwd(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) callconv(.C) JSC.JSValue { + if (to.len == 0) { + return JSC.toInvalidArguments("path is required", .{}, globalObject.ref()); + } + + var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; + const slice = to.sliceZBuf(&buf) catch { + return JSC.toInvalidArguments("Invalid path", .{}, globalObject.ref()); + }; + const result = Syscall.chdir(slice); + + switch (result) { + .err => |err| { + return err.toJSC(globalObject); + }, + .result => { + // When we update the cwd from JS, we have to update the bundler's version as well + // However, this might be called many times in a row, so we use a pre-allocated buffer + // that way we don't have to worry about garbage collector + var trimmed = std.mem.trimRight(u8, buf[0..slice.len], std.fs.path.sep_str); + buf[trimmed.len] = std.fs.path.sep; + const with_trailing_slash = buf[0 .. trimmed.len + 1]; + std.mem.copy(u8, &JSC.VirtualMachine.vm.bundler.fs.top_level_dir_buf, with_trailing_slash); + JSC.VirtualMachine.vm.bundler.fs.top_level_dir = JSC.VirtualMachine.vm.bundler.fs.top_level_dir_buf[0..with_trailing_slash.len]; + return JSC.JSValue.jsUndefined(); + }, + } + } + + pub export const Bun__version: [:0]const u8 = "v" ++ _global.Global.package_json_version; + pub export const Bun__versions_mimalloc: [:0]const u8 = _global.Global.versions.mimalloc; + pub export const Bun__versions_webkit: [:0]const u8 = _global.Global.versions.webkit; + pub export const Bun__versions_libarchive: [:0]const u8 = _global.Global.versions.libarchive; + pub export const Bun__versions_picohttpparser: [:0]const u8 = _global.Global.versions.picohttpparser; + pub export const Bun__versions_boringssl: [:0]const u8 = _global.Global.versions.boringssl; + pub export const Bun__versions_zlib: [:0]const u8 = _global.Global.versions.zlib; + pub export const Bun__versions_zig: [:0]const u8 = _global.Global.versions.zig; +}; + +comptime { + std.testing.refAllDecls(Process); + std.testing.refAllDecls(Stream); + std.testing.refAllDecls(Readable); + std.testing.refAllDecls(Writable); + std.testing.refAllDecls(Writable.State); + std.testing.refAllDecls(Readable.State); +} diff --git a/src/javascript/jsc/test/jest.zig b/src/javascript/jsc/test/jest.zig new file mode 100644 index 000000000..1398e9058 --- /dev/null +++ b/src/javascript/jsc/test/jest.zig @@ -0,0 +1,814 @@ +const std = @import("std"); +const Api = @import("../../../api/schema.zig").Api; +const RequestContext = @import("../../../http.zig").RequestContext; +const MimeType = @import("../../../http.zig").MimeType; +const ZigURL = @import("../../../query_string_map.zig").URL; +const HTTPClient = @import("http"); +const NetworkThread = HTTPClient.NetworkThread; + +const JSC = @import("../../../jsc.zig"); +const js = JSC.C; + +const logger = @import("../../../logger.zig"); +const Method = @import("../../../http/method.zig").Method; + +const ObjectPool = @import("../../../pool.zig").ObjectPool; + +const Output = @import("../../../global.zig").Output; +const MutableString = @import("../../../global.zig").MutableString; +const strings = @import("../../../global.zig").strings; +const string = @import("../../../global.zig").string; +const default_allocator = @import("../../../global.zig").default_allocator; +const FeatureFlags = @import("../../../global.zig").FeatureFlags; +const ArrayBuffer = @import("../base.zig").ArrayBuffer; +const Properties = @import("../base.zig").Properties; +const NewClass = @import("../base.zig").NewClass; +const d = @import("../base.zig").d; +const castObj = @import("../base.zig").castObj; +const getAllocator = @import("../base.zig").getAllocator; +const JSPrivateDataPtr = @import("../base.zig").JSPrivateDataPtr; +const GetJSPrivateData = @import("../base.zig").GetJSPrivateData; + +const ZigString = JSC.ZigString; +const JSInternalPromise = JSC.JSInternalPromise; +const JSPromise = JSC.JSPromise; +const JSValue = JSC.JSValue; +const JSError = JSC.JSError; +const JSGlobalObject = JSC.JSGlobalObject; + +const VirtualMachine = @import("../javascript.zig").VirtualMachine; +const Task = @import("../javascript.zig").Task; + +const Fs = @import("../../../fs.zig"); + +fn notImplementedFn(_: *anyopaque, ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, _: []const js.JSValueRef, exception: js.ExceptionRef) js.JSValueRef { + JSError(getAllocator(ctx), "Not implemented yet!", .{}, ctx, exception); + return null; +} + +fn notImplementedProp( + _: anytype, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSStringRef, + exception: js.ExceptionRef, +) js.JSValueRef { + JSError(getAllocator(ctx), "Property not implemented yet!", .{}, ctx, exception); + return null; +} + +const ArrayIdentityContext = @import("../../../identity_context.zig").ArrayIdentityContext; +pub const TestRunner = struct { + tests: TestRunner.Test.List = .{}, + log: *logger.Log, + files: File.List = .{}, + index: File.Map = File.Map{}, + + timeout_seconds: f64 = 5.0, + + allocator: std.mem.Allocator, + callback: *Callback = undefined, + + pub const Callback = struct { + pub const OnUpdateCount = fn (this: *Callback, delta: u32, total: u32) void; + pub const OnTestStart = fn (this: *Callback, test_id: Test.ID) void; + pub const OnTestPass = fn (this: *Callback, test_id: Test.ID, expectations: u32) void; + pub const OnTestFail = fn (this: *Callback, test_id: Test.ID, file: string, label: string, expectations: u32) void; + onUpdateCount: OnUpdateCount, + onTestStart: OnTestStart, + onTestPass: OnTestPass, + onTestFail: OnTestFail, + }; + + pub fn reportPass(this: *TestRunner, test_id: Test.ID, expectations: u32) void { + this.tests.items(.status)[test_id] = .pass; + this.callback.onTestPass(this.callback, test_id, expectations); + } + pub fn reportFailure(this: *TestRunner, test_id: Test.ID, file: string, label: string, expectations: u32) void { + this.tests.items(.status)[test_id] = .fail; + this.callback.onTestFail(this.callback, test_id, file, label, expectations); + } + + pub fn addTestCount(this: *TestRunner, count: u32) u32 { + this.tests.ensureUnusedCapacity(this.allocator, count) catch unreachable; + const start = @truncate(Test.ID, this.tests.len); + this.tests.len += count; + var statuses = this.tests.items(.status)[start..][0..count]; + std.mem.set(Test.Status, statuses, Test.Status.pending); + this.callback.onUpdateCount(this.callback, count, count + start); + return start; + } + + pub fn getOrPutFile(this: *TestRunner, file_path: string) *DescribeScope { + var entry = this.index.getOrPut(this.allocator, @truncate(u32, std.hash.Wyhash.hash(0, file_path))) catch unreachable; + if (entry.found_existing) { + return this.files.items(.module_scope)[entry.value_ptr.*]; + } + var scope = this.allocator.create(DescribeScope) catch unreachable; + const file_id = @truncate(File.ID, this.files.len); + scope.* = DescribeScope{ + .file_id = file_id, + .test_id_start = @truncate(Test.ID, this.tests.len), + }; + this.files.append(this.allocator, .{ .module_scope = scope, .source = logger.Source.initEmptyFile(file_path) }) catch unreachable; + entry.value_ptr.* = file_id; + return scope; + } + + pub const File = struct { + source: logger.Source = logger.Source.initEmptyFile(""), + log: logger.Log = logger.Log.init(default_allocator), + module_scope: *DescribeScope = undefined, + + pub const List = std.MultiArrayList(File); + pub const ID = u32; + pub const Map = std.ArrayHashMapUnmanaged(u32, u32, ArrayIdentityContext, false); + }; + + pub const Test = struct { + status: Status = Status.pending, + + pub const ID = u32; + pub const List = std.MultiArrayList(Test); + + pub const Status = enum(u3) { + pending, + pass, + fail, + }; + }; +}; + +pub const Jest = struct { + pub var runner: ?*TestRunner = null; + + pub fn call( + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSValueRef { + var runner_ = runner orelse { + JSError(getAllocator(ctx), "Run bun test to run a test", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + }; + + if (arguments.len < 1 or !js.JSValueIsString(ctx, arguments[0])) { + JSError(getAllocator(ctx), "Bun.jest() expects a string filename", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + var str = js.JSValueToStringCopy(ctx, arguments[0], exception); + defer js.JSStringRelease(str); + var ptr = js.JSStringGetCharacters8Ptr(str); + const len = js.JSStringGetLength(str); + if (len == 0 or ptr[0] != '/') { + JSError(getAllocator(ctx), "Bun.jest() expects an absolute file path", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + var str_value = ptr[0..len]; + var filepath = Fs.FileSystem.instance.filename_store.append([]const u8, str_value) catch unreachable; + + var scope = runner_.getOrPutFile(filepath); + DescribeScope.active = scope; + + return DescribeScope.Class.make(ctx, scope); + } +}; + +/// https://jestjs.io/docs/expect +// To support async tests, we need to track the test ID +pub const Expect = struct { + test_id: TestRunner.Test.ID, + scope: *DescribeScope, + value: js.JSValueRef, + op: Op.Set = Op.Set.init(.{}), + + pub const Op = enum(u3) { + resolves, + rejects, + not, + pub const Set = std.EnumSet(Op); + }; + + pub fn finalize( + this: *Expect, + ) void { + js.JSValueUnprotect(VirtualMachine.vm.global.ref(), this.value); + VirtualMachine.vm.allocator.destroy(this); + } + + pub const Class = NewClass( + Expect, + .{ .name = "Expect" }, + .{ + .toBe = .{ + .rfn = Expect.toBe, + .name = "toBe", + }, + .toHaveBeenCalledTimes = .{ + .rfn = Expect.toHaveBeenCalledTimes, + .name = "toHaveBeenCalledTimes", + }, + .finalize = .{ .rfn = Expect.finalize, .name = "finalize" }, + .toHaveBeenCalledWith = .{ + .rfn = Expect.toHaveBeenCalledWith, + .name = "toHaveBeenCalledWith", + }, + .toHaveBeenLastCalledWith = .{ + .rfn = Expect.toHaveBeenLastCalledWith, + .name = "toHaveBeenLastCalledWith", + }, + .toHaveBeenNthCalledWith = .{ + .rfn = Expect.toHaveBeenNthCalledWith, + .name = "toHaveBeenNthCalledWith", + }, + .toHaveReturnedTimes = .{ + .rfn = Expect.toHaveReturnedTimes, + .name = "toHaveReturnedTimes", + }, + .toHaveReturnedWith = .{ + .rfn = Expect.toHaveReturnedWith, + .name = "toHaveReturnedWith", + }, + .toHaveLastReturnedWith = .{ + .rfn = Expect.toHaveLastReturnedWith, + .name = "toHaveLastReturnedWith", + }, + .toHaveNthReturnedWith = .{ + .rfn = Expect.toHaveNthReturnedWith, + .name = "toHaveNthReturnedWith", + }, + .toHaveLength = .{ + .rfn = Expect.toHaveLength, + .name = "toHaveLength", + }, + .toHaveProperty = .{ + .rfn = Expect.toHaveProperty, + .name = "toHaveProperty", + }, + .toBeCloseTo = .{ + .rfn = Expect.toBeCloseTo, + .name = "toBeCloseTo", + }, + .toBeGreaterThan = .{ + .rfn = Expect.toBeGreaterThan, + .name = "toBeGreaterThan", + }, + .toBeGreaterThanOrEqual = .{ + .rfn = Expect.toBeGreaterThanOrEqual, + .name = "toBeGreaterThanOrEqual", + }, + .toBeLessThan = .{ + .rfn = Expect.toBeLessThan, + .name = "toBeLessThan", + }, + .toBeLessThanOrEqual = .{ + .rfn = Expect.toBeLessThanOrEqual, + .name = "toBeLessThanOrEqual", + }, + .toBeInstanceOf = .{ + .rfn = Expect.toBeInstanceOf, + .name = "toBeInstanceOf", + }, + .toContain = .{ + .rfn = Expect.toContain, + .name = "toContain", + }, + .toContainEqual = .{ + .rfn = Expect.toContainEqual, + .name = "toContainEqual", + }, + .toEqual = .{ + .rfn = Expect.toEqual, + .name = "toEqual", + }, + .toMatch = .{ + .rfn = Expect.toMatch, + .name = "toMatch", + }, + .toMatchObject = .{ + .rfn = Expect.toMatchObject, + .name = "toMatchObject", + }, + .toMatchSnapshot = .{ + .rfn = Expect.toMatchSnapshot, + .name = "toMatchSnapshot", + }, + .toMatchInlineSnapshot = .{ + .rfn = Expect.toMatchInlineSnapshot, + .name = "toMatchInlineSnapshot", + }, + .toStrictEqual = .{ + .rfn = Expect.toStrictEqual, + .name = "toStrictEqual", + }, + .toThrow = .{ + .rfn = Expect.toThrow, + .name = "toThrow", + }, + .toThrowErrorMatchingSnapshot = .{ + .rfn = Expect.toThrowErrorMatchingSnapshot, + .name = "toThrowErrorMatchingSnapshot", + }, + .toThrowErrorMatchingInlineSnapshot = .{ + .rfn = Expect.toThrowErrorMatchingInlineSnapshot, + .name = "toThrowErrorMatchingInlineSnapshot", + }, + }, + .{ + .not = .{ + .get = Expect.not, + .name = "not", + }, + .resolves = .{ + .get = Expect.resolves, + .name = "resolves", + }, + .rejects = .{ + .get = Expect.rejects, + .name = "rejects", + }, + }, + ); + + /// Object.is() + pub fn toBe( + this: *Expect, + ctx: js.JSContextRef, + _: js.JSObjectRef, + thisObject: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSValueRef { + if (arguments.len != 1) { + JSC.JSError( + getAllocator(ctx), + ".toBe() takes 1 argument", + .{}, + ctx, + exception, + ); + return js.JSValueMakeUndefined(ctx); + } + this.scope.tests.items[this.test_id].counter.actual += 1; + if (!JSValue.fromRef(arguments[0]).isSameValue(JSValue.fromRef(this.value), ctx.ptr())) { + JSC.JSError( + getAllocator(ctx), + "fail", + .{}, + ctx, + exception, + ); + return null; + } + return thisObject; + } + pub const toHaveBeenCalledTimes = notImplementedFn; + pub const toHaveBeenCalledWith = notImplementedFn; + pub const toHaveBeenLastCalledWith = notImplementedFn; + pub const toHaveBeenNthCalledWith = notImplementedFn; + pub const toHaveReturnedTimes = notImplementedFn; + pub const toHaveReturnedWith = notImplementedFn; + pub const toHaveLastReturnedWith = notImplementedFn; + pub const toHaveNthReturnedWith = notImplementedFn; + pub const toHaveLength = notImplementedFn; + pub const toHaveProperty = notImplementedFn; + pub const toBeCloseTo = notImplementedFn; + pub const toBeGreaterThan = notImplementedFn; + pub const toBeGreaterThanOrEqual = notImplementedFn; + pub const toBeLessThan = notImplementedFn; + pub const toBeLessThanOrEqual = notImplementedFn; + pub const toBeInstanceOf = notImplementedFn; + pub const toContain = notImplementedFn; + pub const toContainEqual = notImplementedFn; + pub const toEqual = notImplementedFn; + pub const toMatch = notImplementedFn; + pub const toMatchObject = notImplementedFn; + pub const toMatchSnapshot = notImplementedFn; + pub const toMatchInlineSnapshot = notImplementedFn; + pub const toStrictEqual = notImplementedFn; + pub const toThrow = notImplementedFn; + pub const toThrowErrorMatchingSnapshot = notImplementedFn; + pub const toThrowErrorMatchingInlineSnapshot = notImplementedFn; + + pub const not = notImplementedProp; + pub const resolves = notImplementedProp; + pub const rejects = notImplementedProp; +}; + +pub const ExpectPrototype = struct { + scope: *DescribeScope, + test_id: TestRunner.Test.ID, + op: Expect.Op.Set = Expect.Op.Set.init(.{}), + + pub const Class = NewClass( + ExpectPrototype, + .{ + .name = "ExpectPrototype", + .read_only = true, + }, + .{ + .call = .{ + .rfn = ExpectPrototype.call, + }, + .extend = .{ + .name = "extend", + .rfn = ExpectPrototype.extend, + }, + .anything = .{ + .name = "anything", + .rfn = ExpectPrototype.anything, + }, + .any = .{ + .name = "any", + .rfn = ExpectPrototype.any, + }, + .arrayContaining = .{ + .name = "arrayContaining", + .rfn = ExpectPrototype.arrayContaining, + }, + .assertions = .{ + .name = "assertions", + .rfn = ExpectPrototype.assertions, + }, + .hasAssertions = .{ + .name = "hasAssertions", + .rfn = ExpectPrototype.hasAssertions, + }, + .objectContaining = .{ + .name = "objectContaining", + .rfn = ExpectPrototype.objectContaining, + }, + .stringContaining = .{ + .name = "stringContaining", + .rfn = ExpectPrototype.stringContaining, + }, + .stringMatching = .{ + .name = "stringMatching", + .rfn = ExpectPrototype.stringMatching, + }, + .addSnapshotSerializer = .{ + .name = "addSnapshotSerializer", + .rfn = ExpectPrototype.addSnapshotSerializer, + }, + }, + .{ + .not = .{ + .name = "not", + .get = ExpectPrototype.not, + }, + .resolves = .{ + .name = "resolves", + .get = ExpectPrototype.resolves, + }, + .rejects = .{ + .name = "rejects", + .get = ExpectPrototype.rejects, + }, + }, + ); + pub const extend = notImplementedFn; + pub const anything = notImplementedFn; + pub const any = notImplementedFn; + pub const arrayContaining = notImplementedFn; + pub const assertions = notImplementedFn; + pub const hasAssertions = notImplementedFn; + pub const objectContaining = notImplementedFn; + pub const stringContaining = notImplementedFn; + pub const stringMatching = notImplementedFn; + pub const addSnapshotSerializer = notImplementedFn; + pub const not = notImplementedProp; + pub const resolves = notImplementedProp; + pub const rejects = notImplementedProp; + + pub fn call( + _: *ExpectPrototype, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSObjectRef { + if (arguments.len != 1) { + JSError(getAllocator(ctx), "expect() requires one argument", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + var expect_ = getAllocator(ctx).create(Expect) catch unreachable; + js.JSValueProtect(ctx, arguments[0]); + expect_.* = .{ + .value = arguments[0], + .scope = DescribeScope.active, + .test_id = DescribeScope.active.current_test_id, + }; + return Expect.Class.make(ctx, expect_); + } +}; + +pub const TestScope = struct { + counter: Counter = Counter{}, + label: string = "", + parent: *DescribeScope, + callback: js.JSValueRef, + id: TestRunner.Test.ID = 0, + + pub const Class = NewClass(void, .{ .name = "test" }, .{ .call = call }, .{}); + + pub const Counter = struct { + expected: u32 = 0, + actual: u32 = 0, + }; + + pub fn call( + // the DescribeScope here is the top of the file, not the real one + _: void, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSObjectRef { + var args = arguments[0..@minimum(arguments.len, 2)]; + var label: string = ""; + if (args.len == 0) { + return js.JSValueMakeUndefined(ctx); + } + + if (js.JSValueIsString(ctx, args[0])) { + var label_ = ZigString.init(""); + JSC.JSValue.fromRef(arguments[0]).toZigString(&label_, ctx.ptr()); + label = if (label_.is16Bit()) + (strings.toUTF8AllocWithType(getAllocator(ctx), @TypeOf(label_.utf16Slice()), label_.utf16Slice()) catch unreachable) + else + label_.full(); + args = args[1..]; + } + + var function = args[0]; + if (!js.JSValueIsObject(ctx, function) or !js.JSObjectIsFunction(ctx, function)) { + JSError(getAllocator(ctx), "test() expects a function", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + + js.JSValueProtect(ctx, function); + + DescribeScope.active.tests.append(getAllocator(ctx), TestScope{ + .label = label, + .callback = function, + .parent = DescribeScope.active, + }) catch unreachable; + + return js.JSValueMakeUndefined(ctx); + } + + pub const Result = union(TestRunner.Test.Status) { + fail: u32, + pass: u32, // assertion count + pending: void, + }; + + pub fn run( + this: *TestScope, + ) Result { + var vm = VirtualMachine.vm; + + var promise = JSC.JSPromise.resolvedPromise( + vm.global, + js.JSObjectCallAsFunctionReturnValue(vm.global.ref(), this.callback, null, 0, null), + ); + js.JSValueUnprotect(vm.global.ref(), this.callback); + this.callback = null; + + while (promise.status(vm.global.vm()) == JSC.JSPromise.Status.Pending) { + vm.tick(); + } + var result = promise.result(vm.global.vm()); + + if (result.isException(vm.global.vm()) or result.isError() or result.isAggregateError(vm.global)) { + vm.defaultErrorHandler(result, null); + return .{ .fail = this.counter.actual }; + } + + if (this.counter.expected > 0 and this.counter.expected < this.counter.actual) { + Output.prettyErrorln("Test fail: {d} / {d} expectations\n (make this better!)", .{ + this.counter.actual, + this.counter.expected, + }); + return .{ .fail = this.counter.actual }; + } + + return .{ .pass = this.counter.actual }; + } +}; + +pub const DescribeScope = struct { + label: string = "", + parent: ?*DescribeScope = null, + beforeAll: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + beforeEach: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + afterEach: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + afterAll: std.ArrayListUnmanaged(js.JSValueRef) = .{}, + test_id_start: TestRunner.Test.ID = 0, + test_id_len: TestRunner.Test.ID = 0, + tests: std.ArrayListUnmanaged(TestScope) = .{}, + file_id: TestRunner.File.ID, + current_test_id: TestRunner.Test.ID = 0, + + pub const TestEntry = struct { + label: string, + callback: js.JSValueRef, + + pub const List = std.MultiArrayList(TestEntry); + }; + + pub threadlocal var active: *DescribeScope = undefined; + + pub const Class = NewClass( + DescribeScope, + .{ + .name = "describe", + .read_only = true, + }, + .{ + .call = describe, + .afterAll = .{ .rfn = callAfterAll, .name = "afterAll" }, + .beforeAll = .{ .rfn = callAfterAll, .name = "beforeAll" }, + .beforeEach = .{ .rfn = callAfterAll, .name = "beforeEach" }, + }, + .{ + .expect = .{ .get = createExpect, .name = "expect" }, + // kind of a mindfuck but + // describe("foo", () => {}).describe("bar") will wrok + .describe = .{ .get = createDescribe, .name = "describe" }, + .it = .{ .get = createTest, .name = "it" }, + .@"test" = .{ .get = createTest, .name = "test" }, + }, + ); + + pub fn describe( + this: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSObjectRef, + _: js.JSObjectRef, + arguments: []const js.JSValueRef, + exception: js.ExceptionRef, + ) js.JSObjectRef { + if (arguments.len == 0 or arguments.len > 2) { + JSError(getAllocator(ctx), "describe() requires 1-2 arguments", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + + var label = ZigString.init(""); + var args = arguments; + + if (js.JSValueIsString(ctx, arguments[0])) { + JSC.JSValue.fromRef(arguments[0]).toZigString(&label, ctx.ptr()); + args = args[1..]; + } + + if (args.len == 0 or !js.JSObjectIsFunction(ctx, args[0])) { + JSError(getAllocator(ctx), "describe() requires a callback function", .{}, ctx, exception); + return js.JSValueMakeUndefined(ctx); + } + + var callback = args[0]; + + var scope = getAllocator(ctx).create(DescribeScope) catch unreachable; + scope.* = .{ + .label = if (label.is16Bit()) + (strings.toUTF8AllocWithType(getAllocator(ctx), @TypeOf(label.utf16Slice()), label.utf16Slice()) catch unreachable) + else + label.full(), + .parent = this, + .file_id = this.file_id, + }; + var new_this = DescribeScope.Class.make(ctx, scope); + + return scope.run(new_this, ctx, callback, exception); + } + + pub fn run(this: *DescribeScope, thisObject: js.JSObjectRef, ctx: js.JSContextRef, callback: js.JSObjectRef, exception: js.ExceptionRef) js.JSObjectRef { + js.JSValueProtect(ctx, callback); + defer js.JSValueUnprotect(ctx, callback); + var original_active = active; + defer active = original_active; + active = this; + + { + var result = js.JSObjectCallAsFunctionReturnValue(ctx, callback, thisObject, 0, null); + if (result.isException(ctx.ptr().vm())) { + exception.* = result.asObjectRef(); + return null; + } + } + this.runTests(ctx); + return js.JSValueMakeUndefined(ctx); + } + + pub fn runTests(this: *DescribeScope, ctx: js.JSContextRef) void { + // Step 1. Initialize the test block + + const file = this.file_id; + + var tests: []TestScope = this.tests.items; + const end = @truncate(TestRunner.Test.ID, tests.len); + + if (end == 0) return; + + // Step 2. Update the runner with the count of how many tests we have for this block + this.test_id_start = Jest.runner.?.addTestCount(end); + + // Step 3. Run the beforeAll callbacks, in reverse order + // TODO: + + const source: logger.Source = Jest.runner.?.files.items(.source)[file]; + + var i: TestRunner.Test.ID = 0; + + while (i < end) { + this.current_test_id = i; + const result = TestScope.run(&tests[i]); + // invalidate it + this.current_test_id = std.math.maxInt(TestRunner.Test.ID); + + const test_id = i + this.test_id_start; + switch (result) { + .pass => |count| Jest.runner.?.reportPass(test_id, count), + .fail => |count| Jest.runner.?.reportFailure(test_id, source.path.text, tests[i].label, count), + .pending => unreachable, + } + + i += 1; + } + this.tests.deinit(getAllocator(ctx)); + } + + const ScopeStack = ObjectPool(std.ArrayListUnmanaged(*DescribeScope), null, true); + + // pub fn runBeforeAll(this: *DescribeScope, ctx: js.JSContextRef, exception: js.ExceptionRef) bool { + // var scopes = ScopeStack.get(default_allocator); + // defer scopes.release(); + // scopes.data.clearRetainingCapacity(); + // var cur: ?*DescribeScope = this; + // while (cur) |scope| { + // scopes.data.append(default_allocator, this) catch unreachable; + // cur = scope.parent; + // } + + // // while (scopes.data.popOrNull()) |scope| { + // // scope. + // // } + // } + + pub fn runCallbacks(this: *DescribeScope, ctx: js.JSContextRef, callbacks: std.ArrayListUnmanaged(js.JSObjectRef), exception: js.ExceptionRef) bool { + var i: usize = 0; + while (i < callbacks.items.len) : (i += 1) { + var callback = callbacks.items[i]; + var result = js.JSObjectCallAsFunctionReturnValue(ctx, callback, this, 0); + if (result.isException(ctx.ptr().vm())) { + exception.* = result.asObjectRef(); + return false; + } + } + } + + pub const callAfterAll = notImplementedFn; + pub const callAfterEach = notImplementedFn; + pub const callBeforeAll = notImplementedFn; + + pub fn createExpect( + _: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + _: js.ExceptionRef, + ) js.JSObjectRef { + var expect_ = getAllocator(ctx).create(ExpectPrototype) catch unreachable; + expect_.* = .{ + .scope = DescribeScope.active, + .test_id = DescribeScope.active.current_test_id, + }; + return ExpectPrototype.Class.make(ctx, expect_); + } + + pub fn createTest( + _: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + _: js.ExceptionRef, + ) js.JSObjectRef { + return js.JSObjectMake(ctx, TestScope.Class.get().*, null); + } + + pub fn createDescribe( + this: *DescribeScope, + ctx: js.JSContextRef, + _: js.JSValueRef, + _: js.JSStringRef, + _: js.ExceptionRef, + ) js.JSObjectRef { + return DescribeScope.Class.make(ctx, this); + } +}; diff --git a/src/javascript/jsc/webcore/response.zig b/src/javascript/jsc/webcore/response.zig index dfb17f630..1ff43bc98 100644 --- a/src/javascript/jsc/webcore/response.zig +++ b/src/javascript/jsc/webcore/response.zig @@ -95,7 +95,7 @@ pub const Response = struct { pub fn getText( this: *Response, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSObjectRef, _: []const js.JSValueRef, @@ -104,30 +104,45 @@ pub const Response = struct { // https://developer.mozilla.org/en-US/docs/Web/API/Response/text defer this.body.value = .Empty; return JSPromise.resolvedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), (brk: { switch (this.body.value) { .Unconsumed => { if (this.body.len > 0) { if (this.body.ptr) |_ptr| { - var offset: usize = 0; - while (offset < this.body.len and (_ptr[offset] > 127 or strings.utf8ByteSequenceLength(_ptr[offset]) == 0)) : (offset += 1) {} - if (offset < this.body.len) { - break :brk ZigString.init(_ptr[offset..this.body.len]).toValue(VirtualMachine.vm.global); + var zig_string = ZigString.init(_ptr[0..this.body.len]); + zig_string.detectEncoding(); + if (zig_string.is16Bit()) { + var value = zig_string.to16BitValue(ctx.ptr()); + this.body.ptr_allocator.?.free(_ptr[0..this.body.len]); + this.body.ptr_allocator = null; + this.body.ptr = null; + break :brk value; } + + break :brk zig_string.toValue(ctx.ptr()); } } - break :brk ZigString.init("").toValue(VirtualMachine.vm.global); + break :brk ZigString.init("").toValue(ctx.ptr()); }, .Empty => { - break :brk ZigString.init("").toValue(VirtualMachine.vm.global); + break :brk ZigString.init("").toValue(ctx.ptr()); }, .String => |str| { - break :brk ZigString.init(str).toValue(VirtualMachine.vm.global); + var zig_string = ZigString.init(str); + + zig_string.detectEncoding(); + if (zig_string.is16Bit()) { + var value = zig_string.to16BitValue(ctx.ptr()); + if (this.body.ptr_allocator) |allocator| this.body.deinit(allocator); + break :brk value; + } + + break :brk zig_string.toValue(ctx.ptr()); }, .ArrayBuffer => |buffer| { - break :brk ZigString.init(buffer.ptr[buffer.offset..buffer.byte_len]).toValue(VirtualMachine.vm.global); + break :brk ZigString.init(buffer.ptr[buffer.offset..buffer.byte_len]).toValue(ctx.ptr()); }, } }), @@ -188,9 +203,9 @@ pub const Response = struct { }, ) orelse { var out = std.fmt.bufPrint(&temp_error_buffer, "Invalid JSON\n\n \"{s}\"", .{zig_string.slice()[0..std.math.min(zig_string.len, 4000)]}) catch unreachable; - error_arg_list[0] = ZigString.init(out).toValueGC(VirtualMachine.vm.global).asRef(); + error_arg_list[0] = ZigString.init(out).toValueGC(ctx.ptr()).asRef(); return JSPromise.rejectedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), JSValue.fromRef( js.JSObjectMakeError( ctx, @@ -203,7 +218,7 @@ pub const Response = struct { }); return JSPromise.resolvedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), JSValue.fromRef(json_value), ).asRef(); } @@ -217,7 +232,7 @@ pub const Response = struct { ) js.JSValueRef { defer this.body.value = .Empty; return JSPromise.resolvedPromiseValue( - VirtualMachine.vm.global, + ctx.ptr(), JSValue.fromRef( (brk: { switch (this.body.value) { @@ -630,14 +645,13 @@ pub const Fetch = struct { node.data.http.schedule(allocator, &batch); NetworkThread.global.pool.schedule(batch); - try VirtualMachine.vm.enqueueTask(Task.init(&node.data)); return node; } pub fn callback(http_: *HTTPClient.AsyncHTTP, sender: *HTTPClient.AsyncHTTP.HTTPSender) void { var task: *FetchTasklet = @fieldParentPtr(FetchTasklet, "http", http_); @atomicStore(Status, &task.status, Status.done, .Monotonic); - _ = task.javascript_vm.eventLoop().ready_tasks_count.fetchAdd(1, .Monotonic); + task.javascript_vm.eventLoop().enqueueTaskConcurrent(Task.init(task)); sender.release(); } }; @@ -650,23 +664,25 @@ pub const Fetch = struct { arguments: []const js.JSValueRef, exception: js.ExceptionRef, ) js.JSObjectRef { + var globalThis = ctx.ptr(); + if (arguments.len == 0) { const fetch_error = fetch_error_no_args; - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } if (!js.JSValueIsString(ctx, arguments[0])) { const fetch_error = fetch_type_error_strings.get(js.JSValueGetType(ctx, arguments[0])); - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } var url_zig_str = ZigString.init(""); - JSValue.fromRef(arguments[0]).toZigString(&url_zig_str, VirtualMachine.vm.global); + JSValue.fromRef(arguments[0]).toZigString(&url_zig_str, globalThis); var url_str = url_zig_str.slice(); if (url_str.len == 0) { const fetch_error = fetch_error_blank_url; - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } if (url_str[0] == '/') { @@ -680,7 +696,7 @@ pub const Fetch = struct { if (url.origin.len > 0 and strings.eql(url.origin, VirtualMachine.vm.bundler.options.origin.origin)) { const fetch_error = fetch_error_cant_fetch_same_origin; - return JSPromise.rejectedPromiseValue(VirtualMachine.vm.global, ZigString.init(fetch_error).toErrorInstance(VirtualMachine.vm.global)).asRef(); + return JSPromise.rejectedPromiseValue(globalThis, ZigString.init(fetch_error).toErrorInstance(globalThis)).asRef(); } var headers: ?Headers = null; @@ -757,7 +773,7 @@ pub const Fetch = struct { // var resolve = FetchTasklet.FetchResolver.Class.make(ctx: js.JSContextRef, ptr: *ZigType) var queued = FetchTasklet.queue( default_allocator, - VirtualMachine.vm.global, + globalThis, method, url, header_entries, @@ -1302,7 +1318,8 @@ pub const Body = struct { ptr_allocator: ?std.mem.Allocator = null, pub fn deinit(this: *Body, allocator: std.mem.Allocator) void { - if (this.init.headers) |headers| { + this.ptr_allocator = null; + if (this.init.headers) |*headers| { headers.deinit(); } @@ -1312,6 +1329,7 @@ pub const Body = struct { allocator.free(str); }, .Empty => {}, + else => {}, } } @@ -1434,7 +1452,7 @@ pub const Body = struct { } else |_| {} } - var wtf_string = JSValue.fromRef(body_ref).toWTFString(VirtualMachine.vm.global); + var wtf_string = JSValue.fromRef(body_ref).toWTFString(ctx.ptr()); if (wtf_string.isEmpty()) { body.value = .{ .String = "" }; @@ -1575,7 +1593,7 @@ pub const Request = struct { _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.default).toValueGC(VirtualMachine.vm.global).asRef()); + return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.default).toValueGC(ctx.ptr()).asRef()); } pub fn getCredentials( _: *Request, @@ -1584,7 +1602,7 @@ pub const Request = struct { _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.include).toValueGC(VirtualMachine.vm.global).asRef()); + return js.JSValueMakeString(ctx, ZigString.init(Properties.UTF8.include).toValueGC(ctx.ptr()).asRef()); } pub fn getDestination( _: *Request, @@ -1593,7 +1611,7 @@ pub const Request = struct { _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return js.JSValueMakeString(ctx, ZigString.init("").toValueGC(VirtualMachine.vm.global).asRef()); + return js.JSValueMakeString(ctx, ZigString.init("").toValueGC(ctx.ptr()).asRef()); } pub fn getHeaders( this: *Request, @@ -1610,16 +1628,16 @@ pub const Request = struct { } pub fn getIntegrity( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.Empty.toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.Empty.toValueGC(ctx.ptr()).asRef(); } pub fn getMethod( this: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, @@ -1634,48 +1652,48 @@ pub const Request = struct { else => "", }; - return ZigString.init(string_contents).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(string_contents).toValueGC(ctx.ptr()).asRef(); } pub fn getMode( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(Properties.UTF8.navigate).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(Properties.UTF8.navigate).toValueGC(ctx.ptr()).asRef(); } pub fn getRedirect( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init(Properties.UTF8.follow).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(Properties.UTF8.follow).toValueGC(ctx.ptr()).asRef(); } pub fn getReferrer( this: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { if (this.request_context.header("Referrer")) |referrer| { - return ZigString.init(referrer).toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init(referrer).toValueGC(ctx.ptr()).asRef(); } else { - return ZigString.init("").toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init("").toValueGC(ctx.ptr()).asRef(); } } pub fn getReferrerPolicy( _: *Request, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSObjectRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSValueRef { - return ZigString.init("").toValueGC(VirtualMachine.vm.global).asRef(); + return ZigString.init("").toValueGC(ctx.ptr()).asRef(); } pub fn getUrl( this: *Request, @@ -1775,6 +1793,7 @@ pub const FetchEvent = struct { exception: js.ExceptionRef, ) js.JSValueRef { if (this.request_context.has_called_done) return js.JSValueMakeUndefined(ctx); + var globalThis = ctx.ptr(); // A Response or a Promise that resolves to a Response. Otherwise, a network error is returned to Fetch. if (arguments.len == 0 or !Response.Class.loaded or !js.JSValueIsObject(ctx, arguments[0])) { @@ -1786,15 +1805,15 @@ pub const FetchEvent = struct { var arg = arguments[0]; if (!js.JSValueIsObjectOfClass(ctx, arg, Response.Class.ref)) { - this.pending_promise = this.pending_promise orelse JSInternalPromise.resolvedPromise(VirtualMachine.vm.global, JSValue.fromRef(arguments[0])); + this.pending_promise = this.pending_promise orelse JSInternalPromise.resolvedPromise(globalThis, JSValue.fromRef(arguments[0])); } if (this.pending_promise) |promise| { - var status = promise.status(VirtualMachine.vm.global.vm()); + var status = promise.status(globalThis.vm()); if (status == .Pending) { VirtualMachine.vm.tick(); - status = promise.status(VirtualMachine.vm.global.vm()); + status = promise.status(globalThis.vm()); } switch (status) { @@ -1806,13 +1825,13 @@ pub const FetchEvent = struct { this.onPromiseRejectionCtx, error.PromiseRejection, this, - promise.result(VirtualMachine.vm.global.vm()), + promise.result(globalThis.vm()), ); return js.JSValueMakeUndefined(ctx); }, } - arg = promise.result(VirtualMachine.vm.global.vm()).asRef(); + arg = promise.result(ctx.ptr().vm()).asRef(); } if (!js.JSValueIsObjectOfClass(ctx, arg, Response.Class.ref)) { diff --git a/src/js_ast.zig b/src/js_ast.zig index 369326de4..dfc43e27b 100644 --- a/src/js_ast.zig +++ b/src/js_ast.zig @@ -3996,12 +3996,12 @@ pub const Macro = struct { }, ); - pub fn makeFromExpr(allocator: std.mem.Allocator, expr: Expr) js.JSObjectRef { + pub fn makeFromExpr(ctx: js.JSContextRef, allocator: std.mem.Allocator, expr: Expr) js.JSObjectRef { var ptr = allocator.create(JSNode) catch unreachable; ptr.* = JSNode.initExpr(expr); // If we look at JSObjectMake, we can see that all it does with the ctx value is lookup what the global object is // so it's safe to just avoid that and do it here like this: - return JSNode.Class.make(JavaScript.VirtualMachine.vm.global.ref(), ptr); + return JSNode.Class.make(ctx, ptr); } pub fn updateSymbolsMap(this: *const JSNode, comptime Visitor: type, visitor: Visitor) void { @@ -4121,11 +4121,11 @@ pub const Macro = struct { fn toStringValue(_: *JSNode, ctx: js.JSContextRef, str: E.String) js.JSObjectRef { if (str.isBlank()) { - return JSC.ZigString.init("").toValue(JavaScript.VirtualMachine.vm.global).asRef(); + return JSC.ZigString.init("").toValue(ctx.ptr()).asRef(); } if (str.isUTF8()) { - return JSC.ZigString.init(str.utf8).toValue(JavaScript.VirtualMachine.vm.global).asRef(); + return JSC.ZigString.init(str.utf8).toValue(ctx.ptr()).asRef(); } else { return js.JSValueMakeString(ctx, js.JSStringCreateWithCharactersNoCopy(str.value.ptr, str.value.len)); } @@ -4138,8 +4138,8 @@ pub const Macro = struct { return js.JSObjectMakeRegExp(ctx, 0, null, exception); } - regex_value_array[0] = JSC.ZigString.init(regex.pattern()).toValue(JavaScript.VirtualMachine.vm.global).asRef(); - regex_value_array[1] = JSC.ZigString.init(regex.flags()).toValue(JavaScript.VirtualMachine.vm.global).asRef(); + regex_value_array[0] = JSC.ZigString.init(regex.pattern()).toValue(ctx.ptr()).asRef(); + regex_value_array[1] = JSC.ZigString.init(regex.flags()).toValue(ctx.ptr()).asRef(); return js.JSObjectMakeRegExp(ctx, 2, ®ex_value_array, exception); } @@ -4265,11 +4265,11 @@ pub const Macro = struct { const str = template.head; if (str.isBlank()) { - return JSC.ZigString.init("").toValue(JavaScript.VirtualMachine.vm.global).asRef(); + return JSC.ZigString.init("").toValue(ctx.ptr()).asRef(); } if (str.isUTF8()) { - return JSC.ZigString.init(str.utf8).toValue(JavaScript.VirtualMachine.vm.global).asRef(); + return JSC.ZigString.init(str.utf8).toValue(ctx.ptr()).asRef(); } else { return js.JSValueMakeString(ctx, js.JSStringCreateWithCharactersNoCopy(str.value.ptr, str.value.len)); } @@ -4278,7 +4278,7 @@ pub const Macro = struct { // }, else => { - return JSC.ZigString.init("").toValue(JavaScript.VirtualMachine.vm.global).asRef(); + return JSC.ZigString.init("").toValue(ctx.ptr()).asRef(); }, } } @@ -4338,16 +4338,16 @@ pub const Macro = struct { fn toValue(this: *JSNode, ctx: js.JSContextRef, exception: js.ExceptionRef) js.JSObjectRef { switch (this.data) { .e_await => |aw| { - return JSNode.makeFromExpr(getAllocator(ctx), aw.value); + return JSNode.makeFromExpr(ctx, getAllocator(ctx), aw.value); }, .e_yield => |yi| { - return JSNode.makeFromExpr(getAllocator(ctx), yi.value orelse return null); + return JSNode.makeFromExpr(ctx, getAllocator(ctx), yi.value orelse return null); }, .e_spread => |spread| { - return JSNode.makeFromExpr(getAllocator(ctx), spread.value); + return JSNode.makeFromExpr(ctx, getAllocator(ctx), spread.value); }, .e_reg_exp => |reg| { - return JSC.ZigString.toRef(reg.value, JavaScript.VirtualMachine.vm.global); + return JSC.ZigString.toRef(reg.value, ctx.ptr()); }, .e_array => |array| { @@ -4394,12 +4394,12 @@ pub const Macro = struct { } pub fn getTagName( this: *JSNode, - _: js.JSContextRef, + ctx: js.JSContextRef, _: js.JSValueRef, _: js.JSStringRef, _: js.ExceptionRef, ) js.JSObjectRef { - return JSC.ZigString.init(@tagName(this.data)).toValue(JavaScript.VirtualMachine.vm.global).asRef(); + return JSC.ZigString.init(@tagName(this.data)).toValue(ctx.ptr()).asRef(); } pub fn getPosition( this: *JSNode, @@ -5813,12 +5813,12 @@ pub const Macro = struct { const i = this.args_i; this.args_i += 1; - return JSC.JSObject.getIndex(this.args_value, JavaScript.VirtualMachine.vm.global, i); + return JSC.JSObject.getIndex(this.args_value, this.ctx.ptr(), i); } pub inline fn peekArg(this: *Writer) ?JSC.JSValue { if (this.args_i >= this.args_len) return null; - return JSC.JSObject.getIndex(this.args_value, JavaScript.VirtualMachine.vm.global, this.args_i); + return JSC.JSObject.getIndex(this.args_value, this.ctx.ptr(), this.args_i); } pub inline fn nextJSValue(this: *Writer) ?JSC.JSValue { @@ -5884,7 +5884,7 @@ pub const Macro = struct { } pub fn fromJSValue(writer: *Writer, value: JSC.JSValue) TagOrJSNode { - return fromJSValueRef(writer, JavaScript.VirtualMachine.vm.global.ref(), value.asRef()); + return fromJSValueRef(writer, writer.ctx, value.asRef()); } }; @@ -5985,7 +5985,7 @@ pub const Macro = struct { } var path_zig_string = JSC.ZigString.Empty; - path_arg.toZigString(&path_zig_string, JavaScript.VirtualMachine.vm.global); + path_arg.toZigString(&path_zig_string, writer.ctx.ptr()); const import_path = path_zig_string.trimmedSlice(); if (import_path.len == 0) { @@ -6006,7 +6006,7 @@ pub const Macro = struct { const has_default = import_default_arg.isString(); var import_default_name_string = JSC.ZigString.Empty; - if (has_default) import_default_arg.toZigString(&import_default_name_string, JavaScript.VirtualMachine.vm.global); + if (has_default) import_default_arg.toZigString(&import_default_name_string, writer.ctx.ptr()); const import_default_name = import_default_name_string.slice(); @@ -6047,7 +6047,7 @@ pub const Macro = struct { } var property_value_zig_string = JSC.ZigString.Empty; - property_value.toZigString(&property_value_zig_string, JavaScript.VirtualMachine.vm.global); + property_value.toZigString(&property_value_zig_string, writer.ctx.ptr()); const alias = property_value_zig_string.slice(); @@ -6103,7 +6103,7 @@ pub const Macro = struct { while (i < count) { var nextArg = writer.eatArg() orelse return false; if (js.JSValueIsArray(writer.ctx, nextArg.asRef())) { - const extras = nextArg.getLengthOfArray(JavaScript.VirtualMachine.vm.global); + const extras = nextArg.getLengthOfArray(writer.ctx.ptr()); count += std.math.max(@truncate(@TypeOf(count), extras), 1) - 1; items.ensureUnusedCapacity(extras) catch unreachable; items.expandToCapacity(); @@ -6194,7 +6194,7 @@ pub const Macro = struct { return true; }, .e_string => { - var wtf_string = JSC.JSValue.toWTFString(writer.nextJSValue() orelse return false, JavaScript.VirtualMachine.vm.global); + var wtf_string = JSC.JSValue.toWTFString(writer.nextJSValue() orelse return false, writer.ctx.ptr()); if (wtf_string.isEmpty()) { expr.* = Expr{ .loc = writer.loc, @@ -6299,7 +6299,7 @@ pub const Macro = struct { const next_value = (writer.eatArg() orelse return null); const next_value_ref = next_value.asRef(); if (js.JSValueIsArray(writer.ctx, next_value_ref)) { - var iter = JSC.JSArrayIterator.init(next_value, JavaScript.VirtualMachine.vm.global); + var iter = JSC.JSArrayIterator.init(next_value, writer.ctx.ptr()); while (iter.next()) |current_value| { switch (TagOrJSNode.fromJSValueRef(writer, writer.ctx, current_value.asRef())) { .node => |node| { @@ -6485,7 +6485,7 @@ pub const Macro = struct { .allocator = JSCBase.getAllocator(ctx), .exception = exception, .args_value = args_value, - .args_len = args_value.getLengthOfArray(JavaScript.VirtualMachine.vm.global), + .args_len = args_value.getLengthOfArray(ctx.ptr()), .args_i = 0, .errored = false, }; @@ -6704,7 +6704,6 @@ pub const Macro = struct { _vm.enableMacroMode(); - _vm.bundler.configureLinker(); try _vm.bundler.configureDefines(); break :brk _vm; }; @@ -6762,7 +6761,7 @@ pub const Macro = struct { args_buf[1] = null; var macro_callback = macro.vm.macros.get(id) orelse return caller; - var result = js.JSObjectCallAsFunctionReturnValue(macro.vm.global.ref(), macro_callback, null, args.len + 1, &args_buf); + var result = js.JSObjectCallAsFunctionReturnValueHoldingAPILock(macro.vm.global.ref(), macro_callback, null, args.len + 1, &args_buf); js.JSValueProtect(macro.vm.global.ref(), result.asRef()); defer js.JSValueUnprotect(macro.vm.global.ref(), result.asRef()); var promise = JSC.JSPromise.resolvedPromise(macro.vm.global, result); diff --git a/src/js_parser/js_parser.zig b/src/js_parser/js_parser.zig index 7294bbe4d..ec6a313cb 100644 --- a/src/js_parser/js_parser.zig +++ b/src/js_parser/js_parser.zig @@ -2590,6 +2590,7 @@ pub const Parser = struct { while (runtime_imports_iter.next()) |entry| { const imports = [_]u16{entry.key}; + // TODO: remove these unnecessary allocations p.generateImportStmt( RuntimeImports.Name, &imports, @@ -3591,6 +3592,7 @@ pub fn NewParser( const allocator = p.allocator; const import_record_i = p.addImportRecordByRange(.stmt, logger.Range.None, import_path); var import_record: *ImportRecord = &p.import_records.items[import_record_i]; + import_record.path.namespace = "runtime"; import_record.is_internal = is_internal; var import_path_identifier = try import_record.path.name.nonUniqueNameString(allocator); var namespace_identifier = try allocator.alloc(u8, import_path_identifier.len + suffix.len); diff --git a/src/js_printer.zig b/src/js_printer.zig index 0c3be9bac..0acc9766a 100644 --- a/src/js_printer.zig +++ b/src/js_printer.zig @@ -358,6 +358,70 @@ pub fn NewPrinter( p.needs_semicolon = false; } } + + // + fn printBunJestImportStatement(p: *Printer, import: S.Import) void { + p.print("const "); + + if (import.star_name_loc != null) { + p.printSymbol(import.namespace_ref); + p.printSpace(); + p.print("="); + p.printSpaceBeforeIdentifier(); + p.print("Bun.jest(import.meta.path)"); + p.printSemicolonAfterStatement(); + p.printIndent(); + p.print("const "); + } + + if (import.items.len > 0) { + p.print("{ "); + if (!import.is_single_line) { + p.print("\n"); + p.options.indent += 1; + p.printIndent(); + } + + for (import.items) |item, i| { + if (i > 0) { + p.print(","); + p.printSpace(); + + if (!import.is_single_line) { + p.print("\n"); + p.printIndent(); + } + } + + const name = p.renamer.nameForSymbol(item.name.ref.?); + p.printIdentifier(name); + + if (!strings.eql(name, item.alias)) { + p.print(" : "); + p.printSpace(); + p.printClauseAlias(item.alias); + } + } + + if (!import.is_single_line) { + p.print("\n"); + p.options.indent -= 1; + } else { + p.printSpace(); + } + + if (import.star_name_loc == null) { + p.print("} = Bun.jest(import.meta.path)"); + } else { + p.print("} ="); + p.printSpaceBeforeIdentifier(); + p.printSymbol(import.namespace_ref); + } + + p.printSemicolonAfterStatement(); + } + } + pub inline fn printSpaceBeforeIdentifier( p: *Printer, ) void { @@ -3160,6 +3224,11 @@ pub fn NewPrinter( p.printIndent(); p.printSpaceBeforeIdentifier(); + if (record.path.isBun() and strings.eqlComptime(record.path.text, "test")) { + p.printBunJestImportStatement(s.*); + return; + } + if (is_inside_bundle) { return p.printBundledImport(record, s); } @@ -4033,7 +4102,7 @@ pub fn NewWriter( pub const Error = error{FormatError}; pub fn writeAll(writer: *Self, bytes: anytype) Error!usize { - const written = std.math.max(writer.written, 0); + const written = @maximum(writer.written, 0); writer.print(@TypeOf(bytes), bytes); return @intCast(usize, writer.written) - @intCast(usize, written); } diff --git a/src/jsc.zig b/src/jsc.zig index ac178b2eb..22e5011a7 100644 --- a/src/jsc.zig +++ b/src/jsc.zig @@ -5,3 +5,10 @@ pub usingnamespace @import("./javascript/jsc/base.zig"); pub usingnamespace @import("./javascript/jsc/javascript.zig"); pub const C = @import("./javascript/jsc/javascript_core_c_api.zig"); pub const WebCore = @import("./javascript/jsc/webcore/response.zig"); +pub const Jest = @import("./javascript/jsc/test/jest.zig"); +pub const Node = struct { + pub usingnamespace @import("./javascript/jsc/node/types.zig"); + pub usingnamespace @import("./javascript/jsc/node/node_fs.zig"); + pub usingnamespace @import("./javascript/jsc/node/node_fs_binding.zig"); + pub const Syscall = @import("./javascript/jsc/node/syscall.zig"); +}; diff --git a/src/linker.zig b/src/linker.zig index 3255d770e..b5caacc49 100644 --- a/src/linker.zig +++ b/src/linker.zig @@ -52,12 +52,13 @@ pub const Linker = struct { resolve_results: *_bundler.ResolveResults, any_needs_runtime: bool = false, runtime_import_record: ?ImportRecord = null, - runtime_source_path: string, hashed_filenames: HashedFileNameMap, import_counter: usize = 0, onImportCSS: ?OnImportCallback = null, + pub const runtime_source_path = "__runtime.js"; + pub fn init( allocator: std.mem.Allocator, log: *logger.Log, @@ -77,7 +78,6 @@ pub const Linker = struct { .resolve_queue = resolve_queue, .resolver = resolver, .resolve_results = resolve_results, - .runtime_source_path = fs.absAlloc(allocator, &([_]string{"__runtime.js"})) catch unreachable, .hashed_filenames = HashedFileNameMap.init(allocator), }; } @@ -210,7 +210,7 @@ pub const Linker = struct { const record_index = @truncate(u32, _record_index); if (comptime !ignore_runtime) { - if (strings.eqlComptime(import_record.path.text, Runtime.Imports.Name)) { + if (strings.eqlComptime(import_record.path.namespace, "runtime")) { // runtime is included in the bundle, so we don't need to dynamically import it if (linker.options.node_modules_bundle != null) { node_module_bundle_import_path = node_module_bundle_import_path orelse @@ -218,14 +218,19 @@ pub const Linker = struct { import_record.path.text = node_module_bundle_import_path.?; result.ast.runtime_import_record_id = record_index; } else { - import_record.path = try linker.generateImportPath( - source_dir, - linker.runtime_source_path, - false, - "bun", - origin, - import_path_format, - ); + if (import_path_format == .absolute_url) { + import_record.path = Fs.Path.initWithNamespace(try origin.joinAlloc(linker.allocator, "", "", "bun:runtime", "", ""), "bun"); + } else { + import_record.path = try linker.generateImportPath( + source_dir, + Linker.runtime_source_path, + false, + "bun", + origin, + import_path_format, + ); + } + result.ast.runtime_import_record_id = record_index; result.ast.needs_runtime = true; } @@ -233,6 +238,20 @@ pub const Linker = struct { } } + if (linker.options.platform.isBun()) { + if (strings.eqlComptime(import_record.path.text, "fs") or strings.eqlComptime(import_record.path.text, "node:fs")) { + externals.append(record_index) catch unreachable; + continue; + } + + if (import_record.path.text.len > 4 and strings.eqlComptime(import_record.path.text[0.."bun:".len], "bun:")) { + import_record.path = Fs.Path.init(import_record.path.text["bun:".len..]); + import_record.path.namespace = "bun"; + // don't link bun + continue; + } + } + if (linker.resolver.resolve(source_dir, import_record.path.text, import_record.kind)) |*_resolved_import| { const resolved_import: *const Resolver.Result = _resolved_import; if (resolved_import.is_external) { @@ -413,15 +432,11 @@ pub const Linker = struct { .kind = .stmt, .path = if (linker.options.node_modules_bundle != null) Fs.Path.init(node_module_bundle_import_path orelse linker.nodeModuleBundleImportPath(origin)) + else if (import_path_format == .absolute_url) + Fs.Path.initWithNamespace(try origin.joinAlloc(linker.allocator, "", "", "bun:runtime", "", ""), "bun") else - try linker.generateImportPath( - source_dir, - linker.runtime_source_path, - false, - "bun", - origin, - import_path_format, - ), + try linker.generateImportPath(source_dir, Linker.runtime_source_path, false, "bun", origin, import_path_format), + .range = logger.Range{ .loc = logger.Loc{ .start = 0 }, .len = 0 }, }; result.ast.runtime_import_record_id = @truncate(u32, import_records.len - 1); @@ -454,6 +469,7 @@ pub const Linker = struct { .data = .{ .s_import = &require_part_import_statement }, .loc = logger.Loc.Empty, }; + result.ast.prepend_part = js_ast.Part{ .stmts = std.mem.span(&require_part_stmts) }; } } diff --git a/src/linux_c.zig b/src/linux_c.zig new file mode 100644 index 000000000..d220a0f8c --- /dev/null +++ b/src/linux_c.zig @@ -0,0 +1,278 @@ +const std = @import("std"); +pub const SystemErrno = enum(u8) { + SUCCESS = 0, + EPERM = 1, + ENOENT = 2, + ESRCH = 3, + EINTR = 4, + EIO = 5, + ENXIO = 6, + E2BIG = 7, + ENOEXEC = 8, + EBADF = 9, + ECHILD = 10, + EAGAIN = 11, + ENOMEM = 12, + EACCES = 13, + EFAULT = 14, + ENOTBLK = 15, + EBUSY = 16, + EEXIST = 17, + EXDEV = 18, + ENODEV = 19, + ENOTDIR = 20, + EISDIR = 21, + EINVAL = 22, + ENFILE = 23, + EMFILE = 24, + ENOTTY = 25, + ETXTBSY = 26, + EFBIG = 27, + ENOSPC = 28, + ESPIPE = 29, + EROFS = 30, + EMLINK = 31, + EPIPE = 32, + EDOM = 33, + ERANGE = 34, + EDEADLK = 35, + ENAMETOOLONG = 36, + ENOLCK = 37, + ENOSYS = 38, + ENOTEMPTY = 39, + ELOOP = 40, + EWOULDBLOCK = 41, + ENOMSG = 42, + EIDRM = 43, + ECHRNG = 44, + EL2NSYNC = 45, + EL3HLT = 46, + EL3RST = 47, + ELNRNG = 48, + EUNATCH = 49, + ENOCSI = 50, + EL2HLT = 51, + EBADE = 52, + EBADR = 53, + EXFULL = 54, + ENOANO = 55, + EBADRQC = 56, + EBADSLT = 57, + EDEADLOCK = 58, + EBFONT = 59, + ENOSTR = 60, + ENODATA = 61, + ETIME = 62, + ENOSR = 63, + ENONET = 64, + ENOPKG = 65, + EREMOTE = 66, + ENOLINK = 67, + EADV = 68, + ESRMNT = 69, + ECOMM = 70, + EPROTO = 71, + EMULTIHOP = 72, + EDOTDOT = 73, + EBADMSG = 74, + EOVERFLOW = 75, + ENOTUNIQ = 76, + EBADFD = 77, + EREMCHG = 78, + ELIBACC = 79, + ELIBBAD = 80, + ELIBSCN = 81, + ELIBMAX = 82, + ELIBEXEC = 83, + EILSEQ = 84, + ERESTART = 85, + ESTRPIPE = 86, + EUSERS = 87, + ENOTSOCK = 88, + EDESTADDRREQ = 89, + EMSGSIZE = 90, + EPROTOTYPE = 91, + ENOPROTOOPT = 92, + EPROTONOSUPPORT = 93, + ESOCKTNOSUPPORT = 94, + /// For Linux, EOPNOTSUPP is the real value + /// but it's ~the same and is incompatible across operating systems + /// https://lists.gnu.org/archive/html/bug-glibc/2002-08/msg00017.html + ENOTSUP = 95, + EPFNOSUPPORT = 96, + EAFNOSUPPORT = 97, + EADDRINUSE = 98, + EADDRNOTAVAIL = 99, + ENETDOWN = 100, + ENETUNREACH = 101, + ENETRESET = 102, + ECONNABORTED = 103, + ECONNRESET = 104, + ENOBUFS = 105, + EISCONN = 106, + ENOTCONN = 107, + ESHUTDOWN = 108, + ETOOMANYREFS = 109, + ETIMEDOUT = 110, + ECONNREFUSED = 111, + EHOSTDOWN = 112, + EHOSTUNREACH = 113, + EALREADY = 114, + EINPROGRESS = 115, + ESTALE = 116, + EUCLEAN = 117, + ENOTNAM = 118, + ENAVAIL = 119, + EISNAM = 120, + EREMOTEIO = 121, + EDQUOT = 122, + ENOMEDIUM = 123, + EMEDIUMTYPE = 124, + ECANCELED = 125, + ENOKEY = 126, + EKEYEXPIRED = 127, + EKEYREVOKED = 128, + EKEYREJECTED = 129, + EOWNERDEAD = 130, + ENOTRECOVERABLE = 131, + ERFKILL = 132, + EHWPOISON = 133, + + pub const max = 134; + + const LabelMap = std.EnumMap(SystemErrno, []const u8); + pub const labels: LabelMap = brk: { + var map: LabelMap = LabelMap.initFull(""); + + map.put(.EPERM, "Operation not permitted"); + map.put(.ENOENT, "No such file or directory"); + map.put(.ESRCH, "No such process"); + map.put(.EINTR, "Interrupted system call"); + map.put(.EIO, "I/O error"); + map.put(.ENXIO, "No such device or address"); + map.put(.E2BIG, "Argument list too long"); + map.put(.ENOEXEC, "Exec format error"); + map.put(.EBADF, "Bad file number"); + map.put(.ECHILD, "No child processes"); + map.put(.EAGAIN, "Try again"); + map.put(.ENOMEM, "Out of memory"); + map.put(.EACCES, "Permission denied"); + map.put(.EFAULT, "Bad address"); + map.put(.ENOTBLK, "Block device required"); + map.put(.EBUSY, "Device or resource busy"); + map.put(.EEXIST, "File or folder exists"); + map.put(.EXDEV, "Cross-device link"); + map.put(.ENODEV, "No such device"); + map.put(.ENOTDIR, "Not a directory"); + map.put(.EISDIR, "Is a directory"); + map.put(.EINVAL, "Invalid argument"); + map.put(.ENFILE, "File table overflow"); + map.put(.EMFILE, "Too many open files"); + map.put(.ENOTTY, "Not a typewriter"); + map.put(.ETXTBSY, "Text file busy"); + map.put(.EFBIG, "File too large"); + map.put(.ENOSPC, "No space left on device"); + map.put(.ESPIPE, "Illegal seek"); + map.put(.EROFS, "Read-only file system"); + map.put(.EMLINK, "Too many links"); + map.put(.EPIPE, "Broken pipe"); + map.put(.EDOM, "Math argument out of domain of func"); + map.put(.ERANGE, "Math result not representable"); + map.put(.EDEADLK, "Resource deadlock would occur"); + map.put(.ENAMETOOLONG, "File name too long"); + map.put(.ENOLCK, "No record locks available"); + map.put(.ENOSYS, "Function not implemented"); + map.put(.ENOTEMPTY, "Directory not empty"); + map.put(.ELOOP, "Too many symbolic links encountered"); + map.put(.ENOMSG, "No message of desired type"); + map.put(.EIDRM, "Identifier removed"); + map.put(.ECHRNG, "Channel number out of range"); + map.put(.EL2NSYNC, "Level 2 not synchronized"); + map.put(.EL3HLT, "Level 3 halted"); + map.put(.EL3RST, "Level 3 reset"); + map.put(.ELNRNG, "Link number out of range"); + map.put(.EUNATCH, "Protocol driver not attached"); + map.put(.ENOCSI, "No CSI structure available"); + map.put(.EL2HLT, "Level 2 halted"); + map.put(.EBADE, "Invalid exchange"); + map.put(.EBADR, "Invalid request descriptor"); + map.put(.EXFULL, "Exchange full"); + map.put(.ENOANO, "No anode"); + map.put(.EBADRQC, "Invalid request code"); + map.put(.EBADSLT, "Invalid slot"); + map.put(.EBFONT, "Bad font file format"); + map.put(.ENOSTR, "Device not a stream"); + map.put(.ENODATA, "No data available"); + map.put(.ETIME, "Timer expired"); + map.put(.ENOSR, "Out of streams resources"); + map.put(.ENONET, "Machine is not on the network"); + map.put(.ENOPKG, "Package not installed"); + map.put(.EREMOTE, "Object is remote"); + map.put(.ENOLINK, "Link has been severed"); + map.put(.EADV, "Advertise error"); + map.put(.ESRMNT, "Srmount error"); + map.put(.ECOMM, "Communication error on send"); + map.put(.EPROTO, "Protocol error"); + map.put(.EMULTIHOP, "Multihop attempted"); + map.put(.EDOTDOT, "RFS specific error"); + map.put(.EBADMSG, "Not a data message"); + map.put(.EOVERFLOW, "Value too large for defined data type"); + map.put(.ENOTUNIQ, "Name not unique on network"); + map.put(.EBADFD, "File descriptor in bad state"); + map.put(.EREMCHG, "Remote address changed"); + map.put(.ELIBACC, "Can not access a needed shared library"); + map.put(.ELIBBAD, "Accessing a corrupted shared library"); + map.put(.ELIBSCN, "lib section in a.out corrupted"); + map.put(.ELIBMAX, "Attempting to link in too many shared libraries"); + map.put(.ELIBEXEC, "Cannot exec a shared library directly"); + map.put(.EILSEQ, "Illegal byte sequence"); + map.put(.ERESTART, "Interrupted system call should be restarted"); + map.put(.ESTRPIPE, "Streams pipe error"); + map.put(.EUSERS, "Too many users"); + map.put(.ENOTSOCK, "Socket operation on non-socket"); + map.put(.EDESTADDRREQ, "Destination address required"); + map.put(.EMSGSIZE, "Message too long"); + map.put(.EPROTOTYPE, "Protocol wrong type for socket"); + map.put(.ENOPROTOOPT, "Protocol not available"); + map.put(.EPROTONOSUPPORT, "Protocol not supported"); + map.put(.ESOCKTNOSUPPORT, "Socket type not supported"); + map.put(.ENOTSUP, "Operation not supported on transport endpoint"); + map.put(.EPFNOSUPPORT, "Protocol family not supported"); + map.put(.EAFNOSUPPORT, "Address family not supported by protocol"); + map.put(.EADDRINUSE, "Address already in use"); + map.put(.EADDRNOTAVAIL, "Cannot assign requested address"); + map.put(.ENETDOWN, "Network is down"); + map.put(.ENETUNREACH, "Network is unreachable"); + map.put(.ENETRESET, "Network dropped connection because of reset"); + map.put(.ECONNABORTED, "Software caused connection abort"); + map.put(.ECONNRESET, "Connection reset by peer"); + map.put(.ENOBUFS, "No buffer space available"); + map.put(.EISCONN, "Transport endpoint is already connected"); + map.put(.ENOTCONN, "Transport endpoint is not connected"); + map.put(.ESHUTDOWN, "Cannot send after transport endpoint shutdown"); + map.put(.ETOOMANYREFS, "Too many references: cannot splice"); + map.put(.ETIMEDOUT, "Connection timed out"); + map.put(.ECONNREFUSED, "Connection refused"); + map.put(.EHOSTDOWN, "Host is down"); + map.put(.EHOSTUNREACH, "No route to host"); + map.put(.EALREADY, "Operation already in progress"); + map.put(.EINPROGRESS, "Operation now in progress"); + map.put(.ESTALE, "Stale NFS file handle"); + map.put(.EUCLEAN, "Structure needs cleaning"); + map.put(.ENOTNAM, "Not a XENIX named type file"); + map.put(.ENAVAIL, "No XENIX semaphores available"); + map.put(.EISNAM, "Is a named type file"); + map.put(.EREMOTEIO, "Remote I/O error"); + map.put(.EDQUOT, "Quota exceeded"); + map.put(.ENOMEDIUM, "No medium found"); + map.put(.EMEDIUMTYPE, "Wrong medium type"); + map.put(.ECANCELED, "Operation Canceled"); + map.put(.ENOKEY, "Required key not available"); + map.put(.EKEYEXPIRED, "Key has expired"); + map.put(.EKEYREVOKED, "Key has been revoked"); + map.put(.EKEYREJECTED, "Key was rejected by service"); + map.put(.EOWNERDEAD, "Owner died"); + map.put(.ENOTRECOVERABLE, "State not recoverable"); + break :brk map; + }; +}; diff --git a/src/logger.zig b/src/logger.zig index ae1d20fed..5ac17f13c 100644 --- a/src/logger.zig +++ b/src/logger.zig @@ -1,6 +1,6 @@ const std = @import("std"); const Api = @import("./api/schema.zig").Api; -const js = @import("javascript_core"); +const js = @import("./jsc.zig"); const ImportKind = @import("./import_record.zig").ImportKind; const _global = @import("./global.zig"); const string = _global.string; @@ -645,11 +645,15 @@ pub const Log = struct { }); } - inline fn _addResolveError(log: *Log, source: *const Source, r: Range, allocator: std.mem.Allocator, comptime fmt: string, args: anytype, import_kind: ImportKind, comptime dupe_text: bool) !void { + inline fn _addResolveErrorWithLevel(log: *Log, source: *const Source, r: Range, allocator: std.mem.Allocator, comptime fmt: string, args: anytype, import_kind: ImportKind, comptime dupe_text: bool, comptime is_error: bool) !void { const text = try std.fmt.allocPrint(allocator, fmt, args); // TODO: fix this. this is stupid, it should be returned in allocPrint. const specifier = BabyString.in(text, args.@"0"); - log.errors += 1; + if (comptime is_error) { + log.errors += 1; + } else { + log.warnings += 1; + } const data = if (comptime dupe_text) brk: { var _data = rangeData( @@ -670,7 +674,7 @@ pub const Log = struct { ); const msg = Msg{ - .kind = .err, + .kind = if (comptime is_error) Kind.err else Kind.warn, .data = data, .metadata = .{ .resolve = Msg.Metadata.Resolve{ .specifier = specifier, .import_kind = import_kind } }, }; @@ -678,6 +682,14 @@ pub const Log = struct { try log.addMsg(msg); } + inline fn _addResolveError(log: *Log, source: *const Source, r: Range, allocator: std.mem.Allocator, comptime fmt: string, args: anytype, import_kind: ImportKind, comptime dupe_text: bool) !void { + return _addResolveErrorWithLevel(log, source, r, allocator, fmt, args, import_kind, dupe_text, true); + } + + inline fn _addResolveWarn(log: *Log, source: *const Source, r: Range, allocator: std.mem.Allocator, comptime fmt: string, args: anytype, import_kind: ImportKind, comptime dupe_text: bool) !void { + return _addResolveErrorWithLevel(log, source, r, allocator, fmt, args, import_kind, dupe_text, false); + } + pub fn addResolveError( log: *Log, source: *const Source, @@ -704,6 +716,24 @@ pub const Log = struct { return try _addResolveError(log, source, r, allocator, fmt, args, import_kind, true); } + pub fn addResolveErrorWithTextDupeMaybeWarn( + log: *Log, + source: *const Source, + r: Range, + allocator: std.mem.Allocator, + comptime fmt: string, + args: anytype, + import_kind: ImportKind, + warn: bool, + ) !void { + @setCold(true); + if (warn) { + return try _addResolveError(log, source, r, allocator, fmt, args, import_kind, true); + } else { + return try _addResolveWarn(log, source, r, allocator, fmt, args, import_kind, true); + } + } + pub fn addRangeError(log: *Log, source: ?*const Source, r: Range, text: string) !void { @setCold(true); log.errors += 1; diff --git a/src/main.zig b/src/main.zig index b3455d884..50f902194 100644 --- a/src/main.zig +++ b/src/main.zig @@ -35,8 +35,8 @@ pub fn PLCrashReportHandler() void { } pub var start_time: i128 = 0; -pub fn main() anyerror!void { - std.debug.assert(CrashReporter.start(Global.package_json_version)); +pub fn main() void { + std.debug.assert(CrashReporter.start(null, Report.CrashReportWriter.printFrame, Report.handleCrash)); start_time = std.time.nanoTimestamp(); @@ -54,7 +54,7 @@ pub fn main() anyerror!void { Output.Source.set(&output_source); defer Output.flush(); - cli.Cli.start(default_allocator, stdout, stderr, MainPanicHandler) catch |err| Report.globalError(err); + cli.Cli.start(default_allocator, stdout, stderr, MainPanicHandler); std.mem.doNotOptimizeAway(JavaScriptVirtualMachine.fetch); std.mem.doNotOptimizeAway(JavaScriptVirtualMachine.init); diff --git a/src/memory_allocator.zig b/src/memory_allocator.zig index a3cd71583..aeb91dfac 100644 --- a/src/memory_allocator.zig +++ b/src/memory_allocator.zig @@ -3,12 +3,24 @@ const builtin = @import("std").builtin; const std = @import("std"); const mimalloc = @import("./allocators/mimalloc.zig"); +const FeatureFlags = @import("./feature_flags.zig"); + const c = struct { pub const malloc_size = mimalloc.mi_malloc_size; pub const malloc_usable_size = mimalloc.mi_malloc_usable_size; - pub const malloc = mimalloc.mi_malloc; + pub const malloc = struct { + pub inline fn malloc_wrapped(size: usize) ?*anyopaque { + if (comptime FeatureFlags.log_allocations) std.debug.print("Malloc: {d}\n", .{size}); + return mimalloc.mi_malloc(size); + } + }.malloc_wrapped; pub const free = mimalloc.mi_free; - pub const posix_memalign = mimalloc.mi_posix_memalign; + pub const posix_memalign = struct { + pub inline fn mi_posix_memalign(p: [*c]?*anyopaque, alignment: usize, size: usize) c_int { + if (comptime FeatureFlags.log_allocations) std.debug.print("Posix_memalign: {d}\n", .{std.mem.alignForward(size, alignment)}); + return mimalloc.mi_posix_memalign(p, alignment, size); + } + }.mi_posix_memalign; }; const Allocator = mem.Allocator; const assert = std.debug.assert; @@ -51,7 +63,7 @@ const CAllocator = struct { // multiple of the pointer size const eff_alignment = @maximum(alignment, @sizeOf(usize)); - var aligned_ptr: ?*anyopaque = undefined; + var aligned_ptr: ?*anyopaque = null; if (c.posix_memalign(&aligned_ptr, eff_alignment, len) != 0) return null; diff --git a/src/meta.zig b/src/meta.zig new file mode 100644 index 000000000..afc502d58 --- /dev/null +++ b/src/meta.zig @@ -0,0 +1,12 @@ +const std = @import("std"); + +pub usingnamespace std.meta; + +pub fn ReturnOf(comptime function: anytype) type { + return ReturnOfType(@TypeOf(function)); +} + +pub fn ReturnOfType(comptime Type: type) type { + const typeinfo: std.builtin.TypeInfo.Fn = @typeInfo(Type); + return typeinfo.return_type orelse void; +} diff --git a/src/node-fallbacks/bun.lockb b/src/node-fallbacks/bun.lockb Binary files differindex d55955ad2..62cf575ac 100755 --- a/src/node-fallbacks/bun.lockb +++ b/src/node-fallbacks/bun.lockb diff --git a/src/node-fallbacks/package-lock.json b/src/node-fallbacks/package-lock.json index 5df702fb2..62a14561a 100644 --- a/src/node-fallbacks/package-lock.json +++ b/src/node-fallbacks/package-lock.json @@ -1,1174 +1,8 @@ { "name": "fallbacks", "version": "1.0.0", - "lockfileVersion": 2, + "lockfileVersion": 1, "requires": true, - "packages": { - "": { - "name": "fallbacks", - "version": "1.0.0", - "license": "ISC", - "dependencies": { - "assert": "^2.0.0", - "browserify-zlib": "^0.2.0", - "buffer": "^6.0.3", - "console-browserify": "^1.2.0", - "constants-browserify": "^1.0.0", - "crypto-browserify": "^3.12.0", - "domain-browser": "^4.22.0", - "esbuild": "^0.12.25", - "events": "^3.3.0", - "https-browserify": "^1.0.0", - "os-browserify": "^0.3.0", - "path-browserify": "^1.0.1", - "process": "^0.11.10", - "punycode": "^2.1.1", - "querystring-es3": "^0.2.1", - "stream-browserify": "^3.0.0", - "stream-http": "^3.2.0", - "string_decoder": "^1.3.0", - "timers-browserify": "^2.0.12", - "tty-browserify": "^0.0.1", - "url": "^0.11.0", - "util": "^0.12.4", - "vm-browserify": "^1.1.2" - } - }, - "node_modules/asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", - "dependencies": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - } - }, - "node_modules/assert": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/assert/-/assert-2.0.0.tgz", - "integrity": "sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==", - "dependencies": { - "es6-object-assign": "^1.1.0", - "is-nan": "^1.2.1", - "object-is": "^1.0.1", - "util": "^0.12.0" - } - }, - "node_modules/available-typed-arrays": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", - "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/bn.js": { - "version": "4.12.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.0.tgz", - "integrity": "sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA==" - }, - "node_modules/brorand": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", - "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=" - }, - "node_modules/browserify-aes": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", - "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", - "dependencies": { - "buffer-xor": "^1.0.3", - "cipher-base": "^1.0.0", - "create-hash": "^1.1.0", - "evp_bytestokey": "^1.0.3", - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/browserify-cipher": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", - "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", - "dependencies": { - "browserify-aes": "^1.0.4", - "browserify-des": "^1.0.0", - "evp_bytestokey": "^1.0.0" - } - }, - "node_modules/browserify-des": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", - "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", - "dependencies": { - "cipher-base": "^1.0.1", - "des.js": "^1.0.0", - "inherits": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "node_modules/browserify-rsa": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.1.0.tgz", - "integrity": "sha512-AdEER0Hkspgno2aR97SAf6vi0y0k8NuOpGnVH3O99rcA5Q6sh8QxcngtHuJ6uXwnfAXNM4Gn1Gb7/MV1+Ymbog==", - "dependencies": { - "bn.js": "^5.0.0", - "randombytes": "^2.0.1" - } - }, - "node_modules/browserify-rsa/node_modules/bn.js": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.0.tgz", - "integrity": "sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw==" - }, - "node_modules/browserify-sign": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.1.tgz", - "integrity": "sha512-/vrA5fguVAKKAVTNJjgSm1tRQDHUU6DbwO9IROu/0WAzC8PKhucDSh18J0RMvVeHAn5puMd+QHC2erPRNf8lmg==", - "dependencies": { - "bn.js": "^5.1.1", - "browserify-rsa": "^4.0.1", - "create-hash": "^1.2.0", - "create-hmac": "^1.1.7", - "elliptic": "^6.5.3", - "inherits": "^2.0.4", - "parse-asn1": "^5.1.5", - "readable-stream": "^3.6.0", - "safe-buffer": "^5.2.0" - } - }, - "node_modules/browserify-sign/node_modules/bn.js": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.0.tgz", - "integrity": "sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw==" - }, - "node_modules/browserify-zlib": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", - "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", - "dependencies": { - "pako": "~1.0.5" - } - }, - "node_modules/buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, - "node_modules/buffer-xor": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", - "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=" - }, - "node_modules/builtin-status-codes": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", - "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=" - }, - "node_modules/call-bind": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", - "dependencies": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/cipher-base": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", - "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", - "dependencies": { - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/console-browserify": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.2.0.tgz", - "integrity": "sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA==" - }, - "node_modules/constants-browserify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", - "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=" - }, - "node_modules/create-ecdh": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", - "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", - "dependencies": { - "bn.js": "^4.1.0", - "elliptic": "^6.5.3" - } - }, - "node_modules/create-hash": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", - "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", - "dependencies": { - "cipher-base": "^1.0.1", - "inherits": "^2.0.1", - "md5.js": "^1.3.4", - "ripemd160": "^2.0.1", - "sha.js": "^2.4.0" - } - }, - "node_modules/create-hmac": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", - "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", - "dependencies": { - "cipher-base": "^1.0.3", - "create-hash": "^1.1.0", - "inherits": "^2.0.1", - "ripemd160": "^2.0.0", - "safe-buffer": "^5.0.1", - "sha.js": "^2.4.8" - } - }, - "node_modules/crypto-browserify": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", - "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", - "dependencies": { - "browserify-cipher": "^1.0.0", - "browserify-sign": "^4.0.0", - "create-ecdh": "^4.0.0", - "create-hash": "^1.1.0", - "create-hmac": "^1.1.0", - "diffie-hellman": "^5.0.0", - "inherits": "^2.0.1", - "pbkdf2": "^3.0.3", - "public-encrypt": "^4.0.0", - "randombytes": "^2.0.0", - "randomfill": "^1.0.3" - }, - "engines": { - "node": "*" - } - }, - "node_modules/define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", - "dependencies": { - "object-keys": "^1.0.12" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/des.js": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz", - "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==", - "dependencies": { - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0" - } - }, - "node_modules/diffie-hellman": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", - "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", - "dependencies": { - "bn.js": "^4.1.0", - "miller-rabin": "^4.0.0", - "randombytes": "^2.0.0" - } - }, - "node_modules/domain-browser": { - "version": "4.22.0", - "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-4.22.0.tgz", - "integrity": "sha512-IGBwjF7tNk3cwypFNH/7bfzBcgSCbaMOD3GsaY1AU/JRrnHnYgEM0+9kQt52iZxjNsjBtJYtao146V+f8jFZNw==", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://bevry.me/fund" - } - }, - "node_modules/elliptic": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", - "integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==", - "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/es-abstract": { - "version": "1.18.5", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.5.tgz", - "integrity": "sha512-DDggyJLoS91CkJjgauM5c0yZMjiD1uK3KcaCeAmffGwZ+ODWzOkPN4QwRbsK5DOFf06fywmyLci3ZD8jLGhVYA==", - "dependencies": { - "call-bind": "^1.0.2", - "es-to-primitive": "^1.2.1", - "function-bind": "^1.1.1", - "get-intrinsic": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.2", - "internal-slot": "^1.0.3", - "is-callable": "^1.2.3", - "is-negative-zero": "^2.0.1", - "is-regex": "^1.1.3", - "is-string": "^1.0.6", - "object-inspect": "^1.11.0", - "object-keys": "^1.1.1", - "object.assign": "^4.1.2", - "string.prototype.trimend": "^1.0.4", - "string.prototype.trimstart": "^1.0.4", - "unbox-primitive": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/es-to-primitive": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", - "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", - "dependencies": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/es6-object-assign": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/es6-object-assign/-/es6-object-assign-1.1.0.tgz", - "integrity": "sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw=" - }, - "node_modules/esbuild": { - "version": "0.12.25", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.25.tgz", - "integrity": "sha512-woie0PosbRSoN8gQytrdCzUbS2ByKgO8nD1xCZkEup3D9q92miCze4PqEI9TZDYAuwn6CruEnQpJxgTRWdooAg==", - "hasInstallScript": true, - "bin": { - "esbuild": "bin/esbuild" - } - }, - "node_modules/events": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", - "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", - "engines": { - "node": ">=0.8.x" - } - }, - "node_modules/evp_bytestokey": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", - "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", - "dependencies": { - "md5.js": "^1.3.4", - "safe-buffer": "^5.1.1" - } - }, - "node_modules/foreach": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", - "integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=" - }, - "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" - }, - "node_modules/get-intrinsic": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "dependencies": { - "function-bind": "^1.1.1" - }, - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/has-bigints": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.1.tgz", - "integrity": "sha512-LSBS2LjbNBTf6287JEbEzvJgftkF5qFkmCo9hDRpAzKhUOlJ+hx8dd4USs00SgsUNwc4617J9ki5YtEClM2ffA==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", - "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", - "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", - "dependencies": { - "has-symbols": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hash-base": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.1.0.tgz", - "integrity": "sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA==", - "dependencies": { - "inherits": "^2.0.4", - "readable-stream": "^3.6.0", - "safe-buffer": "^5.2.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/hash.js": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", - "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", - "dependencies": { - "inherits": "^2.0.3", - "minimalistic-assert": "^1.0.1" - } - }, - "node_modules/hmac-drbg": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", - "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", - "dependencies": { - "hash.js": "^1.0.3", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.1" - } - }, - "node_modules/https-browserify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", - "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" - }, - "node_modules/internal-slot": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.3.tgz", - "integrity": "sha512-O0DB1JC/sPyZl7cIo78n5dR7eUSwwpYPiXRhTzNxZVAMUuB8vlnRFyLxdrVToks6XPLVnFfbzaVd5WLjhgg+vA==", - "dependencies": { - "get-intrinsic": "^1.1.0", - "has": "^1.0.3", - "side-channel": "^1.0.4" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/is-arguments": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.1.1.tgz", - "integrity": "sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==", - "dependencies": { - "call-bind": "^1.0.2", - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-bigint": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", - "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", - "dependencies": { - "has-bigints": "^1.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-boolean-object": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", - "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", - "dependencies": { - "call-bind": "^1.0.2", - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-callable": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.4.tgz", - "integrity": "sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-date-object": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", - "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", - "dependencies": { - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-generator-function": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.10.tgz", - "integrity": "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==", - "dependencies": { - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-nan": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.3.2.tgz", - "integrity": "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==", - "dependencies": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-negative-zero": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz", - "integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-number-object": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.6.tgz", - "integrity": "sha512-bEVOqiRcvo3zO1+G2lVMy+gkkEm9Yh7cDMRusKKu5ZJKPUYSJwICTKZrNKHA2EbSP0Tu0+6B/emsYNHZyn6K8g==", - "dependencies": { - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-regex": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", - "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", - "dependencies": { - "call-bind": "^1.0.2", - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-string": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", - "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", - "dependencies": { - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-symbol": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", - "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", - "dependencies": { - "has-symbols": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-typed-array": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.8.tgz", - "integrity": "sha512-HqH41TNZq2fgtGT8WHVFVJhBVGuY3AnP3Q36K8JKXUxSxRgk/d+7NjmwG2vo2mYmXK8UYZKu0qH8bVP5gEisjA==", - "dependencies": { - "available-typed-arrays": "^1.0.5", - "call-bind": "^1.0.2", - "es-abstract": "^1.18.5", - "foreach": "^2.0.5", - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/md5.js": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", - "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", - "dependencies": { - "hash-base": "^3.0.0", - "inherits": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "node_modules/miller-rabin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", - "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", - "dependencies": { - "bn.js": "^4.0.0", - "brorand": "^1.0.1" - }, - "bin": { - "miller-rabin": "bin/miller-rabin" - } - }, - "node_modules/minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==" - }, - "node_modules/minimalistic-crypto-utils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", - "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=" - }, - "node_modules/object-inspect": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz", - "integrity": "sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/object-is": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.5.tgz", - "integrity": "sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw==", - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/object-keys": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", - "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/object.assign": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.2.tgz", - "integrity": "sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ==", - "dependencies": { - "call-bind": "^1.0.0", - "define-properties": "^1.1.3", - "has-symbols": "^1.0.1", - "object-keys": "^1.1.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/os-browserify": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", - "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=" - }, - "node_modules/pako": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", - "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==" - }, - "node_modules/parse-asn1": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz", - "integrity": "sha512-RnZRo1EPU6JBnra2vGHj0yhp6ebyjBZpmUCLHWiFhxlzvBCCpAuZ7elsBp1PVAbQN0/04VD/19rfzlBSwLstMw==", - "dependencies": { - "asn1.js": "^5.2.0", - "browserify-aes": "^1.0.0", - "evp_bytestokey": "^1.0.0", - "pbkdf2": "^3.0.3", - "safe-buffer": "^5.1.1" - } - }, - "node_modules/path-browserify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", - "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==" - }, - "node_modules/pbkdf2": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.1.2.tgz", - "integrity": "sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA==", - "dependencies": { - "create-hash": "^1.1.2", - "create-hmac": "^1.1.4", - "ripemd160": "^2.0.1", - "safe-buffer": "^5.0.1", - "sha.js": "^2.4.8" - }, - "engines": { - "node": ">=0.12" - } - }, - "node_modules/process": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", - "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", - "engines": { - "node": ">= 0.6.0" - } - }, - "node_modules/public-encrypt": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", - "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", - "dependencies": { - "bn.js": "^4.1.0", - "browserify-rsa": "^4.0.0", - "create-hash": "^1.1.0", - "parse-asn1": "^5.0.0", - "randombytes": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "node_modules/punycode": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", - "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", - "engines": { - "node": ">=6" - } - }, - "node_modules/querystring": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", - "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=", - "deprecated": "The querystring API is considered Legacy. new code should use the URLSearchParams API instead.", - "engines": { - "node": ">=0.4.x" - } - }, - "node_modules/querystring-es3": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", - "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", - "engines": { - "node": ">=0.4.x" - } - }, - "node_modules/randombytes": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "dependencies": { - "safe-buffer": "^5.1.0" - } - }, - "node_modules/randomfill": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", - "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", - "dependencies": { - "randombytes": "^2.0.5", - "safe-buffer": "^5.1.0" - } - }, - "node_modules/readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/ripemd160": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", - "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", - "dependencies": { - "hash-base": "^3.0.0", - "inherits": "^2.0.1" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" - }, - "node_modules/setimmediate": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", - "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=" - }, - "node_modules/sha.js": { - "version": "2.4.11", - "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", - "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", - "dependencies": { - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" - }, - "bin": { - "sha.js": "bin.js" - } - }, - "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", - "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/stream-browserify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-3.0.0.tgz", - "integrity": "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==", - "dependencies": { - "inherits": "~2.0.4", - "readable-stream": "^3.5.0" - } - }, - "node_modules/stream-http": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-3.2.0.tgz", - "integrity": "sha512-Oq1bLqisTyK3TSCXpPbT4sdeYNdmyZJv1LxpEm2vu1ZhK89kSE5YXwZc3cWk0MagGaKriBh9mCFbVGtO+vY29A==", - "dependencies": { - "builtin-status-codes": "^3.0.0", - "inherits": "^2.0.4", - "readable-stream": "^3.6.0", - "xtend": "^4.0.2" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/string.prototype.trimend": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", - "integrity": "sha512-y9xCjw1P23Awk8EvTpcyL2NIr1j7wJ39f+k6lvRnSMz+mz9CGz9NYPelDk42kOz6+ql8xjfK8oYzy3jAP5QU5A==", - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/string.prototype.trimstart": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.4.tgz", - "integrity": "sha512-jh6e984OBfvxS50tdY2nRZnoC5/mLFKOREQfw8t5yytkoUsJRNxvI/E39qu1sD0OtWI3OC0XgKSmcWwziwYuZw==", - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.1.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/timers-browserify": { - "version": "2.0.12", - "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.12.tgz", - "integrity": "sha512-9phl76Cqm6FhSX9Xe1ZUAMLtm1BLkKj2Qd5ApyWkXzsMRaA7dgr81kf4wJmQf/hAvg8EEyJxDo3du/0KlhPiKQ==", - "dependencies": { - "setimmediate": "^1.0.4" - }, - "engines": { - "node": ">=0.6.0" - } - }, - "node_modules/tty-browserify": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.1.tgz", - "integrity": "sha512-C3TaO7K81YvjCgQH9Q1S3R3P3BtN3RIM8n+OvX4il1K1zgE8ZhI0op7kClgkxtutIE8hQrcrHBXvIheqKUUCxw==" - }, - "node_modules/unbox-primitive": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.1.tgz", - "integrity": "sha512-tZU/3NqK3dA5gpE1KtyiJUrEB0lxnGkMFHptJ7q6ewdZ8s12QrODwNbhIJStmJkd1QDXa1NRA8aF2A1zk/Ypyw==", - "dependencies": { - "function-bind": "^1.1.1", - "has-bigints": "^1.0.1", - "has-symbols": "^1.0.2", - "which-boxed-primitive": "^1.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/url": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", - "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", - "dependencies": { - "punycode": "1.3.2", - "querystring": "0.2.0" - } - }, - "node_modules/url/node_modules/punycode": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", - "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" - }, - "node_modules/util": { - "version": "0.12.4", - "resolved": "https://registry.npmjs.org/util/-/util-0.12.4.tgz", - "integrity": "sha512-bxZ9qtSlGUWSOy9Qa9Xgk11kSslpuZwaxCg4sNIDj6FLucDab2JxnHwyNTCpHMtK1MjoQiWQ6DiUMZYbSrO+Sw==", - "dependencies": { - "inherits": "^2.0.3", - "is-arguments": "^1.0.4", - "is-generator-function": "^1.0.7", - "is-typed-array": "^1.1.3", - "safe-buffer": "^5.1.2", - "which-typed-array": "^1.1.2" - } - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" - }, - "node_modules/vm-browserify": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", - "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==" - }, - "node_modules/which-boxed-primitive": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", - "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", - "dependencies": { - "is-bigint": "^1.0.1", - "is-boolean-object": "^1.1.0", - "is-number-object": "^1.0.4", - "is-string": "^1.0.5", - "is-symbol": "^1.0.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/which-typed-array": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.7.tgz", - "integrity": "sha512-vjxaB4nfDqwKI0ws7wZpxIlde1XrLX5uB0ZjpfshgmapJMD7jJWhZI+yToJTqaFByF0eNBcYxbjmCzoRP7CfEw==", - "dependencies": { - "available-typed-arrays": "^1.0.5", - "call-bind": "^1.0.2", - "es-abstract": "^1.18.5", - "foreach": "^2.0.5", - "has-tostringtag": "^1.0.0", - "is-typed-array": "^1.1.7" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/xtend": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", - "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", - "engines": { - "node": ">=0.4" - } - } - }, "dependencies": { "asn1.js": { "version": "5.4.1", @@ -1478,9 +312,137 @@ "integrity": "sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw=" }, "esbuild": { - "version": "0.12.25", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.12.25.tgz", - "integrity": "sha512-woie0PosbRSoN8gQytrdCzUbS2ByKgO8nD1xCZkEup3D9q92miCze4PqEI9TZDYAuwn6CruEnQpJxgTRWdooAg==" + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.14.11.tgz", + "integrity": "sha512-xZvPtVj6yecnDeFb3KjjCM6i7B5TCAQZT77kkW/CpXTMnd6VLnRPKrUB1XHI1pSq6a4Zcy3BGueQ8VljqjDGCg==", + "requires": { + "esbuild-android-arm64": "0.14.11", + "esbuild-darwin-64": "0.14.11", + "esbuild-darwin-arm64": "0.14.11", + "esbuild-freebsd-64": "0.14.11", + "esbuild-freebsd-arm64": "0.14.11", + "esbuild-linux-32": "0.14.11", + "esbuild-linux-64": "0.14.11", + "esbuild-linux-arm": "0.14.11", + "esbuild-linux-arm64": "0.14.11", + "esbuild-linux-mips64le": "0.14.11", + "esbuild-linux-ppc64le": "0.14.11", + "esbuild-linux-s390x": "0.14.11", + "esbuild-netbsd-64": "0.14.11", + "esbuild-openbsd-64": "0.14.11", + "esbuild-sunos-64": "0.14.11", + "esbuild-windows-32": "0.14.11", + "esbuild-windows-64": "0.14.11", + "esbuild-windows-arm64": "0.14.11" + } + }, + "esbuild-android-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.14.11.tgz", + "integrity": "sha512-6iHjgvMnC/SzDH8TefL+/3lgCjYWwAd1LixYfmz/TBPbDQlxcuSkX0yiQgcJB9k+ibZ54yjVXziIwGdlc+6WNw==", + "optional": true + }, + "esbuild-darwin-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.14.11.tgz", + "integrity": "sha512-olq84ikh6TiBcrs3FnM4eR5VPPlcJcdW8BnUz/lNoEWYifYQ+Po5DuYV1oz1CTFMw4k6bQIZl8T3yxL+ZT2uvQ==", + "optional": true + }, + "esbuild-darwin-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.11.tgz", + "integrity": "sha512-Jj0ieWLREPBYr/TZJrb2GFH8PVzDqiQWavo1pOFFShrcmHWDBDrlDxPzEZ67NF/Un3t6sNNmeI1TUS/fe1xARg==", + "optional": true + }, + "esbuild-freebsd-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.11.tgz", + "integrity": "sha512-C5sT3/XIztxxz/zwDjPRHyzj/NJFOnakAanXuyfLDwhwupKPd76/PPHHyJx6Po6NI6PomgVp/zi6GRB8PfrOTA==", + "optional": true + }, + "esbuild-freebsd-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.11.tgz", + "integrity": "sha512-y3Llu4wbs0bk4cwjsdAtVOesXb6JkdfZDLKMt+v1U3tOEPBdSu6w8796VTksJgPfqvpX22JmPLClls0h5p+L9w==", + "optional": true + }, + "esbuild-linux-32": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.14.11.tgz", + "integrity": "sha512-Cg3nVsxArjyLke9EuwictFF3Sva+UlDTwHIuIyx8qpxRYAOUTmxr2LzYrhHyTcGOleLGXUXYsnUVwKqnKAgkcg==", + "optional": true + }, + "esbuild-linux-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.11.tgz", + "integrity": "sha512-oeR6dIrrojr8DKVrxtH3xl4eencmjsgI6kPkDCRIIFwv4p+K7ySviM85K66BN01oLjzthpUMvBVfWSJkBLeRbg==", + "optional": true + }, + "esbuild-linux-arm": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.14.11.tgz", + "integrity": "sha512-vcwskfD9g0tojux/ZaTJptJQU3a7YgTYsptK1y6LQ/rJmw7U5QJvboNawqM98Ca3ToYEucfCRGbl66OTNtp6KQ==", + "optional": true + }, + "esbuild-linux-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.11.tgz", + "integrity": "sha512-+e6ZCgTFQYZlmg2OqLkg1jHLYtkNDksxWDBWNtI4XG4WxuOCUErLqfEt9qWjvzK3XBcCzHImrajkUjO+rRkbMg==", + "optional": true + }, + "esbuild-linux-mips64le": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.11.tgz", + "integrity": "sha512-Rrs99L+p54vepmXIb87xTG6ukrQv+CzrM8eoeR+r/OFL2Rg8RlyEtCeshXJ2+Q66MXZOgPJaokXJZb9snq28bw==", + "optional": true + }, + "esbuild-linux-ppc64le": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.11.tgz", + "integrity": "sha512-JyzziGAI0D30Vyzt0HDihp4s1IUtJ3ssV2zx9O/c+U/dhUHVP2TmlYjzCfCr2Q6mwXTeloDcLS4qkyvJtYptdQ==", + "optional": true + }, + "esbuild-linux-s390x": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.11.tgz", + "integrity": "sha512-DoThrkzunZ1nfRGoDN6REwmo8ZZWHd2ztniPVIR5RMw/Il9wiWEYBahb8jnMzQaSOxBsGp0PbyJeVLTUatnlcw==", + "optional": true + }, + "esbuild-netbsd-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.11.tgz", + "integrity": "sha512-12luoRQz+6eihKYh1zjrw0CBa2aw3twIiHV/FAfjh2NEBDgJQOY4WCEUEN+Rgon7xmLh4XUxCQjnwrvf8zhACw==", + "optional": true + }, + "esbuild-openbsd-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.11.tgz", + "integrity": "sha512-l18TZDjmvwW6cDeR4fmizNoxndyDHamGOOAenwI4SOJbzlJmwfr0jUgjbaXCUuYVOA964siw+Ix+A+bhALWg8Q==", + "optional": true + }, + "esbuild-sunos-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.14.11.tgz", + "integrity": "sha512-bmYzDtwASBB8c+0/HVOAiE9diR7+8zLm/i3kEojUH2z0aIs6x/S4KiTuT5/0VKJ4zk69kXel1cNWlHBMkmavQg==", + "optional": true + }, + "esbuild-windows-32": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.14.11.tgz", + "integrity": "sha512-J1Ys5hMid8QgdY00OBvIolXgCQn1ARhYtxPnG6ESWNTty3ashtc4+As5nTrsErnv8ZGUcWZe4WzTP/DmEVX1UQ==", + "optional": true + }, + "esbuild-windows-64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.14.11.tgz", + "integrity": "sha512-h9FmMskMuGeN/9G9+LlHPAoiQk9jlKDUn9yA0MpiGzwLa82E7r1b1u+h2a+InprbSnSLxDq/7p5YGtYVO85Mlg==", + "optional": true + }, + "esbuild-windows-arm64": { + "version": "0.14.11", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.11.tgz", + "integrity": "sha512-dZp7Krv13KpwKklt9/1vBFBMqxEQIO6ri7Azf8C+ob4zOegpJmha2XY9VVWP/OyQ0OWk6cEeIzMJwInRZrzBUQ==", + "optional": true }, "events": { "version": "3.3.0", @@ -1923,14 +885,6 @@ "xtend": "^4.0.2" } }, - "string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "requires": { - "safe-buffer": "~5.2.0" - } - }, "string.prototype.trimend": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.4.tgz", @@ -1949,6 +903,14 @@ "define-properties": "^1.1.3" } }, + "string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "requires": { + "safe-buffer": "~5.2.0" + } + }, "timers-browserify": { "version": "2.0.12", "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.12.tgz", diff --git a/src/options.zig b/src/options.zig index 20b2d02ae..48fa6c0c5 100644 --- a/src/options.zig +++ b/src/options.zig @@ -440,10 +440,12 @@ pub const Platform = enum { const mjs = Extensions.Out.JavaScript[1]; if (platform == .node) { + exts.ensureTotalCapacity(Extensions.In.JavaScript.len * 2) catch unreachable; for (Extensions.In.JavaScript) |ext| { exts.put(ext, mjs) catch unreachable; } } else { + exts.ensureTotalCapacity(Extensions.In.JavaScript.len + 1) catch unreachable; exts.put(mjs, js) catch unreachable; } @@ -963,9 +965,9 @@ pub const BundleOptions = struct { hot_module_reloading: bool = false, inject: ?[]string = null, origin: URL = URL{}, - - output_dir: string = "", output_dir_handle: ?std.fs.Dir = null, + + output_dir: string = "out", node_modules_bundle_url: string = "", node_modules_bundle_pretty_path: string = "", @@ -1088,13 +1090,12 @@ pub const BundleOptions = struct { transform: Api.TransformOptions, node_modules_bundle_existing: ?*NodeModuleBundle, ) !BundleOptions { - const output_dir_parts = [_]string{ try std.process.getCwdAlloc(allocator), transform.output_dir orelse "out" }; var opts: BundleOptions = BundleOptions{ .log = log, .resolve_mode = transform.resolve orelse .dev, .define = undefined, .loaders = try loadersFromTransformOptions(allocator, transform.loaders), - .output_dir = try fs.absAlloc(allocator, &output_dir_parts), + .output_dir = transform.output_dir orelse "out", .platform = Platform.from(transform.platform), .write = transform.write orelse false, .external = undefined, diff --git a/src/report.zig b/src/report.zig index 400a4dc41..571eca0e7 100644 --- a/src/report.zig +++ b/src/report.zig @@ -18,9 +18,89 @@ const CrashReporter = @import("crash_reporter"); const Report = @This(); +var crash_report_writer: CrashReportWriter = CrashReportWriter{ .file = null }; var crash_reporter_path: [1024]u8 = undefined; +pub const CrashReportWriter = struct { + file: ?std.io.BufferedWriter(4096, std.fs.File.Writer) = null, + file_path: []const u8 = "", + + pub fn printFrame(_: ?*anyopaque, frame: CrashReporter.StackFrame) void { + const function_name = if (frame.function_name.len > 0) frame.function_name else "[function ?]"; + const filename = if (frame.filename.len > 0) frame.function_name else "[file ?]"; + crash_report_writer.print("[{d}] - <b>{s}<r> {s}:{d}\n", .{ frame.pc, function_name, filename, frame.line_number }); + } + + pub fn dump() void { + CrashReporter.print(); + } + + pub fn done() void { + CrashReporter.print(); + } + + pub fn print(this: *CrashReportWriter, comptime fmt: string, args: anytype) void { + Output.prettyError(fmt, args); + if (this.file) |*file| { + var writer = file.writer(); + writer.print(comptime Output.prettyFmt(fmt, false), args) catch {}; + } + } + + pub fn flush(this: *CrashReportWriter) void { + if (this.file) |*file| { + file.flush() catch {}; + } + Output.flush(); + } + + pub fn generateFile(this: *CrashReportWriter) void { + if (this.file != null) return; + + var base_dir: []const u8 = "."; + if (std.os.getenv("BUN_INSTALL")) |install_dir| { + base_dir = std.mem.trimRight(u8, install_dir, std.fs.path.sep_str); + } else if (std.os.getenv("HOME")) |home_dir| { + base_dir = std.mem.trimRight(u8, home_dir, std.fs.path.sep_str); + } + const file_path = std.fmt.bufPrintZ( + &crash_reporter_path, + "{s}/.bun-crash/v{s}-{d}.crash", + .{ base_dir, Global.package_json_version, @intCast(u64, @maximum(std.time.milliTimestamp(), 0)) }, + ) catch return; + + std.fs.cwd().makeDir(std.fs.path.dirname(std.mem.span(file_path)).?) catch {}; + var file = std.fs.cwd().createFileZ(file_path, .{ .truncate = true }) catch return; + this.file = std.io.bufferedWriter( + file.writer(), + ); + this.file_path = std.mem.span(file_path); + } + + pub fn printPath(this: *CrashReportWriter) void { + var display_path = this.file_path; + + if (this.file_path.len > 0) { + var tilda = false; + if (std.os.getenv("HOME")) |home_dir| { + if (strings.hasPrefix(display_path, home_dir)) { + display_path = display_path[home_dir.len..]; + tilda = true; + } + } + + if (tilda) { + Output.prettyError("Crash report saved to:\n <b>~/{s}<r>\n", .{this.file_path}); + } else { + Output.prettyError("Crash report saved to:\n <b>{s}<r>\n", .{this.file_path}); + } + } + } +}; + pub fn printMetadata() void { @setCold(true); + crash_report_writer.generateFile(); + const cmd_label: string = if (CLI.cmd) |tag| @tagName(tag) else "Unknown"; const platform = if (Environment.isMac) "macOS" else "Linux"; @@ -29,7 +109,7 @@ pub fn printMetadata() void { else "x64"; - Output.prettyError( + crash_report_writer.print( \\ \\<r>–––– bun meta –––– ++ "\nBun v" ++ Global.package_json_version ++ " " ++ platform ++ " " ++ arch ++ "\n" ++ @@ -42,7 +122,7 @@ pub fn printMetadata() void { const http_count = HTTP.active_requests_count.loadUnchecked(); if (http_count > 0) - Output.prettyError( + crash_report_writer.print( \\HTTP: {d} \\ , .{http_count}); @@ -67,7 +147,7 @@ pub fn printMetadata() void { &peak_commit, &page_faults, ); - Output.prettyError("Elapsed: {d}ms | User: {d}ms | Sys: {d}ms\nRSS: {:<3.2} | Peak: {:<3.2} | Commit: {:<3.2} | Faults: {d}\n", .{ + crash_report_writer.print("Elapsed: {d}ms | User: {d}ms | Sys: {d}ms\nRSS: {:<3.2} | Peak: {:<3.2} | Commit: {:<3.2} | Faults: {d}\n", .{ elapsed_msecs, user_msecs, system_msecs, @@ -78,7 +158,7 @@ pub fn printMetadata() void { }); } - Output.prettyError("–––– bun meta ––––\n", .{}); + crash_report_writer.print("–––– bun meta ––––\n", .{}); } var has_printed_fatal = false; var has_printed_crash = false; @@ -86,15 +166,16 @@ pub fn fatal(err_: ?anyerror, msg_: ?string) void { const had_printed_fatal = has_printed_fatal; if (!has_printed_fatal) { has_printed_fatal = true; + crash_report_writer.generateFile(); if (err_) |err| { if (Output.isEmojiEnabled()) { - Output.prettyError( + crash_report_writer.print( "\n<r><red>error<r><d>:<r> <b>{s}<r>\n", .{@errorName(err)}, ); } else { - Output.prettyError( + crash_report_writer.print( "\n<r>error: {s}\n\n", .{@errorName(err)}, ); @@ -108,12 +189,12 @@ pub fn fatal(err_: ?anyerror, msg_: ?string) void { if (len > 0) { if (Output.isEmojiEnabled()) { - Output.prettyError( + crash_report_writer.print( "\n<r><red>uh-oh<r><d>:<r> <b>{s}<r>\n", .{msg[0..len]}, ); } else { - Output.prettyError( + crash_report_writer.print( "\n<r>an uh-oh: {s}\n\n", .{msg[0..len]}, ); @@ -125,52 +206,70 @@ pub fn fatal(err_: ?anyerror, msg_: ?string) void { if (err_ == null) { if (Output.isEmojiEnabled()) { if (msg_ == null and err_ == null) { - Output.prettyError("<r><red>", .{}); + crash_report_writer.print("<r><red>", .{}); } else { - Output.prettyError("<r>", .{}); + crash_report_writer.print("<r>", .{}); } - Output.prettyErrorln("bun will crash now<r> 😭😭😭\n", .{}); + crash_report_writer.print("bun will crash now<r> 😭😭😭\n", .{}); } else { - Output.printError("bun has crashed :'(\n", .{}); + crash_report_writer.print("bun has crashed :'(\n", .{}); } } - Output.flush(); + crash_report_writer.flush(); printMetadata(); - Output.flush(); - } - - // It only is a real crash report if it's not coming from Zig - if (err_ == null and msg_ == null and !has_printed_crash) { - var path = CrashReporter.crashReportPath(&crash_reporter_path); + crash_report_writer.flush(); - if (path.len > 0) { - has_printed_crash = true; + // It only is a real crash report if it's not coming from Zig - if (std.os.getenvZ("HOME")) |home| { - if (strings.hasPrefix(path, home) and home.len > 1) { - crash_reporter_path[home.len - 1] = '~'; - crash_reporter_path[home.len] = '/'; - path = path[home.len - 1 ..]; - } - } - Output.prettyErrorln("Crash report saved to:\n {s}\n", .{path}); - if (!had_printed_fatal) Output.prettyError("Ask for #help in https://bun.sh/discord or go to https://bun.sh/issues. Please include the crash report. \n\n", .{}); - Output.flush(); + CrashReportWriter.dump(); + crash_report_writer.flush(); - std.os.exit(1); - } + crash_report_writer.printPath(); } if (!had_printed_fatal) { - Output.prettyError("\nAsk for #help in https://bun.sh/discord or go to https://bun.sh/issues\n\n", .{}); - Output.flush(); + crash_report_writer.print("\nAsk for #help in https://bun.sh/discord or go to https://bun.sh/issues\n\n", .{}); + crash_report_writer.flush(); } } var globalError_ranOnce = false; +pub noinline fn handleCrash(signal: i32, addr: usize) void { + const had_printed_fatal = has_printed_fatal; + if (has_printed_fatal) return; + has_printed_fatal = true; + + crash_report_writer.generateFile(); + + const name = switch (signal) { + std.os.SIG.SEGV => error.SegmentationFault, + std.os.SIG.ILL => error.InstructionError, + std.os.SIG.BUS => error.BusError, + else => error.Crash, + }; + + crash_report_writer.print("\n<r><red>{s}<d> at {d}\n\n", .{ @errorName(name), addr }); + printMetadata(); + CrashReportWriter.dump(); + + if (!had_printed_fatal) { + crash_report_writer.print("\nAsk for #help in https://bun.sh/discord or go to https://bun.sh/issues\n\n", .{}); + } + crash_report_writer.flush(); + + if (crash_report_writer.file) |file| { + // don't handle return codes here + _ = std.os.system.close(file.unbuffered_writer.context.handle); + } + + crash_report_writer.file = null; + + std.c._exit(128 + @truncate(u8, @intCast(u8, @maximum(signal, 0)))); +} + pub noinline fn globalError(err: anyerror) noreturn { @setCold(true); @@ -179,6 +278,23 @@ pub noinline fn globalError(err: anyerror) noreturn { } switch (err) { + error.SyntaxError => { + Output.prettyError( + "\n<r><red>SyntaxError<r><d>:<r> An error occurred while parsing code", + .{}, + ); + Output.flush(); + std.os.exit(1); + }, + error.OutOfMemory => { + Output.prettyError( + "\n<r><red>OutOfMemory<r><d>:<r> There might be an infinite loop somewhere", + .{}, + ); + printMetadata(); + Output.flush(); + std.os.exit(1); + }, error.CurrentWorkingDirectoryUnlinked => { Output.prettyError( "\n<r><red>error: <r>The current working directory was deleted, so that command didn't work. Please cd into a different directory and try again.", diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig index 0aa5a3b31..7e053a3ff 100644 --- a/src/resolver/resolver.zig +++ b/src/resolver/resolver.zig @@ -1630,8 +1630,9 @@ pub const Resolver = struct { } if (needs_iter) { + const allocator = r.fs.allocator; dir_entries_option = try rfs.entries.put(&cached_dir_entry_result, .{ - .entries = Fs.FileSystem.DirEntry.init(dir_path, r.fs.allocator), + .entries = Fs.FileSystem.DirEntry.init(dir_path), }); if (FeatureFlags.store_file_descriptors) { @@ -1640,7 +1641,7 @@ pub const Resolver = struct { } var dir_iterator = open_dir.iterate(); while (try dir_iterator.next()) |_value| { - dir_entries_option.entries.addEntry(_value) catch unreachable; + dir_entries_option.entries.addEntry(_value, allocator, void, void{}) catch unreachable; } } diff --git a/src/string_immutable.zig b/src/string_immutable.zig index 368e245f2..160242fbb 100644 --- a/src/string_immutable.zig +++ b/src/string_immutable.zig @@ -363,6 +363,7 @@ pub fn eqlComptimeIgnoreLen(self: string, comptime alt: anytype) bool { } inline fn eqlComptimeCheckLen(a: string, comptime b: anytype, comptime check_len: bool) bool { + @setEvalBranchQuota(9999); if (comptime check_len) { if (comptime b.len == 0) { return a.len == 0; @@ -515,6 +516,10 @@ pub fn eqlUtf16(comptime self: string, other: []const u16) bool { } pub fn toUTF8Alloc(allocator: std.mem.Allocator, js: []const u16) !string { + return try toUTF8AllocWithType(allocator, []const u16, js); +} + +pub fn toUTF8AllocWithType(allocator: std.mem.Allocator, comptime Type: type, js: Type) !string { var temp: [4]u8 = undefined; var list = std.ArrayList(u8).initCapacity(allocator, js.len) catch unreachable; var i: usize = 0; @@ -668,6 +673,44 @@ pub inline fn decodeWTF8RuneTMultibyte(p: *const [4]u8, len: u3, comptime T: typ unreachable; } +pub fn formatUTF16(slice_: []align(1) const u16, writer: anytype) !void { + var slice = slice_; + var chunk: [512 + 4]u8 = undefined; + var chunk_i: u16 = 0; + + while (slice.len > 0) { + if (chunk_i >= chunk.len - 5) { + try writer.writeAll(chunk[0..chunk_i]); + chunk_i = 0; + } + + var cp: u32 = slice[0]; + slice = slice[1..]; + if (cp & ~@as(u32, 0x03ff) == 0xd800 and slice.len > 0) { + cp = 0x10000 + (((cp & 0x03ff) << 10) | (slice[0] & 0x03ff)); + slice = slice[1..]; + } + + chunk_i += @as( + u8, + @call( + .{ .modifier = .always_inline }, + encodeWTF8RuneT, + .{ chunk[chunk_i..][0..4], u32, cp }, + ), + ); + } + + try writer.writeAll(chunk[0..chunk_i]); +} + +test "print UTF16" { + var err = std.io.getStdErr(); + const utf16 = comptime std.unicode.utf8ToUtf16LeStringLiteral("❌ ✅ opkay "); + try formatUTF16(utf16, err.writer()); + // std.unicode.fmtUtf16le(utf16le: []const u16) +} + /// Convert potentially ill-formed UTF-8 or UTF-16 bytes to a Unicode Codepoint. /// - Invalid codepoints are replaced with `zero` parameter /// - Null bytes return 0 diff --git a/src/string_mutable.zig b/src/string_mutable.zig index 324b6661f..ad9765a26 100644 --- a/src/string_mutable.zig +++ b/src/string_mutable.zig @@ -24,8 +24,10 @@ pub const MutableString = struct { } pub fn deinit(str: *MutableString) void { - str.list.expandToCapacity(); - str.list.deinit(str.allocator); + if (str.list.capacity > 0) { + str.list.expandToCapacity(); + str.list.deinit(str.allocator); + } } pub fn growIfNeeded(self: *MutableString, amount: usize) !void { diff --git a/src/string_types.zig b/src/string_types.zig index 16fef8196..9aa0ff414 100644 --- a/src/string_types.zig +++ b/src/string_types.zig @@ -12,32 +12,60 @@ pub const PathString = packed struct { pub const use_small_path_string = @bitSizeOf(usize) - @bitSizeOf(PathIntLen) >= 53; pub const PathInt = if (use_small_path_string) PathIntLen else usize; pub const PointerIntType = if (use_small_path_string) u53 else usize; - ptr: PointerIntType, - len: PathInt, + ptr: PointerIntType = 0, + len: PathInt = 0, - pub inline fn slice(this: PathString) string { + const JSC = @import("./jsc.zig"); + pub fn fromJS(value: JSC.JSValue, global: *JSC.JSGlobalObject, exception: JSC.C.ExceptionRef) PathString { + if (!value.jsType().isStringLike()) { + JSC.JSError(JSC.getAllocator(global.ref()), "Only path strings are supported for now", .{}, global.ref(), exception); + return PathString{}; + } + var zig_str = JSC.ZigString.init(""); + value.toZigString(&zig_str, global); + + return PathString.init(zig_str.slice()); + } + + pub inline fn asRef(this: PathString) JSC.JSValueRef { + return this.toValue().asObjectRef(); + } + + pub fn toJS(this: PathString, ctx: JSC.C.JSContextRef, _: JSC.C.ExceptionRef) JSC.C.JSValueRef { + var zig_str = JSC.ZigString.init(this.slice()); + zig_str.detectEncoding(); + + return zig_str.toValueAuto(ctx.ptr()).asObjectRef(); + } + + pub inline fn slice(this: anytype) string { @setRuntimeSafety(false); // "cast causes pointer to be null" is fine here. if it is null, the len will be 0. return @intToPtr([*]u8, @intCast(usize, this.ptr))[0..this.len]; } - pub inline fn init(str: string) PathString { + pub inline fn sliceAssumeZ(this: anytype) stringZ { + @setRuntimeSafety(false); // "cast causes pointer to be null" is fine here. if it is null, the len will be 0. + return @intToPtr([*:0]u8, @intCast(usize, this.ptr))[0..this.len]; + } + + pub inline fn init(str: string) @This() { @setRuntimeSafety(false); // "cast causes pointer to be null" is fine here. if it is null, the len will be 0. - return PathString{ + return @This(){ .ptr = @truncate(PointerIntType, @ptrToInt(str.ptr)), .len = @truncate(PathInt, str.len), }; } - pub inline fn isEmpty(this: PathString) bool { + pub inline fn isEmpty(this: anytype) bool { return this.len == 0; } - pub const empty = PathString{ .ptr = 0, .len = 0 }; + pub const empty = @This(){ .ptr = 0, .len = 0 }; comptime { - if (use_small_path_string and @bitSizeOf(PathString) != 64) { + if (use_small_path_string and @bitSizeOf(@This()) != 64) { @compileError("PathString must be 64 bits"); - } else if (!use_small_path_string and @bitSizeOf(PathString) != 128) { + } else if (!use_small_path_string and @bitSizeOf(@This()) != 128) { @compileError("PathString must be 128 bits"); } } |