#
TypeScript SDK Reference
Complete reference documentation for the microsandbox TypeScript SDK.
#
Installation
npm install microsandbox
#
Quick Start
import { PythonSandbox } from "microsandbox";
async function main() {
const sb = await PythonSandbox.create({ name: "my-sandbox" });
try {
const exec = await sb.run("print('Hello, World!')");
console.log(await exec.output());
} finally {
await sb.stop();
}
}
main().catch(console.error);
#
PythonSandbox
The main class for creating and managing Python execution environments.
constructor(options?: SandboxOptions)
#
Class Methods
create()
Creates and automatically starts a new sandbox instance.
static async create(options?: SandboxOptions): Promise<PythonSandbox>
Returns: A started PythonSandbox
instance
const sb = await PythonSandbox.create({ name: "my-sandbox" });
try {
const exec = await sb.run("print('Hello!')");
console.log(await exec.output());
} finally {
await sb.stop();
}
#
Instance Methods
start()
Starts the sandbox with optional resource constraints.
async start(
image?: string,
memory?: number,
cpus?: number,
timeout?: number
): Promise<void>
const sandbox = new PythonSandbox({ name: "resource-limited" });
await sandbox.start("microsandbox/python", 1024, 2.0);
stop()
Stops and cleans up the sandbox.
async stop(): Promise<void>
run()
Executes Python code in the sandbox environment.
async run(code: string, options?: { timeout?: number }): Promise<Execution>
Returns: Execution
object with results
const exec = await sb.run("print('Hello, World!')");
console.log(await exec.output());
const code = `
import math
result = math.sqrt(16)
print(f"Square root of 16 is: {result}")
`;
const exec = await sb.run(code);
#
Properties
command
Access to shell command execution interface.
get command(): Command
const result = await sb.command.run("ls", ["-la", "/"]);
console.log(await result.output());
metrics
Access to resource monitoring interface.
get metrics(): Metrics
const cpu = await sb.metrics.cpu();
const memory = await sb.metrics.memory();
console.log(`CPU: ${cpu}%, Memory: ${memory} MiB`);
isStarted
Returns sandbox running status.
get isStarted(): boolean
name
Returns the sandbox identifier.
get name(): string
serverUrl
Returns the server URL.
get serverUrl(): string
namespace
Returns the namespace.
get namespace(): string
apiKey
Returns the API key.
get apiKey(): string | undefined
#
NodeSandbox
JavaScript/Node.js execution environment with identical API to PythonSandbox.
constructor(options?: SandboxOptions)
All methods are identical to PythonSandbox
but execute JavaScript code.
import { NodeSandbox } from "microsandbox";
const sb = await NodeSandbox.create({ name: "js-sandbox" });
try {
const exec = await sb.run("console.log('Hello from Node.js!');");
console.log(await exec.output());
} finally {
await sb.stop();
}
#
Execution
Represents the result of code execution from sandbox.run()
.
#
Methods
output()
Returns standard output from execution.
async output(): Promise<string>
error()
Returns standard error from execution.
async error(): Promise<string>
hasError()
Checks if execution produced errors.
hasError(): boolean
#
Properties
status
Execution status.
get status(): string
language
Language used for execution.
get language(): string
Example: Handling Execution Results
const exec = await sb.run("print('Hello'); import sys; sys.exit(1)");
console.log(`Status: ${exec.status}`);
console.log(`Language: ${exec.language}`);
console.log(`Output: ${await exec.output()}`);
console.log(`Has error: ${exec.hasError()}`);
#
CommandExecution
Represents the result of command execution from sandbox.command.run()
.
#
Methods
output()
Returns standard output from command execution.
async output(): Promise<string>
error()
Returns standard error from command execution.
async error(): Promise<string>
#
Properties
exitCode
Command exit code.
get exitCode(): number
success
True if command was successful (exit code 0).
get success(): boolean
command
The command that was executed.
get command(): string
args
Arguments used for the command.
get args(): string[]
#
Command
Interface for executing shell commands within sandboxes.
run()
Executes shell commands with arguments.
async run(
command: string,
args?: string[],
timeout?: number
): Promise<CommandExecution>
Returns: CommandExecution
object with results
const result = await sb.command.run("ls");
const result = await sb.command.run("ls", ["-la", "/tmp"]);
const result = await sb.command.run("sleep", ["10"], 5);
const result = await sb.command.run("ls", ["/nonexistent"]);
if (result.success) {
console.log("Output:", await result.output());
} else {
console.log("Error:", await result.error());
console.log("Exit code:", result.exitCode);
}
#
Metrics
Interface for monitoring sandbox resource usage and performance.
#
Methods
cpu()
Current CPU usage percentage.
async cpu(): Promise<number | undefined>
memory()
Current memory usage in MiB.
async memory(): Promise<number | undefined>
disk()
Current disk usage in bytes.
async disk(): Promise<number | undefined>
isRunning()
Sandbox running status.
async isRunning(): Promise<boolean>
all()
All metrics as a dictionary.
async all(): Promise<any>
Returns: Object with keys: name
, namespace
, running
, cpu_usage
, memory_usage
, disk_usage
// Individual metrics
const cpu = await sb.metrics.cpu();
const memory = await sb.metrics.memory();
const disk = await sb.metrics.disk();
const running = await sb.metrics.isRunning();
console.log(`CPU: ${cpu !== undefined ? cpu + '%' : 'Not available'}`);
console.log(`Memory: ${memory || 'Not available'} MiB`);
console.log(`Disk: ${disk || 'Not available'} bytes`);
console.log(`Running: ${running}`);
// All metrics at once
const metrics = await sb.metrics.all();
console.log(`All metrics:`, metrics);
#
Usage Patterns
#
Automatic Cleanup (Recommended)
Manual resource management with proper cleanup.
const sb = await PythonSandbox.create({ name: "my-sandbox" });
try {
const exec = await sb.run("print('Hello, World!')");
console.log(await exec.output());
} finally {
await sb.stop(); // Always cleanup
}
#
Manual Lifecycle Management
Manual control over sandbox lifecycle.
const sandbox = new PythonSandbox({ name: "my-sandbox" });
try {
await sandbox.start(undefined, 1024, 2.0);
const exec = await sandbox.run("print('Hello, World!')");
console.log(await exec.output());
} finally {
await sandbox.stop();
}
#
State Persistence
Variables and imports persist between executions.
const sb = await PythonSandbox.create({ name: "stateful" });
try {
await sb.run("x = 42");
await sb.run("y = x * 2");
const exec = await sb.run("print(f'Result: {y}')");
console.log(await exec.output()); // Output: Result: 84
} finally {
await sb.stop();
}
#
Error Handling
Comprehensive error handling patterns.
const sb = await PythonSandbox.create({ name: "error-handling" });
try {
const exec = await sb.run("1/0"); // Division by zero
if (exec.hasError()) {
console.log("Error occurred:", await exec.error());
}
} catch (error) {
console.log("Runtime error:", error);
} finally {
await sb.stop();
}
#
File Operations
Creating and manipulating files within sandboxes.
const sb = await PythonSandbox.create({ name: "files" });
try {
// Create a file using Python
await sb.run(`
with open('/tmp/test.txt', 'w') as f:
f.write('Hello from sandbox!')
`);
// Read the file using shell command
const result = await sb.command.run("cat", ["/tmp/test.txt"]);
console.log("File content:", await result.output());
} finally {
await sb.stop();
}
#
Configuration
#
Environment Variables
#
Server Configuration
Default server URL: http://127.0.0.1:5555
#
Error Handling
Common Error Types
The SDK throws Error
for various conditions:
- Connection failures — Server unreachable or network issues
- Authentication errors — Invalid or missing API key
- Execution timeouts — Code/commands exceed time limits
- Invalid operations — Attempting operations on stopped sandboxes
#
Best Practices
try {
const sb = await PythonSandbox.create({ name: "error-test" });
try {
const exec = await sb.run("potentially_failing_code()");
if (exec.hasError()) {
console.log("Execution error:", await exec.error());
} else {
console.log("Success:", await exec.output());
}
} finally {
await sb.stop();
}
} catch (error) {
console.log(`SDK error: ${error}`);
}
#
Best Practices
Recommended Practices
- Always use try-finally — Ensures proper cleanup
- Set appropriate timeouts — Prevent hanging operations
- Handle errors gracefully — Use try-catch blocks
- Monitor resources — Use metrics interface
- Use meaningful names — Easier debugging and management
- Install packages once — Reuse sandbox for multiple executions
- Always call stop() — Prevent resource leaks
Common Pitfalls
- Forgetting to call
stop()
in finally blocks - Not handling execution errors properly
- Setting timeouts too low for complex operations
- Creating too many concurrent sandboxes without resource limits