Enhanced web standards, streams, timers, events, and extended JavaScript built-ins with Bun-specific features available globally without imports.
High-performance timer functions with Bun-specific enhancements and precise control.
/**
* Schedule function execution after delay
* @param handler - Function to execute or code string
* @param timeout - Delay in milliseconds (default: 0)
* @param args - Arguments to pass to handler
* @returns Timer instance that can be referenced or cleared
*/
function setTimeout(
handler: TimerHandler,
timeout?: number,
...args: any[]
): Bun.Timer;
/**
* Schedule repeated function execution
* @param handler - Function to execute or code string
* @param interval - Interval in milliseconds
* @param args - Arguments to pass to handler
* @returns Timer instance that can be referenced or cleared
*/
function setInterval(
handler: TimerHandler,
interval?: number,
...args: any[]
): Bun.Timer;
/**
* Schedule immediate execution (next tick)
* @param handler - Function to execute
* @param args - Arguments to pass to handler
* @returns Timer instance
*/
function setImmediate(
handler: TimerHandler,
...args: any[]
): Bun.Timer;
/**
* Clear a timeout timer
* @param id - Timer ID to clear
*/
function clearTimeout(id?: Bun.Timer | number): void;
/**
* Clear an interval timer
* @param id - Timer ID to clear
*/
function clearInterval(id?: Bun.Timer | number): void;
/**
* Clear an immediate timer
* @param id - Timer ID to clear
*/
function clearImmediate(id?: Bun.Timer | number): void;
/** Timer handler function or code string */
type TimerHandler = (() => void) | string;
/** Bun timer instance with additional methods */
interface Bun.Timer {
/** Whether the timer keeps the process alive */
hasRef(): boolean;
/** Prevent timer from keeping process alive */
unref(): Bun.Timer;
/** Allow timer to keep process alive */
ref(): Bun.Timer;
}Usage Examples:
// Basic timers
const timeoutId = setTimeout(() => {
console.log("Executed after 1 second");
}, 1000);
const intervalId = setInterval(() => {
console.log("Repeating every 500ms");
}, 500);
// Clear timers
setTimeout(() => {
clearInterval(intervalId);
}, 3000);
// Immediate execution
setImmediate(() => {
console.log("Executed on next tick");
});
// Timer management
const timer = setTimeout(() => {
console.log("This won't keep process alive");
}, 10000);
timer.unref(); // Process can exit before this timer fires
// Arguments passing
setTimeout((name, count) => {
console.log(`Hello ${name}, count: ${count}`);
}, 1000, "World", 42);Global event handling system for managing application-wide events.
/**
* Add event listener to global event target
* @param type - Event type to listen for
* @param listener - Event handler function
* @param options - Event listener options
*/
function addEventListener<K extends keyof GlobalEventHandlersEventMap>(
type: K,
listener: (this: typeof globalThis, ev: GlobalEventHandlersEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
): void;
/**
* Remove event listener from global event target
* @param type - Event type
* @param listener - Event handler to remove
* @param options - Event listener options
*/
function removeEventListener<K extends keyof GlobalEventHandlersEventMap>(
type: K,
listener: (this: typeof globalThis, ev: GlobalEventHandlersEventMap[K]) => any,
options?: boolean | EventListenerOptions
): void;
/**
* Dispatch event to global event target
* @param event - Event to dispatch
* @returns Whether event was not cancelled
*/
function dispatchEvent(event: Event): boolean;
interface AddEventListenerOptions extends EventListenerOptions {
/** Remove listener after first invocation */
once?: boolean;
/** Add listener for capture phase */
capture?: boolean;
/** Allow passive event handling */
passive?: boolean;
}
interface EventListenerOptions {
/** Listen during capture phase */
capture?: boolean;
}Usage Examples:
// Global error handling
addEventListener("error", (event) => {
console.error("Global error:", event.error);
// Send to error reporting service
reportError(event.error);
});
addEventListener("unhandledrejection", (event) => {
console.error("Unhandled promise rejection:", event.reason);
event.preventDefault(); // Prevent default handling
});
// Custom global events
const customEvent = new CustomEvent("app:ready", {
detail: { timestamp: Date.now() }
});
addEventListener("app:ready", (event) => {
console.log("App ready at:", event.detail.timestamp);
});
dispatchEvent(customEvent);
// One-time listeners
addEventListener("beforeunload", () => {
console.log("Process is shutting down");
}, { once: true });Web Streams API with Bun-specific enhancements for improved performance and functionality.
interface ReadableStream<R = any> {
/** Whether stream is locked to a reader */
readonly locked: boolean;
/**
* Cancel the stream
* @param reason - Cancellation reason
* @returns Promise that resolves when cancelled
*/
cancel(reason?: any): Promise<void>;
/**
* Get a reader for the stream
* @param options - Reader options
* @returns Stream reader
*/
getReader(options?: { mode?: "byob" }): ReadableStreamDefaultReader<R>;
/**
* Pipe stream to writable stream
* @param destination - Writable stream destination
* @param options - Pipe options
* @returns Promise that resolves when piping completes
*/
pipeTo(
destination: WritableStream<R>,
options?: StreamPipeOptions
): Promise<void>;
/**
* Transform stream through transform stream
* @param transform - Transform stream
* @param options - Pipe options
* @returns New readable stream
*/
pipeThrough<T>(
transform: { readable: ReadableStream<T>; writable: WritableStream<R> },
options?: StreamPipeOptions
): ReadableStream<T>;
/**
* Tee the stream into two identical streams
* @returns Array of two identical readable streams
*/
tee(): [ReadableStream<R>, ReadableStream<R>];
/** Async iterator support */
[Symbol.asyncIterator](): AsyncIterableIterator<R>;
}
interface WritableStream<W = any> {
/** Whether stream is locked to a writer */
readonly locked: boolean;
/**
* Abort the stream
* @param reason - Abort reason
* @returns Promise that resolves when aborted
*/
abort(reason?: any): Promise<void>;
/**
* Close the stream
* @returns Promise that resolves when closed
*/
close(): Promise<void>;
/**
* Get a writer for the stream
* @returns Stream writer
*/
getWriter(): WritableStreamDefaultWriter<W>;
}
interface StreamPipeOptions {
/** Prevent closing destination when source closes */
preventClose?: boolean;
/** Prevent aborting destination when source aborts */
preventAbort?: boolean;
/** Prevent cancelling source when destination aborts */
preventCancel?: boolean;
/** AbortSignal to cancel the pipe operation */
signal?: AbortSignal;
}Usage Examples:
// Create readable stream from data
const dataStream = new ReadableStream({
start(controller) {
controller.enqueue("chunk 1");
controller.enqueue("chunk 2");
controller.enqueue("chunk 3");
controller.close();
}
});
// Async iteration over stream
for await (const chunk of dataStream) {
console.log("Received chunk:", chunk);
}
// Transform streams
const upperCaseTransform = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toString().toUpperCase());
}
});
const transformedStream = dataStream.pipeThrough(upperCaseTransform);
// Pipe to writable destination
const logStream = new WritableStream({
write(chunk) {
console.log("Logged:", chunk);
}
});
await transformedStream.pipeTo(logStream);
// Tee stream for multiple consumers
const [stream1, stream2] = originalStream.tee();
// Process same data in parallel
Promise.all([
processStream1(stream1),
processStream2(stream2)
]);Web Crypto API with Node.js compatibility additions and Bun-specific enhancements.
interface Crypto {
/** SubtleCrypto interface for cryptographic operations */
readonly subtle: SubtleCrypto;
/**
* Generate cryptographically secure random values
* @param array - Typed array to fill with random values
* @returns The same array filled with random values
*/
getRandomValues<T extends ArrayBufferView>(array: T): T;
/**
* Generate a random UUID v4
* @returns Random UUID string
*/
randomUUID(): string;
/**
* Timing-safe equality comparison (Node.js compatibility)
* @param a - First buffer to compare
* @param b - Second buffer to compare
* @returns True if buffers are equal
*/
timingSafeEqual(a: ArrayBufferView, b: ArrayBufferView): boolean;
}
/** Global crypto instance */
declare const crypto: Crypto;Usage Examples:
// Generate random values
const randomBytes = new Uint8Array(32);
crypto.getRandomValues(randomBytes);
console.log("Random bytes:", Array.from(randomBytes).map(b => b.toString(16)).join(''));
// Generate UUIDs
const id1 = crypto.randomUUID(); // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"
const id2 = crypto.randomUUID();
console.log("Generated IDs:", id1, id2);
// Timing-safe comparison (prevent timing attacks)
const secret = new TextEncoder().encode("my-secret-key");
const userInput = new TextEncoder().encode("user-provided-key");
const isValid = crypto.timingSafeEqual(secret, userInput);
// Subtle crypto operations
async function hashPassword(password: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(password);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
// Generate key pairs
async function generateKeyPair() {
const keyPair = await crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
return keyPair;
}Extended built-in types with modern JavaScript features and Bun-specific enhancements.
interface Uint8Array {
/**
* Convert to base64 string
* @param options - Encoding options
* @returns Base64 encoded string
*/
toBase64(options?: { alphabet?: "base64" | "base64url" }): string;
/**
* Set contents from base64 string
* @param base64 - Base64 encoded string
* @param offset - Byte offset to start writing
* @returns Number of bytes written
*/
setFromBase64(base64: string, offset?: number): number;
/**
* Convert to hexadecimal string
* @returns Hex encoded string
*/
toHex(): string;
/**
* Set contents from hexadecimal string
* @param hex - Hex encoded string
* @returns Number of bytes written
*/
setFromHex(hex: string): number;
}
interface Uint8ArrayConstructor {
/**
* Create Uint8Array from base64 string
* @param base64 - Base64 encoded string
* @param options - Decoding options
* @returns New Uint8Array with decoded data
*/
fromBase64(base64: string, options?: {
alphabet?: "base64" | "base64url";
lastChunkHandling?: "loose" | "strict";
}): Uint8Array;
/**
* Create Uint8Array from hexadecimal string
* @param hex - Hex encoded string
* @returns New Uint8Array with decoded data
*/
fromHex(hex: string): Uint8Array;
}
interface ArrayConstructor {
/**
* Create array from async iterable
* @param arrayLike - Async iterable to convert
* @param mapFn - Optional mapping function
* @param thisArg - Value to use as this
* @returns Promise resolving to new array
*/
fromAsync<T, U>(
arrayLike: AsyncIterable<T> | Iterable<T>,
mapFn?: (value: T, index: number) => U,
thisArg?: any
): Promise<U[]>;
}
interface ArrayBuffer {
/**
* Resize ArrayBuffer in place (if resizable)
* @param byteLength - New byte length
*/
resize(byteLength: number): void;
/** Whether buffer is resizable */
readonly resizable: boolean;
/** Maximum byte length for resizable buffers */
readonly maxByteLength?: number;
}
interface SharedArrayBuffer {
/**
* Grow SharedArrayBuffer (if growable)
* @param size - New size in bytes
*/
grow(size: number): void;
/** Whether buffer is growable */
readonly growable: boolean;
/** Maximum byte length for growable buffers */
readonly maxByteLength?: number;
}Usage Examples:
// Base64 encoding/decoding
const data = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
const base64 = data.toBase64(); // "SGVsbG8="
const decoded = Uint8Array.fromBase64(base64);
// Hex encoding/decoding
const hexString = data.toHex(); // "48656c6c6f"
const fromHex = Uint8Array.fromHex(hexString);
// Async array creation
async function* asyncGenerator() {
yield 1;
yield 2;
yield 3;
}
const asyncArray = await Array.fromAsync(asyncGenerator(), x => x * 2);
console.log(asyncArray); // [2, 4, 6]
// Resizable buffers
const resizableBuffer = new ArrayBuffer(1024, { maxByteLength: 4096 });
console.log("Initial size:", resizableBuffer.byteLength); // 1024
resizableBuffer.resize(2048);
console.log("Resized to:", resizableBuffer.byteLength); // 2048
// Working with binary data
function processImageData(imageBytes: Uint8Array) {
// Convert to base64 for data URL
const base64 = imageBytes.toBase64();
const dataUrl = `data:image/png;base64,${base64}`;
// Or convert to hex for debugging
const hex = imageBytes.toHex();
console.log("Image signature:", hex.substring(0, 16));
return dataUrl;
}Enhanced import.meta and module system features specific to Bun.
interface ImportMeta {
/** Module URL */
readonly url: string;
/** Absolute path to source file */
readonly path: string;
/** Directory containing source file */
readonly dir: string;
/** Filename of source file */
readonly file: string;
/** Whether this is the main module */
readonly main: boolean;
/** Environment variables */
readonly env: Bun.Env & NodeJS.ProcessEnv;
/** Node.js compatibility aliases */
readonly dirname: string;
readonly filename: string;
/**
* Synchronously resolve module specifier
* @param moduleId - Module to resolve
* @param parent - Parent module URL
* @returns Resolved module URL
*/
resolveSync(moduleId: string, parent?: string): string;
/** CommonJS require function */
readonly require: NodeJS.Require;
}
/** Global require function (CommonJS) */
declare const require: NodeJS.Require;
/** CommonJS exports object */
declare let exports: any;
/** CommonJS module object */
declare const module: NodeModule;Usage Examples:
// Module information
console.log("Current module:", import.meta.url);
console.log("Module path:", import.meta.path);
console.log("Module directory:", import.meta.dir);
console.log("Is main module:", import.meta.main);
// Environment access
const nodeEnv = import.meta.env.NODE_ENV || "development";
const port = parseInt(import.meta.env.PORT || "3000");
// Module resolution
const lodashPath = import.meta.resolveSync("lodash");
console.log("Lodash resolved to:", lodashPath);
// Dynamic imports based on environment
if (import.meta.env.NODE_ENV === "development") {
const devtools = await import("./dev-tools.js");
devtools.setup();
}
// Mixed module systems
const fs = import.meta.require("fs"); // CommonJS require
const { readFile } = await import("fs/promises"); // ES modulesGlobal utility functions for common operations.
/**
* Queue a microtask for execution
* @param callback - Function to execute as microtask
*/
function queueMicrotask(callback: () => void): void;
/**
* Report an error to the global error handler
* @param error - Error to report
*/
function reportError(error: any): void;
/**
* Create a deep clone of an object
* @param value - Value to clone
* @param options - Cloning options
* @returns Deep clone of the value
*/
function structuredClone<T>(value: T, options?: StructuredCloneOptions): T;
interface StructuredCloneOptions {
/** Objects to transfer instead of cloning */
transfer?: Transferable[];
}
/**
* Post message to parent (worker context)
* @param message - Message to send
* @param transfer - Objects to transfer
*/
function postMessage(message: any, transfer?: Transferable[]): void;Usage Examples:
// Microtask scheduling
console.log("1");
queueMicrotask(() => console.log("3"));
console.log("2");
// Output: 1, 2, 3
// Error reporting
try {
throw new Error("Something went wrong");
} catch (error) {
reportError(error); // Reports to global error handlers
}
// Deep cloning with transfer
const original = {
buffer: new ArrayBuffer(1024),
data: { nested: { value: 42 } }
};
const cloned = structuredClone(original, {
transfer: [original.buffer] // Transfer ownership instead of copying
});
// Worker communication (in worker context)
addEventListener("message", (event) => {
const result = processData(event.data);
postMessage({ result }, [result.buffer]);
});/** Transferable objects for postMessage and structured cloning */
type Transferable = ArrayBuffer | MessagePort | ReadableStream | WritableStream | TransformStream;
/** Global event handler map */
interface GlobalEventHandlersEventMap {
"error": ErrorEvent;
"unhandledrejection": PromiseRejectionEvent;
"rejectionhandled": PromiseRejectionEvent;
"beforeunload": BeforeUnloadEvent;
}
/** Enhanced error event */
interface ErrorEvent extends Event {
readonly message: string;
readonly filename: string;
readonly lineno: number;
readonly colno: number;
readonly error: any;
}
/** Promise rejection event */
interface PromiseRejectionEvent extends Event {
readonly promise: Promise<any>;
readonly reason: any;
}