public void LoadExtensions_PointedToPreferencesFile_LoadsCustomSnippets() { // Arrange var engine = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.None); JavaScriptContext ctx = engine.CreateContext(); JavaScriptContext.Current = ctx; var compiler = new EngineCompiler(); // Act compiler.CompileCore(JavaScriptSourceContext.None); compiler.LoadExtensions( Path.Combine(TestContext.DeploymentDirectory, "Resources"), JavaScriptSourceContext.None); // Assert string script = "replaceAbbreviation('cst', '3', 'markup')"; JavaScriptValue result = JavaScriptContext.RunScript(script, JavaScriptSourceContext.None); // preferences.json file contains "cst" abbreviation. If we are able to find it then // our extension has been loaded correctly. result.ValueType.Should().Be(JavaScriptValueType.String); engine.Dispose(); }
private JavascriptServerMiddleware(string rootDir, Predicate <HttpListenerContext> acceptRequest, bool transversalExecution, bool enableWebSocket, bool predicateCompat) { if (string.IsNullOrEmpty(rootDir)) { throw new ArgumentNullException("rootDir"); } _rootDirectory = rootDir; _enableDirectoryTransversalExecution = transversalExecution; _enableWebSocket = enableWebSocket; if (acceptRequest == null) { _acceptRequestFunc = (ctx => !ctx.Request.RawUrl.StartsWith("/assets")); } else { _acceptRequestFunc = acceptRequest; } echoDelegate = JSEcho; runScriptDelegate = JSRunScript; writeFileDelegate = JSWriteFile; readFileDelegate = JSReadFile; getWebSocketClientIdDelegate = JSGetPushClients; pushWebSocketMessageDelegate = JSPushMessage; // initialize javascript runtime // Create the runtime. We're only going to use one runtime for this host. _jsRuntime = JavaScriptRuntime.Create(); }
private void button1_Click(object sender, EventArgs e) { JavaScriptRuntime runtime; JavaScriptContext context; JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero); bool bSuccess = false; try { string script = System.IO.File.ReadAllText("C:/Temp/Script/Sample01.js"); runtime = JavaScriptRuntime.Create(); context = runtime.CreateContext(); JavaScriptContext.Current = context; JavaScriptContext.RunScript(script, currentSourceContext++, ""); bSuccess = true; } finally { if (true == bSuccess) { System.Diagnostics.Trace.WriteLine("Success"); } else { System.Diagnostics.Trace.WriteLine("Error"); } } }
public static oResult test_1(Dictionary <string, object> request = null) { oResult rs = new oResult() { ok = false, request = request }; using (JavaScriptRuntime runtime = JavaScriptRuntime.Create()) { JavaScriptContext context = _create_context(runtime); using (new JavaScriptContext.Scope(context)) { string script = "(()=>{ var val = ___api.test('TEST_1: Hello world'); ___api.log('api-js.test-1', 'key-1', 'TEST_1: This log called by JS...'); return val; })()"; try { JavaScriptValue result = JavaScriptContext.RunScript(script, CURRENT_SOURCE_CONTEXT++, string.Empty); rs.data = result.ConvertToString().ToString(); rs.ok = true; } catch (JavaScriptScriptException e) { var messageName = JavaScriptPropertyId.FromString("message"); rs.error = "ERROR_JS_EXCEPTION: " + e.Error.GetProperty(messageName).ConvertToString().ToString(); } catch (Exception e) { rs.error = "ERROR_CHAKRA: failed to run script: " + e.Message; } } } return(rs); }
/// <summary> /// Instantiates the <see cref="ChakraJavaScriptExecutor"/>. /// </summary> /// <param name="modifyBundle">Callback for bundle modification from outside.</param> public ChakraJavaScriptExecutor(Func <string, string> modifyBundle) { this._modifyBundle = modifyBundle; _runtime = JavaScriptRuntime.Create(); _context = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero); InitializeChakra(); }
public ScriptRunner() { this.runtime = JavaScriptRuntime.Create(); this.context = this.runtime.CreateContext(); JavaScriptContext.Current = this.context; Globals.Set(); }
private Runtime() { this.engine = JavaScriptRuntime.Create(); this.context = CreateContext(this.engine); runScriptDelegate = this.RunScript; createModuleDelegate = this.CreateModuleFunctionCallback; //StartDebugging(); }
public void Start() { if (IsValid) { return; } _runtime = JavaScriptRuntime.Create(); CreateContext(); }
private void button4_Click(object sender, EventArgs e) { JavaScriptRuntime runtime; JavaScriptContext context; JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero); JavaScriptValue DbgStringFn; JavaScriptValue DbgStringName; JavaScriptPropertyId DbgStringId; JavaScriptValue SumFn; JavaScriptValue SumName; JavaScriptPropertyId SumId; IntPtr callbackState = IntPtr.Zero; bool bSuccess = false; try { string script = System.IO.File.ReadAllText("C:/Temp/Script/Sample04.js"); runtime = JavaScriptRuntime.Create(); context = runtime.CreateContext(); JavaScriptContext.Current = context; DbgStringName = JavaScriptValue.FromString("DbgString"); DbgStringId = JavaScriptPropertyId.FromString("DbgString"); Native.JsCreateNamedFunction(DbgStringName, (ChakraHost.Hosting.JavaScriptNativeFunction)DbgString, callbackState, out DbgStringFn); JavaScriptValue.GlobalObject.SetProperty(DbgStringId, DbgStringFn, true); SumName = JavaScriptValue.FromString("Sum"); SumId = JavaScriptPropertyId.FromString("Sum"); Native.JsCreateNamedFunction(SumName, (ChakraHost.Hosting.JavaScriptNativeFunction)Sum, callbackState, out SumFn); JavaScriptValue.GlobalObject.SetProperty(SumId, SumFn, true); JavaScriptContext.RunScript(script, currentSourceContext++, ""); bSuccess = true; } finally { if (true == bSuccess) { System.Diagnostics.Trace.WriteLine("Success"); } else { System.Diagnostics.Trace.WriteLine("Error"); } } }
public ChakraCoreJavaScriptGenerator(ResourceScriptFactory resourceScriptFactory) { _resourceScriptFactory = resourceScriptFactory; _promiseContinuationCallback = PromiseContinuationCallback; _dispatcher.Invoke(() => { _runtime = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.EnableExperimentalFeatures); _runtime.MemoryLimit = ChakraCoreSettings.MemoryLimit; }); }
public JsModuleRuntime() { if (!JavaScriptContext.Current.IsValid) { var runtime = JavaScriptRuntime.Create(); var context = runtime.CreateContext(); JavaScriptContext.Current = context; } this.loader = new ModuleLoader(); loader.AddPredefinedModule("react", JSLibraries.React); loader.AddPredefinedModule("unity-renderer", JSLibraries.UnityRenderer); }
public ChakraCoreTypeScriptTranspiler() { using var stream = typeof(ChakraCoreTypeScriptTranspiler).Assembly.GetManifestResourceStream(typeof(V8TypeScriptTranspiler), "typescriptServices.js"); using var reader = new StreamReader(stream); var typescriptServicesSource = reader.ReadToEnd(); _runtime = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.None); _context = JavaScriptContext.CreateContext(_runtime); // Install the compiler in the context using (var scope = _context.GetScope()) { JavaScriptContext.RunScript(typescriptServicesSource); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { try { runtime = JavaScriptRuntime.Create(); context = runtime.CreateContext(); JavaScriptContext.Current = context; JavaScriptValue hostObject = JavaScriptValue.CreateObject(); JavaScriptValue globalObject = JavaScriptValue.GlobalObject; JavaScriptPropertyId hostPropertyId = JavaScriptPropertyId.FromString("host"); globalObject.SetProperty(hostPropertyId, hostObject, true); JavaScriptValue delegateObject = JavaScriptValue.CreateObject(); JavaScriptPropertyId delegatePropertyId = JavaScriptPropertyId.FromString("delegate"); globalObject.SetProperty(delegatePropertyId, delegateObject, true); DefineHostCallback(delegateObject, "ballCountChanged", onBallCountChanged, IntPtr.Zero); DefineHostCallback(delegateObject, "displayListChanged", onDisplayListChanged, IntPtr.Zero); DefineHostCallback(delegateObject, "eventsPerSecond", onEventsPerSecond, IntPtr.Zero); DefineHostCallback(delegateObject, "phaseChanged", onPhaseChanged, IntPtr.Zero); DefineHostCallback(delegateObject, "measureText", onMeasureText, IntPtr.Zero); DefineHostCallback(delegateObject, "log", onLog, IntPtr.Zero); Uri uri = new Uri("/model.js", UriKind.Relative); StreamResourceInfo info = Application.GetContentStream(uri); System.IO.StreamReader sr = new System.IO.StreamReader(info.Stream); string script = sr.ReadToEnd(); JavaScriptValue result = JavaScriptContext.RunScript(script); script = "var controller = initApp(" + balls.ActualWidth + ", " + balls.ActualHeight + ", delegate);"; result = JavaScriptContext.RunScript(script); } catch (JavaScriptScriptException ex) { PrintScriptException(ex.Error); } catch (Exception ex) { Debug.WriteLine("chakrahost: failed to run script: {0}", ex.Message); } timer = new Timer(1.0 / 30.0 * 1000.0); timer.Elapsed += new ElapsedEventHandler(TimerFired); timer.Enabled = true; }
public ArmTemplate EvaluateTemplate() { if (!_hasEvaluated) { using (JavaScriptRuntime runtime = JavaScriptRuntime.Create()) { JavaScriptContext context = runtime.CreateContext(); using (new JavaScriptContext.Scope(context)) { ArmJsRuntimeHelpers.InitializeContext(context); try { InitializeArmRuntimeScripts(); InitializeArmUnimplementedFunctions(); ParseUserProvidedScripts(); StartDebuggingIfDebuggingIsEnabled(); EvaluateParameters(); RunUserSpecifiedScriptsBeforeVariableEvaluation(); EvaluateVariables(); EvaluateResources(); RunUserSpecifiedScriptsAfterResourceEvalution(); ReadModifiedResources(); } catch (JavaScriptScriptException jEx) { PrintScriptException(jEx.Error); throw; } finally { _hasEvaluated = true; } } } } return(_armTemplate); }
public void Compile_CompilesEmmetEngineScript() { // Arrange var engine = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.None); JavaScriptContext ctx = engine.CreateContext(); JavaScriptContext.Current = ctx; var compiler = new EngineCompiler(); // Act compiler.CompileCore(JavaScriptSourceContext.None); // Assert JavaScriptValue emmet = JavaScriptValue.GlobalObject.GetProperty("expandAbbreviation"); emmet.ValueType.Should().Be(JavaScriptValueType.Function); engine.Dispose(); }
private void InitializeEngine() { Trace("Started initializing Emmet engine."); _engine = JavaScriptRuntime.Create(JavaScriptRuntimeAttributes.EnableIdleProcessing); _context = _engine.CreateContext(); JavaScriptContext.Current = _context; var compiler = new EngineCompiler(); compiler.CompileCore(_currentSourceContext); if (null != _extensionsDir) { compiler.LoadExtensions(_extensionsDir, _currentSourceContext); } Trace("Emmet engine successfully initialized."); _initialized = true; }
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()); }
public void Reset() { Dispose(); runtime = JavaScriptRuntime.Create(); context = runtime.CreateContext(); }
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"); } } }
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"); } } }
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); } } ); }
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); }
/// <summary> /// Instantiates the <see cref="ChakraJavaScriptExecutor"/>. /// </summary> public ChakraJavaScriptExecutor() { _runtime = JavaScriptRuntime.Create(); _context = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero); InitializeChakra(); }
public static void _init() { m_log = new clsLogJS(); js_runtime = JavaScriptRuntime.Create(); js_context = _create_context(js_runtime); }
/// <summary> /// Instantiates the <see cref="ChakraJavaScriptExecutor"/>. /// </summary> public ChakraJavaScriptExecutor() { _runtime = JavaScriptRuntime.Create(); InitializeChakra(); }
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(); }
// // The main entry point for the host. // public static int Main(string[] arguments) { int returnValue = 1; CommandLineArguments commandLineArguments; commandLineArguments.ArgumentsStart = 0; if (arguments.Length - commandLineArguments.ArgumentsStart < 1) { Console.Error.WriteLine("usage: chakrahost <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)) { // // 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; } } } catch (Exception e) { Console.Error.WriteLine("chakrahost: fatal error: internal error: {0}.", e.Message); } Console.WriteLine(returnValue); return(returnValue); }
public MainViewModel() { Runtime = JavaScriptRuntime.Create(); }