pkg_js_interpreter version: 0.0.16

Published 2026-11-05

ruud

sdk | dart
repository | svn
platform | generic
status | n/a
  • Readme
  • Changelog
  • Versions

pkg_js_interpreter

Source taken from js_interpreter:0.0.1.

graph

Pub package License

A comprehensive, pure Dart implementation of a JavaScript interpreter supporting ES6+ features. Perfect for embedding JavaScript execution in Dart/Flutter applications.

AST

✨ Features

🚀 Core Capabilities

  • Full JavaScript Parsing - Complete lexer and parser supporting modern JavaScript syntax
  • Async/Await Support - Native async function execution with Promise integration
  • Module System - ES6 modules with import/export
  • Class System - Full ES6+ class support including private fields and static blocks
  • Generators - function* and yield/yield* support
  • Iterators - Full iterator protocol implementation
  • Proxy/Reflect - Complete metaprogramming support
  • TypedArrays - All typed array types (Int8Array, Uint8Array, Float32Array, etc.)
  • RegExp - Full regular expression support with ES2022 features
  • Strict Mode - Automatic and explicit strict mode handling

For detailed feature coverage and use cases, check the test suite for comprehensive examples.

🔧 Quick Start

Basic Usage

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!
}

Async/Await Support

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!
}

Convert to Dart Types

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
}

ES6 Modules

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}
}

Dart-JS Interop

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 External JavaScript Files

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
}

Execution Control: Pause, Breakpoint Pause, Resume, Step, Step Over

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 session
  • pauseExecution() requests a cooperative pause of the current controlled run
  • resumeExecution() continues from the paused point
  • stepExecution() executes one step-over in the current frame
  • canStepOver() reports whether step-over is currently valid
  • canStepInto() 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 notifications
  • addBreakpointListener(...) receives breakpoint-only pauses
  • addResumeListener(...) notifies when execution continues from a paused state
  • addStepListener(...) / addStepOverListener(...) receive step pauses
  • addExecutionCompleteListener(...) / addExecutionErrorListener(...) notify terminal outcomes
  • executionStatus / executionPauseInfo expose current control state

Pausing is cooperative, not preemptive: the VM pauses at instruction boundaries, not by forcefully interrupting Dart code mid-operation.

Messaging System: sendMessage & sendMessageAsync

The interpreter provides a powerful bidirectional messaging system for complex Dart-JavaScript interactions.

sendMessage (Synchronous)

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);
}

sendMessageAsync (Asynchronous)

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"
}

Advanced Patterns

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);
  }
''');

📚 API Reference

JSInterpreter

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)

Capturing Console Output

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");
''');

Global Functions (JavaScript Context)

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)

JSValue Types

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)

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


Made with ❤️ in Dart

Changelog

0.0.16 - 2026-11-05

Fixed

  • 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.

0.0.15 - 2026-11-05

Fixed

  • 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.
  • Preserved existing 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.

Tests

  • Extended 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.

0.0.14 - 2026-11-05

Fixed

  • Parser error messages for unexpected tokens at } 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.
  • Added 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.

Tests

  • Added test/regex_after_arrow_test.dart with 4 tests covering regex literals in arrow function bodies, including character classes and flag matching.

0.0.13 - 2026-11-03

Fixed

  • Added a guard against infinite microtask loops in _drainMicrotasks() — throws a StateError after 10,000 iterations so the interpreter no longer hangs when a promise resolver re-queues itself indefinitely.
  • Prevented 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.
  • Protected 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).

Changed

  • Unified property enumeration in 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.

0.0.12 - 2026-10-29

Changed

  • Moved all extension classes to a separate package 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).
  • Removed extension exports from lib/pkg_js_interpreter.dart.
  • Users who need the extensions should now depend on pkg_js_interpreter_extensions instead.

Removed

  • lib/src/extensions/ directory and all extension source files.
  • test/extensions/ directory and all extension tests.
  • doc/extensions/ directory and all extension documentation.

0.0.11 - 2026-10-29

Added

  • Exposed all 27 enums from pkg_pdflib_enums as JavaScript global objects via the pdflib_enums extension (opt-in via interpreter.registerPdflibEnums()).
  • Simple enums (26 types) expose each value as a string property and provide a 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.

Tests

  • Added test/extensions/pdflib_enums_extension_test.dart with 36 tests covering all 27 enum types, including specific value checks and PageSize field access.

Documentation

  • Added doc/extensions/pdflib_enums_extension.md documenting registration, the enum reference table, and usage examples.

0.0.10 - 2026-10-29

Added

  • Exposed all 57 tokens from pkg_pdflib_tokens as JavaScript constructors via the pdflib_tokens extension (opt-in via interpreter.registerPdflibTokens()).
  • Each token type provides explicit property getters and setters, so page.width = 600 updates the underlying immutable token via copyWith().
  • Token constructors accept a children array, allowing nested token trees to be built inline: new Page({width: 595, children: [new Text({text: 'Hi'})]}).
  • A children setter on every token wrapper for replacing children after creation.
  • TokenFactory constructor for polymorphic JSON deserialization from JavaScript.
  • Added pkg_pdflib_interfaces as a direct dependency for the IToken interface.

Changed

  • Rewrote the pdflib tokens extension to use dedicated JavaScript classes per token type instead of a generic wrapper, enabling proper code completion in JavaScript editors.

Documentation

  • Added doc/extensions/directory_extension.md documenting the Directory JS extension.
  • Added doc/extensions/file_extension.md documenting the File JS extension.
  • Added doc/extensions/spreadsheet_extension.md documenting the Sheet and Spreadsheet JS extensions.
  • Added doc/extensions/pdflib_tokens_extension.md documenting all 57 token types, the common token API, TokenFactory, and children initialization patterns.

0.0.9 - 2026-10-29

Added

  • captureCallStack() method on JSInterpreter for capturing the current call stack during controlled execution.
  • The method returns a list of frame maps (innermost to outermost), each containing function, sourceFile, line, and column.
  • Internally, the VM's captureCallStack() walks the frame chain using _pausedFrame (when paused) or _currentFrame, resolving source positions via _currentSourcePosition().

0.0.8 - 2026-10-28

Added

  • Exposed all pkg_core DirectoryExtension methods and properties on the JS interpreter Directory class for JavaScript scripting:
    • Properties: isAbsolute, isHidden, isNotHidden, isRelative, isResolved, pathSeparator, resolvedDir, resolvedPath, parent.
    • Methods: deleteIfExists(), getName(), rename(), withChild(), withParent(), withPrefix(), withSuffix(), getFiles().
  • Exposed all pkg_core FileExtension methods and properties on the JS interpreter File class for JavaScript scripting:
    • Properties: pathSeparator, resolvedPath, extension, name, nameWithoutExtension, isHidden, isNotHidden, isResolved, isValidName, dimensions, verdubbeling, resolvedFile, and boolean getters like isDigitaal, isDZ, etc.
    • Methods: canRead(), canWrite(), changeExtension(), deleteSyncIfExists(), renameSyncSafe(), toDigest(), withLowercaseExtension(), withParent(), withPrefix(), withSuffix(), writeBase64(), fromAssets(), getDimensions(), getVerdubbeling(), getName(), getExtension(), getPathSeparator().

Tests

  • Added test/extensions/directory_extension_test.dart with 27 tests covering all new Directory properties and methods.
  • Added test/extensions/file_extension_test.dart with 30 tests covering all new File properties and methods.

0.0.7 - 2026-10-27

Fixed

  • 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.

Tests

  • Added a regression for custom assert(value, message) failures in test/console_test.dart.

0.0.6 - 2026-10-26

Fixed

  • Preserved per-script source metadata for top-level evalControlled() execution and load()-loaded script files so debugger pause info reports the correct sourceFile and line number across script boundaries.
  • Scoped breakpoint matching to the active frame's source file, allowing a debugger to set breakpoints for specific files without collapsing all loaded scripts into one global line set.
  • Kept the sourceName/sourceFile attachment consistent through the compiler and runtime so debugger integrations can step through multiple files with stable file identity.
  • Prevented source-specific breakpoints in setBreakpointsForSource() from leaking into the global breakpoint fallback set, and avoided clearing global breakpoints in clearBreakpointsForSource().
  • Ensured stack frames with an associated sourceFile only evaluate breakpoints registered for that specific source file rather than falling back to global breakpoints.
  • Resolved relative file paths in load() relative to the calling script's parent directory.

Tests

  • Added a regression covering an initial evalControlled() script and a later load()-loaded file to confirm breakpoint and pause metadata remain aligned to each file.
  • Added tests in test/load_relative_path_test.dart covering relative path resolution in load(), nested directory loads, deferred function calls, and error handling.

0.0.5 - 2026-10-23

Changed

  • Version bump from 0.0.4 to 0.0.5 (SDK, TLS security fix).

0.0.4 - 2026-10-23

Added

  • Source location on thrown errors — 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.

Fixed

  • 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: ...').
  • Runtime errors re-thrown from the 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.
  • Lone throw Exception('Expected property name') in the parser replaced with throw ParseError(...) so it consistently carries a source token.

Tests

  • Added 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.

0.0.3 - 2026-10-19

Changed

  • Added explicit debugger stepping APIs on JSInterpreter:
    • stepOver()
    • stepInto()
    • stepOut()
  • Added step-availability APIs on JSInterpreter:
    • canStepOver()
    • canStepInto()
    • canStepOut()
  • Removed stepExecution() did alias stepOver()
  • Improved VM stepping semantics for controlled execution:
    • step-over pauses on the next meaningful source location in the current frame (or after unwind)
    • step-into is only enabled when paused on a call-site that resolves to a script-defined function target
    • step-out is only enabled when a caller frame exists
  • Added/updated execution-control regression tests for step availability and step gating behavior.

0.0.2 - 2026-10-12

Changed

  • Added execution-control APIs on JSInterpreter for controlled evaluation, cooperative pause, and resume:
    • evalControlled(...)
    • pauseExecution()
    • resumeExecution()
    • stepExecution()
    • stepOverExecution()
    • executionStatus
    • executionPauseInfo
  • Added execution-control listener callbacks on JSInterpreter:
    • addPauseListener(...), addBreakpointListener(...), addResumeListener(...)
    • addStepListener(...), addStepOverListener(...)
    • addExecutionCompleteListener(...), addExecutionErrorListener(...)
  • Added resumable pause-on-breakpoint behavior for controlled execution sessions.
  • Added debugger-like step and step-over pause reasons in controlled execution sessions.
  • Added execution-control regression tests and README usage documentation.

0.0.1 - 2026-10-12

  • Initial version. Taken from js_interpreter:0.0.1.

0.0.16

2026-11-05 download

0.0.12

2026-10-29 download

0.0.5

2026-10-23 download

0.0.3

2026-10-19 download