| | | 1 | | using System.Collections.Immutable; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Text; |
| | | 4 | | using Microsoft.CodeAnalysis.Scripting; |
| | | 5 | | using Microsoft.CodeAnalysis.VisualBasic; |
| | | 6 | | using Serilog.Events; |
| | | 7 | | using Microsoft.CodeAnalysis; |
| | | 8 | | using Kestrun.Utilities; |
| | | 9 | | using System.Security.Claims; |
| | | 10 | | using Kestrun.Logging; |
| | | 11 | | using Kestrun.Hosting; |
| | | 12 | | |
| | | 13 | | namespace Kestrun.Languages; |
| | | 14 | | |
| | | 15 | | internal static class VBNetDelegateBuilder |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// The marker that indicates where user code starts in the VB.NET script. |
| | | 19 | | /// This is used to ensure that the user code is correctly placed within the generated module. |
| | | 20 | | /// </summary> |
| | | 21 | | private const string StartMarker = "' ---- User code starts here ----"; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Builds a VB.NET delegate for Kestrun routes. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <remarks> |
| | | 27 | | /// This method uses the Roslyn compiler to compile the provided VB.NET code into a delegate. |
| | | 28 | | /// </remarks> |
| | | 29 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 30 | | /// <param name="code">The VB.NET code to compile.</param> |
| | | 31 | | /// <param name="args">The arguments to pass to the script.</param> |
| | | 32 | | /// <param name="extraImports">Optional additional namespaces to import in the script.</param> |
| | | 33 | | /// <param name="extraRefs">Optional additional assemblies to reference in the script.</param> |
| | | 34 | | /// <param name="languageVersion">The VB.NET language version to use for compilation.</param> |
| | | 35 | | /// <returns>A delegate that takes CsGlobals and returns a Task.</returns> |
| | | 36 | | /// <exception cref="CompilationErrorException">Thrown if the compilation fails with errors.</exception> |
| | | 37 | | /// <remarks> |
| | | 38 | | /// This method uses the Roslyn compiler to compile the provided VB.NET code into a delegate. |
| | | 39 | | /// </remarks> |
| | | 40 | | internal static RequestDelegate Build(KestrunHost host, |
| | | 41 | | string code, Dictionary<string, object?>? args, string[]? extraImports, |
| | | 42 | | Assembly[]? extraRefs, LanguageVersion languageVersion = LanguageVersion.VisualBasic16_9) |
| | | 43 | | { |
| | 5 | 44 | | var log = host.Logger; |
| | 5 | 45 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 46 | | { |
| | 2 | 47 | | log.Debug("Building VB.NET delegate, script length={Length}, imports={ImportsCount}, refs={RefsCount}, lang= |
| | 2 | 48 | | code.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | // Validate inputs |
| | 5 | 52 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 53 | | { |
| | 1 | 54 | | throw new ArgumentNullException(nameof(code), "VB.NET code cannot be null or whitespace."); |
| | | 55 | | } |
| | | 56 | | // 1. Compile the VB.NET code into a script |
| | | 57 | | // - Use VisualBasicScript.Create() to create a script with the provided code |
| | | 58 | | // - Use ScriptOptions to specify imports, references, and language version |
| | | 59 | | // - Inject the provided arguments into the globals |
| | 4 | 60 | | var script = Compile<bool>(host: host, code: code, extraImports: extraImports, extraRefs: extraRefs, null, langu |
| | | 61 | | |
| | | 62 | | // 2. Build the per-request delegate |
| | | 63 | | // - This delegate will be executed for each request |
| | | 64 | | // - It will create a KestrunContext and CsGlobals, then execute the script with these globals |
| | | 65 | | // - The script can access the request context and shared state store |
| | 4 | 66 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 67 | | { |
| | 2 | 68 | | log.Debug("C# delegate built successfully, script length={Length}, imports={ImportsCount}, refs={RefsCount}, |
| | 2 | 69 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 70 | | } |
| | | 71 | | |
| | 4 | 72 | | return async ctx => |
| | 4 | 73 | | { |
| | 4 | 74 | | try |
| | 4 | 75 | | { |
| | 3 | 76 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 77 | | { |
| | 1 | 78 | | log.Debug("Preparing execution for C# script at {Path}", ctx.Request.Path); |
| | 4 | 79 | | } |
| | 4 | 80 | | |
| | 3 | 81 | | var (Globals, Response, Context) = await DelegateBuilder.PrepareExecutionAsync(host, ctx, args).Configur |
| | 4 | 82 | | |
| | 4 | 83 | | // Execute the script with the current context and shared state |
| | 3 | 84 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 85 | | { |
| | 1 | 86 | | log.DebugSanitized("Executing VB.NET script for {Path}", ctx.Request.Path); |
| | 4 | 87 | | } |
| | 4 | 88 | | |
| | 3 | 89 | | _ = await script(Globals).ConfigureAwait(false); |
| | 3 | 90 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 91 | | { |
| | 1 | 92 | | log.DebugSanitized("VB.NET script executed successfully for {Path}", ctx.Request.Path); |
| | 4 | 93 | | } |
| | 4 | 94 | | |
| | 4 | 95 | | // Apply the response to the Kestrun context |
| | 3 | 96 | | await DelegateBuilder.ApplyResponseAsync(ctx, Response, log).ConfigureAwait(false); |
| | 3 | 97 | | } |
| | 4 | 98 | | finally |
| | 4 | 99 | | { |
| | 4 | 100 | | // Do not complete the response here; allow downstream middleware (e.g., StatusCodePages) |
| | 4 | 101 | | // to produce a body for status-only responses when needed. |
| | 4 | 102 | | } |
| | 7 | 103 | | }; |
| | | 104 | | } |
| | | 105 | | |
| | | 106 | | /// <summary> |
| | | 107 | | /// Decide the VB return type string that matches TResult |
| | | 108 | | /// </summary> |
| | | 109 | | /// <param name="t">The type to get the VB return type for.</param> |
| | | 110 | | /// <returns> The VB.NET return type as a string.</returns> |
| | | 111 | | private static string GetVbReturnType(Type t) |
| | | 112 | | { |
| | 16 | 113 | | if (t == typeof(bool)) |
| | | 114 | | { |
| | 10 | 115 | | return "Boolean"; |
| | | 116 | | } |
| | | 117 | | |
| | 6 | 118 | | if (t == typeof(IEnumerable<Claim>)) |
| | | 119 | | { |
| | 3 | 120 | | return "System.Collections.Generic.IEnumerable(Of System.Security.Claims.Claim)"; |
| | | 121 | | } |
| | | 122 | | |
| | | 123 | | // Fallback so it still compiles even for object / string / etc. |
| | 3 | 124 | | return "Object"; |
| | | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Compiles the provided VB.NET code into a delegate that can be executed with CsGlobals. |
| | | 129 | | /// </summary> |
| | | 130 | | /// <typeparam name="TResult">The type of the result returned by the delegate.</typeparam> |
| | | 131 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 132 | | /// <param name="code">The VB.NET code to compile.</param> |
| | | 133 | | /// <param name="extraImports">Optional additional namespaces to import in the script.</param> |
| | | 134 | | /// <param name="extraRefs">Optional additional assemblies to reference in the script.</param> |
| | | 135 | | /// <param name="locals">Optional local variables to provide to the script.</param> |
| | | 136 | | /// <param name="languageVersion">The VB.NET language version to use for compilation.</param> |
| | | 137 | | /// <returns>A delegate that takes CsGlobals and returns a Task.</returns> |
| | | 138 | | /// <exception cref="CompilationErrorException">Thrown if the compilation fails with errors.</exception> |
| | | 139 | | /// <remarks> |
| | | 140 | | /// This method uses the Roslyn compiler to compile the provided VB.NET code into a delegate. |
| | | 141 | | /// </remarks> |
| | | 142 | | internal static Func<CsGlobals, Task<TResult>> Compile<TResult>( |
| | | 143 | | KestrunHost host, |
| | | 144 | | string? code, string[]? extraImports, |
| | | 145 | | Assembly[]? extraRefs, IReadOnlyDictionary<string, object?>? locals, LanguageVersion languageVersion |
| | | 146 | | ) |
| | | 147 | | { |
| | 16 | 148 | | var log = host.Logger; |
| | 16 | 149 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 150 | | { |
| | 12 | 151 | | log.Debug("Building VB.NET delegate, script length={Length}, imports={ImportsCount}, refs={RefsCount}, lang= |
| | 12 | 152 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 153 | | } |
| | | 154 | | |
| | | 155 | | // Validate inputs |
| | 16 | 156 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 157 | | { |
| | 0 | 158 | | throw new ArgumentNullException(nameof(code), "VB.NET code cannot be null or whitespace."); |
| | | 159 | | } |
| | | 160 | | |
| | 16 | 161 | | extraImports ??= []; |
| | 16 | 162 | | extraImports = [.. extraImports, "System.Collections.Generic", "System.Linq", "System.Security.Claims"]; |
| | | 163 | | |
| | 16 | 164 | | var (dynamicImports, dynamicRefs) = CollectDynamicMetadata(host, locals); |
| | 16 | 165 | | if (dynamicImports.Count > 0) |
| | | 166 | | { |
| | 8 | 167 | | var mergedImports = extraImports.Concat(dynamicImports) |
| | 8 | 168 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 8 | 169 | | .ToArray(); |
| | 8 | 170 | | if (log.IsEnabled(LogEventLevel.Debug) && mergedImports.Length != extraImports.Length) |
| | | 171 | | { |
| | 5 | 172 | | log.Debug("Added {Count} dynamic VB imports from globals/locals.", mergedImports.Length - extraImports.L |
| | | 173 | | } |
| | 8 | 174 | | extraImports = mergedImports; |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | // 🔧 1. Build a real VB file around the user snippet |
| | 16 | 178 | | var source = BuildWrappedSource(code, extraImports, vbReturnType: GetVbReturnType(typeof(TResult)), |
| | 16 | 179 | | locals: locals); |
| | | 180 | | |
| | | 181 | | // Prepares the source code for compilation. |
| | 16 | 182 | | var startLine = GetStartLineOrThrow(source, log); |
| | | 183 | | |
| | | 184 | | // Parse the source code into a syntax tree |
| | | 185 | | // This will allow us to analyze and compile the code |
| | 16 | 186 | | var tree = VisualBasicSyntaxTree.ParseText( |
| | 16 | 187 | | source, |
| | 16 | 188 | | new VisualBasicParseOptions(languageVersion)); |
| | | 189 | | |
| | 16 | 190 | | var refs = BuildMetadataReferences(extraRefs, extraImports, dynamicRefs); |
| | | 191 | | // 🔧 3. Normal DLL compilation |
| | 16 | 192 | | var compilation = VisualBasicCompilation.Create( |
| | 16 | 193 | | assemblyName: $"RouteScript_{Guid.NewGuid():N}", |
| | 16 | 194 | | syntaxTrees: [tree], |
| | 16 | 195 | | references: refs, |
| | 16 | 196 | | options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); |
| | | 197 | | |
| | 16 | 198 | | using var ms = new MemoryStream(); |
| | 16 | 199 | | var emitResult = compilation.Emit(ms) ?? throw new InvalidOperationException("Failed to compile VB.NET script.") |
| | | 200 | | // 🔧 4. Log the compilation result |
| | 16 | 201 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 202 | | { |
| | 12 | 203 | | log.Debug("VB.NET script compilation completed, assembly size={Size} bytes", ms.Length); |
| | | 204 | | } |
| | | 205 | | |
| | | 206 | | // 🔧 5. Handle diagnostics |
| | 16 | 207 | | ThrowIfErrors(emitResult.Diagnostics, startLine, log); |
| | | 208 | | // Log any warnings from the compilation process |
| | 16 | 209 | | LogWarnings(emitResult.Diagnostics, startLine, log); |
| | | 210 | | |
| | | 211 | | // If there are no errors, log a debug message |
| | 16 | 212 | | if (emitResult.Success && log.IsEnabled(LogEventLevel.Debug)) |
| | | 213 | | { |
| | 12 | 214 | | log.Debug("VB.NET script compiled successfully with no errors."); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | // If there are no errors, proceed to load the assembly and create the delegate |
| | 16 | 218 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 219 | | { |
| | 12 | 220 | | log.Debug("VB.NET script compiled successfully, loading assembly..."); |
| | | 221 | | } |
| | | 222 | | |
| | 16 | 223 | | ms.Position = 0; |
| | 16 | 224 | | return LoadDelegateFromAssembly<TResult>(ms.ToArray()); |
| | 16 | 225 | | } |
| | | 226 | | |
| | | 227 | | /// <summary> |
| | | 228 | | /// Prepares the source code for compilation. |
| | | 229 | | /// </summary> |
| | | 230 | | /// <param name="source">The source code to prepare.</param> |
| | | 231 | | /// <param name="log">The logger instance.</param> |
| | | 232 | | /// <returns>The prepared source code.</returns> |
| | | 233 | | /// <exception cref="ArgumentException">Thrown when the source code is invalid.</exception> |
| | | 234 | | private static int GetStartLineOrThrow(string source, Serilog.ILogger log) |
| | | 235 | | { |
| | 16 | 236 | | var startIndex = source.IndexOf(StartMarker, StringComparison.Ordinal); |
| | 16 | 237 | | if (startIndex < 0) |
| | | 238 | | { |
| | 0 | 239 | | throw new ArgumentException($"VB.NET code must contain the marker '{StartMarker}' to indicate where user cod |
| | | 240 | | } |
| | | 241 | | |
| | 16 | 242 | | var startLine = CcUtilities.GetLineNumber(source, startIndex); |
| | 16 | 243 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 244 | | { |
| | 12 | 245 | | log.Debug("VB.NET script starts at line {LineNumber}", startLine); |
| | | 246 | | } |
| | | 247 | | |
| | 16 | 248 | | return startLine; |
| | | 249 | | } |
| | | 250 | | |
| | | 251 | | /// <summary> |
| | | 252 | | /// Prepares the metadata references for the VB.NET script. |
| | | 253 | | /// </summary> |
| | | 254 | | /// <param name="extraRefs">The extra references to include.</param> |
| | | 255 | | /// <param name="imports">The effective imports used by the generated source.</param> |
| | | 256 | | /// <param name="dynamicRefs">Assemblies inferred from host globals and compile-time locals.</param> |
| | | 257 | | /// <returns>An enumerable of metadata references.</returns> |
| | | 258 | | private static IEnumerable<MetadataReference> BuildMetadataReferences( |
| | | 259 | | Assembly[]? extraRefs, |
| | | 260 | | IEnumerable<string> imports, |
| | | 261 | | IEnumerable<Assembly> dynamicRefs) |
| | | 262 | | { |
| | 16 | 263 | | var locations = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 16 | 264 | | AddMetadataReferenceLocations(locations, DelegateBuilder.BuildBaselineReferences()); |
| | 16 | 265 | | AddAssemblyLocation(locations, typeof(Microsoft.VisualBasic.Constants).Assembly); |
| | 16 | 266 | | AddAssemblyLocation(locations, typeof(CsGlobals).Assembly); |
| | 16 | 267 | | AddLoadedAssemblyLocation(locations, "System.Runtime"); |
| | 16 | 268 | | AddLoadedAssemblyLocation(locations, "netstandard"); |
| | 16 | 269 | | AddImportAssemblyLocations(locations, imports); |
| | 16 | 270 | | AddAssemblyLocations(locations, dynamicRefs); |
| | 16 | 271 | | AddAssemblyLocations(locations, extraRefs); |
| | | 272 | | |
| | 3492 | 273 | | return locations.Select(static location => MetadataReference.CreateFromFile(location)); |
| | | 274 | | } |
| | | 275 | | |
| | | 276 | | private static bool IsSatelliteAssembly(Assembly a) |
| | | 277 | | { |
| | | 278 | | try |
| | | 279 | | { |
| | 6125 | 280 | | var name = a.GetName(); |
| | 6125 | 281 | | if (name.Name != null && name.Name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) |
| | | 282 | | { |
| | 0 | 283 | | return true; |
| | | 284 | | } |
| | 6125 | 285 | | var loc = a.Location; |
| | 6125 | 286 | | if (!string.IsNullOrEmpty(loc) && loc.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase)) |
| | | 287 | | { |
| | 0 | 288 | | return true; |
| | | 289 | | } |
| | 6125 | 290 | | } |
| | 0 | 291 | | catch |
| | | 292 | | { |
| | | 293 | | // If we can't inspect it, be conservative and treat as non-satellite |
| | 0 | 294 | | } |
| | 6125 | 295 | | return false; |
| | 0 | 296 | | } |
| | | 297 | | |
| | | 298 | | /// <summary> |
| | | 299 | | /// Collects dynamic imports and assembly references from the types of the provided locals and shared globals. |
| | | 300 | | /// </summary> |
| | | 301 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 302 | | /// <param name="locals">The local variables to inspect.</param> |
| | | 303 | | /// <returns>A set of unique namespace strings and the corresponding assembly references.</returns> |
| | | 304 | | private static (HashSet<string> Imports, HashSet<Assembly> References) CollectDynamicMetadata( |
| | | 305 | | KestrunHost host, |
| | | 306 | | IReadOnlyDictionary<string, object?>? locals) |
| | | 307 | | { |
| | 16 | 308 | | var imports = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 16 | 309 | | var references = new HashSet<Assembly>(); |
| | 32 | 310 | | foreach (var g in host.SharedState.Snapshot()) |
| | | 311 | | { |
| | 0 | 312 | | AddTypeMetadata(g.Value?.GetType(), imports, references); |
| | | 313 | | } |
| | | 314 | | |
| | 16 | 315 | | if (locals is { Count: > 0 }) |
| | | 316 | | { |
| | 38 | 317 | | foreach (var l in locals) |
| | | 318 | | { |
| | 11 | 319 | | AddTypeMetadata(l.Value?.GetType(), imports, references); |
| | | 320 | | } |
| | | 321 | | } |
| | | 322 | | |
| | 16 | 323 | | return (imports, references); |
| | | 324 | | } |
| | | 325 | | |
| | | 326 | | /// <summary> |
| | | 327 | | /// Adds the namespace and assembly metadata for the supplied type, including generic arguments and array elements. |
| | | 328 | | /// </summary> |
| | | 329 | | /// <param name="type">The type to inspect.</param> |
| | | 330 | | /// <param name="imports">The namespace set to update.</param> |
| | | 331 | | /// <param name="references">The assembly set to update.</param> |
| | | 332 | | private static void AddTypeMetadata(Type? type, HashSet<string> imports, HashSet<Assembly> references) |
| | | 333 | | { |
| | 13 | 334 | | if (type == null) |
| | | 335 | | { |
| | 0 | 336 | | return; |
| | | 337 | | } |
| | | 338 | | |
| | 13 | 339 | | if (!string.IsNullOrEmpty(type.Namespace)) |
| | | 340 | | { |
| | 13 | 341 | | _ = imports.Add(type.Namespace); |
| | | 342 | | } |
| | | 343 | | |
| | 13 | 344 | | _ = references.Add(type.Assembly); |
| | | 345 | | |
| | 13 | 346 | | if (type.IsGenericType) |
| | | 347 | | { |
| | 0 | 348 | | foreach (var genericArgument in type.GetGenericArguments()) |
| | | 349 | | { |
| | 0 | 350 | | AddTypeMetadata(genericArgument, imports, references); |
| | | 351 | | } |
| | | 352 | | } |
| | | 353 | | |
| | 13 | 354 | | if (type.IsArray) |
| | | 355 | | { |
| | 2 | 356 | | AddTypeMetadata(type.GetElementType(), imports, references); |
| | | 357 | | } |
| | 13 | 358 | | } |
| | | 359 | | |
| | | 360 | | /// <summary> |
| | | 361 | | /// Adds assembly locations needed for the supplied import namespaces. |
| | | 362 | | /// </summary> |
| | | 363 | | /// <param name="locations">The reference location set to update.</param> |
| | | 364 | | /// <param name="imports">The imports used by the generated source.</param> |
| | | 365 | | private static void AddImportAssemblyLocations(HashSet<string> locations, IEnumerable<string> imports) |
| | | 366 | | { |
| | 16 | 367 | | var importSet = imports |
| | 58 | 368 | | .Where(importName => !string.IsNullOrWhiteSpace(importName)) |
| | 16 | 369 | | .ToHashSet(StringComparer.OrdinalIgnoreCase); |
| | 16 | 370 | | if (importSet.Count == 0) |
| | | 371 | | { |
| | 0 | 372 | | return; |
| | | 373 | | } |
| | | 374 | | |
| | 9494 | 375 | | foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(IsReferenceableAssembly)) |
| | | 376 | | { |
| | 21079 | 377 | | if (importSet.Any(importName => NamespaceExistsInAssembly(assembly, importName))) |
| | | 378 | | { |
| | 1322 | 379 | | AddAssemblyLocation(locations, assembly); |
| | | 380 | | } |
| | | 381 | | } |
| | 16 | 382 | | } |
| | | 383 | | |
| | | 384 | | /// <summary> |
| | | 385 | | /// Adds all safe assembly locations from the provided collection. |
| | | 386 | | /// </summary> |
| | | 387 | | /// <param name="locations">The reference location set to update.</param> |
| | | 388 | | /// <param name="assemblies">The assemblies to inspect.</param> |
| | | 389 | | private static void AddAssemblyLocations(HashSet<string> locations, IEnumerable<Assembly>? assemblies) |
| | | 390 | | { |
| | 32 | 391 | | if (assemblies == null) |
| | | 392 | | { |
| | 15 | 393 | | return; |
| | | 394 | | } |
| | | 395 | | |
| | 50 | 396 | | foreach (var assembly in assemblies) |
| | | 397 | | { |
| | 8 | 398 | | AddAssemblyLocation(locations, assembly); |
| | | 399 | | } |
| | 17 | 400 | | } |
| | | 401 | | |
| | | 402 | | /// <summary> |
| | | 403 | | /// Adds file paths from existing metadata references to the location set. |
| | | 404 | | /// </summary> |
| | | 405 | | /// <param name="locations">The reference location set to update.</param> |
| | | 406 | | /// <param name="references">The metadata references to inspect.</param> |
| | | 407 | | private static void AddMetadataReferenceLocations(HashSet<string> locations, IEnumerable<MetadataReference> referenc |
| | | 408 | | { |
| | 6916 | 409 | | foreach (var reference in references.OfType<PortableExecutableReference>()) |
| | | 410 | | { |
| | 3442 | 411 | | var filePath = reference.FilePath; |
| | 3442 | 412 | | if (!string.IsNullOrWhiteSpace(filePath) && File.Exists(filePath)) |
| | | 413 | | { |
| | 3442 | 414 | | _ = locations.Add(filePath); |
| | | 415 | | } |
| | | 416 | | } |
| | 16 | 417 | | } |
| | | 418 | | |
| | | 419 | | /// <summary> |
| | | 420 | | /// Adds a loaded assembly by simple name when it is available and safe to reference. |
| | | 421 | | /// </summary> |
| | | 422 | | /// <param name="locations">The reference location set to update.</param> |
| | | 423 | | /// <param name="assemblyName">The simple assembly name to resolve.</param> |
| | | 424 | | private static void AddLoadedAssemblyLocation(HashSet<string> locations, string assemblyName) |
| | | 425 | | { |
| | 32 | 426 | | var assembly = AppDomain.CurrentDomain.GetAssemblies() |
| | 336 | 427 | | .FirstOrDefault(candidate => string.Equals(candidate.GetName().Name, assemblyName, StringComparison.OrdinalI |
| | 32 | 428 | | if (assembly != null) |
| | | 429 | | { |
| | 32 | 430 | | AddAssemblyLocation(locations, assembly); |
| | | 431 | | } |
| | 32 | 432 | | } |
| | | 433 | | |
| | | 434 | | /// <summary> |
| | | 435 | | /// Adds an assembly location when the assembly can be safely referenced by Roslyn. |
| | | 436 | | /// </summary> |
| | | 437 | | /// <param name="locations">The reference location set to update.</param> |
| | | 438 | | /// <param name="assembly">The assembly to inspect.</param> |
| | | 439 | | private static void AddAssemblyLocation(HashSet<string> locations, Assembly assembly) |
| | | 440 | | { |
| | 1394 | 441 | | if (!IsReferenceableAssembly(assembly)) |
| | | 442 | | { |
| | 0 | 443 | | return; |
| | | 444 | | } |
| | | 445 | | |
| | | 446 | | try |
| | | 447 | | { |
| | 1394 | 448 | | _ = locations.Add(assembly.Location); |
| | 1394 | 449 | | } |
| | 0 | 450 | | catch |
| | | 451 | | { |
| | 0 | 452 | | } |
| | 1394 | 453 | | } |
| | | 454 | | |
| | | 455 | | /// <summary> |
| | | 456 | | /// Determines whether the assembly can be safely used as a metadata reference. |
| | | 457 | | /// </summary> |
| | | 458 | | /// <param name="assembly">The assembly to inspect.</param> |
| | | 459 | | /// <returns><see langword="true"/> when the assembly has a stable file location and is not a satellite assembly.</r |
| | | 460 | | private static bool IsReferenceableAssembly(Assembly assembly) |
| | 6850 | 461 | | => !assembly.IsDynamic && SafeHasLocation(assembly) && !IsSatelliteAssembly(assembly); |
| | | 462 | | |
| | | 463 | | /// <summary> |
| | | 464 | | /// Determines whether the supplied namespace exists in the assembly. |
| | | 465 | | /// </summary> |
| | | 466 | | /// <param name="assembly">The assembly to inspect.</param> |
| | | 467 | | /// <param name="namespaceName">The namespace to search for.</param> |
| | | 468 | | /// <returns><see langword="true"/> when the namespace or one of its children is present.</returns> |
| | | 469 | | private static bool NamespaceExistsInAssembly(Assembly assembly, string namespaceName) |
| | | 470 | | { |
| | | 471 | | try |
| | | 472 | | { |
| | 4461298 | 473 | | foreach (var type in assembly.DefinedTypes) |
| | | 474 | | { |
| | 2214962 | 475 | | var currentNamespace = type.Namespace; |
| | 2214962 | 476 | | if (currentNamespace == null) |
| | | 477 | | { |
| | | 478 | | continue; |
| | | 479 | | } |
| | | 480 | | |
| | 2132968 | 481 | | if (currentNamespace.Equals(namespaceName, StringComparison.OrdinalIgnoreCase) |
| | 2132968 | 482 | | || currentNamespace.StartsWith(namespaceName + ".", StringComparison.OrdinalIgnoreCase)) |
| | | 483 | | { |
| | 1322 | 484 | | return true; |
| | | 485 | | } |
| | | 486 | | } |
| | 15026 | 487 | | } |
| | 0 | 488 | | catch (ReflectionTypeLoadException) |
| | | 489 | | { |
| | | 490 | | // If we can't load all types, be conservative and assume the namespace is not present |
| | 0 | 491 | | } |
| | | 492 | | |
| | 15026 | 493 | | return false; |
| | 1322 | 494 | | } |
| | | 495 | | private static bool SafeHasLocation(Assembly a) |
| | | 496 | | { |
| | | 497 | | try |
| | | 498 | | { |
| | 6775 | 499 | | var loc = a.Location; // may throw for some dynamic contexts |
| | 6775 | 500 | | return !string.IsNullOrEmpty(loc) && File.Exists(loc); |
| | | 501 | | } |
| | 0 | 502 | | catch |
| | | 503 | | { |
| | 0 | 504 | | return false; |
| | | 505 | | } |
| | 6775 | 506 | | } |
| | | 507 | | /// <summary> |
| | | 508 | | /// Logs any warnings from the compilation process. |
| | | 509 | | /// </summary> |
| | | 510 | | /// <param name="diagnostics">The diagnostics to check.</param> |
| | | 511 | | /// <param name="startLine">The starting line number.</param> |
| | | 512 | | /// <param name="log">The logger instance.</param> |
| | | 513 | | private static void LogWarnings(ImmutableArray<Diagnostic> diagnostics, int startLine, Serilog.ILogger log) |
| | | 514 | | { |
| | 134 | 515 | | var warnings = diagnostics.Where(d => d.Severity == DiagnosticSeverity.Warning).ToArray(); |
| | | 516 | | // If there are no warnings, log a debug message |
| | 16 | 517 | | if (warnings.Length == 0) |
| | | 518 | | { |
| | 11 | 519 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 520 | | { |
| | 10 | 521 | | log.Debug("VB.NET script compiled successfully with no warnings."); |
| | | 522 | | } |
| | | 523 | | |
| | 11 | 524 | | return; |
| | | 525 | | } |
| | | 526 | | |
| | 5 | 527 | | log.Warning($"VBNet script compilation completed with {warnings.Length} warning(s):"); |
| | 20 | 528 | | foreach (var warning in warnings) |
| | | 529 | | { |
| | 5 | 530 | | var location = warning.Location.IsInSource |
| | 5 | 531 | | ? $" at line {warning.Location.GetLineSpan().StartLinePosition.Line - startLine + 1}" |
| | 5 | 532 | | : ""; |
| | 5 | 533 | | log.Warning($" Warning [{warning.Id}]: {warning.GetMessage()}{location}"); |
| | | 534 | | } |
| | 5 | 535 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 536 | | { |
| | 2 | 537 | | log.Debug("VB.NET script compiled with warnings: {Count}", warnings.Length); |
| | | 538 | | } |
| | 5 | 539 | | } |
| | | 540 | | |
| | | 541 | | /// <summary> |
| | | 542 | | /// Throws an exception if there are compilation errors. |
| | | 543 | | /// </summary> |
| | | 544 | | /// <param name="diagnostics">The diagnostics to check.</param> |
| | | 545 | | /// <param name="startLine">The starting line number.</param> |
| | | 546 | | /// <param name="log">The logger instance.</param> |
| | | 547 | | private static void ThrowIfErrors(ImmutableArray<Diagnostic> diagnostics, int startLine, Serilog.ILogger log) |
| | | 548 | | { |
| | 134 | 549 | | var errors = diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); |
| | 16 | 550 | | if (errors.Length == 0) |
| | | 551 | | { |
| | 16 | 552 | | return; |
| | | 553 | | } |
| | | 554 | | |
| | 0 | 555 | | log.Error($"VBNet script compilation completed with {errors.Length} error(s):"); |
| | 0 | 556 | | var sb = new StringBuilder(); |
| | 0 | 557 | | _ = sb.AppendLine("VBNet route code compilation failed:"); |
| | 0 | 558 | | foreach (var error in errors) |
| | | 559 | | { |
| | 0 | 560 | | var location = error.Location.IsInSource |
| | 0 | 561 | | ? $" at line {error.Location.GetLineSpan().StartLinePosition.Line - startLine + 1}" |
| | 0 | 562 | | : ""; |
| | 0 | 563 | | var msg = $" Error [{error.Id}]: {error.GetMessage()}{location}"; |
| | 0 | 564 | | log.Error(msg); |
| | 0 | 565 | | _ = sb.AppendLine(msg); |
| | | 566 | | } |
| | 0 | 567 | | throw new CompilationErrorException(sb.ToString().TrimEnd(), diagnostics); |
| | | 568 | | } |
| | | 569 | | |
| | | 570 | | /// <summary> |
| | | 571 | | /// Loads a delegate from the provided assembly bytes. |
| | | 572 | | /// </summary> |
| | | 573 | | /// <typeparam name="TResult">The type of the result.</typeparam> |
| | | 574 | | /// <param name="asmBytes">The assembly bytes.</param> |
| | | 575 | | /// <returns>A delegate that can be invoked with the specified globals.</returns> |
| | | 576 | | private static Func<CsGlobals, Task<TResult>> LoadDelegateFromAssembly<TResult>(byte[] asmBytes) |
| | | 577 | | { |
| | 16 | 578 | | var asm = Assembly.Load(asmBytes); |
| | 16 | 579 | | var runMethod = asm.GetType("RouteScript")! |
| | 16 | 580 | | .GetMethod("Run", BindingFlags.Public | BindingFlags.Static)!; |
| | | 581 | | |
| | 16 | 582 | | var delegateType = typeof(Func<,>).MakeGenericType( |
| | 16 | 583 | | typeof(CsGlobals), |
| | 16 | 584 | | typeof(Task<>).MakeGenericType(typeof(TResult))); |
| | | 585 | | |
| | 16 | 586 | | return (Func<CsGlobals, Task<TResult>>)runMethod.CreateDelegate(delegateType); |
| | | 587 | | } |
| | | 588 | | |
| | | 589 | | /// <summary> |
| | | 590 | | /// Builds the wrapped source code for the VB.NET script. |
| | | 591 | | /// </summary> |
| | | 592 | | /// <param name="code">The user-provided code to wrap.</param> |
| | | 593 | | /// <param name="extraImports">Additional imports to include.</param> |
| | | 594 | | /// <param name="vbReturnType">The return type of the VB.NET function.</param> |
| | | 595 | | /// <param name="locals">Local variables to bind to the script.</param> |
| | | 596 | | /// <returns>The wrapped source code.</returns> |
| | | 597 | | private static string BuildWrappedSource(string? code, IEnumerable<string>? extraImports, |
| | | 598 | | string vbReturnType, IReadOnlyDictionary<string, object?>? locals = null |
| | | 599 | | ) |
| | | 600 | | { |
| | 16 | 601 | | var sb = new StringBuilder(); |
| | | 602 | | |
| | | 603 | | // common + caller-supplied Imports |
| | 16 | 604 | | var builtIns = new[] { |
| | 16 | 605 | | "System", "System.Threading.Tasks", |
| | 16 | 606 | | "Kestrun", "Kestrun.Models", |
| | 16 | 607 | | "Microsoft.VisualBasic", |
| | 16 | 608 | | "Kestrun.Languages" |
| | 16 | 609 | | }; |
| | | 610 | | |
| | 326 | 611 | | foreach (var ns in builtIns.Concat(extraImports ?? []) |
| | 16 | 612 | | .Distinct(StringComparer.OrdinalIgnoreCase)) |
| | | 613 | | { |
| | 147 | 614 | | _ = sb.AppendLine($"Imports {ns}"); |
| | | 615 | | } |
| | | 616 | | |
| | 16 | 617 | | _ = sb.AppendLine($""" |
| | 16 | 618 | | Public Module RouteScript |
| | 16 | 619 | | Public Async Function Run(g As CsGlobals) As Task(Of {vbReturnType}) |
| | 16 | 620 | | Await Task.Yield() ' placeholder await |
| | 16 | 621 | | Dim Request = g.Context?.Request |
| | 16 | 622 | | Dim Response = g.Context?.Response |
| | 16 | 623 | | Dim Context = g.Context |
| | 16 | 624 | | """); |
| | | 625 | | |
| | | 626 | | // only emit these _when_ you called Compile with locals: |
| | 16 | 627 | | if (locals?.ContainsKey("username") ?? false) |
| | | 628 | | { |
| | 2 | 629 | | _ = sb.AppendLine(""" |
| | 2 | 630 | | ' only bind creds if someone passed them in |
| | 2 | 631 | | Dim username As String = CStr(g.Locals("username")) |
| | 2 | 632 | | """); |
| | | 633 | | } |
| | | 634 | | |
| | 16 | 635 | | if (locals?.ContainsKey("password") ?? false) |
| | | 636 | | { |
| | 1 | 637 | | _ = sb.AppendLine(""" |
| | 1 | 638 | | Dim password As String = CStr(g.Locals("password")) |
| | 1 | 639 | | """); |
| | | 640 | | } |
| | | 641 | | |
| | 16 | 642 | | if (locals?.ContainsKey("providedKey") == true) |
| | | 643 | | { |
| | 2 | 644 | | _ = sb.AppendLine(""" |
| | 2 | 645 | | ' only bind keys if someone passed them in |
| | 2 | 646 | | Dim providedKey As String = CStr(g.Locals("providedKey")) |
| | 2 | 647 | | """); |
| | | 648 | | } |
| | | 649 | | |
| | 16 | 650 | | if (locals?.ContainsKey("providedKeyBytes") == true) |
| | | 651 | | { |
| | 2 | 652 | | _ = sb.AppendLine(""" |
| | 2 | 653 | | Dim providedKeyBytes As Byte() = CType(g.Locals("providedKeyBytes"), Byte()) |
| | 2 | 654 | | """); |
| | | 655 | | } |
| | | 656 | | |
| | 16 | 657 | | if (locals?.ContainsKey("identity") == true) |
| | | 658 | | { |
| | 3 | 659 | | _ = sb.AppendLine(""" |
| | 3 | 660 | | Dim identity As String = CStr(g.Locals("identity")) |
| | 3 | 661 | | """); |
| | | 662 | | } |
| | | 663 | | |
| | | 664 | | // add the Marker for user code |
| | 16 | 665 | | _ = sb.AppendLine(StartMarker); |
| | | 666 | | // ---- User code starts here ---- |
| | | 667 | | |
| | 16 | 668 | | if (!string.IsNullOrEmpty(code)) |
| | | 669 | | { |
| | | 670 | | // indent the user snippet so VB is happy |
| | 16 | 671 | | _ = sb.AppendLine(string.Join( |
| | 16 | 672 | | Environment.NewLine, |
| | 37 | 673 | | code.Split('\n').Select(l => " " + l.TrimEnd('\r')))); |
| | | 674 | | } |
| | 16 | 675 | | _ = sb.AppendLine(""" |
| | 16 | 676 | | |
| | 16 | 677 | | End Function |
| | 16 | 678 | | End Module |
| | 16 | 679 | | """); |
| | 16 | 680 | | return sb.ToString(); |
| | | 681 | | } |
| | | 682 | | } |