private JsValue AddAttachment(JsValue self, JsValue[] args)
        {
            JsValue attachmentReference = null;
            string  name = null; // will preserve original name

            switch (args.Length)
            {
            case 2:
                if (args[0].IsString() == false)
                {
                    ThrowInvalidSriptMethodCall($"First argument of {Transformation.AddAttachment}(name, attachment) must be string");
                }

                name = args[0].AsString();
                attachmentReference = args[1];
                break;

            case 1:
                attachmentReference = args[0];
                break;

            default:
                ThrowInvalidSriptMethodCall($"{Transformation.AddAttachment} must have one or two arguments");
                break;
            }

            if (attachmentReference.IsNull())
            {
                return(self);
            }

            if (attachmentReference.IsString() == false || attachmentReference.AsString().StartsWith(Transformation.AttachmentMarker) == false)
            {
                var message =
                    $"{Transformation.AddAttachment}() method expects to get the reference to an attachment while it got argument of '{attachmentReference.Type}' type";

                if (attachmentReference.IsString())
                {
                    message += $" (value: '{attachmentReference.AsString()}')";
                }

                ThrowInvalidSriptMethodCall(message);
            }

            _currentRun.AddAttachment(self, name, attachmentReference);

            return(self);
        }
Exemplo n.º 2
0
        public static ObjectInstance ToObject(Engine 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.º 3
0
        private JsValue ScheduleTimeout(JsValue[] args, bool repeat)
        {
            if (args.Length == 0)
            {
                return(JsValue.Undefined);
            }
            JsValue vCb      = args[0];
            JsValue vTimeout = args.Length > 1 ? args[1] : new JsValue(0);

            JsValue[] cbArgs = args.Length > 2 ? args.Skip(2).ToArray() : new JsValue[0];

            ICallable cb;

            if (vCb.IsString())
            {
                cb = new DelegateWrapper(_engine, new Action(() => _engine.Eval.Call(JsValue.Undefined, cbArgs)));
            }
            else
            {
                cb = vCb.TryCast <ICallable>();
            }
            if (cb == null)
            {
                throw new JavaScriptException(_engine.TypeError, "argument 1 requires a function or a string");
            }

            int timeout = TypeConverter.ToInt32(vTimeout);
            //Logger.Debug("timeout {0}", timeout);
            //Logger.Debug("val {0}", vTimeout);
            Item item = new Item(cb, timeout, cbArgs, repeat);

            return(Schedule(item));
        }
Exemplo n.º 4
0
        /// <inheritdoc/>
        public override AnalysisValueIntermediateResult ObjectResultForResultRow(ICrmDataSourceRow row)
        {
            var objectResultArray = new List <JsValue>();

            foreach (AnalysisValueFunction func in this.Arguments)
            {
                AnalysisValueIntermediateResult res = func.ObjectResultForResultRow(row);
                if (res == null || !res.Complete)
                {
                    objectResultArray.Add(new JsValue(0));
                }
                else
                {
                    objectResultArray.Add(res.JavascriptResult);
                }
            }

            JsValue resultValue = this.JavascriptFunction.Invoke(objectResultArray.ToArray());

            if (resultValue.IsString())
            {
                return(new AnalysisValueIntermediateResult(resultValue.ToString()));
            }
            else if (resultValue.IsNumber())
            {
                return(new AnalysisValueIntermediateResult(resultValue.ToDouble()));
            }
            else
            {
                return(new AnalysisValueIntermediateResult(resultValue));
            }
        }
        private static string EnsureNonNullStringValue(JsValue parameter, string parameterName)
        {
            if (parameter != JsValue.Null &&
                parameter.IsString() &&
                (parameter.AsString() is { } value&&
                 !string.IsNullOrWhiteSpace(value)))
            {
                return(value);
            }

            if (parameter == JsValue.Null || parameter == JsValue.Undefined || parameter.IsString())
            {
                throw new ArgumentNullException(parameterName);
            }

            throw new ArgumentException("string expected", parameterName);
        }
        public static string AsString(this JsValue value)
        {
            if (!value.IsString())
            {
                ThrowWrongTypeException(value, "string");
            }

            return(value.ToString());
        }
        private void PrepareOutput(out string?newState, out string?newSharedState, out EmittedEventEnvelope[]?emittedEvents)
        {
            emittedEvents = _emitted.Count > 0 ? _emitted.ToArray() : null;
            _emitted.Clear();
            if (_definitionBuilder.IsBiState && _state.IsArray())
            {
                var arr = _state.AsArray();
                if (arr.TryGetValue(0, out var state))
                {
                    if (_state.IsString())
                    {
                        newState = _state.AsString();
                    }
                    else
                    {
                        newState = ConvertToStringHandlingNulls(_json, state);
                    }
                }
                else
                {
                    newState = "";
                }

                if (arr.TryGetValue(1, out var sharedState))
                {
                    newSharedState = ConvertToStringHandlingNulls(_json, sharedState);
                }
                else
                {
                    newSharedState = null;
                }
            }
            else if (_state.IsString())
            {
                newState       = _state.AsString();
                newSharedState = null;
            }
            else
            {
                newState       = ConvertToStringHandlingNulls(_json, _state);
                newSharedState = null;
            }
        }
Exemplo n.º 8
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);
            }
        }
Exemplo n.º 9
0
 public void SetUnderline(JsValue value)
 {
     if (value.IsString())
     {
         Font.Underline = _underline.FromString(value.AsString(), FontUnderlineType.None);
     }
     else
     {
         Font.Underline = value.ConvertToBoolean().GetValueOrDefault() ? FontUnderlineType.Single : FontUnderlineType.None;
     }
 }
 public string AsNativeString(JsValue jsValue)
 {
     if (jsValue.IsNull() || jsValue.IsUndefined())
     {
         return(null);
     }
     if (jsValue.IsString())
     {
         return(jsValue.AsString());
     }
     return(jsValue.ToString());
 }
Exemplo n.º 11
0
 private string SerializeRequest(Engine engine, JsValue value)
 {
     if (value.IsObject())
     {
         return(engine.Json.Stringify(engine.Json, new[] { value }).ConvertToString());
     }
     if (value.IsString())
     {
         return(value.ConvertToString());
     }
     return(null);
 }
Exemplo n.º 12
0
        private async Task GetReferencesAsync(ExecutionContext 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 emptyAssets = Array.Empty <IEnrichedAssetEntity>();

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

            context.MarkAsync();

            try
            {
                var app = await GetAppAsync(appId);

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

                var assetQuery = serviceProvider.GetRequiredService <IAssetQueryService>();

                var assets = await assetQuery.QueryAsync(requestContext, null, Q.Empty.WithIds(ids), context.CancellationToken);

                callback(JsValue.FromObject(context.Engine, assets.ToArray()));
            }
            catch (Exception ex)
            {
                context.Fail(ex);
            }
        }
Exemplo n.º 13
0
        public object ConvertFromJs(JsValue jsValue)
        {
            if (jsValue == _getEngine().Global)
            {
                return(_global);
            }

            if (jsValue.IsUndefined())
            {
                return(null);
            }

            if (jsValue.IsObject())
            {
                switch (jsValue.AsObject())
                {
                case IObjectWrapper wrapper:
                    return(wrapper.Target);

                case ClrPrototype proto:
                    return(proto);

                case ObjectInstance objInst:

                    //todo: instantiate object instead of distionary
                    return(objInst.GetOwnProperties().ToDictionary(x => x.Key, x =>
                                                                   ConvertFromJs(objInst.Get(x.Key))));
                }

                return(jsValue);
            }

            if (jsValue.IsBoolean())
            {
                return(jsValue.AsBoolean());
            }

            if (jsValue.IsString())
            {
                return(jsValue.AsString());
            }

            if (jsValue.IsNumber())
            {
                return(jsValue.AsNumber());
            }

            return(null);
        }
Exemplo n.º 14
0
        internal JToken ConvertBack(JTokenType type, JsValue value)
        {
            switch (type)
            {
            case JTokenType.Array:
                if (value.IsArray())
                {
                    var array = value.AsArray();
                    return(new JArray(array.Properties.Where(k => ArrayInstance.IsArrayIndex(new JsValue(k.Key))).Select(kvp => ConvertBack(kvp.Value.Value ?? JsValue.Null))));
                }
                break;

            case JTokenType.Boolean:
                if (value.IsBoolean())
                {
                    return(new JValue(value.AsBoolean()));
                }
                break;

            case JTokenType.Date:
                if (value.IsDate())
                {
                    return(new JValue(value.AsDate()));
                }
                break;

            case JTokenType.Float:
                if (value.IsNumber())
                {
                    return(new JValue((float)value.AsNumber()));
                }
                break;

            case JTokenType.Integer:
                if (value.IsNumber())
                {
                    return(new JValue((int)value.AsNumber()));
                }
                break;

            case JTokenType.String:
                if (value.IsString())
                {
                    return(JValue.CreateString(value.AsString()));
                }
                break;
            }
            return(ConvertBack(value));
        }
Exemplo n.º 15
0
 private string GetDebugValue(JsValue obj, bool recursive)
 {
     if (obj.IsString())
     {
         var debugValue = obj.ToString();
         return(recursive ? '"' + debugValue + '"' : debugValue);
     }
     if (obj.IsArray())
     {
         var sb      = new StringBuilder("[");
         var array   = obj.AsArray();
         var jsValue = (int)array.Get("length").AsNumber();
         for (var i = 0; i < jsValue; i++)
         {
             if (i != 0)
             {
                 sb.Append(",");
             }
             sb.Append(GetDebugValue(array.Get(i.ToString()), true));
         }
         sb.Append("]");
         return(sb.ToString());
     }
     if (obj.IsObject())
     {
         var result = new ScriptRunnerResult(this, obj);
         using (var jsonObj = result.TranslateToObject(_jsonCtx))
         {
             return(jsonObj.ToString());
         }
     }
     if (obj.IsBoolean())
     {
         return(obj.AsBoolean().ToString());
     }
     if (obj.IsNumber())
     {
         return(obj.AsNumber().ToString(CultureInfo.InvariantCulture));
     }
     if (obj.IsNull())
     {
         return("null");
     }
     if (obj.IsUndefined())
     {
         return("undefined");
     }
     return(obj.ToString());
 }
Exemplo n.º 16
0
        private static string GetErrorMessage(JsValue error)
        {
            if (error.IsObject())
            {
                var oi      = error.AsObject();
                var message = oi.Get("message").AsString();
                return(message);
            }
            if (error.IsString())
            {
                return(error.AsString());
            }

            return(error.ToString());
        }
Exemplo n.º 17
0
        private JsValue ToStringString(JsValue thisObj, JsValue[] arguments)
        {
            if (thisObj.IsString())
            {
                return(thisObj);
            }

            var s = TypeConverter.ToObject(_realm, thisObj) as StringInstance;

            if (ReferenceEquals(s, null))
            {
                ExceptionHelper.ThrowTypeError(_realm);
            }

            return(s.StringData);
        }
Exemplo n.º 18
0
        public void ShouldBeANumber()
        {
            var value = new JsValue(2);

            Assert.Equal(false, value.IsBoolean());
            Assert.Equal(false, value.IsArray());
            Assert.Equal(false, value.IsDate());
            Assert.Equal(false, value.IsNull());
            Assert.Equal(true, value.IsNumber());
            Assert.Equal(2, value.AsNumber());
            Assert.Equal(false, value.IsObject());
            Assert.Equal(true, value.IsPrimitive());
            Assert.Equal(false, value.IsRegExp());
            Assert.Equal(false, value.IsString());
            Assert.Equal(false, value.IsUndefined());
        }
Exemplo n.º 19
0
        private static bool EqualUnlikely(JsValue x, JsValue y)
        {
            if (x._type == InternalTypes.Null && y._type == InternalTypes.Undefined)
            {
                return(true);
            }

            if (x._type == InternalTypes.Undefined && y._type == InternalTypes.Null)
            {
                return(true);
            }

            if (x.IsNumber() && y.IsString())
            {
                return(Equal(x, TypeConverter.ToNumber(y)));
            }

            if (x.IsString() && y.IsNumber())
            {
                return(Equal(TypeConverter.ToNumber(x), y));
            }

            if (x.IsBoolean())
            {
                return(Equal(TypeConverter.ToNumber(x), y));
            }

            if (y.IsBoolean())
            {
                return(Equal(x, TypeConverter.ToNumber(y)));
            }

            const InternalTypes stringOrNumber = InternalTypes.String | InternalTypes.Integer | InternalTypes.Number;

            if (y.IsObject() && (x._type & stringOrNumber) != 0)
            {
                return(Equal(x, TypeConverter.ToPrimitive(y)));
            }

            if (x.IsObject() && ((y._type & stringOrNumber) != 0))
            {
                return(Equal(TypeConverter.ToPrimitive(x), y));
            }

            return(false);
        }
Exemplo n.º 20
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static bool ToBoolean(JsValue o)
        {
            if (o.IsObject())
            {
                return true;
            }

            if (o == Undefined.Instance || o == Null.Instance)
            {
                return false;
            }
            
            if (o.IsBoolean())
            {
                return o.AsBoolean();
            }

            if (o.IsNumber())
            {
                var n = o.AsNumber();
                if (n.Equals(0) || double.IsNaN(n))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

            if (o.IsString())
            {
                var s = o.AsString();
                if (String.IsNullOrEmpty(s))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }

            return true;
        }
Exemplo n.º 21
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static bool ToBoolean(JsValue o)
        {
            if (o.IsObject())
            {
                return(true);
            }

            if (o == Undefined.Instance || o == Null.Instance)
            {
                return(false);
            }

            if (o.IsBoolean())
            {
                return(o.AsBoolean());
            }

            if (o.IsNumber())
            {
                var n = o.AsNumber();
                if (n.Equals(0) || double.IsNaN(n))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }

            if (o.IsString())
            {
                var s = o.AsString();
                if (String.IsNullOrEmpty(s))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }

            return(true);
        }
Exemplo n.º 22
0
 public static KeyCode AsKeyCode(JsValue value)
 {
     if (value == null)
     {
         Logger.Warn("invalid keycode: " + value);
         return(KeyCode.None);
     }
     else if (value.IsNumber())
     {
         return((KeyCode)TypeConverter.ToInt32(value));
     }
     else if (value.IsString())
     {
         return(AsKeyCode(TypeConverter.ToString(value)));
     }
     Logger.Warn("invalid keycode: " + value);
     return(KeyCode.None);
 }
Exemplo n.º 23
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToString(JsValue o)
        {
            if (o == null)
            {
                return(null);
            }
            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o.IsString())
            {
                return(o.AsString());
            }

            if (o == Undefined.Instance)
            {
                return(Undefined.Text);
            }

            if (o == Null.Instance)
            {
                return(Null.Text);
            }

            if (o.IsBoolean())
            {
                return(o.AsBoolean() ? "true" : "false");
            }

            if (o.IsNumber())
            {
                return(NumberPrototype.ToNumberString(o.AsNumber()));
            }

            return(ToString(ToPrimitive(o, Types.String)));
        }
Exemplo n.º 24
0
        public static List <DomainId> ToIds(this JsValue?value)
        {
            var ids = new List <DomainId>();

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

            return(ids);
        }
Exemplo n.º 25
0
        public object UncastJsValue(JsValue value)
        {
            if (value.IsBoolean())
            {
                return(value.AsBoolean());
            }
            if (value.IsNumber())
            {
                return(value.AsNumber());
            }
            if (value.IsObject())
            {
                return(value.AsObject());
            }
            if (value.IsString())
            {
                return(value.AsString());
            }

            return(null);
        }
Exemplo n.º 26
0
        public static object GetItem(this Jint.Native.Array.ArrayInstance a, int index)
        {
            JsValue l = a.Get(index.ToString());

            if (l.IsNull())
            {
                return(null);
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsBoolean())
            {
                return(l.AsBoolean());
            }
            if (l.IsString())
            {
                return(l.AsString());
            }
            if (l.IsNumber())
            {
                return(l.AsNumber());
            }
            if (l.IsUndefined())
            {
                return("undefined");
            }
            if (l.IsObject())
            {
                return(l.AsObject());
            }
            if (l.IsRegExp())
            {
                return(l.AsObject());
            }

            throw new ArgumentException(string.Format("Cannot deal with JsValue {0}", l));
        }
Exemplo n.º 27
0
        public static JToken Map(JsValue value)
        {
            if (value == null || value.IsNull())
            {
                return(JValue.CreateNull());
            }

            if (value.IsUndefined())
            {
                return(JValue.CreateUndefined());
            }

            if (value.IsString())
            {
                return(new JValue(value.AsString()));
            }

            if (value.IsBoolean())
            {
                return(new JValue(value.AsBoolean()));
            }

            if (value.IsNumber())
            {
                return(new JValue(value.AsNumber()));
            }

            if (value.IsDate())
            {
                return(new JValue(value.AsDate().ToDateTime()));
            }

            if (value.IsRegExp())
            {
                return(JValue.CreateString(value.AsRegExp().Value?.ToString()));
            }

            if (value.IsArray())
            {
                var arr = value.AsArray();

                var target = new JArray();

                for (var i = 0; i < arr.GetLength(); i++)
                {
                    target.Add(Map(arr.Get(i.ToString())));
                }

                return(target);
            }

            if (value.IsObject())
            {
                var obj = value.AsObject();

                var target = new JObject();

                foreach (var kvp in obj.GetOwnProperties())
                {
                    target[kvp.Key] = Map(kvp.Value.Value);
                }

                return(target);
            }

            throw new ArgumentException("Invalid json type.", nameof(value));
        }
Exemplo n.º 28
0
        private object ToBlittableValue(JsValue v, string propertyKey, bool recursiveCall)
        {
            if (v.IsBoolean())
            {
                return(v.AsBoolean());
            }

            if (v.IsString())
            {
                const string RavenDataByteArrayToBase64 = "raven-data:byte[];base64,";
                var          valueAsObject = v.ToObject();
                var          value         = valueAsObject?.ToString();
                if (value != null && value.StartsWith(RavenDataByteArrayToBase64))
                {
                    value = value.Remove(0, RavenDataByteArrayToBase64.Length);
                    var byteArray = Convert.FromBase64String(value);
                    return(Encoding.UTF8.GetString(byteArray));
                }
                return(value);
            }

            if (v.IsNumber())
            {
                var num = v.AsNumber();

                KeyValuePair <object, JsValue> property;
                if (_propertiesByValue.TryGetValue(propertyKey, out property))
                {
                    var originalValue = property.Key;
                    if (originalValue is float || originalValue is int)
                    {
                        // If the current value is exactly as the original value, we can return the original value before we made the JS conversion,
                        // which will convert a Int64 to jsFloat.
                        var jsValue = property.Value;
                        if (jsValue.IsNumber() && Math.Abs(num - jsValue.AsNumber()) < double.Epsilon)
                        {
                            return(originalValue);
                        }

                        //We might have change the type of num from Integer to long in the script by design
                        //Making sure the number isn't a real float before returning it as integer
                        if (originalValue is int && (Math.Abs(num - Math.Floor(num)) <= double.Epsilon || Math.Abs(num - Math.Ceiling(num)) <= double.Epsilon))
                        {
                            return((long)num);
                        }
                        return(num); //float
                    }
                }

                // If we don't have the type, assume that if the number ending with ".0" it actually an integer.
                var integer = Math.Truncate(num);
                if (Math.Abs(num - integer) < double.Epsilon)
                {
                    return((long)integer);
                }
                return(num);
            }
            if (v.IsNull() || v.IsUndefined())
            {
                return(null);
            }
            if (v.IsArray())
            {
                var jsArray = v.AsArray();
                var array   = new DynamicJsonArray();

                foreach (var property in jsArray.GetOwnProperties())
                {
                    if (InheritedProperties.Contains(property.Key))
                    {
                        continue;
                    }

                    var jsInstance = property.Value.Value;
                    if (!jsInstance.HasValue)
                    {
                        continue;
                    }

                    var ravenJToken = ToBlittableValue(jsInstance.Value, propertyKey + "[" + property.Key + "]", recursiveCall);
                    if (ravenJToken == null)
                    {
                        continue;
                    }

                    array.Add(ravenJToken);
                }

                return(array);
            }
            if (v.IsDate())
            {
                return(v.AsDate().ToDateTime());
            }
            if (v.IsObject())
            {
                return(ToBlittable(v.AsObject(), propertyKey, recursiveCall));
            }
            if (v.IsRegExp())
            {
                return(null);
            }

            throw new NotSupportedException(v.Type.ToString());
        }
Exemplo n.º 29
0
        private static object GetValue(JsValue jsValue)
        {
            if (jsValue.IsNull())
            {
                return(null);
            }
            if (jsValue.IsString())
            {
                return(jsValue.AsString());
            }
            if (jsValue.IsBoolean())
            {
                return(jsValue.AsBoolean());
            }
            if (jsValue.IsNumber())
            {
                return(jsValue.AsNumber());
            }
            if (jsValue.IsDate())
            {
                return(jsValue.AsDate());
            }
            if (jsValue is ObjectWrapper ow)
            {
                var target = ow.Target;
                switch (target)
                {
                case LazyStringValue lsv:
                    return(lsv);

                case LazyCompressedStringValue lcsv:
                    return(lcsv);

                case LazyNumberValue lnv:
                    return(lnv);    //should be already blittable supported type.
                }
                ThrowInvalidObject(jsValue);
            }
            else if (jsValue.IsArray())
            {
                var arr   = jsValue.AsArray();
                var array = new object[arr.GetLength()];
                var i     = 0;
                foreach ((var key, var val) in arr.GetOwnProperties())
                {
                    if (key == "length")
                    {
                        continue;
                    }

                    array[i++] = GetValue(val.Value);
                }

                return(array);
            }
            else if (jsValue.IsObject())
            {
                return(jsValue.AsObject());
            }
            if (jsValue.IsUndefined())
            {
                return(null);
            }

            ThrowInvalidObject(jsValue);
            return(null);
        }
Exemplo n.º 30
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.3
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static double ToNumber(JsValue o)
        {
            // check number first as this is what is usually expected
            if (o.IsNumber())
            {
                return o.AsNumber();
            } 
            
            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o == Undefined.Instance)
            {
                return double.NaN;
            }

            if (o == Null.Instance)
            {
                return 0;
            }

            if (o.IsBoolean())
            {
                return o.AsBoolean() ? 1 : 0;
            }

            if (o.IsString())
            {
                var s = o.AsString().Trim();

                if (String.IsNullOrEmpty(s))
                {
                    return 0;
                }

                if ("+Infinity".Equals(s) || "Infinity".Equals(s))
                {
                    return double.PositiveInfinity;
                }

                if ("-Infinity".Equals(s))
                {
                    return double.NegativeInfinity;
                }

                // todo: use a common implementation with JavascriptParser
                try
                {
                    if (!s.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        var start = s[0];
                        if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
                        {
                            return double.NaN;
                        }

                        double n = Double.Parse(s,
                            NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
                            NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
                            NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
                        if (s.StartsWith("-") && n.Equals(0))
                        {
                            return -0.0;
                        }

                        return n;
                    }

                    int i = int.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                 
                    return i;
                }
                catch (OverflowException)
                {
                    return s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
                }
                catch
                {
                    return double.NaN;
                }
            }

            return ToNumber(ToPrimitive(o, Types.Number));
        }
Exemplo n.º 31
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ToString(JsValue o)
        {
            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o.IsString())
            {
                return o.AsString();
            }

            if (o == Undefined.Instance)
            {
                return Undefined.Text;
            }

            if (o == Null.Instance)
            {
                return Null.Text;
            }
            
            if (o.IsBoolean())
            {
                return o.AsBoolean() ? "true" : "false";
            }

            if (o.IsNumber())
            {
                return NumberPrototype.ToNumberString(o.AsNumber());
            }

            return ToString(ToPrimitive(o, Types.String));
        }
Exemplo n.º 32
0
        public static ObjectInstance ToObject(Engine 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.º 33
0
        /// <summary>
        /// http://www.ecma-international.org/ecma-262/5.1/#sec-9.3
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static double ToNumber(JsValue o)
        {
            // check number first as this is what is usually expected
            if (o.IsNumber())
            {
                return(o.AsNumber());
            }

            if (o.IsObject())
            {
                var p = o.AsObject() as IPrimitiveInstance;
                if (p != null)
                {
                    o = p.PrimitiveValue;
                }
            }

            if (o == Undefined.Instance)
            {
                return(double.NaN);
            }

            if (o == Null.Instance)
            {
                return(0);
            }

            if (o.IsBoolean())
            {
                return(o.AsBoolean() ? 1 : 0);
            }

            if (o.IsString())
            {
                var s = StringPrototype.TrimEx(o.AsString());

                if (String.IsNullOrEmpty(s))
                {
                    return(0);
                }

                if ("+Infinity".Equals(s) || "Infinity".Equals(s))
                {
                    return(double.PositiveInfinity);
                }

                if ("-Infinity".Equals(s))
                {
                    return(double.NegativeInfinity);
                }

                // todo: use a common implementation with JavascriptParser
                try
                {
                    if (!s.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        var start = s[0];
                        if (start != '+' && start != '-' && start != '.' && !char.IsDigit(start))
                        {
                            return(double.NaN);
                        }

                        double n = Double.Parse(s,
                                                NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign |
                                                NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite |
                                                NumberStyles.AllowExponent, CultureInfo.InvariantCulture);
                        if (s.StartsWith("-") && n.Equals(0))
                        {
                            return(-0.0);
                        }

                        return(n);
                    }

                    int i = int.Parse(s.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);

                    return(i);
                }
                catch (OverflowException)
                {
                    return(s.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity);
                }
                catch
                {
                    return(double.NaN);
                }
            }

            return(ToNumber(ToPrimitive(o, Types.Number)));
        }
Exemplo n.º 34
0
        public JsValue Serialize(JsValue value, JsValue replacer, JsValue space)
        {
            _stack = new Stack<object>();

            // for JSON.stringify(), any function passed as the first argument will return undefined
            // if the replacer is not defined. The function is not called either.
            if (value.Is<ICallable>() && replacer == Undefined.Instance) 
            {
                return Undefined.Instance;
            }

            if (replacer.IsObject())
            {
                if (replacer.Is<ICallable>())
                {
                    _replacerFunction = replacer;
                }
                else
                {
                    var replacerObj = replacer.AsObject();
                    if (replacerObj.Class == "Array")
                    {
                        _propertyList = new List<string>();
                    }

                    foreach (var property in replacerObj.GetOwnProperties().Select(x => x.Value))
                    {
                        JsValue v = _engine.GetValue(property);
                        string item = null;
                        if (v.IsString())
                        {
                            item = v.AsString();
                        }
                        else if (v.IsNumber())
                        {
                            item = TypeConverter.ToString(v);
                        }
                        else if (v.IsObject())
                        {
                            var propertyObj = v.AsObject();
                            if (propertyObj.Class == "String" || propertyObj.Class == "Number")
                            {
                                item = TypeConverter.ToString(v);
                            }
                        }

                        if (item != null && !_propertyList.Contains(item))
                        {
                            _propertyList.Add(item);
                        }

                    }
                }
            }

            if (space.IsObject())
            {
                var spaceObj = space.AsObject();
                if (spaceObj.Class == "Number")
                {
                    space = TypeConverter.ToNumber(spaceObj);
                }
                else if (spaceObj.Class == "String")
                {
                    space = TypeConverter.ToString(spaceObj);
                }
            }

            // defining the gap
            if (space.IsNumber())
            {
                if (space.AsNumber() > 0) {
                    _gap = new System.String(' ', (int)System.Math.Min(10, space.AsNumber()));
                }
                else 
                {
                    _gap = string.Empty;
                }
            }
            else if (space.IsString())
            {
                var stringSpace = space.AsString();
                _gap = stringSpace.Length <= 10 ? stringSpace : stringSpace.Substring(0, 10);
            }
            else
            {
                _gap = string.Empty;
            }

            var wrapper = _engine.Object.Construct(Arguments.Empty);
            wrapper.DefineOwnProperty("", new PropertyDescriptor(value, true, true, true), false);

            return Str("", wrapper);
        }
Exemplo n.º 35
0
        private RavenJToken ToRavenJToken(JsValue v, string propertyKey, bool recursiveCall)
        {
            if (v.IsBoolean())
            {
                return(new RavenJValue(v.AsBoolean()));
            }
            if (v.IsString())
            {
                const string RavenDataByteArrayToBase64 = "raven-data:byte[];base64,";
                var          valueAsObject = v.ToObject();
                var          value         = valueAsObject != null?valueAsObject.ToString() : null;

                if (value != null && value.StartsWith(RavenDataByteArrayToBase64))
                {
                    value = value.Remove(0, RavenDataByteArrayToBase64.Length);
                    var byteArray = Convert.FromBase64String(value);
                    return(new RavenJValue(byteArray));
                }
                return(new RavenJValue(value));
            }
            if (v.IsNumber())
            {
                var num = v.AsNumber();

                KeyValuePair <RavenJValue, JsValue> property;
                if (propertiesByValue.TryGetValue(propertyKey, out property))
                {
                    var originalValue = property.Key;
                    if (originalValue.Type == JTokenType.Float ||
                        originalValue.Type == JTokenType.Integer)
                    {
                        // If the current value is exactly as the original value, we can return the original value before we made the JS conversion,
                        // which will convert a Int64 to jsFloat.
                        var originalJsValue = property.Value;
                        if (originalJsValue.IsNumber() && Math.Abs(num - originalJsValue.AsNumber()) < double.Epsilon)
                        {
                            return(originalValue);
                        }

                        if (originalValue.Type == JTokenType.Integer)
                        {
                            return(new RavenJValue((long)num));
                        }
                        return(new RavenJValue(num));//float
                    }
                }

                // If we don't have the type, assume that if the number ending with ".0" it actually an integer.
                var integer = Math.Truncate(num);
                if (Math.Abs(num - integer) < double.Epsilon)
                {
                    return(new RavenJValue((long)integer));
                }
                return(new RavenJValue(num));
            }
            if (v.IsNull())
            {
                return(RavenJValue.Null);
            }
            if (v.IsUndefined())
            {
                return(RavenJValue.Null);
            }
            if (v.IsArray())
            {
                var jsArray = v.AsArray();
                var rja     = new RavenJArray();

                foreach (var property in jsArray.Properties)
                {
                    if (property.Key == "length")
                    {
                        continue;
                    }

                    var jsInstance = property.Value.Value;
                    if (!jsInstance.HasValue)
                    {
                        continue;
                    }

                    var ravenJToken = ToRavenJToken(jsInstance.Value, propertyKey + "[" + property.Key + "]", recursiveCall);
                    if (ravenJToken == null)
                    {
                        continue;
                    }

                    rja.Add(ravenJToken);
                }

                return(rja);
            }
            if (v.IsObject())
            {
                return(ToRavenJObject(v, propertyKey, recursiveCall));
            }
            if (v.IsRegExp())
            {
                return(null);
            }

            throw new NotSupportedException(v.Type.ToString());
        }