< Summary

Information
Class: NexusLabs.Needlr.Generators.Export.CollectedDiagnostic
Assembly: NexusLabs.Needlr.Generators
File(s): /home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/Export/GraphExporter.cs
Line coverage
100%
Covered lines: 6
Uncovered lines: 0
Coverable lines: 6
Total lines: 620
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_Id()100%11100%
get_Severity()100%11100%
get_Message()100%11100%
get_FilePath()100%11100%
get_Line()100%11100%
get_RelatedServices()100%11100%

File(s)

/home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/Export/GraphExporter.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using NexusLabs.Needlr.Generators.Models;
 6
 7namespace NexusLabs.Needlr.Generators.Export;
 8
 9/// <summary>
 10/// Generates the Needlr dependency graph JSON for IDE tooling.
 11/// </summary>
 12internal static class GraphExporter
 13{
 14    /// <summary>
 15    /// Generates the needlr-graph.json content from the discovery result.
 16    /// </summary>
 17    public static string GenerateGraphJson(
 18        DiscoveryResult discoveryResult,
 19        string assemblyName,
 20        string? projectPath,
 21        IReadOnlyList<CollectedDiagnostic>? diagnostics = null,
 22        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes = null)
 23    {
 24        var graph = BuildGraph(discoveryResult, assemblyName, projectPath, diagnostics, referencedAssemblyTypes);
 25        return SerializeToJson(graph);
 26    }
 27
 28    private static NeedlrGraph BuildGraph(
 29        DiscoveryResult discoveryResult,
 30        string assemblyName,
 31        string? projectPath,
 32        IReadOnlyList<CollectedDiagnostic>? diagnostics,
 33        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes)
 34    {
 35        var graph = new NeedlrGraph
 36        {
 37            SchemaVersion = "1.0",
 38            GeneratedAt = DateTime.UtcNow.ToString("O"),
 39            ProjectPath = projectPath,
 40            AssemblyName = assemblyName
 41        };
 42
 43        // Build type lookup for resolving dependencies (include referenced assembly types)
 44        var typeLookup = BuildTypeLookup(discoveryResult, referencedAssemblyTypes);
 45
 46        // Map injectable types from current assembly to graph services
 47        foreach (var type in discoveryResult.InjectableTypes)
 48        {
 49            var service = MapToGraphService(type, assemblyName, typeLookup, discoveryResult);
 50            graph.Services.Add(service);
 51        }
 52
 53        // Add types from referenced assemblies with [GenerateTypeRegistry]
 54        if (referencedAssemblyTypes != null)
 55        {
 56            foreach (var kvp in referencedAssemblyTypes)
 57            {
 58                var refAssemblyName = kvp.Key;
 59                var types = kvp.Value;
 60                foreach (var type in types)
 61                {
 62                    var service = MapToGraphService(type, refAssemblyName, typeLookup, discoveryResult);
 63                    graph.Services.Add(service);
 64                }
 65            }
 66        }
 67
 68        // Add diagnostics if provided
 69        if (diagnostics != null)
 70        {
 71            foreach (var diag in diagnostics)
 72            {
 73                graph.Diagnostics.Add(new GraphDiagnostic
 74                {
 75                    Id = diag.Id,
 76                    Severity = diag.Severity,
 77                    Message = diag.Message,
 78                    Location = diag.FilePath != null ? new GraphLocation
 79                    {
 80                        FilePath = diag.FilePath,
 81                        Line = diag.Line,
 82                        Column = 0
 83                    } : null,
 84                    RelatedServices = diag.RelatedServices?.ToList() ?? new List<string>()
 85                });
 86            }
 87        }
 88
 89        // Compute statistics (include referenced assembly types in count)
 90        graph.Statistics = ComputeStatistics(discoveryResult, referencedAssemblyTypes);
 91
 92        return graph;
 93    }
 94
 95    private static Dictionary<string, DiscoveredType> BuildTypeLookup(
 96        DiscoveryResult discoveryResult,
 97        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes)
 98    {
 99        var lookup = new Dictionary<string, DiscoveredType>();
 100
 101        // Add types from current assembly
 102        foreach (var type in discoveryResult.InjectableTypes)
 103        {
 104            lookup[type.TypeName] = type;
 105            foreach (var iface in type.InterfaceNames)
 106            {
 107                if (!lookup.ContainsKey(iface))
 108                {
 109                    lookup[iface] = type;
 110                }
 111            }
 112        }
 113
 114        // Add types from referenced assemblies for dependency resolution
 115        if (referencedAssemblyTypes != null)
 116        {
 117            foreach (var kvp in referencedAssemblyTypes)
 118            {
 119                foreach (var type in kvp.Value)
 120                {
 121                    if (!lookup.ContainsKey(type.TypeName))
 122                    {
 123                        lookup[type.TypeName] = type;
 124                    }
 125                    foreach (var iface in type.InterfaceNames)
 126                    {
 127                        if (!lookup.ContainsKey(iface))
 128                        {
 129                            lookup[iface] = type;
 130                        }
 131                    }
 132                }
 133            }
 134        }
 135
 136        return lookup;
 137    }
 138
 139    private static GraphService MapToGraphService(
 140        DiscoveredType type,
 141        string assemblyName,
 142        Dictionary<string, DiscoveredType> typeLookup,
 143        DiscoveryResult discoveryResult)
 144    {
 145        var service = new GraphService
 146        {
 147            Id = type.TypeName,
 148            TypeName = GetSimpleTypeName(type.TypeName),
 149            FullTypeName = type.TypeName,
 150            AssemblyName = assemblyName,
 151            Lifetime = type.Lifetime.ToString(),
 152            Location = type.SourceFilePath != null ? new GraphLocation
 153            {
 154                FilePath = type.SourceFilePath,
 155                Line = type.SourceLine,
 156                Column = 0
 157            } : null,
 158            ServiceKeys = type.ServiceKeys.ToList(),
 159            Metadata = new GraphServiceMetadata
 160            {
 161                IsDisposable = type.IsDisposable,
 162                HasFactory = discoveryResult.Factories.Any(f => f.TypeName == type.TypeName),
 163                HasOptions = discoveryResult.Options.Any(o => o.TypeName == type.TypeName),
 164                IsHostedService = discoveryResult.HostedServices.Any(h => h.TypeName == type.TypeName),
 165                IsPlugin = discoveryResult.PluginTypes.Any(p => p.TypeName == type.TypeName)
 166            }
 167        };
 168
 169        // Map interfaces with locations
 170        foreach (var ifaceInfo in type.InterfaceInfos)
 171        {
 172            service.Interfaces.Add(new GraphInterface
 173            {
 174                Name = GetSimpleTypeName(ifaceInfo.FullName),
 175                FullName = ifaceInfo.FullName,
 176                Location = ifaceInfo.HasLocation ? new GraphLocation
 177                {
 178                    FilePath = ifaceInfo.SourceFilePath!,
 179                    Line = ifaceInfo.SourceLine,
 180                    Column = 0
 181                } : null
 182            });
 183        }
 184        // Fall back to InterfaceNames if no InterfaceInfos (for backwards compat)
 185        if (type.InterfaceInfos.Length == 0)
 186        {
 187            foreach (var iface in type.InterfaceNames)
 188            {
 189                service.Interfaces.Add(new GraphInterface
 190                {
 191                    Name = GetSimpleTypeName(iface),
 192                    FullName = iface
 193                });
 194            }
 195        }
 196
 197        // Map dependencies from constructor parameters
 198        foreach (var param in type.ConstructorParameters)
 199        {
 200            var dependency = new GraphDependency
 201            {
 202                ParameterName = param.ParameterName ?? string.Empty,
 203                TypeName = GetSimpleTypeName(param.TypeName),
 204                FullTypeName = param.TypeName,
 205                IsKeyed = param.IsKeyed,
 206                ServiceKey = param.ServiceKey
 207            };
 208
 209            // Try to resolve the dependency
 210            if (typeLookup.TryGetValue(param.TypeName, out var resolved))
 211            {
 212                dependency.ResolvedTo = resolved.TypeName;
 213                dependency.ResolvedLifetime = resolved.Lifetime.ToString();
 214            }
 215
 216            service.Dependencies.Add(dependency);
 217        }
 218
 219        // Map decorators
 220        var decorators = discoveryResult.Decorators
 221            .Where(d => type.InterfaceNames.Contains(d.ServiceTypeName))
 222            .OrderBy(d => d.Order);
 223
 224        foreach (var decorator in decorators)
 225        {
 226            service.Decorators.Add(new GraphDecorator
 227            {
 228                TypeName = decorator.DecoratorTypeName,
 229                Order = decorator.Order
 230            });
 231        }
 232
 233        // Map interceptors
 234        var intercepted = discoveryResult.InterceptedServices
 235            .FirstOrDefault(i => i.TypeName == type.TypeName);
 236
 237        if (intercepted.TypeName != null)
 238        {
 239            service.Interceptors = intercepted.AllInterceptorTypeNames.ToList();
 240        }
 241
 242        // Collect attributes
 243        service.Attributes.Add(type.Lifetime.ToString());
 244        if (type.IsKeyed)
 245        {
 246            service.Attributes.Add("Keyed");
 247        }
 248
 249        return service;
 250    }
 251
 252    private static GraphStatistics ComputeStatistics(
 253        DiscoveryResult discoveryResult,
 254        IReadOnlyDictionary<string, IReadOnlyList<DiscoveredType>>? referencedAssemblyTypes)
 255    {
 256        // Get all types for statistics - current assembly + referenced assemblies
 257        var allTypes = new List<DiscoveredType>(discoveryResult.InjectableTypes);
 258        if (referencedAssemblyTypes != null)
 259        {
 260            foreach (var kvp in referencedAssemblyTypes)
 261            {
 262                allTypes.AddRange(kvp.Value);
 263            }
 264        }
 265
 266        return new GraphStatistics
 267        {
 268            TotalServices = allTypes.Count,
 269            Singletons = allTypes.Count(t => t.Lifetime == GeneratorLifetime.Singleton),
 270            Scoped = allTypes.Count(t => t.Lifetime == GeneratorLifetime.Scoped),
 271            Transient = allTypes.Count(t => t.Lifetime == GeneratorLifetime.Transient),
 272            Decorators = discoveryResult.Decorators.Count,
 273            Interceptors = discoveryResult.InterceptedServices.Count,
 274            Factories = discoveryResult.Factories.Count,
 275            Options = discoveryResult.Options.Count,
 276            HostedServices = discoveryResult.HostedServices.Count,
 277            Plugins = discoveryResult.PluginTypes.Count
 278        };
 279    }
 280
 281    private static string GetSimpleTypeName(string fullTypeName)
 282    {
 283        // Remove global:: prefix
 284        var name = fullTypeName;
 285        if (name.StartsWith("global::"))
 286        {
 287            name = name.Substring(8);
 288        }
 289
 290        // Handle generic types like Lazy<T> or IReadOnlyList<Assembly>
 291        // We want to preserve the generic structure but simplify inner types
 292        var genericStart = name.IndexOf('<');
 293        if (genericStart >= 0)
 294        {
 295            // Get the outer type name (before generic params)
 296            var outerPart = name.Substring(0, genericStart);
 297            var lastDot = outerPart.LastIndexOf('.');
 298            var simpleOuter = lastDot >= 0 ? outerPart.Substring(lastDot + 1) : outerPart;
 299
 300            // Get the generic parameters and simplify them recursively
 301            var genericEnd = name.LastIndexOf('>');
 302            if (genericEnd > genericStart)
 303            {
 304                var genericParams = name.Substring(genericStart + 1, genericEnd - genericStart - 1);
 305                // Simplify each generic parameter (split by comma, handle nested generics)
 306                var simplifiedParams = SimplifyGenericParameters(genericParams);
 307                return $"{simpleOuter}<{simplifiedParams}>";
 308            }
 309
 310            return simpleOuter;
 311        }
 312
 313        // Get just the type name (after last dot)
 314        var idx = name.LastIndexOf('.');
 315        return idx >= 0 ? name.Substring(idx + 1) : name;
 316    }
 317
 318    private static string SimplifyGenericParameters(string genericParams)
 319    {
 320        // Handle nested generics by tracking depth
 321        var result = new StringBuilder();
 322        var depth = 0;
 323        var currentParam = new StringBuilder();
 324
 325        foreach (var c in genericParams)
 326        {
 327            if (c == '<')
 328            {
 329                depth++;
 330                currentParam.Append(c);
 331            }
 332            else if (c == '>')
 333            {
 334                depth--;
 335                currentParam.Append(c);
 336            }
 337            else if (c == ',' && depth == 0)
 338            {
 339                // End of parameter at top level
 340                if (result.Length > 0)
 341                {
 342                    result.Append(", ");
 343                }
 344                result.Append(GetSimpleTypeName(currentParam.ToString().Trim()));
 345                currentParam.Clear();
 346            }
 347            else
 348            {
 349                currentParam.Append(c);
 350            }
 351        }
 352
 353        // Add last parameter
 354        if (currentParam.Length > 0)
 355        {
 356            if (result.Length > 0)
 357            {
 358                result.Append(", ");
 359            }
 360            result.Append(GetSimpleTypeName(currentParam.ToString().Trim()));
 361        }
 362
 363        return result.ToString();
 364    }
 365
 366    /// <summary>
 367    /// Serializes the graph to JSON without using System.Text.Json (not available in all targets).
 368    /// Uses simple string building for source generator compatibility.
 369    /// </summary>
 370    private static string SerializeToJson(NeedlrGraph graph)
 371    {
 372        var sb = new StringBuilder();
 373        sb.AppendLine("{");
 374        sb.AppendLine($"  \"schemaVersion\": \"{Escape(graph.SchemaVersion)}\",");
 375        sb.AppendLine($"  \"generatedAt\": \"{Escape(graph.GeneratedAt)}\",");
 376        sb.AppendLine($"  \"projectPath\": {NullableString(graph.ProjectPath)},");
 377        sb.AppendLine($"  \"assemblyName\": {NullableString(graph.AssemblyName)},");
 378
 379        // Services array
 380        sb.AppendLine("  \"services\": [");
 381        for (int i = 0; i < graph.Services.Count; i++)
 382        {
 383            SerializeService(sb, graph.Services[i], i == graph.Services.Count - 1);
 384        }
 385        sb.AppendLine("  ],");
 386
 387        // Diagnostics array
 388        sb.AppendLine("  \"diagnostics\": [");
 389        for (int i = 0; i < graph.Diagnostics.Count; i++)
 390        {
 391            SerializeDiagnostic(sb, graph.Diagnostics[i], i == graph.Diagnostics.Count - 1);
 392        }
 393        sb.AppendLine("  ],");
 394
 395        // Statistics object
 396        sb.AppendLine("  \"statistics\": {");
 397        sb.AppendLine($"    \"totalServices\": {graph.Statistics.TotalServices},");
 398        sb.AppendLine($"    \"singletons\": {graph.Statistics.Singletons},");
 399        sb.AppendLine($"    \"scoped\": {graph.Statistics.Scoped},");
 400        sb.AppendLine($"    \"transient\": {graph.Statistics.Transient},");
 401        sb.AppendLine($"    \"decorators\": {graph.Statistics.Decorators},");
 402        sb.AppendLine($"    \"interceptors\": {graph.Statistics.Interceptors},");
 403        sb.AppendLine($"    \"factories\": {graph.Statistics.Factories},");
 404        sb.AppendLine($"    \"options\": {graph.Statistics.Options},");
 405        sb.AppendLine($"    \"hostedServices\": {graph.Statistics.HostedServices},");
 406        sb.AppendLine($"    \"plugins\": {graph.Statistics.Plugins}");
 407        sb.AppendLine("  }");
 408
 409        sb.AppendLine("}");
 410        return sb.ToString();
 411    }
 412
 413    private static void SerializeService(StringBuilder sb, GraphService service, bool isLast)
 414    {
 415        sb.AppendLine("    {");
 416        sb.AppendLine($"      \"id\": \"{Escape(service.Id)}\",");
 417        sb.AppendLine($"      \"typeName\": \"{Escape(service.TypeName)}\",");
 418        sb.AppendLine($"      \"fullTypeName\": \"{Escape(service.FullTypeName)}\",");
 419        sb.AppendLine($"      \"assemblyName\": {NullableString(service.AssemblyName)},");
 420
 421        // Interfaces
 422        sb.AppendLine("      \"interfaces\": [");
 423        for (int i = 0; i < service.Interfaces.Count; i++)
 424        {
 425            var iface = service.Interfaces[i];
 426            var comma = i < service.Interfaces.Count - 1 ? "," : "";
 427            sb.AppendLine("        {");
 428            sb.AppendLine($"          \"name\": \"{Escape(iface.Name)}\",");
 429            sb.AppendLine($"          \"fullName\": \"{Escape(iface.FullName)}\",");
 430            if (iface.Location != null)
 431            {
 432                sb.AppendLine("          \"location\": {");
 433                sb.AppendLine($"            \"filePath\": {NullableString(iface.Location.FilePath)},");
 434                sb.AppendLine($"            \"line\": {iface.Location.Line},");
 435                sb.AppendLine($"            \"column\": {iface.Location.Column}");
 436                sb.AppendLine("          }");
 437            }
 438            else
 439            {
 440                sb.AppendLine("          \"location\": null");
 441            }
 442            sb.AppendLine($"        }}{comma}");
 443        }
 444        sb.AppendLine("      ],");
 445
 446        sb.AppendLine($"      \"lifetime\": \"{Escape(service.Lifetime)}\",");
 447
 448        // Location
 449        if (service.Location != null)
 450        {
 451            sb.AppendLine("      \"location\": {");
 452            sb.AppendLine($"        \"filePath\": {NullableString(service.Location.FilePath)},");
 453            sb.AppendLine($"        \"line\": {service.Location.Line},");
 454            sb.AppendLine($"        \"column\": {service.Location.Column}");
 455            sb.AppendLine("      },");
 456        }
 457        else
 458        {
 459            sb.AppendLine("      \"location\": null,");
 460        }
 461
 462        // Dependencies
 463        sb.AppendLine("      \"dependencies\": [");
 464        for (int i = 0; i < service.Dependencies.Count; i++)
 465        {
 466            var dep = service.Dependencies[i];
 467            var comma = i < service.Dependencies.Count - 1 ? "," : "";
 468            sb.AppendLine("        {");
 469            sb.AppendLine($"          \"parameterName\": \"{Escape(dep.ParameterName)}\",");
 470            sb.AppendLine($"          \"typeName\": \"{Escape(dep.TypeName)}\",");
 471            sb.AppendLine($"          \"fullTypeName\": \"{Escape(dep.FullTypeName)}\",");
 472            sb.AppendLine($"          \"resolvedTo\": {NullableString(dep.ResolvedTo)},");
 473            sb.AppendLine($"          \"resolvedLifetime\": {NullableString(dep.ResolvedLifetime)},");
 474            sb.AppendLine($"          \"isKeyed\": {dep.IsKeyed.ToString().ToLowerInvariant()},");
 475            sb.AppendLine($"          \"serviceKey\": {NullableString(dep.ServiceKey)}");
 476            sb.AppendLine($"        }}{comma}");
 477        }
 478        sb.AppendLine("      ],");
 479
 480        // Decorators
 481        sb.AppendLine("      \"decorators\": [");
 482        for (int i = 0; i < service.Decorators.Count; i++)
 483        {
 484            var dec = service.Decorators[i];
 485            var comma = i < service.Decorators.Count - 1 ? "," : "";
 486            sb.AppendLine($"        {{ \"typeName\": \"{Escape(dec.TypeName)}\", \"order\": {dec.Order} }}{comma}");
 487        }
 488        sb.AppendLine("      ],");
 489
 490        // Interceptors
 491        sb.Append("      \"interceptors\": [");
 492        sb.Append(string.Join(", ", service.Interceptors.Select(i => $"\"{Escape(i)}\"")));
 493        sb.AppendLine("],");
 494
 495        // Attributes
 496        sb.Append("      \"attributes\": [");
 497        sb.Append(string.Join(", ", service.Attributes.Select(a => $"\"{Escape(a)}\"")));
 498        sb.AppendLine("],");
 499
 500        // Service keys
 501        sb.Append("      \"serviceKeys\": [");
 502        sb.Append(string.Join(", ", service.ServiceKeys.Select(k => $"\"{Escape(k)}\"")));
 503        sb.AppendLine("],");
 504
 505        // Metadata
 506        sb.AppendLine("      \"metadata\": {");
 507        sb.AppendLine($"        \"hasFactory\": {service.Metadata.HasFactory.ToString().ToLowerInvariant()},");
 508        sb.AppendLine($"        \"hasOptions\": {service.Metadata.HasOptions.ToString().ToLowerInvariant()},");
 509        sb.AppendLine($"        \"isHostedService\": {service.Metadata.IsHostedService.ToString().ToLowerInvariant()},")
 510        sb.AppendLine($"        \"isDisposable\": {service.Metadata.IsDisposable.ToString().ToLowerInvariant()},");
 511        sb.AppendLine($"        \"isPlugin\": {service.Metadata.IsPlugin.ToString().ToLowerInvariant()}");
 512        sb.AppendLine("      }");
 513
 514        sb.AppendLine(isLast ? "    }" : "    },");
 515    }
 516
 517    private static void SerializeDiagnostic(StringBuilder sb, GraphDiagnostic diagnostic, bool isLast)
 518    {
 519        sb.AppendLine("    {");
 520        sb.AppendLine($"      \"id\": \"{Escape(diagnostic.Id)}\",");
 521        sb.AppendLine($"      \"severity\": \"{Escape(diagnostic.Severity)}\",");
 522        sb.AppendLine($"      \"message\": \"{Escape(diagnostic.Message)}\",");
 523
 524        if (diagnostic.Location != null)
 525        {
 526            sb.AppendLine("      \"location\": {");
 527            sb.AppendLine($"        \"filePath\": {NullableString(diagnostic.Location.FilePath)},");
 528            sb.AppendLine($"        \"line\": {diagnostic.Location.Line},");
 529            sb.AppendLine($"        \"column\": {diagnostic.Location.Column}");
 530            sb.AppendLine("      },");
 531        }
 532        else
 533        {
 534            sb.AppendLine("      \"location\": null,");
 535        }
 536
 537        sb.Append("      \"relatedServices\": [");
 538        sb.Append(string.Join(", ", diagnostic.RelatedServices.Select(s => $"\"{Escape(s)}\"")));
 539        sb.AppendLine("]");
 540
 541        sb.AppendLine(isLast ? "    }" : "    },");
 542    }
 543
 544    private static string Escape(string value)
 545    {
 546        if (string.IsNullOrEmpty(value))
 547            return value;
 548
 549        return value
 550            .Replace("\\", "\\\\")
 551            .Replace("\"", "\\\"")
 552            .Replace("\n", "\\n")
 553            .Replace("\r", "\\r")
 554            .Replace("\t", "\\t");
 555    }
 556
 557    private static string NullableString(string? value)
 558    {
 559        return value == null ? "null" : $"\"{Escape(value)}\"";
 560    }
 561
 562    /// <summary>
 563    /// Generates the NeedlrGraph.g.cs source file that embeds the graph JSON
 564    /// in a generated class for IDE tooling.
 565    /// </summary>
 566    internal static string GenerateGraphExportSource(string graphJson, string assemblyName, BreadcrumbWriter breadcrumbs
 567    {
 568        var sb = new StringBuilder();
 569
 570        breadcrumbs.WriteFileHeader(sb, assemblyName, "Needlr IDE Graph Export");
 571
 572        sb.AppendLine("using System;");
 573        sb.AppendLine("using System.IO;");
 574        sb.AppendLine();
 575        sb.AppendLine($"namespace {assemblyName}.Generated");
 576        sb.AppendLine("{");
 577        sb.AppendLine("    /// <summary>");
 578        sb.AppendLine("    /// Provides the Needlr dependency graph for IDE tooling.");
 579        sb.AppendLine("    /// </summary>");
 580        sb.AppendLine("    internal static class NeedlrGraphExport");
 581        sb.AppendLine("    {");
 582        sb.AppendLine("        /// <summary>");
 583        sb.AppendLine("        /// Gets the dependency graph JSON.");
 584        sb.AppendLine("        /// </summary>");
 585        sb.AppendLine("        public static string GraphJson => GraphJsonContent;");
 586        sb.AppendLine();
 587        sb.AppendLine("        private const string GraphJsonContent = @\"");
 588
 589        // Escape the JSON for C# verbatim string (double quotes only)
 590        var escapedJson = graphJson.Replace("\"", "\"\"");
 591        sb.Append(escapedJson);
 592
 593        sb.AppendLine("\";");
 594        sb.AppendLine();
 595        sb.AppendLine("        /// <summary>");
 596        sb.AppendLine("        /// Writes the graph to the specified path.");
 597        sb.AppendLine("        /// </summary>");
 598        sb.AppendLine("        public static void WriteGraphToFile(string path)");
 599        sb.AppendLine("        {");
 600        sb.AppendLine("            File.WriteAllText(path, GraphJson);");
 601        sb.AppendLine("        }");
 602        sb.AppendLine("    }");
 603        sb.AppendLine("}");
 604
 605        return sb.ToString();
 606    }
 607}
 608
 609/// <summary>
 610/// Represents a diagnostic collected during generation for inclusion in the graph.
 611/// </summary>
 612internal sealed class CollectedDiagnostic
 613{
 18614    public string Id { get; set; } = string.Empty;
 18615    public string Severity { get; set; } = string.Empty;
 18616    public string Message { get; set; } = string.Empty;
 16617    public string? FilePath { get; set; }
 10618    public int Line { get; set; }
 10619    public IReadOnlyList<string>? RelatedServices { get; set; }
 620}