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 _hub; public ScriptEngine(IHubContext hub, string[]? extraImports = null, Assembly[]? extraAssemblies = null) { _hub = hub; var imports = new List { "System", "System.Threading", "System.Threading.Tasks", "Lab505.Script.Facades", "Lab505.Shared", }; if (extraImports != null) imports.AddRange(extraImports); var refs = new List { 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 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? 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()) + "]"; if (value is System.Collections.IEnumerable en) { var items = new List(); foreach (var item in en) items.Add(item?.ToString() ?? ""); return "[" + string.Join(", ", items) + "]"; } return JsonSerializer.Serialize(value); } }