Javascript Interpreter for C# (no dependencies)
#scripting #script-engine

Marko Lahma caf8ff8b43 Support extension methods (#812) преди 4 години
.github 4978e9f4dc Create FUNDING.yml преди 5 години
Jint caf8ff8b43 Support extension methods (#812) преди 4 години
Jint.Benchmark cccd41e73a Optimize interop, use NET5 to run tests (#803) преди 4 години
Jint.Repl cccd41e73a Optimize interop, use NET5 to run tests (#803) преди 4 години
Jint.Tests caf8ff8b43 Support extension methods (#812) преди 4 години
Jint.Tests.CommonScripts cccd41e73a Optimize interop, use NET5 to run tests (#803) преди 4 години
Jint.Tests.Ecma cccd41e73a Optimize interop, use NET5 to run tests (#803) преди 4 години
Jint.Tests.Test262 cccd41e73a Optimize interop, use NET5 to run tests (#803) преди 4 години
.gitattributes 2289f9ca31 Enable Symbol and RegExp tests and fix issues (#693) преди 5 години
.gitignore 189af9f321 Make ObjectInstance MruPropertyCache2 dictionary lazy (#454) преди 7 години
CREDITS.txt 5f713ad215 Using FastDtoa to serialize numbers преди 11 години
Common.props 03e614b6c9 Generating file version преди 7 години
Jint.sln 021c01a615 Add some missing new Math methods in ECMAScript 6 (#539) преди 7 години
Jint.sln.DotSettings dc2ce8ceb7 StringDictionarySlim instead of Dictionary/StructDictionary (#554) преди 6 години
LICENSE.txt f53137698a Adding license information преди 11 години
NuGet.config 7dbdd67c53 net45 support. (#530) преди 7 години
NuGet.release.config c4ae012e20 Ensure we are not using MyGet for releases преди 5 години
README.md 93f345f1b0 Update README.md преди 4 години
appveyor.yml 1d29ae72bb Publish symbols on rel/3.0-beta (#800) преди 4 години

README.md

Build status NuGet MyGet

Jint

Jint is a Javascript interpreter for .NET which provides full ECMA 5.1 compliance and can run on any .NET platform. Because it doesn't generate any .NET bytecode nor use the DLR it runs relatively small scripts faster. It's available as a PCL on Nuget at https://www.nuget.org/packages/Jint.

Features

ECMAScript 6.0 currently being implemeted, see https://github.com/sebastienros/jint/issues/343

Discussion

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

Examples

This example defines a new value named log pointing to Console.WriteLine, then executes 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 executed 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
        .Execute("x * x") // execute a statement
        .GetCompletionValue() // get the latest statement completion value
        .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

Constraints

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 implementing the IConstraint interface:

public interface IConstraint
{
    /// Called before a script is executed and useful when you us an engine object for multiple executions.
    void Reset();

    // Called before each statement to check if your requirements are met.
    void Check();
}

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

class MyCPUConstraint : IConstraint
{
    public void Reset()
    {
    }

    public 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 you want to use cancellation tokens you have to reset the token before each call of Execute:

var constraint = new CancellationConstraint();

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

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

Implemented features:

ECMAScript 5.1

ECMAScript 6.0

ES6 features which are being implemented:

.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

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.

Continuous Integration kindly provided by AppVeyor

Branches and releases

  • The recommended branch is dev, any PR should target this branch
  • The dev 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 dev branch is occasionally merged to master and 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.