Ejemplo n.º 1
0
        private void AddProperty(ObjectInstance instance, string name, DelegateWrapper delegateWrapper)
        {
            JsValue getter = JsValue.FromObject(_engine.JintEngine, delegateWrapper);
            JsValue setter = JsValue.Null;

            instance.DefineOwnProperty(name, new PropertyDescriptor(getter, setter, true, false), true);
        }
Ejemplo n.º 2
0
        public void ShouldWork()
        {
            var script = @"
function execute(doc, args)
{
    var i = doc;
    {
        function doSomething() {
            return ""ayende"";
        }

        i.Name = doSomething();
    }
}
";
            var engine = new Engine(options =>
            {
                options.Strict();
            });

            var args = new JsValue[1];
            var user = new User();

            args[0] = JsValue.FromObject(engine, user);

            engine.Execute(script);
            var call = engine.GetValue("execute").TryCast <ICallable>();

            call.Call(Undefined.Instance, args);

            Assert.Equal("ayende", user.Name);
        }
Ejemplo n.º 3
0
        public ClrProperty(global::Jint.Engine engine, DomConverter converter, PropertyInfo property)
        {
            Get =
                property.GetMethod != null && property.GetMethod.IsPublic ?  new ClrFunctionInstance(engine, (jsThis, values) =>
            {
                var clrThis = converter.ConvertFromJs(jsThis);
                return(JsValue.FromObject(engine, property.GetValue(clrThis)));
            }) : null;

            var setter = new Lazy <Action <object, JsValue> >(() => CreateSetter(converter, property));

            Set =
                property.SetMethod != null && property.SetMethod.IsPublic ? new ClrFunctionInstance(engine, (jsThis, values) =>
            {
                try
                {
                    var clrThis = converter.ConvertFromJs(jsThis);
                    if (values.Length == 0)
                    {
                        return(JsValue.Undefined);
                    }

                    setter.Value(clrThis, values[0]);

                    return(JsValue.Undefined);
                }
                catch (Exception e)
                {
                    throw new JavaScriptException(e.Message);
                }
            }) : new ClrFunctionInstance(engine, (value, values) => JsValue.Undefined);
        }
Ejemplo n.º 4
0
            protected override ExpressionResult EvaluateInternal(EvaluationContext context)
            {
                var left  = _left.GetValue(context).Value;
                var right = _right.GetValue(context).Value;

                if (context.OperatorOverloadingAllowed &&
                    TryOperatorOverloading(context, left, right, "op_Subtraction", out var opResult))
                {
                    return(NormalCompletion(JsValue.FromObject(context.Engine, opResult)));
                }

                JsValue number;

                left  = TypeConverter.ToNumeric(left);
                right = TypeConverter.ToNumeric(right);

                if (AreIntegerOperands(left, right))
                {
                    number = JsNumber.Create((long)left.AsInteger() - right.AsInteger());
                }
                else if (AreNonBigIntOperands(left, right))
                {
                    number = JsNumber.Create(left.AsNumber() - right.AsNumber());
                }
                else
                {
                    number = JsBigInt.Create(TypeConverter.ToBigInt(left) - TypeConverter.ToBigInt(right));
                }

                return(NormalCompletion(number));
            }
Ejemplo n.º 5
0
            protected override ExpressionResult EvaluateInternal(EvaluationContext context)
            {
                var left  = _left.GetValue(context).Value;
                var right = _right.GetValue(context).Value;

                JsValue result;

                if (context.OperatorOverloadingAllowed &&
                    TryOperatorOverloading(context, left, right, "op_Multiply", out var opResult))
                {
                    result = JsValue.FromObject(context.Engine, opResult);
                }
                else if (AreIntegerOperands(left, right))
                {
                    result = JsNumber.Create((long)left.AsInteger() * right.AsInteger());
                }
                else
                {
                    var leftNumeric  = TypeConverter.ToNumeric(left);
                    var rightNumeric = TypeConverter.ToNumeric(right);

                    if (leftNumeric.IsNumber() && rightNumeric.IsNumber())
                    {
                        result = JsNumber.Create(leftNumeric.AsNumber() * rightNumeric.AsNumber());
                    }
                    else
                    {
                        AssertValidBigIntArithmeticOperands(context, leftNumeric, rightNumeric);
                        result = JsBigInt.Create(leftNumeric.AsBigInt() * rightNumeric.AsBigInt());
                    }
                }

                return(NormalCompletion(result));
            }
Ejemplo n.º 6
0
        public bool TryConvert(Engine engine, object value, out JsValue result)
        {
            result = null;

            if (value is Enum)
            {
                result = value.ToString();
                return(true);
            }

            switch (value)
            {
            case IUser user:
                result = JintUser.Create(engine, user);
                return(true);

            case ClaimsPrincipal principal:
                result = JintUser.Create(engine, principal);
                return(true);

            case Instant instant:
                result = JsValue.FromObject(engine, instant.ToDateTimeUtc());
                return(true);

            case Status status:
                result = status.ToString();
                return(true);

            case NamedContentData content:
                result = new ContentDataObject(engine, content);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 7
0
        private IEnumerable <KeyValuePair <string, PropertyDescriptor> > GetObjectProperties(ObjectWrapper objectWrapper)
        {
            var target = objectWrapper.Target;

            if (target is IDictionary dictionary)
            {
                foreach (DictionaryEntry entry in dictionary)
                {
                    var jsValue    = JsValue.FromObject(_scriptEngine, entry.Value);
                    var descriptor = new PropertyDescriptor(jsValue, false, false, false);
                    yield return(new KeyValuePair <string, PropertyDescriptor>(entry.Key.ToString(), descriptor));
                }
                yield break;
            }

            var type = target.GetType();

            if (target is Task task &&
                task.IsCompleted == false)
            {
                foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    if (property.CanRead == false)
                    {
                        continue;
                    }

                    if (property.Name == nameof(Task <int> .Result))
                    {
                        var taskResultDescriptor = JintPreventResolvingTasksReferenceResolver.GetRunningTaskResult(task);
                        yield return(new KeyValuePair <string, PropertyDescriptor>(property.Name, taskResultDescriptor));

                        continue;
                    }

                    var descriptor = new PropertyInfoDescriptor(_scriptEngine, property, target);
                    yield return(new KeyValuePair <string, PropertyDescriptor>(property.Name, descriptor));
                }
                yield break;
            }

            // look for properties
            foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (property.CanRead == false)
                {
                    continue;
                }

                var descriptor = new PropertyInfoDescriptor(_scriptEngine, property, target);
                yield return(new KeyValuePair <string, PropertyDescriptor>(property.Name, descriptor));
            }

            // look for fields
            foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
            {
                var descriptor = new FieldInfoDescriptor(_scriptEngine, field, target);
                yield return(new KeyValuePair <string, PropertyDescriptor>(field.Name, descriptor));
            }
        }
Ejemplo n.º 8
0
        private JsValue Json(object obj)
        {
            var engine = new Engine();

            return(engine.Json.Parse(engine.Global,
                                     new[] { JsValue.FromObject(engine, JsonConvert.SerializeObject(obj)), }));
        }
Ejemplo n.º 9
0
        public JsValue Compile(string sourceCode, string filePath)
        {
            var moduleObject = JsValue.FromObject(this.engine.engine, this);

            // moduleObject.AsObject().DefineOwnProperty("exports", new Runtime.Descriptors.PropertyDescriptor() {
            //     Get = new ClrFunctionInstance(engine.engine, (thisObj, args) => Exports),
            //     Set = new ClrFunctionInstance(engine.engine, (thisObj, args) => Exports = args.At(0)),
            //     Enumerable = true,
            //     Configurable = true,
            // }, throwOnError: true);

            engine.engine.Execute($@"
                ;(function (module, exports, __dirname, require) {{
                    {sourceCode}
                }})
            ").GetCompletionValue().As <FunctionInstance>().Call(
                JsValue.FromObject(this.engine.engine, this),
                new JsValue[] {
                moduleObject,
                this.Exports,
                Path.GetDirectoryName(filePath),
                new ClrFunctionInstance(this.engine.engine, filePath, (thisObj, arguments) => Require(arguments.At(0).AsString()))
                //  new DelegateWrapper(engine.engine, new Func<string, JsValue>(this.Require)),
            }
                );

            return(Exports);
        }
Ejemplo n.º 10
0
        public void Test1()
        {
            var engine = new Engine();

            engine.Execute("function add(a, b) { return a + b; }");
            var v1 = engine.GetValue("add");
            var v2 = engine.GetValue("non-existant");

            _output.WriteLine($"{v1.Type}");
            _output.WriteLine($"{v2.Type}");
            var v3 = v1.Invoke(1, 2);

            _output.WriteLine($"{v3.Type}");
            _output.WriteLine($"{v3.AsNumber()}");
            var v4 = JsValue.FromObject(engine, null);

            _output.WriteLine($"{v4.Type}");

            var js_obj_raw = new TestObj1()
            {
                Id = 10, Content = "Hello!"
            };
            var v5 = JsValue.FromObject(engine, js_obj_raw);

            _output.WriteLine($"{v5.Type}");
            var v6 = v5.AsObject().Get(JsValue.FromObject(engine, "content"));

            _output.WriteLine($"{v6.Type}");
            _output.WriteLine($"{v6.AsString()}");
        }
Ejemplo n.º 11
0
        /// <inheritDoc />
        public object Invoke(params object[] args)
        {
            var jsThis = _binding == null ? JsValue.Null : _binding;

            var argsLength = args?.Length ?? 0;
            var jsArgs     = new JsValue[argsLength];

            for (int i = 0; i < argsLength; ++i)
            {
                jsArgs[i] = JsValue.FromObject(_context.Engine, args[i]);
            }

            try
            {
                var result = _callback(jsThis, jsArgs);
                return(result.ToObject());
            }
            catch (JavaScriptException jsError)
            {
                Log.Warning("Scripting", "[{0}:{1}] {2}", jsError.Location.Source, jsError.LineNumber, jsError.Message);
                ExecutionError = jsError;
            }
            catch (Exception exception)
            {
                // TODO: Most recent js stack trace?
                Log.Warning("Scripting", "An unknown error has occured: {0}", exception);
                ExecutionError = exception;
            }
            return(null);
        }
Ejemplo n.º 12
0
        public void ExecuteModule(string entryPointModuleIdentifier)
        {
            var sourceCode      = resourceLoader.Load(new Uri("resm:RaisingStudio.NativeScript.require.js"));
            var requireFunction = this.Execute(sourceCode, "require.js").GetCompletionValue();
            var require         = requireFunction.Invoke(this.applicationPath, JsValue.FromObject(this, new Func <string, string, object>(this.CreateModuleFunction)));

            require.Invoke("./");
        }
Ejemplo n.º 13
0
        private CliApiBuilder AddProperty(string name, DelegateWrapper delegateWrapper)
        {
            JsValue getter = JsValue.FromObject(_engine, delegateWrapper);
            JsValue setter = JsValue.Null;

            _instance.DefineOwnProperty(name, new PropertyDescriptor(getter, setter, true, false), true);
            return(this);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Loads this plugin
        /// </summary>
        public void Load()
        {
            // Load the plugin
            string code = File.ReadAllText(Filename);

            Name = Path.GetFileNameWithoutExtension(Filename);
            JavaScriptEngine.Execute(code);
            if (JavaScriptEngine.GetValue(Name).TryCast <ObjectInstance>() == null)
            {
                throw new Exception("Plugin is missing main object");
            }
            Class = JavaScriptEngine.GetValue(Name).AsObject();
            if (!Class.HasProperty("Name"))
            {
                Class.FastAddProperty("Name", Name, true, false, true);
            }
            else
            {
                Class.Put("Name", Name, true);
            }

            // Read plugin attributes
            if (!Class.HasProperty("Title") || string.IsNullOrEmpty(Class.Get("Title").AsString()))
            {
                throw new Exception("Plugin is missing title");
            }
            if (!Class.HasProperty("Author") || string.IsNullOrEmpty(Class.Get("Author").AsString()))
            {
                throw new Exception("Plugin is missing author");
            }
            if (!Class.HasProperty("Version") || Class.Get("Version").ToObject() == null)
            {
                throw new Exception("Plugin is missing version");
            }
            Title     = Class.Get("Title").AsString();
            Author    = Class.Get("Author").AsString();
            Version   = (VersionNumber)Class.Get("Version").ToObject();
            HasConfig = Class.HasProperty("HasConfig") && Class.Get("HasConfig").AsBoolean();

            // Set attributes
            Class.FastAddProperty("Plugin", JsValue.FromObject(JavaScriptEngine, this), true, false, true);

            Globals = new List <string>();
            foreach (var property in Class.Properties)
            {
                if (property.Value.Value != null)
                {
                    var callable = property.Value.Value.Value.TryCast <ICallable>();
                    if (callable != null)
                    {
                        Globals.Add(property.Key);
                    }
                }
            }

            // Bind any base methods (we do it here because we don't want them to be hooked)
            BindBaseMethods();
        }
Ejemplo n.º 15
0
 public JsValue readJson(String path)
 {
     using (var reader = new StreamReader(formatPath(path)))
     {
         return(eng.Json.Parse(eng.Json, new JsValue[] {
             JsValue.FromObject(eng, reader.ReadToEnd( ))
         }));
     }
 }
Ejemplo n.º 16
0
        /// <inheritDoc />
        public void Bind(object @this)
        {
            if (null != _binding)
            {
                return;
            }

            _binding = JsValue.FromObject(_context.Engine, @this);
        }
Ejemplo n.º 17
0
        public JsValue EvaluateLiteral(Literal literal)
        {
            if (literal.Type == SyntaxNodes.RegularExpressionLiteral)
            {
                return(_engine.RegExp.Construct(literal.Raw));
            }

            return(JsValue.FromObject(_engine, literal.Value));
        }
Ejemplo n.º 18
0
        public JsValue getString(String URL)
        {
            using (var client = new WebClient( ))
            {
                client.Headers.Set("user-agent", UA);

                return(JsValue.FromObject(eng, client.DownloadString(URL)));
            }
        }
Ejemplo n.º 19
0
        public ObjectInstance Construct(JsValue[] arguments)
        {
            if (arguments.Length == 0 &&
#if NETPORTABLE
                Type.IsValueType)
#else
                Type.IsValueType())
#endif
            {
                var instance = Activator.CreateInstance(Type);
                var result   = TypeConverter.ToObject(Engine, JsValue.FromObject(Engine, instance));

                return(result);
            }

            var constructors = Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);

            var methods = TypeConverter.FindBestMatch(Engine, constructors, arguments).ToList();

            foreach (var method in methods)
            {
                var parameters = new object[arguments.Length];
                try
                {
                    for (var i = 0; i < arguments.Length; i++)
                    {
                        var parameterType = method.GetParameters()[i].ParameterType;

                        if (parameterType == typeof(JsValue))
                        {
                            parameters[i] = arguments[i];
                        }
                        else
                        {
                            parameters[i] = Engine.ClrTypeConverter.Convert(
                                arguments[i].ToObject(),
                                parameterType,
                                CultureInfo.InvariantCulture);
                        }
                    }

                    var constructor = (ConstructorInfo)method;
                    var instance    = constructor.Invoke(parameters.ToArray());
                    var result      = TypeConverter.ToObject(Engine, JsValue.FromObject(Engine, instance));

                    // todo: cache method info

                    return(result);
                }
                catch
                {
                    // ignore method
                }
            }

            throw new JavaScriptException(Engine.TypeError, "No public methods with the specified arguments were found.");
        }
Ejemplo n.º 20
0
        private void CustomResultHandler(MulticastDelegate resultHander, KApiResponse response)
        {
            var func   = resultHander.Target as ScriptFunctionInstance;
            var result = func.Call(func, new[] { JsValue.FromObject(func.Engine, response.Code), JsValue.FromObject(func.Engine, response.Data) }).ToObject();

            if (result != null)
            {
                _renderContext.Response.AppendString(Helpers.ToJson(result));
            }
        }
Ejemplo n.º 21
0
        public static Jint.Native.Array.ArrayInstance ToJavaScriptArray(List <object> values, Jint.Engine engine)
        {
            var jsValues = new List <JsValue>();

            foreach (var v in values)
            {
                jsValues.Add(JsValue.FromObject(engine, v));
            }
            return((ArrayInstance)engine.Array.Construct(jsValues.ToArray()));
        }
Ejemplo n.º 22
0
        public void Restore(String refer, Object args)
        {
            var func = GetFunc(refer, "Restore");

            if (func == null)
            {
                return;
            }
            func(JsValue.Undefined, new JsValue[] { JsValue.FromObject(_engine, args) });
        }
Ejemplo n.º 23
0
        void SetArguments(Object args)
        {
            var func = GetFunc(_root.Id, "Arguments");

            if (func == null)
            {
                throw new WorkflowException($"Script element {_root.Id}.Arguments not found");
            }
            func(JsValue.Undefined, new JsValue[] { JsValue.FromObject(_engine, args) });
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Called when it's time to call a hook
        /// </summary>
        /// <param name="hookname"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected override object OnCallHook(string hookname, object[] args)
        {
            ICallable callable;

            if (!Globals.TryGetValue(hookname, out callable))
            {
                return(null);
            }
            return(callable.Call(Class, args != null ? args.Select(x => JsValue.FromObject(JavaScriptEngine, x)).ToArray() : new JsValue[] {}).ToObject());
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Calls a function by the given name and returns the output
        /// </summary>
        /// <param name="name"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private object CallFunction(string name, object[] args)
        {
            var callable = Class.Get(name).TryCast <ICallable>();

            if (!Globals.Contains(name) || !Class.HasProperty(name) || callable == null)
            {
                return(null);
            }
            return(callable.Call(Class, args != null ? args.Select(x => JsValue.FromObject(JavaScriptEngine, x)).ToArray() : new JsValue[] {}));
        }
Ejemplo n.º 26
0
        public JsValue getJson(String URL)
        {
            using (var client = new WebClient( ))
            {
                client.Headers.Set("user-agent", UA);

                var str = client.DownloadString(URL);
                return(eng.Json.Parse(eng.Json, new JsValue[] { JsValue.FromObject(eng, str) }));
            }
        }
Ejemplo n.º 27
0
        private JsValue ConstructValues(List <BlittableJsonReaderObject> values)
        {
            var items = new PropertyDescriptor[values.Count];

            for (int j = 0; j < values.Count; j++)
            {
                var val = values[j];

                if (JavaScriptIndexUtils.GetValue(Engine, val, out JsValue jsValue, true) == false)
                {
                    continue;
                }
                items[j] = new PropertyDescriptor(jsValue, true, true, true);
            }
            var jsArray = new ArrayInstance(Engine, items);

            jsArray.Prototype  = Engine.Array.PrototypeObject;
            jsArray.Extensible = false;

            var result = new ObjectInstance(Engine)
            {
                Extensible = true
            };

            result.Put("values", jsArray, false);
            if (_singleField)
            {
                var index = values[0].GetPropertyIndex(_groupByFields[0]);
                if (index != -1)
                {
                    BlittableJsonReaderObject.PropertyDetails prop = default;
                    values[0].GetPropertyByIndex(index, ref prop, addObjectToCache: false);
                    result.Put("key", JsValue.FromObject(Engine, prop.Value), false);
                }
            }
            else
            {
                var key = new ObjectInstance(Engine)
                {
                    Extensible = true
                };
                result.Put("key", key, false);
                for (int i = 0; i < _groupByFields.Length; i++)
                {
                    var index = values[0].GetPropertyIndex(_groupByFields[i]);
                    if (index != -1)
                    {
                        BlittableJsonReaderObject.PropertyDetails prop = default;
                        values[0].GetPropertyByIndex(index, ref prop, addObjectToCache: false);
                        key.Put(_groupByFields[i], JsValue.FromObject(Engine, prop.Value), false);
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 28
0
        public ObjectInstance Construct(JsValue[] arguments)
        {
            var constructors = Type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);

            var methods = TypeConverter.FindBestMatch(Engine, constructors, arguments).ToList();

            var parameters = new object[arguments.Length];

            foreach (var method in methods)
            {
                try
                {
                    for (var i = 0; i < arguments.Length; i++)
                    {
                        var parameterType = method.GetParameters()[i].ParameterType;

                        if (parameterType == typeof(JsValue))
                        {
                            parameters[i] = arguments[i];
                        }
                        else
                        {
                            parameters[i] = Engine.ClrTypeConverter.Convert(
                                arguments[i].ToObject(),
                                parameterType,
                                CultureInfo.InvariantCulture);
                        }
                    }

                    var constructor = (ConstructorInfo)method;
                    var result      = TypeConverter.ToObject(Engine, JsValue.FromObject(Engine, constructor.Invoke(parameters.ToArray())));

                    // todo: cache method info

                    return(result);
                }
                catch
                {
                    // ignore method
                }
            }

            StringBuilder argumentLog = new StringBuilder(arguments.Length);

            for (int i = 0, len = arguments.Length; i < len; i++)
            {
                argumentLog.AppendLine(arguments[i].ToString());
            }

            throw new JavaScriptException(
                      Engine.TypeError,
                      string.Format("No public constructors with the specified arguments found on {0}:\n{1}",
                                    Type.Name,
                                    argumentLog));
        }
Ejemplo n.º 29
0
        private async Task GetReferencesAsync(ScriptExecutionContext context, DomainId appId, ClaimsPrincipal user, JsValue references, Action <JsValue> callback)
        {
            Guard.NotNull(callback, nameof(callback));

            var ids = new List <DomainId>();

            if (references.IsString())
            {
                ids.Add(DomainId.Create(references.ToString()));
            }
            else if (references.IsArray())
            {
                foreach (var value in references.AsArray())
                {
                    if (value.IsString())
                    {
                        ids.Add(DomainId.Create(value.ToString()));
                    }
                }
            }

            if (ids.Count == 0)
            {
                var emptyContents = Array.Empty <IEnrichedContentEntity>();

                callback(JsValue.FromObject(context.Engine, emptyContents));
                return;
            }

            context.MarkAsync();

            try
            {
                var app = await GetAppAsync(appId);

                var requestContext =
                    new Context(user, app).Clone(b => b
                                                 .WithoutContentEnrichment()
                                                 .WithUnpublished()
                                                 .WithoutTotal());

                var contentQuery = serviceProvider.GetRequiredService <IContentQueryService>();

                var contents = await contentQuery.QueryAsync(requestContext, Q.Empty.WithIds(ids), context.CancellationToken);

                // Reset the time contraints and other constraints so that our awaiting does not count as script time.
                context.Engine.ResetConstraints();

                callback(JsValue.FromObject(context.Engine, contents.ToArray()));
            }
            catch (Exception ex)
            {
                context.Fail(ex);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Invoke the current value as function.
        /// </summary>
        /// <param name="value">The function to call.</param>
        /// <param name="thisObj">The this value inside the function call.</param>
        /// <param name="arguments">The arguments of the function call.</param>
        /// <returns>The value returned by the function call.</returns>
        public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
        {
            var callable = value.TryCast <ICallable>();

            if (callable == null)
            {
                throw new ArgumentException("Can only invoke functions");
            }

            return(callable.Call(JsValue.FromObject(this, thisObj), arguments.Select(x => JsValue.FromObject(this, x)).ToArray()));
        }