2023-12-06 21:32:08 +00:00
|
|
|
using System.Dynamic;
|
2023-03-03 21:47:23 +00:00
|
|
|
using Elsa.Expressions.Contracts;
|
2023-11-14 19:44:42 +00:00
|
|
|
using Elsa.Expressions.Helpers;
|
2022-05-26 10:47:31 +00:00
|
|
|
using Elsa.Expressions.Models;
|
2023-02-13 11:15:20 +00:00
|
|
|
using Elsa.JavaScript.Contracts;
|
2023-12-06 21:32:08 +00:00
|
|
|
using Humanizer;
|
|
|
|
|
using Jint;
|
2022-01-12 10:43:46 +00:00
|
|
|
|
2022-05-26 10:47:31 +00:00
|
|
|
namespace Elsa.JavaScript.Expressions;
|
2022-01-12 10:43:46 +00:00
|
|
|
|
2023-05-08 20:38:59 +00:00
|
|
|
/// <summary>
|
|
|
|
|
/// Evaluates JavaScript expressions.
|
|
|
|
|
/// </summary>
|
2022-01-12 10:43:46 +00:00
|
|
|
public class JavaScriptExpressionHandler : IExpressionHandler
|
|
|
|
|
{
|
|
|
|
|
private readonly IJavaScriptEvaluator _javaScriptEvaluator;
|
|
|
|
|
|
2023-05-08 20:38:59 +00:00
|
|
|
/// <summary>
|
|
|
|
|
/// Initializes a new instance of the <see cref="JavaScriptExpressionHandler"/> class.
|
|
|
|
|
/// </summary>
|
2022-01-12 10:43:46 +00:00
|
|
|
public JavaScriptExpressionHandler(IJavaScriptEvaluator javaScriptEvaluator)
|
|
|
|
|
{
|
|
|
|
|
_javaScriptEvaluator = javaScriptEvaluator;
|
|
|
|
|
}
|
2023-05-08 20:38:59 +00:00
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
2023-12-06 21:32:08 +00:00
|
|
|
public async ValueTask<object?> EvaluateAsync(Expression expression, Type returnType, ExpressionExecutionContext context, ExpressionEvaluatorOptions options)
|
2022-01-12 10:43:46 +00:00
|
|
|
{
|
2023-11-14 19:44:42 +00:00
|
|
|
var javaScriptExpression = expression.Value.ConvertTo<string>() ?? "";
|
2023-12-06 21:32:08 +00:00
|
|
|
return await _javaScriptEvaluator.EvaluateAsync(javaScriptExpression, returnType, context, engine => ConfigureEngine(engine, options), context.CancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void ConfigureEngine(Engine engine, ExpressionEvaluatorOptions options)
|
|
|
|
|
{
|
|
|
|
|
var args = new ExpandoObject() as IDictionary<string, object>;
|
|
|
|
|
|
|
|
|
|
foreach (var (name, value) in options.Arguments)
|
|
|
|
|
args[name.Camelize()] = value;
|
|
|
|
|
|
|
|
|
|
engine.SetValue("args", args);
|
2022-01-12 10:43:46 +00:00
|
|
|
}
|
|
|
|
|
}
|