| | | 1 | | using System.Collections; |
| | | 2 | | using System.Dynamic; |
| | | 3 | | using Elsa.Extensions; |
| | | 4 | | using Elsa.Expressions.JavaScript.Options; |
| | | 5 | | using Jint; |
| | | 6 | | using Jint.Native; |
| | | 7 | | using Jint.Native.Object; |
| | | 8 | | using Jint.Runtime.Descriptors; |
| | | 9 | | using Microsoft.Extensions.Options; |
| | | 10 | | |
| | | 11 | | namespace Elsa.Expressions.JavaScript.Helpers; |
| | | 12 | | |
| | | 13 | | internal static class ObjectConverterHelper |
| | | 14 | | { |
| | | 15 | | |
| | | 16 | | |
| | | 17 | | public static object? ProcessVariableValue(Engine engine, object? variableValue) |
| | | 18 | | { |
| | 13 | 19 | | if (variableValue == null) |
| | 1 | 20 | | return null; |
| | | 21 | | |
| | 12 | 22 | | if (variableValue is not ExpandoObject expandoObject) |
| | 6 | 23 | | return variableValue; |
| | | 24 | | |
| | 6 | 25 | | return ConvertToJsObject(engine, expandoObject); |
| | | 26 | | } |
| | | 27 | | |
| | | 28 | | public static ObjectInstance ConvertToJsObject(Engine engine, IDictionary<string, object?> expando) |
| | | 29 | | { |
| | 6 | 30 | | var jsObject = engine.Intrinsics.Object.Construct([]); |
| | | 31 | | |
| | 46 | 32 | | foreach (var kvp in expando) |
| | | 33 | | { |
| | 17 | 34 | | var value = kvp.Value; |
| | 17 | 35 | | var jsValue = ConvertToJsValue(engine, value); |
| | 17 | 36 | | var propertyDescriptor = new PropertyDescriptor(jsValue, true, true, true); |
| | 17 | 37 | | jsObject.DefineOwnProperty(kvp.Key, propertyDescriptor); |
| | | 38 | | } |
| | | 39 | | |
| | 6 | 40 | | return jsObject; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | private static JsValue ConvertToJsValue(Engine engine, object? value) |
| | | 44 | | { |
| | 20 | 45 | | if (value == null) |
| | 0 | 46 | | return JsValue.Null; |
| | | 47 | | |
| | 20 | 48 | | if (value is IDictionary<string, object?> dict) |
| | 0 | 49 | | return ConvertToJsObject(engine, dict); |
| | | 50 | | |
| | 20 | 51 | | var valueType = value.GetType(); |
| | 20 | 52 | | if (valueType.IsCollectionType()) |
| | | 53 | | { |
| | 1 | 54 | | var list = (ICollection)value; |
| | 1 | 55 | | var jsArray = engine.Intrinsics.Array.Construct(list.Count); |
| | 1 | 56 | | var index = 0; |
| | | 57 | | |
| | 8 | 58 | | foreach (var item in list) |
| | 3 | 59 | | jsArray.Set(index++, ConvertToJsValue(engine, item), true); |
| | | 60 | | |
| | 1 | 61 | | return jsArray; |
| | | 62 | | } |
| | | 63 | | |
| | 19 | 64 | | if (value is string str) |
| | 7 | 65 | | return JsValue.FromObject(engine, str); |
| | | 66 | | |
| | 12 | 67 | | if (value is int or double or float or decimal) |
| | 7 | 68 | | return JsValue.FromObject(engine, Convert.ToDouble(value)); |
| | | 69 | | |
| | 5 | 70 | | if (value is bool b) |
| | 0 | 71 | | return JsValue.FromObject(engine, b); |
| | | 72 | | |
| | 5 | 73 | | return JsValue.FromObject(engine, value); |
| | | 74 | | } |
| | | 75 | | } |