Jint 3.0.0-beta-2056

Build NuGet NuGet MyGet Join the chat at https://gitter.im/sebastienros/jint

Jint

Jint is a Javascript interpreter for .NET which can run on any modern .NET platform as it supports .NET Standard 2.0 and .NET 4.6.2 targets (and later).

💡 You should prefer 3.x beta versions from NuGet over the 2.x. All new features and improvements are targeted against version 3.x.

Supported features

Following features are supported in version 3.x.

ECMAScript 2015 (ES6)

  • ✔ ArrayBuffer
  • ✔ Arrow function expression
  • ✔ Binary and octal literals
  • ✔ Class support
  • ✔ DataView
  • ✔ Destructuring
  • ✔ Default, rest and spread
  • ✔ Enhanced object literals
  • for...of
  • ❌ Generators
  • ✔ Template strings
  • ✔ Lexical scoping of variables (let and const)
  • ✔ Map and Set
  • ✔ Modules and module loaders
  • ✔ Promises (Experimental, API is unstable)
  • ✔ Reflect
  • ✔ Proxies
  • ✔ Symbols
  • ❌ Tail calls
  • ✔ Typed arrays
  • ✔ Unicode
  • ✔ Weakmap and Weakset

ECMAScript 2016

  • Array.prototype.includes
  • await, async
  • ✔ Block-scoping of variables and functions
  • ✔ Exponentiation operator **
  • ✔ Destructuring patterns (of variables)

ECMAScript 2017

  • Object.values, Object.entries and Object.getOwnPropertyDescriptors

ECMAScript 2018

  • Promise.prototype.finally
  • ✔ RegExp named capture groups
  • ✔ Rest/spread operators for object literals (...identifier),

ECMAScript 2019

  • Array.prototype.flat, Array.prototype.flatMap
  • String.prototype.trimStart, String.prototype.trimEnd
  • Object.fromEntries
  • Symbol.description
  • ✔ Optional catch binding

ECMAScript 2020

  • BigInt
  • export * as ns from
  • for-in enhancements
  • globalThis object
  • import
  • import.meta
  • ✔ Nullish coalescing operator (??)
  • ✔ Optional chaining
  • Promise.allSettled
  • String.prototype.matchAll

ECMAScript 2021

  • ✔ Logical Assignment Operators (&&= ||= ??=)
  • ✔ Numeric Separators (1_000)
  • AggregateError
  • Promise.any
  • String.prototype.replaceAll
  • WeakRef
  • FinalizationRegistry

ECMAScript 2022

  • ✔ Class Fields
  • ✔ RegExp Match Indices
  • ✔ Top-level await
  • ✔ Ergonomic brand checks for Private Fields
  • .at()
  • ✔ Accessible Object.prototype.hasOwnProperty (Object.hasOwn)
  • ✔ Class Static Block
  • ✔ Error Cause

ECMAScript 2023

  • ✔ Array find from last
  • ✔ Change Array by copy
  • ✔ Hashbang Grammar
  • ✔ Symbols as WeakMap keys

ECMAScript Stage 3 (no version yet)

  • ✔ Array Grouping - Object.groupBy and Map.groupBy
  • ✔ Promise.withResolvers
  • ✔ ShadowRealm

Other

  • Further refined .NET CLR interop capabilities
  • Constraints for execution (recursion, memory usage, duration)

Follow new features as they are being implemented, see https://github.com/sebastienros/jint/issues/343

Version 2.x

Version 2.x is no longer maintained and you should consider moving to using version 3.

Performance

  • Because Jint neither generates any .NET bytecode nor uses the DLR it runs relatively small scripts really fast
  • If you repeatedly run the same script, you should cache the Script or Module instance produced by Esprima and feed it to Jint instead of the content string
  • You should prefer running engine in strict mode, it improves performance

You can check out the engine comparison results, bear in mind that every use case is different and benchmarks might not reflect your real-world usage.

Discussion

Join the chat on Gitter or post your questions with the jint tag on stackoverflow.

Video

Here is a short video of how Jint works and some sample usage

https://docs.microsoft.com/shows/code-conversations/sebastien-ros-on-jint-javascript-interpreter-net

Thread-safety

Engine instances are not thread-safe and they should not accessed from multiple threads simultaneously.

Examples

This example defines a new value named log pointing to Console.WriteLine, then runs a script calling log('Hello World!').

var engine = new Engine()
    .SetValue("log", new Action<object>(Console.WriteLine));
    
engine.Execute(@"
    function hello() { 
        log('Hello World');
    };
 
    hello();
");

Here, the variable x is set to 3 and x * x is evaluated in JavaScript. The result is returned to .NET directly, in this case as a double value 9.

var square = new Engine()
    .SetValue("x", 3) // define a new variable
    .Evaluate("x * x") // evaluate a statement
    .ToObject(); // converts the value to .NET

You can also directly pass POCOs or anonymous objects and use them from JavaScript. In this example for instance a new Person instance is manipulated from JavaScript.

var p = new Person {
    Name = "Mickey Mouse"
};

var engine = new Engine()
    .SetValue("p", p)
    .Execute("p.Name = 'Minnie'");

Assert.AreEqual("Minnie", p.Name);

You can invoke JavaScript function reference

var add = new Engine()
    .Execute("function add(a, b) { return a + b; }")
    .GetValue("add");

add.Invoke(1, 2); // -> 3

or directly by name

var engine = new Engine()
   .Execute("function add(a, b) { return a + b; }");

engine.Invoke("add", 1, 2); // -> 3

Accessing .NET assemblies and classes

You can allow an engine to access any .NET class by configuring the engine instance like this:

var engine = new Engine(cfg => cfg.AllowClr());

Then you have access to the System namespace as a global value. Here is how it's used in the context on the command line utility:

jint> var file = new System.IO.StreamWriter('log.txt');
jint> file.WriteLine('Hello World !');
jint> file.Dispose();

And even create shortcuts to common .NET methods

jint> var log = System.Console.WriteLine;
jint> log('Hello World !');
=> "Hello World !"

When allowing the CLR, you can optionally pass custom assemblies to load types from.

var engine = new Engine(cfg => cfg
    .AllowClr(typeof(Bar).Assembly)
);

and then to assign local namespaces the same way System does it for you, use importNamespace

jint> var Foo = importNamespace('Foo');
jint> var bar = new Foo.Bar();
jint> log(bar.ToString());

adding a specific CLR type reference can be done like this

engine.SetValue("TheType", TypeReference.CreateTypeReference(engine, typeof(TheType)))

and used this way

jint> var o = new TheType();

Generic types are also supported. Here is how to declare, instantiate and use a List<string>:

jint> var ListOfString = System.Collections.Generic.List(System.String);
jint> var list = new ListOfString();
jint> list.Add('foo');
jint> list.Add(1); // automatically converted to String
jint> list.Count; // 2

Internationalization

You can enforce what Time Zone or Culture the engine should use when locale JavaScript methods are used if you don't want to use the computer's default values.

This example forces the Time Zone to Pacific Standard Time.

var PST = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var engine = new Engine(cfg => cfg.LocalTimeZone(PST));
    
engine.Execute("new Date().toString()"); // Wed Dec 31 1969 16:00:00 GMT-08:00

This example is using French as the default culture.

var FR = CultureInfo.GetCultureInfo("fr-FR");
var engine = new Engine(cfg => cfg.Culture(FR));
    
engine.Execute("new Number(1.23).toString()"); // 1.23
engine.Execute("new Number(1.23).toLocaleString()"); // 1,23

Execution Constraints

Execution constraints are used during script execution to ensure that requirements around resource consumption are met, for example:

  • Scripts should not use more than X memory.
  • Scripts should only run for a maximum amount of time.

You can configure them via the options:

var engine = new Engine(options => {

    // Limit memory allocations to MB
    options.LimitMemory(4_000_000);

    // Set a timeout to 4 seconds.
    options.TimeoutInterval(TimeSpan.FromSeconds(4));

    // Set limit of 1000 executed statements.
    options.MaxStatements(1000);

    // Use a cancellation token.
    options.CancellationToken(cancellationToken);
}

You can also write a custom constraint by deriving from the Constraint base class:

public abstract class Constraint
{
    /// Called before script is run and useful when you use an engine object for multiple executions.
    public abstract void Reset();

    // Called before each statement to check if your requirements are met; if not - throws an exception.
    public abstract void Check();
}

For example we can write a constraint that stops scripts when the CPU usage gets too high:

class MyCPUConstraint : Constraint
{
    public override void Reset()
    {
    }

    public override void Check()
    {
        var cpuUsage = GetCPUUsage();

        if (cpuUsage > 0.8) // 80%
        {
            throw new OperationCancelledException();
        }
    }
}

var engine = new Engine(options =>
{
    options.Constraint(new MyCPUConstraint());
});

When you reuse the engine and want to use cancellation tokens you have to reset the token before each call of Execute:

var engine = new Engine(options =>
{
    options.CancellationToken(new CancellationToken(true));
});

var constraint = engine.FindConstraint<CancellationConstraint>();

for (var i = 0; i < 10; i++) 
{
    using (var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
    {
        constraint.Reset(tcs.Token);

        engine.SetValue("a", 1);
        engine.Execute("a++");
    }
}

Using Modules

You can use modules to import and export variables from multiple script files:

var engine = new Engine(options =>
{
    options.EnableModules(@"C:\Scripts");
})

var ns = engine.ImportModule("./my-module.js");

var value = ns.Get("value").AsString();

By default, the module resolution algorithm will be restricted to the base path specified in EnableModules, and there is no package support. However you can provide your own packages in two ways.

Defining modules using JavaScript source code:

engine.AddModule("user", "export const name = 'John';");

var ns = engine.ImportModule("user");

var name = ns.Get("name").AsString();

Defining modules using the module builder, which allows you to export CLR classes and values from .NET:

// Create the module 'lib' with the class MyClass and the variable version
engine.AddModule("lib", builder => builder
    .ExportType<MyClass>()
    .ExportValue("version", 15)
);

// Create a user-defined module and do something with 'lib'
engine.AddModule("custom", @"
    import { MyClass, version } from 'lib';
    const x = new MyClass();
    export const result as x.doSomething();
");

// Import the user-defined module; this will execute the import chain
var ns = engine.ImportModule("custom");

// The result contains "live" bindings to the module
var id = ns.Get("result").AsInteger();

Note that you don't need to EnableModules if you only use modules created using AddModule.

.NET Interoperability

  • Manipulate CLR objects from JavaScript, including:
    • Single values
    • Objects
      • Properties
      • Methods
    • Delegates
    • Anonymous objects
  • Convert JavaScript values to CLR objects
    • Primitive values
    • Object -> expando objects (IDictionary<string, object> and dynamic)
    • Array -> object[]
    • Date -> DateTime
    • number -> double
    • string -> string
    • boolean -> bool
    • Regex -> RegExp
    • Function -> Delegate
  • Extensions methods

Security

The following features provide you with a secure, sand-boxed environment to run user scripts.

  • Define memory limits, to prevent allocations from depleting the memory.
  • Enable/disable usage of BCL to prevent scripts from invoking .NET code.
  • Limit number of statements to prevent infinite loops.
  • Limit depth of calls to prevent deep recursion calls.
  • Define a timeout, to prevent scripts from taking too long to finish.

Branches and releases

  • The recommended branch is main, any PR should target this branch
  • The main branch is automatically built and published on MyGet. Add this feed to your NuGet sources to use it: https://www.myget.org/F/jint/api/v3/index.json
  • The main branch is occasionally published on NuGet
  • The 3.x releases have more features (from es6) and is faster than the 2.x ones. They run the same test suite so they are as reliable. For instance RavenDB is using the 3.x version.
  • The 3.x versions are marked as beta as they might get breaking changes while es6 features are added.

No packages depend on Jint.

.NET Framework 4.6.2

.NET 6.0

.NET Standard 2.0

.NET Standard 2.1

Version Downloads Last updated
4.1.0 6 10/28/2024
4.0.3 9 09/28/2024
4.0.2 8 08/27/2024
4.0.1 12 08/12/2024
4.0.0 7 07/28/2024
3.1.6 8 08/12/2024
3.1.5 6 07/17/2024
3.1.4 8 06/28/2024
3.1.3 10 06/18/2024
3.1.2 11 05/29/2024
3.1.1 9 04/28/2024
3.1.0 12 04/16/2024
3.0.2 12 04/25/2024
3.0.1 17 03/04/2024
3.0.0 320 01/31/2024
3.0.0-beta-2060 11 06/26/2024
3.0.0-beta-2058 13 01/03/2024
3.0.0-beta-2057 12 01/05/2024
3.0.0-beta-2056 17 11/22/2023
3.0.0-beta-2055 19 11/16/2023
3.0.0-beta-2054 19 11/22/2023
3.0.0-beta-2053 15 11/22/2023
3.0.0-beta-2052 20 09/30/2023
3.0.0-beta-2051 16 11/17/2023
3.0.0-beta-2050 15 08/24/2023
3.0.0-beta-2049 21 06/04/2023
3.0.0-beta-2048 19 06/05/2023
3.0.0-beta-2047 19 06/05/2023
3.0.0-beta-2046 19 06/05/2023
3.0.0-beta-2045 21 06/05/2023
3.0.0-beta-2044 18 06/05/2023
3.0.0-beta-2043 19 06/05/2023
3.0.0-beta-2042 18 06/05/2023
3.0.0-beta-2041 21 06/05/2023
3.0.0-beta-2040 19 06/05/2023
3.0.0-beta-2039 20 06/05/2023
3.0.0-beta-2038 22 06/05/2023
3.0.0-beta-2037 21 06/05/2023
3.0.0-beta-2036 17 06/05/2023
3.0.0-beta-2035 17 06/05/2023
3.0.0-beta-2034 15 06/05/2023
3.0.0-beta-2033 18 06/05/2023
3.0.0-beta-2032 21 06/05/2023
3.0.0-beta-2031 19 06/05/2023
3.0.0-beta-2002 22 06/05/2023
3.0.0-beta-1914 20 06/05/2023
3.0.0-beta-1828 20 06/05/2023
3.0.0-beta-1778 18 06/05/2023
3.0.0-beta-1767 17 06/05/2023
3.0.0-beta-1756 20 06/05/2023
3.0.0-beta-1715 18 06/05/2023
3.0.0-beta-1632 22 06/05/2023
3.0.0-beta-1629 16 06/05/2023
3.0.0-beta-1612 20 06/05/2023
3.0.0-beta-1598 23 06/05/2023
3.0.0-beta-1525 19 06/05/2023
3.0.0-beta-1353 20 06/05/2023
3.0.0-beta-1293 22 06/05/2023
3.0.0-beta-1249 15 06/05/2023
3.0.0-beta-1210 20 06/05/2023
3.0.0-beta-1158 18 06/05/2023
3.0.0-beta-1156 20 06/05/2023
3.0.0-beta-1138 20 06/05/2023
3.0.0-beta-1123 16 06/05/2023
3.0.0-beta-1101 17 06/05/2023
3.0.0-beta-001 16 06/05/2023
2.11.58 6,752 12/16/2020
2.11.55 13 06/05/2023
2.11.23 14 06/05/2023
2.11.21 14 06/05/2023
2.11.20 18 06/05/2023
2.11.10 19 06/05/2023
2.10.4 17 06/05/2023
2.10.3 14 06/05/2023
2.10.2 16 06/05/2023
2.10.1 18 06/05/2023
2.10.0 19 06/05/2023
2.9.1 18 06/05/2023
2.9.0 14 06/05/2023
2.8.0 18 06/05/2023
2.7.1 16 06/05/2023
2.6.0 19 06/05/2023
2.5.0 22 06/05/2023
2.4.0 15 06/05/2023
2.3.0 18 06/05/2023
2.2.0 15 06/05/2023
2.1.0 16 06/05/2023
2.0.0 18 06/05/2023