Compare commits

..

4 Commits

Author SHA1 Message Date
Ashcon Partovi
e5b773922a Remove latest tag from canary Docker workflow 2023-09-26 16:38:09 -07:00
Ashcon Partovi
d77dd4a75a Update docker workflow 2023-09-26 16:32:43 -07:00
Ashcon Partovi
8031786f56 Add alpine and distroless images 2023-09-26 16:32:43 -07:00
Ashcon Partovi
5f86413b2c Improve Docker images 2023-09-26 16:32:43 -07:00
368 changed files with 3939 additions and 25429 deletions

View File

@@ -0,0 +1,50 @@
name: bun-ecosystem-test
on:
schedule:
- cron: "0 15 * * *" # every day at 7am PST
workflow_dispatch:
inputs:
version:
description: "The version of Bun to run"
required: true
default: "canary"
type: string
jobs:
test:
name: ${{ matrix.tag }}
runs-on: ${{ matrix.os }}
if: github.repository_owner == 'oven-sh'
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
tag: linux-x64
url: linux/x64?avx2=true
- os: ubuntu-latest
tag: linux-x64-baseline
url: linux/x64?baseline=true
# FIXME: runner fails with "No tests found"?
#- os: macos-latest
# tag: darwin-x64
# url: darwin/x64?avx2=true
- os: macos-latest
tag: darwin-x64-baseline
url: darwin/x64?baseline=true
steps:
- id: checkout
name: Checkout
uses: Bhacaz/checkout-files@v2
with:
files: packages/bun-internal-test
- id: setup
name: Setup
uses: oven-sh/setup-bun@v1
with:
bun-download-url: https://bun.sh/download/${{ github.event.inputs.version }}/${{ matrix.url }}
- id: test
name: Test
working-directory: packages/bun-internal-test
run: bun run test:ecosystem

View File

@@ -37,7 +37,7 @@ jobs:
arch: aarch64
build_arch: arm64
runner: linux-arm64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-linux-arm64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-linux-arm64-lto.tar.gz"
webkit_basename: "bun-webkit-linux-arm64-lto"
build_machine_arch: aarch64

View File

@@ -47,7 +47,7 @@ jobs:
arch: x86_64
build_arch: amd64
runner: big-ubuntu
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-linux-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-linux-amd64-lto.tar.gz"
webkit_basename: "bun-webkit-linux-amd64-lto"
build_machine_arch: x86_64
- cpu: nehalem
@@ -55,7 +55,7 @@ jobs:
arch: x86_64
build_arch: amd64
runner: big-ubuntu
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-linux-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-linux-amd64-lto.tar.gz"
webkit_basename: "bun-webkit-linux-amd64-lto"
build_machine_arch: x86_64
@@ -153,33 +153,13 @@ jobs:
name: "Canary (${{github.sha}})"
tag: "canary"
artifacts: "${{runner.temp}}/release/bun-${{matrix.tag}}.zip,${{runner.temp}}/release/bun-${{matrix.tag}}-profile.zip"
- uses: sarisia/actions-status-discord@v1
if: failure() && github.repository_owner == 'oven-sh' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: ${{ job.status }}
noprefix: true
nocontext: true
description: |
Pull Request
### [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
@${{ github.actor }}
Build failed on ${{ matrix.tag }}:
**[View build output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
[Commit ${{github.sha}}](https://github.com/oven-sh/bun/commits/${{github.sha}})
linux-test:
name: Tests ${{matrix.tag}}
runs-on: ubuntu-latest
needs: [linux]
if: github.event_name == 'pull_request'
timeout-minutes: 20
permissions:
pull-requests: write
outputs:
failing_tests: ${{ steps.test.outputs.failing_tests }}
failing_tests_count: ${{ steps.test.outputs.failing_tests_count }}
@@ -201,8 +181,8 @@ jobs:
with:
name: bun-${{matrix.tag}}
path: ${{runner.temp}}/release
- id: install-bun
name: Install Bun
- id: install
name: Install
run: |
cd ${{runner.temp}}/release
unzip bun-${{matrix.tag}}.zip
@@ -210,13 +190,6 @@ jobs:
chmod +x bun
pwd >> $GITHUB_PATH
./bun --version
- id: install-dependnecies
name: Install dependencies
run: |
sudo apt-get update && sudo apt-get install -y openssl
bun install --verbose
bun install --cwd=test --verbose
bun install --cwd=packages/bun-internal-test --verbose
- id: test
name: Test (node runner)
env:
@@ -225,24 +198,11 @@ jobs:
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
sudo apt-get update && sudo apt-get install -y openssl
bun install
bun install --cwd test
bun install --cwd packages/bun-internal-test
node packages/bun-internal-test/src/runner.node.mjs || true
- uses: sarisia/actions-status-discord@v1
if: always() && steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: "failure"
noprefix: true
nocontext: true
description: |
Pull Request
### ❌ [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
@${{ github.actor }}, there are ${{ steps.test.outputs.failing_tests_count }} files with test failures on ${{ matrix.tag }}:
${{ steps.test.outputs.failing_tests }}
**[View test output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
- name: Comment on PR
if: steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
uses: thollander/actions-comment-pull-request@v2

View File

@@ -117,7 +117,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-12
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
# - cpu: haswell
@@ -126,7 +126,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
# - cpu: nehalem
@@ -135,7 +135,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-12
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
# - cpu: haswell
@@ -144,7 +144,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
- cpu: native
@@ -152,7 +152,7 @@ jobs:
tag: bun-darwin-aarch64
obj: bun-obj-darwin-aarch64
artifact: bun-obj-darwin-aarch64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-arm64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-arm64-lto.tar.gz"
runner: macos-arm64
dependencies: true
compile_obj: true
@@ -258,7 +258,7 @@ jobs:
# package: bun-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: haswell
# arch: x86_64
# tag: bun-darwin-x64
@@ -266,14 +266,14 @@ jobs:
# package: bun-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
- cpu: native
arch: aarch64
tag: bun-darwin-aarch64
obj: bun-obj-darwin-aarch64
package: bun-darwin-aarch64
artifact: bun-obj-darwin-aarch64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-arm64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-arm64-lto.tar.gz"
runner: macos-arm64
steps:
- uses: actions/checkout@v3
@@ -393,32 +393,11 @@ jobs:
name: "Canary (${{github.sha}})"
tag: "canary"
artifacts: "${{runner.temp}}/release/${{matrix.tag}}.zip,${{runner.temp}}/release/${{matrix.tag}}-profile.zip"
- uses: sarisia/actions-status-discord@v1
if: failure() && github.repository_owner == 'oven-sh' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: ${{ job.status }}
noprefix: true
nocontext: true
description: |
Pull Request
### [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
@${{ github.actor }}
Build failed on ${{ matrix.tag }}:
**[View build output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
[Commit ${{github.sha}}](https://github.com/oven-sh/bun/commits/${{github.sha}})
macOS-test:
name: Tests ${{matrix.tag}}
runs-on: ${{ matrix.runner }}
needs: [macOS]
if: github.event_name == 'pull_request' && github.repository_owner == 'oven-sh'
permissions:
pull-requests: write
timeout-minutes: 30
outputs:
failing_tests: ${{ steps.test.outputs.failing_tests }}
@@ -441,8 +420,8 @@ jobs:
with:
name: ${{matrix.tag}}
path: ${{runner.temp}}/release
- id: install-bun
name: Install Bun
- id: install
name: Install
run: |
cd ${{runner.temp}}/release
unzip ${{matrix.tag}}.zip
@@ -450,12 +429,6 @@ jobs:
chmod +x bun
pwd >> $GITHUB_PATH
./bun --version
- id: install
name: Install dependencies
run: |
bun install --verbose
bun install --cwd=test --verbose
bun install --cwd=packages/bun-internal-test --verbose
- id: test
name: Test (node runner)
env:
@@ -464,24 +437,10 @@ jobs:
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
bun install
bun install --cwd test
bun install --cwd packages/bun-internal-test
node packages/bun-internal-test/src/runner.node.mjs || true
- uses: sarisia/actions-status-discord@v1
if: always() && steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: "failure"
noprefix: true
nocontext: true
description: |
Pull Request
### ❌ [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
@${{ github.actor }}, there are ${{ steps.test.outputs.failing_tests_count }} files with test failures on ${{ matrix.tag }}:
${{ steps.test.outputs.failing_tests }}
**[View test output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
- name: Comment on PR
if: steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
uses: thollander/actions-comment-pull-request@v2

View File

@@ -117,7 +117,7 @@ jobs:
obj: bun-obj-darwin-x64-baseline
runner: macos-12
artifact: bun-obj-darwin-x64-baseline
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: true
compile_obj: false
# - cpu: haswell
@@ -126,7 +126,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
- cpu: nehalem
@@ -135,7 +135,7 @@ jobs:
obj: bun-obj-darwin-x64-baseline
runner: macos-12
artifact: bun-obj-darwin-x64-baseline
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: false
compile_obj: true
# - cpu: haswell
@@ -144,7 +144,7 @@ jobs:
# obj: bun-obj-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
# - cpu: native
@@ -152,7 +152,7 @@ jobs:
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# runner: macos-arm64
# dependencies: true
# compile_obj: true
@@ -259,7 +259,7 @@ jobs:
package: bun-darwin-x64
runner: macos-12
artifact: bun-obj-darwin-x64-baseline
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: haswell
# arch: x86_64
# tag: bun-darwin-x64
@@ -267,14 +267,14 @@ jobs:
# package: bun-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: native
# arch: aarch64
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# package: bun-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# runner: macos-arm64
steps:
- uses: actions/checkout@v3
@@ -397,32 +397,11 @@ jobs:
name: "Canary (${{github.sha}})"
tag: "canary"
artifacts: "${{runner.temp}}/release/${{matrix.tag}}.zip,${{runner.temp}}/release/${{matrix.tag}}-profile.zip"
- uses: sarisia/actions-status-discord@v1
if: failure() && github.repository_owner == 'oven-sh' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: ${{ job.status }}
noprefix: true
nocontext: true
description: |
Pull Request
### [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
@${{ github.actor }}
Build failed on ${{ matrix.tag }}:
**[View build output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
[Commit ${{github.sha}}](https://github.com/oven-sh/bun/commits/${{github.sha}})
macOS-test:
name: Tests ${{matrix.tag}}
runs-on: ${{ matrix.runner }}
needs: [macOS]
if: github.event_name == 'pull_request' && github.repository_owner == 'oven-sh'
permissions:
pull-requests: write
timeout-minutes: 30
outputs:
failing_tests: ${{ steps.test.outputs.failing_tests }}
@@ -445,8 +424,8 @@ jobs:
with:
name: ${{matrix.tag}}
path: ${{runner.temp}}/release
- id: install-bun
name: Install Bun
- id: install
name: Install
run: |
cd ${{runner.temp}}/release
unzip ${{matrix.tag}}.zip
@@ -454,12 +433,6 @@ jobs:
chmod +x bun
pwd >> $GITHUB_PATH
./bun --version
- id: install
name: Install dependencies
run: |
bun install --verbose
bun install --cwd=test --verbose
bun install --cwd=packages/bun-internal-test --verbose
- id: test
name: Test (node runner)
env:
@@ -468,27 +441,10 @@ jobs:
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
bun install
bun install --cwd test
bun install --cwd packages/bun-internal-test
node packages/bun-internal-test/src/runner.node.mjs || true
- uses: sarisia/actions-status-discord@v1
if: always() && steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: "failure"
noprefix: true
nocontext: true
description: |
Pull Request
### ❌ [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
Hey @${{ github.actor }},
${{ steps.test.outputs.failing_tests_count }} files with test failures on ${{ matrix.tag }}:
${{ steps.test.outputs.failing_tests }}
**[View test output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
- name: Comment on PR
if: steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
uses: thollander/actions-comment-pull-request@v2

View File

@@ -117,7 +117,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-12
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: true
# compile_obj: false
- cpu: haswell
@@ -126,7 +126,7 @@ jobs:
obj: bun-obj-darwin-x64
runner: macos-12
artifact: bun-obj-darwin-x64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: true
compile_obj: false
# - cpu: nehalem
@@ -135,7 +135,7 @@ jobs:
# obj: bun-obj-darwin-x64-baseline
# runner: macos-12
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# dependencies: false
# compile_obj: true
- cpu: haswell
@@ -144,7 +144,7 @@ jobs:
obj: bun-obj-darwin-x64
runner: macos-12
artifact: bun-obj-darwin-x64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
dependencies: false
compile_obj: true
# - cpu: native
@@ -152,7 +152,7 @@ jobs:
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-arm64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-arm64-lto.tar.gz"
# runner: macos-arm64
# dependencies: true
# compile_obj: true
@@ -261,7 +261,7 @@ jobs:
# package: bun-darwin-x64
# runner: macos-12
# artifact: bun-obj-darwin-x64-baseline
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
- cpu: haswell
arch: x86_64
tag: bun-darwin-x64
@@ -269,14 +269,14 @@ jobs:
package: bun-darwin-x64
runner: macos-12
artifact: bun-obj-darwin-x64
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-amd64-lto.tar.gz"
webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-amd64-lto.tar.gz"
# - cpu: native
# arch: aarch64
# tag: bun-darwin-aarch64
# obj: bun-obj-darwin-aarch64
# package: bun-darwin-aarch64
# artifact: bun-obj-darwin-aarch64
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-oct3/bun-webkit-macos-arm64-lto.tar.gz"
# webkit_url: "https://github.com/oven-sh/WebKit/releases/download/2023-sept15-1/bun-webkit-macos-arm64-lto.tar.gz"
# runner: macos-arm64
steps:
- uses: actions/checkout@v3
@@ -399,32 +399,11 @@ jobs:
name: "Canary (${{github.sha}})"
tag: "canary"
artifacts: "${{runner.temp}}/release/${{matrix.tag}}.zip,${{runner.temp}}/release/${{matrix.tag}}-profile.zip"
- uses: sarisia/actions-status-discord@v1
if: failure() && github.repository_owner == 'oven-sh' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: ${{ job.status }}
noprefix: true
nocontext: true
description: |
Pull Request
### [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
@${{ github.actor }}
Build failed on ${{ matrix.tag }}:
**[View build output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
[Commit ${{github.sha}}](https://github.com/oven-sh/bun/commits/${{github.sha}})
macOS-test:
name: Tests ${{matrix.tag}}
runs-on: ${{ matrix.runner }}
needs: [macOS]
if: github.event_name == 'pull_request' && github.repository_owner == 'oven-sh'
permissions:
pull-requests: write
timeout-minutes: 30
outputs:
failing_tests: ${{ steps.test.outputs.failing_tests }}
@@ -447,8 +426,8 @@ jobs:
with:
name: ${{matrix.tag}}
path: ${{runner.temp}}/release
- id: install-bun
name: Install Bun
- id: install
name: Install
run: |
cd ${{runner.temp}}/release
unzip ${{matrix.tag}}.zip
@@ -456,12 +435,6 @@ jobs:
chmod +x bun
pwd >> $GITHUB_PATH
./bun --version
- id: install
name: Install dependencies
run: |
bun install --verbose
bun install --cwd=test --verbose
bun install --cwd=packages/bun-internal-test --verbose
- id: test
name: Test (node runner)
env:
@@ -470,24 +443,10 @@ jobs:
TLS_POSTGRES_DATABASE_URL: ${{ secrets.TLS_POSTGRES_DATABASE_URL }}
# if: ${{github.event.inputs.use_bun == 'false'}}
run: |
bun install
bun install --cwd test
bun install --cwd packages/bun-internal-test
node packages/bun-internal-test/src/runner.node.mjs || true
- uses: sarisia/actions-status-discord@v1
if: always() && steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
with:
title: ""
webhook: ${{ secrets.DISCORD_WEBHOOK }}
status: "failure"
noprefix: true
nocontext: true
description: |
Pull Request
### ❌ [${{github.event.pull_request.title}}](https://github.com/oven-sh/bun/pull/${{github.event.number}})
@${{ github.actor }}, there are ${{ steps.test.outputs.failing_tests_count }} files with test failures on ${{ matrix.tag }}:
${{ steps.test.outputs.failing_tests }}
**[View test output](https://github.com/oven-sh/bun/actions/runs/${{github.run_id}})**
- name: Comment on PR
if: steps.test.outputs.failing_tests != '' && github.event_name == 'pull_request'
uses: thollander/actions-comment-pull-request@v2

144
.github/workflows/bun-release-canary.yml vendored Normal file
View File

@@ -0,0 +1,144 @@
name: bun-release-canary
concurrency: release-canary
on:
schedule:
- cron: "0 14 * * *" # every day at 6am PST
workflow_dispatch:
jobs:
sign:
name: Sign Release
runs-on: ubuntu-latest
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-release
steps:
- id: checkout
name: Checkout
uses: actions/checkout@v3
- id: setup-gpg
name: Setup GPG
uses: crazy-max/ghaction-import-gpg@v5
with:
gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }}
passphrase: ${{ secrets.GPG_PASSPHRASE }}
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- id: bun-run
name: Sign Release
run: |
echo "$GPG_PASSPHRASE" | bun upload-assets -- "canary"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
npm:
name: Release to NPM
runs-on: ubuntu-latest
needs: sign
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-release
steps:
- id: checkout
name: Checkout
uses: actions/checkout@v3
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- id: bun-run
name: Release
run: bun upload-npm -- canary publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
docker:
name: Release to Dockerhub (${{ matrix.variant }})
runs-on: ubuntu-latest
needs: sign
if: github.repository_owner == 'oven-sh'
strategy:
matrix:
variant:
- debian
- slim
- alpine
- distroless
steps:
- id: checkout
name: Checkout
uses: actions/checkout@v3
- id: qemu
name: Setup Docker QEMU
uses: docker/setup-qemu-action@v2
- id: buildx
name: Setup Docker buildx
uses: docker/setup-buildx-action@v2
with:
platforms: linux/amd64,linux/arm64
- id: metadata
name: Setup Docker metadata
uses: docker/metadata-action@v4
with:
images: oven/bun
flavor: |
suffix=${{ matrix.variant }}
tags: canary
- id: login
name: Login to Docker
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- id: push
name: Push to Docker
uses: docker/build-push-action@v3
with:
context: ./dockerhub/${{ matrix.variant }}
platforms: linux/amd64,linux/arm64
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ${{ steps.metadata.outputs.tags }}
labels: ${{ steps.metadata.outputs.labels }}
build-args: |
BUN_VERSION=canary
s3:
name: Upload to S3
runs-on: ubuntu-latest
needs: sign
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-release
steps:
- id: checkout
name: Checkout
uses: actions/checkout@v3
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- id: bun-run
name: Release
run: bun upload-s3 -- canary
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY}}
AWS_ENDPOINT: ${{ secrets.AWS_ENDPOINT }}
AWS_BUCKET: bun

View File

@@ -0,0 +1,54 @@
name: bun-release-types-canary
concurrency: release-canary
on:
push:
branches:
- main
paths:
- "packages/bun-types/**"
workflow_dispatch:
jobs:
npm-types:
name: Release types to NPM
runs-on: ubuntu-latest
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-types
steps:
- id: checkout
name: Checkout
uses: actions/checkout@v3
- id: setup-node
name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: latest
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- id: setup-env
name: Setup Environment
run: |
SHA=$(git rev-parse --short "$GITHUB_SHA")
VERSION=$(bun --version)
TAG="${VERSION}-canary.$(date +'%Y%m%dT%H%M%S')"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- id: bun-run
name: Build
run: bun run build
env:
BUN_VERSION: ${{ env.TAG }}
- id: npm-publish
name: Release
uses: JS-DevTools/npm-publish@v1
with:
package: packages/bun-types/dist/package.json
token: ${{ secrets.NPM_TOKEN }}
tag: canary

View File

@@ -1,95 +1,87 @@
name: bun-release
concurrency: release
env:
BUN_VERSION: ${{ github.event.inputs.tag || github.event.release.tag_name || 'canary' }}
BUN_LATEST: ${{ github.event.inputs.is-latest || github.event.release.prerelease == 'false' }}
on:
release:
types:
- published
schedule:
- cron: "0 14 * * *" # every day at 6am PST
workflow_dispatch:
inputs:
is-latest:
description: Is this the latest release?
type: boolean
default: false
tag:
type: string
description: What is the release tag? (e.g. "1.0.2", "canary")
description: The tag to publish
required: true
use-docker:
description: Should Docker images be released?
type: boolean
default: false
use-npm:
description: Should npm packages be published?
type: boolean
default: false
use-homebrew:
description: Should binaries be released to Homebrew?
type: boolean
default: false
use-s3:
description: Should binaries be uploaded to S3?
type: boolean
default: false
use-types:
description: Should types be released to npm?
type: boolean
default: false
jobs:
sign:
name: Sign Release
permissions: write-all
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'oven-sh' }}
permissions:
contents: write
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-release
steps:
- name: Checkout
- id: checkout
name: Checkout
uses: actions/checkout@v3
- name: Setup GPG
- id: setup-env
name: Setup Environment
run: |
TAG="${{ github.event.inputs.tag }}"
TAG="${TAG:-"${{ github.event.release.tag_name }}"}"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- id: setup-gpg
name: Setup GPG
uses: crazy-max/ghaction-import-gpg@v5
with:
gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }}
passphrase: ${{ secrets.GPG_PASSPHRASE }}
- name: Setup Bun
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install Dependencies
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- name: Sign Release
- id: bun-run
name: Sign Release
run: |
echo "$GPG_PASSPHRASE" | bun upload-assets -- "${{ env.BUN_VERSION }}"
echo "$GPG_PASSPHRASE" | bun upload-assets -- "${{ env.TAG }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
npm:
name: Release to NPM
runs-on: ubuntu-latest
permissions: write-all
needs: sign
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.use-npm == 'true' }}
permissions:
contents: read
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-release
steps:
- name: Checkout
- id: checkout
name: Checkout
uses: actions/checkout@v3
- name: Setup Bun
- id: setup-env
name: Setup Environment
run: |
TAG="${{ github.event.inputs.tag }}"
TAG="${TAG:-"${{ github.event.release.tag_name }}"}"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install Dependencies
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- name: Release
run: bun upload-npm -- "${{ env.BUN_VERSION }}" publish
- id: bun-run
name: Release
run: bun upload-npm -- "${{ env.TAG }}" publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -97,75 +89,70 @@ jobs:
name: Release types to NPM
runs-on: ubuntu-latest
needs: sign
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.use-types == 'true' }}
permissions:
contents: read
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-types
steps:
- name: Checkout
- id: checkout
name: Checkout
uses: actions/checkout@v3
- name: Setup Node.js
- id: setup-env
name: Setup Environment
run: |
TAG="${{ github.event.inputs.tag }}"
TAG="${TAG:-"${{ github.event.release.tag_name }}"}"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- id: setup-node
name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: latest
- name: Setup Bun
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install Dependencies
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- name: Setup Tag
if: ${{ env.BUN_VERSION == 'canary' }}
run: |
VERSION=$(bun --version)
TAG="${VERSION}-canary.$(date +'%Y%m%dT%H%M%S')"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- name: Build
- id: bun-run
name: Build
run: bun run build
env:
BUN_VERSION: ${{ env.TAG || env.BUN_VERSION }}
- name: Release (canary)
if: ${{ env.BUN_VERSION == 'canary' }}
uses: JS-DevTools/npm-publish@v1
with:
package: packages/bun-types/dist/package.json
token: ${{ secrets.NPM_TOKEN }}
tag: canary
- name: Release (latest)
if: ${{ env.BUN_LATEST == 'true' }}
BUN_VERSION: ${{ env.TAG }}
- id: npm-publish
name: Release
uses: JS-DevTools/npm-publish@v1
with:
package: packages/bun-types/dist/package.json
token: ${{ secrets.NPM_TOKEN }}
docker:
name: Release to Dockerhub
name: Release to Dockerhub (${{ matrix.variant }})
runs-on: ubuntu-latest
needs: sign
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.use-docker == 'true' }}
permissions:
contents: read
if: github.repository_owner == 'oven-sh'
strategy:
fail-fast: false
matrix:
include:
- variant: debian
suffix: ''
- variant: debian
suffix: -debian
- variant: slim
suffix: -slim
dir: debian-slim
- variant: alpine
suffix: -alpine
- variant: distroless
suffix: -distroless
variant:
- debian
- slim
- alpine
- distroless
steps:
- name: Checkout
- id: checkout
name: Checkout
uses: actions/checkout@v3
- name: Setup Docker emulator
- id: environment
name: Setup Environment
run: |
TAG="${{ github.event.inputs.tag }}"
TAG="${TAG:-"${{ github.event.release.tag_name }}"}"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- id: qemu
name: Setup Docker QEMU
uses: docker/setup-qemu-action@v2
- id: buildx
name: Setup Docker buildx
@@ -178,83 +165,104 @@ jobs:
with:
images: oven/bun
flavor: |
latest=false
latest=${{ matrix.variant == 'debian' }}
suffix=${{ matrix.variant }}
tags: |
type=raw,value=latest,enable=${{ env.BUN_LATEST == 'true' && matrix.suffix == '' }}
type=raw,value=${{ matrix.variant }},enable=${{ env.BUN_LATEST == 'true' }}
type=match,pattern=(bun-v)?(canary|\d+.\d+.\d+),group=2,value=${{ env.BUN_VERSION }},suffix=${{ matrix.suffix }}
type=match,pattern=(bun-v)?(canary|\d+.\d+),group=2,value=${{ env.BUN_VERSION }},suffix=${{ matrix.suffix }}
type=match,pattern=(bun-v)?(canary|\d+),group=2,value=${{ env.BUN_VERSION }},suffix=${{ matrix.suffix }}
- name: Login to Docker
type=match,pattern=(bun-v)?(\d+.\d+.\d+),group=2,value=${{ env.TAG }}
type=match,pattern=(bun-v)?(\d+.\d+),group=2,value=${{ env.TAG }}
type=match,pattern=(bun-v)?(\d+),group=2,value=${{ env.TAG }}
- id: login
name: Login to Docker
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Push to Docker
- id: push
name: Push to Docker
uses: docker/build-push-action@v3
with:
context: ./dockerhub/${{ matrix.dir || matrix.variant }}
context: ./dockerhub/${{ matrix.variant }}
platforms: linux/amd64,linux/arm64
builder: ${{ steps.buildx.outputs.name }}
push: true
tags: ${{ steps.metadata.outputs.tags }}
labels: ${{ steps.metadata.outputs.labels }}
build-args: |
BUN_VERSION=${{ env.BUN_VERSION }}
BUN_VERSION=${{ env.TAG }}
homebrew:
name: Release to Homebrew
permissions: write-all
runs-on: ubuntu-latest
needs: sign
permissions:
contents: read
if: ${{ github.event_name == 'release' || github.event.inputs.use-homebrew == 'true' }}
if: github.repository_owner == 'oven-sh'
steps:
- name: Checkout
- id: checkout
name: Checkout
uses: actions/checkout@v3
with:
repository: oven-sh/homebrew-bun
token: ${{ secrets.ROBOBUN_TOKEN }}
- id: gpg
- id: setup-gpg
name: Setup GPG
uses: crazy-max/ghaction-import-gpg@v5
with:
gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }}
passphrase: ${{ secrets.GPG_PASSPHRASE }}
- name: Setup Ruby
- id: setup-env
name: Setup Environment
run: |
TAG="${{ github.event.inputs.tag }}"
TAG="${TAG:-"${{ github.event.release.tag_name }}"}"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- id: setup-ruby
name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: "2.6"
- name: Update Tap
run: ruby scripts/release.rb "${{ env.BUN_VERSION }}"
- name: Commit Tap
- id: update-tap
name: Update Tap
run: ruby scripts/release.rb "${{ env.TAG }}"
- id: commit-tap
name: Commit Tap
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_options: --gpg-sign=${{ steps.gpg.outputs.keyid }}
commit_message: Release ${{ env.BUN_VERSION }}
commit_options: --gpg-sign=${{ steps.setup-gpg.outputs.keyid }}
commit_message: Release ${{ env.TAG }}
commit_user_name: robobun
commit_user_email: robobun@oven.sh
commit_author: robobun <robobun@oven.sh>
s3:
name: Upload to S3
runs-on: ubuntu-latest
permissions: write-all
needs: sign
if: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.use-s3 == 'true' }}
permissions:
contents: read
if: github.repository_owner == 'oven-sh'
defaults:
run:
working-directory: packages/bun-release
steps:
- name: Checkout
- id: checkout
name: Checkout
uses: actions/checkout@v3
- name: Setup Bun
- id: setup-env
name: Setup Environment
run: |
TAG="${{ github.event.inputs.tag }}"
TAG="${TAG:-"${{ github.event.release.tag_name }}"}"
echo "Setup tag: ${TAG}"
echo "TAG=${TAG}" >> ${GITHUB_ENV}
- id: setup-bun
name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: latest
- name: Install Dependencies
bun-version: canary
- id: bun-install
name: Install Dependencies
run: bun install
- name: Release
run: bun upload-s3 -- "${{ env.BUN_VERSION }}"
- id: bun-run
name: Release
run: bun upload-s3 -- "${{ env.TAG }}"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}

View File

@@ -12,8 +12,6 @@ jobs:
prettier-fmt:
name: prettier
runs-on: ubuntu-latest
permissions:
pull-requests: write
outputs:
prettier_fmt_errs: ${{ steps.fmt.outputs.prettier_fmt_errs }}
steps:

View File

@@ -18,8 +18,6 @@ jobs:
zig-fmt:
name: zig fmt
runs-on: ubuntu-latest
permissions:
pull-requests: write
outputs:
zig_fmt_errs: ${{ steps.fmt.outputs.zig_fmt_errs }}
steps:

View File

@@ -27,8 +27,7 @@
"editor.formatOnSave": true
},
"zig.zls.enableInlayHints": false,
"zig.zls.enabled": true,
"git.ignoreSubmodules": true,
"[jsx]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
@@ -81,9 +80,7 @@
"src/deps/zstd": true,
"test/snippets/package-json-exports/_node_modules_copy": true,
"src/js/out": true,
"packages/bun-uws/fuzzing/seed-corpus/": true,
"**/*.dep": true,
"**/CMakeFiles": true
"src/packages/bun-uws/fuzzing/seed-corpus/": true
},
"C_Cpp.files.exclude": {
"**/.vscode": true,

View File

@@ -10,7 +10,7 @@ ARG ARCH=x86_64
ARG BUILD_MACHINE_ARCH=x86_64
ARG TRIPLET=${ARCH}-linux-gnu
ARG BUILDARCH=amd64
ARG WEBKIT_TAG=2023-oct3
ARG WEBKIT_TAG=2023-sept15
ARG ZIG_TAG=jul1
ARG ZIG_VERSION="0.12.0-dev.163+6780a6bbf"
ARG WEBKIT_BASENAME="bun-webkit-linux-$BUILDARCH"
@@ -286,7 +286,6 @@ COPY packages/bun-uws ${BUN_DIR}/packages/bun-uws
COPY packages/bun-usockets ${BUN_DIR}/packages/bun-usockets
COPY src/deps/zlib ${BUN_DIR}/src/deps/zlib
COPY src/deps/boringssl/include ${BUN_DIR}/src/deps/boringssl/include
COPY src/deps/c-ares/include ${BUN_DIR}/src/deps/c-ares/include
COPY src/deps/libuwsockets.cpp ${BUN_DIR}/src/deps/libuwsockets.cpp
COPY src/deps/_libusockets.h ${BUN_DIR}/src/deps/_libusockets.h

View File

@@ -31,7 +31,7 @@ Bun is an all-in-one toolkit for JavaScript and TypeScript apps. It ships as a s
At its core is the _Bun runtime_, a fast JavaScript runtime designed as a drop-in replacement for Node.js. It's written in Zig and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage.
```bash
bun run index.tsx # TS and JSX supported out-of-the-box
bun run index.tsx # TS and JSX supported out of the box
```
The `bun` command-line tool also implements a test runner, script runner, and Node.js-compatible package manager. Instead of 1,000 node_modules for development, you only need `bun`. Bun's built-in tools are significantly faster than existing options and usable in existing Node.js projects with little to no changes.

BIN
bun.lockb

Binary file not shown.

View File

@@ -74,18 +74,18 @@ RUN apk --no-cache add \
--retry 5 \
|| (echo "error: failed to download: glibc-bin v${GLIBC_VERSION}" && exit 1) \
&& mv "glibc-bin-${GLIBC_VERSION}.apk" glibc-bin.apk ;; \
aarch64) curl "https://raw.githubusercontent.com/squishyu/alpine-pkg-glibc-aarch64-bin/master/glibc-${GLIBC_VERSION_AARCH64}.apk" \
aarch64) curl "https://raw.githubusercontent.com/squishyu/alpine-pkg-glibc-aarch64-bin/master/glibc-${GLIBC_VERSION}.apk" \
-fsSLO \
--compressed \
--retry 5 \
|| (echo "error: failed to download: glibc v${GLIBC_VERSION_AARCH64}" && exit 1) \
&& mv "glibc-${GLIBC_VERSION_AARCH64}.apk" glibc.apk \
&& curl "https://raw.githubusercontent.com/squishyu/alpine-pkg-glibc-aarch64-bin/master/glibc-bin-${GLIBC_VERSION_AARCH64}.apk" \
|| (echo "error: failed to download: glibc v${GLIBC_VERSION}" && exit 1) \
&& mv "glibc-${GLIBC_VERSION}.apk" glibc.apk \
&& curl "https://raw.githubusercontent.com/squishyu/alpine-pkg-glibc-aarch64-bin/master/glibc-bin-${GLIBC_VERSION}.apk" \
-fsSLO \
--compressed \
--retry 5 \
|| (echo "error: failed to download: glibc-bin v${GLIBC_VERSION_AARCH64}" && exit 1) \
&& mv "glibc-bin-${GLIBC_VERSION_AARCH64}.apk" glibc-bin.apk ;; \
|| (echo "error: failed to download: glibc-bin v${GLIBC_VERSION}" && exit 1) \
&& mv "glibc-bin-${GLIBC_VERSION}.apk" glibc-bin.apk ;; \
*) echo "error: unsupported architecture '$arch'"; exit 1 ;; \
esac
@@ -103,7 +103,7 @@ RUN addgroup -g 1000 bun \
/tmp/glibc-bin.apk \
&& rm /tmp/glibc.apk \
&& rm /tmp/glibc-bin.apk \
&& ln -s /usr/local/bin/bun /usr/local/bin/bunx \
&& ln /usr/local/bin/bun /usr/local/bin/bunx \
&& which bun \
&& which bunx \
&& bun --version

View File

@@ -67,7 +67,7 @@ RUN groupadd bun \
--gid bun \
--shell /bin/sh \
--create-home \
&& ln -s /usr/local/bin/bun /usr/local/bin/bunx \
&& ln /usr/local/bin/bun /usr/local/bin/bunx \
&& which bun \
&& which bunx \
&& bun --version

View File

@@ -65,7 +65,7 @@ RUN groupadd bun \
--gid bun \
--shell /bin/sh \
--create-home \
&& ln -s /usr/local/bin/bun /usr/local/bin/bunx \
&& ln /usr/local/bin/bun /usr/local/bin/bunx \
&& which bun \
&& which bunx \
&& bun --version

View File

@@ -59,11 +59,9 @@ FROM gcr.io/distroless/base-nossl-debian11
COPY --from=build /usr/local/bin/bun /usr/local/bin/
# Temporarily use the `build`-stage image binaries to create a symlink:
RUN --mount=type=bind,from=build,source=/usr/bin,target=/usr/bin \
--mount=type=bind,from=build,source=/bin,target=/bin <<EOF
ln -s /usr/local/bin/bun /usr/local/bin/bunx
which bunx
EOF
# Known issue: `bunx` is not available in distroless.
#
# If `ln` is used in the build image, the size of the final
# image will be double, because of: https://github.com/oven-sh/bun/issues/5269
ENTRYPOINT ["/usr/local/bin/bun"]

View File

@@ -93,7 +93,6 @@ interface Bun {
style: "nextjs";
origin?: string;
assetPrefix?: string;
fileExtensions?: string[];
});
reload(): void;

View File

@@ -99,20 +99,6 @@ const query = db.prepare("SELECT * FROM foo WHERE bar = ?");
{% /callout %}
## WAL mode
SQLite supports [write-ahead log mode](https://www.sqlite.org/wal.html) (WAL) which dramatically improves performance, especially in situations with many concurrent writes. It's broadly recommended to enable WAL mode for most typical applications.
To enable WAL mode, run this pragma query at the beginning of your application:
```ts
db.exec("PRAGMA journal_mode = WAL;");
```
{% details summary="What is WAL mode" %}
In WAL mode, writes to the database are written directly to a separate file called the "WAL file" (write-ahead log). This file will be later integrated into the main database file. Think of it as a buffer for pending writes. Refer to the [SQLite docs](https://www.sqlite.org/wal.html) for a more detailed overview.
{% /details %}
## Statements
A `Statement` is a _prepared query_, which means it's been parsed and compiled into an efficient binary form. It can be executed multiple times in a performant way.

View File

@@ -192,7 +192,7 @@ const server = Bun.serve<{ username: string }>({
close(ws) {
const msg = `${ws.data.username} has left the chat`;
ws.unsubscribe("the-group-chat");
server.publish("the-group-chat", msg);
ws.publish("the-group-chat", msg);
},
},
});

View File

@@ -21,7 +21,7 @@ Configuring with `bunfig.toml` is optional. Bun tries to be zero configuration i
# Scope name The value can be a URL string or an object
"@mybigcompany" = { token = "123456", url = "https://registry.mybigcompany.com" }
# URL is optional and falls back to the default registry
# URL is optional and fallsback to the default registry
# The "@" in the scope is optional
mybigcompany2 = { token = "123456" }
@@ -62,9 +62,6 @@ dev = true
# Install peerDependencies (default: false)
peer = false
# Whether to use the github REST api (unauthenticated)
github.api = true
# When using `bun install -g`, install packages here
globalDir = "~/.bun/install/global"

View File

@@ -89,9 +89,6 @@ frozenLockfile = false
# equivalent to `--dry-run` flag
dryRun = false
# whether to use the github REST api (unauthenticated)
github.api = true
```
{% /details %}

View File

@@ -72,7 +72,7 @@ $ bun --watch run dev # ✔️ do this
$ bun run dev --watch # ❌ don't do this
```
Flags that occur at the end of the command will be ignored and passed through to the `"dev"` script itself.
Flags that occur at the end of the command will be ignores and passed through to the `"dev"` script itself.
{% /callout %}
### `--smol`

View File

@@ -49,7 +49,7 @@ This is useful for preventing flash of unstyled content.
## With `bun bun`
Bun bundles `.css` files imported via `@import` into a single file. It doesnt auto-prefix or minify CSS today. Multiple `.css` files imported in one JavaScript file will _not_ be bundled into one file. Youll have to import those from a `.css` file.
Bun bundles `.css` files imported via `@import` into a single file. It doesnt autoprefix or minify CSS today. Multiple `.css` files imported in one JavaScript file will _not_ be bundled into one file. Youll have to import those from a `.css` file.
This input:

View File

@@ -65,7 +65,7 @@ $ bunx --bun astro dev
Open [http://localhost:4321](http://localhost:4321) with your browser to see the result. Astro will hot-reload your app as you edit your source files.
{% image src="https://i.imgur.com/Dswiu6w.png" caption="An Astro v3 starter app running on Bun" %}
{% image src="https://imgur.com/Dswiu6w" caption="An Astro v3 starter app running on Bun" %}
---

View File

@@ -11,17 +11,17 @@ name: Get started using Prisma
Prisma works out of the box with Bun. First, create a directory and initialize it with `bun init`.
```bash
$ mkdir prisma-app
$ cd prisma-app
$ bun init
mkdir prisma-app
cd prisma-app
bun init
```
---
Then install the Prisma CLI (`prisma`) and Prisma Client (`@prisma/client`) as dependencies.
Then add Prisma as a dependency.
```bash
$ bun add prisma @prisma/client
bun add prisma
```
---
@@ -29,7 +29,7 @@ $ bun add prisma @prisma/client
We'll use the Prisma CLI with `bunx` to initialize our schema and migration directory. For simplicity we'll be using an in-memory SQLite database.
```bash
$ bunx prisma init --datasource-provider sqlite
bunx prisma init --datasource-provider sqlite
```
---
@@ -60,37 +60,14 @@ Then generate and run initial migration.
This will generate a `.sql` migration file in `prisma/migrations`, create a new SQLite instance, and execute the migration against the new instance.
```bash
$ bunx prisma migrate dev --name init
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": SQLite database "dev.db" at "file:./dev.db"
SQLite database dev.db created at file:./dev.db
Applying migration `20230928182242_init`
The following migration(s) have been created and applied from new schema changes:
migrations/
└─ 20230928182242_init/
└─ migration.sql
Your database is now in sync with your schema.
✔ Generated Prisma Client (v5.3.1) to ./node_modules/@prisma/client in 41ms
bunx prisma migrate dev --name init
```
---
As indicated in the output, Prisma re-generates our _Prisma client_ whenever we execute a new migration. The client provides a fully typed API for reading and writing from our database. You can manually re-generate the client with the Prisma CLI.
Prisma automatically generates our _Prisma client_ whenever we execute a new migration. The client provides a fully typed API for reading and writing from our database.
```sh
$ bunx prisma generate
```
---
We can import the generated client from `@prisma/client`.
It can be imported from `@prisma/client`.
```ts#src/index.ts
import {PrismaClient} from "@prisma/client";

View File

@@ -8,7 +8,7 @@ The `Bun.file()` function accepts a path and returns a `BunFile` instance. The `
const path = "/path/to/package.json";
const file = Bun.file(path);
const stream = file.stream();
const stream = await file.stream();
```
---

View File

@@ -47,7 +47,7 @@ Bun.serve<WebSocketData>({
// use a library to parse cookies
const cookies = parseCookies(req.headers.get("Cookie"));
const token = cookies["X-Token"];
const user = await getUserFromToken(token);
const user = await getUserFromToken(ws.data.authToken);
const upgraded = server.upgrade(req, {
data: {

View File

@@ -91,9 +91,6 @@ frozenLockfile = false
# equivalent to `--dry-run` flag
dryRun = false
# whether to use the github REST api (unauthenticated)
github.api = true
```
{% /details %}

View File

@@ -3,8 +3,7 @@ Bun ships as a single executable that can be installed a few different ways.
## macOS and Linux
{% callout %}
**Linux users** — The `unzip` package is required to install Bun. Use `sudo apt install unzip` to install `unzip` package.
Kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1. Use `uname -r` to check Kernel version.
**Linux users** — The `unzip` package is required to install Bun. Kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1.
{% /callout %}
{% codetabs %}
@@ -49,24 +48,6 @@ The test runner, package manager, and bundler are still under development. The f
- `bun link/unlink`
- `bun build`
## Docker
Bun provides a [Docker image](https://hub.docker.com/r/oven/bun/tags) that supports both Linux x64 and arm64.
```bash
$ docker pull oven/bun
$ docker run --rm --init --ulimit memlock=-1:-1 oven/bun
```
There are also image variants for different operating systems.
```bash
$ docker pull oven/bun:debian
$ docker pull oven/bun:slim
$ docker pull oven/bun:alpine
$ docker pull oven/bun:distroless
```
## Upgrading
Once installed, the binary can upgrade itself.

View File

@@ -46,13 +46,8 @@ $ wget https://apt.llvm.org/llvm.sh -O - | sudo bash -s -- 16 all
```
```bash#Arch
$ sudo pacman -S llvm clang lld
```
$ sudo pacman -S llvm16 clang16 lld
```bash#Fedora
$ sudo dnf install 'dnf-command(copr)'
$ sudo dnf copr enable -y @fedora-llvm-team/llvm-snapshots
$ sudo dnf install llvm clang lld
```
{% /codetabs %}
@@ -104,10 +99,6 @@ $ sudo apt install cargo ccache cmake git golang libtool ninja-build pkg-config
$ sudo pacman -S base-devel ccache cmake esbuild git go libiconv libtool make ninja pkg-config python rust sed unzip
```
```bash#Fedora
$ sudo dnf install cargo ccache cmake git golang libtool ninja-build pkg-config rustc golang-github-evanw-esbuild libatomic-static libstdc++-static sed unzip
```
{% /codetabs %}
{% details summary="Ubuntu — Unable to locate package esbuild" %}
@@ -385,13 +376,35 @@ $ valgrind --fair-sched=try --track-origins=yes bun-debug <args>
## Updating `WebKit`
The Bun team will occasionally bump the version of WebKit used in Bun. When this happens, you may see errors in `src/bun.js/bindings` during builds. When you see this, install the latest version of `bun-webkit` and re-compile.
The Bun team will occasionally bump the version of WebKit used in Bun. When this happens, you may see something like this with you run `git status`.
```bash
$ git status
On branch my-branch
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: src/bun.js/WebKit (new commits)
```
For performance reasons, `make submodule` does not automatically update the WebKit submodule. To update, run the following commands from the root of the Bun repo:
```bash
$ bun install
$ make cpp
```
<!-- Check the [Bun repo](https://github.com/oven-sh/bun/tree/main/src/bun.js) to get the hash of the commit of WebKit is currently being used.
{% image width="270" src="https://github.com/oven-sh/bun/assets/3084745/51730b73-89ef-4358-9a41-9563a60a54be" /%} -->
<!--
```bash
$ cd src/bun.js/WebKit
$ git fetch
$ git checkout <hash>
``` -->
## Troubleshooting
### 'span' file not found on Ubuntu
@@ -451,7 +464,7 @@ If you see an error about `cmakeconfig.h` not being found, this is because the p
$ bun install
```
Check to see the command installed webkit, and you can manually look for `node_modules/bun-webkit-{platform}-{arch}`:
Check to see the command installed webkit, and you can manully look for `node_modules/bun-webkit-{platform}-{arch}`:
```bash
# this should reveal two directories. if not, something went wrong

View File

@@ -42,6 +42,9 @@ const server = Bun.serve({
console.log(`Listening on http://localhost:${server.port} ...`);
```
<!--
### TypeScript
If you're using TypeScript, you may see a type error on the `Bun` global. To fix this, install `bun-types`.
```sh
@@ -56,7 +59,7 @@ Then add the following line to your `compilerOptions` in `tsconfig.json`.
+ "types": ["bun-types"]
}
}
```
``` -->
Run the file from your shell.

View File

@@ -19,11 +19,11 @@ Bun's runtime behavior is configured using top-level fields in the `bunfig.toml`
### `preload`
An array of scripts/plugins to execute before running a file or script.
An array of scripts to execute before running a file or script. This is useful for registering plugins.
```toml
# scripts to run before `bun run`-ing a file or script
# register plugins by adding them to this list
# scripts to run before `bun run`ning a file or script
# useful for registering plugins
preload = ["./preload.ts"]
```
@@ -216,17 +216,6 @@ Whether to install peer dependencies. Default `false`.
peer = false
```
### `install.github.api`
Enable using the github REST API to install github dependencies. Default `true`.
Private github repositories will fail to install if this option is true because the REST API is unauthenticated.
```toml
[install]
github.api = true
```
### `install.production`
Whether `bun install` will run in "production mode". Default `false`.

View File

@@ -25,47 +25,9 @@ Or programmatically by assigning a property to `process.env`.
process.env.FOO = "hello";
```
### Quotation marks
Bun supports double quotes, single quotes, and
### Expansion
Environment variables are automatically _expanded_. This means you can reference previously-defined variables in your environment variables.
```txt#.env
FOO=world
BAR=hello$FOO
```
```ts
process.env.BAR; // => "helloworld"
```
This is useful for constructing connection strings or other compound values.
```txt#.env
DB_USER=postgres
DB_PASSWORD=secret
DB_HOST=localhost
DB_PORT=5432
DB_URL=postgres://$DB_USER:$DB_PASSWORD@$DB_HOST:$DB_PORT/$DB_NAME
```
This can be disabled by escaping the `$` with a backslash.
```txt#.env
FOO=world
BAR=hello\$FOO
```
```ts
process.env.BAR; // => "hello$FOO"
```
### `dotenv`
Generally speaking, you won't need `dotenv` or `dotenv-expand` anymore, because Bun reads `.env` files automatically.
Generally speaking, you won't need `dotenv` anymore, because Bun reads `.env` files automatically.
## Reading environment variables

View File

@@ -33,20 +33,15 @@ Hello world!
In this case, we are importing from `./hello`, a relative path with no extension. **Extensioned imports are optional but supported.** To resolve this import, Bun will check for the following files in order:
- `./hello.tsx`
- `./hello.jsx`
- `./hello.ts`
- `./hello.mjs`
- `./hello.tsx`
- `./hello.js`
- `./hello.mjs`
- `./hello.cjs`
- `./hello.json`
- `./hello/index.tsx`
- `./hello/index.jsx`
- `./hello/index.ts`
- `./hello/index.mjs`
- `./hello/index.js`
- `./hello/index.cjs`
- `./hello/index.json`
- `./hello/index.mjs`
Import paths are case-insensitive, meaning these are all valid imports:

View File

@@ -1,12 +1,12 @@
Bun aims for complete Node.js API compatibility. Most `npm` packages intended for `Node.js` environments will work with Bun out of the box; the best way to know for certain is to try it.
This page is updated regularly to reflect compatibility status of the latest version of Bun. The information below reflects Bun's compatibility with _Node.js v20_. If you run into any bugs with a particular package, please [open an issue](https://bun.sh/issues). Opening issues for compatibility bugs helps us prioritize what to work on next.
This page is updated regularly to reflect compatibility status of the latest version of Bun. If you run into any bugs with a particular package, please [open an issue](https://bun.sh/issues). Opening issues for compatibility bugs helps us prioritize what to work on next.
## Built-in modules
### [`node:assert`](https://nodejs.org/api/assert.html)
🟡 Missing `doesNotMatch`
🟢 Fully implemented.
### [`node:async_hooks`](https://nodejs.org/api/async_hooks.html)
@@ -18,7 +18,7 @@ This page is updated regularly to reflect compatibility status of the latest ver
### [`node:child_process`](https://nodejs.org/api/child_process.html)
🟡 Missing `Stream` stdio, `proc.gid` `proc.uid`. IPC has partial support and only current only works with other `bun` processes.
🟡 Missing `Stream` stdio, `proc.gid`, `proc.uid`. IPC has partial support and only current only works with other `bun` processes.
### [`node:cluster`](https://nodejs.org/api/cluster.html)
@@ -30,9 +30,7 @@ This page is updated regularly to reflect compatibility status of the latest ver
### [`node:crypto`](https://nodejs.org/api/crypto.html)
🟡 Missing `Certificate` `ECDH` `KeyObject` `X509Certificate` `checkPrime` `checkPrimeSync` `createPrivateKey` `createPublicKey` `createSecretKey` `diffieHellman` `generateKey` `generateKeyPair` `generateKeyPairSync` `generateKeySync` `generatePrime` `generatePrimeSync` `getCipherInfo` `getFips` `hkdf` `hkdfSync` `secureHeapUsed` `setEngine` `setFips` `sign` `verify`
Some methods are not optimized yet.
🟡 Missing `crypto.Certificate` `crypto.ECDH` `crypto.KeyObject` `crypto.X509Certificate` `crypto.checkPrime{Sync}` `crypto.createPrivateKey` `crypto.createPublicKey` `crypto.createSecretKey` `crypto.diffieHellman` `crypto.generateKey{Sync}` `crypto.generateKeyPair{Sync}` `crypto.generatePrime{Sync}` `crypto.getCipherInfo` `crypto.{get|set}Fips` `crypto.hkdf` `crypto.hkdfSync` `crypto.secureHeapUsed` `crypto.setEngine` `crypto.sign` `crypto.verify`. Some methods are not optimized yet.
### [`node:dgram`](https://nodejs.org/api/dgram.html)
@@ -44,19 +42,19 @@ Some methods are not optimized yet.
### [`node:dns`](https://nodejs.org/api/dns.html)
🟡 Missing `cancel` `setServers` `getDefaultResultOrder`
🟢 Fully implemented.
### [`node:domain`](https://nodejs.org/api/domain.html)
🟡 Missing `Domain` `active`
🟢 Fully implemented.
### [`node:events`](https://nodejs.org/api/events.html)
🟡 Missing `on` `addAbortListener` `getMaxListeners`
🟡 Missing `require('node:events').on`.
### [`node:fs`](https://nodejs.org/api/fs.html)
🟡 Missing `Dir` `fdatasync` `fdatasyncSync` `openAsBlob` `opendir` `opendirSync` `statfs` `statfsSync`. `fs.promises.open` incorrectly returns a file descriptor instead of a `FileHandle`.
🟡 Missing `fs.fdatasync{Sync}` `fs.opendir{Sync}`, `fs.statfs{Sync}`. `fs.promises.open` incorrectly returns a file descriptor instead of a `FileHandle`.
### [`node:http`](https://nodejs.org/api/http.html)
@@ -76,11 +74,11 @@ Some methods are not optimized yet.
### [`node:module`](https://nodejs.org/api/module.html)
🟢 Missing `runMain` `syncBuiltinESMExports`, `Module#load()`. Attempts to override or patch the module cache will fail.
🟢 Fully implemented.
### [`node:net`](https://nodejs.org/api/net.html)
🟡 Missing `BlockList` `SocketAddress` `Stream` `getDefaultAutoSelectFamily` `getDefaultAutoSelectFamilyAttemptTimeout` `setDefaultAutoSelectFamily` `setDefaultAutoSelectFamilyAttemptTimeout` `Server#ref()` `Server#unref()` `Socket#ref()` `Socket#unref()`.
🟡 Missing `net.{get|set}DefaultAutoSelectFamily` `net.SocketAddress` `net.BlockList` `net.Server.ref()` `net.Server.unref()` `net.Socket.ref()` `net.Socket.unref()`.
### [`node:os`](https://nodejs.org/api/os.html)
@@ -92,7 +90,7 @@ Some methods are not optimized yet.
### [`node:perf_hooks`](https://nodejs.org/api/perf_hooks.html)
🟡 Only `perf_hooks.performance.now()` and `perf_hooks.performance.timeOrigin` are implemented. Missing `Performance` `PerformanceMark` `PerformanceMeasure` `PerformanceObserverEntryList` `PerformanceResourceTiming` `createHistogram` `monitorEventLoopDelay`. It's recommended to use `performance` global instead of `perf_hooks.performance`.
🟡 Only `perf_hooks.performance.now()` and `perf_hooks.performance.timeOrigin` are implemented. Recommended to use `performance` global instead of `perf_hooks.performance`.
### [`node:process`](https://nodejs.org/api/process.html)
@@ -116,7 +114,7 @@ Some methods are not optimized yet.
### [`node:stream`](https://nodejs.org/api/stream.html)
🟡 Missing `getDefaultHighWaterMark` `setDefaultHighWaterMark`
🟢 Fully implemented.
### [`node:string_decoder`](https://nodejs.org/api/string_decoder.html)
@@ -144,11 +142,11 @@ Some methods are not optimized yet.
### [`node:url`](https://nodejs.org/api/url.html)
🟡 Missing `domainToASCII` `domainToUnicode`. It's recommended to use `URL` and `URLSearchParams` globals instead.
🟡 Missing `url.domainTo{ASCII|Unicode}`. Recommended to use `URL` and `URLSearchParams` globals instead.
### [`node:util`](https://nodejs.org/api/util.html)
🟡 Missing `MIMEParams` `MIMEType` `aborted` `debug` `getSystemErrorMap` `getSystemErrorName` `parseArgs` `transferableAbortController` `transferableAbortSignal` `stripVTControlCharacters`
🟡 Missing `util.MIMEParams` `util.MIMEType` `util.getSystemErrorMap()` `util.getSystemErrorName()` `util.parseArgs()` `util.stripVTControlCharacters()` `util.transferableAbortController()` `util.transferableAbortSignal()`.
### [`node:v8`](https://nodejs.org/api/v8.html)
@@ -156,7 +154,7 @@ Some methods are not optimized yet.
### [`node:vm`](https://nodejs.org/api/vm.html)
🟡 Core functionality works, but VM modules are not implemented. Missing `createScript`. `ShadowRealm` can be used.
🟡 Core functionality works, but VM modules are not implemented. `ShadowRealm` can be used.
### [`node:wasi`](https://nodejs.org/api/wasi.html)
@@ -164,11 +162,266 @@ Some methods are not optimized yet.
### [`node:worker_threads`](https://nodejs.org/api/worker_threads.html)
🟡 `Worker` doesn't support the following options: `eval` `argv` `execArgv` `stdin` `stdout` `stderr` `trackedUnmanagedFds` `resourceLimits`. Missing `markAsUntransferable` `moveMessagePortToContext` `getHeapSnapshot`.
🟡 `Worker` doesn't support the following options: `eval`, `argv`, `execArgv`, `stdin`, `stdout`, `stderr`, `trackedUnmanagedFds`, `resourceLimits`. Missing `markAsUntransferable`, `moveMessagePortToContext`, `getHeapSnapshot`.
### [`node:zlib`](https://nodejs.org/api/zlib.html)
🟡 Missing `BrotliCompress` `BrotliDecompress` `brotliCompressSync` `brotliDecompress` `brotliDecompressSync` `createBrotliCompress` `createBrotliDecompress`. Unoptimized.
🟡 Missing `zlib.brotli*`. Has not been optimized.
<!-- {% block className="ScrollFrame" %}
{% table %}
- Module
- Status
- Notes
---
- {% anchor id="node_assert" %} [`node:assert`](https://nodejs.org/api/assert.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_async_hooks" %} [`node:async_hooks`](https://nodejs.org/api/async_hooks.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_buffer" %} [`node:buffer`](https://nodejs.org/api/buffer.html) {% /anchor %}
- 🟢
---
- {% anchor id="node_child_process" %} [`node:child_process`](https://nodejs.org/api/child_process.html) {% /anchor %}
- 🟡
- Missing IPC, `Stream` stdio, `proc.gid`, `proc.uid`, advanced serialization.
---
- {% anchor id="node_cluster" %} [`node:cluster`](https://nodejs.org/api/cluster.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_console" %} [`node:console`](https://nodejs.org/api/console.html) {% /anchor %}
- 🟢
- Recommended to use `console` global instead
---
- {% anchor id="node_crypto" %} [`node:crypto`](https://nodejs.org/api/crypto.html) {% /anchor %}
- 🟡
- Missing `crypto.Certificate` `crypto.ECDH` `crypto.KeyObject` `crypto.X509Certificate` `crypto.checkPrime{Sync}` `crypto.createPrivateKey` `crypto.createPublicKey` `crypto.createSecretKey` `crypto.diffieHellman` `crypto.generateKey{Sync}` `crypto.generateKeyPair{Sync}` `crypto.generatePrime{Sync}` `crypto.getCipherInfo` `crypto.{get|set}Fips` `crypto.hkdf` `crypto.hkdfSync` `crypto.secureHeapUsed` `crypto.setEngine` `crypto.sign` `crypto.verify`. Some methods are not optimized yet.
---
- {% anchor id="node_dgram" %} [`node:dgram`](https://nodejs.org/api/dgram.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_diagnostics_channel" %} [`node:diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_dns" %} [`node:dns`](https://nodejs.org/api/dns.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_domain" %} [`node:domain`](https://nodejs.org/api/domain.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_events" %} [`node:events`](https://nodejs.org/api/events.html) {% /anchor %}
- 🟡
- Missing `EventEmitterAsyncResource` `events.on`.
---
- {% anchor id="node_fs" %} [`node:fs`](https://nodejs.org/api/fs.html) {% /anchor %}
- 🟡
- Missing `fs.fdatasync{Sync}` `fs.opendir{Sync}`. `fs.promises.open` incorrectly returns a file descriptor instead of a `FileHandle`.
---
- {% anchor id="node_http" %} [`node:http`](https://nodejs.org/api/http.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_http2" %} [`node:http2`](https://nodejs.org/api/http2.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_https" %} [`node:https`](https://nodejs.org/api/https.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_inspector" %} [`node:inspector`](https://nodejs.org/api/inspector.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_module" %} [`node:module`](https://nodejs.org/api/module.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_net" %} [`node:net`](https://nodejs.org/api/net.html) {% /anchor %}
- 🟡
- Missing `net.{get|set}DefaultAutoSelectFamily` `net.SocketAddress` `net.BlockList`.
---
- {% anchor id="node_os" %} [`node:os`](https://nodejs.org/api/os.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_path" %} [`node:path`](https://nodejs.org/api/path.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_perf_hooks" %} [`node:perf_hooks`](https://nodejs.org/api/perf_hooks.html) {% /anchor %}
- 🟡
- Only `perf_hooks.performance.now()` and `perf_hooks.performance.timeOrigin` are implemented. Recommended to use `performance` global instead of `perf_hooks.performance`.
---
- {% anchor id="node_process" %} [`node:process`](https://nodejs.org/api/process.html) {% /anchor %}
- 🟡
- See `Globals > process`.
---
- {% anchor id="node_punycode" %} [`node:punycode`](https://nodejs.org/api/punycode.html) {% /anchor %}
- 🟢
- Fully implemented. _Deprecated by Node.js._
---
- {% anchor id="node_querystring" %} [`node:querystring`](https://nodejs.org/api/querystring.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_readline" %} [`node:readline`](https://nodejs.org/api/readline.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_repl" %} [`node:repl`](https://nodejs.org/api/repl.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_stream" %} [`node:stream`](https://nodejs.org/api/stream.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_string_decoder" %} [`node:string_decoder`](https://nodejs.org/api/string_decoder.html) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_sys" %} [`node:sys`](https://nodejs.org/api/util.html) {% /anchor %}
- 🟡
- See `node:util`.
---
- {% anchor id="node_timers" %} [`node:timers`](https://nodejs.org/api/timers.html) {% /anchor %}
- 🟢
- Recommended to use global `setTimeout`, et. al. instead.
---
- {% anchor id="node_tls" %} [`node:tls`](https://nodejs.org/api/tls.html) {% /anchor %}
- 🟡
- Missing `tls.createSecurePair`.
---
- {% anchor id="node_trace_events" %} [`node:trace_events`](https://nodejs.org/api/tracing.html) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_tty" %} [`node:tty`](https://nodejs.org/api/tty.html) {% /anchor %}
- 🟡
- Missing `tty.ReadStream` and `tty.WriteStream`.
---
- {% anchor id="node_url" %} [`node:url`](https://nodejs.org/api/url.html) {% /anchor %}
- 🟡
- Missing `url.domainTo{ASCII|Unicode}`. Recommended to use `URL` and `URLSearchParams` globals instead.
---
- {% anchor id="node_util" %} [`node:util`](https://nodejs.org/api/util.html) {% /anchor %}
- 🟡
- Missing `util.MIMEParams` `util.MIMEType` `util.formatWithOptions()` `util.getSystemErrorMap()` `util.getSystemErrorName()` `util.parseArgs()` `util.stripVTControlCharacters()` `util.transferableAbortController()` `util.transferableAbortSignal()`.
---
- {% anchor id="node_v8" %} [`node:v8`](https://nodejs.org/api/v8.html) {% /anchor %}
- 🔴
- `serialize` and `deserialize` use JavaScriptCore's wire format instead of V8's. Otherwise, not implemented. For profiling, use [`bun:jsc`](/docs/project/benchmarking#bunjsc) instead.
---
- {% anchor id="node_vm" %} [`node:vm`](https://nodejs.org/api/vm.html) {% /anchor %}
- 🟡
- Core functionality works, but VM modules are not implemented. `ShadowRealm` can be used.
---
- {% anchor id="node_wasi" %} [`node:wasi`](https://nodejs.org/api/wasi.html) {% /anchor %}
- 🟡
- Partially implemented.
---
- {% anchor id="node_worker_threads" %} [`node:worker_threads`](https://nodejs.org/api/worker_threads.html) {% /anchor %}
- 🔴
- Not implemented, but coming soon.
---
- {% anchor id="node_zlib" %} [`node:zlib`](https://nodejs.org/api/zlib.html) {% /anchor %}
- 🟡
- Missing `zlib.brotli*`.
{% /table %}
{% /block %} -->
## Globals
@@ -336,7 +589,7 @@ The table below lists all globals implemented by Node.js and Bun's current compa
### [`process`](https://nodejs.org/api/process.html)
🟡 Missing `domain` `hasUncaughtExceptionCaptureCallback` `initgroups` `report` `resourceUsage` `setUncaughtExceptionCaptureCallback` `setegid` `seteuid` `setgid` `setgroups` `setuid` `allowedNodeEnvironmentFlags` `getActiveResourcesInfo` `setActiveResourcesInfo` `moduleLoadList` `setSourceMapsEnabled` `channel`. `process.binding` is partially implemented.
🟡 Missing `process.allowedNodeEnvironmentFlags` `process.channel` `process.getActiveResourcesInfo/setActiveResourcesInfo()` `process.setuid/setgid/setegid/seteuid/setgroups()` `process.hasUncaughtExceptionCaptureCallback` `process.initGroups()` `process.report` `process.resourceUsage()`. `process.binding` is partially implemented.
### [`queueMicrotask()`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask)
@@ -449,3 +702,421 @@ The table below lists all globals implemented by Node.js and Bun's current compa
### [`WritableStreamDefaultWriter`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter)
🟢 Fully implemented.
<!-- {% table %}
---
- {% anchor id="node_abortcontroller" %} [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_abortsignal" %} [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_blob" %} [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_buffer" %} [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) {% /anchor %}
- 🟡
- Incomplete implementation of `base64` and `base64url` encodings.
---
- {% anchor id="node_bytelengthqueuingstrategy" %} [`ByteLengthQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_dirname" %} [`__dirname`](https://nodejs.org/api/globals.html#__dirname) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_filename" %} [`__filename`](https://nodejs.org/api/globals.html#__filename) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_atob" %} [`atob()`](https://developer.mozilla.org/en-US/docs/Web/API/atob) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_broadcastchannel" %} [`BroadcastChannel`](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_btoa" %} [`btoa()`](https://developer.mozilla.org/en-US/docs/Web/API/btoa) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_clearimmediate" %} [`clearImmediate()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearImmediate) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_clearinterval" %} [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearInterval) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_cleartimeout" %} [`clearTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearTimeout) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_compressionstream" %} [`CompressionStream`](https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_console" %} [`console`](https://developer.mozilla.org/en-US/docs/Web/API/console) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_countqueuingstrategy" %} [`CountQueuingStrategy`](https://developer.mozilla.org/en-US/docs/Web/API/CountQueuingStrategy) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_crypto" %} [`Crypto`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_crypto" %} [`SubtleCrypto (crypto)`](https://developer.mozilla.org/en-US/docs/Web/API/crypto) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_cryptokey" %} [`CryptoKey`](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_customevent" %} [`CustomEvent`](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_decompressionstream" %} [`DecompressionStream`](https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_event" %} [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_eventtarget" %} [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_exports" %} [`exports`](https://nodejs.org/api/globals.html#exports) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_fetch" %} [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_formdata" %} [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_global" %} [`global`](https://nodejs.org/api/globals.html#global) {% /anchor %}
- 🟢
- Implemented. This is an object containing all objects in the global namespace. It's rarely referenced directly, as its contents are available without an additional prefix, e.g. `__dirname` instead of `global.__dirname`.
---
- {% anchor id="node_globalthis" %} [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) {% /anchor %}
- 🟢
- Aliases to `global`.
---
- {% anchor id="node_headers" %} [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_messagechannel" %} [`MessageChannel`](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_messageevent" %} [`MessageEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_messageport" %} [`MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_module" %} [`module`](https://nodejs.org/api/globals.html#module) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_performanceentry" %} [`PerformanceEntry`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_performancemark" %} [`PerformanceMark`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMark) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_performancemeasure" %} [`PerformanceMeasure`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_performanceobserver" %} [`PerformanceObserver`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_performanceobserverentrylist" %} [`PerformanceObserverEntryList`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_performanceresourcetiming" %} [`PerformanceResourceTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_performance" %} [`performance`](https://developer.mozilla.org/en-US/docs/Web/API/performance) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_process" %} [`process`](https://nodejs.org/api/process.html) {% /anchor %}
- 🟡
- Missing `process.allowedNodeEnvironmentFlags` `process.channel()` `process.connected` `process.constrainedMemory()` `process.disconnect()` `process.getActiveResourcesInfo/setActiveResourcesInfo()` `process.setuid/setgid/setegid/seteuid/setgroups()` `process.hasUncaughtExceptionCaptureCallback` `process.initGroups()` `process.report` `process.resourceUsage()` `process.send()`.
---
- {% anchor id="node_queuemicrotask" %} [`queueMicrotask()`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_readablebytestreamcontroller" %} [`ReadableByteStreamController`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_readablestream" %} [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_readablestreambyobreader" %} [`ReadableStreamBYOBReader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_readablestreambyobrequest" %} [`ReadableStreamBYOBRequest`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBRequest) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_readablestreamdefaultcontroller" %} [`ReadableStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_readablestreamdefaultreader" %} [`ReadableStreamDefaultReader`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_require" %} [`require()`](https://nodejs.org/api/globals.html#require) {% /anchor %}
- 🟢
- Fully implemented, as well as [`require.main`](https://nodejs.org/api/modules.html#requiremain), [`require.cache`](https://nodejs.org/api/modules.html#requirecache), and [`require.resolve`](https://nodejs.org/api/modules.html#requireresolverequest-options)
---
- {% anchor id="node_response" %} [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_request" %} [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_setimmediate" %} [`setImmediate()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_setinterval" %} [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_settimeout" %} [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_structuredclone" %} [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_subtlecrypto" %} [`SubtleCrypto`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_domexception" %} [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_textdecoder" %} [`TextDecoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_textdecoderstream" %} [`TextDecoderStream`](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoderStream) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_textencoder" %} [`TextEncoder`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_textencoderstream" %} [`TextEncoderStream`](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoderStream) {% /anchor %}
- 🔴
- Not implemented.
---
- {% anchor id="node_transformstream" %} [`TransformStream`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_transformstreamdefaultcontroller" %} [`TransformStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStreamDefaultController) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_url" %} [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_urlsearchparams" %} [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_webassembly" %} [`WebAssembly`](https://nodejs.org/api/globals.html#webassembly) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_writablestream" %} [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_writablestreamdefaultcontroller" %} [`WritableStreamDefaultController`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultController) {% /anchor %}
- 🟢
- Fully implemented.
---
- {% anchor id="node_writablestreamdefaultwriter" %} [`WritableStreamDefaultWriter`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStreamDefaultWriter) {% /anchor %}
- 🟢
- Fully implemented.
{% /table %} -->

View File

@@ -45,7 +45,7 @@ plugin(
);
```
Bun's plugin API is loosely based on [esbuild](https://esbuild.github.io/plugins). Only [a subset](/docs/bundler/vs-esbuild#plugin-api) of the esbuild API is implemented, but some esbuild plugins "just work" in Bun, like the official [MDX loader](https://mdxjs.com/packages/esbuild/):
Bun's plugin API is based on [esbuild](https://esbuild.github.io/plugins). Only [a subset](/docs/bundler/vs-esbuild#plugin-api) of the esbuild API is implemented, but some esbuild plugins "just work" in Bun, like the official [MDX loader](https://mdxjs.com/packages/esbuild/):
```jsx
import { plugin } from "bun";
@@ -217,91 +217,6 @@ import MySvelteComponent from "./component.svelte";
console.log(mySvelteComponent.render());
```
## Virtual Modules
{% note %}
This feature is currently only available at runtime with `Bun.plugin` and not yet supported in the bundler, but you can mimick the behavior using `onResolve` and `onLoad`.
{% /note %}
To create virtual modules at runtime, use `builder.module(specifier, callback)` in the `setup` function of a `Bun.plugin`.
For example:
```js
import { plugin } from "bun";
plugin({
name: "my-virtual-module",
setup(build) {
build.module(
// The specifier, which can be any string
"my-transpiled-virtual-module",
// The callback to run when the module is imported or required for the first time
() => {
return {
contents: "console.log('hello world!')",
loader: "js",
};
},
);
build.module("my-object-virtual-module", () => {
return {
exports: {
foo: "bar",
},
loader: "object",
};
});
},
});
// Sometime later
// All of these work
import "my-transpiled-virtual-module";
require("my-transpiled-virtual-module");
await import("my-transpiled-virtual-module");
require.resolve("my-transpiled-virtual-module");
import { foo } from "my-object-virtual-module";
const object = require("my-object-virtual-module");
await import("my-object-virtual-module");
require.resolve("my-object-virtual-module");
```
### Overriding existing modules
You can also override existing modules with `build.module`.
```js
import { plugin } from "bun";
build.module("my-object-virtual-module", () => {
return {
exports: {
foo: "bar",
},
loader: "object",
};
});
require("my-object-virtual-module"); // { foo: "bar" }
await import("my-object-virtual-module"); // { foo: "bar" }
build.module("my-object-virtual-module", () => {
return {
exports: {
baz: "quix",
},
loader: "object",
};
});
require("my-object-virtual-module"); // { baz: "quix" }
await import("my-object-virtual-module"); // { baz: "quix" }
```
## Reading the config
Plugins can read and write to the [build config](/docs/bundler#api) with `build.config`.

View File

@@ -168,252 +168,252 @@ Bun implements the following matchers. Full Jest compatibility is on the roadmap
---
-
- ✔️
- [`.not`](https://jestjs.io/docs/expect#not)
---
-
- ✔️
- [`.toBe()`](https://jestjs.io/docs/expect#tobevalue)
---
-
- ✔️
- [`.toEqual()`](https://jestjs.io/docs/expect#toequalvalue)
---
-
- ✔️
- [`.toBeNull()`](https://jestjs.io/docs/expect#tobenull)
---
-
- ✔️
- [`.toBeUndefined()`](https://jestjs.io/docs/expect#tobeundefined)
---
-
- ✔️
- [`.toBeNaN()`](https://jestjs.io/docs/expect#tobenan)
---
-
- ✔️
- [`.toBeDefined()`](https://jestjs.io/docs/expect#tobedefined)
---
-
- ✔️
- [`.toBeFalsy()`](https://jestjs.io/docs/expect#tobefalsy)
---
-
- ✔️
- [`.toBeTruthy()`](https://jestjs.io/docs/expect#tobetruthy)
---
-
- ✔️
- [`.toContain()`](https://jestjs.io/docs/expect#tocontainitem)
---
-
- ✔️
- [`.toStrictEqual()`](https://jestjs.io/docs/expect#tostrictequalvalue)
---
-
- ✔️
- [`.toThrow()`](https://jestjs.io/docs/expect#tothrowerror)
---
-
- ✔️
- [`.toHaveLength()`](https://jestjs.io/docs/expect#tohavelengthnumber)
---
-
- ✔️
- [`.toHaveProperty()`](https://jestjs.io/docs/expect#tohavepropertykeypath-value)
---
-
- ✖️
- [`.extend`](https://jestjs.io/docs/expect#expectextendmatchers)
---
-
- ✔️
- [`.anything()`](https://jestjs.io/docs/expect#expectanything)
---
-
- ✔️
- [`.any()`](https://jestjs.io/docs/expect#expectanyconstructor)
---
-
- ✖️
- [`.arrayContaining()`](https://jestjs.io/docs/expect#expectarraycontainingarray)
---
-
- ✖️
- [`.assertions()`](https://jestjs.io/docs/expect#expectassertionsnumber)
---
-
- ✖️
- [`.closeTo()`](https://jestjs.io/docs/expect#expectclosetonumber-numdigits)
---
-
- ✖️
- [`.hasAssertions()`](https://jestjs.io/docs/expect#expecthasassertions)
---
-
- ✖️
- [`.objectContaining()`](https://jestjs.io/docs/expect#expectobjectcontainingobject)
---
-
- ✔️
- [`.stringContaining()`](https://jestjs.io/docs/expect#expectstringcontainingstring)
---
-
- ✔️
- [`.stringMatching()`](https://jestjs.io/docs/expect#expectstringmatchingstring--regexp)
---
-
- ✖️
- [`.addSnapshotSerializer()`](https://jestjs.io/docs/expect#expectaddsnapshotserializerserializer)
---
-
- ✔️
- [`.resolves()`](https://jestjs.io/docs/expect#resolves)
---
-
- ✔️
- [`.rejects()`](https://jestjs.io/docs/expect#rejects)
---
-
- ✔️
- [`.toHaveBeenCalled()`](https://jestjs.io/docs/expect#tohavebeencalled)
---
-
- ✔️
- [`.toHaveBeenCalledTimes()`](https://jestjs.io/docs/expect#tohavebeencalledtimesnumber)
---
-
- ✖️
- [`.toHaveBeenCalledWith()`](https://jestjs.io/docs/expect#tohavebeencalledwitharg1-arg2-)
---
-
- ✖️
- [`.toHaveBeenLastCalledWith()`](https://jestjs.io/docs/expect#tohavebeenlastcalledwitharg1-arg2-)
---
-
- ✖️
- [`.toHaveBeenNthCalledWith()`](https://jestjs.io/docs/expect#tohavebeennthcalledwithnthcall-arg1-arg2-)
---
-
- ✖️
- [`.toHaveReturned()`](https://jestjs.io/docs/expect#tohavereturned)
---
-
- ✖️
- [`.toHaveReturnedTimes()`](https://jestjs.io/docs/expect#tohavereturnedtimesnumber)
---
-
- ✖️
- [`.toHaveReturnedWith()`](https://jestjs.io/docs/expect#tohavereturnedwithvalue)
---
-
- ✖️
- [`.toHaveLastReturnedWith()`](https://jestjs.io/docs/expect#tohavelastreturnedwithvalue)
---
-
- ✖️
- [`.toHaveNthReturnedWith()`](https://jestjs.io/docs/expect#tohaventhreturnedwithnthcall-value)
---
-
- ✔️
- [`.toBeCloseTo()`](https://jestjs.io/docs/expect#tobeclosetonumber-numdigits)
---
-
- ✔️
- [`.toBeGreaterThan()`](https://jestjs.io/docs/expect#tobegreaterthannumber--bigint)
---
-
- ✔️
- [`.toBeGreaterThanOrEqual()`](https://jestjs.io/docs/expect#tobegreaterthanorequalnumber--bigint)
---
-
- ✔️
- [`.toBeLessThan()`](https://jestjs.io/docs/expect#tobelessthannumber--bigint)
---
-
- ✔️
- [`.toBeLessThanOrEqual()`](https://jestjs.io/docs/expect#tobelessthanorequalnumber--bigint)
---
-
- ✔️
- [`.toBeInstanceOf()`](https://jestjs.io/docs/expect#tobeinstanceofclass)
---
-
- ✖️
- [`.toContainEqual()`](https://jestjs.io/docs/expect#tocontainequalitem)
---
-
- ✔️
- [`.toMatch()`](https://jestjs.io/docs/expect#tomatchregexp--string)
---
-
- ✔️
- [`.toMatchObject()`](https://jestjs.io/docs/expect#tomatchobjectobject)
---
-
- ✔️
- [`.toMatchSnapshot()`](https://jestjs.io/docs/expect#tomatchsnapshotpropertymatchers-hint)
---
-
- ✖️
- [`.toMatchInlineSnapshot()`](https://jestjs.io/docs/expect#tomatchinlinesnapshotpropertymatchers-inlinesnapshot)
---
-
- ✖️
- [`.toThrowErrorMatchingSnapshot()`](https://jestjs.io/docs/expect#tothrowerrormatchingsnapshothint)
---
-
- ✖️
- [`.toThrowErrorMatchingInlineSnapshot()`](https://jestjs.io/docs/expect#tothrowerrormatchinginlinesnapshotinlinesnapshot)
{% /table %}

View File

@@ -31,7 +31,7 @@ Bun supports things like top-level await, JSX, and extensioned `.ts` imports, wh
"types": ["bun-types"],
// enable latest features
"lib": ["ESNext"],
"lib": ["esnext"],
"module": "esnext",
"target": "esnext",
@@ -45,6 +45,7 @@ Bun supports things like top-level await, JSX, and extensioned `.ts` imports, wh
"jsx": "react-jsx", // support JSX
"allowJs": true, // allow importing `.js` from `.ts`
"esModuleInterop": true, // allow default imports for CommonJS modules
// best practices
"strict": true,

View File

@@ -1,210 +0,0 @@
const nodejsBuiltinModules = [
"assert",
"async_hooks",
"buffer",
"child_process",
"cluster",
"console",
"constants",
"crypto",
"dgram",
"diagnostics_channel",
"dns",
"domain",
"events",
"fs",
"http",
"http2",
"https",
"inspector",
"module",
"net",
"os",
"path",
"perf_hooks",
"process",
"punycode",
"querystring",
"readline",
"repl",
"stream",
"string_decoder",
"timers",
"tls",
"trace_events",
"tty",
"url",
"util",
"v8",
"vm",
"wasi",
"worker_threads",
"zlib",
];
function getModuleKeys(moduleName: string): string[] {
const script = `import('${moduleName}').then(mod=>console.log(JSON.stringify(Object.keys(mod))))`;
const nodeProc = Bun.spawnSync(["node", "-e", script], {
stderr: "ignore",
});
const nodeKeys: string[] = JSON.parse(nodeProc.stdout.toString());
return nodeKeys;
}
function getAllProperties(obj = {}) {
const allKeys = new Set();
do {
Reflect.ownKeys(obj).forEach(key => allKeys.add(key));
} while ((obj = Object.getPrototypeOf(obj)));
return [...allKeys];
}
function getPrototypeKeys(moduleName: string, className: string): string[] {
// const script = `import('${moduleName}').then(mod=>console.log(JSON.stringify(Object.keys(mod.${className}.prototype))))`;
const script = `
import("${moduleName}").then((mod) => {
const lines = new Set();
let obj = mod.${className}.prototype;
do {
Reflect.ownKeys(obj).forEach((key) => lines.add(key));
} while ((obj = Object.getPrototypeOf(obj)));
console.log("[", [...lines].map(k => \`"\${String(k)}"\`).join(","), "]");
});`.replace(/\n/g, "");
// remove whitespace
// .replace(/\s+/g, "");
// console.log(script);
const nodeProc = Bun.spawnSync(["node", "-e", script], {
// stderr: "inherit",
// stdout: "inherit",
});
// console.log(nodeProc.stdout.toString());
const nodeKeys: string[] = JSON.parse(nodeProc.stdout.toString());
return nodeKeys;
}
const SKIP: Record<string, boolean> = {
"buffer.File": true,
"process.abort": true,
"process.exit": true,
"process.kill": true,
"process.reallyExit": true,
"vm.Script": true,
"zlib.deflate": true,
"zlib.inflate": true,
"zlib.unzip": true,
"zlib.deflateRaw": true,
"zlib.gunzip": true,
"zlib.gzip": true,
"zlib.inflateRaw": true,
"console.assert": true,
"console.count": true,
// "fs.mkdtempSync": true,
// "fs.read": true,
// "fs.readv": true,
// "fs.writev": true,
// "fs.writeSync": true,
// "fs.writeFileSync": true,
// "fs.writeFile": true,
// "fs.write": true,
// "fs.writevSync": true,
// "fs.watchFile": true,
// "fs.watch": true,
// "fs.utimesSync": true,
// "fs.utimes": true,
// "fs.unwatchFile": true,
// "fs.unlinkSync": true,
// "fs.unlink": true,
// "fs.truncateSync": true,
// "fs.truncate": true,
// "fs.symlinkSync": true,
};
for (const moduleName of nodejsBuiltinModules) {
const heading = `======== ${moduleName} ========`;
// print equals sign to match the length of heading
console.log("\n\n" + "=".repeat(heading.length));
console.log(heading);
console.log("=".repeat(heading.length));
const mod = await import(moduleName);
const bunKeys: string[] = Object.keys(mod);
const nodeKeys = getModuleKeys(moduleName);
// print top-level elements that are missing
// const missingKeys = nodeKeys
// .filter((key) => !bunKeys.includes(key))
// .filter((k) => !k.startsWith("_"));
// const notMissing = nodeKeys.filter((key) => bunKeys.includes(key));
// if (missingKeys.length === 0) {
// console.log(`Fully implemented.`);
// } else {
// console.log(`Missing ${missingKeys.map((k) => `\`${k}\``).join(" ")}`);
// }
console.log();
// check for prototype compatibility
let missing = false;
for (const k of nodeKeys) {
if (k.startsWith("_")) continue;
if (!bunKeys.includes(k)) {
missing = true;
console.log(` [${moduleName}.${k}] Not implemented.`);
continue;
}
if (mod[k] && typeof mod[k] === "function") {
if (!!mod[k].prototype) {
const className = `${moduleName}.${k}`;
const bunProtoKeys = getAllProperties(mod[k].prototype);
// console.log(mod[k].prototype);
// getAllProperties;
// for (const l in mod[k].prototype) {
// bunProtoKeys.push(l);
// }
const nodeProtoKeys = getPrototypeKeys(moduleName, k);
// console.log("nodeProtoKeys", nodeProtoKeys);
// console.log("bunProtoKeys", bunProtoKeys);
// console.log("nodeProtoKeys", nodeProtoKeys);
// console.log("bunProtoKeys", bunProtoKeys);
const missingProtoKeys = nodeProtoKeys.filter(key => !bunProtoKeys.includes(key));
// const notMissingProtoKeys = nodeProtoKeys.filter((key) =>
// bunProtoKeys.includes(key)
// );
if (missingProtoKeys.length === 0) {
console.log(` [${className}] Fully implemented.`);
} else {
missing = true;
console.log(
` [${className}] Missing ${missingProtoKeys
.filter(k => !k.startsWith("_"))
.map(k => `\`${k}\``)
.join(" ")}`,
);
}
} else {
if (moduleName === "console") continue;
if (moduleName === "fs") continue;
if (SKIP[`${moduleName}.${k}`]) continue;
try {
// console.log(`trying ${moduleName}.${k}...`);
await mod[k]();
await Bun.sleep(1);
} catch (err: any) {
if ((err?.message as string).includes("not yet implemented")) {
missing = true;
console.log(` [${moduleName}.${k}] Not implemented.`);
}
}
}
}
}
if (!missing) {
console.log(`[${moduleName}] Fully implemented.`);
}
}
console.log("\n\n================\nDONE.");
process.exit();

View File

@@ -26,7 +26,7 @@
"@types/react": "^18.0.25",
"@typescript-eslint/eslint-plugin": "^5.31.0",
"@typescript-eslint/parser": "^5.31.0",
"bun-webkit": "0.0.1-2c4d07c9499a65f36f554dc4cd4e9e0640632b8c"
"bun-webkit": "0.0.1-f8aa36d4737faee92bd2d1e337a2fd01a5437c61"
},
"version": "0.0.0",
"prettier": "./.prettierrc.cjs"

3
packages/bun-ecosystem/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
.DS_Store
node_modules
tmp

View File

@@ -0,0 +1,7 @@
# bun-ecosystem
A registry to test `npm` packages using Bun. This can be used as a tool to find bugs in Bun by running the test suites of these packages. In the future, we will run theses tests to catch regressions between releases.
```sh
bun run test
```

BIN
packages/bun-ecosystem/bun.lockb Executable file

Binary file not shown.

View File

@@ -0,0 +1,15 @@
{
"name": "bun-ecosystem-ci",
"private": true,
"dependencies": {
"globby": "^13.1.3"
},
"devDependencies": {
"bun-types": "canary",
"prettier": "^2.8.2"
},
"scripts": {
"format": "prettier --write src",
"test": "bun run src/runner.ts"
}
}

View File

@@ -0,0 +1,69 @@
export type Package = {
readonly name: string;
readonly repository: string;
readonly cwd?: string;
readonly tests?: {
readonly style: "jest" | "ava" | "tape" | "custom";
readonly include: string[];
readonly exclude?: string[];
readonly disabled?: boolean;
};
};
export const packages: Package[] = [
{
name: "lodash",
repository: github("lodash/lodash"),
tests: {
style: "jest",
include: ["test/*.js"],
exclude: [
"debounce.test.js", // hangs runner
"size.test.js", // require('vm').runInNewContext()
"merge.test.js", // failing
],
},
},
{
name: "chalk",
repository: github("chalk/chalk"),
tests: {
style: "ava",
include: ["test/*.js"],
},
},
{
name: "request",
repository: github("request/request"),
tests: {
style: "tape",
include: ["tests/*.js"],
},
},
{
name: "commander",
repository: github("tj/commander.js"),
tests: {
style: "jest",
include: ["tests/*.js"],
},
},
{
name: "express",
repository: github("expressjs/express"),
tests: {
style: "jest",
include: ["test/**/*.js"],
exclude: [
"test/res.sendStatus.js", // https://github.com/oven-sh/bun/issues/887
"test/Route.js", // https://github.com/oven-sh/bun/issues/2030
],
// Most tests fail due to lack of "http2"
disabled: true,
},
},
];
function github(repository: string): string {
return `git@github.com:${repository}.git`;
}

View File

@@ -0,0 +1,92 @@
import type { Package } from "./packages";
import { packages } from "./packages";
import { existsSync, copyFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { globby } from "globby";
for (const pkg of packages) {
try {
await loadPackage(pkg, "tmp");
} catch (error) {
console.error(pkg.name, error);
}
}
async function loadPackage(pkg: Package, cwd?: string): Promise<void> {
await gitClone({
cwd,
repository: pkg.repository,
name: pkg.name,
});
const dir = join(cwd ?? "", pkg.name, pkg.cwd ?? "");
await spawn({
cwd: dir,
cmd: ["bun", "install"],
});
if (!pkg.tests || pkg.tests.style !== "jest") {
return;
}
const files = await globby(pkg.tests.include, {
cwd: dir,
ignore: pkg.tests.exclude ?? [crypto.randomUUID()],
onlyFiles: true,
caseSensitiveMatch: false,
});
if (!files.length) {
throw new Error("No tests found");
}
for (const file of files) {
let path = file;
if (!file.includes(".test.")) {
const ext = path.lastIndexOf(".");
path = file.substring(0, ext) + ".test" + file.substring(ext);
copyFileSync(join(dir, file), join(dir, path));
}
await spawn({
cwd: dir,
cmd: ["bun", "test", path],
});
}
}
type GitCloneOptions = {
repository: string;
cwd?: string;
name?: string;
};
async function gitClone(options: GitCloneOptions): Promise<void> {
const name = options.name ?? dirname(options.repository);
const cwd = options.cwd ?? process.cwd();
const path = join(cwd, name);
if (existsSync(path)) {
await spawn({
cwd: path,
cmd: ["git", "pull"],
});
} else {
const url = `${options.repository}`;
await spawn({
cwd,
cmd: ["git", "clone", "--single-branch", "--depth", "1", url, name],
});
}
}
type SpawnOptions = {
cwd: string;
cmd: string[];
};
async function spawn({ cwd, cmd }: SpawnOptions) {
const { exited } = await Bun.spawn({
cwd,
cmd,
stdout: "inherit",
stderr: "inherit",
});
const exitCode = await exited;
if (exitCode !== 0) {
throw new Error(`"${cmd.join(" ")}" exited with ${exitCode}`);
}
}

View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "ESNext",
"target": "ESNext",
"moduleResolution": "node",
"types": ["bun-types"],
"esModuleInterop": true,
"allowJs": true,
"strict": true,
"resolveJsonModule": true
},
"include": [
"src"
]
}

View File

@@ -46,10 +46,7 @@ export function objectPreviewToString(objectPreview: JSC.Runtime.ObjectPreview):
items = entries.map(entryPreviewToString).sort();
} else if (properties) {
if (isIndexed(subtype)) {
items = properties.map(indexedPropertyPreviewToString);
if (subtype !== "array") {
items.sort();
}
items = properties.map(indexedPropertyPreviewToString).sort();
} else {
items = properties.map(namedPropertyPreviewToString).sort();
}

Binary file not shown.

View File

@@ -70,19 +70,6 @@ declare module "bun" {
options?: { PATH?: string; cwd?: string },
): string | null;
interface TOML {
/**
* Parse a TOML string into a JavaScript object.
*
* @param {string} command The name of the executable or script
* @param {string} options.PATH Overrides the PATH environment variable
* @param {string} options.cwd Limits the search to a particular directory in which to searc
*
*/
parse(input: string): object;
}
export const TOML: TOML;
export type Serve<WebSocketDataType = undefined> =
| ServeOptions
| TLSServeOptions
@@ -925,14 +912,6 @@ declare module "bun" {
* Minify whitespace and comments from the output.
*/
minifyWhitespace?: boolean;
/**
* **Experimental**
*
* Enabled by default, use this to disable dead code elimination.
*
* Some other transpiler options may still do some specific dead code elimination.
*/
deadCodeElimination?: boolean;
/**
* This does two things (and possibly more in the future):
@@ -2209,21 +2188,6 @@ declare module "bun" {
tls?: TLSOptions;
}
export interface SocketAddress {
/**
* The IP address of the client.
*/
address: string;
/**
* The port of the client.
*/
port: number;
/**
* The IP family ("IPv4" or "IPv6").
*/
family: "IPv4" | "IPv6";
}
/**
* HTTP & HTTPS Server
*
@@ -2371,20 +2335,6 @@ declare module "bun" {
compress?: boolean,
): ServerWebSocketSendStatus;
/**
* Returns the client IP address and port of the given Request. If the request was closed or is a unix socket, returns null.
*
* @example
* ```js
* export default {
* async fetch(request, server) {
* return new Response(server.requestIP(request));
* }
* }
* ```
*/
requestIP(request: Request): SocketAddress | null;
/**
* How many requests are in-flight right now?
*/
@@ -3214,7 +3164,7 @@ declare module "bun" {
loader: Loader;
}
type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject | undefined;
type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject;
type OnLoadCallback = (
args: OnLoadArgs,
) => OnLoadResult | Promise<OnLoadResult>;
@@ -3306,37 +3256,6 @@ declare module "bun" {
* The config object passed to `Bun.build` as is. Can be mutated.
*/
config: BuildConfig & { plugins: BunPlugin[] };
/**
* Create a lazy-loaded virtual module that can be `import`ed or `require`d from other modules
*
* @param specifier The module specifier to register the callback for
* @param callback The function to run when the module is imported or required
*
* ### Example
* @example
* ```ts
* Bun.plugin({
* setup(builder) {
* builder.module("hello:world", () => {
* return { exports: { foo: "bar" }, loader: "object" };
* });
* },
* });
*
* // sometime later
* const { foo } = await import("hello:world");
* console.log(foo); // "bar"
*
* // or
* const { foo } = require("hello:world");
* console.log(foo); // "bar"
* ```
*/
module(
specifier: string,
callback: () => OnLoadResult | Promise<OnLoadResult>,
): void;
}
interface BunPlugin {
@@ -3900,7 +3819,7 @@ declare module "bun" {
: undefined;
type ReadableToSyncIO<X extends Readable> = X extends "pipe" | undefined
? Buffer
? Uint8Array
: undefined;
type WritableIO = FileSink | number | undefined;

View File

@@ -701,10 +701,10 @@ declare module "dns" {
* one of the `DNS error codes`.
* @since v0.1.16
*/
export function reverse(
ip: string,
callback: (err: ErrnoException | null, hostnames: string[]) => void,
): void;
// export function reverse(
// ip: string,
// callback: (err: ErrnoException | null, hostnames: string[]) => void,
// ): void;
/**
* Sets the IP address and port of servers to be used when performing DNS
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
@@ -749,7 +749,7 @@ declare module "dns" {
* ```
* @since v0.11.3
*/
export function getServers(): string[];
// export function getServers(): string[];
/**
* Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be:
*
@@ -841,7 +841,7 @@ declare module "dns" {
* @since v8.3.0
*/
cancel(): void;
getServers: typeof getServers;
// getServers: typeof getServers;
resolve: typeof resolve;
resolve4: typeof resolve4;
resolve6: typeof resolve6;
@@ -854,7 +854,7 @@ declare module "dns" {
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
// reverse: typeof reverse;
/**
* The resolver instance will send its requests from the specified IP address.
* This allows programs to specify outbound interfaces when used on multi-homed

View File

@@ -681,7 +681,7 @@ interface Process {
*/
setSourceMapsEnabled(enabled: boolean): void;
kill(pid: number, signal?: string | number): true;
kill(pid: number, signal?: string | number): void;
on(event: "beforeExit", listener: BeforeExitListener): this;
// on(event: "disconnect", listener: DisconnectListener): this;

View File

@@ -1,7 +1,6 @@
{
"name": "bun-types",
"repository": "https://github.com/oven-sh/bun",
"license": "MIT",
"devDependencies": {
"conditional-type-checks": "^1.0.6",
"prettier": "^2.4.1",

View File

@@ -41,6 +41,3 @@ import * as tsd from "tsd";
env: { ...process.env, dummy: "" },
});
}
{
Bun.TOML.parse("asdf = asdf");
}

View File

@@ -1,5 +0,0 @@
import * as dns from "node:dns";
dns.resolve("asdf", "A", () => {});
dns.reverse("asdf", () => {});
dns.getServers();

View File

@@ -665,39 +665,9 @@ int bsd_udp_packet_buffer_ecn(void *msgvec, int index) {
return 0; // no ecn defaults to 0
}
static int bsd_do_connect_raw(struct addrinfo *rp, int fd)
static int bsd_do_connect(struct addrinfo *result, int fd)
{
do {
if (connect(fd, rp->ai_addr, rp->ai_addrlen) == 0 || errno == EINPROGRESS) {
return 0;
}
} while (errno == EINTR);
return LIBUS_SOCKET_ERROR;
}
static int bsd_do_connect(struct addrinfo *rp, int *fd)
{
while (rp != NULL) {
if (bsd_do_connect_raw(rp, *fd) == 0) {
return 0;
}
rp = rp->ai_next;
bsd_close_socket(*fd);
if (rp == NULL) {
return LIBUS_SOCKET_ERROR;
}
int resultFd = bsd_create_socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (resultFd < 0) {
return LIBUS_SOCKET_ERROR;
}
*fd = resultFd;
}
return LIBUS_SOCKET_ERROR;
return connect(fd, result->ai_addr, (socklen_t) result->ai_addrlen);
}
LIBUS_SOCKET_DESCRIPTOR bsd_create_connect_socket(const char *host, int port, const char *source_host, int options) {
@@ -730,21 +700,18 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_connect_socket(const char *host, int port, co
return LIBUS_SOCKET_ERROR;
}
}
if (bsd_do_connect_raw(result, fd) != 0) {
}
do {
if (bsd_do_connect(result, fd) != 0 && errno != EINPROGRESS) {
bsd_close_socket(fd);
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
} else {
if (bsd_do_connect(result, &fd) != 0) {
freeaddrinfo(result);
return LIBUS_SOCKET_ERROR;
}
}
} while (errno == EINTR);
freeaddrinfo(result);
return fd;
}

View File

@@ -30,7 +30,7 @@ void Bun__internal_dispatch_ready_poll(void* loop, void* poll);
#include <stdint.h>
#endif
void us_loop_run_bun_tick(struct us_loop_t *loop, int64_t timeoutMs, void*);
void us_loop_run_bun_tick(struct us_loop_t *loop, int64_t timeoutMs);
/* Pointer tags are used to indicate a Bun pointer versus a uSockets pointer */
#define UNSET_BITS_49_UNTIL_64 0x0000FFFFFFFFFFFF
@@ -174,20 +174,13 @@ void us_loop_run(struct us_loop_t *loop) {
}
}
void bun_on_tick_before(void* ctx);
void bun_on_tick_after(void* ctx);
void us_loop_run_bun_tick(struct us_loop_t *loop, int64_t timeoutMs, void* tickCallbackContext) {
void us_loop_run_bun_tick(struct us_loop_t *loop, int64_t timeoutMs) {
us_loop_integrate(loop);
if (loop->num_polls == 0)
return;
if (tickCallbackContext) {
bun_on_tick_before(tickCallbackContext);
}
/* Emit pre callback */
us_internal_loop_pre(loop);
@@ -209,10 +202,6 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, int64_t timeoutMs, void* tickC
}
#endif
if (tickCallbackContext) {
bun_on_tick_after(tickCallbackContext);
}
/* Iterate ready polls, dispatching them by type */
for (loop->current_ready_poll = 0; loop->current_ready_poll < loop->num_ready_polls; loop->current_ready_poll++) {
struct us_poll_t *poll = GET_READY_POLL(loop, loop->current_ready_poll);
@@ -414,18 +403,14 @@ struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough, unsi
#endif
#ifdef LIBUS_USE_EPOLL
void us_timer_close(struct us_timer_t *timer, int fallthrough) {
void us_timer_close(struct us_timer_t *timer) {
struct us_internal_callback_t *cb = (struct us_internal_callback_t *) timer;
us_poll_stop(&cb->p, cb->loop);
close(us_poll_fd(&cb->p));
/* (regular) sockets are the only polls which are not freed immediately */
if(fallthrough){
us_free(timer);
}else {
us_poll_free((struct us_poll_t *) timer, cb->loop);
}
/* (regular) sockets are the only polls which are not freed immediately */
us_poll_free((struct us_poll_t *) timer, cb->loop);
}
void us_timer_set(struct us_timer_t *t, void (*cb)(struct us_timer_t *t), int ms, int repeat_ms) {
@@ -442,7 +427,7 @@ void us_timer_set(struct us_timer_t *t, void (*cb)(struct us_timer_t *t), int ms
us_poll_start((struct us_poll_t *) t, internal_cb->loop, LIBUS_SOCKET_READABLE);
}
#else
void us_timer_close(struct us_timer_t *timer, int fallthrough) {
void us_timer_close(struct us_timer_t *timer) {
struct us_internal_callback_t *internal_cb = (struct us_internal_callback_t *) timer;
struct kevent64_s event;
@@ -450,11 +435,7 @@ void us_timer_close(struct us_timer_t *timer, int fallthrough) {
kevent64(internal_cb->loop->fd, &event, 1, NULL, 0, 0, NULL);
/* (regular) sockets are the only polls which are not freed immediately */
if(fallthrough){
us_free(timer);
}else {
us_poll_free((struct us_poll_t *) timer, internal_cb->loop);
}
us_poll_free((struct us_poll_t *) timer, internal_cb->loop);
}
void us_timer_set(struct us_timer_t *t, void (*cb)(struct us_timer_t *t), int ms, int repeat_ms) {

View File

@@ -132,7 +132,7 @@ struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough, unsi
void *us_timer_ext(struct us_timer_t *timer);
/* */
void us_timer_close(struct us_timer_t *timer, int fallthrough);
void us_timer_close(struct us_timer_t *timer);
/* Arm a timer with a delay from now and eventually a repeat delay.
* Specify 0 as repeat delay to disable repeating. Specify both 0 to disarm. */
@@ -391,7 +391,6 @@ struct us_socket_t *us_socket_wrap_with_tls(int ssl, struct us_socket_t *s, stru
int us_socket_raw_write(int ssl, struct us_socket_t *s, const char *data, int length, int msg_more);
struct us_socket_t* us_socket_open(int ssl, struct us_socket_t * s, int is_client, char* ip, int ip_length);
int us_raw_root_certs(struct us_cert_string_t**out);
unsigned int us_get_remote_address_info(char *buf, struct us_socket_t *s, const char **dest, int *port, int *is_ipv6);
#ifdef __cplusplus
}

View File

@@ -47,7 +47,7 @@ void us_internal_loop_data_free(struct us_loop_t *loop) {
free(loop->data.recv_buf);
us_timer_close(loop->data.sweep_timer, 0);
us_timer_close(loop->data.sweep_timer);
us_internal_async_close(loop->data.wakeup_async);
}

View File

@@ -280,25 +280,3 @@ int us_socket_raw_write(int ssl, struct us_socket_t *s, const char *data, int le
// non-TLS is always raw
return us_socket_write(ssl, s, data, length, msg_more);
}
unsigned int us_get_remote_address_info(char *buf, struct us_socket_t *s, const char **dest, int *port, int *is_ipv6)
{
// This function is manual inlining + modification of
// us_socket_remote_address
// AsyncSocket::getRemoteAddress
// To get { ip, port, is_ipv6 } for Bun.serve().requestIP()
struct bsd_addr_t addr;
if (bsd_remote_addr(us_poll_fd(&s->p), &addr)) {
return 0;
}
int length = bsd_addr_get_ip_length(&addr);
if (!length) {
return 0;
}
memcpy(buf, bsd_addr_get_ip(&addr), length);
*port = bsd_addr_get_port(&addr);
return length;
}

View File

@@ -14,7 +14,7 @@ void uws_timer_close(struct us_timer_t *timer)
struct timer_handler_data *data;
memcpy(&data, us_timer_ext(t), sizeof(struct timer_handler_data *));
free(data);
us_timer_close(t, 0);
us_timer_close(t);
}
//Timer create helper
struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void *data), void *data)
@@ -47,7 +47,7 @@ struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void
if (!data->repeat)
{
free(data);
us_timer_close(t, 0);
us_timer_close(t);
}
},
ms, repeat_ms);

View File

@@ -19,7 +19,7 @@ void uws_timer_close(struct us_timer_t *timer)
struct timer_handler_data *data;
memcpy(&data, us_timer_ext(t), sizeof(struct timer_handler_data *));
free(data);
us_timer_close(t, 0);
us_timer_close(t);
}
//Timer create helper
struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void *data), void *data)
@@ -52,7 +52,7 @@ struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void
if (!data->repeat)
{
free(data);
us_timer_close(t, 0);
us_timer_close(t);
}
},
ms, repeat_ms);

View File

@@ -62,7 +62,7 @@ void uws_timer_close(struct us_timer_t *timer)
struct timer_handler_data *data;
memcpy(&data, us_timer_ext(t), sizeof(struct timer_handler_data *));
free(data);
us_timer_close(t, 0);
us_timer_close(t);
}
//Timer create helper
struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void *data), void *data)
@@ -95,7 +95,7 @@ struct us_timer_t *uws_create_timer(int ms, int repeat_ms, void (*handler)(void
if (!data->repeat)
{
free(data);
us_timer_close(t, 0);
us_timer_close(t);
}
},
ms, repeat_ms);

View File

@@ -205,7 +205,6 @@ extern "C"
DLL_EXPORT unsigned int uws_ws_get_buffered_amount(int ssl, uws_websocket_t *ws);
DLL_EXPORT size_t uws_ws_get_remote_address(int ssl, uws_websocket_t *ws, const char **dest);
DLL_EXPORT size_t uws_ws_get_remote_address_as_text(int ssl, uws_websocket_t *ws, const char **dest);
DLL_EXPORT void uws_res_get_remote_address_info(uws_res_t *res, const char **dest, size_t *length, unsigned int *port);
//Response
DLL_EXPORT void uws_res_end(int ssl, uws_res_t *res, const char *data, size_t length, bool close_connection);

View File

@@ -90,7 +90,7 @@ int main() {
delete upgradeData;
us_timer_close(t, 0);
us_timer_close(t);
}, 5000, 0);
},

View File

@@ -439,24 +439,6 @@ public:
return {internalEnd(data, totalSize, true, true, closeConnection), hasResponded()};
}
/* Write the end of chunked encoded stream */
bool sendTerminatingChunk(bool closeConnection = false) {
writeStatus(HTTP_200_OK);
HttpResponseData<SSL> *httpResponseData = getHttpResponseData();
if (!(httpResponseData->state & HttpResponseData<SSL>::HTTP_WRITE_CALLED)) {
/* Write mark on first call to write */
writeMark();
writeHeader("Transfer-Encoding", "chunked");
httpResponseData->state |= HttpResponseData<SSL>::HTTP_WRITE_CALLED;
}
/* Terminating 0 chunk */
Super::write("\r\n0\r\n\r\n", 7);
return internalEnd({nullptr, 0}, 0, false, false, closeConnection);
}
/* Write parts of the response in chunking fashion. Starts timeout if failed. */
bool write(std::string_view data) {
writeStatus(HTTP_200_OK);

View File

@@ -126,7 +126,7 @@ public:
LoopData *loopData = (LoopData *) us_loop_ext((us_loop_t *) this);
/* Stop and free dateTimer first */
us_timer_close(loopData->dateTimer, 1);
us_timer_close(loopData->dateTimer);
loopData->~LoopData();
/* uSockets will track whether this loop is owned by us or a borrowed alien loop */

1
src/api/schema.d.ts generated vendored
View File

@@ -719,7 +719,6 @@ export interface BunInstall {
global_bin_dir?: string;
frozen_lockfile?: boolean;
exact?: boolean;
use_github_api?: boolean;
}
export interface ClientServerModule {

10
src/api/schema.js generated
View File

@@ -3038,10 +3038,6 @@ function decodeBunInstall(bb) {
result["exact"] = !!bb.readByte();
break;
case 21:
result["use_github_api"] = !!bb.readByte();
break;
default:
throw new Error("Attempted to parse invalid message");
}
@@ -3174,12 +3170,6 @@ function encodeBunInstall(message, bb) {
bb.writeByte(20);
bb.writeByte(value);
}
var value = message["use_github_api"];
if (value != null) {
bb.writeByte(21);
bb.writeByte(value);
}
bb.writeByte(0);
}

View File

@@ -588,7 +588,6 @@ message BunInstall {
string global_bin_dir = 18;
bool frozen_lockfile = 19;
bool exact = 20;
bool use_github_api = 21;
}
struct ClientServerModule {

View File

@@ -2882,9 +2882,6 @@ pub const Api = struct {
/// exact
exact: ?bool = null,
/// use_github_api
use_github_api: ?bool = null,
pub fn decode(reader: anytype) anyerror!BunInstall {
var this = std.mem.zeroes(BunInstall);
@@ -2954,9 +2951,6 @@ pub const Api = struct {
20 => {
this.exact = try reader.readValue(bool);
},
21 => {
this.use_github_api = try reader.readValue(bool);
},
else => {
return error.InvalidMessage;
},
@@ -3046,10 +3040,6 @@ pub const Api = struct {
try writer.writeFieldID(20);
try writer.writeInt(@as(u8, @intFromBool(exact)));
}
if (this.use_github_api) |use_github_api| {
try writer.writeFieldID(21);
try writer.writeInt(@as(u8, @intFromBool(use_github_api)));
}
try writer.endMessage();
}
};

View File

@@ -1 +1 @@
5
4

View File

@@ -72,7 +72,6 @@ const TranspilerOptions = struct {
trim_unused_imports: ?bool = null,
inlining: bool = false,
dead_code_elimination: bool = true,
minify_whitespace: bool = false,
minify_identifiers: bool = false,
minify_syntax: bool = false,
@@ -542,10 +541,6 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std
transpiler.minify_whitespace = flag.toBoolean();
}
if (object.get(globalThis, "deadCodeElimination")) |flag| {
transpiler.dead_code_elimination = flag.toBoolean();
}
if (object.getTruthy(globalThis, "minify")) |hot| {
if (hot.isBoolean()) {
transpiler.minify_whitespace = hot.coerce(bool, globalThis);
@@ -805,7 +800,6 @@ pub fn constructor(
bundler.options.macro_remap = transpiler_options.macro_map;
}
bundler.options.dead_code_elimination = transpiler_options.dead_code_elimination;
bundler.options.minify_whitespace = transpiler_options.minify_whitespace;
// Keep defaults for these

View File

@@ -782,17 +782,11 @@ fn doResolveWithArgs(
var errorable: ErrorableString = undefined;
var query_string = ZigString.Empty;
const specifier_decoded = if (specifier.hasPrefixComptime("file://"))
bun.JSC.URL.pathFromFileURL(specifier)
else
specifier.dupeRef();
defer specifier_decoded.deref();
if (comptime is_file_path) {
VirtualMachine.resolveFilePathForAPI(
&errorable,
ctx.ptr(),
specifier_decoded,
specifier,
from,
&query_string,
is_esm,
@@ -801,7 +795,7 @@ fn doResolveWithArgs(
VirtualMachine.resolveForAPI(
&errorable,
ctx.ptr(),
specifier_decoded,
specifier,
from,
&query_string,
is_esm,
@@ -1104,12 +1098,10 @@ pub const Crypto = struct {
}
pub fn reset(this: *EVP, engine: *BoringSSL.ENGINE) void {
BoringSSL.ERR_clear_error();
_ = BoringSSL.EVP_DigestInit_ex(&this.ctx, this.md, engine);
}
pub fn hash(this: *EVP, engine: *BoringSSL.ENGINE, input: []const u8, output: []u8) ?u32 {
BoringSSL.ERR_clear_error();
var outsize: c_uint = @min(@as(u16, @truncate(output.len)), this.size());
if (BoringSSL.EVP_Digest(input.ptr, input.len, output.ptr, &outsize, this.md, engine) != 1) {
return null;
@@ -1119,7 +1111,6 @@ pub const Crypto = struct {
}
pub fn final(this: *EVP, engine: *BoringSSL.ENGINE, output: []u8) []const u8 {
BoringSSL.ERR_clear_error();
var outsize: u32 = @min(@as(u16, @truncate(output.len)), this.size());
if (BoringSSL.EVP_DigestFinal_ex(
&this.ctx,
@@ -1135,7 +1126,6 @@ pub const Crypto = struct {
}
pub fn update(this: *EVP, input: []const u8) void {
BoringSSL.ERR_clear_error();
_ = BoringSSL.EVP_DigestUpdate(&this.ctx, input.ptr, input.len);
}
@@ -1144,7 +1134,6 @@ pub const Crypto = struct {
}
pub fn copy(this: *const EVP, engine: *BoringSSL.ENGINE) error{OutOfMemory}!EVP {
BoringSSL.ERR_clear_error();
var new = init(this.algorithm, this.md, engine);
if (BoringSSL.EVP_MD_CTX_copy_ex(&new.ctx, &this.ctx) == 0) {
return error.OutOfMemory;
@@ -2015,6 +2004,7 @@ pub const Crypto = struct {
pub const digest = JSC.wrapInstanceMethod(CryptoHasher, "digest_", false);
pub const hash = JSC.wrapStaticMethod(CryptoHasher, "hash_", false);
pub fn getByteLength(
this: *CryptoHasher,
_: *JSC.JSGlobalObject,
@@ -3604,7 +3594,7 @@ pub const Timer = struct {
this.poll_ref.unref(vm);
this.timer.deinit(false);
this.timer.deinit();
// balance double unreffing in doUnref
vm.event_loop_handle.?.num_polls += @as(i32, @intFromBool(this.did_unref_timer));

View File

@@ -771,7 +771,7 @@ pub const Listener = struct {
Socket.dataSetCached(this_socket.getThisValue(globalObject), globalObject, default_data);
}
socket.ext(**anyopaque).?.* = bun.cast(**anyopaque, this_socket);
socket.setTimeout(120000);
socket.timeout(120000);
}
// pub fn addServerName(this: *Listener, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) callconv(.C) JSValue {
@@ -1599,7 +1599,7 @@ fn NewSocket(comptime ssl: bool) type {
return .zero;
}
this.socket.setTimeout(@as(c_uint, @intCast(t)));
this.socket.timeout(@as(c_uint, @intCast(t)));
return JSValue.jsUndefined();
}
@@ -2962,17 +2962,6 @@ pub fn NewWrappedHandler(comptime tls: bool) type {
}
}
pub fn onLongTimeout(
this: WrappedSocket,
socket: Socket,
) void {
if (comptime tls) {
TLSSocket.onTimeout(this.tls, socket);
} else {
TLSSocket.onTimeout(this.tcp, socket);
}
}
pub fn onConnectError(
this: WrappedSocket,
socket: Socket,

View File

@@ -317,9 +317,9 @@ pub const FFI = struct {
};
};
};
var size = symbols.values().len;
if (size >= 63) {
if(size >= 63) {
size = 0;
}
var obj = JSC.JSValue.createEmptyObject(global, size);

View File

@@ -24,10 +24,6 @@ function generate(name) {
fn: "doStop",
length: 1,
},
requestIP: {
fn: "doRequestIP",
length: 1,
},
port: {
getter: "getPort",
},

View File

@@ -1125,92 +1125,6 @@ fn NewFlags(comptime debug_mode: bool) type {
};
}
/// A generic wrapper for the HTTP(s) Server`RequestContext`s.
/// Only really exists because of `NewServer()` and `NewRequestContext()` generics.
pub const AnyRequestContext = struct {
pub const Pointer = bun.TaggedPointerUnion(.{
HTTPServer.RequestContext,
HTTPSServer.RequestContext,
DebugHTTPServer.RequestContext,
DebugHTTPSServer.RequestContext,
});
tagged_pointer: Pointer,
pub const Null = .{ .tagged_pointer = Pointer.Null };
pub fn init(request_ctx: anytype) AnyRequestContext {
return .{ .tagged_pointer = Pointer.init(request_ctx) };
}
pub fn getRemoteSocketInfo(self: AnyRequestContext) ?uws.SocketAddress {
if (self.tagged_pointer.isNull()) {
return null;
}
switch (self.tagged_pointer.tag()) {
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(HTTPServer.RequestContext))) => {
return self.tagged_pointer.as(HTTPServer.RequestContext).getRemoteSocketInfo();
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(HTTPSServer.RequestContext))) => {
return self.tagged_pointer.as(HTTPSServer.RequestContext).getRemoteSocketInfo();
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(DebugHTTPServer.RequestContext))) => {
return self.tagged_pointer.as(DebugHTTPServer.RequestContext).getRemoteSocketInfo();
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(DebugHTTPSServer.RequestContext))) => {
return self.tagged_pointer.as(DebugHTTPSServer.RequestContext).getRemoteSocketInfo();
},
else => @panic("Unexpected AnyRequestContext tag"),
}
}
/// Wont actually set anything if `self` is `.none`
pub fn setRequest(self: AnyRequestContext, req: *uws.Request) void {
if (self.tagged_pointer.isNull()) {
return;
}
switch (self.tagged_pointer.tag()) {
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(HTTPServer.RequestContext))) => {
self.tagged_pointer.as(HTTPServer.RequestContext).req = req;
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(HTTPSServer.RequestContext))) => {
self.tagged_pointer.as(HTTPSServer.RequestContext).req = req;
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(DebugHTTPServer.RequestContext))) => {
self.tagged_pointer.as(DebugHTTPServer.RequestContext).req = req;
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(DebugHTTPSServer.RequestContext))) => {
self.tagged_pointer.as(DebugHTTPSServer.RequestContext).req = req;
},
else => @panic("Unexpected AnyRequestContext tag"),
}
}
pub fn getRequest(self: AnyRequestContext) ?*uws.Request {
if (self.tagged_pointer.isNull()) {
return null;
}
switch (self.tagged_pointer.tag()) {
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(HTTPServer.RequestContext))) => {
return self.tagged_pointer.as(HTTPServer.RequestContext).req;
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(HTTPSServer.RequestContext))) => {
return self.tagged_pointer.as(HTTPSServer.RequestContext).req;
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(DebugHTTPServer.RequestContext))) => {
return self.tagged_pointer.as(DebugHTTPServer.RequestContext).req;
},
@field(Pointer.Tag, bun.meta.typeBaseName(@typeName(DebugHTTPSServer.RequestContext))) => {
return self.tagged_pointer.as(DebugHTTPSServer.RequestContext).req;
},
else => @panic("Unexpected AnyRequestContext tag"),
}
}
};
// This is defined separately partially to work-around an LLVM debugger bug.
fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comptime ThisServer: type) type {
return struct {
@@ -1529,7 +1443,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
}
pub fn endStream(this: *RequestContext, closeConnection: bool) void {
ctxLog("endStream", .{});
if (this.resp) |resp| {
if (this.flags.is_waiting_for_request_body) {
this.flags.is_waiting_for_request_body = false;
@@ -1816,7 +1729,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
this: *RequestContext,
headers: *JSC.FetchHeaders,
) void {
ctxLog("writeHeaders", .{});
headers.fastRemove(.ContentLength);
headers.fastRemove(.TransferEncoding);
if (!ssl_enabled) headers.fastRemove(.StrictTransportSecurity);
@@ -2188,7 +2100,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
}
fn doRenderStream(pair: *StreamPair) void {
ctxLog("doRenderStream", .{});
var this = pair.this;
var stream = pair.stream;
if (this.resp == null or this.flags.aborted) {
@@ -2312,14 +2223,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
},
}
return;
} else {
// if is not a promise we treat it as Error
streamLog("returned an error", .{});
if (!this.flags.aborted) resp.clearAborted();
response_stream.detach();
this.sink = null;
response_stream.sink.destroy();
return this.handleReject(assignment_result);
}
}
@@ -2329,7 +2232,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
defer stream.value.unprotect();
response_stream.sink.markDone();
this.finalizeForAbort();
response_stream.sink.onFirstWrite = null;
response_stream.sink.finalize();
return;
@@ -2353,12 +2255,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
this.setAbortHandler();
streamLog("is in progress, but did not return a Promise. Finalizing request context", .{});
response_stream.sink.onFirstWrite = null;
response_stream.sink.ctx = null;
response_stream.detach();
stream.cancel(globalThis);
response_stream.sink.markDone();
this.renderMissing();
this.finalize();
}
const streamLog = Output.scoped(.ReadableStream, false);
@@ -2368,7 +2265,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
}
fn toAsyncWithoutAbortHandler(ctx: *RequestContext, req: *uws.Request, request_object: *Request) void {
request_object.request_context.setRequest(req);
request_object.uws_request = req;
request_object.ensureURL() catch {
request_object.url = bun.String.empty;
@@ -2381,7 +2278,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
// This object dies after the stack frame is popped
// so we have to clear it in here too
request_object.request_context = JSC.API.AnyRequestContext.Null;
request_object.uws_request = null;
}
fn toAsync(
@@ -2558,6 +2455,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
}
streamLog("onResolve({any})", .{wrote_anything});
//aborted so call finalizeForAbort
if (req.flags.aborted or req.resp == null) {
req.finalizeForAbort();
@@ -3254,10 +3152,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
return onStartStreamingRequestBody(bun.cast(*RequestContext, this));
}
pub fn getRemoteSocketInfo(this: *RequestContext) ?uws.SocketAddress {
return (this.resp orelse return null).getRemoteSocketInfo();
}
pub const Export = shim.exportFunctions(.{
.onResolve = onResolve,
.onReject = onReject,
@@ -4783,6 +4677,17 @@ pub const ServerWebSocket = struct {
return JSValue.jsBoolean(this.websocket.isSubscribed(topic.slice()));
}
// pub fn getTopics(
// this: *ServerWebSocket,
// globalThis: *JSC.JSGlobalObject,
// ) callconv(.C) JSValue {
// if (this.closed) {
// return JSValue.createStringArray(globalThis, bun.default_allocator, null, 0, false);
// }
// this
// }
pub fn getRemoteAddress(
this: *ServerWebSocket,
globalThis: *JSC.JSGlobalObject,
@@ -4809,7 +4714,7 @@ pub const ServerWebSocket = struct {
pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
return struct {
pub const ssl_enabled = ssl_enabled_;
pub const debug_mode = debug_mode_;
const debug_mode = debug_mode_;
const ThisServer = @This();
pub const RequestContext = NewRequestContext(ssl_enabled, debug_mode, @This());
@@ -4847,7 +4752,6 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
pub const doPublish = JSC.wrapInstanceMethod(ThisServer, "publish", false);
pub const doReload = onReload;
pub const doFetch = onFetch;
pub const doRequestIP = JSC.wrapInstanceMethod(ThisServer, "requestIP", false);
pub usingnamespace NamespaceType;
@@ -4855,24 +4759,6 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
globalThis.throw("Server() is not a constructor", .{});
return null;
}
extern fn JSSocketAddress__create(global: *JSC.JSGlobalObject, ip: JSValue, port: i32, is_ipv6: bool) JSValue;
pub fn requestIP(this: *ThisServer, request: *JSC.WebCore.Request) JSC.JSValue {
if (this.config.address == .unix) {
return JSValue.jsNull();
}
return if (request.request_context.getRemoteSocketInfo()) |info|
JSSocketAddress__create(
this.globalThis,
bun.String.static(info.ip).toJSConst(this.globalThis),
info.port,
info.is_ipv6,
)
else
JSValue.jsNull();
}
pub fn publish(this: *ThisServer, globalThis: *JSC.JSGlobalObject, topic: ZigString, message_value: JSValue, compress_value: ?JSValue, exception: JSC.C.ExceptionRef) JSValue {
if (this.config.websocket == null)
return JSValue.jsNumber(0);
@@ -5216,7 +5102,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
return JSPromise.rejectedPromiseValue(ctx, err);
}
var request = bun.default_allocator.create(Request) catch unreachable;
var request = ctx.bunVM().allocator.create(Request) catch unreachable;
request.* = existing_request;
const response_value = this.config.onRequest.callWithThis(
@@ -5636,19 +5522,21 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
req.setYield(false);
var ctx = this.request_pool_allocator.tryGet() catch @panic("ran out of memory");
ctx.create(this, req, resp);
this.vm.jsc.reportExtraMemory(@sizeOf(RequestContext));
var request_object = this.allocator.create(JSC.WebCore.Request) catch unreachable;
var body = JSC.WebCore.InitRequestBodyValue(.{ .Null = {} }) catch unreachable;
ctx.request_body = body;
var signal = JSC.WebCore.AbortSignal.new(this.globalThis);
ctx.signal = signal;
const js_signal = JSC.WebCore.AbortSignal.create(this.globalThis);
js_signal.ensureStillAlive();
if (JSC.WebCore.AbortSignal.fromJS(js_signal)) |signal| {
ctx.signal = signal.ref().ref(); // +2 refs 1 for the request and 1 for the request context
}
request_object.* = .{
.method = ctx.method,
.request_context = AnyRequestContext.init(ctx),
.uws_request = req,
.https = ssl_enabled,
.signal = signal.ref(),
.signal = ctx.signal,
.body = body.ref(),
};
@@ -5715,7 +5603,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
const response_value = this.config.onRequest.callWithThis(this.globalThis, this.thisObject, &args);
defer {
// uWS request will not live longer than this function
request_object.request_context = JSC.API.AnyRequestContext.Null;
request_object.uws_request = null;
}
var should_deinit_context = false;
@@ -5730,7 +5618,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
ctx.defer_deinit_until_callback_completes = null;
if (should_deinit_context) {
request_object.request_context = JSC.API.AnyRequestContext.Null;
request_object.uws_request = null;
ctx.deinit();
return;
}
@@ -5759,15 +5647,18 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
var body = JSC.WebCore.InitRequestBodyValue(.{ .Null = {} }) catch unreachable;
ctx.request_body = body;
var signal = JSC.WebCore.AbortSignal.new(this.globalThis);
ctx.signal = signal;
const js_signal = JSC.WebCore.AbortSignal.create(this.globalThis);
js_signal.ensureStillAlive();
if (JSC.WebCore.AbortSignal.fromJS(js_signal)) |signal| {
ctx.signal = signal.ref().ref(); // +2 refs 1 for the request and 1 for the request context
}
request_object.* = .{
.method = ctx.method,
.request_context = AnyRequestContext.init(ctx),
.uws_request = req,
.upgrader = ctx,
.https = ssl_enabled,
.signal = signal.ref(),
.signal = ctx.signal,
.body = body.ref(),
};
ctx.upgrade_context = upgrade_ctx;
@@ -5782,7 +5673,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
const response_value = this.config.onRequest.callWithThis(this.globalThis, this.thisObject, &args);
defer {
// uWS request will not live longer than this function
request_object.request_context = JSC.API.AnyRequestContext.Null;
request_object.uws_request = null;
}
var should_deinit_context = false;
@@ -5797,7 +5688,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
ctx.defer_deinit_until_callback_completes = null;
if (should_deinit_context) {
request_object.request_context = JSC.API.AnyRequestContext.Null;
request_object.uws_request = null;
ctx.deinit();
return;
}

View File

@@ -17,10 +17,8 @@
#include "JavaScriptCore/RegExpObject.h"
#include "JavaScriptCore/JSPromise.h"
#include "BunClientData.h"
#include "isBuiltinModule.h"
#include "JavaScriptCore/RegularExpression.h"
#include "JavaScriptCore/JSMap.h"
#include "JavaScriptCore/JSMapInlines.h"
namespace Zig {
@@ -88,76 +86,6 @@ static EncodedJSValue jsFunctionAppendOnLoadPluginBody(JSC::JSGlobalObject* glob
return JSValue::encode(jsUndefined());
}
static EncodedJSValue jsFunctionAppendVirtualModulePluginBody(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
if (callframe->argumentCount() < 2) {
throwException(globalObject, scope, createError(globalObject, "module() needs 2 arguments: a module ID and a function to call"_s));
return JSValue::encode(jsUndefined());
}
JSValue moduleIdValue = callframe->uncheckedArgument(0);
JSValue functionValue = callframe->uncheckedArgument(1);
if (!moduleIdValue.isString()) {
throwException(globalObject, scope, createError(globalObject, "module() expects first argument to be a string for the module ID"_s));
return JSValue::encode(jsUndefined());
}
if (!functionValue.isCallable()) {
throwException(globalObject, scope, createError(globalObject, "module() expects second argument to be a function"_s));
return JSValue::encode(jsUndefined());
}
String moduleId = moduleIdValue.toWTFString(globalObject);
RETURN_IF_EXCEPTION(scope, encodedJSValue());
if (moduleId.isEmpty()) {
throwException(globalObject, scope, createError(globalObject, "virtual module cannot be blank"_s));
return JSValue::encode(jsUndefined());
}
if (Bun::isBuiltinModule(moduleId)) {
throwException(globalObject, scope, createError(globalObject, makeString("module() cannot be used to override builtin module \""_s, moduleId, "\""_s)));
return JSValue::encode(jsUndefined());
}
if (moduleId.startsWith("."_s)) {
throwException(globalObject, scope, createError(globalObject, "virtual module cannot start with \".\""_s));
return JSValue::encode(jsUndefined());
}
Zig::GlobalObject* global = Zig::jsCast<Zig::GlobalObject*>(globalObject);
if (global->onLoadPlugins.virtualModules == nullptr) {
global->onLoadPlugins.virtualModules = new BunPlugin::VirtualModuleMap;
}
auto* virtualModules = global->onLoadPlugins.virtualModules;
virtualModules->set(moduleId, JSC::Strong<JSC::JSObject> { vm, jsCast<JSC::JSObject*>(functionValue) });
JSMap* esmRegistry;
if (auto loaderValue = global->getIfPropertyExists(global, JSC::Identifier::fromString(vm, "Loader"_s))) {
if (auto registryValue = loaderValue.getObject()->getIfPropertyExists(global, JSC::Identifier::fromString(vm, "registry"_s))) {
esmRegistry = jsCast<JSC::JSMap*>(registryValue);
}
}
global->requireMap()->remove(globalObject, moduleIdValue);
esmRegistry && esmRegistry->remove(globalObject, moduleIdValue);
// bool hasBeenRequired = global->requireMap()->has(globalObject, moduleIdValue);
// bool hasBeenImported = esmRegistry && esmRegistry->has(globalObject, moduleIdValue);
// if (hasBeenRequired || hasBeenImported) {
// // callAndReplaceModule(global, moduleIdValue, functionValue, global->requireMap(), esmRegistry, hasBeenRequired, hasBeenImported);
// // RETURN_IF_EXCEPTION(scope, encodedJSValue());
// }
return JSValue::encode(jsUndefined());
}
static EncodedJSValue jsFunctionAppendOnResolvePluginBody(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target, BunPlugin::Base& plugin, void* ctx, OnAppendPluginCallback callback)
{
JSC::VM& vm = globalObject->vm();
@@ -215,7 +143,7 @@ static EncodedJSValue jsFunctionAppendOnResolvePluginGlobal(JSC::JSGlobalObject*
{
Zig::GlobalObject* global = Zig::jsCast<Zig::GlobalObject*>(globalObject);
auto& plugins = global->onResolvePlugins;
auto& plugins = global->onResolvePlugins[target];
auto callback = Bun__onDidAppendPlugin;
return jsFunctionAppendOnResolvePluginBody(globalObject, callframe, target, plugins, global->bunVM(), callback);
}
@@ -224,7 +152,7 @@ static EncodedJSValue jsFunctionAppendOnLoadPluginGlobal(JSC::JSGlobalObject* gl
{
Zig::GlobalObject* global = Zig::jsCast<Zig::GlobalObject*>(globalObject);
auto& plugins = global->onLoadPlugins;
auto& plugins = global->onLoadPlugins[target];
auto callback = Bun__onDidAppendPlugin;
return jsFunctionAppendOnLoadPluginBody(globalObject, callframe, target, plugins, global->bunVM(), callback);
}
@@ -254,11 +182,6 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionAppendOnResolvePluginBun, (JSC::JSGlobalObjec
return jsFunctionAppendOnResolvePluginGlobal(globalObject, callframe, BunPluginTargetBun);
}
JSC_DEFINE_HOST_FUNCTION(jsFunctionAppendVirtualModule, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callframe))
{
return jsFunctionAppendVirtualModulePluginBody(globalObject, callframe);
}
JSC_DEFINE_HOST_FUNCTION(jsFunctionAppendOnResolvePluginBrowser, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callframe))
{
return jsFunctionAppendOnResolvePluginGlobal(globalObject, callframe, BunPluginTargetBrowser);
@@ -267,12 +190,12 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionAppendOnResolvePluginBrowser, (JSC::JSGlobalO
extern "C" EncodedJSValue jsFunctionBunPluginClear(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
{
Zig::GlobalObject* global = reinterpret_cast<Zig::GlobalObject*>(globalObject);
global->onLoadPlugins.fileNamespace.clear();
global->onResolvePlugins.fileNamespace.clear();
global->onLoadPlugins.groups.clear();
global->onResolvePlugins.namespaces.clear();
delete global->onLoadPlugins.virtualModules;
for (uint8_t i = 0; i < BunPluginTargetMax + 1; i++) {
global->onLoadPlugins[i].fileNamespace.clear();
global->onResolvePlugins[i].fileNamespace.clear();
global->onLoadPlugins[i].groups.clear();
global->onResolvePlugins[i].namespaces.clear();
}
return JSValue::encode(jsUndefined());
}
@@ -316,37 +239,76 @@ extern "C" EncodedJSValue setupBunPlugin(JSC::JSGlobalObject* globalObject, JSC:
}
JSFunction* setupFunction = jsCast<JSFunction*>(setupFunctionValue);
JSObject* builderObject = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 4);
JSObject* builderObject = JSC::constructEmptyObject(globalObject, globalObject->objectPrototype(), 3);
builderObject->putDirect(vm, Identifier::fromString(vm, "target"_s), jsString(vm, String("bun"_s)), 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onLoad"_s),
1,
jsFunctionAppendOnLoadPluginBun,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onResolve"_s),
1,
jsFunctionAppendOnResolvePluginBun,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "module"_s),
1,
jsFunctionAppendVirtualModule,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
switch (target) {
case BunPluginTargetNode: {
builderObject->putDirect(vm, Identifier::fromString(vm, "target"_s), jsString(vm, String("node"_s)), 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onLoad"_s),
1,
jsFunctionAppendOnLoadPluginNode,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onResolve"_s),
1,
jsFunctionAppendOnResolvePluginNode,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
break;
}
case BunPluginTargetBun: {
builderObject->putDirect(vm, Identifier::fromString(vm, "target"_s), jsString(vm, String("bun"_s)), 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onLoad"_s),
1,
jsFunctionAppendOnLoadPluginBun,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onResolve"_s),
1,
jsFunctionAppendOnResolvePluginBun,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
break;
}
case BunPluginTargetBrowser: {
builderObject->putDirect(vm, Identifier::fromString(vm, "target"_s), jsString(vm, String("browser"_s)), 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onLoad"_s),
1,
jsFunctionAppendOnLoadPluginBrowser,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
builderObject->putDirectNativeFunction(
vm,
globalObject,
JSC::Identifier::fromString(vm, "onResolve"_s),
1,
jsFunctionAppendOnResolvePluginBrowser,
ImplementationVisibility::Public,
NoIntrinsic,
JSC::PropertyAttribute::DontDelete | 0);
break;
}
}
JSC::MarkedArgumentBuffer args;
args.append(builderObject);
@@ -367,7 +329,9 @@ extern "C" EncodedJSValue setupBunPlugin(JSC::JSGlobalObject* globalObject, JSC:
extern "C" EncodedJSValue jsFunctionBunPlugin(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
{
Zig::GlobalObject* global = reinterpret_cast<Zig::GlobalObject*>(globalObject);
return setupBunPlugin(globalObject, callframe, BunPluginTargetBun);
BunPluginTarget target = global->defaultBunPluginTarget;
return setupBunPlugin(globalObject, callframe, target);
}
void BunPlugin::Group::append(JSC::VM& vm, JSC::RegExp* filter, JSC::JSFunction* func)
@@ -549,60 +513,10 @@ EncodedJSValue BunPlugin::OnResolve::run(JSC::JSGlobalObject* globalObject, BunS
extern "C" JSC::EncodedJSValue Bun__runOnResolvePlugins(Zig::GlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* from, BunPluginTarget target)
{
return globalObject->onResolvePlugins.run(globalObject, namespaceString, path, from);
return globalObject->onResolvePlugins[target].run(globalObject, namespaceString, path, from);
}
extern "C" JSC::EncodedJSValue Bun__runOnLoadPlugins(Zig::GlobalObject* globalObject, BunString* namespaceString, BunString* path, BunPluginTarget target)
{
return globalObject->onLoadPlugins.run(globalObject, namespaceString, path);
return globalObject->onLoadPlugins[target].run(globalObject, namespaceString, path);
}
namespace Bun {
JSC::JSValue runVirtualModule(Zig::GlobalObject* globalObject, BunString* specifier)
{
auto fallback = [&]() -> JSC::JSValue {
return JSValue::decode(Bun__runVirtualModule(globalObject, specifier));
};
if (!globalObject->onLoadPlugins.virtualModules) {
return fallback();
}
auto& virtualModules = *globalObject->onLoadPlugins.virtualModules;
WTF::String specifierString = Bun::toWTFString(*specifier);
if (auto virtualModuleFn = virtualModules.get(specifierString)) {
auto& vm = globalObject->vm();
JSC::JSObject* function = virtualModuleFn.get();
auto throwScope = DECLARE_THROW_SCOPE(vm);
JSC::MarkedArgumentBuffer arguments;
JSC::CallData callData = JSC::getCallData(function);
RELEASE_ASSERT(callData.type != JSC::CallData::Type::None);
auto result = call(globalObject, function, callData, JSC::jsUndefined(), arguments);
RETURN_IF_EXCEPTION(throwScope, JSC::jsUndefined());
if (auto* promise = JSC::jsDynamicCast<JSPromise*>(result)) {
switch (promise->status(vm)) {
case JSPromise::Status::Rejected:
case JSPromise::Status::Pending: {
return promise;
}
case JSPromise::Status::Fulfilled: {
result = promise->result(vm);
break;
}
}
}
if (!result.isObject()) {
JSC::throwTypeError(globalObject, throwScope, "virtual module expects an object returned"_s);
return JSC::jsUndefined();
}
return result;
}
return fallback();
}
}

View File

@@ -15,8 +15,6 @@ using namespace JSC;
class BunPlugin {
public:
using VirtualModuleMap = WTF::HashMap<String, JSC::Strong<JSC::JSObject>>;
// This is a list of pairs of regexps and functions to match against
class Group {
@@ -69,15 +67,7 @@ public:
{
}
VirtualModuleMap* virtualModules = nullptr;
JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path);
~OnLoad()
{
if (virtualModules) {
delete virtualModules;
}
}
EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path);
};
class OnResolve final : public Base {
@@ -88,14 +78,8 @@ public:
{
}
JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* importer);
EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* importer);
};
};
class GlobalObject;
} // namespace Zig
namespace Bun {
JSC::JSValue runVirtualModule(Zig::GlobalObject*, BunString* specifier);
}
} // namespace Zig

View File

@@ -9,7 +9,6 @@
#include <wtf/text/AtomString.h>
using namespace JSC;
extern "C" BunString BunString__fromBytes(const char* bytes, size_t length);
extern "C" bool Bun__WTFStringImpl__hasPrefix(const WTF::StringImpl* impl, const char* bytes, size_t length)
{
@@ -75,10 +74,7 @@ JSC::JSValue toJS(JSC::JSGlobalObject* globalObject, BunString bunString, size_t
#endif
return jsSubstring(globalObject, jsUndefined(), Bun::toWTFString(bunString), 0, length);
}
BunString toString(const char* bytes, size_t length)
{
return BunString__fromBytes(bytes, length);
}
WTF::String toWTFString(const BunString& bunString)
{
if (bunString.tag == BunStringTag::ZigString) {
@@ -194,6 +190,22 @@ BunString toStringRef(WTF::StringImpl* wtfString)
return { BunStringTag::WTFStringImpl, { .wtf = wtfString } };
}
BunString fromString(WTF::String& wtfString)
{
if (wtfString.isEmpty())
return { BunStringTag::Empty };
return { BunStringTag::WTFStringImpl, { .wtf = wtfString.impl() } };
}
BunString fromString(WTF::StringImpl* wtfString)
{
if (wtfString->isEmpty())
return { BunStringTag::Empty };
return { BunStringTag::WTFStringImpl, { .wtf = wtfString } };
}
}
extern "C" JSC::EncodedJSValue BunString__toJS(JSC::JSGlobalObject* globalObject, BunString* bunString)
@@ -240,7 +252,7 @@ extern "C" BunString BunString__fromUTF8(const char* bytes, size_t length)
auto str = WTF::String::fromUTF8ReplacingInvalidSequences(reinterpret_cast<const LChar*>(bytes), length);
str.impl()->ref();
return Bun::toString(str);
return Bun::fromString(str);
}
extern "C" BunString BunString__fromLatin1(const char* bytes, size_t length)
@@ -369,17 +381,7 @@ extern "C" BunString URL__getHref(BunString* input)
return Bun::toStringRef(url.string());
}
extern "C" BunString URL__pathFromFileURL(BunString* input)
{
auto&& str = Bun::toWTFString(*input);
auto url = WTF::URL(str);
if (!url.isValid() || url.isEmpty())
return { BunStringTag::Dead };
return Bun::toStringRef(url.fileSystemPath());
}
extern "C" BunString URL__getHrefJoin(BunString* baseStr, BunString* relativeStr)
extern "C" BunString URL__getHrefJoin(BunString* baseStr, BunString *relativeStr)
{
auto base = Bun::toWTFString(*baseStr);
auto relative = Bun::toWTFString(*relativeStr);
@@ -453,4 +455,4 @@ extern "C" uint32_t URL__port(WTF::URL* url)
extern "C" BunString URL__pathname(WTF::URL* url)
{
return Bun::toStringRef(url->path().toStringWithoutCopying());
}
}

View File

@@ -8,7 +8,7 @@
* Then, at runtime, we create a JSCommonJSModule object.
*
* On this special object, we override the setter for the "exports" property in
* a non-observable way using a CustomGetterSetter.
* a non-observable way (`static bool put ...`)
*
* When the setter is called, we set the internal "exports" property to the
* value passed in and we also update the requireMap with the new value.
@@ -20,13 +20,17 @@
*
* If an exception occurs, we remove the entry from the requireMap.
*
* How cyclical dependencies are handled:
* We tried using a CustomGetterSetter instead of overriding `put`, but it led
* to returning the getter itself
*
* How cyclical dependencies are handled
*
* Before executing the CommonJS module, we set the exports object in the
* requireMap to an empty object. When the CommonJS module is required again, we
* return the exports object from the requireMap. The values should be in sync
* while the module is being executed, unless module.exports is re-assigned to a
* different value. In that case, it will have a stale value.
*
*/
#include "root.h"
@@ -94,35 +98,29 @@ static bool canPerformFastEnumeration(Structure* s)
static bool evaluateCommonJSModuleOnce(JSC::VM& vm, Zig::GlobalObject* globalObject, JSCommonJSModule* moduleObject, JSString* dirname, JSValue filename, WTF::NakedPtr<Exception>& exception)
{
JSC::Structure* thisObjectStructure = globalObject->commonJSFunctionArgumentsStructure();
JSC::JSObject* thisObject = JSC::constructEmptyObject(
vm,
thisObjectStructure);
thisObject->putDirectOffset(
vm,
0,
moduleObject);
JSFunction* resolveFunction = JSC::JSBoundFunction::create(vm,
globalObject,
globalObject->requireResolveFunctionUnbound(),
moduleObject->id(),
ArgList(), 1, jsString(vm, String("resolve"_s)));
JSFunction* requireFunction = JSC::JSBoundFunction::create(vm,
globalObject,
globalObject->requireFunctionUnbound(),
moduleObject,
ArgList(), 1, jsString(vm, String("require"_s)));
requireFunction->putDirect(vm, vm.propertyNames->resolve, resolveFunction, 0);
moduleObject->putDirect(vm, WebCore::clientData(vm)->builtinNames().requirePublicName(), requireFunction, 0);
thisObject->putDirectOffset(
vm,
1,
dirname);
JSC::JSObject* thisObject = JSC::constructEmptyObject(vm, thisObjectStructure);
thisObject->putDirectOffset(vm, 0, moduleObject);
thisObject->putDirectOffset(vm, 1, requireFunction);
thisObject->putDirectOffset(vm, 2, resolveFunction);
thisObject->putDirectOffset(vm, 3, dirname);
thisObject->putDirectOffset(vm, 4, filename);
thisObject->putDirectOffset(
vm,
2,
filename);
moduleObject->hasEvaluated = true;
// TODO: try to not use this write barrier. it needs some extensive testing.
// there is some possible GC issue where `thisObject` is gc'd before it should be
globalObject->m_BunCommonJSModuleValue.set(vm, globalObject, thisObject);
JSValue empty = JSC::evaluate(globalObject, moduleObject->sourceCode.get()->sourceCode(), thisObject, exception);
ensureStillAliveHere(thisObject);
globalObject->m_BunCommonJSModuleValue.clear();
moduleObject->sourceCode.clear();
@@ -400,9 +398,9 @@ JSC_DEFINE_HOST_FUNCTION(functionCommonJSModuleRecord_compile, (JSGlobalObject *
RETURN_IF_EXCEPTION(throwScope, JSValue::encode({}));
String wrappedString = makeString(
"(function(exports,require,module,__filename,__dirname){"_s,
"(function(module,exports,require,__dirname,__filename){"_s,
sourceString,
"\n}).call(this.module.exports,this.module.exports,this.require,this.module,this.__filename,this.__dirname)"_s);
"\n}).call($_BunCommonJSModule_$.module.exports, $_BunCommonJSModule_$.module, $_BunCommonJSModule_$.module.exports, ($_BunCommonJSModule_$.module.require = $_BunCommonJSModule_$.module.require.bind($_BunCommonJSModule_$.module), $_BunCommonJSModule_$.module.require.path = $_BunCommonJSModule_$.module.id, $_BunCommonJSModule_$.module.require.resolve = $_BunCommonJSModule_$.module.require.resolve.bind($_BunCommonJSModule_$.module.id), $_BunCommonJSModule_$.module.require), $_BunCommonJSModule_$.__dirname, $_BunCommonJSModule_$.__filename);"_s);
SourceCode sourceCode = makeSource(
WTFMove(wrappedString),
@@ -485,12 +483,14 @@ public:
ASSERT(inherits(vm, info()));
reifyStaticProperties(vm, JSCommonJSModule::info(), JSCommonJSModulePrototypeTableValues, *this);
this->putDirect(vm, clientData(vm)->builtinNames().requirePublicName(), (static_cast<Zig::GlobalObject*>(globalObject))->requireFunctionUnbound(), PropertyAttribute::Builtin | PropertyAttribute::Function | 0);
this->putDirectNativeFunction(
vm,
globalObject,
clientData(vm)->builtinNames().requirePrivateName(),
2,
jsFunctionRequireCommonJS, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontDelete);
jsFunctionRequireCommonJS, ImplementationVisibility::Public, NoIntrinsic, JSC::PropertyAttribute::ReadOnly | 0);
}
};
@@ -774,6 +774,21 @@ JSValue JSCommonJSModule::id()
return m_id.get();
}
bool JSCommonJSModule::put(
JSC::JSCell* cell,
JSC::JSGlobalObject* globalObject,
JSC::PropertyName propertyName,
JSC::JSValue value,
JSC::PutPropertySlot& slot)
{
auto& vm = globalObject->vm();
auto* clientData = WebCore::clientData(vm);
auto throwScope = DECLARE_THROW_SCOPE(vm);
RELEASE_AND_RETURN(throwScope, Base::put(cell, globalObject, propertyName, value, slot));
}
template<typename, SubspaceAccess mode> JSC::GCClient::IsoSubspace* JSCommonJSModule::subspaceFor(JSC::VM& vm)
{
if constexpr (mode == JSC::SubspaceAccess::Concurrently)
@@ -1007,7 +1022,7 @@ JSObject* JSCommonJSModule::createBoundRequireFunction(VM& vm, JSGlobalObject* l
globalObject,
globalObject->requireResolveFunctionUnbound(),
moduleObject,
ArgList(), 1, jsString(vm, String("resolve"_s)));
ArgList(), 1, jsString(vm, String("require"_s)));
requireFunction->putDirect(vm, builtinNames.resolvePublicName(), resolveFunction, PropertyAttribute::Function | 0);

View File

@@ -20,7 +20,7 @@ JSC_DECLARE_HOST_FUNCTION(jsFunctionLoadModule);
class JSCommonJSModule final : public JSC::JSDestructibleObject {
public:
using Base = JSC::JSDestructibleObject;
static constexpr unsigned StructureFlags = Base::StructureFlags;
static constexpr unsigned StructureFlags = Base::StructureFlags | JSC::OverridesPut;
mutable JSC::WriteBarrier<JSString> m_id;
mutable JSC::WriteBarrier<Unknown> m_filename;
@@ -74,6 +74,10 @@ public:
DECLARE_VISIT_CHILDREN;
static bool put(JSC::JSCell* cell, JSC::JSGlobalObject* globalObject,
JSC::PropertyName propertyName, JSC::JSValue value,
JSC::PutPropertySlot& slot);
DECLARE_INFO;
template<typename, SubspaceAccess mode>
static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm);

View File

@@ -64,12 +64,6 @@ static EncodedJSValue functionRequireResolve(JSC::JSGlobalObject* globalObject,
JSC::JSValue moduleName = callFrame->argument(0);
auto doIt = [&](const WTF::String& fromStr) -> JSC::EncodedJSValue {
if (auto* virtualModules = jsCast<Zig::GlobalObject*>(globalObject)->onLoadPlugins.virtualModules) {
if (virtualModules->contains(fromStr)) {
return JSC::JSValue::encode(jsString(vm, fromStr));
}
}
BunString from = Bun::toString(fromStr);
auto result = Bun__resolveSyncWithSource(globalObject, JSC::JSValue::encode(moduleName), &from, false);
@@ -166,14 +160,6 @@ extern "C" EncodedJSValue functionImportMeta__resolveSync(JSC::JSGlobalObject* g
JSC__JSValue from;
bool isESM = true;
if (auto* virtualModules = jsCast<Zig::GlobalObject*>(globalObject)->onLoadPlugins.virtualModules) {
if (moduleName.isString()) {
if (virtualModules->contains(moduleName.toWTFString(globalObject))) {
return JSC::JSValue::encode(moduleName);
}
}
}
if (callFrame->argumentCount() > 1) {
if (callFrame->argumentCount() > 2) {
@@ -240,7 +226,6 @@ extern "C" EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlobalOb
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
auto* global = jsDynamicCast<Zig::GlobalObject*>(globalObject);
JSC::JSValue moduleName = callFrame->argument(0);
JSValue from = callFrame->argument(1);
@@ -254,15 +239,8 @@ extern "C" EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlobalOb
RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue {}));
if (auto* virtualModules = global->onLoadPlugins.virtualModules) {
if (moduleName.isString()) {
if (virtualModules->contains(moduleName.toWTFString(globalObject))) {
return JSC::JSValue::encode(moduleName);
}
}
}
if (!isESM) {
auto* global = jsDynamicCast<Zig::GlobalObject*>(globalObject);
if (LIKELY(global)) {
auto overrideHandler = global->m_nodeModuleOverriddenResolveFilename.get();
if (UNLIKELY(overrideHandler)) {
@@ -311,14 +289,6 @@ JSC_DEFINE_HOST_FUNCTION(functionImportMeta__resolve,
JSC__JSValue from;
if (auto* virtualModules = jsCast<Zig::GlobalObject*>(globalObject)->onLoadPlugins.virtualModules) {
if (moduleName.isString()) {
if (virtualModules->contains(moduleName.toWTFString(globalObject))) {
return JSC::JSValue::encode(moduleName);
}
}
}
if (callFrame->argumentCount() > 1 && callFrame->argument(1).isString()) {
from = JSC::JSValue::encode(callFrame->argument(1));
} else {

View File

@@ -865,49 +865,28 @@ static inline JSC::EncodedJSValue jsBufferPrototypeFunction_compareBody(JSC::JSG
size_t sourceEndInit = castedThis->byteLength();
size_t sourceEnd = sourceEndInit;
JSValue targetStartValue = jsUndefined();
JSValue targetEndValue = jsUndefined();
JSValue sourceStartValue = jsUndefined();
JSValue sourceEndValue = jsUndefined();
switch (callFrame->argumentCount()) {
default:
sourceEndValue = callFrame->uncheckedArgument(4);
sourceEnd = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(4));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
FALLTHROUGH;
case 4:
sourceStartValue = callFrame->uncheckedArgument(3);
sourceStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(3));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
FALLTHROUGH;
case 3:
targetEndValue = callFrame->uncheckedArgument(2);
targetEnd = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(2));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
FALLTHROUGH;
case 2:
targetStartValue = callFrame->uncheckedArgument(1);
targetStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(1));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
break;
case 1:
case 0:
break;
}
if (!targetStartValue.isUndefined()) {
targetStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(1));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
if (!targetEndValue.isUndefined()) {
targetEnd = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(2));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
if (!sourceStartValue.isUndefined()) {
sourceStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(3));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
if (!sourceEndValue.isUndefined()) {
sourceEnd = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(4));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
targetStart = std::min(targetStart, std::min(targetEnd, targetEndInit));
sourceStart = std::min(sourceStart, std::min(sourceEnd, sourceEndInit));
@@ -952,40 +931,24 @@ static inline JSC::EncodedJSValue jsBufferPrototypeFunction_copyBody(JSC::JSGlob
size_t sourceEndInit = castedThis->byteLength();
size_t sourceEnd = sourceEndInit;
JSValue targetStartValue = jsUndefined();
JSValue sourceStartValue = jsUndefined();
JSValue sourceEndValue = jsUndefined();
switch (callFrame->argumentCount()) {
default:
sourceEndValue = callFrame->uncheckedArgument(3);
sourceEnd = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(3));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
FALLTHROUGH;
case 3:
sourceStartValue = callFrame->uncheckedArgument(2);
sourceStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(2));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
FALLTHROUGH;
case 2:
targetStartValue = callFrame->uncheckedArgument(1);
targetStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(1));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
break;
case 1:
case 0:
break;
}
if (!targetStartValue.isUndefined()) {
targetStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(1));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
if (!sourceStartValue.isUndefined()) {
sourceStart = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(2));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
if (!sourceEndValue.isUndefined()) {
sourceEnd = parseIndex(lexicalGlobalObject, throwScope, callFrame->uncheckedArgument(3));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
targetStart = std::min(targetStart, targetEnd);
sourceEnd = std::min(sourceEnd, sourceEndInit);
sourceStart = std::min(sourceStart, sourceEnd);

View File

@@ -31,7 +31,6 @@ namespace Bun {
extern "C" void JSBundlerPlugin__addError(void*, void*, JSC::EncodedJSValue, JSC::EncodedJSValue);
extern "C" void JSBundlerPlugin__onLoadAsync(void*, void*, JSC::EncodedJSValue, JSC::EncodedJSValue);
extern "C" void JSBundlerPlugin__onResolveAsync(void*, void*, JSC::EncodedJSValue, JSC::EncodedJSValue, JSC::EncodedJSValue);
extern "C" void JSBundlerPlugin__onVirtualModulePlugin(void*, void*, JSC::EncodedJSValue, JSC::EncodedJSValue, JSC::EncodedJSValue);
JSC_DECLARE_HOST_FUNCTION(jsBundlerPluginFunction_addFilter);
JSC_DECLARE_HOST_FUNCTION(jsBundlerPluginFunction_addError);
@@ -155,7 +154,6 @@ public:
Bun::BundlerPlugin plugin;
JSC::LazyProperty<JSBundlerPlugin, JSC::JSFunction> onLoadFunction;
JSC::LazyProperty<JSBundlerPlugin, JSC::JSFunction> onResolveFunction;
JSC::LazyProperty<JSBundlerPlugin, JSC::JSFunction> moduleFunction;
JSC::LazyProperty<JSBundlerPlugin, JSC::JSFunction> setupFunction;
private:

View File

@@ -1,12 +0,0 @@
#include "root.h"
#include "JavaScriptCore/VM.h"
extern "C" void bun_on_tick_before(JSC::VM* vm)
{
// Let the GC do some work while we are idle
vm->heap.releaseAccess();
}
extern "C" void bun_on_tick_after(JSC::VM* vm)
{
vm->heap.acquireAccess();
}

View File

@@ -314,12 +314,12 @@ JSReadableState_NULLABLE_BOOLEAN_GETTER_SETTER(paused)
#undef JSReadableState_JSVALUE_GETTER_SETTER
#define JSReadableState_GETTER_SETTER_HASH_TABLE_VALUE(NAME) \
{ \
#NAME ""_s, static_cast<unsigned>(JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute), NoIntrinsic, \
{ \
HashTableValue::GetterSetterType, jsReadableState_##NAME, setJSReadableState_##NAME \
} \
#define JSReadableState_GETTER_SETTER_HASH_TABLE_VALUE(NAME) \
{ \
#NAME ""_s, static_cast < unsigned>(JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute), NoIntrinsic, \
{ \
HashTableValue::GetterSetterType, jsReadableState_##NAME, setJSReadableState_##NAME \
} \
}
/* Hash table for prototype */

View File

@@ -1,63 +0,0 @@
#include "JSSocketAddress.h"
#include "ZigGlobalObject.h"
#include "JavaScriptCore/JSObjectInlines.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/JSCast.h"
using namespace JSC;
namespace Bun {
namespace JSSocketAddress {
// Using a structure with inlined offsets should be more lightweight than a class.
Structure* createStructure(VM& vm, JSGlobalObject* globalObject)
{
JSC::Structure* structure = globalObject->structureCache().emptyObjectStructureForPrototype(
globalObject,
globalObject->objectPrototype(),
3);
JSC::PropertyOffset offset;
structure = structure->addPropertyTransition(
vm,
structure,
JSC::Identifier::fromString(vm, "address"_s),
0,
offset);
structure = structure->addPropertyTransition(
vm,
structure,
JSC::Identifier::fromString(vm, "family"_s),
0,
offset);
structure = structure->addPropertyTransition(
vm,
structure,
JSC::Identifier::fromString(vm, "port"_s),
0,
offset);
return structure;
}
} // namespace JSSocketAddress
} // namespace Bun
extern "C" JSObject* JSSocketAddress__create(JSGlobalObject* globalObject, JSString* value, int32_t port, bool isIPv6)
{
static const NeverDestroyed<String> IPv4 = MAKE_STATIC_STRING_IMPL("IPv4");
static const NeverDestroyed<String> IPv6 = MAKE_STATIC_STRING_IMPL("IPv6");
VM& vm = globalObject->vm();
auto* global = jsCast<Zig::GlobalObject*>(globalObject);
JSObject* thisObject = constructEmptyObject(vm, global->JSSocketAddressStructure());
thisObject->putDirectOffset(vm, 0, value);
thisObject->putDirectOffset(vm, 1, isIPv6 ? jsString(vm, IPv6) : jsString(vm, IPv4));
thisObject->putDirectOffset(vm, 2, jsNumber(port));
return thisObject;
}

View File

@@ -1,16 +0,0 @@
// The object returned by Bun.serve's .requestIP()
#pragma once
#include "root.h"
#include "JavaScriptCore/JSObjectInlines.h"
using namespace JSC;
namespace Bun {
namespace JSSocketAddress {
Structure* createStructure(VM& vm, JSGlobalObject* globalObject);
} // namespace JSSocketAddress
} // namespace Bun
extern "C" JSObject* JSSocketAddress__create(JSGlobalObject* globalObject, JSString* value, int port, bool isIPv6);

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +0,0 @@
#pragma once
#include "root.h"
#include "helpers.h"
namespace WebCore {
JSC::EncodedJSValue KeyObject__AsymmetricKeyType(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject_AsymmetricKeyDetails(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__SymmetricKeySize(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__Equals(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__Exports(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__createSecretKey(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__createPublicKey(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__createPrivateKey(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__generateKeySync(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC::EncodedJSValue KeyObject__generateKeyPairSync(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
}

View File

@@ -458,7 +458,7 @@ JSValue fetchCommonJSModule(
}
}
if (JSC::JSValue virtualModuleResult = Bun::runVirtualModule(globalObject, specifier)) {
if (JSC::JSValue virtualModuleResult = JSValue::decode(Bun__runVirtualModule(globalObject, specifier))) {
JSPromise* promise = jsCast<JSPromise*>(handleVirtualModuleResult<true>(globalObject, virtualModuleResult, res, specifier, referrer));
switch (promise->status(vm)) {
case JSPromise::Status::Rejected: {
@@ -633,7 +633,7 @@ static JSValue fetchESMSourceCode(
}
}
if (JSC::JSValue virtualModuleResult = Bun::runVirtualModule(globalObject, specifier)) {
if (JSC::JSValue virtualModuleResult = JSValue::decode(Bun__runVirtualModule(globalObject, specifier))) {
return handleVirtualModuleResult<allowPromise>(globalObject, virtualModuleResult, res, specifier, referrer);
}

View File

@@ -45,7 +45,7 @@ namespace Bun {
using namespace JSC;
#define REPORTED_NODE_VERSION "20.8.0"
#define REPORTED_NODE_VERSION "18.15.0"
#define processObjectBindingCodeGenerator processObjectInternalsBindingCodeGenerator
#define processObjectMainModuleCodeGenerator moduleMainCodeGenerator
@@ -749,8 +749,8 @@ JSC_DEFINE_CUSTOM_SETTER(setProcessExitCode, (JSC::JSGlobalObject * lexicalGloba
int exitCodeInt = exitCode.toInt32(lexicalGlobalObject);
RETURN_IF_EXCEPTION(throwScope, false);
if (exitCodeInt < 0 || exitCodeInt > 255) {
throwRangeError(lexicalGlobalObject, throwScope, "exitCode must be between 0 and 255"_s);
if (exitCodeInt < 0 || exitCodeInt > 127) {
throwRangeError(lexicalGlobalObject, throwScope, "exitCode must be between 0 and 127"_s);
return false;
}
@@ -810,12 +810,12 @@ static JSValue constructVersions(VM& vm, JSObject* processObject)
object->putDirect(vm, JSC::Identifier::fromString(vm, "usockets"_s),
JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_usockets))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "v8"_s), JSValue(JSC::jsString(vm, makeString("11.3.244.8-node.15"_s))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "uv"_s), JSValue(JSC::jsString(vm, makeString("1.46.0"_s))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "napi"_s), JSValue(JSC::jsString(vm, makeString("9"_s))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "v8"_s), JSValue(JSC::jsString(vm, makeString("10.8.168.20-node.8"_s))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "uv"_s), JSValue(JSC::jsString(vm, makeString("1.44.2"_s))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "napi"_s), JSValue(JSC::jsString(vm, makeString("8"_s))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "modules"_s),
JSC::JSValue(JSC::jsString(vm, makeAtomString("115"))));
JSC::JSValue(JSC::jsString(vm, makeAtomString("108"))));
return object;
}
@@ -1835,7 +1835,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionKill,
return JSValue::encode(jsUndefined());
}
return JSValue::encode(jsBoolean(true));
return JSValue::encode(jsUndefined());
}
extern "C" void Process__emitMessageEvent(Zig::GlobalObject* global, EncodedJSValue value)

View File

@@ -35,14 +35,7 @@ String URLDecomposition::origin() const
if (fullURL.protocolIsInHTTPFamily() or fullURL.protocolIsInFTPFamily() or fullURL.protocolIs("ws"_s) or fullURL.protocolIs("wss"_s))
return fullURL.protocolHostAndPort();
if (fullURL.protocolIsBlob()) {
const String& path = fullURL.path().toString();
const URL subUrl { URL {}, path };
if (subUrl.isValid()) {
if (subUrl.protocolIsInHTTPFamily() or subUrl.protocolIsInFTPFamily() or subUrl.protocolIs("ws"_s) or subUrl.protocolIs("wss"_s) or subUrl.protocolIsFile())
return subUrl.protocolHostAndPort();
}
}
return "null"_s;
}

View File

@@ -1777,7 +1777,7 @@ JSC::EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSBlobConstructor::construct(JSC::J
}
JSBlob* instance = JSBlob::create(vm, globalObject, structure, ptr);
vm.heap.reportExtraMemoryAllocated(instance, Blob__estimatedSize(instance->wrapped()));
vm.heap.reportExtraMemoryAllocated(Blob__estimatedSize(instance->wrapped()));
return JSValue::encode(instance);
}
@@ -1871,7 +1871,7 @@ extern "C" EncodedJSValue Blob__create(Zig::GlobalObject* globalObject, void* pt
auto& vm = globalObject->vm();
JSC::Structure* structure = globalObject->JSBlobStructure();
JSBlob* instance = JSBlob::create(vm, globalObject, structure, ptr);
vm.heap.reportExtraMemoryAllocated(instance, Blob__estimatedSize(ptr));
vm.heap.reportExtraMemoryAllocated(Blob__estimatedSize(ptr));
return JSValue::encode(instance);
}
@@ -4197,9 +4197,6 @@ JSC_DECLARE_HOST_FUNCTION(DebugHTTPSServerPrototype__publishCallback);
extern "C" EncodedJSValue DebugHTTPSServerPrototype__doReload(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(DebugHTTPSServerPrototype__reloadCallback);
extern "C" EncodedJSValue DebugHTTPSServerPrototype__doRequestIP(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(DebugHTTPSServerPrototype__requestIPCallback);
extern "C" EncodedJSValue DebugHTTPSServerPrototype__doStop(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(DebugHTTPSServerPrototype__stopCallback);
@@ -4219,7 +4216,6 @@ static const HashTableValue JSDebugHTTPSServerPrototypeTableValues[] = {
{ "protocol"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, DebugHTTPSServerPrototype__protocolGetterWrap, 0 } },
{ "publish"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPSServerPrototype__publishCallback, 3 } },
{ "reload"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPSServerPrototype__reloadCallback, 2 } },
{ "requestIP"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPSServerPrototype__requestIPCallback, 1 } },
{ "stop"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPSServerPrototype__stopCallback, 1 } },
{ "upgrade"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPSServerPrototype__upgradeCallback, 1 } }
};
@@ -4444,34 +4440,6 @@ JSC_DEFINE_HOST_FUNCTION(DebugHTTPSServerPrototype__reloadCallback, (JSGlobalObj
return DebugHTTPSServerPrototype__doReload(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(DebugHTTPSServerPrototype__requestIPCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
JSDebugHTTPSServer* thisObject = jsDynamicCast<JSDebugHTTPSServer*>(callFrame->thisValue());
if (UNLIKELY(!thisObject)) {
auto throwScope = DECLARE_THROW_SCOPE(vm);
throwVMTypeError(lexicalGlobalObject, throwScope, "Expected 'this' to be instanceof DebugHTTPSServer"_s);
return JSValue::encode({});
}
JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
#ifdef BUN_DEBUG
/** View the file name of the JS file that called this function
* from a debugger */
SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm);
const char* fileName = sourceOrigin.string().utf8().data();
static const char* lastFileName = nullptr;
if (lastFileName != fileName) {
lastFileName = fileName;
}
#endif
return DebugHTTPSServerPrototype__doRequestIP(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(DebugHTTPSServerPrototype__stopCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
@@ -4711,9 +4679,6 @@ JSC_DECLARE_HOST_FUNCTION(DebugHTTPServerPrototype__publishCallback);
extern "C" EncodedJSValue DebugHTTPServerPrototype__doReload(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(DebugHTTPServerPrototype__reloadCallback);
extern "C" EncodedJSValue DebugHTTPServerPrototype__doRequestIP(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(DebugHTTPServerPrototype__requestIPCallback);
extern "C" EncodedJSValue DebugHTTPServerPrototype__doStop(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(DebugHTTPServerPrototype__stopCallback);
@@ -4733,7 +4698,6 @@ static const HashTableValue JSDebugHTTPServerPrototypeTableValues[] = {
{ "protocol"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, DebugHTTPServerPrototype__protocolGetterWrap, 0 } },
{ "publish"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPServerPrototype__publishCallback, 3 } },
{ "reload"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPServerPrototype__reloadCallback, 2 } },
{ "requestIP"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPServerPrototype__requestIPCallback, 1 } },
{ "stop"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPServerPrototype__stopCallback, 1 } },
{ "upgrade"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, DebugHTTPServerPrototype__upgradeCallback, 1 } }
};
@@ -4958,34 +4922,6 @@ JSC_DEFINE_HOST_FUNCTION(DebugHTTPServerPrototype__reloadCallback, (JSGlobalObje
return DebugHTTPServerPrototype__doReload(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(DebugHTTPServerPrototype__requestIPCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
JSDebugHTTPServer* thisObject = jsDynamicCast<JSDebugHTTPServer*>(callFrame->thisValue());
if (UNLIKELY(!thisObject)) {
auto throwScope = DECLARE_THROW_SCOPE(vm);
throwVMTypeError(lexicalGlobalObject, throwScope, "Expected 'this' to be instanceof DebugHTTPServer"_s);
return JSValue::encode({});
}
JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
#ifdef BUN_DEBUG
/** View the file name of the JS file that called this function
* from a debugger */
SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm);
const char* fileName = sourceOrigin.string().utf8().data();
static const char* lastFileName = nullptr;
if (lastFileName != fileName) {
lastFileName = fileName;
}
#endif
return DebugHTTPServerPrototype__doRequestIP(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(DebugHTTPServerPrototype__stopCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
@@ -11684,9 +11620,6 @@ JSC_DECLARE_HOST_FUNCTION(HTTPSServerPrototype__publishCallback);
extern "C" EncodedJSValue HTTPSServerPrototype__doReload(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(HTTPSServerPrototype__reloadCallback);
extern "C" EncodedJSValue HTTPSServerPrototype__doRequestIP(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(HTTPSServerPrototype__requestIPCallback);
extern "C" EncodedJSValue HTTPSServerPrototype__doStop(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(HTTPSServerPrototype__stopCallback);
@@ -11706,7 +11639,6 @@ static const HashTableValue JSHTTPSServerPrototypeTableValues[] = {
{ "protocol"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, HTTPSServerPrototype__protocolGetterWrap, 0 } },
{ "publish"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPSServerPrototype__publishCallback, 3 } },
{ "reload"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPSServerPrototype__reloadCallback, 2 } },
{ "requestIP"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPSServerPrototype__requestIPCallback, 1 } },
{ "stop"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPSServerPrototype__stopCallback, 1 } },
{ "upgrade"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPSServerPrototype__upgradeCallback, 1 } }
};
@@ -11931,34 +11863,6 @@ JSC_DEFINE_HOST_FUNCTION(HTTPSServerPrototype__reloadCallback, (JSGlobalObject *
return HTTPSServerPrototype__doReload(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(HTTPSServerPrototype__requestIPCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
JSHTTPSServer* thisObject = jsDynamicCast<JSHTTPSServer*>(callFrame->thisValue());
if (UNLIKELY(!thisObject)) {
auto throwScope = DECLARE_THROW_SCOPE(vm);
throwVMTypeError(lexicalGlobalObject, throwScope, "Expected 'this' to be instanceof HTTPSServer"_s);
return JSValue::encode({});
}
JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
#ifdef BUN_DEBUG
/** View the file name of the JS file that called this function
* from a debugger */
SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm);
const char* fileName = sourceOrigin.string().utf8().data();
static const char* lastFileName = nullptr;
if (lastFileName != fileName) {
lastFileName = fileName;
}
#endif
return HTTPSServerPrototype__doRequestIP(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(HTTPSServerPrototype__stopCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
@@ -12198,9 +12102,6 @@ JSC_DECLARE_HOST_FUNCTION(HTTPServerPrototype__publishCallback);
extern "C" EncodedJSValue HTTPServerPrototype__doReload(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(HTTPServerPrototype__reloadCallback);
extern "C" EncodedJSValue HTTPServerPrototype__doRequestIP(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(HTTPServerPrototype__requestIPCallback);
extern "C" EncodedJSValue HTTPServerPrototype__doStop(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame);
JSC_DECLARE_HOST_FUNCTION(HTTPServerPrototype__stopCallback);
@@ -12220,7 +12121,6 @@ static const HashTableValue JSHTTPServerPrototypeTableValues[] = {
{ "protocol"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, HTTPServerPrototype__protocolGetterWrap, 0 } },
{ "publish"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPServerPrototype__publishCallback, 3 } },
{ "reload"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPServerPrototype__reloadCallback, 2 } },
{ "requestIP"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPServerPrototype__requestIPCallback, 1 } },
{ "stop"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPServerPrototype__stopCallback, 1 } },
{ "upgrade"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::NativeFunctionType, HTTPServerPrototype__upgradeCallback, 1 } }
};
@@ -12445,34 +12345,6 @@ JSC_DEFINE_HOST_FUNCTION(HTTPServerPrototype__reloadCallback, (JSGlobalObject *
return HTTPServerPrototype__doReload(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(HTTPServerPrototype__requestIPCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
JSHTTPServer* thisObject = jsDynamicCast<JSHTTPServer*>(callFrame->thisValue());
if (UNLIKELY(!thisObject)) {
auto throwScope = DECLARE_THROW_SCOPE(vm);
throwVMTypeError(lexicalGlobalObject, throwScope, "Expected 'this' to be instanceof HTTPServer"_s);
return JSValue::encode({});
}
JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
#ifdef BUN_DEBUG
/** View the file name of the JS file that called this function
* from a debugger */
SourceOrigin sourceOrigin = callFrame->callerSourceOrigin(vm);
const char* fileName = sourceOrigin.string().utf8().data();
static const char* lastFileName = nullptr;
if (lastFileName != fileName) {
lastFileName = fileName;
}
#endif
return HTTPServerPrototype__doRequestIP(thisObject->wrapped(), lexicalGlobalObject, callFrame);
}
JSC_DEFINE_HOST_FUNCTION(HTTPServerPrototype__stopCallback, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = lexicalGlobalObject->vm();
@@ -17810,7 +17682,7 @@ JSC::EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSRequestConstructor::construct(JSC
}
JSRequest* instance = JSRequest::create(vm, globalObject, structure, ptr);
vm.heap.reportExtraMemoryAllocated(instance, Request__estimatedSize(instance->wrapped()));
vm.heap.reportExtraMemoryAllocated(Request__estimatedSize(instance->wrapped()));
return JSValue::encode(instance);
}
@@ -17904,7 +17776,7 @@ extern "C" EncodedJSValue Request__create(Zig::GlobalObject* globalObject, void*
auto& vm = globalObject->vm();
JSC::Structure* structure = globalObject->JSRequestStructure();
JSRequest* instance = JSRequest::create(vm, globalObject, structure, ptr);
vm.heap.reportExtraMemoryAllocated(instance, Request__estimatedSize(ptr));
vm.heap.reportExtraMemoryAllocated(Request__estimatedSize(ptr));
return JSValue::encode(instance);
}
@@ -19137,7 +19009,7 @@ JSC::EncodedJSValue JSC_HOST_CALL_ATTRIBUTES JSResponseConstructor::construct(JS
}
JSResponse* instance = JSResponse::create(vm, globalObject, structure, ptr);
vm.heap.reportExtraMemoryAllocated(instance, Response__estimatedSize(instance->wrapped()));
vm.heap.reportExtraMemoryAllocated(Response__estimatedSize(instance->wrapped()));
return JSValue::encode(instance);
}
@@ -19231,7 +19103,7 @@ extern "C" EncodedJSValue Response__create(Zig::GlobalObject* globalObject, void
auto& vm = globalObject->vm();
JSC::Structure* structure = globalObject->JSResponseStructure();
JSResponse* instance = JSResponse::create(vm, globalObject, structure, ptr);
vm.heap.reportExtraMemoryAllocated(instance, Response__estimatedSize(ptr));
vm.heap.reportExtraMemoryAllocated(Response__estimatedSize(ptr));
return JSValue::encode(instance);
}
@@ -26705,16 +26577,12 @@ JSC_DECLARE_CUSTOM_GETTER(TextDecoderPrototype__encodingGetterWrap);
extern "C" JSC::EncodedJSValue TextDecoderPrototype__getFatal(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject);
JSC_DECLARE_CUSTOM_GETTER(TextDecoderPrototype__fatalGetterWrap);
extern "C" JSC::EncodedJSValue TextDecoderPrototype__getIgnoreBOM(void* ptr, JSC::JSGlobalObject* lexicalGlobalObject);
JSC_DECLARE_CUSTOM_GETTER(TextDecoderPrototype__ignoreBOMGetterWrap);
STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTextDecoderPrototype, JSTextDecoderPrototype::Base);
static const HashTableValue JSTextDecoderPrototypeTableValues[] = {
{ "decode"_s, static_cast<unsigned>(JSC::PropertyAttribute::Function | JSC::PropertyAttribute::DOMJITFunction | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::DOMJITFunctionType, TextDecoderPrototype__decodeCallback, &DOMJITSignatureForTextDecoderPrototype__decode } },
{ "encoding"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, TextDecoderPrototype__encodingGetterWrap, 0 } },
{ "fatal"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, TextDecoderPrototype__fatalGetterWrap, 0 } },
{ "ignoreBOM"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, TextDecoderPrototype__ignoreBOMGetterWrap, 0 } }
{ "fatal"_s, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | PropertyAttribute::DontDelete), NoIntrinsic, { HashTableValue::GetterSetterType, TextDecoderPrototype__fatalGetterWrap, 0 } }
};
const ClassInfo JSTextDecoderPrototype::s_info = { "TextDecoder"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTextDecoderPrototype) };
@@ -26802,18 +26670,6 @@ JSC_DEFINE_CUSTOM_GETTER(TextDecoderPrototype__fatalGetterWrap, (JSGlobalObject
RELEASE_AND_RETURN(throwScope, result);
}
JSC_DEFINE_CUSTOM_GETTER(TextDecoderPrototype__ignoreBOMGetterWrap, (JSGlobalObject * lexicalGlobalObject, EncodedJSValue thisValue, PropertyName attributeName))
{
auto& vm = lexicalGlobalObject->vm();
Zig::GlobalObject* globalObject = reinterpret_cast<Zig::GlobalObject*>(lexicalGlobalObject);
auto throwScope = DECLARE_THROW_SCOPE(vm);
JSTextDecoder* thisObject = jsCast<JSTextDecoder*>(JSValue::decode(thisValue));
JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
JSC::EncodedJSValue result = TextDecoderPrototype__getIgnoreBOM(thisObject->wrapped(), globalObject);
RETURN_IF_EXCEPTION(throwScope, {});
RELEASE_AND_RETURN(throwScope, result);
}
void JSTextDecoderPrototype::finishCreation(JSC::VM& vm, JSC::JSGlobalObject* globalObject)
{
Base::finishCreation(vm);

View File

@@ -191,6 +191,9 @@ namespace JSCastingHelpers = JSC::JSCastingHelpers;
#include "DOMJITHelpers.h"
#include <JavaScriptCore/DFGAbstractHeap.h>
#include "webcrypto/JSCryptoKey.h"
#include "webcrypto/JSSubtleCrypto.h"
#include "JSDOMFormData.h"
#include "JSDOMBinding.h"
#include "JSDOMConstructor.h"
@@ -203,7 +206,6 @@ namespace JSCastingHelpers = JSC::JSCastingHelpers;
#include "JSDOMConvertStrings.h"
#include "JSDOMConvertUnion.h"
#include "AddEventListenerOptions.h"
#include "JSSocketAddress.h"
#include "ErrorStackTrace.h"
#include "CallSite.h"
@@ -214,9 +216,6 @@ namespace JSCastingHelpers = JSC::JSCastingHelpers;
#include <wtf/text/Base64.h>
#include "simdutf.h"
#include "libusockets.h"
#include "KeyObject.h"
#include "webcrypto/JSCryptoKey.h"
#include "webcrypto/JSSubtleCrypto.h"
constexpr size_t DEFAULT_ERROR_STACK_TRACE_LIMIT = 10;
@@ -1759,41 +1758,6 @@ JSC_DEFINE_HOST_FUNCTION(functionLazyLoad,
if (string == "events"_s) {
return JSValue::encode(WebCore::JSEventEmitter::getConstructor(vm, globalObject));
}
if (string == "internal/crypto"_s) {
// auto sourceOrigin = callFrame->callerSourceOrigin(vm).url();
// bool isBuiltin = sourceOrigin.protocolIs("builtin"_s);
// if (!isBuiltin) {
// return JSC::JSValue::encode(JSC::jsUndefined());
// }
auto* obj = constructEmptyObject(globalObject);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "symmetricKeySize"_s)), JSC::JSFunction::create(vm, globalObject, 1, "symmetricKeySize"_s, KeyObject__SymmetricKeySize, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "asymmetricKeyType"_s)), JSC::JSFunction::create(vm, globalObject, 1, "asymmetricKeyType"_s, KeyObject__AsymmetricKeyType, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "asymmetricKeyDetails"_s)), JSC::JSFunction::create(vm, globalObject, 1, "asymmetricKeyDetails"_s, KeyObject_AsymmetricKeyDetails, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "equals"_s)), JSC::JSFunction::create(vm, globalObject, 2, "equals"_s, KeyObject__Equals, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "exports"_s)), JSC::JSFunction::create(vm, globalObject, 2, "exports"_s, KeyObject__Exports, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "createSecretKey"_s)), JSC::JSFunction::create(vm, globalObject, 1, "createSecretKey"_s, KeyObject__createSecretKey, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "createPublicKey"_s)), JSC::JSFunction::create(vm, globalObject, 1, "createPublicKey"_s, KeyObject__createPublicKey, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "createPrivateKey"_s)), JSC::JSFunction::create(vm, globalObject, 1, "createPrivateKey"_s, KeyObject__createPrivateKey, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "generateKeySync"_s)), JSC::JSFunction::create(vm, globalObject, 2, "generateKeySync"_s, KeyObject__generateKeySync, ImplementationVisibility::Public, NoIntrinsic), 0);
obj->putDirect(vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "generateKeyPairSync"_s)), JSC::JSFunction::create(vm, globalObject, 2, "generateKeyPairSync"_s, KeyObject__generateKeyPairSync, ImplementationVisibility::Public, NoIntrinsic), 0);
return JSValue::encode(obj);
}
if (string == "internal/tls"_s) {
auto* obj = constructEmptyObject(globalObject);
@@ -1984,11 +1948,6 @@ JSC_DECLARE_HOST_FUNCTION(getInternalWritableStream);
JSC_DECLARE_HOST_FUNCTION(whenSignalAborted);
JSC_DECLARE_HOST_FUNCTION(isAbortSignal);
JSC_DEFINE_HOST_FUNCTION(jsCreateCJSImportMeta, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
return JSValue::encode(Zig::ImportMetaObject::create(globalObject, callFrame->argument(0).toString(globalObject)));
}
JSC_DEFINE_HOST_FUNCTION(makeThisTypeErrorForBuiltins, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
ASSERT(callFrame);
@@ -2866,20 +2825,11 @@ void GlobalObject::finishCreation(VM& vm)
m_commonJSFunctionArgumentsStructure.initLater(
[](const Initializer<Structure>& init) {
auto* globalObject = reinterpret_cast<Zig::GlobalObject*>(init.owner);
auto prototype = JSC::constructEmptyObject(init.owner, globalObject->objectPrototype(), 1);
prototype->putDirect(
init.vm,
Identifier::fromString(init.vm, "createImportMeta"_s),
JSFunction::create(init.vm, init.owner, 2, ""_s, jsCreateCJSImportMeta, ImplementationVisibility::Public),
PropertyAttribute::DontDelete | PropertyAttribute::DontEnum | 0);
JSC::Structure* structure = globalObject->structureCache().emptyObjectStructureForPrototype(
globalObject,
prototype,
5);
globalObject->objectPrototype(),
3);
JSC::PropertyOffset offset;
auto& vm = globalObject->vm();
structure = structure->addPropertyTransition(
@@ -2889,20 +2839,6 @@ void GlobalObject::finishCreation(VM& vm)
0,
offset);
structure = structure->addPropertyTransition(
vm,
structure,
JSC::Identifier::fromString(vm, "require"_s),
0,
offset);
structure = structure->addPropertyTransition(
vm,
structure,
JSC::Identifier::fromString(vm, "resolve"_s),
0,
offset);
structure = structure->addPropertyTransition(
vm,
structure,
@@ -2920,11 +2856,6 @@ void GlobalObject::finishCreation(VM& vm)
init.set(structure);
});
m_JSSocketAddressStructure.initLater(
[](const Initializer<Structure>& init) {
init.set(JSSocketAddress::createStructure(init.vm, init.owner));
});
// Change prototype from null to object for synthetic modules.
m_moduleNamespaceObjectStructure.initLater(
[](const Initializer<Structure>& init) {
@@ -3239,14 +3170,6 @@ void GlobalObject::finishCreation(VM& vm)
init.setConstructor(constructor);
});
m_JSCryptoKey.initLater(
[](const JSC::LazyProperty<JSC::JSGlobalObject, JSC::Structure>::Initializer& init) {
Zig::GlobalObject* globalObject = reinterpret_cast<Zig::GlobalObject*>(init.owner);
auto* prototype = JSCryptoKey::createPrototype(init.vm, *globalObject);
auto* structure = JSCryptoKey::createStructure(init.vm, init.owner, JSValue(prototype));
init.set(structure);
});
m_JSHTTPSResponseSinkClassStructure.initLater(
[](LazyClassStructure::Initializer& init) {
auto* prototype = createJSSinkPrototype(init.vm, init.global, WebCore::SinkID::HTTPSResponseSink);
@@ -3717,7 +3640,6 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm)
putDirectBuiltinFunction(vm, this, builtinNames.createFIFOPrivateName(), streamInternalsCreateFIFOCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
putDirectBuiltinFunction(vm, this, builtinNames.createEmptyReadableStreamPrivateName(), readableStreamCreateEmptyReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
putDirectBuiltinFunction(vm, this, builtinNames.createUsedReadableStreamPrivateName(), readableStreamCreateUsedReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
putDirectBuiltinFunction(vm, this, builtinNames.consumeReadableStreamPrivateName(), readableStreamConsumeReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
putDirectBuiltinFunction(vm, this, builtinNames.createNativeReadableStreamPrivateName(), readableStreamCreateNativeReadableStreamCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
putDirectBuiltinFunction(vm, this, builtinNames.requireESMPrivateName(), importMetaObjectRequireESMCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
@@ -3725,8 +3647,6 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm)
putDirectBuiltinFunction(vm, this, builtinNames.internalRequirePrivateName(), importMetaObjectInternalRequireCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
putDirectBuiltinFunction(vm, this, builtinNames.requireNativeModulePrivateName(), moduleRequireNativeModuleCodeGenerator(vm), PropertyAttribute::Builtin | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
putDirectBuiltinFunction(vm, this, builtinNames.overridableRequirePrivateName(), moduleOverridableRequireCodeGenerator(vm), 0);
putDirectNativeFunction(vm, this, builtinNames.createUninitializedArrayBufferPrivateName(), 1, functionCreateUninitializedArrayBuffer, ImplementationVisibility::Public, NoIntrinsic, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function);
putDirectNativeFunction(vm, this, builtinNames.resolveSyncPrivateName(), 1, functionImportMeta__resolveSyncPrivate, ImplementationVisibility::Public, NoIntrinsic, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function);
putDirectNativeFunction(vm, this, builtinNames.createInternalModuleByIdPrivateName(), 1, InternalModuleRegistry::jsCreateInternalModuleById, ImplementationVisibility::Public, NoIntrinsic, PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::Function);
@@ -3891,8 +3811,6 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)
thisObject->m_callSiteStructure.visit(visitor);
thisObject->m_emitReadableNextTickFunction.visit(visitor);
thisObject->m_JSBufferSubclassStructure.visit(visitor);
thisObject->m_JSCryptoKey.visit(visitor);
thisObject->m_cryptoObject.visit(visitor);
thisObject->m_JSDOMFileConstructor.visit(visitor);
@@ -3910,7 +3828,6 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)
thisObject->m_commonJSModuleObjectStructure.visit(visitor);
thisObject->m_memoryFootprintStructure.visit(visitor);
thisObject->m_commonJSFunctionArgumentsStructure.visit(visitor);
thisObject->m_JSSocketAddressStructure.visit(visitor);
thisObject->m_cachedGlobalObjectStructure.visit(visitor);
thisObject->m_cachedGlobalProxyStructure.visit(visitor);
@@ -4082,45 +3999,16 @@ extern "C" void JSC__JSGlobalObject__queueMicrotaskCallback(Zig::GlobalObject* g
globalObject->queueMicrotask(function, JSValue(bitwise_cast<double>(reinterpret_cast<uintptr_t>(ptr))), JSValue(bitwise_cast<double>(reinterpret_cast<uintptr_t>(callback))), jsUndefined(), jsUndefined());
}
JSC::Identifier GlobalObject::moduleLoaderResolve(JSGlobalObject* jsGlobalObject,
JSC::Identifier GlobalObject::moduleLoaderResolve(JSGlobalObject* globalObject,
JSModuleLoader* loader, JSValue key,
JSValue referrer, JSValue origin)
{
Zig::GlobalObject* globalObject = reinterpret_cast<Zig::GlobalObject*>(jsGlobalObject);
ErrorableString res;
res.success = false;
if (key.isString()) {
if (auto* virtualModules = globalObject->onLoadPlugins.virtualModules) {
auto keyString = key.toWTFString(globalObject);
if (virtualModules->contains(keyString)) {
return JSC::Identifier::fromString(globalObject->vm(), keyString);
}
}
}
BunString keyZ;
if (key.isString()) {
auto moduleName = jsCast<JSString*>(key)->value(globalObject);
if (moduleName.startsWith("file://"_s)) {
auto url = WTF::URL(moduleName);
if (url.isValid() && !url.isEmpty()) {
keyZ = Bun::toStringRef(url.fileSystemPath());
} else {
keyZ = Bun::toStringRef(moduleName);
}
} else {
keyZ = Bun::toStringRef(moduleName);
}
} else {
keyZ = Bun::toStringRef(globalObject, key);
}
BunString referrerZ = referrer && !referrer.isUndefinedOrNull() && referrer.isString() ? Bun::toStringRef(globalObject, referrer) : BunStringEmpty;
BunString keyZ = Bun::toString(globalObject, key);
BunString referrerZ = referrer && !referrer.isUndefinedOrNull() && referrer.isString() ? Bun::toString(globalObject, referrer) : BunStringEmpty;
ZigString queryString = { 0, 0 };
Zig__GlobalObject__resolve(&res, globalObject, &keyZ, &referrerZ, &queryString);
keyZ.deref();
referrerZ.deref();
if (res.success) {
if (queryString.len > 0) {
@@ -4135,60 +4023,25 @@ JSC::Identifier GlobalObject::moduleLoaderResolve(JSGlobalObject* jsGlobalObject
}
}
JSC::JSInternalPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* jsGlobalObject,
JSC::JSInternalPromise* GlobalObject::moduleLoaderImportModule(JSGlobalObject* globalObject,
JSModuleLoader*,
JSString* moduleNameValue,
JSValue parameters,
const SourceOrigin& sourceOrigin)
{
auto* globalObject = reinterpret_cast<Zig::GlobalObject*>(jsGlobalObject);
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
auto* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
RETURN_IF_EXCEPTION(scope, promise->rejectWithCaughtException(globalObject, scope));
if (auto* virtualModules = globalObject->onLoadPlugins.virtualModules) {
auto keyString = moduleNameValue->value(globalObject);
if (virtualModules->contains(keyString)) {
auto resolvedIdentifier = JSC::Identifier::fromString(vm, keyString);
auto result = JSC::importModule(globalObject, resolvedIdentifier,
JSC::jsUndefined(), parameters, JSC::jsUndefined());
RETURN_IF_EXCEPTION(scope, promise->rejectWithCaughtException(globalObject, scope));
return result;
}
}
auto sourceURL = sourceOrigin.url();
ErrorableString resolved;
BunString moduleNameZ;
auto moduleName = moduleNameValue->value(globalObject);
#if BUN_DEBUG
auto startRefCount = moduleName.impl()->refCount();
#endif
if (moduleName.startsWith("file://"_s)) {
auto url = WTF::URL(moduleName);
if (url.isValid() && !url.isEmpty()) {
moduleNameZ = Bun::toStringRef(url.fileSystemPath());
} else {
moduleNameZ = Bun::toStringRef(moduleName);
}
} else {
moduleNameZ = Bun::toStringRef(moduleName);
}
auto sourceOriginZ = sourceURL.isEmpty() ? BunStringCwd : Bun::toStringRef(sourceURL.fileSystemPath());
auto moduleNameZ = Bun::toString(globalObject, moduleNameValue);
auto sourceOriginZ = sourceURL.isEmpty() ? BunStringCwd : Bun::toString(sourceURL.fileSystemPath());
ZigString queryString = { 0, 0 };
resolved.success = false;
Zig__GlobalObject__resolve(&resolved, globalObject, &moduleNameZ, &sourceOriginZ, &queryString);
moduleNameZ.deref();
sourceOriginZ.deref();
#if BUN_DEBUG
// TODO: ASSERT doesnt work right now
RELEASE_ASSERT(startRefCount == moduleName.impl()->refCount());
#endif
if (!resolved.success) {
throwException(scope, resolved.result.err, globalObject);
return promise->rejectWithCaughtException(globalObject, scope);

Some files were not shown because too many files have changed in this diff Show More