Compare commits

..

1 Commits

Author SHA1 Message Date
Zack Radisic
c78df80a1f WIP code cache 2025-03-24 13:14:08 -07:00
419 changed files with 19075 additions and 41202 deletions

View File

@@ -1,14 +1,13 @@
---
description: JavaScript class implemented in C++
globs: *.cpp
alwaysApply: false
---
# Implementing JavaScript classes in C++
If there is a publicly accessible Constructor and Prototype, then there are 3 classes:
- IF there are C++ class members we need a destructor, so `class Foo : public JSC::DestructibleObject`, if no C++ class fields (only JS properties) then we don't need a class at all usually. We can instead use JSC::constructEmptyObject(vm, structure) and `putDirectOffset` like in [NodeFSStatBinding.cpp](mdc:src/bun.js/bindings/NodeFSStatBinding.cpp).
- IF there are C++ class members we need a destructor, so `class Foo : public JSC::DestructibleObject`, if no C++ class fields (only JS properties) then we don't need a class at all usually. We can instead use JSC::constructEmptyObject(vm, structure) and `putDirectOffset` like in [NodeFSBinding.cpp](mdc:src/bun.js/bindings/NodeFSBinding.cpp).
- class FooPrototype : public JSC::JSNonFinalObject
- class FooConstructor : public JSC::InternalFunction
@@ -19,7 +18,6 @@ If there are C++ fields on the Foo class, the Foo class will need an iso subspac
Usually you'll need to #include "root.h" at the top of C++ files or you'll get lint errors.
Generally, defining the subspace looks like this:
```c++
class Foo : public JSC::DestructibleObject {
@@ -47,7 +45,6 @@ It's better to put it in the .cpp file instead of the .h file, when possible.
## Defining properties
Define properties on the prototype. Use a const HashTableValues like this:
```C++
static JSC_DECLARE_HOST_FUNCTION(jsX509CertificateProtoFuncCheckEmail);
static JSC_DECLARE_HOST_FUNCTION(jsX509CertificateProtoFuncCheckHost);
@@ -161,7 +158,6 @@ void JSX509CertificatePrototype::finishCreation(VM& vm)
```
### Getter definition:
```C++
JSC_DEFINE_CUSTOM_GETTER(jsX509CertificateGetter_ca, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName))
@@ -216,6 +212,7 @@ JSC_DEFINE_HOST_FUNCTION(jsX509CertificateProtoFuncToJSON, (JSGlobalObject * glo
}
```
### Constructor definition
```C++
@@ -262,6 +259,7 @@ private:
};
```
### Structure caching
If there's a class, prototype, and constructor:
@@ -281,7 +279,6 @@ void GlobalObject::finishCreation(VM& vm) {
```
Then, implement the function that creates the structure:
```c++
void setupX509CertificateClassStructure(LazyClassStructure::Initializer& init)
{
@@ -304,12 +301,11 @@ If there's only a class, use `JSC::LazyProperty<JSGlobalObject, Structure>` inst
1. Add the `JSC::LazyProperty<JSGlobalObject, Structure>` to @ZigGlobalObject.h
2. Initialize the class structure in @ZigGlobalObject.cpp in `void GlobalObject::finishCreation(VM& vm)`
3. Visit the lazy property in visitChildren in @ZigGlobalObject.cpp in `void GlobalObject::visitChildrenImpl`
void GlobalObject::finishCreation(VM& vm) {
// ...
void GlobalObject::finishCreation(VM& vm) {
// ...
this.m_myLazyProperty.initLater([](const JSC::LazyProperty<JSC::JSGlobalObject, JSC::Structure>::Initializer& init) {
init.set(Bun::initMyStructure(init.vm, reinterpret_cast<Zig::GlobalObject\*>(init.owner)));
});
init.set(Bun::initMyStructure(init.vm, reinterpret_cast<Zig::GlobalObject*>(init.owner)));
});
```
Then, implement the function that creates the structure:
@@ -320,7 +316,7 @@ Structure* setupX509CertificateStructure(JSC::VM &vm, Zig::GlobalObject* globalO
auto* prototypeStructure = JSX509CertificatePrototype::createStructure(init.vm, init.global, init.global->objectPrototype());
auto* prototype = JSX509CertificatePrototype::create(init.vm, init.global, prototypeStructure);
// If there is no prototype or it only has
// If there is no prototype or it only has
auto* structure = JSX509Certificate::createStructure(init.vm, init.global, prototype);
init.setPrototype(prototype);
@@ -329,6 +325,7 @@ Structure* setupX509CertificateStructure(JSC::VM &vm, Zig::GlobalObject* globalO
}
```
Then, use the structure by calling `globalObject.m_myStructureName.get(globalObject)`
```C++
@@ -381,14 +378,12 @@ extern "C" JSC::EncodedJSValue Bun__JSBigIntStatsObjectConstructor(Zig::GlobalOb
```
Zig:
```zig
extern "c" fn Bun__JSBigIntStatsObjectConstructor(*JSC.JSGlobalObject) JSC.JSValue;
pub const getBigIntStatsConstructor = Bun__JSBigIntStatsObjectConstructor;
```
To create an object (instance) of a JS class defined in C++ from Zig, follow the \_\_toJS convention like this:
To create an object (instance) of a JS class defined in C++ from Zig, follow the __toJS convention like this:
```c++
// X509* is whatever we need to create the object
extern "C" EncodedJSValue Bun__X509__toJS(Zig::GlobalObject* globalObject, X509* cert)
@@ -400,13 +395,12 @@ extern "C" EncodedJSValue Bun__X509__toJS(Zig::GlobalObject* globalObject, X509*
```
And from Zig:
```zig
const X509 = opaque {
// ... class
// ... class
extern fn Bun__X509__toJS(*JSC.JSGlobalObject, *X509) JSC.JSValue;
pub fn toJS(this: *X509, globalObject: *JSC.JSGlobalObject) JSC.JSValue {
return Bun__X509__toJS(globalObject, this);
}

View File

@@ -1,488 +0,0 @@
---
description: How Zig works with JavaScriptCore bindings generator
globs:
alwaysApply: false
---
# Bun's JavaScriptCore Class Bindings Generator
This document explains how Bun's class bindings generator works to bridge Zig and JavaScript code through JavaScriptCore (JSC).
## Architecture Overview
Bun's binding system creates a seamless bridge between JavaScript and Zig, allowing Zig implementations to be exposed as JavaScript classes. The system has several key components:
1. **Zig Implementation** (.zig files)
2. **JavaScript Interface Definition** (.classes.ts files)
3. **Generated Code** (C++/Zig files that connect everything)
## Class Definition Files
### JavaScript Interface (.classes.ts)
The `.classes.ts` files define the JavaScript API using a declarative approach:
```typescript
// Example: encoding.classes.ts
define({
name: "TextDecoder",
constructor: true,
JSType: "object",
finalize: true,
proto: {
decode: {
// Function definition
args: 1,
},
encoding: {
// Getter with caching
getter: true,
cache: true,
},
fatal: {
// Read-only property
getter: true,
},
ignoreBOM: {
// Read-only property
getter: true,
}
}
});
```
Each class definition specifies:
- The class name
- Whether it has a constructor
- JavaScript type (object, function, etc.)
- Properties and methods in the `proto` field
- Caching strategy for properties
- Finalization requirements
### Zig Implementation (.zig)
The Zig files implement the native functionality:
```zig
// Example: TextDecoder.zig
pub const TextDecoder = struct {
// Internal state
encoding: []const u8,
fatal: bool,
ignoreBOM: bool,
// Use generated bindings
pub usingnamespace JSC.Codegen.JSTextDecoder;
pub usingnamespace bun.New(@This());
// Constructor implementation - note use of globalObject
pub fn constructor(
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame,
) bun.JSError!*TextDecoder {
// Implementation
}
// Prototype methods - note return type includes JSError
pub fn decode(
this: *TextDecoder,
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame,
) bun.JSError!JSC.JSValue {
// Implementation
}
// Getters
pub fn getEncoding(this: *TextDecoder, globalObject: *JSGlobalObject) JSC.JSValue {
return JSC.JSValue.createStringFromUTF8(globalObject, this.encoding);
}
pub fn getFatal(this: *TextDecoder, globalObject: *JSGlobalObject) JSC.JSValue {
return JSC.JSValue.jsBoolean(this.fatal);
}
// Cleanup - note standard pattern of using deinit/deref
pub fn deinit(this: *TextDecoder) void {
// Release any retained resources
}
pub fn finalize(this: *TextDecoder) void {
this.deinit();
// Or sometimes this is used to free memory instead
bun.default_allocator.destroy(this);
}
};
```
Key components in the Zig file:
- The struct containing native state
- `usingnamespace JSC.Codegen.JS<ClassName>` to include generated code
- `usingnamespace bun.New(@This())` for object creation helpers
- Constructor and methods using `bun.JSError!JSValue` return type for proper error handling
- Consistent use of `globalObject` parameter name instead of `ctx`
- Methods matching the JavaScript interface
- Getters/setters for properties
- Proper resource cleanup pattern with `deinit()` and `finalize()`
## Code Generation System
The binding generator produces C++ code that connects JavaScript and Zig:
1. **JSC Class Structure**: Creates C++ classes for the JS object, prototype, and constructor
2. **Memory Management**: Handles GC integration through JSC's WriteBarrier
3. **Method Binding**: Connects JS function calls to Zig implementations
4. **Type Conversion**: Converts between JS values and Zig types
5. **Property Caching**: Implements the caching system for properties
The generated C++ code includes:
- A JSC wrapper class (`JSTextDecoder`)
- A prototype class (`JSTextDecoderPrototype`)
- A constructor function (`JSTextDecoderConstructor`)
- Function bindings (`TextDecoderPrototype__decodeCallback`)
- Property getters/setters (`TextDecoderPrototype__encodingGetterWrap`)
## CallFrame Access
The `CallFrame` object provides access to JavaScript execution context:
```zig
pub fn decode(
this: *TextDecoder,
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame
) bun.JSError!JSC.JSValue {
// Get arguments
const input = callFrame.argument(0);
const options = callFrame.argument(1);
// Get this value
const thisValue = callFrame.thisValue();
// Implementation with error handling
if (input.isUndefinedOrNull()) {
return globalObject.throw("Input cannot be null or undefined", .{});
}
// Return value or throw error
return JSC.JSValue.jsString(globalObject, "result");
}
```
CallFrame methods include:
- `argument(i)`: Get the i-th argument
- `argumentCount()`: Get the number of arguments
- `thisValue()`: Get the `this` value
- `callee()`: Get the function being called
## Property Caching and GC-Owned Values
The `cache: true` option in property definitions enables JSC's WriteBarrier to efficiently store values:
```typescript
encoding: {
getter: true,
cache: true, // Enable caching
}
```
### C++ Implementation
In the generated C++ code, caching uses JSC's WriteBarrier:
```cpp
JSC_DEFINE_CUSTOM_GETTER(TextDecoderPrototype__encodingGetterWrap, (...)) {
auto& vm = JSC::getVM(lexicalGlobalObject);
Zig::GlobalObject *globalObject = reinterpret_cast<Zig::GlobalObject*>(lexicalGlobalObject);
auto throwScope = DECLARE_THROW_SCOPE(vm);
JSTextDecoder* thisObject = jsCast<JSTextDecoder*>(JSValue::decode(encodedThisValue));
JSC::EnsureStillAliveScope thisArg = JSC::EnsureStillAliveScope(thisObject);
// Check for cached value and return if present
if (JSValue cachedValue = thisObject->m_encoding.get())
return JSValue::encode(cachedValue);
// Get value from Zig implementation
JSC::JSValue result = JSC::JSValue::decode(
TextDecoderPrototype__getEncoding(thisObject->wrapped(), globalObject)
);
RETURN_IF_EXCEPTION(throwScope, {});
// Store in cache for future access
thisObject->m_encoding.set(vm, thisObject, result);
RELEASE_AND_RETURN(throwScope, JSValue::encode(result));
}
```
### Zig Accessor Functions
For each cached property, the generator creates Zig accessor functions that allow Zig code to work with these GC-owned values:
```zig
// External function declarations
extern fn TextDecoderPrototype__encodingSetCachedValue(JSC.JSValue, *JSC.JSGlobalObject, JSC.JSValue) callconv(JSC.conv) void;
extern fn TextDecoderPrototype__encodingGetCachedValue(JSC.JSValue) callconv(JSC.conv) JSC.JSValue;
/// `TextDecoder.encoding` setter
/// This value will be visited by the garbage collector.
pub fn encodingSetCached(thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void {
JSC.markBinding(@src());
TextDecoderPrototype__encodingSetCachedValue(thisValue, globalObject, value);
}
/// `TextDecoder.encoding` getter
/// This value will be visited by the garbage collector.
pub fn encodingGetCached(thisValue: JSC.JSValue) ?JSC.JSValue {
JSC.markBinding(@src());
const result = TextDecoderPrototype__encodingGetCachedValue(thisValue);
if (result == .zero)
return null;
return result;
}
```
### Benefits of GC-Owned Values
This system provides several key benefits:
1. **Automatic Memory Management**: The JavaScriptCore GC tracks and manages these values
2. **Proper Garbage Collection**: The WriteBarrier ensures values are properly visited during GC
3. **Consistent Access**: Zig code can easily get/set these cached JS values
4. **Performance**: Cached values avoid repeated computation or serialization
### Use Cases
GC-owned cached values are particularly useful for:
1. **Computed Properties**: Store expensive computation results
2. **Lazily Created Objects**: Create objects only when needed, then cache them
3. **References to Other Objects**: Store references to other JS objects that need GC tracking
4. **Memoization**: Cache results based on input parameters
The WriteBarrier mechanism ensures that any JS values stored in this way are properly tracked by the garbage collector.
## Memory Management and Finalization
The binding system handles memory management across the JavaScript/Zig boundary:
1. **Object Creation**: JavaScript `new TextDecoder()` creates both a JS wrapper and a Zig struct
2. **Reference Tracking**: JSC's GC tracks all JS references to the object
3. **Finalization**: When the JS object is collected, the finalizer releases Zig resources
Bun uses a consistent pattern for resource cleanup:
```zig
// Resource cleanup method - separate from finalization
pub fn deinit(this: *TextDecoder) void {
// Release resources like strings
this._encoding.deref(); // String deref pattern
// Free any buffers
if (this.buffer) |buffer| {
bun.default_allocator.free(buffer);
}
}
// Called by the GC when object is collected
pub fn finalize(this: *TextDecoder) void {
JSC.markBinding(@src()); // For debugging
this.deinit(); // Clean up resources
bun.default_allocator.destroy(this); // Free the object itself
}
```
Some objects that hold references to other JS objects use `.deref()` instead:
```zig
pub fn finalize(this: *SocketAddress) void {
JSC.markBinding(@src());
this._presentation.deref(); // Release references
this.destroy();
}
```
## Error Handling with JSError
Bun uses `bun.JSError!JSValue` return type for proper error handling:
```zig
pub fn decode(
this: *TextDecoder,
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame
) bun.JSError!JSC.JSValue {
// Throwing an error
if (callFrame.argumentCount() < 1) {
return globalObject.throw("Missing required argument", .{});
}
// Or returning a success value
return JSC.JSValue.jsString(globalObject, "Success!");
}
```
This pattern allows Zig functions to:
1. Return JavaScript values on success
2. Throw JavaScript exceptions on error
3. Propagate errors automatically through the call stack
## Type Safety and Error Handling
The binding system includes robust error handling:
```cpp
// Example of type checking in generated code
JSTextDecoder* thisObject = jsDynamicCast<JSTextDecoder*>(callFrame->thisValue());
if (UNLIKELY(!thisObject)) {
scope.throwException(lexicalGlobalObject,
Bun::createInvalidThisError(lexicalGlobalObject, callFrame->thisValue(), "TextDecoder"_s));
return {};
}
```
## Prototypal Inheritance
The binding system creates proper JavaScript prototype chains:
1. **Constructor**: JSTextDecoderConstructor with standard .prototype property
2. **Prototype**: JSTextDecoderPrototype with methods and properties
3. **Instances**: Each JSTextDecoder instance with __proto__ pointing to prototype
This ensures JavaScript inheritance works as expected:
```cpp
// From generated code
void JSTextDecoderConstructor::finishCreation(VM& vm, JSC::JSGlobalObject* globalObject, JSTextDecoderPrototype* prototype)
{
Base::finishCreation(vm, 0, "TextDecoder"_s, PropertyAdditionMode::WithoutStructureTransition);
// Set up the prototype chain
putDirectWithoutTransition(vm, vm.propertyNames->prototype, prototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
ASSERT(inherits(info()));
}
```
## Performance Considerations
The binding system is optimized for performance:
1. **Direct Pointer Access**: JavaScript objects maintain a direct pointer to Zig objects
2. **Property Caching**: WriteBarrier caching avoids repeated native calls for stable properties
3. **Memory Management**: JSC garbage collection integrated with Zig memory management
4. **Type Conversion**: Fast paths for common JavaScript/Zig type conversions
## Creating a New Class Binding
To create a new class binding in Bun:
1. **Define the class interface** in a `.classes.ts` file:
```typescript
define({
name: "MyClass",
constructor: true,
finalize: true,
proto: {
myMethod: {
args: 1,
},
myProperty: {
getter: true,
cache: true,
}
}
});
```
2. **Implement the native functionality** in a `.zig` file:
```zig
pub const MyClass = struct {
// State
value: []const u8,
// Generated bindings
pub usingnamespace JSC.Codegen.JSMyClass;
pub usingnamespace bun.New(@This());
// Constructor
pub fn constructor(
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame,
) bun.JSError!*MyClass {
const arg = callFrame.argument(0);
// Implementation
}
// Method
pub fn myMethod(
this: *MyClass,
globalObject: *JSGlobalObject,
callFrame: *JSC.CallFrame,
) bun.JSError!JSC.JSValue {
// Implementation
}
// Getter
pub fn getMyProperty(this: *MyClass, globalObject: *JSGlobalObject) JSC.JSValue {
return JSC.JSValue.jsString(globalObject, this.value);
}
// Resource cleanup
pub fn deinit(this: *MyClass) void {
// Clean up resources
}
pub fn finalize(this: *MyClass) void {
this.deinit();
bun.default_allocator.destroy(this);
}
};
```
3. **The binding generator** creates all necessary C++ and Zig glue code to connect JavaScript and Zig, including:
- C++ class definitions
- Method and property bindings
- Memory management utilities
- GC integration code
## Generated Code Structure
The binding generator produces several components:
### 1. C++ Classes
For each Zig class, the system generates:
- **JS<Class>**: Main wrapper that holds a pointer to the Zig object (`JSTextDecoder`)
- **JS<Class>Prototype**: Contains methods and properties (`JSTextDecoderPrototype`)
- **JS<Class>Constructor**: Implementation of the JavaScript constructor (`JSTextDecoderConstructor`)
### 2. C++ Methods and Properties
- **Method Callbacks**: `TextDecoderPrototype__decodeCallback`
- **Property Getters/Setters**: `TextDecoderPrototype__encodingGetterWrap`
- **Initialization Functions**: `finishCreation` methods for setting up the class
### 3. Zig Bindings
- **External Function Declarations**:
```zig
extern fn TextDecoderPrototype__decode(*TextDecoder, *JSC.JSGlobalObject, *JSC.CallFrame) callconv(JSC.conv) JSC.EncodedJSValue;
```
- **Cached Value Accessors**:
```zig
pub fn encodingGetCached(thisValue: JSC.JSValue) ?JSC.JSValue { ... }
pub fn encodingSetCached(thisValue: JSC.JSValue, globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { ... }
```
- **Constructor Helpers**:
```zig
pub fn create(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { ... }
```
### 4. GC Integration
- **Memory Cost Calculation**: `estimatedSize` method
- **Child Visitor Methods**: `visitChildrenImpl` and `visitAdditionalChildren`
- **Heap Analysis**: `analyzeHeap` for debugging memory issues
This architecture makes it possible to implement high-performance native functionality in Zig while exposing a clean, idiomatic JavaScript API to users.

View File

@@ -28,7 +28,7 @@ This adds a new flag --bail to bun test. When set, it will stop running tests af
- [ ] I checked the lifetime of memory allocated to verify it's (1) freed and (2) only freed when it should be
- [ ] I included a test for the new code, or an existing test covers it
- [ ] JSValue used outside of the stack is either wrapped in a JSC.Strong or is JSValueProtect'ed
- [ ] JSValue used outside outside of the stack is either wrapped in a JSC.Strong or is JSValueProtect'ed
- [ ] I wrote TypeScript/JavaScript tests and they pass locally (`bun-debug test test-file-name.test`)
-->

15
.vscode/launch.json generated vendored
View File

@@ -146,21 +146,6 @@
"action": "openExternally",
},
},
{
"type": "lldb",
"request": "launch",
"name": "ZACK",
"program": "${workspaceFolder}/build/debug/bun-debug",
"args": ["./index.ts"],
"cwd": "/Users/zackradisic/Code/dd-trace-bun",
"env": {
"FORCE_COLOR": "0",
"BUN_DEBUG_QUIET_LOGS": "1",
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
},
"console": "internalConsole",
// Don't pause when the GC runs while the debugger is open.
},
// bun run [file]
{
"type": "lldb",

View File

@@ -35,6 +35,8 @@
// "zig.zls.enableBuildOnSave": true,
// "zig.buildOnSave": true,
"zig.buildFilePath": "${workspaceFolder}/build.zig",
"zig.path": "${workspaceFolder}/vendor/zig/zig.exe",
"zig.zls.path": "${workspaceFolder}/vendor/zig/zls.exe",
"zig.formattingProvider": "zls",
"zig.zls.enableInlayHints": false,
"[zig]": {

View File

@@ -53,39 +53,39 @@ $ brew install bun
## Install LLVM
Bun requires LLVM 19 (`clang` is part of LLVM). This version requirement is to match WebKit (precompiled), as mismatching versions will cause memory allocation failures at runtime. In most cases, you can install LLVM through your system package manager:
Bun requires LLVM 18 (`clang` is part of LLVM). This version requirement is to match WebKit (precompiled), as mismatching versions will cause memory allocation failures at runtime. In most cases, you can install LLVM through your system package manager:
{% codetabs group="os" %}
```bash#macOS (Homebrew)
$ brew install llvm@19
$ brew install llvm@18
```
```bash#Ubuntu/Debian
$ # LLVM has an automatic installation script that is compatible with all versions of Ubuntu
$ wget https://apt.llvm.org/llvm.sh -O - | sudo bash -s -- 19 all
$ wget https://apt.llvm.org/llvm.sh -O - | sudo bash -s -- 18 all
```
```bash#Arch
$ sudo pacman -S llvm clang lld
$ sudo pacman -S llvm clang18 lld
```
```bash#Fedora
$ sudo dnf install llvm clang lld-devel
$ sudo dnf install llvm18 clang18 lld18-devel
```
```bash#openSUSE Tumbleweed
$ sudo zypper install clang19 lld19 llvm19
$ sudo zypper install clang18 lld18 llvm18
```
{% /codetabs %}
If none of the above solutions apply, you will have to install it [manually](https://github.com/llvm/llvm-project/releases/tag/llvmorg-19.1.7).
Make sure Clang/LLVM 19 is in your path:
Make sure Clang/LLVM 18 is in your path:
```bash
$ which clang-19
$ which clang-18
```
If not, run this to manually add it:
@@ -94,13 +94,13 @@ If not, run this to manually add it:
```bash#macOS (Homebrew)
# use fish_add_path if you're using fish
# use path+="$(brew --prefix llvm@19)/bin" if you are using zsh
$ export PATH="$(brew --prefix llvm@19)/bin:$PATH"
# use path+="$(brew --prefix llvm@18)/bin" if you are using zsh
$ export PATH="$(brew --prefix llvm@18)/bin:$PATH"
```
```bash#Arch
# use fish_add_path if you're using fish
$ export PATH="$PATH:/usr/lib/llvm19/bin"
$ export PATH="$PATH:/usr/lib/llvm18/bin"
```
{% /codetabs %}
@@ -134,16 +134,6 @@ We recommend adding `./build/debug` to your `$PATH` so that you can run `bun-deb
$ bun-debug
```
## Running debug builds
The `bd` package.json script compiles and runs a debug build of Bun, only printing the output of the build process if it fails.
```sh
$ bun bd <args>
$ bun bd test foo.test.ts
$ bun bd ./foo.ts
```
## Code generation scripts
Several code generation scripts are used during Bun's build process. These are run automatically when changes are made to certain files.
@@ -260,7 +250,7 @@ The issue may manifest when initially running `bun setup` as Clang being unable
```
The C++ compiler
"/usr/bin/clang++-19"
"/usr/bin/clang++-18"
is not able to compile a simple test program.
```

2
LATEST
View File

@@ -1 +1 @@
1.2.8
1.2.5

View File

@@ -1,44 +0,0 @@
import { bench, run } from "../runner.mjs";
import crypto from "node:crypto";
import { Buffer } from "node:buffer";
const keylen = { "aes-128-gcm": 16, "aes-192-gcm": 24, "aes-256-gcm": 32 };
const sizes = [4 * 1024, 1024 * 1024];
const ciphers = ["aes-128-gcm", "aes-192-gcm", "aes-256-gcm"];
const messages = {};
sizes.forEach(size => {
messages[size] = Buffer.alloc(size, "b");
});
const keys = {};
ciphers.forEach(cipher => {
keys[cipher] = crypto.randomBytes(keylen[cipher]);
});
// Fixed IV and AAD
const iv = crypto.randomBytes(12);
const associate_data = Buffer.alloc(16, "z");
for (const cipher of ciphers) {
for (const size of sizes) {
const message = messages[size];
const key = keys[cipher];
bench(`${cipher} ${size / 1024}KB`, () => {
const alice = crypto.createCipheriv(cipher, key, iv);
alice.setAAD(associate_data);
const enc = alice.update(message);
alice.final();
const tag = alice.getAuthTag();
const bob = crypto.createDecipheriv(cipher, key, iv);
bob.setAuthTag(tag);
bob.setAAD(associate_data);
bob.update(enc);
bob.final();
});
}
}
await run();

View File

@@ -1,7 +1,7 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext"],
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",

View File

@@ -1,7 +1,7 @@
{
"compilerOptions": {
// Enable latest features
"lib": ["ESNext"],
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",

View File

@@ -27,10 +27,9 @@
},
"packages/bun-types": {
"name": "bun-types",
"version": "1.2.5",
"dependencies": {
"@types/node": "*",
"@types/ws": "*",
"@types/ws": "~8.5.10",
},
"devDependencies": {
"@biomejs/biome": "^1.5.3",

View File

@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
oven-sh/boringssl
COMMIT
7a5d984c69b0c34c4cbb56c6812eaa5b9bef485c
914b005ef3ece44159dca0ffad74eb42a9f6679f
)
register_cmake_command(

View File

@@ -785,10 +785,6 @@ target_include_directories(${bun} PRIVATE
${NODEJS_HEADERS_PATH}/include
)
if(NOT WIN32)
target_include_directories(${bun} PRIVATE ${CWD}/src/bun.js/bindings/libuv)
endif()
if(LINUX)
include(CheckIncludeFiles)
check_include_files("sys/queue.h" HAVE_SYS_QUEUE_H)

View File

@@ -2,7 +2,7 @@ option(WEBKIT_VERSION "The version of WebKit to use")
option(WEBKIT_LOCAL "If a local version of WebKit should be used instead of downloading")
if(NOT WEBKIT_VERSION)
set(WEBKIT_VERSION ef31d98a1370e01b7483cabcbe3593d055bea982)
set(WEBKIT_VERSION 91bf2baced1b1309c7e05f19177c97fefec20976)
endif()
string(SUBSTRING ${WEBKIT_VERSION} 0 16 WEBKIT_VERSION_PREFIX)

View File

@@ -1,449 +0,0 @@
Bun provides native APIs for working with HTTP cookies through `Bun.Cookie` and `Bun.CookieMap`. These APIs offer fast, easy-to-use methods for parsing, generating, and manipulating cookies in HTTP requests and responses.
## CookieMap class
`Bun.CookieMap` provides a Map-like interface for working with collections of cookies. It implements the `Iterable` interface, allowing you to use it with `for...of` loops and other iteration methods.
```ts
// Empty cookie map
const cookies = new Bun.CookieMap();
// From a cookie string
const cookies1 = new Bun.CookieMap("name=value; foo=bar");
// From an object
const cookies2 = new Bun.CookieMap({
session: "abc123",
theme: "dark",
});
// From an array of name/value pairs
const cookies3 = new Bun.CookieMap([
["session", "abc123"],
["theme", "dark"],
]);
```
### In HTTP servers
In Bun's HTTP server, the `cookies` property on the request object (in `routes`) is an instance of `CookieMap`:
```ts
const server = Bun.serve({
routes: {
"/": req => {
// Access request cookies
const cookies = req.cookies;
// Get a specific cookie
const sessionCookie = cookies.get("session");
if (sessionCookie != null) {
console.log(sessionCookie);
}
// Check if a cookie exists
if (cookies.has("theme")) {
// ...
}
// Set a cookie, it will be automatically applied to the response
cookies.set("visited", "true");
return new Response("Hello");
},
},
});
console.log("Server listening at: " + server.url);
```
### Methods
#### `get(name: string): string | null`
Retrieves a cookie by name. Returns `null` if the cookie doesn't exist.
```ts
// Get by name
const cookie = cookies.get("session");
if (cookie != null) {
console.log(cookie);
}
```
#### `has(name: string): boolean`
Checks if a cookie with the given name exists.
```ts
// Check if cookie exists
if (cookies.has("session")) {
// Cookie exists
}
```
#### `set(name: string, value: string): void`
#### `set(options: CookieInit): void`
#### `set(cookie: Cookie): void`
Adds or updates a cookie in the map. Cookies default to `{ path: "/", sameSite: "lax" }`.
```ts
// Set by name and value
cookies.set("session", "abc123");
// Set using options object
cookies.set({
name: "theme",
value: "dark",
maxAge: 3600,
secure: true,
});
// Set using Cookie instance
const cookie = new Bun.Cookie("visited", "true");
cookies.set(cookie);
```
#### `delete(name: string): void`
#### `delete(options: CookieStoreDeleteOptions): void`
Removes a cookie from the map. When applied to a Response, this adds a cookie with an empty string value and an expiry date in the past. A cookie will only delete successfully on the browser if the domain and path is the same as it was when the cookie was created.
```ts
// Delete by name using default domain and path.
cookies.delete("session");
// Delete with domain/path options.
cookies.delete({
name: "session",
domain: "example.com",
path: "/admin",
});
```
#### `toJSON(): Record<string, string>`
Converts the cookie map to a serializable format.
```ts
const json = cookies.toJSON();
```
#### `toSetCookieHeaders(): string[]`
Returns an array of values for Set-Cookie headers that can be used to apply all cookie changes.
When using `Bun.serve()`, you don't need to call this method explicitly. Any changes made to the `req.cookies` map are automatically applied to the response headers. This method is primarily useful when working with other HTTP server implementations.
```js
import { createServer } from "node:http";
import { CookieMap } from "bun";
const server = createServer((req, res) => {
const cookieHeader = req.headers.cookie || "";
const cookies = new CookieMap(cookieHeader);
cookies.set("view-count", Number(cookies.get("view-count") || "0") + 1);
cookies.delete("session");
res.writeHead(200, {
"Content-Type": "text/plain",
"Set-Cookie": cookies.toSetCookieHeaders(),
});
res.end(`Found ${cookies.size} cookies`);
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
```
### Iteration
`CookieMap` provides several methods for iteration:
```ts
// Iterate over [name, cookie] entries
for (const [name, value] of cookies) {
console.log(`${name}: ${value}`);
}
// Using entries()
for (const [name, value] of cookies.entries()) {
console.log(`${name}: ${value}`);
}
// Using keys()
for (const name of cookies.keys()) {
console.log(name);
}
// Using values()
for (const value of cookies.values()) {
console.log(value);
}
// Using forEach
cookies.forEach((value, name) => {
console.log(`${name}: ${value}`);
});
```
### Properties
#### `size: number`
Returns the number of cookies in the map.
```ts
console.log(cookies.size); // Number of cookies
```
## Cookie class
`Bun.Cookie` represents an HTTP cookie with its name, value, and attributes.
```ts
import { Cookie } from "bun";
// Create a basic cookie
const cookie = new Bun.Cookie("name", "value");
// Create a cookie with options
const secureSessionCookie = new Bun.Cookie("session", "abc123", {
domain: "example.com",
path: "/admin",
expires: new Date(Date.now() + 86400000), // 1 day
httpOnly: true,
secure: true,
sameSite: "strict",
});
// Parse from a cookie string
const parsedCookie = new Bun.Cookie("name=value; Path=/; HttpOnly");
// Create from an options object
const objCookie = new Bun.Cookie({
name: "theme",
value: "dark",
maxAge: 3600,
secure: true,
});
```
### Constructors
```ts
// Basic constructor with name/value
new Bun.Cookie(name: string, value: string);
// Constructor with name, value, and options
new Bun.Cookie(name: string, value: string, options: CookieInit);
// Constructor from cookie string
new Bun.Cookie(cookieString: string);
// Constructor from cookie object
new Bun.Cookie(options: CookieInit);
```
### Properties
```ts
cookie.name; // string - Cookie name
cookie.value; // string - Cookie value
cookie.domain; // string | null - Domain scope (null if not specified)
cookie.path; // string - URL path scope (defaults to "/")
cookie.expires; // number | undefined - Expiration timestamp (ms since epoch)
cookie.secure; // boolean - Require HTTPS
cookie.sameSite; // "strict" | "lax" | "none" - SameSite setting
cookie.partitioned; // boolean - Whether the cookie is partitioned (CHIPS)
cookie.maxAge; // number | undefined - Max age in seconds
cookie.httpOnly; // boolean - Accessible only via HTTP (not JavaScript)
```
### Methods
#### `isExpired(): boolean`
Checks if the cookie has expired.
```ts
// Expired cookie (Date in the past)
const expiredCookie = new Bun.Cookie("name", "value", {
expires: new Date(Date.now() - 1000),
});
console.log(expiredCookie.isExpired()); // true
// Valid cookie (Using maxAge instead of expires)
const validCookie = new Bun.Cookie("name", "value", {
maxAge: 3600, // 1 hour in seconds
});
console.log(validCookie.isExpired()); // false
// Session cookie (no expiration)
const sessionCookie = new Bun.Cookie("name", "value");
console.log(sessionCookie.isExpired()); // false
```
#### `serialize(): string`
#### `toString(): string`
Returns a string representation of the cookie suitable for a `Set-Cookie` header.
```ts
const cookie = new Bun.Cookie("session", "abc123", {
domain: "example.com",
path: "/admin",
expires: new Date(Date.now() + 86400000),
secure: true,
httpOnly: true,
sameSite: "strict",
});
console.log(cookie.serialize());
// => "session=abc123; Domain=example.com; Path=/admin; Expires=Sun, 19 Mar 2025 15:03:26 GMT; Secure; HttpOnly; SameSite=strict"
console.log(cookie.toString());
// => "session=abc123; Domain=example.com; Path=/admin; Expires=Sun, 19 Mar 2025 15:03:26 GMT; Secure; HttpOnly; SameSite=strict"
```
#### `toJSON(): CookieInit`
Converts the cookie to a plain object suitable for JSON serialization.
```ts
const cookie = new Bun.Cookie("session", "abc123", {
secure: true,
httpOnly: true,
});
const json = cookie.toJSON();
// => {
// name: "session",
// value: "abc123",
// path: "/",
// secure: true,
// httpOnly: true,
// sameSite: "lax",
// partitioned: false
// }
// Works with JSON.stringify
const jsonString = JSON.stringify(cookie);
```
### Static methods
#### `Cookie.parse(cookieString: string): Cookie`
Parses a cookie string into a `Cookie` instance.
```ts
const cookie = Bun.Cookie.parse("name=value; Path=/; Secure; SameSite=Lax");
console.log(cookie.name); // "name"
console.log(cookie.value); // "value"
console.log(cookie.path); // "/"
console.log(cookie.secure); // true
console.log(cookie.sameSite); // "lax"
```
#### `Cookie.from(name: string, value: string, options?: CookieInit): Cookie`
Factory method to create a cookie.
```ts
const cookie = Bun.Cookie.from("session", "abc123", {
httpOnly: true,
secure: true,
maxAge: 3600,
});
```
## Types
```ts
interface CookieInit {
name?: string;
value?: string;
domain?: string;
/** Defaults to '/'. To allow the browser to set the path, use an empty string. */
path?: string;
expires?: number | Date | string;
secure?: boolean;
/** Defaults to `lax`. */
sameSite?: CookieSameSite;
httpOnly?: boolean;
partitioned?: boolean;
maxAge?: number;
}
interface CookieStoreDeleteOptions {
name: string;
domain?: string | null;
path?: string;
}
interface CookieStoreGetOptions {
name?: string;
url?: string;
}
type CookieSameSite = "strict" | "lax" | "none";
class Cookie {
constructor(name: string, value: string, options?: CookieInit);
constructor(cookieString: string);
constructor(cookieObject?: CookieInit);
readonly name: string;
value: string;
domain?: string;
path: string;
expires?: Date;
secure: boolean;
sameSite: CookieSameSite;
partitioned: boolean;
maxAge?: number;
httpOnly: boolean;
isExpired(): boolean;
serialize(): string;
toString(): string;
toJSON(): CookieInit;
static parse(cookieString: string): Cookie;
static from(name: string, value: string, options?: CookieInit): Cookie;
}
class CookieMap implements Iterable<[string, string]> {
constructor(init?: string[][] | Record<string, string> | string);
get(name: string): string | null;
toSetCookieHeaders(): string[];
has(name: string): boolean;
set(name: string, value: string, options?: CookieInit): void;
set(options: CookieInit): void;
delete(name: string): void;
delete(options: CookieStoreDeleteOptions): void;
delete(name: string, options: Omit<CookieStoreDeleteOptions, "name">): void;
toJSON(): Record<string, string>;
readonly size: number;
entries(): IterableIterator<[string, string]>;
keys(): IterableIterator<string>;
values(): IterableIterator<string>;
forEach(callback: (value: string, key: string, map: CookieMap) => void): void;
[Symbol.iterator](): IterableIterator<[string, string]>;
}
```

View File

@@ -61,7 +61,6 @@ Routes in `Bun.serve()` receive a `BunRequest` (which extends [`Request`](https:
// Simplified for brevity
interface BunRequest<T extends string> extends Request {
params: Record<T, string>;
readonly cookies: CookieMap;
}
```
@@ -935,83 +934,6 @@ const server = Bun.serve({
Returns `null` for closed requests or Unix domain sockets.
## Working with Cookies
Bun provides a built-in API for working with cookies in HTTP requests and responses. The `BunRequest` object includes a `cookies` property that provides a `CookieMap` for easily accessing and manipulating cookies. When using `routes`, `Bun.serve()` automatically tracks `request.cookies.set` and applies them to the response.
### Reading cookies
Read cookies from incoming requests using the `cookies` property on the `BunRequest` object:
```ts
Bun.serve({
routes: {
"/profile": req => {
// Access cookies from the request
const userId = req.cookies.get("user_id");
const theme = req.cookies.get("theme") || "light";
return Response.json({
userId,
theme,
message: "Profile page",
});
},
},
});
```
### Setting cookies
To set cookies, use the `set` method on the `CookieMap` from the `BunRequest` object.
```ts
Bun.serve({
routes: {
"/login": req => {
const cookies = req.cookies;
// Set a cookie with various options
cookies.set("user_id", "12345", {
maxAge: 60 * 60 * 24 * 7, // 1 week
httpOnly: true,
secure: true,
path: "/",
});
// Add a theme preference cookie
cookies.set("theme", "dark");
// Modified cookies from the request are automatically applied to the response
return new Response("Login successful");
},
},
});
```
`Bun.serve()` automatically tracks modified cookies from the request and applies them to the response.
### Deleting cookies
To delete a cookie, use the `delete` method on the `request.cookies` (`CookieMap`) object:
```ts
Bun.serve({
routes: {
"/logout": req => {
// Delete the user_id cookie
req.cookies.delete("user_id", {
path: "/",
});
return new Response("Logged out successfully");
},
},
});
```
Deleted cookies become a `Set-Cookie` header on the response with the `maxAge` set to `0` and an empty `value`.
## Server Metrics
### server.pendingRequests and server.pendingWebSockets

View File

@@ -240,7 +240,7 @@ const result = await sql.unsafe(
### Execute and Cancelling Queries
Bun's SQL is lazy, which means it will only start executing when awaited or executed with `.execute()`.
Bun's SQL is lazy that means its will only start executing when awaited or executed with `.execute()`.
You can cancel a query that is currently executing by calling the `cancel()` method on the query object.
```ts

View File

@@ -15,8 +15,8 @@ Below is the full set of recommended `compilerOptions` for a Bun project. With t
```jsonc
{
"compilerOptions": {
// Environment setup & latest features
"lib": ["ESNext"],
// Enable latest features
"lib": ["ESNext", "DOM"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
@@ -33,12 +33,11 @@ Below is the full set of recommended `compilerOptions` for a Bun project. With t
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false,
// Some stricter flags
"noUnusedLocals": true,
"noUnusedParameters": true,
"noPropertyAccessFromIndexSignature": true,
},
}
```

View File

@@ -355,24 +355,24 @@ export default {
page("api/spawn", "Child processes", {
description: `Spawn sync and async child processes with easily configurable input and output streams.`,
}), // "`Bun.spawn`"),
page("api/html-rewriter", "HTMLRewriter", {
description: `Parse and transform HTML with Bun's native HTMLRewriter API, inspired by Cloudflare Workers.`,
}), // "`HTMLRewriter`"),
page("api/transpiler", "Transpiler", {
description: `Bun exposes its internal transpiler as a pluggable API.`,
}), // "`Bun.Transpiler`"),
page("api/hashing", "Hashing", {
description: `Native support for a range of fast hashing algorithms.`,
}), // "`Bun.serve`"),
page("api/console", "Console", {
description: `Bun implements a Node.js-compatible \`console\` object with colorized output and deep pretty-printing.`,
}), // "`Node-API`"),
page("api/cookie", "Cookie", {
description: "Bun's native Cookie API simplifies working with HTTP cookies.",
}), // "`Node-API`"),
page("api/ffi", "FFI", {
description: `Call native code from JavaScript with Bun's foreign function interface (FFI) API.`,
}), // "`bun:ffi`"),
page("api/cc", "C Compiler", {
description: `Build & run native C from JavaScript with Bun's native C compiler API`,
}), // "`bun:ffi`"),
page("api/html-rewriter", "HTMLRewriter", {
description: `Parse and transform HTML with Bun's native HTMLRewriter API, inspired by Cloudflare Workers.`,
}), // "`HTMLRewriter`"),
page("api/test", "Testing", {
description: `Bun's built-in test runner is fast and uses Jest-compatible syntax.`,
}), // "`bun:test`"),
@@ -398,9 +398,6 @@ export default {
page("api/color", "Color", {
description: `Bun's color function leverages Bun's CSS parser for parsing, normalizing, and converting colors from user input to a variety of output formats.`,
}), // "`Color`"),
page("api/transpiler", "Transpiler", {
description: `Bun exposes its internal transpiler as a pluggable API.`,
}), // "`Bun.Transpiler`"),
// divider("Dev Server"),
// page("bun-dev", "Vanilla"),

View File

@@ -104,7 +104,7 @@ This page is updated regularly to reflect compatibility status of the latest ver
### [`node:crypto`](https://nodejs.org/api/crypto.html)
🟡 Missing `secureHeapUsed` `setEngine` `setFips`
🟡 Missing `ECDH` `checkPrime` `checkPrimeSync` `generatePrime` `generatePrimeSync` `hkdf` `hkdfSync` `secureHeapUsed` `setEngine` `setFips`
Some methods are not optimized yet.
@@ -118,7 +118,7 @@ Some methods are not optimized yet.
### [`node:module`](https://nodejs.org/api/module.html)
🟡 Missing `syncBuiltinESMExports`, `Module#load()`. Overriding `require.cache` is supported for ESM & CJS modules. `module._extensions`, `module._pathCache`, `module._cache` are no-ops. `module.register` is not implemented and we recommend using a [`Bun.plugin`](https://bun.sh/docs/runtime/plugins) in the meantime.
🟡 Missing `runMain` `syncBuiltinESMExports`, `Module#load()`. Overriding `require.cache` is supported for ESM & CJS modules. `module._extensions`, `module._pathCache`, `module._cache` are no-ops. `module.register` is not implemented and we recommend using a [`Bun.plugin`](https://bun.sh/docs/runtime/plugins) in the meantime.
### [`node:net`](https://nodejs.org/api/net.html)
@@ -378,7 +378,8 @@ The table below lists all globals implemented by Node.js and Bun's current compa
### [`require()`](https://nodejs.org/api/globals.html#require)
🟢 Fully implemented, including [`require.main`](https://nodejs.org/api/modules.html#requiremain), [`require.cache`](https://nodejs.org/api/modules.html#requirecache), [`require.resolve`](https://nodejs.org/api/modules.html#requireresolverequest-options).
🟢 Fully implemented, including [`require.main`](https://nodejs.org/api/modules.html#requiremain), [`require.cache`](https://nodejs.org/api/modules.html#requirecache), [`require.resolve`](https://nodejs.org/api/modules.html#requireresolverequest-options). `require.extensions` is a stub.
### [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
🟢 Fully implemented.

View File

@@ -17,7 +17,7 @@ Bun supports things like top-level await, JSX, and extensioned `.ts` imports, wh
```jsonc
{
"compilerOptions": {
// Environment setup & latest features
// Enable latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
@@ -35,13 +35,12 @@ Bun supports things like top-level await, JSX, and extensioned `.ts` imports, wh
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false,
},
// Some stricter flags
"noUnusedLocals": true,
"noUnusedParameters": true,
"noPropertyAccessFromIndexSignature": true
}
}
```

View File

@@ -1,21 +0,0 @@
import { $ } from "bun";
import util from "node:util";
let foo = "hi";
console.log(util.inspect(foo));
// await $`ls fljsdklfjslkdfj`.quiet();
// Options:
// 1. make it so that VirtualMachine.printErrorInstance (javascript.zig) knows how to check if an error instance is a ShellError (right now it skips custom inspect)
// 2. make the shell error not actually an Error but just an obejct
// try {
// await $`ls fljsdklfjslkdfj`.throws(true).quiet();
// } catch (e) {
// // e[Bun.inspect.custom] = () => "LOL";
// console.log(e);
// console.log(Object.getOwnPropertyNames(e.stdout));
// }
await $`ls fljsdklfjslkdfj`.throws(true).quiet();

85
instructions.md Normal file
View File

@@ -0,0 +1,85 @@
ZACK IMPORTANT INFORMATION for implementing `cachedDataRejected`:
- cachedDataRejected is set in two scenarios: A) invalid binary data or B) source code mismatch
- this means that we need to parse the code in the constrcutre of `vm.Script` (this will also solve the sourceMappingURL test not passing)
- this means that we probably need to copy the code from `JSC::evaluate(...)` (inside `Intepreter.cpp`)
- the way that function works is that it does `ProgramExecutable* program = ProgramExecutable::create(globalObject, source)`
- then it does some shit to compile it to bytecode and runs it
- the parsing of the source code and checking the CodeCache happens in `ProgramExecutable::initializeGlobalProperties(...)`
- this calls `CodeCache::getUnlinkedProgramCodeBlock`
- which is a wrapper around `CodeCache::getUnlinkedGlobalCodeBlock`
- which finally calls `CodeCache::findAndUpdateArgs` which will call `fetchFromDiskImpl` downstream
- `fetchFromDisk` is called when IT IS NOT FOUND IN THE CACHE, it will try to get it from the SourceProvider
- we should probably always set `cachedDataRejected` to true
- if it calls upon `fetchFromDisk` and it is successful we can set `cachedDataRejected` to false
- not sure if it will then later add it to the cache map
# Background
I am working on the node:vm module in the Bun JavaScript runtime which uses JavaScriptCore (JSC) as its JavaScript engine.
I am implementing the `cachedData` option for `new vm.Script()`.
I want to add support to the `cachedDataRejected` property to the `vm.Script` class.
This property is set to false if the cached data is rejected by JSC because it does not match the input source code.
# Your to-do list
- [ ] Add an overriddable method to `JSC::SourceProvider` called `isBytecodeCacheValid` and `setBytecodeCacheValid`
- [ ] Update `fetchFromDiskImpl` in `vendor/WebKit/Source/JavaScriptCore/runtime/CodeCache.cpp`
- [ ] We need to add code which checks that
## Add an overriddable method to `JSC::SourceProvider` called `isBytecodeCacheValid` and `setBytecodeCacheValid`
The `setBytecodeCacheValid` method will be called by JSC if the bytecode cache associated with the source provider is valid.
The `isBytecodeCacheValid` method will be called by JSC to check if the bytecode cache associated with the source provider is valid.
You will add this in `vendor/WebKit/Source/JavaScriptCore/parser/SourceProvider.h`.
Make sure to wrap these changes in the `#if USE(BUN_JSC_ADDITIONS)` macro wrapper.
## Update `fetchFromDiskImpl` in `vendor/WebKit/Source/JavaScriptCore/runtime/CodeCache.cpp`
This is the definition of this function:
```cpp
UnlinkedCodeBlockType* fetchFromDiskImpl(VM& vm, const SourceCodeKey& key)
{
RefPtr<CachedBytecode> cachedBytecode = key.source().provider().cachedBytecode();
if (!cachedBytecode || !cachedBytecode->size())
return nullptr;
return decodeCodeBlock<UnlinkedCodeBlockType>(vm, key, *cachedBytecode);
}
```
Basically the `return decodeCodeBlock<UnlinkedCodeBlockType>(vm, key, *cachedBytecode);` line will return a `nullptr` if it could not decode the bytecod
NOTE: this is just ONE way that the cached data can be rejected; when it is invalid
## Add a check in `constructScript` in `NodeVM.cpp` to check the bytecode cache source matches the input source code
ANOTHER way that the cached data can be rejected is if the source code of the bytecode cache does not match the input source code.
## Appendix: Node.js documentation for `new vm.Script()`
Documentation from Node.js:
```
# new vm.Script(code[, options])
- `code` <string> The JavaScript code to compile.
- `options` <Object> | <string>
- `filename` <string> Specifies the filename used in stack traces produced by this script. Default: 'evalmachine.<anonymous>'.
- `lineOffset` <number> Specifies the line number offset that is displayed in stack traces produced by this script. Default: 0.
- `columnOffset` <number> Specifies the first-line column number offset that is displayed in stack traces produced by this script. Default: 0.
- `cachedData` <Buffer> | <TypedArray> | <DataView> Provides an optional Buffer or TypedArray, or DataView with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either true or false depending on acceptance of the data by V8.
- `produceCachedData` <boolean> When true and no cachedData is present, V8 will attempt to produce code cache data for code. Upon success, a Buffer with V8's code cache data will be produced and stored in the `cachedData` property of the returned vm.Script instance. The `cachedDataProduced` value will be set to either true or false depending on whether code cache data is produced successfully. This option is deprecated in favor of `script.createCachedData()`. Default: false.
- `importModuleDynamically` <Function> | <vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER> Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see Support of dynamic import() in compilation APIs.
If `options` is a string, then it specifies the filename.
Creating a new `vm.Script` object compiles code but does not run it. The compiled `vm.Script` can be run later multiple times. The code is not bound to any global object; rather, it is bound before each run, just for that run.
```

View File

@@ -29,9 +29,6 @@
"test/js/**/*bad.js",
"test/bundler/transpiler/decorators.test.ts", // uses `arguments` as decorator
"test/bundler/native-plugin.test.ts", // parser doesn't handle import metadata
"test/bundler/transpiler/with-statement-works.js", // parser doesn't allow `with` statement
"test/js/node/module/extensions-fixture", // these files are not meant to be linted
"test/cli/run/module-type-fixture",
"test/bundler/transpiler/with-statement-works.js" // parser doesn't allow `with` statement
],
"overrides": [

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "bun",
"version": "1.2.9",
"version": "1.2.6",
"workspaces": [
"./packages/bun-types"
],
@@ -31,7 +31,6 @@
},
"scripts": {
"build": "bun run build:debug",
"bd": "(bun run --silent build:debug &> /tmp/bun.debug.build.log || (cat /tmp/bun.debug.build.log && rm -rf /tmp/bun.debug.build.log && exit 1)) && rm -f /tmp/bun.debug.build.log && ./build/debug/bun-debug",
"build:debug": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Debug -B build/debug",
"build:valgrind": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Debug -DENABLE_BASELINE=ON -ENABLE_VALGRIND=ON -B build/debug-valgrind",
"build:release": "bun ./scripts/build.mjs -GNinja -DCMAKE_BUILD_TYPE=Release -B build/release",
@@ -45,7 +44,6 @@
"build:release:with_logs": "cmake . -DCMAKE_BUILD_TYPE=Release -DENABLE_LOGS=true -GNinja -Bbuild-release && ninja -Cbuild-release",
"build:debug-zig-release": "cmake . -DCMAKE_BUILD_TYPE=Release -DZIG_OPTIMIZE=Debug -GNinja -Bbuild-debug-zig-release && ninja -Cbuild-debug-zig-release",
"css-properties": "bun run src/css/properties/generate_properties.ts",
"uv-posix-stubs": "bun run src/bun.js/bindings/libuv/generate_uv_posix_stubs.ts",
"bump": "bun ./scripts/bump.ts",
"typecheck": "tsc --noEmit && cd test && bun run typecheck",
"fmt": "bun run prettier",

View File

@@ -4,12 +4,12 @@
"": {
"name": "bun-plugin-svelte",
"devDependencies": {
"@threlte/core": "8.0.1",
"bun-types": "canary",
"svelte": "^5.20.4",
},
"peerDependencies": {
"svelte": "^5",
"typescript": "^5",
},
},
},
@@ -26,8 +26,6 @@
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="],
"@threlte/core": ["@threlte/core@8.0.1", "", { "dependencies": { "mitt": "^3.0.1" }, "peerDependencies": { "svelte": ">=5", "three": ">=0.155" } }, "sha512-vy1xRQppJFNmfPTeiRQue+KmYFsbPgVhwuYXRTvVrwPeD2oYz43gxUeOpe1FACeGKxrxZykeKJF5ebVvl7gBxw=="],
"@types/estree": ["@types/estree@1.0.6", "", {}, "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw=="],
"@types/node": ["@types/node@22.13.5", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-+lTU0PxZXn0Dr1NBtC7Y8cR21AJr87dLLU953CWA6pMxxv/UDc7jYAY90upcrie1nRcD6XNG5HOYEDtgW5TxAg=="],
@@ -56,11 +54,9 @@
"magic-string": ["magic-string@0.30.17", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" } }, "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA=="],
"mitt": ["mitt@3.0.1", "", {}, "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="],
"svelte": ["svelte@5.20.4", "", { "dependencies": { "@ampproject/remapping": "^2.3.0", "@jridgewell/sourcemap-codec": "^1.5.0", "@types/estree": "^1.0.5", "acorn": "^8.12.1", "acorn-typescript": "^1.4.13", "aria-query": "^5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "esm-env": "^1.2.1", "esrap": "^1.4.3", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-2Mo/AfObaw9zuD0u1JJ7sOVzRCGcpETEyDkLbtkcctWpCMCIyT0iz83xD8JT29SR7O4SgswuPRIDYReYF/607A=="],
"three": ["three@0.174.0", "", {}, "sha512-p+WG3W6Ov74alh3geCMkGK9NWuT62ee21cV3jEnun201zodVF4tCE5aZa2U122/mkLRmhJJUQmLLW1BH00uQJQ=="],
"typescript": ["typescript@5.7.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw=="],
"undici-types": ["undici-types@6.20.0", "", {}, "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg=="],

View File

@@ -1,6 +1,6 @@
{
"name": "bun-plugin-svelte",
"version": "0.0.6",
"version": "0.0.5",
"description": "Official Svelte plugin for Bun",
"repository": {
"type": "git",

View File

@@ -11,11 +11,7 @@ describe("SveltePlugin", () => {
expect(() => SveltePlugin(undefined)).not.toThrow();
});
it.each([1, "hi", {}, "Client"])("throws if forceSide is not 'client' or 'server' (%p)", (forceSide: any) => {
it.each([null, 1, "hi", {}, "Client"])("throws if forceSide is not 'client' or 'server' (%p)", (forceSide: any) => {
expect(() => SveltePlugin({ forceSide })).toThrow(TypeError);
});
it.each([null, undefined])("forceSide may be nullish", (forceSide: any) => {
expect(() => SveltePlugin({ forceSide })).not.toThrow();
});
});

View File

@@ -2,7 +2,7 @@ import { describe, beforeAll, it, expect } from "bun:test";
import type { BuildConfig } from "bun";
import type { CompileOptions } from "svelte/compiler";
import { getBaseCompileOptions, validateOptions, type SvelteOptions } from "./options";
import { getBaseCompileOptions, type SvelteOptions } from "./options";
describe("getBaseCompileOptions", () => {
describe("when no options are provided", () => {
@@ -42,13 +42,4 @@ describe("getBaseCompileOptions", () => {
);
},
);
}); // getBaseCompileOptions
describe("validateOptions(options)", () => {
it.each(["", 1, null, undefined, true, false, Symbol("hi")])(
"throws if options is not an object (%p)",
(badOptions: any) => {
expect(() => validateOptions(badOptions)).toThrow();
},
);
}); // validateOptions
});

View File

@@ -2,8 +2,7 @@ import { strict as assert } from "node:assert";
import { type BuildConfig } from "bun";
import type { CompileOptions, ModuleCompileOptions } from "svelte/compiler";
type OverrideCompileOptions = Pick<CompileOptions, "customElement" | "runes" | "modernAst" | "namespace">;
export interface SvelteOptions extends Pick<CompileOptions, "runes"> {
export interface SvelteOptions {
/**
* Force client-side or server-side generation.
*
@@ -21,11 +20,6 @@ export interface SvelteOptions extends Pick<CompileOptions, "runes"> {
* Defaults to `true` when run via Bun's dev server, `false` otherwise.
*/
development?: boolean;
/**
* Options to forward to the Svelte compiler.
*/
compilerOptions?: OverrideCompileOptions;
}
/**
@@ -33,24 +27,15 @@ export interface SvelteOptions extends Pick<CompileOptions, "runes"> {
*/
export function validateOptions(options: unknown): asserts options is SvelteOptions {
assert(options && typeof options === "object", new TypeError("bun-svelte-plugin: options must be an object"));
const opts = options as Record<keyof SvelteOptions, unknown>;
if (opts.forceSide != null) {
if (typeof opts.forceSide !== "string") {
throw new TypeError("bun-svelte-plugin: forceSide must be a string, got " + typeof opts.forceSide);
}
switch (opts.forceSide) {
if ("forceSide" in options) {
switch (options.forceSide) {
case "client":
case "server":
break;
default:
throw new TypeError(`bun-svelte-plugin: forceSide must be either 'client' or 'server', got ${opts.forceSide}`);
}
}
if (opts.compilerOptions) {
if (typeof opts.compilerOptions !== "object") {
throw new TypeError("bun-svelte-plugin: compilerOptions must be an object");
throw new TypeError(
`bun-svelte-plugin: forceSide must be either 'client' or 'server', got ${options.forceSide}`,
);
}
}
}
@@ -59,10 +44,7 @@ export function validateOptions(options: unknown): asserts options is SvelteOpti
* @internal
*/
export function getBaseCompileOptions(pluginOptions: SvelteOptions, config: Partial<BuildConfig>): CompileOptions {
let {
development = false,
compilerOptions: { customElement, runes, modernAst, namespace } = kEmptyObject as OverrideCompileOptions,
} = pluginOptions;
let { development = false } = pluginOptions;
const { minify = false } = config;
const shouldMinify = Boolean(minify);
@@ -86,10 +68,6 @@ export function getBaseCompileOptions(pluginOptions: SvelteOptions, config: Part
preserveWhitespace: !minifyWhitespace,
preserveComments: !shouldMinify,
dev: development,
customElement,
runes,
modernAst,
namespace,
cssHash({ css }) {
// same prime number seed used by svelte/compiler.
// TODO: ensure this provides enough entropy
@@ -131,4 +109,3 @@ function generateSide(pluginOptions: SvelteOptions, config: Partial<BuildConfig>
}
export const hash = (content: string): string => Bun.hash(content, 5381).toString(36);
const kEmptyObject = Object.create(null);

View File

@@ -24,32 +24,13 @@ afterAll(() => {
}
});
describe("given a hello world component", () => {
const entrypoints = [fixturePath("foo.svelte")];
it("when no options are provided, builds successfully", async () => {
const res = await Bun.build({
entrypoints,
outdir,
plugins: [SveltePlugin()],
});
expect(res.success).toBeTrue();
});
describe("when a custom element is provided", () => {
let res: BuildOutput;
beforeAll(async () => {
res = await Bun.build({
entrypoints,
outdir,
plugins: [SveltePlugin({ compilerOptions: { customElement: true } })],
});
});
it("builds successfully", () => {
expect(res.success).toBeTrue();
});
it("hello world component", async () => {
const res = await Bun.build({
entrypoints: [fixturePath("foo.svelte")],
outdir,
plugins: [SveltePlugin()],
});
expect(res.success).toBeTrue();
});
describe("when importing `.svelte.ts` files with ESM", () => {

View File

@@ -20,7 +20,7 @@ That's it! VS Code and TypeScript automatically load `@types/*` packages into yo
# Contributing
The `@types/bun` package is a shim that loads `bun-types`. The `bun-types` package lives in the Bun repo under `packages/bun-types`.
The `@types/bun` package is a shim that loads `bun-types`. The `bun-types` package lives in the Bun repo under `packages/bun-types`. It is generated via [./scripts/bundle.ts](./scripts/bundle.ts).
To add a new file, add it under `packages/bun-types`. Then add a [triple-slash directive](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html) pointing to it inside [./index.d.ts](./index.d.ts).
@@ -28,6 +28,8 @@ To add a new file, add it under `packages/bun-types`. Then add a [triple-slash d
+ /// <reference path="./newfile.d.ts" />
```
[`./bundle.ts`](./bundle.ts) merges the types in this folder into a single file. To run it:
```bash
bun build
```

View File

@@ -19,13 +19,13 @@ declare module "*/bun.lock" {
}
declare module "*.html" {
// In Bun v1.2, this might change to Bun.HTMLBundle
// In Bun v1.2, we might change this to Bun.HTMLBundle
var contents: any;
export = contents;
}
declare module "*.svg" {
// Bun 1.2.3 added support for frontend dev server
var content: `${string}.svg`;
export = content;
var contents: `${string}.svg`;
export = contents;
}

View File

@@ -1,114 +0,0 @@
# Authoring @types/bun
These declarations define the `'bun'` module, the `Bun` global variable, and lots of other global declarations like extending the `fetch` interface.
## The `'bun'` Module
The `Bun` global variable and the `'bun'` module types are defined with one syntax. It supports declaring both types/interfaces and runtime values:
```typescript
declare module "bun" {
// Your types go here
interface MyInterface {
// ...
}
type MyType = string | number;
function myFunction(): void;
}
```
You can write as many `declare module "bun"` declarations as you need. Symbols will be accessible from other files inside of the declaration, and they will all be merged when the types are evaluated.
You can consume these declarations in two ways:
1. Importing it from `'bun'`:
```typescript
import { type MyInterface, type MyType, myFunction } from "bun";
const myInterface: MyInterface = {};
const myType: MyType = "cool";
myFunction();
```
2. Using the global `Bun` object:
```typescript
const myInterface: Bun.MyInterface = {};
const myType: Bun.MyType = "cool";
Bun.myFunction();
```
Consuming them inside the ambient declarations is also easy:
```ts
// These are equivalent
type A = import("bun").MyType;
type A = Bun.MyType;
```
## File Structure
Types are organized across multiple `.d.ts` files in the `packages/bun-types` directory:
- `index.d.ts` - The main entry point that references all other type files
- `bun.d.ts` - Core Bun APIs and types
- `globals.d.ts` - Global type declarations
- `test.d.ts` - Testing-related types
- `sqlite.d.ts` - SQLite-related types
- ...etc. You can make more files
Note: The order of references in `index.d.ts` is important - `bun.ns.d.ts` must be referenced last to ensure the `Bun` global gets defined properly.
### Best Practices
1. **Type Safety**
- Please use strict types instead of `any` where possible
- Leverage TypeScript's type system features (generics, unions, etc.)
- Document complex types with JSDoc comments
2. **Compatibility**
- Use `Bun.__internal.UseLibDomIfAvailable<LibDomName extends string, OurType>` for types that might conflict with lib.dom.d.ts (see [`./fetch.d.ts`](./fetch.d.ts) for a real example)
- `@types/node` often expects variables to always be defined (this was the biggest cause of most of the conflicts in the past!), so we use the `UseLibDomIfAvailable` type to make sure we don't overwrite `lib.dom.d.ts` but still provide Bun types while simultaneously declaring the variable exists (for Node to work) in the cases that we can.
3. **Documentation**
- Add JSDoc comments for public APIs
- Include examples in documentation when helpful
- Document default values and important behaviors
### Internal Types
For internal types that shouldn't be exposed to users, use the `__internal` namespace:
```typescript
declare module "bun" {
namespace __internal {
interface MyInternalType {
// ...
}
}
}
```
The internal namespace is mostly used for declaring things that shouldn't be globally accessible on the `bun` namespace, but are still used in public apis. You can see a pretty good example of that in the [`./fetch.d.ts`](./fetch.d.ts) file.
## Testing Types
We test our type definitions using a special test file at `fixture/index.ts`. This file contains TypeScript code that exercises our type definitions, but is never actually executed - it's only used to verify that the types work correctly.
The test file is type-checked in two different environments:
1. With `lib.dom.d.ts` included - This simulates usage in a browser environment where DOM types are available
2. Without `lib.dom.d.ts` - This simulates usage in a server-like environment without DOM types
Your type definitions must work properly in both environments. This ensures that Bun's types are compatible regardless of whether DOM types are present or not.
For example, if you're adding types for a new API, you should just add code to `fixture/index.ts` that uses your new API. Doesn't need to work at runtime (e.g. you can fake api keys for example), it's just checking that the types are correct.
## Questions
Feel free to open an issue or speak to any of the more TypeScript-focused team members if you need help authoring types or fixing type tests.

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +0,0 @@
import * as BunModule from "bun";
declare global {
export import Bun = BunModule;
}
export {};

View File

@@ -1,19 +1,4 @@
declare module "bun" {
interface BunMessageEvent<T> {
/**
* @deprecated
*/
initMessageEvent(
type: string,
bubbles?: boolean,
cancelable?: boolean,
data?: any,
origin?: string,
lastEventId?: string,
source?: null,
): void;
}
/**
* @deprecated Renamed to `ErrorLike`
*/
@@ -53,6 +38,21 @@ declare namespace NodeJS {
}
}
declare namespace Bun {
interface MessageEvent {
/** @deprecated */
initMessageEvent(
type: string,
bubbles?: boolean,
cancelable?: boolean,
data?: any,
origin?: string,
lastEventId?: string,
source?: null,
): void;
}
}
interface CustomEvent<T = any> {
/** @deprecated */
initCustomEvent(type: string, bubbles?: boolean, cancelable?: boolean, detail?: T): void;

View File

@@ -1,189 +1,192 @@
declare module "bun" {
type HMREventNames =
| "beforeUpdate"
| "afterUpdate"
| "beforeFullReload"
| "beforePrune"
| "invalidate"
| "error"
| "ws:disconnect"
| "ws:connect";
export {};
/**
* The event names for the dev server
*/
type HMREvent = `bun:${HMREventNames}` | (string & {});
}
interface ImportMeta {
/**
* Hot module replacement APIs. This value is `undefined` in production and
* can be used in an `if` statement to check if HMR APIs are available
*
* ```ts
* if (import.meta.hot) {
* // HMR APIs are available
* }
* ```
*
* However, this check is usually not needed as Bun will dead-code-eliminate
* calls to all of the HMR APIs in production builds.
*
* https://bun.sh/docs/bundler/hmr
*/
hot: {
/**
* `import.meta.hot.data` maintains state between module instances during
* hot replacement, enabling data transfer from previous to new versions.
* When `import.meta.hot.data` is written to, Bun will mark this module as
* capable of self-accepting (equivalent of calling `accept()`).
*
* @example
* ```ts
* const root = import.meta.hot.data.root ??= createRoot(elem);
* root.render(<App />); // re-use an existing root
* ```
*
* In production, `data` is inlined to be `{}`. This is handy because Bun
* knows it can minify `{}.prop ??= value` into `value` in production.
*
*
*/
data: any;
/**
* Indicate that this module can be replaced simply by re-evaluating the
* file. After a hot update, importers of this module will be
* automatically patched.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*
* @example
* ```ts
* import { getCount } from "./foo";
*
* console.log("count is ", getCount());
*
* import.meta.hot.accept();
* ```
*/
accept(): void;
/**
* Indicate that this module can be replaced by evaluating the new module,
* and then calling the callback with the new module. In this mode, the
* importers do not get patched. This is to match Vite, which is unable
* to patch their import statements. Prefer using `import.meta.hot.accept()`
* without an argument as it usually makes your code easier to understand.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*
* @example
* ```ts
* export const count = 0;
*
* import.meta.hot.accept((newModule) => {
* if (newModule) {
* // newModule is undefined when SyntaxError happened
* console.log('updated: count is now ', newModule.count)
* }
* });
* ```
*
* In production, calls to this are dead-code-eliminated.
*/
accept(cb: (newModule: any | undefined) => void): void;
/**
* Indicate that a dependency's module can be accepted. When the dependency
* is updated, the callback will be called with the new module.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*
* @example
* ```ts
* import.meta.hot.accept('./foo', (newModule) => {
* if (newModule) {
* // newModule is undefined when SyntaxError happened
* console.log('updated: count is now ', newModule.count)
* }
* });
* ```
*/
accept(specifier: string, callback: (newModule: any) => void): void;
/**
* Indicate that a dependency's module can be accepted. This variant
* accepts an array of dependencies, where the callback will receive
* the one updated module, and `undefined` for the rest.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*/
accept(specifiers: string[], callback: (newModules: (any | undefined)[]) => void): void;
/**
* Attach an on-dispose callback. This is called:
* - Just before the module is replaced with another copy (before the next is loaded)
* - After the module is detached (removing all imports to this module)
*
* This callback is not called on route navigation or when the browser tab closes.
*
* Returning a promise will delay module replacement until the module is
* disposed. All dispose callbacks are called in parallel.
*/
dispose(cb: (data: any) => void | Promise<void>): void;
/**
* No-op
* @deprecated
*/
decline(): void;
// NOTE TO CONTRIBUTORS ////////////////////////////////////////
// Callback is currently never called for `.prune()` //
// so the types are commented out until we support it. //
////////////////////////////////////////////////////////////////
// /**
// * Attach a callback that is called when the module is removed from the module graph.
// *
// * This can be used to clean up resources that were created when the module was loaded.
// * Unlike `import.meta.hot.dispose()`, this pairs much better with `accept` and `data` to manage stateful resources.
// *
// * @example
// * ```ts
// * export const ws = (import.meta.hot.data.ws ??= new WebSocket(location.origin));
// *
// * import.meta.hot.prune(() => {
// * ws.close();
// * });
// * ```
// */
// prune(callback: () => void): void;
/**
* Listen for an event from the dev server
*
* For compatibility with Vite, event names are also available via vite:* prefix instead of bun:*.
*
* https://bun.sh/docs/bundler/hmr#import-meta-hot-on-and-off
* @param event The event to listen to
* @param callback The callback to call when the event is emitted
*/
on(event: Bun.HMREvent, callback: () => void): void;
/**
* Stop listening for an event from the dev server
*
* For compatibility with Vite, event names are also available via vite:* prefix instead of bun:*.
*
* https://bun.sh/docs/bundler/hmr#import-meta-hot-on-and-off
* @param event The event to stop listening to
* @param callback The callback to stop listening to
*/
off(event: Bun.HMREvent, callback: () => void): void;
};
declare global {
namespace Bun {
type HMREventNames =
| "bun:ready"
| "bun:beforeUpdate"
| "bun:afterUpdate"
| "bun:beforeFullReload"
| "bun:beforePrune"
| "bun:invalidate"
| "bun:error"
| "bun:ws:disconnect"
| "bun:ws:connect";
/**
* The event names for the dev server
*/
type HMREvent = `bun:${HMREventNames}` | (string & {});
}
interface ImportMeta {
/**
* Hot module replacement APIs. This value is `undefined` in production and
* can be used in an `if` statement to check if HMR APIs are available
*
* ```ts
* if (import.meta.hot) {
* // HMR APIs are available
* }
* ```
*
* However, this check is usually not needed as Bun will dead-code-eliminate
* calls to all of the HMR APIs in production builds.
*
* https://bun.sh/docs/bundler/hmr
*/
hot: {
/**
* `import.meta.hot.data` maintains state between module instances during
* hot replacement, enabling data transfer from previous to new versions.
* When `import.meta.hot.data` is written to, Bun will mark this module as
* capable of self-accepting (equivalent of calling `accept()`).
*
* @example
* ```ts
* const root = import.meta.hot.data.root ??= createRoot(elem);
* root.render(<App />); // re-use an existing root
* ```
*
* In production, `data` is inlined to be `{}`. This is handy because Bun
* knows it can minify `{}.prop ??= value` into `value` in production.
*/
data: any;
/**
* Indicate that this module can be replaced simply by re-evaluating the
* file. After a hot update, importers of this module will be
* automatically patched.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*
* @example
* ```ts
* import { getCount } from "./foo";
*
* console.log("count is ", getCount());
*
* import.meta.hot.accept();
* ```
*/
accept(): void;
/**
* Indicate that this module can be replaced by evaluating the new module,
* and then calling the callback with the new module. In this mode, the
* importers do not get patched. This is to match Vite, which is unable
* to patch their import statements. Prefer using `import.meta.hot.accept()`
* without an argument as it usually makes your code easier to understand.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*
* @example
* ```ts
* export const count = 0;
*
* import.meta.hot.accept((newModule) => {
* if (newModule) {
* // newModule is undefined when SyntaxError happened
* console.log('updated: count is now ', newModule.count)
* }
* });
* ```
*
* In production, calls to this are dead-code-eliminated.
*/
accept(cb: (newModule: any | undefined) => void): void;
/**
* Indicate that a dependency's module can be accepted. When the dependency
* is updated, the callback will be called with the new module.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*
* @example
* ```ts
* import.meta.hot.accept('./foo', (newModule) => {
* if (newModule) {
* // newModule is undefined when SyntaxError happened
* console.log('updated: count is now ', newModule.count)
* }
* });
* ```
*/
accept(specifier: string, callback: (newModule: any) => void): void;
/**
* Indicate that a dependency's module can be accepted. This variant
* accepts an array of dependencies, where the callback will receive
* the one updated module, and `undefined` for the rest.
*
* When `import.meta.hot.accept` is not used, the page will reload when
* the file updates, and a console message shows which files were checked.
*/
accept(specifiers: string[], callback: (newModules: (any | undefined)[]) => void): void;
/**
* Attach an on-dispose callback. This is called:
* - Just before the module is replaced with another copy (before the next is loaded)
* - After the module is detached (removing all imports to this module)
*
* This callback is not called on route navigation or when the browser tab closes.
*
* Returning a promise will delay module replacement until the module is
* disposed. All dispose callbacks are called in parallel.
*/
dispose(cb: (data: any) => void | Promise<void>): void;
/**
* No-op
* @deprecated
*/
decline(): void;
// NOTE TO CONTRIBUTORS ////////////////////////////////////////
// Callback is currently never called for `.prune()` //
// so the types are commented out until we support it. //
////////////////////////////////////////////////////////////////
// /**
// * Attach a callback that is called when the module is removed from the module graph.
// *
// * This can be used to clean up resources that were created when the module was loaded.
// * Unlike `import.meta.hot.dispose()`, this pairs much better with `accept` and `data` to manage stateful resources.
// *
// * @example
// * ```ts
// * export const ws = (import.meta.hot.data.ws ??= new WebSocket(location.origin));
// *
// * import.meta.hot.prune(() => {
// * ws.close();
// * });
// * ```
// */
// prune(callback: () => void): void;
/**
* Listen for an event from the dev server
*
* For compatibility with Vite, event names are also available via vite:* prefix instead of bun:*.
*
* https://bun.sh/docs/bundler/hmr#import-meta-hot-on-and-off
* @param event The event to listen to
* @param callback The callback to call when the event is emitted
*/
on(event: Bun.HMREvent, callback: () => void): void;
/**
* Stop listening for an event from the dev server
*
* For compatibility with Vite, event names are also available via vite:* prefix instead of bun:*.
*
* https://bun.sh/docs/bundler/hmr#import-meta-hot-on-and-off
* @param event The event to stop listening to
* @param callback The callback to stop listening to
*/
off(event: Bun.HMREvent, callback: () => void): void;
};
}
}

View File

@@ -1,72 +1,161 @@
/*
This file does not declare any global types.
That should only happen in [./globals.d.ts](./globals.d.ts)
so that our documentation generator can pick it up, as it
expects all globals to be declared in one file.
*/
declare module "bun" {
type HeadersInit = string[][] | Record<string, string | ReadonlyArray<string>> | Headers;
type BodyInit = ReadableStream | Bun.XMLHttpRequestBodyInit | URLSearchParams | AsyncGenerator<Uint8Array>;
namespace __internal {
type LibOrFallbackHeaders = LibDomIsLoaded extends true ? {} : import("undici-types").Headers;
type LibOrFallbackRequest = LibDomIsLoaded extends true ? {} : import("undici-types").Request;
type LibOrFallbackResponse = LibDomIsLoaded extends true ? {} : import("undici-types").Response;
type LibOrFallbackResponseInit = LibDomIsLoaded extends true ? {} : import("undici-types").ResponseInit;
type LibOrFallbackRequestInit = LibDomIsLoaded extends true
? {}
: Omit<import("undici-types").RequestInit, "body" | "headers"> & {
body?: Bun.BodyInit | null | undefined;
headers?: Bun.HeadersInit;
};
interface BunHeadersOverride extends LibOrFallbackHeaders {
/**
* Convert {@link Headers} to a plain JavaScript object.
*
* About 10x faster than `Object.fromEntries(headers.entries())`
*
* Called when you run `JSON.stringify(headers)`
*
* Does not preserve insertion order. Well-known header names are lowercased. Other header names are left as-is.
*/
toJSON(): Record<string, string>;
/**
* Get the total number of headers
*/
readonly count: number;
/**
* Get all headers matching the name
*
* Only supports `"Set-Cookie"`. All other headers are empty arrays.
*
* @param name - The header name to get
*
* @returns An array of header values
*
* @example
* ```ts
* const headers = new Headers();
* headers.append("Set-Cookie", "foo=bar");
* headers.append("Set-Cookie", "baz=qux");
* headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"]
* ```
*/
getAll(name: "set-cookie" | "Set-Cookie"): string[];
}
interface BunRequestOverride extends LibOrFallbackRequest {
headers: BunHeadersOverride;
}
interface BunResponseOverride extends LibOrFallbackResponse {
headers: BunHeadersOverride;
}
}
interface Headers {
/**
* Convert {@link Headers} to a plain JavaScript object.
*
* About 10x faster than `Object.fromEntries(headers.entries())`
*
* Called when you run `JSON.stringify(headers)`
*
* Does not preserve insertion order. Well-known header names are lowercased. Other header names are left as-is.
*/
toJSON(): Record<string, string>;
/**
* Get the total number of headers
*/
readonly count: number;
/**
* Get all headers matching the name
*
* Only supports `"Set-Cookie"`. All other headers are empty arrays.
*
* @param name - The header name to get
*
* @returns An array of header values
*
* @example
* ```ts
* const headers = new Headers();
* headers.append("Set-Cookie", "foo=bar");
* headers.append("Set-Cookie", "baz=qux");
* headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"]
* ```
*/
getAll(name: "set-cookie" | "Set-Cookie"): string[];
}
var Headers: {
prototype: Headers;
new (init?: Bun.HeadersInit): Headers;
};
interface Request {
headers: Headers;
}
var Request: {
prototype: Request;
new (requestInfo: string, requestInit?: RequestInit): Request;
new (requestInfo: RequestInit & { url: string }): Request;
new (requestInfo: Request, requestInit?: RequestInit): Request;
};
var Response: {
new (body?: Bun.BodyInit | null | undefined, init?: Bun.ResponseInit | undefined): Response;
/**
* Create a new {@link Response} with a JSON body
*
* @param body - The body of the response
* @param options - options to pass to the response
*
* @example
*
* ```ts
* const response = Response.json({hi: "there"});
* console.assert(
* await response.text(),
* `{"hi":"there"}`
* );
* ```
* -------
*
* This is syntactic sugar for:
* ```js
* new Response(JSON.stringify(body), {headers: { "Content-Type": "application/json" }})
* ```
* @link https://github.com/whatwg/fetch/issues/1389
*/
json(body?: any, options?: Bun.ResponseInit | number): Response;
/**
* Create a new {@link Response} that redirects to url
*
* @param url - the URL to redirect to
* @param status - the HTTP status code to use for the redirect
*/
// tslint:disable-next-line:unified-signatures
redirect(url: string, status?: number): Response;
/**
* Create a new {@link Response} that redirects to url
*
* @param url - the URL to redirect to
* @param options - options to pass to the response
*/
// tslint:disable-next-line:unified-signatures
redirect(url: string, options?: Bun.ResponseInit): Response;
/**
* Create a new {@link Response} that has a network error
*/
error(): Response;
};
type _BunTLSOptions = import("bun").TLSOptions;
interface BunFetchRequestInitTLS extends _BunTLSOptions {
/**
* Custom function to check the server identity
* @param hostname - The hostname of the server
* @param cert - The certificate of the server
* @returns An error if the server is unauthorized, otherwise undefined
*/
checkServerIdentity?: NonNullable<import("node:tls").ConnectionOptions["checkServerIdentity"]>;
}
/**
* BunFetchRequestInit represents additional options that Bun supports in `fetch()` only.
*
* Bun extends the `fetch` API with some additional options, except
* this interface is not quite a `RequestInit`, because they won't work
* if passed to `new Request()`. This is why it's a separate type.
*/
interface BunFetchRequestInit extends RequestInit {
/**
* Override the default TLS options
*/
tls?: BunFetchRequestInitTLS;
}
var fetch: {
/**
* Send a HTTP(s) request
*
* @param request Request object
* @param init A structured value that contains settings for the fetch() request.
*
* @returns A promise that resolves to {@link Response} object.
*/
(request: Request, init?: BunFetchRequestInit): Promise<Response>;
/**
* Send a HTTP(s) request
*
* @param url URL string
* @param init A structured value that contains settings for the fetch() request.
*
* @returns A promise that resolves to {@link Response} object.
*/
(url: string | URL | Request, init?: BunFetchRequestInit): Promise<Response>;
(input: string | URL | globalThis.Request, init?: BunFetchRequestInit): Promise<Response>;
/**
* Start the DNS resolution, TCP connection, and TLS handshake for a request
* before the request is actually sent.
*
* This can reduce the latency of a request when you know there's some
* long-running task that will delay the request starting.
*
* This is a bun-specific API and is not part of the Fetch API specification.
*/
preconnect(url: string | URL): void;
};

View File

@@ -13,8 +13,6 @@
* that convert JavaScript types to C types and back. Internally,
* bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks
* goes to Fabrice Bellard and TinyCC maintainers for making this possible.
*
* @category FFI
*/
declare module "bun:ffi" {
enum FFIType {
@@ -545,6 +543,14 @@ declare module "bun:ffi" {
type Symbols = Readonly<Record<string, FFIFunction>>;
// /**
// * Compile a callback function
// *
// * Returns a function pointer
// *
// */
// export function callback(ffi: FFIFunction, cb: Function): number;
interface Library<Fns extends Symbols> {
symbols: ConvertFns<Fns>;
@@ -602,8 +608,6 @@ declare module "bun:ffi" {
* that convert JavaScript types to C types and back. Internally,
* bun uses [tinycc](https://github.com/TinyCC/tinycc), so a big thanks
* goes to Fabrice Bellard and TinyCC maintainers for making this possible.
*
* @category FFI
*/
function dlopen<Fns extends Record<string, FFIFunction>>(
name: string | import("bun").BunFile | URL,
@@ -622,9 +626,9 @@ declare module "bun:ffi" {
* JavaScript:
* ```js
* import { cc } from "bun:ffi";
* import source from "./hello.c" with {type: "file"};
* import hello from "./hello.c" with {type: "file"};
* const {symbols: {hello}} = cc({
* source,
* source: hello,
* symbols: {
* hello: {
* returns: "cstring",
@@ -677,9 +681,8 @@ declare module "bun:ffi" {
* @example
* ```js
* import { cc } from "bun:ffi";
* import source from "./hello.c" with {type: "file"};
* const {symbols: {hello}} = cc({
* source,
* source: hello,
* define: {
* "NDEBUG": "1",
* },
@@ -704,9 +707,8 @@ declare module "bun:ffi" {
* @example
* ```js
* import { cc } from "bun:ffi";
* import source from "./hello.c" with {type: "file"};
* const {symbols: {hello}} = cc({
* source,
* source: hello,
* flags: ["-framework CoreFoundation", "-framework Security"],
* symbols: {
* hello: {
@@ -1022,8 +1024,6 @@ declare module "bun:ffi" {
* // Do something with rawPtr
* }
* ```
*
* @category FFI
*/
function ptr(view: NodeJS.TypedArray | ArrayBufferLike | DataView, byteOffset?: number): Pointer;
@@ -1048,9 +1048,8 @@ declare module "bun:ffi" {
* thing to do safely. Passing an invalid pointer can crash the program and
* reading beyond the bounds of the pointer will crash the program or cause
* undefined behavior. Use with care!
*
* @category FFI
*/
class CString extends String {
/**
* Get a string from a UTF-8 encoded C string

File diff suppressed because it is too large Load Diff

View File

@@ -147,8 +147,6 @@ declare namespace HTMLRewriterTypes {
* });
* rewriter.transform(await fetch("https://remix.run"));
* ```
*
* @category HTML Manipulation
*/
declare class HTMLRewriter {
constructor();

View File

@@ -1,26 +1,24 @@
// Project: https://github.com/oven-sh/bun
// Definitions by: Bun Contributors <https://github.com/oven-sh/bun/graphs/contributors>
// Definitions by: Jarred Sumner <https://github.com/Jarred-Sumner>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference lib="esnext" />
/// <reference types="ws" />
/// <reference types="node" />
/// <reference path="./globals.d.ts" />
/// <reference path="./s3.d.ts" />
/// <reference path="./fetch.d.ts" />
// contributors: uncomment this to detect conflicts with lib.dom.d.ts
// /// <reference lib="dom" />
/// <reference path="./bun.d.ts" />
/// <reference path="./extensions.d.ts" />
/// <reference path="./devserver.d.ts" />
/// <reference path="./globals.d.ts" />
/// <reference path="./fetch.d.ts" />
/// <reference path="./overrides.d.ts" />
/// <reference path="./ffi.d.ts" />
/// <reference path="./test.d.ts" />
/// <reference path="./html-rewriter.d.ts" />
/// <reference path="./jsc.d.ts" />
/// <reference path="./sqlite.d.ts" />
/// <reference path="./test.d.ts" />
/// <reference path="./wasm.d.ts" />
/// <reference path="./overrides.d.ts" />
/// <reference path="./deprecated.d.ts" />
/// <reference path="./bun.ns.d.ts" />
// @ts-ignore Must disable this so it doesn't conflict with the DOM onmessage type, but still
// allows us to declare our own globals that Node's types can "see" and not conflict with
declare var onmessage: never;
/// <reference path="./ambient.d.ts" />
/// <reference path="./devserver.d.ts" />

View File

@@ -1,73 +1,18 @@
export {};
import type { BunFile, Env, PathLike } from "bun";
declare global {
namespace NodeJS {
interface ProcessEnv extends Bun.Env {}
interface Process {
readonly version: string;
browser: boolean;
/**
* Whether you are using Bun
*/
isBun: true;
/**
* The current git sha of Bun
*/
revision: string;
reallyExit(code?: number): never;
dlopen(module: { exports: any }, filename: string, flags?: number): void;
_exiting: boolean;
noDeprecation: boolean;
binding(m: "constants"): {
os: typeof import("node:os").constants;
fs: typeof import("node:fs").constants;
crypto: typeof import("node:crypto").constants;
zlib: typeof import("node:zlib").constants;
trace: {
TRACE_EVENT_PHASE_BEGIN: number;
TRACE_EVENT_PHASE_END: number;
TRACE_EVENT_PHASE_COMPLETE: number;
TRACE_EVENT_PHASE_INSTANT: number;
TRACE_EVENT_PHASE_ASYNC_BEGIN: number;
TRACE_EVENT_PHASE_ASYNC_STEP_INTO: number;
TRACE_EVENT_PHASE_ASYNC_STEP_PAST: number;
TRACE_EVENT_PHASE_ASYNC_END: number;
TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN: number;
TRACE_EVENT_PHASE_NESTABLE_ASYNC_END: number;
TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT: number;
TRACE_EVENT_PHASE_FLOW_BEGIN: number;
TRACE_EVENT_PHASE_FLOW_STEP: number;
TRACE_EVENT_PHASE_FLOW_END: number;
TRACE_EVENT_PHASE_METADATA: number;
TRACE_EVENT_PHASE_COUNTER: number;
TRACE_EVENT_PHASE_SAMPLE: number;
TRACE_EVENT_PHASE_CREATE_OBJECT: number;
TRACE_EVENT_PHASE_SNAPSHOT_OBJECT: number;
TRACE_EVENT_PHASE_DELETE_OBJECT: number;
TRACE_EVENT_PHASE_MEMORY_DUMP: number;
TRACE_EVENT_PHASE_MARK: number;
TRACE_EVENT_PHASE_CLOCK_SYNC: number;
TRACE_EVENT_PHASE_ENTER_CONTEXT: number;
TRACE_EVENT_PHASE_LEAVE_CONTEXT: number;
TRACE_EVENT_PHASE_LINK_IDS: number;
};
};
binding(m: string): object;
}
interface ProcessVersions extends Dict<string> {
bun: string;
}
interface ProcessEnv extends Env {}
}
}
declare module "fs/promises" {
function exists(path: Bun.PathLike): Promise<boolean>;
function exists(path: PathLike): Promise<boolean>;
}
declare module "tls" {
@@ -77,7 +22,7 @@ declare module "tls" {
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?: string | Buffer | NodeJS.TypedArray | Bun.BunFile | Array<string | Buffer | Bun.BunFile> | undefined;
ca?: string | Buffer | NodeJS.TypedArray | BunFile | Array<string | Buffer | BunFile> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
@@ -93,8 +38,8 @@ declare module "tls" {
| string
| Buffer
| NodeJS.TypedArray
| Bun.BunFile
| Array<string | Buffer | NodeJS.TypedArray | Bun.BunFile>
| BunFile
| Array<string | Buffer | NodeJS.TypedArray | BunFile>
| undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
@@ -109,9 +54,9 @@ declare module "tls" {
key?:
| string
| Buffer
| Bun.BunFile
| BunFile
| NodeJS.TypedArray
| Array<string | Buffer | Bun.BunFile | NodeJS.TypedArray | KeyObject>
| Array<string | Buffer | BunFile | NodeJS.TypedArray | KeyObject>
| undefined;
}

View File

@@ -9,14 +9,14 @@
"directory": "packages/bun-types"
},
"files": [
"./*.d.ts",
"*.d.ts",
"docs/**/*.md",
"docs/*.md"
],
"homepage": "https://bun.sh",
"dependencies": {
"@types/node": "*",
"@types/ws": "*"
"@types/ws": "~8.5.10"
},
"devDependencies": {
"@biomejs/biome": "^1.5.3",
@@ -27,7 +27,7 @@
"scripts": {
"prebuild": "echo $(pwd)",
"copy-docs": "rm -rf docs && cp -rL ../../docs/ ./docs && find ./docs -type f -name '*.md' -exec sed -i 's/\\$BUN_LATEST_VERSION/'\"${BUN_VERSION#bun-v}\"'/g' {} +",
"build": "bun run copy-docs && bun scripts/build.ts",
"build": "bun run copy-docs && bun scripts/build.ts && bun run fmt",
"test": "tsc",
"fmt": "echo $(which biome) && biome format --write ."
},

View File

@@ -1,831 +0,0 @@
declare module "bun" {
/**
* Fast incremental writer for files and pipes.
*
* This uses the same interface as {@link ArrayBufferSink}, but writes to a file or pipe.
*/
interface FileSink {
/**
* Write a chunk of data to the file.
*
* If the file descriptor is not writable yet, the data is buffered.
*/
write(chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer): number;
/**
* Flush the internal buffer, committing the data to disk or the pipe.
*/
flush(): number | Promise<number>;
/**
* Close the file descriptor. This also flushes the internal buffer.
*/
end(error?: Error): number | Promise<number>;
start(options?: {
/**
* Preallocate an internal buffer of this size
* This can significantly improve performance when the chunk size is small
*/
highWaterMark?: number;
}): void;
/**
* For FIFOs & pipes, this lets you decide whether Bun's process should
* remain alive until the pipe is closed.
*
* By default, it is automatically managed. While the stream is open, the
* process remains alive and once the other end hangs up or the stream
* closes, the process exits.
*
* If you previously called {@link unref}, you can call this again to re-enable automatic management.
*
* Internally, it will reference count the number of times this is called. By default, that number is 1
*
* If the file is not a FIFO or pipe, {@link ref} and {@link unref} do
* nothing. If the pipe is already closed, this does nothing.
*/
ref(): void;
/**
* For FIFOs & pipes, this lets you decide whether Bun's process should
* remain alive until the pipe is closed.
*
* If you want to allow Bun's process to terminate while the stream is open,
* call this.
*
* If the file is not a FIFO or pipe, {@link ref} and {@link unref} do
* nothing. If the pipe is already closed, this does nothing.
*/
unref(): void;
}
interface NetworkSink extends FileSink {
/**
* Write a chunk of data to the network.
*
* If the network is not writable yet, the data is buffered.
*/
write(chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer): number;
/**
* Flush the internal buffer, committing the data to the network.
*/
flush(): number | Promise<number>;
/**
* Finish the upload. This also flushes the internal buffer.
*/
end(error?: Error): number | Promise<number>;
/**
* Get the stat of the file.
*/
stat(): Promise<import("node:fs").Stats>;
}
/**
* Configuration options for S3 operations
*/
interface S3Options extends BlobPropertyBag {
/**
* The Access Control List (ACL) policy for the file.
* Controls who can access the file and what permissions they have.
*
* @example
* // Setting public read access
* const file = s3.file("public-file.txt", {
* acl: "public-read",
* bucket: "my-bucket"
* });
*
* @example
* // Using with presigned URLs
* const url = file.presign({
* acl: "public-read",
* expiresIn: 3600
* });
*/
acl?:
| "private"
| "public-read"
| "public-read-write"
| "aws-exec-read"
| "authenticated-read"
| "bucket-owner-read"
| "bucket-owner-full-control"
| "log-delivery-write";
/**
* The S3 bucket name. Defaults to `S3_BUCKET` or `AWS_BUCKET` environment variables.
*
* @example
* // Using explicit bucket
* const file = s3.file("my-file.txt", { bucket: "my-bucket" });
*
* @example
* // Using environment variables
* // With S3_BUCKET=my-bucket in .env
* const file = s3.file("my-file.txt");
*/
bucket?: string;
/**
* The AWS region. Defaults to `S3_REGION` or `AWS_REGION` environment variables.
*
* @example
* const file = s3.file("my-file.txt", {
* bucket: "my-bucket",
* region: "us-west-2"
* });
*/
region?: string;
/**
* The access key ID for authentication.
* Defaults to `S3_ACCESS_KEY_ID` or `AWS_ACCESS_KEY_ID` environment variables.
*/
accessKeyId?: string;
/**
* The secret access key for authentication.
* Defaults to `S3_SECRET_ACCESS_KEY` or `AWS_SECRET_ACCESS_KEY` environment variables.
*/
secretAccessKey?: string;
/**
* Optional session token for temporary credentials.
* Defaults to `S3_SESSION_TOKEN` or `AWS_SESSION_TOKEN` environment variables.
*
* @example
* // Using temporary credentials
* const file = s3.file("my-file.txt", {
* accessKeyId: tempAccessKey,
* secretAccessKey: tempSecretKey,
* sessionToken: tempSessionToken
* });
*/
sessionToken?: string;
/**
* The S3-compatible service endpoint URL.
* Defaults to `S3_ENDPOINT` or `AWS_ENDPOINT` environment variables.
*
* @example
* // AWS S3
* const file = s3.file("my-file.txt", {
* endpoint: "https://s3.us-east-1.amazonaws.com"
* });
*
* @example
* // Cloudflare R2
* const file = s3.file("my-file.txt", {
* endpoint: "https://<account-id>.r2.cloudflarestorage.com"
* });
*
* @example
* // DigitalOcean Spaces
* const file = s3.file("my-file.txt", {
* endpoint: "https://<region>.digitaloceanspaces.com"
* });
*
* @example
* // MinIO (local development)
* const file = s3.file("my-file.txt", {
* endpoint: "http://localhost:9000"
* });
*/
endpoint?: string;
/**
* Use virtual hosted style endpoint. default to false, when true if `endpoint` is informed it will ignore the `bucket`
*
* @example
* // Using virtual hosted style
* const file = s3.file("my-file.txt", {
* virtualHostedStyle: true,
* endpoint: "https://my-bucket.s3.us-east-1.amazonaws.com"
* });
*/
virtualHostedStyle?: boolean;
/**
* The size of each part in multipart uploads (in bytes).
* - Minimum: 5 MiB
* - Maximum: 5120 MiB
* - Default: 5 MiB
*
* @example
* // Configuring multipart uploads
* const file = s3.file("large-file.dat", {
* partSize: 10 * 1024 * 1024, // 10 MiB parts
* queueSize: 4 // Upload 4 parts in parallel
* });
*
* const writer = file.writer();
* // ... write large file in chunks
*/
partSize?: number;
/**
* Number of parts to upload in parallel for multipart uploads.
* - Default: 5
* - Maximum: 255
*
* Increasing this value can improve upload speeds for large files
* but will use more memory.
*/
queueSize?: number;
/**
* Number of retry attempts for failed uploads.
* - Default: 3
* - Maximum: 255
*
* @example
* // Setting retry attempts
* const file = s3.file("my-file.txt", {
* retry: 5 // Retry failed uploads up to 5 times
* });
*/
retry?: number;
/**
* The Content-Type of the file.
* Automatically set based on file extension when possible.
*
* @example
* // Setting explicit content type
* const file = s3.file("data.bin", {
* type: "application/octet-stream"
* });
*/
type?: string;
/**
* By default, Amazon S3 uses the STANDARD Storage Class to store newly created objects.
*
* @example
* // Setting explicit Storage class
* const file = s3.file("my-file.json", {
* storageClass: "STANDARD_IA"
* });
*/
storageClass?:
| "STANDARD"
| "DEEP_ARCHIVE"
| "EXPRESS_ONEZONE"
| "GLACIER"
| "GLACIER_IR"
| "INTELLIGENT_TIERING"
| "ONEZONE_IA"
| "OUTPOSTS"
| "REDUCED_REDUNDANCY"
| "SNOW"
| "STANDARD_IA";
/**
* @deprecated The size of the internal buffer in bytes. Defaults to 5 MiB. use `partSize` and `queueSize` instead.
*/
highWaterMark?: number;
}
/**
* Options for generating presigned URLs
*/
interface S3FilePresignOptions extends S3Options {
/**
* Number of seconds until the presigned URL expires.
* - Default: 86400 (1 day)
*
* @example
* // Short-lived URL
* const url = file.presign({
* expiresIn: 3600 // 1 hour
* });
*
* @example
* // Long-lived public URL
* const url = file.presign({
* expiresIn: 7 * 24 * 60 * 60, // 7 days
* acl: "public-read"
* });
*/
expiresIn?: number;
/**
* The HTTP method allowed for the presigned URL.
*
* @example
* // GET URL for downloads
* const downloadUrl = file.presign({
* method: "GET",
* expiresIn: 3600
* });
*
* @example
* // PUT URL for uploads
* const uploadUrl = file.presign({
* method: "PUT",
* expiresIn: 3600,
* type: "application/json"
* });
*/
method?: "GET" | "POST" | "PUT" | "DELETE" | "HEAD";
}
interface S3Stats {
size: number;
lastModified: Date;
etag: string;
type: string;
}
/**
* Represents a file in an S3-compatible storage service.
* Extends the Blob interface for compatibility with web APIs.
*
* @category Cloud Storage
*/
interface S3File extends Blob {
/**
* The size of the file in bytes.
* This is a Promise because it requires a network request to determine the size.
*
* @example
* // Getting file size
* const size = await file.size;
* console.log(`File size: ${size} bytes`);
*
* @example
* // Check if file is larger than 1MB
* if (await file.size > 1024 * 1024) {
* console.log("Large file detected");
* }
*/
/**
* TODO: figure out how to get the typescript types to not error for this property.
*/
// size: Promise<number>;
/**
* Creates a new S3File representing a slice of the original file.
* Uses HTTP Range headers for efficient partial downloads.
*
* @param begin - Starting byte offset
* @param end - Ending byte offset (exclusive)
* @param contentType - Optional MIME type for the slice
* @returns A new S3File representing the specified range
*
* @example
* // Reading file header
* const header = file.slice(0, 1024);
* const headerText = await header.text();
*
* @example
* // Reading with content type
* const jsonSlice = file.slice(1024, 2048, "application/json");
* const data = await jsonSlice.json();
*
* @example
* // Reading from offset to end
* const remainder = file.slice(1024);
* const content = await remainder.text();
*/
slice(begin?: number, end?: number, contentType?: string): S3File;
slice(begin?: number, contentType?: string): S3File;
slice(contentType?: string): S3File;
/**
* Creates a writable stream for uploading data.
* Suitable for large files as it uses multipart upload.
*
* @param options - Configuration for the upload
* @returns A NetworkSink for writing data
*
* @example
* // Basic streaming write
* const writer = file.writer({
* type: "application/json"
* });
* writer.write('{"hello": ');
* writer.write('"world"}');
* await writer.end();
*
* @example
* // Optimized large file upload
* const writer = file.writer({
* partSize: 10 * 1024 * 1024, // 10MB parts
* queueSize: 4, // Upload 4 parts in parallel
* retry: 3 // Retry failed parts
* });
*
* // Write large chunks of data efficiently
* for (const chunk of largeDataChunks) {
* writer.write(chunk);
* }
* await writer.end();
*
* @example
* // Error handling
* const writer = file.writer();
* try {
* writer.write(data);
* await writer.end();
* } catch (err) {
* console.error('Upload failed:', err);
* // Writer will automatically abort multipart upload on error
* }
*/
writer(options?: S3Options): NetworkSink;
/**
* Gets a readable stream of the file's content.
* Useful for processing large files without loading them entirely into memory.
*
* @returns A ReadableStream for the file content
*
* @example
* // Basic streaming read
* const stream = file.stream();
* for await (const chunk of stream) {
* console.log('Received chunk:', chunk);
* }
*
* @example
* // Piping to response
* const stream = file.stream();
* return new Response(stream, {
* headers: { 'Content-Type': file.type }
* });
*
* @example
* // Processing large files
* const stream = file.stream();
* const textDecoder = new TextDecoder();
* for await (const chunk of stream) {
* const text = textDecoder.decode(chunk);
* // Process text chunk by chunk
* }
*/
readonly readable: ReadableStream;
stream(): ReadableStream;
/**
* The name or path of the file in the bucket.
*
* @example
* const file = s3.file("folder/image.jpg");
* console.log(file.name); // "folder/image.jpg"
*/
readonly name?: string;
/**
* The bucket name containing the file.
*
* @example
* const file = s3.file("s3://my-bucket/file.txt");
* console.log(file.bucket); // "my-bucket"
*/
readonly bucket?: string;
/**
* Checks if the file exists in S3.
* Uses HTTP HEAD request to efficiently check existence without downloading.
*
* @returns Promise resolving to true if file exists, false otherwise
*
* @example
* // Basic existence check
* if (await file.exists()) {
* console.log("File exists in S3");
* }
*
* @example
* // With error handling
* try {
* const exists = await file.exists();
* if (!exists) {
* console.log("File not found");
* }
* } catch (err) {
* console.error("Error checking file:", err);
* }
*/
exists(): Promise<boolean>;
/**
* Uploads data to S3.
* Supports various input types and automatically handles large files.
*
* @param data - The data to upload
* @param options - Upload configuration options
* @returns Promise resolving to number of bytes written
*
* @example
* // Writing string data
* await file.write("Hello World", {
* type: "text/plain"
* });
*
* @example
* // Writing JSON
* const data = { hello: "world" };
* await file.write(JSON.stringify(data), {
* type: "application/json"
* });
*
* @example
* // Writing from Response
* const response = await fetch("https://example.com/data");
* await file.write(response);
*
* @example
* // Writing with ACL
* await file.write(data, {
* acl: "public-read",
* type: "application/octet-stream"
* });
*/
write(
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer | Request | Response | BunFile | S3File | Blob,
options?: S3Options,
): Promise<number>;
/**
* Generates a presigned URL for the file.
* Allows temporary access to the file without exposing credentials.
*
* @param options - Configuration for the presigned URL
* @returns Presigned URL string
*
* @example
* // Basic download URL
* const url = file.presign({
* expiresIn: 3600 // 1 hour
* });
*
* @example
* // Upload URL with specific content type
* const uploadUrl = file.presign({
* method: "PUT",
* expiresIn: 3600,
* type: "image/jpeg",
* acl: "public-read"
* });
*
* @example
* // URL with custom permissions
* const url = file.presign({
* method: "GET",
* expiresIn: 7 * 24 * 60 * 60, // 7 days
* acl: "public-read"
* });
*/
presign(options?: S3FilePresignOptions): string;
/**
* Deletes the file from S3.
*
* @returns Promise that resolves when deletion is complete
*
* @example
* // Basic deletion
* await file.delete();
*
* @example
* // With error handling
* try {
* await file.delete();
* console.log("File deleted successfully");
* } catch (err) {
* console.error("Failed to delete file:", err);
* }
*/
delete(): Promise<void>;
/**
* Alias for delete() method.
* Provided for compatibility with Node.js fs API naming.
*
* @example
* await file.unlink();
*/
unlink: S3File["delete"];
/**
* Get the stat of a file in an S3-compatible storage service.
*
* @returns Promise resolving to S3Stat
*/
stat(): Promise<S3Stats>;
}
/**
* A configured S3 bucket instance for managing files.
* The instance is callable to create S3File instances and provides methods
* for common operations.
*
* @example
* // Basic bucket setup
* const bucket = new S3Client({
* bucket: "my-bucket",
* accessKeyId: "key",
* secretAccessKey: "secret"
* });
*
* // Get file instance
* const file = bucket.file("image.jpg");
*
* // Common operations
* await bucket.write("data.json", JSON.stringify({hello: "world"}));
* const url = bucket.presign("file.pdf");
* await bucket.unlink("old.txt");
*
* @category Cloud Storage
*/
class S3Client {
prototype: S3Client;
/**
* Create a new instance of an S3 bucket so that credentials can be managed
* from a single instance instead of being passed to every method.
*
* @param options The default options to use for the S3 client. Can be
* overriden by passing options to the methods.
*
* ## Keep S3 credentials in a single instance
*
* @example
* const bucket = new Bun.S3Client({
* accessKeyId: "your-access-key",
* secretAccessKey: "your-secret-key",
* bucket: "my-bucket",
* endpoint: "https://s3.us-east-1.amazonaws.com",
* sessionToken: "your-session-token",
* });
*
* // S3Client is callable, so you can do this:
* const file = bucket.file("my-file.txt");
*
* // or this:
* await file.write("Hello Bun!");
* await file.text();
*
* // To delete the file:
* await bucket.delete("my-file.txt");
*
* // To write a file without returning the instance:
* await bucket.write("my-file.txt", "Hello Bun!");
*
*/
constructor(options?: S3Options);
/**
* Creates an S3File instance for the given path.
*
* @example
* const file = bucket.file("image.jpg");
* await file.write(imageData);
* const configFile = bucket.file("config.json", {
* type: "application/json",
* acl: "private"
* });
*/
file(path: string, options?: S3Options): S3File;
/**
* Writes data directly to a path in the bucket.
* Supports strings, buffers, streams, and web API types.
*
* @example
* // Write string
* await bucket.write("hello.txt", "Hello World");
*
* // Write JSON with type
* await bucket.write(
* "data.json",
* JSON.stringify({hello: "world"}),
* {type: "application/json"}
* );
*
* // Write from fetch
* const res = await fetch("https://example.com/data");
* await bucket.write("data.bin", res);
*
* // Write with ACL
* await bucket.write("public.html", html, {
* acl: "public-read",
* type: "text/html"
* });
*/
write(
path: string,
data:
| string
| ArrayBufferView
| ArrayBuffer
| SharedArrayBuffer
| Request
| Response
| BunFile
| S3File
| Blob
| File,
options?: S3Options,
): Promise<number>;
/**
* Generate a presigned URL for temporary access to a file.
* Useful for generating upload/download URLs without exposing credentials.
*
* @example
* // Download URL
* const downloadUrl = bucket.presign("file.pdf", {
* expiresIn: 3600 // 1 hour
* });
*
* // Upload URL
* const uploadUrl = bucket.presign("uploads/image.jpg", {
* method: "PUT",
* expiresIn: 3600,
* type: "image/jpeg",
* acl: "public-read"
* });
*
* // Long-lived public URL
* const publicUrl = bucket.presign("public/doc.pdf", {
* expiresIn: 7 * 24 * 60 * 60, // 7 days
* acl: "public-read"
* });
*/
presign(path: string, options?: S3FilePresignOptions): string;
/**
* Delete a file from the bucket.
*
* @example
* // Simple delete
* await bucket.unlink("old-file.txt");
*
* // With error handling
* try {
* await bucket.unlink("file.dat");
* console.log("File deleted");
* } catch (err) {
* console.error("Delete failed:", err);
* }
*/
unlink(path: string, options?: S3Options): Promise<void>;
delete: S3Client["unlink"];
/**
* Get the size of a file in bytes.
* Uses HEAD request to efficiently get size.
*
* @example
* // Get size
* const bytes = await bucket.size("video.mp4");
* console.log(`Size: ${bytes} bytes`);
*
* // Check if file is large
* if (await bucket.size("data.zip") > 100 * 1024 * 1024) {
* console.log("File is larger than 100MB");
* }
*/
size(path: string, options?: S3Options): Promise<number>;
/**
* Check if a file exists in the bucket.
* Uses HEAD request to check existence.
*
* @example
* // Check existence
* if (await bucket.exists("config.json")) {
* const file = bucket.file("config.json");
* const config = await file.json();
* }
*
* // With error handling
* try {
* if (!await bucket.exists("required.txt")) {
* throw new Error("Required file missing");
* }
* } catch (err) {
* console.error("Check failed:", err);
* }
*/
exists(path: string, options?: S3Options): Promise<boolean>;
/**
* Get the stat of a file in an S3-compatible storage service.
*
* @param path The path to the file.
* @param options The options to use for the S3 client.
*/
stat(path: string, options?: S3Options): Promise<S3Stats>;
}
/**
* A default instance of S3Client
*
* Pulls credentials from environment variables. Use `new Bun.S3Client()` if you need to explicitly set credentials.
*
* @category Cloud Storage
*/
var s3: S3Client;
}

View File

@@ -58,8 +58,6 @@ declare module "bun:sqlite" {
* ```ts
* const db = new Database("mydb.sqlite", {readonly: true});
* ```
*
* @category Database
*/
constructor(
filename?: string,
@@ -569,8 +567,6 @@ declare module "bun:sqlite" {
*
* This is returned by {@link Database.prepare} and {@link Database.query}.
*
* @category Database
*
* @example
* ```ts
* const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?");

View File

@@ -16,8 +16,6 @@
declare module "bun:test" {
/**
* -- Mocks --
*
* @category Testing
*/
export type Mock<T extends (...args: any[]) => any> = JestMock.Mock<T>;
@@ -151,10 +149,6 @@ declare module "bun:test" {
methodOrPropertyValue: K,
): Mock<T[K] extends (...args: any[]) => any ? T[K] : never>;
interface FunctionLike {
readonly name: string;
}
/**
* Describes a group of related tests.
*
@@ -170,9 +164,11 @@ declare module "bun:test" {
*
* @param label the label for the tests
* @param fn the function that defines the tests
*
* @category Testing
*/
interface FunctionLike {
readonly name: string;
}
export interface Describe {
(fn: () => void): void;
@@ -356,8 +352,6 @@ declare module "bun:test" {
* @param label the label for the test
* @param fn the test function
* @param options the test timeout or options
*
* @category Testing
*/
export interface Test {
(
@@ -426,6 +420,7 @@ declare module "bun:test" {
*
* @param label the label for the test
* @param fn the test function
* @param options the test timeout or options
*/
failing(label: string, fn?: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void)): void;
/**
@@ -1783,6 +1778,10 @@ declare module "bun:test" {
type MatcherContext = MatcherUtils & MatcherState;
}
declare module "test" {
export type * from "bun:test";
}
declare namespace JestMock {
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.

View File

@@ -1,4 +1,4 @@
import { expectType } from "./utilities";
import { expectType } from "./utilities.test";
async function* listReleases() {
for (let page = 1; ; page++) {

View File

@@ -2,7 +2,8 @@ const channel = new BroadcastChannel("my-channel");
const message = { hello: "world" };
channel.onmessage = event => {
console.log(event);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
console.log((event as any).data); // { hello: "world" }
};
channel.postMessage(message);

View File

@@ -1,5 +1,5 @@
import type { BunFile, BunPlugin, FileBlob } from "bun";
import * as tsd from "./utilities";
import { BunFile, BunPlugin, FileBlob } from "bun";
import * as tsd from "./utilities.test";
{
const _plugin: BunPlugin = {
name: "asdf",
@@ -7,7 +7,6 @@ import * as tsd from "./utilities";
};
_plugin;
}
{
// tslint:disable-next-line:no-void-expression
const arg = Bun.plugin({

View File

@@ -1,20 +1,21 @@
import { expectType } from "./utilities";
import { expectType } from "./utilities.test";
declare module "bun" {
interface Env {
FOO: "FOO";
}
}
expectType<"FOO">(Bun.env.FOO);
expectType<"FOO">(process.env.FOO);
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace NodeJS {
interface ProcessEnv {
BAR: "BAR";
}
}
}
expectType<"BAR">(process.env.BAR);
process.env.FOO;

View File

@@ -1,5 +1,5 @@
import { EventEmitter } from "events";
import { expectType } from "./utilities";
import { expectType } from "./utilities.test";
// eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
// EventEmitter<

View File

@@ -1,5 +1,5 @@
import { dlopen, FFIType, JSCallback, read, suffix, type CString, type Pointer } from "bun:ffi";
import * as tsd from "./utilities";
import { CString, dlopen, FFIType, JSCallback, Pointer, read, suffix } from "bun:ffi";
import * as tsd from "./utilities.test";
// `suffix` is either "dylib", "so", or "dll" depending on the platform
// you don't have to use "suffix", it's just there for convenience

View File

@@ -4,7 +4,7 @@ constants.O_APPEND;
import * as fs from "fs";
import { exists } from "fs/promises";
import * as tsd from "./utilities";
import * as tsd from "./utilities.test";
tsd.expectType<Promise<boolean>>(exists("/etc/passwd"));
tsd.expectType<Promise<boolean>>(fs.promises.exists("/etc/passwd"));

View File

@@ -1,5 +1,5 @@
import { FileSystemRouter } from "bun";
import { expectType } from "./utilities";
import { expectType } from "./utilities.test";
const router = new FileSystemRouter({
dir: "/pages",

View File

@@ -1,6 +1,7 @@
import { ZlibCompressionOptions } from "bun";
import * as fs from "fs";
import * as fsPromises from "fs/promises";
import { expectAssignable, expectType } from "./utilities";
import { expectAssignable, expectType } from "./utilities.test";
// FileBlob
expectType<ReadableStream<Uint8Array>>(Bun.file("index.test-d.ts").stream());
@@ -35,7 +36,7 @@ expectType<Uint8Array>(
expectType<Uint8Array>(Bun.gzipSync(new Uint8Array(128), { level: 9, memLevel: 6, windowBits: 27 }));
expectType<Uint8Array>(Bun.inflateSync(new Uint8Array(64))); // Pretend this is DEFLATE compressed data
expectType<Uint8Array>(Bun.gunzipSync(new Uint8Array(64))); // Pretend this is GZIP compressed data
expectAssignable<Bun.ZlibCompressionOptions>({ windowBits: -11 });
expectAssignable<ZlibCompressionOptions>({ windowBits: -11 });
// Other
expectType<Promise<number>>(Bun.write("test.json", "lol"));
@@ -46,8 +47,14 @@ expectType<string>(Bun.fileURLToPath(new URL("file:///foo/bar.txt")));
// Testing ../fs.d.ts
expectType<string>(fs.readFileSync("./index.d.ts", { encoding: "utf-8" }).toString());
expectType<boolean>(fs.existsSync("./index.d.ts"));
// tslint:disable-next-line:no-void-expression
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
expectType<void>(fs.accessSync("./index.d.ts"));
// tslint:disable-next-line:no-void-expression
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
expectType<void>(fs.appendFileSync("./index.d.ts", "test"));
// tslint:disable-next-line:no-void-expression
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
expectType<void>(fs.mkdirSync("./index.d.ts"));
// Testing ^promises.d.ts
@@ -105,36 +112,38 @@ CountQueuingStrategy;
TextEncoder;
TextDecoder;
ReadableStreamDefaultReader;
ReadableStreamBYOBReader;
// ReadableStreamBYOBReader;
ReadableStreamDefaultController;
ReadableByteStreamController;
// ReadableByteStreamController;
WritableStreamDefaultWriter;
declare function stuff(arg: Blob): any;
declare function stuff(arg: WebSocket): any;
declare function stuff(arg: Request): any;
declare function stuff(arg: Response): any;
declare function stuff(arg: Headers): any;
declare function stuff(arg: FormData): any;
declare function stuff(arg: URL): any;
declare function stuff(arg: URLSearchParams): any;
declare function stuff(arg: ReadableStream): any;
declare function stuff(arg: WritableStream): any;
declare function stuff(arg: TransformStream): any;
declare function stuff(arg: ByteLengthQueuingStrategy): any;
declare function stuff(arg: CountQueuingStrategy): any;
declare function stuff(arg: TextEncoder): any;
declare function stuff(arg: TextDecoder): any;
declare function stuff(arg: ReadableStreamDefaultReader): any;
declare function stuff(arg: ReadableStreamDefaultController): any;
declare function stuff(arg: WritableStreamDefaultWriter): any;
function stuff(arg: Blob): any;
function stuff(arg: WebSocket): any;
function stuff(arg: Request): any;
function stuff(arg: Response): any;
function stuff(arg: Headers): any;
function stuff(arg: FormData): any;
function stuff(arg: URL): any;
function stuff(arg: URLSearchParams): any;
function stuff(arg: ReadableStream): any;
function stuff(arg: WritableStream): any;
function stuff(arg: TransformStream): any;
function stuff(arg: ByteLengthQueuingStrategy): any;
function stuff(arg: CountQueuingStrategy): any;
function stuff(arg: TextEncoder): any;
function stuff(arg: TextDecoder): any;
function stuff(arg: ReadableStreamDefaultReader): any;
function stuff(arg: ReadableStreamDefaultController): any;
function stuff(arg: WritableStreamDefaultWriter): any;
function stuff(arg: any) {
return "asfd";
}
stuff("asdf" as any as Blob);
new ReadableStream();
new WritableStream();
new Worker("asdfasdf");
new Worker("asdfasdf").onmessage;
new File([{} as Blob], "asdf");
new Crypto();
new ShadowRealm();
@@ -220,19 +229,6 @@ const writableStream = new WritableStream();
{
const a = new FormData();
a.delete("asdf");
a.get("asdf");
a.append("asdf", "asdf");
a.set("asdf", "asdf");
a.forEach((value, key) => {
console.log(value, key);
});
a.entries();
a.get("asdf");
a.getAll("asdf");
a.has("asdf");
a.keys();
a.values();
a.toString();
}
{
const a = new Headers();
@@ -264,9 +260,8 @@ const writableStream = new WritableStream();
a.href;
}
{
new URLSearchParams();
new URLSearchParams("");
new URLSearchParams([]);
const a = new URLSearchParams();
a;
}
{
const a = new TextDecoder();
@@ -283,7 +278,6 @@ const writableStream = new WritableStream();
{
const a = new MessageChannel();
a.port1;
new MessageChannel().port1.addEventListener("message", console.log);
}
{
const a = new MessagePort();
@@ -302,10 +296,6 @@ const writableStream = new WritableStream();
{
const ws = new WebSocket("ws://www.host.com/path");
ws.send("asdf");
new WebSocket("url", {
headers: { "Authorization": "my key" },
});
}
atob("asf");

View File

@@ -32,10 +32,4 @@ for (const q of sp) {
console.log(q);
}
fetch("https://example.com", {
s3: {
accessKeyId: "123",
secretAccessKey: "456",
},
proxy: "cool",
});
fetch;

View File

@@ -0,0 +1,2 @@
Bun.spawn(["echo", '"hi"']);
performance;

View File

@@ -1,5 +1,5 @@
import { jest, mock } from "bun:test";
import { expectType } from "./utilities";
import { expectType } from "./utilities.test";
const mock1 = mock((arg: string) => {
return arg.length;

View File

@@ -5,7 +5,6 @@ const rl = readline.createInterface({
output: process.stdout,
terminal: true,
});
await rl.question("What is your age?\n").then(answer => {
console.log("Your age is: " + answer);
});

View File

@@ -0,0 +1,178 @@
Bun.serve({
fetch(req) {
console.log(req.url); // => http://localhost:3000/
return new Response("Hello World");
},
});
Bun.serve({
fetch(req) {
console.log(req.url); // => http://localhost:3000/
return new Response("Hello World");
},
keyFile: "ca.pem",
certFile: "cert.pem",
});
Bun.serve({
websocket: {
message(ws, message) {
ws.send(message);
},
},
fetch(req, server) {
// Upgrade to a ServerWebSocket if we can
// This automatically checks for the `Sec-WebSocket-Key` header
// meaning you don't have to check headers, you can just call `upgrade()`
if (server.upgrade(req)) {
// When upgrading, we return undefined since we don't want to send a Response
return;
}
return new Response("Regular HTTP response");
},
});
Bun.serve<{
name: string;
}>({
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === "/chat") {
if (
server.upgrade(req, {
data: {
name: new URL(req.url).searchParams.get("name") || "Friend",
},
headers: {
"Set-Cookie": "name=" + new URL(req.url).searchParams.get("name"),
},
})
) {
return;
}
}
return new Response("Expected a websocket connection", { status: 400 });
},
websocket: {
open(ws) {
console.log("WebSocket opened");
ws.subscribe("the-group-chat");
},
message(ws, message) {
ws.publish("the-group-chat", `${ws.data.name}: ${message.toString()}`);
},
close(ws, code, reason) {
ws.publish("the-group-chat", `${ws.data.name} left the chat`);
},
drain(ws) {
console.log("Please send me data. I am ready to receive it.");
},
perMessageDeflate: true,
},
});
Bun.serve({
fetch(req) {
throw new Error("woops!");
},
error(error) {
return new Response(`<pre>${error.message}\n${error.stack}</pre>`, {
headers: {
"Content-Type": "text/html",
},
});
},
});
export {};
Bun.serve({
port: 1234,
fetch(req, server) {
server.upgrade(req);
if (Math.random() > 0.5) return undefined;
return new Response();
},
websocket: { message() {} },
});
Bun.serve({
unix: "/tmp/bun.sock",
fetch() {
return new Response();
},
});
Bun.serve({
unix: "/tmp/bun.sock",
fetch(req, server) {
server.upgrade(req);
if (Math.random() > 0.5) return undefined;
return new Response();
},
websocket: { message() {} },
});
Bun.serve({
unix: "/tmp/bun.sock",
fetch() {
return new Response();
},
tls: {},
});
Bun.serve({
unix: "/tmp/bun.sock",
fetch(req, server) {
server.upgrade(req);
if (Math.random() > 0.5) return undefined;
return new Response();
},
websocket: { message() {} },
tls: {},
});
Bun.serve({
fetch(req, server) {
server.upgrade(req);
},
websocket: {
open(ws) {
console.log("WebSocket opened");
ws.subscribe("test-channel");
},
message(ws, message) {
ws.publish("test-channel", `${message.toString()}`);
},
perMessageDeflate: true,
},
});
// Bun.serve({
// unix: "/tmp/bun.sock",
// // @ts-expect-error
// port: 1234,
// fetch() {
// return new Response();
// },
// });
// Bun.serve({
// unix: "/tmp/bun.sock",
// // @ts-expect-error
// port: 1234,
// fetch(req, server) {
// server.upgrade(req);
// if (Math.random() > 0.5) return undefined;
// return new Response();
// },
// websocket: { message() {} },
// });

View File

@@ -1,12 +1,5 @@
import type {
FileSink,
NullSubprocess,
PipedSubprocess,
ReadableSubprocess,
SyncSubprocess,
WritableSubprocess,
} from "bun";
import * as tsd from "./utilities";
import { FileSink, NullSubprocess, PipedSubprocess, ReadableSubprocess, SyncSubprocess, WritableSubprocess } from "bun";
import * as tsd from "./utilities.test";
Bun.spawn(["echo", "hello"]);

View File

@@ -1,5 +1,5 @@
import { type Changes, Database } from "bun:sqlite";
import { expectType } from "./utilities";
import { Changes, Database } from "bun:sqlite";
import { expectType } from "./utilities.test";
const db = new Database(":memory:");
const query1 = db.query<

View File

@@ -0,0 +1,23 @@
new ReadableStream({
start(controller) {
controller.enqueue("hello");
controller.enqueue("world");
controller.close();
},
});
// this will have type errors when lib.dom.d.ts is present
// afaik this isn't fixable
new ReadableStream({
type: "direct",
pull(controller) {
// eslint-disable-next-line
controller.write("hello");
// eslint-disable-next-line
controller.write("world");
controller.close();
},
cancel() {
// called if stream.cancel() is called
},
});

View File

@@ -1,5 +1,5 @@
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { expectType } from "./utilities";
import { expectType } from "./utilities.test";
const spy = spyOn(console, "log");
expectType<any[][]>(spy.mock.calls);
@@ -93,8 +93,8 @@ const data = [
["a", true, 5],
["b", false, "asdf"],
];
test.each(data)("test.each", arg => {
expectType<string | number | boolean>(arg);
test.each(data)("test.each", (...args) => {
expectType<string | number | boolean>(args[0]);
});
describe.each(data)("test.each", (a, b, c) => {
expectType<string | number | boolean>(a);

View File

@@ -1,4 +1,4 @@
import data from "./bunfig.toml";
import { expectType } from "./utilities";
import { expectType } from "./utilities.test";
expectType<any>(data);

View File

@@ -0,0 +1,8 @@
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectType: <T>(expression: T) => void;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectAssignable: <T>(expression: T) => void;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectNotAssignable: <T>(expression: any) => void;
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
export declare const expectTypeEquals: <T, S>(expression: T extends S ? (S extends T ? true : false) : false) => void;

View File

@@ -1,5 +1,5 @@
import { Worker as NodeWorker } from "node:worker_threads";
import * as tsd from "./utilities";
import * as tsd from "./utilities.test";
const webWorker = new Worker("./worker.js");
@@ -18,7 +18,6 @@ webWorker.postMessage("asdf", []);
webWorker.terminate();
webWorker.addEventListener("close", () => {});
webWorker.removeEventListener("sadf", () => {});
// these methods don't exist if lib.dom.d.ts is present
webWorker.ref();
webWorker.unref();

View File

@@ -1,12 +1,12 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"skipLibCheck": true,
"declaration": true,
"emitDeclarationOnly": true,
"noEmit": false,
"declarationDir": "out"
},
"include": ["**/*.ts"],
"exclude": ["dist", "node_modules"]
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"skipLibCheck": true,
"declaration": true,
"emitDeclarationOnly": true,
"noEmit": false,
"declarationDir": "out"
},
"include": ["**/*.ts"],
"exclude": ["dist", "node_modules"]
}

View File

@@ -1,193 +1,270 @@
declare module "bun" {
namespace WebAssembly {
type ImportExportKind = "function" | "global" | "memory" | "table";
type TableKind = "anyfunc" | "externref";
type ExportValue = Function | Global | WebAssembly.Memory | WebAssembly.Table;
type Exports = Record<string, ExportValue>;
type ImportValue = ExportValue | number;
type Imports = Record<string, ModuleImports>;
type ModuleImports = Record<string, ImportValue>;
export {};
interface ValueTypeMap {
anyfunc: Function;
externref: any;
f32: number;
f64: number;
i32: number;
i64: bigint;
v128: never;
}
type _Global<T extends Bun.WebAssembly.ValueType = Bun.WebAssembly.ValueType> = typeof globalThis extends {
onerror: any;
WebAssembly: { Global: infer T };
}
? T
: Bun.WebAssembly.Global<T>;
type ValueType = keyof ValueTypeMap;
type _CompileError = typeof globalThis extends {
onerror: any;
WebAssembly: { CompileError: infer T };
}
? T
: Bun.WebAssembly.CompileError;
interface GlobalDescriptor<T extends ValueType = ValueType> {
mutable?: boolean;
value: T;
}
type _LinkError = typeof globalThis extends {
onerror: any;
WebAssembly: { LinkError: infer T };
}
? T
: Bun.WebAssembly.LinkError;
interface Global<T extends ValueType = ValueType> {
// <T extends ValueType = ValueType> {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/value) */
value: ValueTypeMap[T];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/valueOf) */
valueOf(): ValueTypeMap[T];
}
type _RuntimeError = typeof globalThis extends {
onerror: any;
WebAssembly: { RuntimeError: infer T };
}
? T
: Bun.WebAssembly.RuntimeError;
interface CompileError extends Error {}
type _Memory = typeof globalThis extends {
onerror: any;
WebAssembly: { Memory: infer T };
}
? T
: Bun.WebAssembly.Memory;
interface LinkError extends Error {}
type _Instance = typeof globalThis extends {
onerror: any;
WebAssembly: { Instance: infer T };
}
? T
: Bun.WebAssembly.Instance;
interface RuntimeError extends Error {}
type _Module = typeof globalThis extends {
onerror: any;
WebAssembly: { Module: infer T };
}
? T
: Bun.WebAssembly.Module;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance) */
interface Instance {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports) */
readonly exports: Exports;
}
type _Table = typeof globalThis extends {
onerror: any;
WebAssembly: { Table: infer T };
}
? T
: Bun.WebAssembly.Table;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) */
interface Memory {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/buffer) */
readonly buffer: ArrayBuffer;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/grow) */
grow(delta: number): number;
}
declare global {
namespace Bun {
namespace WebAssembly {
type ImportExportKind = "function" | "global" | "memory" | "table";
type TableKind = "anyfunc" | "externref";
// eslint-disable-next-line @typescript-eslint/ban-types
type ExportValue = Function | Global | WebAssembly.Memory | WebAssembly.Table;
type Exports = Record<string, ExportValue>;
type ImportValue = ExportValue | number;
type Imports = Record<string, ModuleImports>;
type ModuleImports = Record<string, ImportValue>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) */
interface Module {}
interface ValueTypeMap {
// eslint-disable-next-line @typescript-eslint/ban-types
anyfunc: Function;
externref: any;
f32: number;
f64: number;
i32: number;
i64: bigint;
v128: never;
}
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table) */
interface Table {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/length) */
readonly length: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/get) */
get(index: number): any;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/grow) */
grow(delta: number, value?: any): number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/set) */
set(index: number, value?: any): void;
}
type ValueType = keyof ValueTypeMap;
interface MemoryDescriptor {
initial: number;
maximum?: number;
shared?: boolean;
}
interface GlobalDescriptor<T extends ValueType = ValueType> {
mutable?: boolean;
value: T;
}
interface ModuleExportDescriptor {
kind: ImportExportKind;
name: string;
}
interface Global<T extends ValueType = ValueType> {
// <T extends ValueType = ValueType> {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/value) */
value: ValueTypeMap[T];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/valueOf) */
valueOf(): ValueTypeMap[T];
}
interface ModuleImportDescriptor {
kind: ImportExportKind;
module: string;
name: string;
}
interface CompileError extends Error {}
interface TableDescriptor {
element: TableKind;
initial: number;
maximum?: number;
}
interface LinkError extends Error {}
interface WebAssemblyInstantiatedSource {
instance: Instance;
module: Module;
interface RuntimeError extends Error {}
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance) */
interface Instance {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports) */
readonly exports: Exports;
}
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) */
interface Memory {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/buffer) */
readonly buffer: ArrayBuffer;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory/grow) */
grow(delta: number): number;
}
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) */
interface Module {}
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table) */
interface Table {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/length) */
readonly length: number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/get) */
get(index: number): any;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/grow) */
grow(delta: number, value?: any): number;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Table/set) */
set(index: number, value?: any): void;
}
interface MemoryDescriptor {
initial: number;
maximum?: number;
shared?: boolean;
}
interface ModuleExportDescriptor {
kind: ImportExportKind;
name: string;
}
interface ModuleImportDescriptor {
kind: ImportExportKind;
module: string;
name: string;
}
interface TableDescriptor {
element: TableKind;
initial: number;
maximum?: number;
}
interface WebAssemblyInstantiatedSource {
instance: Instance;
module: Module;
}
}
}
}
declare namespace WebAssembly {
interface ValueTypeMap extends Bun.WebAssembly.ValueTypeMap {}
interface GlobalDescriptor<T extends keyof ValueTypeMap = keyof ValueTypeMap>
extends Bun.WebAssembly.GlobalDescriptor<T> {}
interface MemoryDescriptor extends Bun.WebAssembly.MemoryDescriptor {}
interface ModuleExportDescriptor extends Bun.WebAssembly.ModuleExportDescriptor {}
interface ModuleImportDescriptor extends Bun.WebAssembly.ModuleImportDescriptor {}
interface TableDescriptor extends Bun.WebAssembly.TableDescriptor {}
interface WebAssemblyInstantiatedSource extends Bun.WebAssembly.WebAssemblyInstantiatedSource {}
namespace WebAssembly {
interface ValueTypeMap extends Bun.WebAssembly.ValueTypeMap {}
interface GlobalDescriptor<T extends keyof ValueTypeMap = keyof ValueTypeMap>
extends Bun.WebAssembly.GlobalDescriptor<T> {}
interface MemoryDescriptor extends Bun.WebAssembly.MemoryDescriptor {}
interface ModuleExportDescriptor extends Bun.WebAssembly.ModuleExportDescriptor {}
interface ModuleImportDescriptor extends Bun.WebAssembly.ModuleImportDescriptor {}
interface TableDescriptor extends Bun.WebAssembly.TableDescriptor {}
interface WebAssemblyInstantiatedSource extends Bun.WebAssembly.WebAssemblyInstantiatedSource {}
interface LinkError extends Bun.WebAssembly.LinkError {}
var LinkError: {
prototype: LinkError;
new (message?: string): LinkError;
(message?: string): LinkError;
};
interface LinkError extends _LinkError {}
var LinkError: {
prototype: LinkError;
new (message?: string): LinkError;
(message?: string): LinkError;
};
interface CompileError extends Bun.WebAssembly.CompileError {}
var CompileError: {
prototype: CompileError;
new (message?: string): CompileError;
(message?: string): CompileError;
};
interface RuntimeError extends Bun.WebAssembly.RuntimeError {}
var RuntimeError: {
prototype: RuntimeError;
new (message?: string): RuntimeError;
(message?: string): RuntimeError;
};
interface Global<T extends keyof ValueTypeMap = keyof ValueTypeMap> extends Bun.WebAssembly.Global<T> {}
var Global: {
prototype: Global;
new <T extends Bun.WebAssembly.ValueType = Bun.WebAssembly.ValueType>(
descriptor: GlobalDescriptor<T>,
v?: ValueTypeMap[T],
): Global<T>;
};
interface Instance extends Bun.WebAssembly.Instance {}
var Instance: {
prototype: Instance;
new (module: Module, importObject?: Bun.WebAssembly.Imports): Instance;
};
interface Memory extends Bun.WebAssembly.Memory {}
var Memory: {
prototype: Memory;
new (descriptor: MemoryDescriptor): Memory;
};
interface Module extends Bun.WebAssembly.Module {}
var Module: Bun.__internal.UseLibDomIfAvailable<
"WebAssembly",
{
Module: {
prototype: Module;
new (bytes: Bun.BufferSource): Module;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/customSections) */
customSections(moduleObject: Module, sectionName: string): ArrayBuffer[];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/exports) */
exports(moduleObject: Module): ModuleExportDescriptor[];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/imports) */
imports(moduleObject: Module): ModuleImportDescriptor[];
};
interface CompileError extends _CompileError {}
var CompileError: typeof globalThis extends {
onerror: any;
WebAssembly: { CompileError: infer T };
}
>["Module"];
? T
: {
prototype: CompileError;
new (message?: string): CompileError;
(message?: string): CompileError;
};
interface Table extends Bun.WebAssembly.Table {}
var Table: {
prototype: Table;
new (descriptor: TableDescriptor, value?: any): Table;
};
interface RuntimeError extends _RuntimeError {}
var RuntimeError: {
prototype: RuntimeError;
new (message?: string): RuntimeError;
(message?: string): RuntimeError;
};
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile) */
function compile(bytes: Bun.BufferSource): Promise<Module>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming) */
function compileStreaming(source: Response | PromiseLike<Response>): Promise<Module>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) */
function instantiate(
bytes: Bun.BufferSource,
importObject?: Bun.WebAssembly.Imports,
): Promise<WebAssemblyInstantiatedSource>;
function instantiate(moduleObject: Module, importObject?: Bun.WebAssembly.Imports): Promise<Instance>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming) */
function instantiateStreaming(
source: Response | PromiseLike<Response>,
importObject?: Bun.WebAssembly.Imports,
): Promise<WebAssemblyInstantiatedSource>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate) */
function validate(bytes: Bun.BufferSource): boolean;
interface Global<T extends keyof ValueTypeMap = keyof ValueTypeMap> extends _Global<T> {}
var Global: typeof globalThis extends {
onerror: any;
WebAssembly: { Global: infer T };
}
? T
: {
prototype: Global;
new <T extends Bun.WebAssembly.ValueType = Bun.WebAssembly.ValueType>(
descriptor: GlobalDescriptor<T>,
v?: ValueTypeMap[T],
): Global<T>;
};
interface Instance extends _Instance {}
var Instance: typeof globalThis extends {
onerror: any;
WebAssembly: { Instance: infer T };
}
? T
: {
prototype: Instance;
new (module: Module, importObject?: Bun.WebAssembly.Imports): Instance;
};
interface Memory extends _Memory {}
var Memory: {
prototype: Memory;
new (descriptor: MemoryDescriptor): Memory;
};
interface Module extends _Module {}
var Module: typeof globalThis extends {
onerror: any;
WebAssembly: { Module: infer T };
}
? T
: {
prototype: Module;
new (bytes: Bun.BufferSource): Module;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/customSections) */
customSections(moduleObject: Module, sectionName: string): ArrayBuffer[];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/exports) */
exports(moduleObject: Module): ModuleExportDescriptor[];
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/imports) */
imports(moduleObject: Module): ModuleImportDescriptor[];
};
interface Table extends _Table {}
var Table: {
prototype: Table;
new (descriptor: TableDescriptor, value?: any): Table;
};
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compile) */
function compile(bytes: Bun.BufferSource): Promise<Module>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming) */
function compileStreaming(source: Response | PromiseLike<Response>): Promise<Module>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate) */
function instantiate(
bytes: Bun.BufferSource,
importObject?: Bun.WebAssembly.Imports,
): Promise<WebAssemblyInstantiatedSource>;
function instantiate(moduleObject: Module, importObject?: Bun.WebAssembly.Imports): Promise<Instance>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming) */
function instantiateStreaming(
source: Response | PromiseLike<Response>,
importObject?: Bun.WebAssembly.Imports,
): Promise<WebAssemblyInstantiatedSource>;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/validate) */
function validate(bytes: Bun.BufferSource): boolean;
}
}

View File

@@ -353,21 +353,15 @@ int kqueue_change(int kqfd, int fd, int old_events, int new_events, void *user_d
int change_length = 0;
/* Do they differ in readable? */
int is_readable = (new_events & LIBUS_SOCKET_READABLE);
int is_writable = (new_events & LIBUS_SOCKET_WRITABLE);
if ((new_events & LIBUS_SOCKET_READABLE) != (old_events & LIBUS_SOCKET_READABLE)) {
EV_SET64(&change_list[change_length++], fd, EVFILT_READ, is_readable ? EV_ADD : EV_DELETE, 0, 0, (uint64_t)(void*)user_data, 0, 0);
EV_SET64(&change_list[change_length++], fd, EVFILT_READ, (new_events & LIBUS_SOCKET_READABLE) ? EV_ADD : EV_DELETE, 0, 0, (uint64_t)(void*)user_data, 0, 0);
}
if(!is_readable && !is_writable) {
if(!(old_events & LIBUS_SOCKET_WRITABLE)) {
// if we are not reading or writing, we need to add writable to receive FIN
EV_SET64(&change_list[change_length++], fd, EVFILT_WRITE, EV_ADD, 0, 0, (uint64_t)(void*)user_data, 0, 0);
}
} else if ((new_events & LIBUS_SOCKET_WRITABLE) != (old_events & LIBUS_SOCKET_WRITABLE)) {
/* Do they differ in writable? */
/* Do they differ in writable? */
if ((new_events & LIBUS_SOCKET_WRITABLE) != (old_events & LIBUS_SOCKET_WRITABLE)) {
EV_SET64(&change_list[change_length++], fd, EVFILT_WRITE, (new_events & LIBUS_SOCKET_WRITABLE) ? EV_ADD : EV_DELETE, 0, 0, (uint64_t)(void*)user_data, 0, 0);
}
}
int ret;
do {
ret = kevent64(kqfd, change_list, change_length, change_list, change_length, KEVENT_FLAG_ERROR_EVENTS, NULL);
@@ -405,10 +399,6 @@ int us_poll_start_rc(struct us_poll_t *p, struct us_loop_t *loop, int events) {
#ifdef LIBUS_USE_EPOLL
struct epoll_event event;
if(!(events & LIBUS_SOCKET_READABLE) && !(events & LIBUS_SOCKET_WRITABLE)) {
// if we are disabling readable, we need to add the other events to detect EOF/HUP/ERR
events |= EPOLLRDHUP | EPOLLHUP | EPOLLERR;
}
event.events = events;
event.data.ptr = p;
int ret;
@@ -433,10 +423,6 @@ void us_poll_change(struct us_poll_t *p, struct us_loop_t *loop, int events) {
#ifdef LIBUS_USE_EPOLL
struct epoll_event event;
if(!(events & LIBUS_SOCKET_READABLE) && !(events & LIBUS_SOCKET_WRITABLE)) {
// if we are disabling readable, we need to add the other events to detect EOF/HUP/ERR
events |= EPOLLRDHUP | EPOLLHUP | EPOLLERR;
}
event.events = events;
event.data.ptr = p;
int rc;

View File

@@ -104,6 +104,7 @@ void us_poll_change(struct us_poll_t *p, struct us_loop_t *loop, int events) {
us_internal_poll_type(p) |
((events & LIBUS_SOCKET_READABLE) ? POLL_TYPE_POLLING_IN : 0) |
((events & LIBUS_SOCKET_WRITABLE) ? POLL_TYPE_POLLING_OUT : 0);
uv_poll_start(p->uv_p, events, poll_cb);
}
}

View File

@@ -472,7 +472,6 @@ int us_socket_raw_write(int ssl, us_socket_r s, const char *data, int length, in
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, us_socket_r s, const char **dest, int *port, int *is_ipv6);
unsigned int us_get_local_address_info(char *buf, us_socket_r s, const char **dest, int *port, int *is_ipv6);
int us_socket_get_error(int ssl, us_socket_r s);
void us_socket_ref(us_socket_r s);

View File

@@ -213,21 +213,21 @@ void us_internal_free_closed_sockets(struct us_loop_t *loop) {
us_poll_free((struct us_poll_t *) s, loop);
s = next;
}
loop->data.closed_head = NULL;
loop->data.closed_head = 0;
for (struct us_udp_socket_t *s = loop->data.closed_udp_head; s; ) {
struct us_udp_socket_t *next = s->next;
us_poll_free((struct us_poll_t *) s, loop);
s = next;
}
loop->data.closed_udp_head = NULL;
loop->data.closed_udp_head = 0;
for (struct us_connecting_socket_t *s = loop->data.closed_connecting_head; s; ) {
struct us_connecting_socket_t *next = s->next;
us_free(s);
s = next;
}
loop->data.closed_connecting_head = NULL;
loop->data.closed_connecting_head = 0;
}
void us_internal_free_closed_contexts(struct us_loop_t *loop) {
@@ -236,7 +236,7 @@ void us_internal_free_closed_contexts(struct us_loop_t *loop) {
us_free(ctx);
ctx = next;
}
loop->data.closed_context_head = NULL;
loop->data.closed_context_head = 0;
}
void sweep_timer_cb(struct us_internal_callback_t *cb) {

View File

@@ -501,24 +501,6 @@ unsigned int us_get_remote_address_info(char *buf, struct us_socket_t *s, const
return length;
}
unsigned int us_get_local_address_info(char *buf, struct us_socket_t *s, const char **dest, int *port, int *is_ipv6)
{
struct bsd_addr_t addr;
if (bsd_local_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;
}
void us_socket_ref(struct us_socket_t *s) {
#ifdef LIBUS_USE_LIBUV
uv_ref((uv_handle_t*)s->p.uv_p);
@@ -558,6 +540,11 @@ struct us_loop_t *us_connecting_socket_get_loop(struct us_connecting_socket_t *c
void us_socket_pause(int ssl, struct us_socket_t *s) {
// closed cannot be paused because it is already closed
if(us_socket_is_closed(ssl, s)) return;
if(us_socket_is_shut_down(ssl, s)) {
// we already sent FIN so we pause all events because we are read-only
us_poll_change(&s->p, s->context->loop, 0);
return;
}
// we are readable and writable so we can just pause readable side
us_poll_change(&s->p, s->context->loop, LIBUS_SOCKET_WRITABLE);
}

View File

@@ -131,7 +131,7 @@ public:
getLoopData()->setCorkedSocket(this, SSL);
}
/* Returns whether we are corked */
/* Returns wheter we are corked or not */
bool isCorked() {
return getLoopData()->isCorkedWith(this);
}
@@ -182,9 +182,9 @@ public:
}
/* Returns the user space backpressure. */
size_t getBufferedAmount() {
unsigned int getBufferedAmount() {
/* We return the actual amount of bytes in backbuffer, including pendingRemoval */
return getAsyncSocketData()->buffer.totalLength();
return (unsigned int) getAsyncSocketData()->buffer.totalLength();
}
/* Returns the text representation of an IPv4 or IPv6 address */
@@ -222,63 +222,6 @@ public:
return addressAsText(getRemoteAddress());
}
/**
* Flushes the socket buffer by writing as much data as possible to the underlying socket.
*
* @return The total number of bytes successfully written to the socket
*/
size_t flush() {
/* Check if socket is valid for operations */
if (us_socket_is_closed(SSL, (us_socket_t *) this)) {
/* Socket is closed, no flushing is possible */
return 0;
}
/* Get the associated asynchronous socket data structure */
AsyncSocketData<SSL> *asyncSocketData = getAsyncSocketData();
size_t total_written = 0;
/* Continue flushing as long as we have data in the buffer */
while (asyncSocketData->buffer.length()) {
/* Get current buffer size */
size_t buffer_len = asyncSocketData->buffer.length();
/* Limit write size to INT_MAX as the underlying socket API uses int for length */
int max_flush_len = std::min(buffer_len, (size_t)INT_MAX);
/* Attempt to write data to the socket */
int written = us_socket_write(SSL, (us_socket_t *) this, asyncSocketData->buffer.data(), max_flush_len, 0);
total_written += written;
/* Check if we couldn't write the entire buffer */
if ((unsigned int) written < buffer_len) {
/* Remove the successfully written data from the buffer */
asyncSocketData->buffer.erase((unsigned int) written);
/* If we wrote less than we attempted, the socket buffer is likely full
* likely is used as an optimization hint to the compiler
* since written < buffer_len is very likely to be true
*/
if(written < max_flush_len) {
[[likely]]
/* Cannot write more at this time, return what we've written so far */
return total_written;
}
/* If we wrote exactly max_flush_len, we might be able to write more, so continue
* This is unlikely to happen, because this would be INT_MAX bytes, which is unlikely to be written in one go
* but we keep this check for completeness
*/
continue;
}
/* Successfully wrote the entire buffer, clear the buffer */
asyncSocketData->buffer.clear();
}
/* Return the total number of bytes written during this flush operation */
return total_written;
}
/* Write in three levels of prioritization: cork-buffer, syscall, socket-buffer. Always drain if possible.
* Returns pair of bytes written (anywhere) and wheter or not this call resulted in the polling for
* writable (or we are in a state that implies polling for writable). */
@@ -290,6 +233,7 @@ public:
LoopData *loopData = getLoopData();
AsyncSocketData<SSL> *asyncSocketData = getAsyncSocketData();
/* We are limited if we have a per-socket buffer */
if (asyncSocketData->buffer.length()) {
size_t buffer_len = asyncSocketData->buffer.length();
@@ -317,7 +261,7 @@ public:
asyncSocketData->buffer.clear();
}
if (length) {
if (length) {
if (loopData->isCorkedWith(this)) {
/* We are corked */
if (LoopData::CORK_BUFFER_SIZE - loopData->getCorkOffset() >= (unsigned int) length) {

View File

@@ -125,7 +125,7 @@ private:
}
/* Signal broken HTTP request only if we have a pending request */
if (httpResponseData->onAborted != nullptr && httpResponseData->userData != nullptr) {
if (httpResponseData->onAborted) {
httpResponseData->onAborted((HttpResponse<SSL> *)s, httpResponseData->userData);
}
@@ -235,7 +235,7 @@ private:
}
/* Returning from a request handler without responding or attaching an onAborted handler is ill-use */
if (!((HttpResponse<SSL> *) s)->hasResponded() && !httpResponseData->onAborted && !httpResponseData->socketData) {
if (!((HttpResponse<SSL> *) s)->hasResponded() && !httpResponseData->onAborted) {
/* Throw exception here? */
std::cerr << "Error: Returning from a request handler without responding or attaching an abort handler is forbidden!" << std::endl;
std::terminate();
@@ -365,32 +365,11 @@ private:
auto *asyncSocket = reinterpret_cast<AsyncSocket<SSL> *>(s);
auto *httpResponseData = reinterpret_cast<HttpResponseData<SSL> *>(asyncSocket->getAsyncSocketData());
/* Attempt to drain the socket buffer before triggering onWritable callback */
size_t bufferedAmount = asyncSocket->getBufferedAmount();
if (bufferedAmount > 0) {
/* Try to flush pending data from the socket's buffer to the network */
bufferedAmount -= asyncSocket->flush();
/* Check if there's still data waiting to be sent after flush attempt */
if (bufferedAmount > 0) {
/* Socket buffer is not completely empty yet
* - Reset the timeout to prevent premature connection closure
* - This allows time for another writable event or new request
* - Return the socket to indicate we're still processing
*/
reinterpret_cast<HttpResponse<SSL> *>(s)->resetTimeout();
return s;
}
/* If bufferedAmount is now 0, we've successfully flushed everything
* and will fall through to the next section of code
*/
}
/* Ask the developer to write data and return success (true) or failure (false), OR skip sending anything and return success (true). */
if (httpResponseData->onWritable) {
/* We are now writable, so hang timeout again, the user does not have to do anything so we should hang until end or tryEnd rearms timeout */
us_socket_timeout(SSL, s, 0);
/* We expect the developer to return whether or not write was successful (true).
* If write was never called, the developer should still return true so that we may drain. */
bool success = httpResponseData->callOnWritable(reinterpret_cast<HttpResponse<SSL> *>(asyncSocket), httpResponseData->offset);
@@ -405,7 +384,7 @@ private:
}
/* Drain any socket buffer, this might empty our backpressure and thus finish the request */
asyncSocket->flush();
/*auto [written, failed] = */asyncSocket->write(nullptr, 0, true, 0);
/* Should we close this connection after a response - and is this response really done? */
if (httpResponseData->state & HttpResponseData<SSL>::HTTP_CONNECTION_CLOSE) {

View File

@@ -122,10 +122,15 @@ public:
/* We do not have tryWrite-like functionalities, so ignore optional in this path */
/* Write the chunked data if there is any (this will not send zero chunks) */
this->write(data, nullptr);
/* Do not allow sending 0 chunk here */
if (data.length()) {
Super::write("\r\n", 2);
writeUnsignedHex((unsigned int) data.length());
Super::write("\r\n", 2);
/* Ignoring optional for now */
Super::write(data.data(), (int) data.length());
}
/* Terminating 0 chunk */
Super::write("\r\n0\r\n\r\n", 7);
@@ -475,40 +480,6 @@ public:
return true;
}
size_t length = data.length();
// Special handling for extremely large data (greater than UINT_MAX bytes)
// most clients expect a max of UINT_MAX, so we need to split the write into multiple writes
if (length > UINT_MAX) {
bool has_failed = false;
size_t total_written = 0;
// Process full-sized chunks until remaining data is less than UINT_MAX
while (length > UINT_MAX) {
size_t written = 0;
// Write a UINT_MAX-sized chunk and check for failure
// even after failure we continue writing because the data will be buffered
if(!this->write(data.substr(0, UINT_MAX), &written)) {
has_failed = true;
}
total_written += written;
length -= UINT_MAX;
data = data.substr(UINT_MAX);
}
// Handle the final chunk (less than UINT_MAX bytes)
if (length > 0) {
size_t written = 0;
if(!this->write(data, &written)) {
has_failed = true;
}
total_written += written;
}
if (writtenPtr) {
*writtenPtr = total_written;
}
return !has_failed;
}
HttpResponseData<SSL> *httpResponseData = getHttpResponseData();
if (!(httpResponseData->state & HttpResponseData<SSL>::HTTP_WROTE_CONTENT_LENGTH_HEADER) && !httpResponseData->fromAncientRequest) {
@@ -528,36 +499,17 @@ public:
Super::write("\r\n", 2);
httpResponseData->state |= HttpResponseData<SSL>::HTTP_WRITE_CALLED;
}
size_t total_written = 0;
bool has_failed = false;
// Handle data larger than INT_MAX by writing it in chunks of INT_MAX bytes
while (length > INT_MAX) {
// Write the maximum allowed chunk size (INT_MAX)
auto [written, failed] = Super::write(data.data(), INT_MAX);
// If the write failed, set the has_failed flag we continue writting because the data will be buffered
has_failed = has_failed || failed;
total_written += written;
length -= INT_MAX;
data = data.substr(INT_MAX);
}
// Handle the remaining data (less than INT_MAX bytes)
if (length > 0) {
// Write the final chunk with exact remaining length
auto [written, failed] = Super::write(data.data(), (int) length);
has_failed = has_failed || failed;
total_written += written;
}
auto [written, failed] = Super::write(data.data(), (int) data.length());
/* Reset timeout on each sended chunk */
this->resetTimeout();
if (writtenPtr) {
*writtenPtr = total_written;
*writtenPtr = written;
}
/* If we did not fail the write, accept more */
return !has_failed;
return !failed;
}
/* Get the current byte write offset for this Http response */
@@ -708,6 +660,12 @@ public:
return httpResponseData->socketData;
}
void setSocketData(void* socketData) {
HttpResponseData<SSL> *httpResponseData = getHttpResponseData();
httpResponseData->socketData = socketData;
}
void setWriteOffset(uint64_t offset) {
HttpResponseData<SSL> *httpResponseData = getHttpResponseData();

View File

@@ -339,7 +339,7 @@ private:
/* We store old backpressure since it is unclear whether write drained anything,
* however, in case of coming here with 0 backpressure we still need to emit drain event */
size_t backpressure = asyncSocket->getBufferedAmount();
unsigned int backpressure = asyncSocket->getBufferedAmount();
/* Drain as much as possible */
asyncSocket->write(nullptr, 0);

View File

@@ -1,31 +0,0 @@
#!/usr/bin/env bash
# This file is not run often, so we don't need to make it part of the build system.
# We do this because the event names have to be compile-time constants.
export TRACE_EVENTS=$(rg 'bun\.perf\.trace\("([^"]*)"\)' -t zig --json \
| jq -r 'select(.type == "match")' \
| jq -r '.data.submatches[].match.text' \
| cut -d'"' -f2 \
| sort \
| uniq)
echo "// Generated with scripts/generate-perf-trace-events.sh" > src/bun.js/bindings/generated_perf_trace_events.h
echo "// clang-format off" >> src/bun.js/bindings/generated_perf_trace_events.h
echo "#define FOR_EACH_TRACE_EVENT(macro) \\" >> src/bun.js/bindings/generated_perf_trace_events.h
i=0
for event in $TRACE_EVENTS; do
echo " macro($event, $((i++))) \\" >> src/bun.js/bindings/generated_perf_trace_events.h
done
echo " // end" >> src/bun.js/bindings/generated_perf_trace_events.h
echo "Generated src/bun.js/bindings/generated_perf_trace_events.h"
echo "// Generated with scripts/generate-perf-trace-events.sh" > src/generated_perf_trace_events.zig
echo "pub const PerfEvent = enum(i32) {" >> src/generated_perf_trace_events.zig
for event in $TRACE_EVENTS; do
echo " @\"$event\"," >> src/generated_perf_trace_events.zig
done
echo "};" >> src/generated_perf_trace_events.zig
echo "Generated src/generated_perf_trace_events.zig"

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