Skip to main content

A pure Python JavaScript sandbox engine based on MQuickJS

Project description

micro-javascript

PyPI Changelog Tests License

A pure Python JavaScript engine, inspired by MicroQuickJS.

Overview

This project provides a JavaScript execution environment with:

  • Memory limits - Configurable maximum memory usage
  • Time limits - Configurable execution timeout
  • Pure Python - No C extensions or external dependencies
  • Broad ES5+ support - Variables, functions, closures, classes, iterators, promises, regex, and more

How it was built

Most of this library was built using Claude Code for web - here is the 15+ hour transcript.

Installation

pip install micro-javascript

Usage

from microjs import JSContext

# Create a context with optional limits
ctx = JSContext(memory_limit=1024*1024, time_limit=5.0)

# Evaluate JavaScript code
result = ctx.eval("1 + 2")  # Returns 3

# Functions and closures
ctx.eval("""
    function makeCounter() {
        var count = 0;
        return function() { return ++count; };
    }
    var counter = makeCounter();
""")
assert ctx.eval("counter()") == 1
assert ctx.eval("counter()") == 2

# Regular expressions
result = ctx.eval('/hello (\\w+)/.exec("hello world")')
# Returns ['hello world', 'world']

# Error handling with line/column tracking
ctx.eval("""
try {
    throw new Error("oops");
} catch (e) {
    // e.lineNumber and e.columnNumber are set
}
""")

Setting and Getting Variables

Use set() and get() to pass values between Python and JavaScript:

ctx = JSContext()

# Set a Python value as a JavaScript global variable
ctx.set("x", 42)
ctx.set("name", "Alice")
ctx.set("items", [1, 2, 3])

# Use the variable in JavaScript
result = ctx.eval("x * 2")  # Returns 84
result = ctx.eval("'Hello, ' + name")  # Returns 'Hello, Alice'
result = ctx.eval("items.map(n => n * 2)")  # Returns [2, 4, 6]

# Get a JavaScript variable back into Python
ctx.eval("var total = items.reduce((a, b) => a + b, 0)")
total = ctx.get("total")  # Returns 6

Exposing Python Functions to JavaScript

You can expose Python functions to JavaScript by setting them as global variables:

ctx = JSContext()

# Define a Python function
def add(a, b):
    return a + b

# Expose it to JavaScript
ctx.set("add", add)

# Call it from JavaScript
result = ctx.eval("add(2, 3)")  # Returns 5

Primitive values (numbers, strings, booleans) are passed directly as Python types, and primitives returned from Python functions work in JavaScript.

Arrays and objects are passed as internal JavaScript types (JSArray, JSObject). To return objects that JavaScript can use, return JSObject instances:

from microjs.values import JSObject, JSArray

ctx = JSContext()

# Access array elements via ._elements
def sum_array(arr):
    return sum(arr._elements)

ctx.set("sumArray", sum_array)
result = ctx.eval("sumArray([1, 2, 3, 4, 5])")  # Returns 15

# Return a JSObject for JavaScript to use
def make_point(x, y):
    obj = JSObject()
    obj.set("x", x)
    obj.set("y", y)
    return obj

ctx.set("makePoint", make_point)
result = ctx.eval("var p = makePoint(10, 20); p.x + p.y;")  # Returns 30

Supported Features

  • Core: variables, operators, control flow, functions, closures
  • Objects: object literals, prototypes, getters/setters, JSON
  • Arrays: literals, methods (map, filter, reduce, etc.), typed arrays
  • Functions: arrow functions, rest/spread, default parameters
  • Classes: class syntax, inheritance, static methods
  • Iteration: for-of, iterators, generators
  • Async: Promises, async/await
  • Regex: Full regex support with capture groups, lookahead/lookbehind
  • Error handling: try/catch/finally with stack traces

Known Limitations

See open-problems.md for details on:

  • Deep nesting limits (parser uses recursion)
  • Some regex edge cases with optional lookahead captures
  • Error constructor location tracking

Development

This project uses uv for dependency management.

# Run tests
uv run pytest

License

MIT License - see LICENSE file.

Based on MicroQuickJS by Fabrice Bellard.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

micro_javascript-0.1a1.tar.gz (68.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

micro_javascript-0.1a1-py3-none-any.whl (75.4 kB view details)

Uploaded Python 3

File details

Details for the file micro_javascript-0.1a1.tar.gz.

File metadata

  • Download URL: micro_javascript-0.1a1.tar.gz
  • Upload date:
  • Size: 68.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for micro_javascript-0.1a1.tar.gz
Algorithm Hash digest
SHA256 8cf0b3fa273e4206e479c8f34ecb38bf09b0ae981b4c810144388f57d37b3fb0
MD5 d3f294579d4df7cc6853eed075210fcf
BLAKE2b-256 57eefa97c458a1029bf8da779c2eddee1b6a6e6c2077b43f4a93dc5e3813b06e

See more details on using hashes here.

Provenance

The following attestation bundles were made for micro_javascript-0.1a1.tar.gz:

Publisher: publish.yml on simonw/micro-javascript

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file micro_javascript-0.1a1-py3-none-any.whl.

File metadata

File hashes

Hashes for micro_javascript-0.1a1-py3-none-any.whl
Algorithm Hash digest
SHA256 f0e6fd8ffd2fb5f2ca89b5d8be45f007f2f7d15469e176be8caef1ebaeb27e64
MD5 18d3005858663dc699e36e088082395e
BLAKE2b-256 17bce32076480014c1b5cbfb2b0c97378d81726a6ab7fd1e5962029ce3c90a41

See more details on using hashes here.

Provenance

The following attestation bundles were made for micro_javascript-0.1a1-py3-none-any.whl:

Publisher: publish.yml on simonw/micro-javascript

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page