Published 2026-11-05
Source taken from js_interpreter:0.0.1.

A comprehensive, pure Dart implementation of a JavaScript interpreter supporting ES6+ features. Perfect for embedding JavaScript execution in Dart/Flutter applications.
import/exportfunction* and yield/yield* supportInt8Array, Uint8Array, Float32Array, etc.)For detailed feature coverage and use cases, check the test suite for comprehensive examples.
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() {
final interpreter = JSInterpreter();
// Evaluate JavaScript code
final result = interpreter.eval('''
const greeting = "Hello";
const name = "World";
greeting + ", " + name + "!";
''');
print(result); // Hello, World!
}
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() async {
final interpreter = JSInterpreter();
final result = await interpreter.evalAsync('''
async function fetchData() {
const response = await Promise.resolve({ data: "Hello Async!" });
return response.data;
}
await fetchData();
''');
print(result); // Hello Async!
}
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() async {
final interpreter = JSInterpreter();
// Returns native Dart types (String, int, double, List, Map, etc.)
final result = await interpreter.evalAsyncToDart('''
const data = {
name: "Alice",
age: 30,
hobbies: ["reading", "coding"]
};
JSON.stringify(data);
''');
print(result); // {"name":"Alice","age":30,"hobbies":["reading","coding"]}
print(result.runtimeType); // String
}
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() async {
final interpreter = JSInterpreter();
// Register a module
interpreter.registerModule('math-utils', '''
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export const PI = 3.14159;
''');
// Use the module
final result = await interpreter.evalModuleAsync('''
import { add, multiply, PI } from 'math-utils';
const sum = add(5, 3);
const product = multiply(4, PI);
export default { sum, product };
''');
print(result); // {sum: 8, product: 12.56636}
}
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() {
final interpreter = JSInterpreter();
// Inject Dart function into JavaScript
interpreter.setGlobal('dartPrint', (List<JSValue> args) {
print('From Dart: ${args.first}');
return JSValueFactory.undefined();
});
interpreter.eval('''
dartPrint("Hello from JavaScript!");
''');
// Output: From Dart: Hello from JavaScript!
}
load(path) is available by default (similar to print() and trace()).
It reads the JavaScript file from disk and evaluates it in the current
interpreter context.
import 'dart:io';
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() {
final interpreter = JSInterpreter();
final file = File('/tmp/helpers.js');
file.writeAsStringSync('''
function add(a, b) { return a + b; }
''');
interpreter.eval('load("/tmp/helpers.js");');
final result = interpreter.eval('add(2, 3);');
print(result); // 5
}
You can run code in controlled mode, pause at configured source-line breakpoints, request a cooperative pause during execution, and resume from the paused state.
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() {
final interpreter = JSInterpreter();
interpreter.setBreakpoints({3});
final first = interpreter.evalControlled('''
const a = 1;
const b = 2;
const c = a + b;
c;
''');
if (first.isPaused) {
print(first.pauseInfo?.reason); // ExecutionPauseReason.breakpoint
print(first.pauseInfo?.line); // 3
}
final resumed = interpreter.resumeExecution();
print(resumed.value); // 3
interpreter.setBreakpoints({4});
final second = interpreter.evalControlled('''
function add(a, b) {
return a + b;
}
const result = add(1, 2);
result;
''');
if (second.isPaused) {
final stepped = interpreter.stepExecution(); // step-over in current frame
print(stepped.pauseInfo?.reason); // ExecutionPauseReason.step
}
}
Host APIs:
evalControlled(code) starts a resumable execution sessionpauseExecution() requests a cooperative pause of the current controlled runresumeExecution() continues from the paused pointstepExecution() executes one step-over in the current framecanStepOver() reports whether step-over is currently validcanStepInto() reports whether step-into is currently valid (only when paused at a call-site whose runtime target is script-defined)canStepOut() reports whether stepping out is currently possible (caller frame exists)addPauseListener(...) receives all pause notificationsaddBreakpointListener(...) receives breakpoint-only pausesaddResumeListener(...) notifies when execution continues from a paused stateaddStepListener(...) / addStepOverListener(...) receive step pausesaddExecutionCompleteListener(...) / addExecutionErrorListener(...) notify terminal outcomesexecutionStatus / executionPauseInfo expose current control statePausing is cooperative, not preemptive: the VM pauses at instruction boundaries, not by forcefully interrupting Dart code mid-operation.
The interpreter provides a powerful bidirectional messaging system for complex Dart-JavaScript interactions.
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() {
final interpreter = JSInterpreter();
// Register a message handler
interpreter.onMessage('greet', (dynamic message) {
final name = message as String;
return 'Hello, $name!';
});
// Call from JavaScript (synchronous)
final result = interpreter.eval('''
const greeting = sendMessage('greet', 'Alice');
greeting; // "Hello, Alice!"
''');
print(result);
}
For async operations that require waiting for results:
import 'package:pkg_js_interpreter/pkg_js_interpreter.dart';
void main() async {
final interpreter = JSInterpreter();
// Register an async message handler
interpreter.onMessage('fetchUser', (dynamic message) async {
final userId = message as int;
// Simulate async operation
await Future.delayed(Duration(milliseconds: 100));
return {
'id': userId,
'name': 'Alice',
'email': 'alice@example.com'
};
});
// Call from JavaScript (asynchronous)
final result = await interpreter.evalAsync('''
async function loadUser() {
const user = await sendMessageAsync('fetchUser', 1);
return user.email;
}
await loadUser();
''');
print(result); // "alice@example.com"
}
Message Handlers with Multiple Arguments:
interpreter.onMessage('calculate', (dynamic message) {
final args = message as List;
final operation = args[0] as String;
final a = args[1] as num;
final b = args[2] as num;
switch (operation) {
case 'add': return a + b;
case 'multiply': return a * b;
default: return null;
}
});
// In JavaScript:
final result = interpreter.eval('''
sendMessage('calculate', 'add', 5, 3); // 8
sendMessage('calculate', 'multiply', 4, 7); // 28
''');
Async Pipeline with Promise.all:
interpreter.onMessage('fetchData', (dynamic message) async {
final source = message as String;
await Future.delayed(Duration(milliseconds: 50));
return {'source': source, 'data': [1, 2, 3]};
});
final result = await interpreter.evalAsync('''
const results = await Promise.all([
sendMessageAsync('fetchData', 'database'),
sendMessageAsync('fetchData', 'api'),
sendMessageAsync('fetchData', 'cache')
]);
results.map(r => r.source);
''');
// ['database', 'api', 'cache']
Error Handling:
interpreter.onMessage('riskyOperation', (dynamic message) {
if (message == 'fail') {
throw Exception('Operation failed');
}
return 'Success';
});
// In JavaScript:
final result = await interpreter.evalAsync('''
try {
const result1 = await sendMessageAsync('riskyOperation', 'ok');
const result2 = await sendMessageAsync('riskyOperation', 'fail');
} catch (error) {
console.log('Caught:', error.message);
}
''');
The main class for JavaScript interpretation.
| Method | Description |
|---|---|
eval(String code) |
Synchronously evaluate JavaScript code |
evalAsync(String code) |
Asynchronously evaluate JavaScript code (returns Future<JSValue>) |
evalAsyncToDart(String code) |
Asynchronously evaluate and convert result to Dart types |
evalModule(String code) |
Evaluate as ES6 module |
evalModuleAsync(String code) |
Asynchronously evaluate as ES6 module |
registerModule(String name, String code) |
Register a module for import |
setGlobal(String name, dynamic value) |
Set a global variable |
registerHostCommand(String name, HostCommand handler) |
Register one custom global JS command backed by Dart |
registerHostCommands(Map<String, HostCommand> commands) |
Register multiple custom global JS commands |
getGlobal(String name) |
Get a global variable |
onMessage(String channel, dynamic callback) |
Register a message handler for a specific channel |
setConsoleCallbacks({onLog, onWarn, onError}) |
Capture console.log/warn/error output in Dart callbacks (suppresses default printing for registered levels) |
final interpreter = JSInterpreter();
final logs = <String>[];
final warns = <String>[];
final errors = <String>[];
interpreter.setConsoleCallbacks(
onLog: logs.add,
onWarn: warns.add,
onError: errors.add,
);
interpreter.eval('''
print("uses same log callback channel as console.log");
console.log("hello", 123);
console.warn("careful");
console.error("boom");
''');
| Function | Description |
|---|---|
print(...args) |
Built-in alias of console logging; auto-registered on every JSInterpreter |
sendMessage(String channel, [arg1, arg2, ...]) |
Send a synchronous message to Dart and get a result |
sendMessageAsync(String channel, [arg1, arg2, ...]) |
Send an asynchronous message to Dart (returns Promise) |
| Type | Description |
|---|---|
JSUndefined |
JavaScript undefined |
JSNull |
JavaScript null |
JSBoolean |
JavaScript boolean |
JSNumber |
JavaScript number (int or double) |
JSString |
JavaScript string |
JSBigInt |
JavaScript BigInt |
JSSymbol |
JavaScript Symbol |
JSObject |
JavaScript object |
JSArray |
JavaScript array |
JSFunction |
JavaScript function |
JSClass |
JavaScript class |
JSGenerator |
JavaScript generator |
JSAsyncGenerator |
JavaScript async generator |
JSPromise |
JavaScript Promise |
JSRegExp |
JavaScript RegExp |
JSDate |
JavaScript Date |
JSError |
JavaScript Error (and all error types) |
This project is licensed under the MIT License - see the LICENSE file for details.
Made with ❤️ in Dart
Object.defineProperties() now accepts JSFunction objects in addition to JSObject, correctly treating functions as objects per JavaScript semantics. Previously, calling Object.defineProperties() on a function would throw a TypeError.load(path) now falls back to Darwin-configured script roots when the initially resolved file is missing: it first tries DARWIN_BASE_FOLDER/path, then DARWIN_SCRIPT_FOLDER/path, and only then throws the existing load failure error.load() behavior for successful direct/relative paths while applying the selected fallback path consistently for source metadata, circular dependency detection, listener notifications, and error reporting.test/load_relative_path_test.dart with regressions for Darwin fallback resolution, including base-folder priority and script-folder fallback when the base candidate is absent.} now include the line number of the matching opening {, making it easier to locate mismatched braces in switch bodies, blocks, object literals, and class bodies.TokenType.arrow to the lexer's regex-context token set so that regex literals after arrow functions (e.g., (v) => /hello/.test(v)) are lexed correctly instead of throwing a SyntaxError.test/regex_after_arrow_test.dart with 4 tests covering regex literals in arrow function bodies, including character classes and flag matching._drainMicrotasks() — throws a StateError after 10,000 iterations so the interpreter no longer hangs when a promise resolver re-queues itself indefinitely.JSNativeFunction getters from re-entering the controlled-execution VM loop, which could cause infinite loops during stepping or breakpoint handling. Native getters are now invoked directly without the runtime stack capture.toMap() conversion from re-entering the VM for accessor properties with native getters — these now return '<native getter>' instead of triggering the getter (e.g., File objects with many native getters no longer hang).ownKeys() and toMap() so that both data properties (_properties) and accessor properties (_accessorProperties) are iterated together, ensuring accessor properties are no longer skipped when listing keys or converting to a Dart map.pkg_js_interpreter_extensions:
Directory extension (properties and methods from pkg_core).File extension (properties and methods from pkg_core).Spreadsheet and Sheet extensions (from pkg_spreadsheet).PdflibEnums extension (27 enums from pkg_pdflib_enums).PdflibTokens extension (57 token types from pkg_pdflib_tokens).lib/pkg_js_interpreter.dart.pkg_js_interpreter_extensions instead.lib/src/extensions/ directory and all extension source files.test/extensions/ directory and all extension tests.doc/extensions/ directory and all extension documentation.pkg_pdflib_enums as JavaScript global objects via the pdflib_enums extension (opt-in via interpreter.registerPdflibEnums()).values property returning an array of all value names.PageSize enum (with width/height fields) exposes each value as an object with name, width, height properties and a toRectangle() method.test/extensions/pdflib_enums_extension_test.dart with 36 tests covering all 27 enum types, including specific value checks and PageSize field access.doc/extensions/pdflib_enums_extension.md documenting registration, the enum reference table, and usage examples.pkg_pdflib_tokens as JavaScript constructors via the pdflib_tokens extension (opt-in via interpreter.registerPdflibTokens()).page.width = 600 updates the underlying immutable token via copyWith().children array, allowing nested token trees to be built inline: new Page({width: 595, children: [new Text({text: 'Hi'})]}).children setter on every token wrapper for replacing children after creation.TokenFactory constructor for polymorphic JSON deserialization from JavaScript.pkg_pdflib_interfaces as a direct dependency for the IToken interface.doc/extensions/directory_extension.md documenting the Directory JS extension.doc/extensions/file_extension.md documenting the File JS extension.doc/extensions/spreadsheet_extension.md documenting the Sheet and Spreadsheet JS extensions.doc/extensions/pdflib_tokens_extension.md documenting all 57 token types, the common token API, TokenFactory, and children initialization patterns.captureCallStack() method on JSInterpreter for capturing the current call stack during controlled execution.function, sourceFile, line, and column.captureCallStack() walks the frame chain using _pausedFrame (when paused) or _currentFrame, resolving source positions via _currentSourcePosition().pkg_core DirectoryExtension methods and properties on the JS interpreter Directory class for JavaScript scripting:
isAbsolute, isHidden, isNotHidden, isRelative, isResolved, pathSeparator, resolvedDir, resolvedPath, parent.deleteIfExists(), getName(), rename(), withChild(), withParent(), withPrefix(), withSuffix(), getFiles().pkg_core FileExtension methods and properties on the JS interpreter File class for JavaScript scripting:
pathSeparator, resolvedPath, extension, name, nameWithoutExtension, isHidden, isNotHidden, isResolved, isValidName, dimensions, verdubbeling, resolvedFile, and boolean getters like isDigitaal, isDZ, etc.canRead(), canWrite(), changeExtension(), deleteSyncIfExists(), renameSyncSafe(), toDigest(), withLowercaseExtension(), withParent(), withPrefix(), withSuffix(), writeBase64(), fromAssets(), getDimensions(), getVerdubbeling(), getName(), getExtension(), getPathSeparator().test/extensions/directory_extension_test.dart with 27 tests covering all new Directory properties and methods.test/extensions/file_extension_test.dart with 30 tests covering all new File properties and methods.assert() host command now accepts an optional message argument and throws that message when the assertion fails instead of always reporting the generic assert failed string.assert(value, message) failures in test/console_test.dart.evalControlled() execution and load()-loaded script files so debugger pause info reports the correct sourceFile and line number across script boundaries.sourceName/sourceFile attachment consistent through the compiler and runtime so debugger integrations can step through multiple files with stable file identity.setBreakpointsForSource() from leaking into the global breakpoint fallback set, and avoided clearing global breakpoints in clearBreakpointsForSource().sourceFile only evaluate breakpoints registered for that specific source file rather than falling back to global breakpoints.load() relative to the calling script's parent directory.evalControlled() script and a later load()-loaded file to confirm breakpoint and pause metadata remain aligned to each file.test/load_relative_path_test.dart covering relative path resolution in load(), nested directory loads, deferred function calls, and error handling.JSError and all typed subclasses (JSTypeError, JSReferenceError, JSSyntaxError, JSRangeError, JSURIError) now carry optional file, line, and sourceColumn fields.JSError.withLocation({file, line, sourceColumn}) method to attach or update location on an error. Each typed subclass overrides it to return the correct concrete type, so Dart-level isA<JSSyntaxError>() checks remain valid.LexerError.toString() now includes the column number: SyntaxError: (line LINE:COL), message.ParseError and LexerError thrown during JSParser.parseString() now propagate as JSSyntaxError with structured line/sourceColumn set through all interpreter entry points (eval, evalAsync, evalControlled, evalToDart). Previously these either used fragile string-matching (contains('ParseError')) that also missed LexerError entirely, or were silently swallowed into a generic JSError('Evaluation error: ...').ExposeAsDartError path (e.g. BigInt(), Number() type errors) now carry the JS call-site line and column extracted from the JS error object.load() and assert() host-command errors now attach the current VM source position.loadExternalScript FileSystemException error now carries the calling JS line/column.throw Exception('Expected property name') in the parser replaced with throw ParseError(...) so it consistently carries a source token.test/error_location_test.dart with 41 tests covering error-location propagation end-to-end: LexerError/ParseError structure, subclass constructors, withLocation() type preservation, and location relay through every interpreter entry point.JSInterpreter:
stepOver()stepInto()stepOut()JSInterpreter:
canStepOver()canStepInto()canStepOut()stepExecution() did alias stepOver()JSInterpreter for controlled evaluation, cooperative pause, and resume:
evalControlled(...)pauseExecution()resumeExecution()stepExecution()stepOverExecution()executionStatusexecutionPauseInfoJSInterpreter:
addPauseListener(...), addBreakpointListener(...), addResumeListener(...)addStepListener(...), addStepOverListener(...)addExecutionCompleteListener(...), addExecutionErrorListener(...)js_interpreter:0.0.1.