Core runtime environment for executing Edge Functions with complete Web API compatibility and isolated execution context. Provides a secure, standards-compliant environment for running serverless functions.
Main runtime class that creates an isolated execution environment with Web API globals. Extends the base VM with edge-specific functionality.
/**
* Edge Runtime VM for executing Edge Functions with Web API compatibility
* @template T - Extended context type
*/
class EdgeRuntime<T extends EdgeContext = EdgeContext> {
constructor(options?: EdgeVMOptions<T>);
/** The execution context containing all available globals */
readonly context: EdgeContext & T;
/** The dispatch function for handling fetch events */
readonly dispatchFetch: DispatchFetch;
/** Execute JavaScript code in the runtime context */
evaluate<T = any>(code: string): T;
}
interface EdgeVMOptions<T extends EdgeContext> {
/** VM code generation options - defaults to { strings: false, wasm: true } */
codeGeneration?: VMOptions<T>['codeGeneration'];
/** Function to extend the execution context with additional properties */
extend?: (context: EdgeContext) => EdgeContext & T;
/** Code to evaluate immediately when the runtime is created */
initialCode?: string;
}
interface VMOptions<T> {
/** Code generation options for the VM context */
codeGeneration?: {
/** Whether to allow eval() and new Function() - defaults to false for security */
strings?: boolean;
/** Whether to allow WebAssembly compilation - defaults to true */
wasm?: boolean;
};
/** Function to extend the base VM context */
extend?: (context: VMContext) => VMContext & T;
}
interface VMContext {
// Standard JavaScript global objects
Array: typeof Array;
ArrayBuffer: typeof ArrayBuffer;
Boolean: typeof Boolean;
Date: typeof Date;
Error: typeof Error;
JSON: typeof JSON;
Map: typeof Map;
Math: typeof Math;
Number: typeof Number;
Object: typeof Object;
Promise: typeof Promise;
Proxy: typeof Proxy;
Reflect: typeof Reflect;
RegExp: typeof RegExp;
Set: typeof Set;
String: typeof String;
Symbol: typeof Symbol;
WeakMap: typeof WeakMap;
WeakSet: typeof WeakSet;
// ... and other standard JavaScript globals
}Usage Examples:
import { EdgeRuntime } from "edge-runtime";
// Basic runtime creation
const runtime = new EdgeRuntime();
// Runtime with initial code
const runtime = new EdgeRuntime({
initialCode: `
addEventListener('fetch', event => {
event.respondWith(new Response('Hello World'));
});
`
});
// Runtime with extended context
const runtime = new EdgeRuntime({
extend: (context) => {
context.myCustomGlobal = 'custom value';
return context;
}
});Execute JavaScript code within the isolated runtime context.
/**
* Execute JavaScript code in the runtime context
* @param code - JavaScript code to execute
* @returns The result of the code execution
*/
evaluate<T = any>(code: string): T;Usage Examples:
// Execute simple expressions
const result = runtime.evaluate('2 + 2'); // 4
// Define functions and variables
runtime.evaluate(`
globalThis.myFunction = (x) => x * 2;
globalThis.myVar = 'hello';
`);
// Call defined functions
const doubled = runtime.evaluate('myFunction(5)'); // 10
const greeting = runtime.evaluate('myVar'); // 'hello'Dispatch fetch events to registered event listeners in the runtime.
/**
* Dispatch a fetch event to the runtime's event listeners
* @param input - URL string or Request object
* @param init - Optional RequestInit configuration
* @returns Promise resolving to Response with waitUntil method
*/
dispatchFetch(
input: string,
init?: RequestInit
): Promise<Response & { waitUntil: () => Promise<any> }>;
interface DispatchFetch {
(input: string, init?: RequestInit): Promise<Response & { waitUntil: () => Promise<any> }>;
}Usage Examples:
// Set up fetch event handler
runtime.evaluate(`
addEventListener('fetch', event => {
const url = new URL(event.request.url);
const response = new Response(
JSON.stringify({ path: url.pathname }),
{ headers: { 'content-type': 'application/json' } }
);
event.respondWith(response);
});
`);
// Dispatch fetch events
const response1 = await runtime.dispatchFetch('https://example.com/api/users');
const response2 = await runtime.dispatchFetch('https://example.com/health', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ check: true })
});
// Wait for any background tasks
await response1.waitUntil();The runtime provides a complete Web API-compatible execution context with all standard globals.
interface EdgeContext {
// Core globals
self: EdgeContext;
globalThis: EdgeContext;
EdgeRuntime: string;
// Web APIs
fetch: typeof fetch;
Request: typeof Request;
Response: typeof Response;
Headers: typeof Headers;
URL: typeof URL;
URLSearchParams: typeof URLSearchParams;
URLPattern: typeof URLPattern;
// Crypto APIs
crypto: typeof crypto;
Crypto: typeof Crypto;
CryptoKey: typeof CryptoKey;
SubtleCrypto: typeof SubtleCrypto;
// Stream APIs
ReadableStream: typeof ReadableStream;
ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;
ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;
WritableStream: typeof WritableStream;
WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;
TransformStream: typeof TransformStream;
// Text encoding
TextEncoder: typeof TextEncoder;
TextDecoder: typeof TextDecoder;
TextEncoderStream: typeof TextEncoderStream;
TextDecoderStream: typeof TextDecoderStream;
atob: typeof atob;
btoa: typeof btoa;
// Events
Event: typeof Event;
EventTarget: typeof EventTarget;
FetchEvent: typeof FetchEvent;
PromiseRejectionEvent: typeof PromiseRejectionEvent;
// Abort controllers
AbortController: typeof AbortController;
AbortSignal: typeof AbortSignal;
DOMException: typeof DOMException;
// File and form APIs
Blob: typeof Blob;
File: typeof File;
FormData: typeof FormData;
// Timers
setTimeout: typeof setTimeout;
setInterval: typeof setInterval;
// Utilities
console: typeof console;
structuredClone: typeof structuredClone;
// Standard JavaScript globals (inherited from VMContext)
Array: typeof Array;
Object: typeof Object;
String: typeof String;
Number: typeof Number;
Boolean: typeof Boolean;
Date: typeof Date;
RegExp: typeof RegExp;
Promise: typeof Promise;
Map: typeof Map;
Set: typeof Set;
WeakMap: typeof WeakMap;
WeakSet: typeof WeakSet;
Symbol: typeof Symbol;
Proxy: typeof Proxy;
Reflect: typeof Reflect;
JSON: typeof JSON;
Math: typeof Math;
Intl: typeof Intl;
// ... and all other standard JavaScript globals
}The runtime supports standard Web API event listeners for handling fetch events and errors.
Usage Examples:
// Register fetch event handler
runtime.evaluate(`
addEventListener('fetch', event => {
// Handle the fetch event
const response = new Response('Hello World');
event.respondWith(response);
});
`);
// Register error handlers
runtime.evaluate(`
addEventListener('error', event => {
console.error('Uncaught error:', event.error);
});
addEventListener('unhandledrejection', event => {
console.error('Unhandled rejection:', event.reason);
event.preventDefault();
});
`);The runtime provides automatic memory management and cleanup for executed code.
Usage Examples:
// The runtime automatically manages memory for evaluated code
const runtime = new EdgeRuntime();
// Large objects are automatically garbage collected
runtime.evaluate(`
let largeArray = new Array(1000000).fill('data');
largeArray = null; // Will be garbage collected
`);
// Context is cleaned up when runtime is no longer referenced
// No explicit cleanup required