public static Task<NKScriptContext> createContext(Dictionary<string, object> options = null)
        {

            syncContext = new SingleThreadSynchronizationContext();

            Task.Factory.StartNew(() => { syncContext.RunOnCurrentThread(); }, TaskCreationOptions.LongRunning);
            var oldSyncContext = SynchronizationContext.Current;
            SynchronizationContext.SetSynchronizationContext(syncContext);
            var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            SynchronizationContext.SetSynchronizationContext(oldSyncContext);

            syncContext.Post((s) => { }, null);

            return Task.Factory.StartNew(() =>
             {
                 if (options == null)
                     options = new Dictionary<string, object>();

                 if (!runtimeCreated)
                 {
                     runtime = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.None, JavaScriptRuntimeVersion.VersionEdge, null);
                     runtimeCreated = true;
                 }

                 var chakra = runtime.CreateContext();
                 int id = NKScriptContextFactory.sequenceNumber++;
                 var context = new NKSChakraContext(id, chakra, options);

                 var item = new Dictionary<String, object>();
                 NKScriptContextFactory._contexts[id] = item;
                 item["JSVirtualMachine"] = runtime;  // if future non-shared runtimes required;
                 item["context"] = context;

                 return context.completeInitialization();
             }, Task.Factory.CancellationToken, TaskCreationOptions.LongRunning, taskScheduler).Unwrap();
        }
Example #2
0
 internal static extern JavaScriptErrorCode JsGetRuntimeMemoryUsage(JavaScriptRuntime runtime, out UIntPtr memoryUsage);
Example #3
0
 internal static extern JavaScriptErrorCode JsCollectGarbage(JavaScriptRuntime handle);
 /// <summary>
 /// Instantiates the <see cref="ChakraJavaScriptExecutor"/>.
 /// </summary>
 public ChakraJavaScriptExecutor()
 {
     _runtime = JavaScriptRuntime.Create();
     _context = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
     InitializeChakra();
 }
Example #5
0
        private static JavaScriptContext CreateHostContext(JavaScriptRuntime runtime, string[] arguments, int argumentsStart)
        {
            //
            // Create the context. Note that if we had wanted to start debugging from the very
            // beginning, we would have called JsStartDebugging right after context is created.
            //

            JavaScriptContext context = runtime.CreateContext();

            //
            // Now set the execution context as being the current one on this thread.
            //

            using (new JavaScriptContext.Scope(context))
            {
                //
                // Create the host object the script will use.
                //

                JavaScriptValue hostObject = JavaScriptValue.CreateObject();

                //
                // Get the global object
                //

                JavaScriptValue globalObject = JavaScriptValue.GlobalObject;

                //
                // Get the name of the property ("host") that we're going to set on the global object.
                //

                JavaScriptPropertyId hostPropertyId = JavaScriptPropertyId.FromString("host");

                //
                // Set the property.
                //

                globalObject.SetProperty(hostPropertyId, hostObject, true);

                //
                // Now create the host callbacks that we're going to expose to the script.
                //

                DefineHostCallback(hostObject, "echo", echoDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "runScript", runScriptDelegate, IntPtr.Zero);

                //
                // Create an array for arguments.
                //

                JavaScriptValue hostArguments = JavaScriptValue.CreateArray((uint)(arguments.Length - argumentsStart));

                for (int index = argumentsStart; index < arguments.Length; index++)
                {
                    //
                    // Create the argument value.
                    //

                    JavaScriptValue argument = JavaScriptValue.FromString(arguments[index]);

                    //
                    // Create the index.
                    //

                    JavaScriptValue indexValue = JavaScriptValue.FromInt32(index - argumentsStart);

                    //
                    // Set the value.
                    //

                    hostArguments.SetIndexedProperty(indexValue, argument);
                }

                //
                // Get the name of the property that we're going to set on the host object.
                //

                JavaScriptPropertyId argumentsPropertyId = JavaScriptPropertyId.FromString("arguments");

                //
                // Set the arguments property.
                //

                hostObject.SetProperty(argumentsPropertyId, hostArguments, true);
            }

            return(context);
        }
Example #6
0
 public static extern JavaScriptErrorCode JsEnableRuntimeExecution(JavaScriptRuntime runtime);
Example #7
0
 public static extern JavaScriptErrorCode JsCreateContext(JavaScriptRuntime runtime, out JavaScriptContext newContext);
Example #8
0
 internal static extern JavaScriptErrorCode JsCreateContext(JavaScriptRuntime runtime, out JavaScriptContext newContext);
Example #9
0
 public static void _init()
 {
     m_log      = new clsLogJS();
     js_runtime = JavaScriptRuntime.Create();
     js_context = _create_context(js_runtime);
 }
        public JavaScriptContext CreateContext(JavaScriptRuntime engine)
        {
            var context = engine.CreateContext();

            return(context);
        }
Example #11
0
 public void Reset()
 {
     Dispose();
     runtime = JavaScriptRuntime.Create();
     context = runtime.CreateContext();
 }
Example #12
0
        public static string js_chakra_run_2(object p = null)
        {
            //if (p == null || string.IsNullOrWhiteSpace(p.ToString())) return string.Empty;
            //string body_function = p.ToString();

            string v = "";
            //string script = "(()=>{ try{ " + body_function + " }catch(e){ return 'ERR:'+e.message; } })()";
            //var result = JavaScriptContext.RunScript(script, js_currentSourceContext++, string.Empty);
            //string v = result.ConvertToString().ToString();


            //int returnValue = 1;
            CommandLineArguments commandLineArguments;

            commandLineArguments.ArgumentsStart = 0;
            string[] arguments = new string[] { "chakrahost", "test.js", "12345" };

            using (JavaScriptRuntime runtime = JavaScriptRuntime.Create())
            {
                //
                // Similarly, create a single execution context. Note that we're putting it on the stack here,
                // so it will stay alive through the entire run.
                //

                JavaScriptContext context = CreateHostContext(runtime, arguments, commandLineArguments.ArgumentsStart);

                //
                // Now set the execution context as being the current one on this thread.
                //

                using (new JavaScriptContext.Scope(context))
                {
                    //
                    // Load the script from the disk.
                    //

                    //string script = File.ReadAllText(arguments[commandLineArguments.ArgumentsStart]);
                    string script = "(()=>{ var val = host.echo('Hello world'); return val; })()";

                    //
                    // Run the script.
                    //

                    JavaScriptValue result = new JavaScriptValue();
                    try
                    {
                        result = JavaScriptContext.RunScript(script, currentSourceContext++, arguments[commandLineArguments.ArgumentsStart]);
                    }
                    catch (JavaScriptScriptException e)
                    {
                        PrintScriptException(e.Error);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine("chakrahost: failed to run script: {0}", e.Message);
                    }

                    //
                    // Convert the return value.
                    //

                    //JavaScriptValue numberResult = result.ConvertToNumber();
                    //double doubleResult = numberResult.ToDouble();
                    //returnValue = (int)doubleResult;
                    //v = returnValue.ToString();

                    v = result.ConvertToString().ToString();
                }
            }

            return(v);
        }
Example #13
0
 public MainViewModel()
 {
     Runtime = JavaScriptRuntime.Create();
 }
Example #14
0
 internal static extern JavaScriptErrorCode JsIsRuntimeExecutionDisabled(JavaScriptRuntime runtime, out bool isDisabled);
Example #15
0
        public async Task Run(string[] arguments)
        {
            try
            {
                using (JavaScriptRuntime runtime = JavaScriptRuntime.Create())
                {
                    // Create a context. Note that if we had wanted to start debugging from the very
                    // beginning, we would have called JsStartDebugging right after context is create
                    JavaScriptContext context = runtime.CreateContext();

                    // Now set the execution context as being the current one on this thread.
                    using (new JavaScriptContext.Scope(context))
                    {
                        var hostObject = JavaScriptValue.CreateObject();

                        // Create an object called 'host' and set it on the global object.
                        var hostPropertyId = JavaScriptPropertyId.FromString("host");
                        JavaScriptValue.GlobalObject.SetProperty(hostPropertyId, hostObject, true);

                        // Register a bunch of callbacks on the 'host' object so that the JS code can call into C# code.
                        this.DefineHostCallback(hostObject, "echo", this.hostFunctions.EchoDelegate, IntPtr.Zero);
                        //this.DefineHostCallback(hostObject, "runScript", this.hostFunctions.RunScriptDelegate, IntPtr.Zero);

                        // Now register some async callbacks.
                        this.DefineHostCallback(hostObject, "doSuccessfulWork", this.hostFunctions.DoSuccessfulWorkDelegate, IntPtr.Zero);
                        this.DefineHostCallback(
                            hostObject,
                            "doUnsuccessfulWork",
                            this.hostFunctions.DoUnsuccessfulWorkDelegate,
                            IntPtr.Zero);
                        this.DefineHostCallback(hostObject, "getUrl", this.hostFunctions.GetUrlDelegate, IntPtr.Zero);

                        // Tell Chakra how to handle promises.
                        JavaScriptRuntime.SetPromiseContinuationCallback(this.jsTaskScheduler.PromiseContinuationCallback, IntPtr.Zero);

                        // Everything is setup, so we can go and use the engine now.
                        try
                        {
                            var javaScriptSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);

                            // Load and execute the JavaScript file.
                            var script = File.ReadAllText(arguments[0]);
                            var result = JavaScriptContext.RunScript(
                                script,
                                javaScriptSourceContext + 0,
                                arguments[0]);

                            // Start pumping the task queue so that promise continuations will be processed.
                            // Note that this must be done after the task queue has been initially filled.
                            var completion = this.jsTaskScheduler.PumpMessages();

                            // If the result was a promise, convert it into a C# Task and await its result.
                            // Note that this could be simplified so that the
                            if (IsPromise(result))
                            {
                                Console.WriteLine("Script returned a promise, awaiting it.");
                                result = await this.ConvertPromiseToTask(result);
                            }

                            Console.WriteLine($"Script result: {result.ConvertToString().ToString()}");

                            // Call the 'sayHello' method on the object which was returned from the script.
                            await this.ConvertPromiseToTask(
                                result.GetProperty(JavaScriptPropertyId.FromString("sayHello"))
                                .CallFunction(JavaScriptValue.GlobalObject, JavaScriptValue.FromString("do a barrel roll!")));

                            // Call the 'add' method, which is not an async method
                            var addResult = result.GetProperty(JavaScriptPropertyId.FromString("add"))
                                            .CallFunction(
                                JavaScriptValue.GlobalObject,
                                JavaScriptValue.FromInt32(78),
                                JavaScriptValue.FromInt32(22));

                            Console.WriteLine($"In C# land: 78 + 22 = {addResult.ConvertToNumber().ToDouble()}");

                            // Wait for the task pump to complete.
                            await completion;
                        }
                        catch (JavaScriptScriptException exception)
                        {
                            var messageValue = exception.Error.GetProperty(JavaScriptPropertyId.FromString("message"));
                            Console.Error.WriteLine("exception: {0}", messageValue.ToString());
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine("failed to run script: {0}", e.Message);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("fatal error: internal error: {0}.", e.Message);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Example #16
0
 internal static extern JavaScriptErrorCode JsSetRuntimeMemoryAllocationCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptMemoryAllocationCallback allocationCallback);
Example #17
0
        void Awake()
        {
#if UNITY_EDITOR
            javascriptRoot = Application.streamingAssetsPath + "/../../src/";
#else
            javascriptRoot = Application.streamingAssetsPath + "/src/";
#endif

            if (instance == null)
            {
                instance = this;
            }
            else
            {
                throw new Exception("There should not be more than one instance of Javascript.Engine in a scene at a time.");
            }

            runtime = JavaScriptRuntime.Create();
            context = runtime.CreateContext();

            Engine.With(() => {
                Module.Loader.Register(context);
                API.JSSystem.JSSystem.Register(context);
                API.Console.Register(context);
                API.DOM.Register(context);
                API.Inspect.Register(context);
                API.TypescriptServices.Register(context);
                API.File.Register(context);
                API.Http.Register(context);
                API.UpdateHelper.Register(context);
                API.Timer.Register(context);
                API.PromiseContinuation.Register(context);
                API.ChakraInternals.Register(context);
                API.JSUnityEngine.JSUnityEngine.Register(context);
                JavaScript.JSBehaviour.Register(context);

                JavaScriptValue.GlobalObject.SetProperty(
                    "engine",
                    Bridge.CreateExternalWithPrototype(
                        this,
                        Bridge.GetPrototype("UnityEngine.MonoBehaviour")
                        )
                    );
                JavaScriptValue.GlobalObject.SetProperty(
                    "root",
                    Bridge.CreateExternalWithPrototype(
                        gameObject
                        )
                    );
                JavaScriptValue.GlobalObject.SetProperty(
                    "importModule",
                    Bridge.CreateFunction("importModule", (args) => {
                    if (args[1].ValueType != JavaScriptValueType.String)
                    {
                        throw new Exception("The first argument to importModule must be a string");
                    }
                    return(Import(args[1].ToString()));
                })
                    );
                JavaScriptValue.GlobalObject.SetProperty(
                    "importScripts",
                    Bridge.CreateFunction("importScripts", (args) => {
                    foreach (var arg in args.Skip(1))
                    {
                        if (args[1].ValueType != JavaScriptValueType.String)
                        {
                            throw new Exception("All arguments to importScripts must be strings");
                        }
                        RunFile(args[1].ToString());
                    }
                })
                    );

                JavaScriptValue BindingsGlobal = JavaScriptValue.CreateObject();
                BindingsGlobal.SetProperty("get", Bridge.CreateFunction("get", (arguments) => {
                    string name = arguments[1].ToString();

                    var binding = bindings.Find((b) => b.name.Equals(name));
                    if (binding.Equals(null))
                    {
                        throw new Exception($"Attempted to retrieve the '{name}' binding from the Engine, but no such binding was associated. ");
                    }

                    return(Bridge.CreateExternalWithPrototype(binding.boundObject));
                }));

                JavaScriptValue.GlobalObject.SetProperty(
                    "bindings",
                    BindingsGlobal
                    );
            });


            CreateFileWatcher(
                javascriptRoot,
                (path) => {
                Debug.Log("file changed: " + path);
                if (fileChangedCallbacks.ContainsKey(path))
                {
                    Module.Loader.defaultCache.Reset();

                    Debug.Log("calling callback");
                    fileChangedCallbacks[path](path);
                }
            }
                );
        }
Example #18
0
 public override void Setup()
 {
     runtime_ = new JavaScriptRuntime();
     engine_  = runtime_.CreateEngine();
 }
        private void button3_Click(object sender, EventArgs e)
        {
            JavaScriptRuntime       runtime;
            JavaScriptContext       context;
            JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
            JavaScriptValue         jsValue;
            string szWelcomMessage;
            string szWhoamI;


            JavaScriptValue returnValue;
            JavaScriptValue myfunc_1;
            JavaScriptValue myfunc_2;
            JavaScriptValue myfunc_3;
            JavaScriptValue myfunc_4;

            bool bSuccess = false;

            try
            {
                string script = System.IO.File.ReadAllText("C:/Temp/Script/Sample03.js");


                runtime = JavaScriptRuntime.Create();
                context = runtime.CreateContext();
                JavaScriptContext.Current = context;
                JavaScriptContext.RunScript(script, currentSourceContext++, "");

                jsValue         = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWelcomMessage"));
                szWelcomMessage = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWhoamI"));
                szWhoamI = jsValue.ToString();

                System.Diagnostics.Trace.WriteLine("szWelcomMessage = " + szWelcomMessage);
                System.Diagnostics.Trace.WriteLine("szWhoamI = " + szWhoamI);



                // myfunc_1

                JavaScriptValue[] args1 = new JavaScriptValue[1] {
                    JavaScriptValue.FromString("self")
                };
                myfunc_1 = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("myfunc_1"));
                myfunc_1.CallFunction(args1);


                jsValue         = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWelcomMessage"));
                szWelcomMessage = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWhoamI"));
                szWhoamI = jsValue.ToString();


                System.Diagnostics.Trace.WriteLine("szWelcomMessage = " + szWelcomMessage);
                System.Diagnostics.Trace.WriteLine("szWhoamI = " + szWhoamI);



                // myfunc_2
                JavaScriptValue[] args2 = new JavaScriptValue[1] {
                    JavaScriptValue.GlobalObject
                };
                myfunc_2    = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("myfunc_2"));
                returnValue = myfunc_2.CallFunction(args2);


                jsValue         = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWelcomMessage"));
                szWelcomMessage = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWhoamI"));
                szWhoamI = jsValue.ToString();

                System.Diagnostics.Trace.WriteLine("Return Value = " + returnValue.ToString());
                System.Diagnostics.Trace.WriteLine("szWelcomMessage = " + szWelcomMessage);
                System.Diagnostics.Trace.WriteLine("szWhoamI = " + szWhoamI);


                // myfunc_3
                JavaScriptValue[] args3 = new JavaScriptValue[2] {
                    JavaScriptValue.GlobalObject, JavaScriptValue.FromString("myfunc_3")
                };
                myfunc_3    = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("myfunc_3"));
                returnValue = myfunc_3.CallFunction(args3);


                jsValue         = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWelcomMessage"));
                szWelcomMessage = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWhoamI"));
                szWhoamI = jsValue.ToString();

                System.Diagnostics.Trace.WriteLine("Return Value[0] = " + (returnValue.GetIndexedProperty(JavaScriptValue.FromInt32(0))).ToString());
                System.Diagnostics.Trace.WriteLine("Return Value[1] = " + (returnValue.GetIndexedProperty(JavaScriptValue.FromInt32(1))).ToBoolean());
                System.Diagnostics.Trace.WriteLine("szWelcomMessage = " + szWelcomMessage);
                System.Diagnostics.Trace.WriteLine("szWhoamI = " + szWhoamI);


                // myfunc_4
                JavaScriptValue[] args4 = new JavaScriptValue[3] {
                    JavaScriptValue.GlobalObject, JavaScriptValue.FromString("myfunc_4"), JavaScriptValue.FromBoolean(false)
                };
                myfunc_4    = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("myfunc_4"));
                returnValue = myfunc_4.CallFunction(args4);


                jsValue         = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWelcomMessage"));
                szWelcomMessage = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWhoamI"));
                szWhoamI = jsValue.ToString();

                System.Diagnostics.Trace.WriteLine("Return Value[0] = " + (returnValue.GetIndexedProperty(JavaScriptValue.FromInt32(0))).ToString());
                System.Diagnostics.Trace.WriteLine("Return Value[1] = " + (returnValue.GetIndexedProperty(JavaScriptValue.FromInt32(1))).ToBoolean());
                System.Diagnostics.Trace.WriteLine("szWelcomMessage = " + szWelcomMessage);
                System.Diagnostics.Trace.WriteLine("szWhoamI = " + szWhoamI);

                bSuccess = true;
            }
            finally
            {
                if (true == bSuccess)
                {
                    System.Diagnostics.Trace.WriteLine("Success");
                }
                else
                {
                    System.Diagnostics.Trace.WriteLine("Error");
                }
            }
        }
Example #20
0
 public static extern JavaScriptErrorCode JsGetRuntime(JavaScriptContext context, out JavaScriptRuntime runtime);
        private void button2_Click(object sender, EventArgs e)
        {
            JavaScriptRuntime       runtime;
            JavaScriptContext       context;
            JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
            JavaScriptValue         jsValue;
            string szWelcomMessage;
            string szWhoamI;
            double nVersion;
            bool   bSuccess = false;

            try
            {
                string script = System.IO.File.ReadAllText("C:/Temp/Script/Sample02.js");


                runtime = JavaScriptRuntime.Create();
                context = runtime.CreateContext();
                JavaScriptContext.Current = context;
                JavaScriptContext.RunScript(script, currentSourceContext++, "");

                jsValue         = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWelcomMessage"));
                szWelcomMessage = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWhoamI"));
                szWhoamI = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("nVersion"));
                nVersion = jsValue.ToDouble();

                System.Diagnostics.Trace.WriteLine("szWelcomMessage = " + szWelcomMessage);
                System.Diagnostics.Trace.WriteLine("szWhoamI = " + szWhoamI);
                System.Diagnostics.Trace.WriteLine("nVersion = " + nVersion.ToString());



                jsValue = JavaScriptValue.FromString("New_Sample02.js");
                JavaScriptValue.GlobalObject.SetProperty(JavaScriptPropertyId.FromString("szWhoamI"), jsValue, true);


                jsValue         = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWelcomMessage"));
                szWelcomMessage = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("szWhoamI"));
                szWhoamI = jsValue.ToString();

                jsValue  = JavaScriptValue.GlobalObject.GetProperty(JavaScriptPropertyId.FromString("nVersion"));
                nVersion = jsValue.ToDouble();

                System.Diagnostics.Trace.WriteLine("szWelcomMessage = " + szWelcomMessage);
                System.Diagnostics.Trace.WriteLine("szWhoamI = " + szWhoamI);
                System.Diagnostics.Trace.WriteLine("nVersion = " + nVersion.ToString());

                bSuccess = true;
            }
            finally
            {
                if (true == bSuccess)
                {
                    System.Diagnostics.Trace.WriteLine("Success");
                }
                else
                {
                    System.Diagnostics.Trace.WriteLine("Error");
                }
            }
        }
Example #22
0
 public static extern JavaScriptErrorCode JsIsRuntimeExecutionDisabled(JavaScriptRuntime runtime, out bool isDisabled);
Example #23
0
 public static extern JavaScriptErrorCode JsCreateRuntime(JavaScriptRuntimeAttributes attributes, JavaScriptThreadServiceCallback threadService, out JavaScriptRuntime runtime);
Example #24
0
        //
        // The main entry point for the host.
        //
        public static int Main(string[] arguments)
        {
            int returnValue = 1;
            CommandLineArguments commandLineArguments = ProcessArguments(arguments);

            if (arguments.Length - commandLineArguments.ArgumentsStart < 0)
            {
                Console.Error.WriteLine("usage: chakrahost [-debug] [-profile] <script name> <arguments>");
                return(returnValue);
            }

            try
            {
                //
                // Create the runtime. We're only going to use one runtime for this host.
                //

                using (JavaScriptRuntime runtime = JavaScriptRuntime.Create())
                {
                    //
                    // Similarly, create a single execution context. Note that we're putting it on the stack here,
                    // so it will stay alive through the entire run.
                    //

                    JavaScriptContext context = CreateHostContext(runtime, arguments, commandLineArguments.ArgumentsStart);

                    //
                    // Now set the execution context as being the current one on this thread.
                    //

                    using (new JavaScriptContext.Scope(context))
                    {
                        //
                        // Start debugging if requested.
                        //

                        if (commandLineArguments.Debug)
                        {
                            StartDebugging();
                        }

                        //
                        // Start profiling if requested.
                        //

                        if (commandLineArguments.Profile)
                        {
                            var profiler = new Profiler();
                            JavaScriptContext.StartProfiling(profiler, Native.ProfilerEventMask.TraceAll, 0);
                        }

                        //
                        // Load the script from the disk.
                        //

                        string script = File.ReadAllText(arguments[commandLineArguments.ArgumentsStart]);

                        //
                        // Run the script.
                        //

                        JavaScriptValue result;
                        try
                        {
                            result = JavaScriptContext.RunScript(script, currentSourceContext++, arguments[commandLineArguments.ArgumentsStart]);
                        }
                        catch (JavaScriptScriptException e)
                        {
                            PrintScriptException(e.Error);
                            return(1);
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine("chakrahost: failed to run script: {0}", e.Message);
                            return(1);
                        }

                        //
                        // Convert the return value.
                        //

                        JavaScriptValue numberResult = result.ConvertToNumber();
                        double          doubleResult = numberResult.ToDouble();
                        returnValue = (int)doubleResult;

                        //
                        // Stop profiling.
                        //

                        if (commandLineArguments.Profile)
                        {
                            JavaScriptContext.StopProfiling(0);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("chakrahost: fatal error: internal error: {0}.", e.Message);
            }

            return(returnValue);
        }
Example #25
0
 public static extern JavaScriptErrorCode JsCollectGarbage(JavaScriptRuntime handle);
Example #26
0
 internal static extern JavaScriptErrorCode JsCreateRuntime(JavaScriptRuntimeAttributes attributes, 
     JavaScriptThreadServiceCallback threadService, out JavaScriptRuntime runtime);
Example #27
0
 public static extern JavaScriptErrorCode JsDisposeRuntime(JavaScriptRuntime handle);
Example #28
0
 internal static extern JavaScriptErrorCode JsDisposeRuntime(JavaScriptRuntime handle);
Example #29
0
 public static extern JavaScriptErrorCode JsGetRuntimeMemoryUsage(JavaScriptRuntime runtime, out UIntPtr memoryUsage);
Example #30
0
 internal static extern JavaScriptErrorCode JsEnableRuntimeExecution(JavaScriptRuntime runtime);
Example #31
0
 public static extern JavaScriptErrorCode JsSetRuntimeMemoryLimit(JavaScriptRuntime runtime, UIntPtr memoryLimit);
Example #32
0
 internal static extern JavaScriptErrorCode JsSetRuntimeMemoryLimit(JavaScriptRuntime runtime, UIntPtr memoryLimit);
Example #33
0
 public static extern JavaScriptErrorCode JsSetRuntimeMemoryAllocationCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptMemoryAllocationCallback allocationCallback);
Example #34
0
 internal static extern JavaScriptErrorCode JsSetRuntimeBeforeCollectCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptBeforeCollectCallback beforeCollectCallback);
Example #35
0
 public static extern JavaScriptErrorCode JsSetRuntimeBeforeCollectCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptBeforeCollectCallback beforeCollectCallback);
Example #36
0
 internal static extern JavaScriptErrorCode JsGetRuntime(JavaScriptContext context, out JavaScriptRuntime runtime);
        private JavaScriptContext CreateHostContext(JavaScriptRuntime runtime, HttpListenerRequest request)
        {
            // Create the context. Note that if we had wanted to start debugging from the very
            // beginning, we would have called JsStartDebugging right after context is created.
            JavaScriptContext context = runtime.CreateContext();

            // Now set the execution context as being the current one on this thread.
            using (new JavaScriptContext.Scope(context))
            {
                // Create the host object the script will use.
                JavaScriptValue hostObject = JavaScriptValue.CreateObject();

                // Get the global object
                JavaScriptValue globalObject = JavaScriptValue.GlobalObject;

                // Get the name of the property ("host") that we're going to set on the global object.
                JavaScriptPropertyId hostPropertyId = JavaScriptPropertyId.FromString("host");

                // Set the property.
                globalObject.SetProperty(hostPropertyId, hostObject, true);

                // Now create the host callbacks that we're going to expose to the script.
                DefineHostCallback(hostObject, "echo", echoDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "runScript", runScriptDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "readFile", readFileDelegate, IntPtr.Zero);
                DefineHostCallback(hostObject, "writeFile", writeFileDelegate, IntPtr.Zero);

                // Create an object for request.
                JavaScriptValue requestParams = JavaScriptValue.CreateObject();

                if (request.RawUrl != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("rawUrl"), JavaScriptValue.FromString(request.RawUrl), true);
                }
                if (request.UserAgent != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("userAgent"), JavaScriptValue.FromString(request.UserAgent), true);
                }
                if (request.UserHostName != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("userHostName"), JavaScriptValue.FromString(request.UserHostName), true);
                }
                if (request.UserHostAddress != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("userHostAddress"), JavaScriptValue.FromString(request.UserHostAddress), true);
                }
                if (request.ServiceName != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("serviceName"), JavaScriptValue.FromString(request.ServiceName), true);
                }
                if (request.HttpMethod != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("httpMethod"), JavaScriptValue.FromString(request.HttpMethod), true);
                }
                if (request.ContentType != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("contentType"), JavaScriptValue.FromString(request.ContentType), true);
                }
                if (request.ContentEncoding != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("contentEncoding"), JavaScriptValue.FromString(request.ContentEncoding.WebName), true);
                }

                requestParams.SetProperty(JavaScriptPropertyId.FromString("keepAlive"), JavaScriptValue.FromBoolean(request.KeepAlive), true);
                requestParams.SetProperty(JavaScriptPropertyId.FromString("isWebSocketRequest"), JavaScriptValue.FromBoolean(request.IsWebSocketRequest), true);
                requestParams.SetProperty(JavaScriptPropertyId.FromString("isSecureConnection"), JavaScriptValue.FromBoolean(request.IsSecureConnection), true);
                requestParams.SetProperty(JavaScriptPropertyId.FromString("isLocal"), JavaScriptValue.FromBoolean(request.IsLocal), true);
                requestParams.SetProperty(JavaScriptPropertyId.FromString("isAuthenticated"), JavaScriptValue.FromBoolean(request.IsAuthenticated), true);
                requestParams.SetProperty(JavaScriptPropertyId.FromString("hasEntityBody"), JavaScriptValue.FromBoolean(request.HasEntityBody), true);
                requestParams.SetProperty(JavaScriptPropertyId.FromString("contentLength64"), JavaScriptValue.FromDouble(request.ContentLength64), true);

                // need to call begingetclientcertificate
                //requestParams.SetProperty(JavaScriptPropertyId.FromString("clientCertificateError"), JavaScriptValue.FromInt32(request.ClientCertificateError), true);

                if (request.UrlReferrer != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("urlReferrer"), JavaScriptValue.FromString(request.UrlReferrer.ToString()), true);
                }
                if (request.RequestTraceIdentifier != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("requestTraceIdentifier"), JavaScriptValue.FromString(request.RequestTraceIdentifier.ToString()), true);
                }
                if (request.RemoteEndPoint != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("remoteEndPoint"), JavaScriptValue.FromString(request.RemoteEndPoint.ToString()), true);
                }
                if (request.ProtocolVersion != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("protocolVersion"), JavaScriptValue.FromString(request.ProtocolVersion.ToString()), true);
                }
                if (request.LocalEndPoint != null)
                {
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("localEndPoint"), JavaScriptValue.FromString(request.LocalEndPoint.ToString()), true);
                }

                if (request.UserLanguages != null)
                {
                    JavaScriptValue userLanguages = JavaScriptValue.CreateArray((uint)request.UserLanguages.Length);
                    for (int i = 0; i < request.UserLanguages.Length; i++)
                    {
                        userLanguages.SetIndexedProperty(JavaScriptValue.FromInt32(i), JavaScriptValue.FromString(request.UserLanguages[i]));
                    }
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("userLanguages"), userLanguages, true);
                }

                if (request.AcceptTypes != null)
                {
                    JavaScriptValue acceptTypes = JavaScriptValue.CreateArray((uint)request.AcceptTypes.Length);
                    for (int i = 0; i < request.AcceptTypes.Length; i++)
                    {
                        acceptTypes.SetIndexedProperty(JavaScriptValue.FromInt32(i), JavaScriptValue.FromString(request.AcceptTypes[i]));
                    }
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("acceptTypes"), acceptTypes, true);
                }

                if (request.QueryString != null)
                {
                    JavaScriptValue queryString = JavaScriptValue.CreateArray((uint)request.QueryString.Count);
                    for (int i = 0; i < request.QueryString.Count; i++)
                    {
                        JavaScriptValue qsItem = JavaScriptValue.CreateObject();

                        qsItem.SetProperty(JavaScriptPropertyId.FromString("name"), JavaScriptValue.FromString(request.QueryString.GetKey(i) ?? string.Empty), false);
                        qsItem.SetProperty(JavaScriptPropertyId.FromString("value"), JavaScriptValue.FromString(request.QueryString[i] ?? string.Empty), false);

                        queryString.SetIndexedProperty(JavaScriptValue.FromInt32(i), qsItem);
                    }
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("queryString"), queryString, true);
                }

                if (request.Headers != null)
                {
                    JavaScriptValue headers = JavaScriptValue.CreateArray((uint)request.Headers.Count);
                    for (int i = 0; i < request.Headers.Count; i++)
                    {
                        JavaScriptValue headerItem = JavaScriptValue.CreateObject();
                        headerItem.SetProperty(JavaScriptPropertyId.FromString("name"), JavaScriptValue.FromString(request.Headers.GetKey(i) ?? string.Empty), false);
                        headerItem.SetProperty(JavaScriptPropertyId.FromString("value"), JavaScriptValue.FromString(request.Headers[i] ?? string.Empty), false);

                        headers.SetIndexedProperty(JavaScriptValue.FromInt32(i), headerItem);
                    }
                    requestParams.SetProperty(JavaScriptPropertyId.FromString("headers"), headers, true);
                }

                // #todo
                // Stream InputStream
                // CookieCollection Cookies

                hostObject.SetProperty(JavaScriptPropertyId.FromString("request"), requestParams, true);
            }

            return(context);
        }