Пример #1
0
        public static oResult test_2(Dictionary <string, object> request = null)
        {
            oResult rs = new oResult()
            {
                ok = false, request = request
            };

            using (new JavaScriptContext.Scope(js_context))
            {
                string script = "(()=>{ var val = ___api.test('TEST_2: Hello world'); ___api.log('api-js.test-2', 'key-2', 'TEST_2: 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);
        }
        private static string GetExceptionString(JavaScriptValue exception)
        {
            var code = JavaScriptPropertyId.FromString("Code");

            if (exception.ValueType == JavaScriptValueType.Error)
            {
                JavaScriptPropertyId messageName  = JavaScriptPropertyId.FromString("message");
                JavaScriptValue      messageValue = exception.GetProperty(messageName);
                string message = messageValue.ToString();

                double column = -1, line = -1;
                var    lineProp = JavaScriptPropertyId.FromString("line");
                var    colProp  = JavaScriptPropertyId.FromString("column");
                if (exception.HasProperty(lineProp))
                {
                    line = exception.GetProperty(lineProp).ConvertToNumber().ToDouble();
                }

                if (exception.HasProperty(colProp))
                {
                    column = exception.GetProperty(lineProp).ConvertToNumber().ToDouble();
                }

                return(string.Format("{0}, at {1}:{2}", message, (int)line, (int)column));
            }

            if (exception.ValueType == JavaScriptValueType.Object && exception.HasProperty(code))
            {
                return(exception.GetProperty(code).ConvertToString().ToString());
            }

            return(string.Format("{0}", exception.ConvertToString().ToString()));
        }
Пример #3
0
 private static void PromiseRejectionTrackerCallback(
     JavaScriptValue promise,
     JavaScriptValue reason,
     bool handled,
     IntPtr callbackState
     )
 {
     // TODO
     UnityEngine.Debug.LogError("Unhandled Promise rejection: " + reason.ConvertToString().ToString());
 }
Пример #4
0
        public static string JSValToString(JavaScriptValue val)
        {
            val = val.ConvertToString();
            IntPtr  returnValue = IntPtr.Zero;
            UIntPtr stringLength;

            if (Native.JsStringToPointer(val, out returnValue, out stringLength) != JavaScriptErrorCode.NoError)
            {
                throw new Exception("Failed to convert return value.");
            }
            return(Marshal.PtrToStringUni(returnValue));
        }
        private string Stringify(JavaScriptValue value)
        {
            switch (value.ValueType)
            {
            case JavaScriptValueType.Undefined:
            case JavaScriptValueType.Null:
            case JavaScriptValueType.Number:
            case JavaScriptValueType.String:
            case JavaScriptValueType.Boolean:
            case JavaScriptValueType.Object:
            case JavaScriptValueType.Array:
                return(ConvertJson(value).ToString(Formatting.None));

            case JavaScriptValueType.Function:
            case JavaScriptValueType.Error:
                return(value.ConvertToString().ToString());

            default:
                throw new NotImplementedException();
            }
        }
Пример #6
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     using (new JavaScriptContext.Scope(context))
     {
         string script = inputText.Text;
         try
         {
             JavaScriptValue result       = JavaScriptContext.RunScript(script);
             JavaScriptValue stringResult = result.ConvertToString();
             outputText.Text += stringResult.ToString() + "\n";
             inputText.SelectAll();
         }
         catch (JavaScriptScriptException ex)
         {
             PrintScriptException(ex.Error);
         }
         catch (Exception ex)
         {
             Debug.WriteLine("chakrahost: failed to run script: {0}", ex.Message);
         }
     }
 }
        private JToken ParseAndExpandStringIfNeeded(JToken token, string str)
        {
            if (str.StartsWith("[") && str.EndsWith("]") && !str.StartsWith("[["))
            {
                var jsonLineInfo = (token as IJsonLineInfo);
                if (_verboseLogging)
                {
                    Console.WriteLine("<{0},{1}>:{2}", jsonLineInfo.LineNumber, jsonLineInfo.LinePosition, str);
                }

                var jsExpression = str.Substring(1, str.Length - 2);

                try
                {
                    EnsureValidCallHierarchy(string.Format("JSON.stringify({0});", jsExpression));
                    JavaScriptValue jsValue =
                        JavaScriptContext.RunScript(string.Format("JSON.stringify({0});", jsExpression));
                    var    resultAsJson = jsValue.ConvertToString().ToString();
                    JToken retval       = JToken.Parse(resultAsJson);
                    if (token.Root != token)
                    {
                        token.Replace(retval);
                    }
                    return(retval);
                }
                catch (JavaScriptScriptException jEx)
                {
                    Console.WriteLine("<{0},{1}>:Invalid expression '{2}' : {3}", jsonLineInfo.LineNumber, jsonLineInfo.LinePosition, str, GetExceptionString(jEx.Error));
                    if (!IsNotFatalJsException(jEx.Error))
                    {
                        throw;
                    }
                }
            }

            return(token);
        }
Пример #8
0
        /// <summary>
        /// Converts a <see cref="JavaScriptValue"/> with a number type to host value.
        /// </summary>
        public object ToHostNumber(JavaScriptValue arg, Type toType)
        {
            // 32-bit Conversions
            if (toType == typeof(byte))
            {
                return((byte)arg.ToInt32());
            }
            if (toType == typeof(sbyte))
            {
                return((sbyte)arg.ToInt32());
            }
            if (toType == typeof(short))
            {
                return((short)arg.ToInt32());
            }
            if (toType == typeof(ushort))
            {
                return((ushort)arg.ToInt32());
            }
            if (toType == typeof(int))
            {
                return(arg.ToInt32());
            }
            if (toType == typeof(uint))
            {
                return((uint)arg.ToInt32());
            }

            // 64-bit Conversions
            if (toType == typeof(long))
            {
                return((long)arg.ToDouble());
            }
            if (toType == typeof(ulong))
            {
                return((ulong)arg.ToDouble());
            }
            if (toType == typeof(float))
            {
                return((float)arg.ToDouble());
            }
            if (toType == typeof(double))
            {
                return(arg.ToDouble());
            }
            if (toType == typeof(decimal))
            {
                return((decimal)arg.ToDouble());
            }

            // Other Conversions
            if (toType == typeof(string))
            {
                return(arg.ConvertToString().ToString());
            }
            if (toType == typeof(bool))
            {
                return(arg.ConvertToBoolean().ToBoolean());
            }

            // Last Attempt
            if (toType.IsAssignableFrom(typeof(double)))
            {
                return(arg.ToDouble());
            }

            throw new Exception($"Cannot convert javascript number to type: {toType}");
        }
Пример #9
0
        public static oResult run_api(Dictionary <string, object> request = null)
        {
            oResult rs = new oResult()
            {
                ok = false, request = request
            };

            string scope = request.getValueByKey("___scope");

            if (string.IsNullOrEmpty(scope))
            {
                rs.error = "[___scope] is null or empty";
                return(rs);
            }

            if (!clsApi.Exist(scope))
            {
                rs.error = "[___scope] = " + scope + " is not exist";
                return(rs);
            }

            string sapi = request.getValueByKey("___api");

            if (string.IsNullOrEmpty(sapi))
            {
                rs.error = "[___api] is null or empty";
                return(rs);
            }

            oApi o = clsApi.Get(scope);

            if (o.apis.Length == 0)
            {
                rs.error = "folder " + scope + " missing files api: " + sapi.Replace("|", ".js; ") + ".js";
                return(rs);
            }

            sapi = sapi.ToLower().Trim();
            string[]      a  = sapi.Split('|');
            StringBuilder bi = new StringBuilder();

            bi.Append("(()=>{ ");
            bi.Append(Environment.NewLine);
            bi.Append("var ___scope = 'API-JS." + scope + "." + sapi + "'; ");
            bi.Append(Environment.NewLine);
            bi.Append("var ___log = function(key,text){ ___api.log(___scope, key, text); }; ");
            bi.Append(Environment.NewLine);
            bi.Append("var ___para = ");
            bi.Append(JsonConvert.SerializeObject(request));
            bi.Append(Environment.NewLine);
            bi.Append(Environment.NewLine);

            for (var i = 0; i < a.Length; i++)
            {
                if (o.apis_data.ContainsKey(a[i]) == false)
                {
                    rs.error = "folder " + scope + " missing files api: " + a[i] + ".js";
                    return(rs);
                }
                bi.Append(o.apis_data[a[i]]);
                bi.Append(Environment.NewLine);
                bi.Append(Environment.NewLine);
            }

            bi.Append(Environment.NewLine);
            bi.Append(" })()");

            string script = bi.ToString();

            using (new JavaScriptContext.Scope(js_context))
            {
                try
                {
                    JavaScriptValue result = JavaScriptContext.RunScript(script, CURRENT_SOURCE_CONTEXT++, string.Empty);
                    string          v      = result.ConvertToString().ToString();
                    if (v == "undefined")
                    {
                        rs.data = null;
                    }
                    else
                    {
                        rs.data = v;
                    }
                    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);
        }
Пример #10
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);
        }
 public JavaScriptException(JavaScriptValue error) : base(error.ConvertToString().ToString())
 {
     this.error = error;
 }