91 lines
2.9 KiB
C#
91 lines
2.9 KiB
C#
using Microsoft.AspNetCore.SignalR;
|
|
using Microsoft.CodeAnalysis.CSharp.Scripting;
|
|
using Microsoft.CodeAnalysis.Scripting;
|
|
using System.Reflection;
|
|
using System.Text.Json;
|
|
|
|
namespace Lab505.Script;
|
|
|
|
public class ScriptEngine
|
|
{
|
|
private readonly ScriptOptions _baseOptions;
|
|
private readonly IHubContext<ScriptHub> _hub;
|
|
|
|
public ScriptEngine(IHubContext<ScriptHub> hub, string[]? extraImports = null, Assembly[]? extraAssemblies = null)
|
|
{
|
|
_hub = hub;
|
|
|
|
var imports = new List<string>
|
|
{
|
|
"System",
|
|
"System.Threading",
|
|
"System.Threading.Tasks",
|
|
"Lab505.Script.Facades",
|
|
"Lab505.Shared",
|
|
};
|
|
if (extraImports != null) imports.AddRange(extraImports);
|
|
|
|
var refs = new List<Assembly>
|
|
{
|
|
typeof(Task).Assembly,
|
|
typeof(ScriptEngine).Assembly, // Lab505.Script itself
|
|
};
|
|
if (extraAssemblies != null) refs.AddRange(extraAssemblies);
|
|
|
|
_baseOptions = ScriptOptions.Default
|
|
.WithImports(imports)
|
|
.WithReferences(refs);
|
|
}
|
|
|
|
public async Task<string> ExecuteAsync(string code, object? globals = null, CancellationToken token = default,
|
|
string? userId = null)
|
|
{
|
|
var options = globals != null
|
|
? _baseOptions.AddReferences(globals.GetType().Assembly)
|
|
: _baseOptions;
|
|
|
|
var script = CSharpScript.Create(
|
|
code,
|
|
options: options,
|
|
globalsType: globals?.GetType()
|
|
);
|
|
|
|
var writer = new RealtimeWriter(_hub, userId);
|
|
|
|
// Set per-user Log on the globals (thread-safe — no global Console mutation)
|
|
if (globals is FlowContext sg) sg.Log = writer;
|
|
|
|
try
|
|
{
|
|
ScriptState<object>? state = globals != null
|
|
? await script.RunAsync(globals, token)
|
|
: await script.RunAsync(cancellationToken: token);
|
|
|
|
return state?.ReturnValue != null ? Pretty(state.ReturnValue) : "";
|
|
}
|
|
catch (CompilationErrorException ex)
|
|
{
|
|
writer.WriteLine("❌ Compile error:");
|
|
foreach (var d in ex.Diagnostics)
|
|
writer.WriteLine(" " + d);
|
|
return "";
|
|
}
|
|
}
|
|
|
|
private static string Pretty(object value)
|
|
{
|
|
var type = value.GetType();
|
|
if (type.IsPrimitive || value is string || value is decimal)
|
|
return value.ToString() ?? "";
|
|
if (type.IsArray)
|
|
return "[" + string.Join(", ", ((Array)value).Cast<object>()) + "]";
|
|
if (value is System.Collections.IEnumerable en)
|
|
{
|
|
var items = new List<string>();
|
|
foreach (var item in en) items.Add(item?.ToString() ?? "");
|
|
return "[" + string.Join(", ", items) + "]";
|
|
}
|
|
return JsonSerializer.Serialize(value);
|
|
}
|
|
}
|