// 这个函数可能从 JSComponent 调用过来
    public static void FirstInit(JSEngine jse = null)
    {
        if (!initSuccess && !initFail)
        {
            if (jse == null)
            {
                var goEngine = new GameObject("_JSEngine");
                goEngine.AddComponent <JSEngine>();
                return;
            }

            if (jse != null)
            {
                DontDestroyOnLoad(jse.gameObject);
                inst = jse;

                JSFileLoader jsLoader = jse.gameObject.GetComponent <JSFileLoader>();
                if (jsLoader == null)
                {
                    jsLoader = jse.gameObject.AddComponent <JSFileLoader>();
                }
                JSMgr.InitJSEngine(jsLoader, jse.OnInitJSEngine);
            }
        }
    }
Exemplo n.º 2
0
        public void CanProduceCorrectStackTrace()
        {
            var engine = new JSEngine(options => options.LimitRecursion(1000));

            engine.Execute(@"var a = function(v) {
	return v.xxx.yyy;
}

var b = function(v) {
	return a(v);
}", new ParserOptions
            {
                Source = "custom.js"
            });

            var e = Assert.Throws <JavaScriptException>(() => engine.Execute("var x = b(7);", new ParserOptions {
                Source = "main.js"
            }));

            Assert.Equal("xxx is undefined", e.Message);
            Assert.Equal(2, e.Location.Start.Line);
            Assert.Equal(8, e.Location.Start.Column);
            Assert.Equal("custom.js", e.Location.Source);

            var stack = e.CallStack;

            Assert.Equal(@" at a(v) @ custom.js 8:6
 at b(7) @ main.js 8:1
".Replace("\r\n", "\n"), stack.Replace("\r\n", "\n"));
        }
Exemplo n.º 3
0
 public ClrAccessDescriptor(JSEngine engine, Func <JsValue, JsValue> get, Action <JsValue, JsValue> set)
     : base(
         get: new GetterFunctionInstance(engine, get),
         set: set == null ? Native.Undefined.Instance : new SetterFunctionInstance(engine, set)
         )
 {
 }
Exemplo n.º 4
0
        public void NullPropagationTest()
        {
            var JSEngine = new JSEngine(cfg => cfg.SetReferencesResolver(new NullPropagationReferenceResolver()));

            const string Script = @"
var input = { 
	Address : null 
};

var address = input.Address;
var city = input.Address.City;
var length = input.Address.City.length;

var output = {
	Count1 : input.Address.City.length,
	Count2 : this.XYZ.length
};
";

            JSEngine.Execute(Script);

            var address = JSEngine.GetValue("address");
            var city    = JSEngine.GetValue("city");
            var length  = JSEngine.GetValue("length");
            var output  = JSEngine.GetValue("output").AsObject();

            Assert.Equal(Null.Instance, address);
            Assert.Equal(Null.Instance, city);
            Assert.Equal(Null.Instance, length);

            Assert.Equal(Null.Instance, output.Get("Count1"));
            Assert.Equal(Undefined.Instance, output.Get("Count2"));
        }
Exemplo n.º 5
0
    void Awake()
    {
//         string path = "file://"+Application.streamingAssetsPath + "/JavaScript/RotateObject.javascript";
//         WWW w = new WWW(path);
//         while (true)
//         {
//             if (w.isDone)
//                 break;
//         }
//         Debug.Log(w.text);
//         return;
// #if UNITY_EDITOR_WIN
//         Debug.Log("windows editor");
//         return;
// #endif


        DontDestroyOnLoad(gameObject);

        JSMgr.useReflection = false;// this.useReflection;
        if (JSMgr.InitJSEngine())
        {
            inited = true;
            inst   = this;
            Debug.Log("----------InitJSEngine OK ---");
        }
        else
        {
            Debug.Log("----------InitJSEngine FAIL ---");
        }
    }
Exemplo n.º 6
0
        public void ShouldCatchAllClrExceptions()
        {
            string exceptionMessage = "myExceptionMessage";

            var engine = new JSEngine(o => o.CatchClrExceptions())
                         .SetValue("throwMyException", new Action(() => { throw new Exception(exceptionMessage); }))
                         .SetValue("Thrower", typeof(Thrower))
                         .Execute(@"
                    function throwException1(){
                        try {
                            throwMyException();
                            return '';
                        } 
                        catch(e) {
                            return e.message;
                        }
                    }

                    function throwException2(){
                        try {
                            new Thrower().ThrowExceptionWithMessage('myExceptionMessage');
                            return;
                        } 
                        catch(e) {
                            return e.message;
                        }
                    }
                ");

            Assert.Equal(engine.Invoke("throwException1").AsString(), exceptionMessage);
            Assert.Equal(engine.Invoke("throwException2").AsString(), exceptionMessage);
        }
Exemplo n.º 7
0
        public void ShouldNotCatchClrExceptions()
        {
            var engine = new JSEngine()
                         .SetValue("throwMyException", new Action(() => { throw new NotSupportedException(); }))
                         .SetValue("Thrower", typeof(Thrower))
                         .Execute(@"
                    function throwException1(){
                        try {
                            throwMyException();
                            return;
                        } 
                        catch(e) {
                            return;
                        }
                    }

                    function throwException2(){
                        try {
                            new Thrower().ThrowNotSupportedException();
                            return;
                        } 
                        catch(e) {
                            return;
                        }
                    }
                ");

            Assert.ThrowsAny <NotSupportedException>(() => engine.Invoke("throwException1"));
            Assert.ThrowsAny <NotSupportedException>(() => engine.Invoke("throwException2"));
        }
Exemplo n.º 8
0
        public static void CheckObjectCoercible(JSEngine engine, JsValue o, MemberExpression expression,
                                                object baseReference)
        {
            if (o != Undefined.Instance && o != Null.Instance)
            {
                return;
            }

            if (engine.Options._ReferenceResolver != null &&
                engine.Options._ReferenceResolver.CheckCoercible(o))
            {
                return;
            }

            var message   = string.Empty;
            var reference = baseReference as Reference;

            if (reference != null)
            {
                message = $"{reference.GetReferencedName()} is {o}";
            }

            throw new JavaScriptException(engine.TypeError, message)
                  .SetCallstack(engine, expression.Location);
        }
Exemplo n.º 9
0
 protected FunctionInstance(JSEngine engine, string[] parameters, LexicalEnvironment scope, bool strict) : base(engine)
 {
     _engine          = engine;
     FormalParameters = parameters;
     Scope            = scope;
     Strict           = strict;
 }
Exemplo n.º 10
0
    // FirstInit may be called from JSComponent!
    public static void FirstInit(JSEngine jse = null)
    {
        if (!initSuccess && !initFail)
        {
            if (jse == null)
            {
                GameObject jseGO = GameObject.Find("_JSEngine");
                if (jseGO == null)
                {
                    initFail = true;
                    Debug.LogError("_JSEngine gameObject not found. Drag a \"JSBinding/Prefabs/_JSEngine.prefab\" to the scene.");
                }
                else
                {
                    jse = jseGO.GetComponent<JSEngine>();
                }
            }

            if (jse != null)
            {
                /*
                * Don't destroy this GameObject on load
                */
                DontDestroyOnLoad(jse.gameObject);
                inst = jse;

                JSMgr.InitJSEngine(jse.jsLoader, jse.OnInitJSEngine);
            }
        }
    }
Exemplo n.º 11
0
 /// <summary>
 /// 初始化
 /// </summary>
 private void Init()
 {
     // 工作对应的线程
     _work_lk_thread = new ConcurrentDictionary <Work, Thread>();
     // 引擎 注入执行器
     _engine = new JSEngine(typeof(Executor).Assembly);
 }
Exemplo n.º 12
0
 public static void CheckObjectCoercible(JSEngine engine, JsValue o)
 {
     if (o == Undefined.Instance || o == Null.Instance)
     {
         throw new JavaScriptException(engine.TypeError);
     }
 }
Exemplo n.º 13
0
        public static JsValue FromPropertyDescriptor(JSEngine engine, PropertyDescriptor desc)
        {
            if (desc == Undefined)
            {
                return(Native.Undefined.Instance);
            }

            var obj = engine.Object.Construct(Arguments.Empty);

            if (desc.IsDataDescriptor())
            {
                obj.DefineOwnProperty("value", new PropertyDescriptor(value: desc.Value != null ? desc.Value : Native.Undefined.Instance, writable: true, enumerable: true, configurable: true), false);
                obj.DefineOwnProperty("writable", new PropertyDescriptor(value: desc.Writable.HasValue && desc.Writable.Value, writable: true, enumerable: true, configurable: true), false);
            }
            else
            {
                obj.DefineOwnProperty("get", new PropertyDescriptor(desc.Get ?? Native.Undefined.Instance, writable: true, enumerable: true, configurable: true), false);
                obj.DefineOwnProperty("set", new PropertyDescriptor(desc.Set ?? Native.Undefined.Instance, writable: true, enumerable: true, configurable: true), false);
            }

            obj.DefineOwnProperty("enumerable", new PropertyDescriptor(value: desc.Enumerable.HasValue && desc.Enumerable.Value, writable: true, enumerable: true, configurable: true), false);
            obj.DefineOwnProperty("configurable", new PropertyDescriptor(value: desc.Configurable.HasValue && desc.Configurable.Value, writable: true, enumerable: true, configurable: true), false);

            return(obj);
        }
Exemplo n.º 14
0
        public static ObjectInstance ToObject(JSEngine engine, JsValue value)
        {
            if (value.IsObject())
            {
                return(value.AsObject());
            }

            if (value == Undefined.Instance)
            {
                throw new JavaScriptException(engine.TypeError);
            }

            if (value == Null.Instance)
            {
                throw new JavaScriptException(engine.TypeError);
            }

            if (value.IsBoolean())
            {
                return(engine.Boolean.Construct(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(engine.Number.Construct(value.AsNumber()));
            }

            if (value.IsString())
            {
                return(engine.String.Construct(value.AsString()));
            }

            throw new JavaScriptException(engine.TypeError);
        }
Exemplo n.º 15
0
 public SamplesTests()
 {
     _engine = new JSEngine()
               .SetValue("log", new Action <object>(Console.WriteLine))
               .SetValue("assert", new Action <bool>(Assert.True))
     ;
 }
Exemplo n.º 16
0
        public static JsonInstance CreateJsonObject(JSEngine engine)
        {
            var json = new JsonInstance(engine);

            json.Prototype = engine.Object.PrototypeObject;
            return(json);
        }
Exemplo n.º 17
0
 public bool TryGetCallable(JSEngine JSEngine, object reference, out JsValue value)
 {
     value = new JsValue(
         new ClrFunctionInstance(JSEngine, (thisObj, values) => thisObj)
         );
     return(true);
 }
Exemplo n.º 18
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-13.2
        /// </summary>
        /// <param name="engine"></param>
        /// <param name="functionDeclaration"></param>
        /// <param name="scope"></param>
        /// <param name="strict"></param>
        public ScriptFunctionInstance(JSEngine engine, IFunctionDeclaration functionDeclaration, LexicalEnvironment scope, bool strict)
            : base(engine, functionDeclaration.Parameters.Select(x => x.Name).ToArray(), scope, strict)
        {
            _functionDeclaration = functionDeclaration;

            Engine     = engine;
            Extensible = true;
            Prototype  = engine.Function.PrototypeObject;

            DefineOwnProperty("length", new PropertyDescriptor(new JsValue(FormalParameters.Length), false, false, false), false);

            var proto = engine.Object.Construct(Arguments.Empty);

            proto.DefineOwnProperty("constructor", new PropertyDescriptor(this, true, false, true), false);
            DefineOwnProperty("prototype", new PropertyDescriptor(proto, true, false, false), false);
            if (_functionDeclaration.Id != null)
            {
                DefineOwnProperty("name", new PropertyDescriptor(_functionDeclaration.Id.Name, null, null, null), false);
            }

            if (strict)
            {
                var thrower = engine.Function.ThrowTypeError;
                DefineOwnProperty("caller", new PropertyDescriptor(thrower, thrower, false, false), false);
                DefineOwnProperty("arguments", new PropertyDescriptor(thrower, thrower, false, false), false);
            }
        }
Exemplo n.º 19
0
        public void NullPropagationShouldNotAffectOperators()
        {
            var JSEngine = new JSEngine(cfg => cfg.SetReferencesResolver(new NullPropagationReferenceResolver()));

            var jsObject = JSEngine.Object.Construct(Arguments.Empty);

            jsObject.Put("NullField", JsValue.Null, true);

            var script = @"
this.is_nullfield_not_null = this.NullField !== null;
this.is_notnullfield_not_null = this.NotNullField !== null;
this.has_emptyfield_not_null = this.EmptyField !== null;
";

            var wrapperScript = string.Format(@"function ExecutePatchScript(docInner){{ (function(doc){{ {0} }}).apply(docInner); }};", script);

            JSEngine.Execute(wrapperScript, new ParserOptions
            {
                Source = "main.js"
            });

            JSEngine.Invoke("ExecutePatchScript", jsObject);

            Assert.False(jsObject.Get("is_nullfield_not_null").AsBoolean());
            Assert.True(jsObject.Get("is_notnullfield_not_null").AsBoolean());
            Assert.True(jsObject.Get("has_emptyfield_not_null").AsBoolean());
        }
Exemplo n.º 20
0
    // FirstInit may be called from JSComponent!
    public static void FirstInit(JSEngine jse = null)
    {
        if (!initSuccess && !initFail)
        {
            if (jse == null)
            {
                GameObject jseGO = GameObject.Find("_JSEngine");
                if (jseGO == null)
                {
                    initFail = true;
                    Debug.LogError("_JSEngine gameObject not found. Drag a \"JSBinding/Prefabs/_JSEngine.prefab\" to the scene.");
                }
                else
                {
                    jse = jseGO.GetComponent <JSEngine>();
                }
            }

            if (jse != null)
            {
                // ! Don't destroy this GameObject on load
                DontDestroyOnLoad(jse.gameObject);
                inst = jse;

                JSMgr.InitJSEngine(jse.jsLoader, jse.OnInitJSEngine);
            }
        }
    }
Exemplo n.º 21
0
        public VerifyCodeRes Verify(VerifyCodeReq req)
        {
            _VerifyCodeReq = req;
            var jsEngine = new JSEngine(Assembly.GetExecutingAssembly());
            var now      = jsEngine.Execute("TDC", "TDC.now").ToString();

            _HttpClient.Reset();
            _HttpClient.Url = VerifyURL.CombineParam(GetVerifyParam(now));
            foreach (var item in GetImageParam())
            {
                var requestParam = (RequestParam)item;
                if (requestParam.Key != "Random" && requestParam.Key != "ischartype" && requestParam.Key != "rand")
                {
                    _HttpClient.PostingData.Add(requestParam.Key, requestParam.Value);
                }
            }
            _HttpClient.PostingData.Add("subcapclass", "0");
            _HttpClient.PostingData.Add("cdata", "0");

            var begintime = now.Substring(0, now.Length - 3);
            var endtime   = (Convert.ToInt64(now) + 30000).ToString();

            endtime = endtime.Substring(0, endtime.Length - 3);
            var focusBlurin  = (Convert.ToInt64(now) + 16000).ToString();
            var focusBlurout = focusBlurin;
            var json         = "{\"mousemove\":[{\"t\":7,\"x\":206,\"y\":0},{\"t\":8,\"x\":203,\"y\":0},{\"t\":9,\"x\":204,\"y\":65},{\"t\":10,\"x\":240,\"y\":66},{\"t\":11,\"x\":240,\"y\":67}],\"mouseclick\":[{\"t\":8,\"x\":184,\"y\":76}],\"keyvalue\":[9,9,10,10],\"user_Agent\":\"chrome/56.0.2924.87\",\"resolutionx\":1280,\"resolutiony\":1024,\"winSize\":[300,152],\"url\":\"http://captcha.qq.com/cap_union_new_show\",\"refer\":\"http://xui.ptlogin2.qq.com/cgi-bin/xlogin\",\"begintime\":" + begintime + ",\"endtime\":" + endtime + ",\"platform\":1,\"os\":\"Win7\",\"keyboards\":4,\"flash\":1,\"pluginNum\":5,\"index\":1,\"ptcz\":\"\",\"tokenid\":262531355,\"btokenid\":null,\"tokents\":1487908779,\"ips\":{\"in\":[\"192.168.119.44\"]},\"colorDepth\":24,\"cookieEnabled\":true,\"timezone\":9,\"wDelta\":0,\"keyUpCnt\":4,\"keyUpValue\":[9,10,10,10],\"mouseUpValue\":[{\"t\":8,\"x\":184,\"y\":76},{\"t\":11,\"x\":235,\"y\":119}],\"mouseUpCnt\":2,\"mouseDownValue\":[{\"t\":8,\"x\":184,\"y\":74},{\"t\":11,\"x\":235,\"y\":119}],\"mouseDownCnt\":2,\"orientation\":[{\"x\":0,\"y\":0,\"z\":0}],\"bSimutor\":0,\"focusBlur\":{\"in\":[" + focusBlurin + "],\"out\":[" + focusBlurout + "],\"t\":[3136]},\"fVersion\":24,\"charSet\":\"UTF-8\",\"resizeCnt\":0,\"errors\":[],\"screenInfo\":\"1280-1024-984-24-*-*-*\",\"elapsed\":8000,\"clientType\":\"2\",\"trycnt\":1,\"refreshcnt\":0}               ";
            var collect      = jsEngine.Execute("TDC", "TDC.getData", json).ToString();

            _HttpClient.PostingData.Add("collect", collect);
            _HttpClient.PostingData.Add("ans", req.VerifyCode);
            return(_HttpClient.POST().GetVerifyCode());
        }
Exemplo n.º 22
0
 public ClrFunctionInstance(JSEngine engine, Func <JsValue, JsValue[], JsValue> func, int length)
     : base(engine, null, null, false)
 {
     _func     = func;
     Prototype = engine.Function.PrototypeObject;
     FastAddProperty("length", length, false, false, false);
     Extensible = true;
 }
Exemplo n.º 23
0
        public PropertyInfoDescriptor(JSEngine engine, PropertyInfo propertyInfo, object item)
        {
            _engine       = engine;
            _propertyInfo = propertyInfo;
            _item         = item;

            Writable = propertyInfo.CanWrite;
        }
Exemplo n.º 24
0
        public string Compile(string source)
        {
            var transpileResult = JSEngine.CallGlobalFunction("tsTranspile", source);
            var outputCode      = JSEngine.CallGlobalFunction <string>("getTranspileResultCode", transpileResult);

            //var outputDiagnostics = JSEngine.CallGlobalFunction<string>("getTranspileResultDiagnostics", transpileResult);
            return(outputCode);
        }
Exemplo n.º 25
0
 public void TestTDCJS()
 {
     var jsEngine  = new JSEngine(Assembly.GetExecutingAssembly());
     var begintime = DateTime.Now.Ticks;
     var endtime   = begintime + 4310;
     var json      = "{\"mousemove\":[{\"t\":78,\"x\":138,\"y\":148},{\"t\":115,\"x\":91,\"y\":145},{\"t\":116,\"x\":113,\"y\":105},{\"t\":117,\"x\":200,\"y\":81},{\"t\":118,\"x\":200,\"y\":81},{\"t\":119,\"x\":200,\"y\":81},{\"t\":120,\"x\":230,\"y\":121}],\"mouseclick\":[{\"t\":116,\"x\":176,\"y\":83}],\"keyvalue\":[117,117,118,118,118,119],\"user_Agent\":\"chrome/56.0.2924.87\",\"resolutionx\":1280,\"resolutiony\":1024,\"winSize\":[300,152],\"url\":\"http://captcha.qq.com/cap_union_new_show\",\"refer\":\"http://xui.ptlogin2.qq.com/cgi-bin/xlogin\",\"begintime\":" + begintime + ",\"endtime\":" + endtime + ",\"platform\":1,\"os\":\"Win7\",\"keyboards\":6,\"flash\":1,\"pluginNum\":5,\"index\":1,\"ptcz\":\"\",\"tokenid\":262531355,\"btokenid\":null,\"tokents\":1487908779,\"ips\":{\"in\":[\"192.168.119.44\"]},\"colorDepth\":24,\"cookieEnabled\":true,\"timezone\":9,\"wDelta\":0,\"keyUpCnt\":6,\"keyUpValue\":[117,117,118,118,118,119],\"mouseUpValue\":[{\"t\":116,\"x\":176,\"y\":83},{\"t\":120,\"x\":230,\"y\":121}],\"mouseUpCnt\":2,\"mouseDownValue\":[{\"t\":116,\"x\":176,\"y\":83},{\"t\":120,\"x\":230,\"y\":121}],\"mouseDownCnt\":2,\"orientation\":[{\"x\":0,\"y\":0,\"z\":0}],\"bSimutor\":0,\"focusBlur\":{\"in\":[1488243803410],\"out\":[1488243803410],\"t\":[3629]},\"fVersion\":24,\"charSet\":\"UTF-8\",\"resizeCnt\":0,\"errors\":[],\"screenInfo\":\"1280-1024-984-24-*-*-*\",\"elapsed\":37000,\"clientType\":\"2\",\"trycnt\":1,\"refreshcnt\":0}             ";
     var ss        = jsEngine.Execute("TDC", "TDC.getData", json);
 }
Exemplo n.º 26
0
        public FieldInfoDescriptor(JSEngine engine, FieldInfo fieldInfo, object item)
        {
            _engine    = engine;
            _fieldInfo = fieldInfo;
            _item      = item;

            Writable = !fieldInfo.Attributes.HasFlag(FieldAttributes.InitOnly); // don't write to fields marked as readonly
        }
Exemplo n.º 27
0
 public LoginClient()
 {
     _JsEngine   = new JSEngine(Assembly.GetExecutingAssembly());
     _Generate   = new Generate();
     _HttpClient = new DefaultHttpClient {
         KeepContext = true
     };
 }
Exemplo n.º 28
0
        public static GlobalObject CreateGlobalObject(JSEngine engine)
        {
            var global = new GlobalObject(engine)
            {
                Prototype = null, Extensible = true
            };

            return(global);
        }
Exemplo n.º 29
0
        public void GithubReadme1()
        {
            var square = new JSEngine()
                         .SetValue("x", 3)
                         .Execute("x * x")
                         .GetCompletionValue()
                         .ToObject();

            Assert.Equal(9d, square);
        }
Exemplo n.º 30
0
 void OnDestroy()
 {
     if (this == JSEngine.inst)
     {
         JSMgr.ShutdownJSEngine();
         JSEngine.inst      = null;
         JSEngine.initState = 0;
         Debug.Log("JS: JSEngine Destroy");
     }
 }
Exemplo n.º 31
0
        public static MathInstance CreateMathObject(JSEngine engine)
        {
            var math = new MathInstance(engine);

            math.Extensible = true;
            math.Prototype  = engine.Object.PrototypeObject;


            return(math);
        }
Exemplo n.º 32
0
    void Awake()
    {
        if (JSEngine.inst != null)
        {
            // destroy self
            Destroy(gameObject);
            return;
        }

        /*
         * Don't destroy this GameObject on load
         */
        DontDestroyOnLoad(gameObject);
        inst = this;

        JSMgr.InitJSEngine(jsLoader, OnInitJSEngine);
    }
Exemplo n.º 33
0
 void OnDestroy()
 {
     if (this == JSEngine.inst)
     {
         JSMgr.ShutdownJSEngine();
         if (mDebug)
             JSApi.cleanupDebugger();
         JSEngine.inst = null;
         JSEngine.inited = false;
         Debug.Log("JS: JSEngine Destroy");
     }
 }
Exemplo n.º 34
0
 //     void OnApplicationQuit()
 //     {
 //         Debug.Log("OnApplicationQuit");
 //     }
 void OnDestroy()
 {
     if (this == JSEngine.inst)
     {
         if (mDebug && initSuccess)
         {
             JSApi.cleanupDebugger();
         }
         JSMgr.ShutdownJSEngine();
         JSEngine.inst = null;
         JSEngine.initState = 0;
         Debug.Log("JS: JSEngine Destroy");
     }
 }