Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424// <auto-generated />#nullable enable
using System;using System.Collections.Generic;using System.Linq;using CarpaNet.Models;using CarpaNet.Utilities;
namespace CarpaNet.Generation;
/// <summary>/// Generates abstract ASP.NET controller classes for XRPC server endpoints./// </summary>public static class XrpcEndpointGenerator{ /// <summary> /// Generates all XRPC controllers from the given namespace-grouped lexicons. /// </summary> public static string Generate( Dictionary<string, List<(string Nsid, LexiconDocument Doc)>> byNamespace, TypeRegistry registry, GeneratorOptions options) { // Collect all query/procedure definitions and group by controller (first 3 NSID segments) var controllerGroups = new Dictionary<string, List<EndpointInfo>>();
foreach (var kvp in byNamespace) { var ns = kvp.Key; foreach (var (nsid, doc) in kvp.Value) { if (doc.Defs == null) continue;
foreach (var def in doc.Defs) { if (def.Value.Type != "query" && def.Value.Type != "procedure") continue;
var groupKey = GetControllerGroup(nsid); if (groupKey == null) continue;
if (!controllerGroups.TryGetValue(groupKey, out var list)) { list = new List<EndpointInfo>(); controllerGroups[groupKey] = list; }
var className = NsidHelper.ToTypeName(nsid); list.Add(new EndpointInfo { Nsid = nsid, ClassName = className, Definition = def.Value, Namespace = ns, }); } } }
if (controllerGroups.Count == 0) return string.Empty;
var sb = new SourceBuilder(); sb.WriteHeader();
foreach (var kvp in controllerGroups.OrderBy(x => x.Key)) { var groupNsid = kvp.Key; var endpoints = kvp.Value; var controllerName = GetControllerName(groupNsid); var controllerNamespace = GetControllerNamespace(groupNsid, options.RootNamespace);
sb.WriteNamespaceBlock(controllerNamespace); GenerateController(sb, groupNsid, controllerName, endpoints, registry, options); sb.CloseBrace(); // namespace sb.AppendLine(); }
return sb.ToString(); }
/// <summary> /// Extracts the controller group from an NSID (first 3 segments). /// For example, "app.bsky.actor.getProfile" returns "app.bsky.actor". /// </summary> public static string? GetControllerGroup(string nsid) { var parts = nsid.Split('.'); if (parts.Length < 4) return null; return $"{parts[0]}.{parts[1]}.{parts[2]}"; }
/// <summary> /// Gets the controller class name from a group NSID. /// For example, "app.bsky.actor" returns "ActorController". /// </summary> public static string GetControllerName(string groupNsid) { var parts = groupNsid.Split('.'); return NsidHelper.ToPascalCase(parts[parts.Length - 1]) + "Controller"; }
/// <summary> /// Gets the namespace for a controller. /// For example, "app.bsky.actor" with root "MyApp" returns "MyApp.Xrpc.AppBsky.Actor". /// </summary> public static string GetControllerNamespace(string groupNsid, string? rootNamespace) { var nsidNamespace = NsidHelper.ToNamespace(groupNsid + ".placeholder", rootNamespace); if (rootNamespace != null) return $"{rootNamespace}.Xrpc.{nsidNamespace.Substring(rootNamespace.Length + 1)}"; return $"Xrpc.{nsidNamespace}"; }
/// <summary> /// Generates an abstract controller class for a group of endpoints. /// </summary> internal static void GenerateController( SourceBuilder sb, string groupNsid, string controllerName, List<EndpointInfo> endpoints, TypeRegistry registry, GeneratorOptions options) { sb.WriteSummary($"Abstract XRPC controller for {groupNsid} endpoints."); sb.WriteAttribute("Microsoft.AspNetCore.Mvc.ApiController"); sb.AppendLine($"public abstract partial class {controllerName} : Microsoft.AspNetCore.Mvc.ControllerBase"); sb.OpenBrace();
for (int i = 0; i < endpoints.Count; i++) { var endpoint = endpoints[i]; if (i > 0) sb.AppendLine();
if (endpoint.Definition.Type == "query") GenerateQueryMethod(sb, endpoint, registry, options); else if (endpoint.Definition.Type == "procedure") GenerateProcedureMethod(sb, endpoint, registry, options); }
sb.CloseBrace(); // class }
/// <summary> /// Generates an abstract method for a query (HTTP GET) endpoint. /// </summary> internal static void GenerateQueryMethod( SourceBuilder sb, EndpointInfo endpoint, TypeRegistry registry, GeneratorOptions options) { var def = endpoint.Definition; var hasOutput = def.Output?.Schema != null; var returnType = GetReturnType(endpoint, registry, hasOutput); var methodName = GetMethodName(endpoint.Nsid) + "Async";
sb.WriteSummary(def.Description ?? $"XRPC query: {endpoint.Nsid}"); sb.WriteAttribute($"Microsoft.AspNetCore.Mvc.HttpGet(\"/xrpc/{endpoint.Nsid}\")"); sb.Append(""); sb.AppendIndent(); sb.Append($"public abstract System.Threading.Tasks.Task<{returnType}> {methodName}(");
var parameters = BuildQueryParameters(def, endpoint.Nsid, registry); WriteParameterList(sb, parameters);
sb.Append(");\n"); }
/// <summary> /// Generates an abstract method for a procedure (HTTP POST) endpoint. /// </summary> internal static void GenerateProcedureMethod( SourceBuilder sb, EndpointInfo endpoint, TypeRegistry registry, GeneratorOptions options) { var def = endpoint.Definition; var hasInput = def.Input?.Schema != null; var hasOutput = def.Output?.Schema != null; var returnType = GetReturnType(endpoint, registry, hasOutput); var methodName = GetMethodName(endpoint.Nsid) + "Async";
sb.WriteSummary(def.Description ?? $"XRPC procedure: {endpoint.Nsid}"); sb.WriteAttribute($"Microsoft.AspNetCore.Mvc.HttpPost(\"/xrpc/{endpoint.Nsid}\")"); sb.Append(""); sb.AppendIndent(); sb.Append($"public abstract System.Threading.Tasks.Task<{returnType}> {methodName}(");
var parameters = new List<ParameterDef>();
if (hasInput) { var inputType = ApiGenerator.ResolveInputType(def, endpoint.Nsid, endpoint.Namespace, endpoint.ClassName, registry); parameters.Add(new ParameterDef { Attribute = "Microsoft.AspNetCore.Mvc.FromBody", Type = $"global::{inputType}", Name = "input", IsOptional = false, }); }
parameters.Add(new ParameterDef { Type = "System.Threading.CancellationToken", Name = "cancellationToken", DefaultValue = "default", IsOptional = true, });
WriteParameterList(sb, parameters);
sb.Append(");\n"); }
/// <summary> /// Builds the parameter list for a query method from the definition's parameters. /// </summary> private static List<ParameterDef> BuildQueryParameters( LexiconDefinition def, string currentNsid, TypeRegistry registry) { var parameters = new List<ParameterDef>();
if (def.Parameters?.Properties != null) { var requiredProps = def.Parameters.Required ?? new List<string>();
foreach (var prop in def.Parameters.Properties) { var isRequired = requiredProps.Contains(prop.Key); var csharpType = ResolveParameterType(prop.Value, currentNsid, registry); var isArray = prop.Value.Type == "array";
if (!isRequired && !isArray) { csharpType = MakeNullable(csharpType); }
parameters.Add(new ParameterDef { Attribute = "Microsoft.AspNetCore.Mvc.FromQuery", AttributeArgs = $"Name = \"{prop.Key}\"", Type = csharpType, Name = NsidHelper.EscapeIdentifier(NsidHelper.ToCamelCase(prop.Key)), DefaultValue = isRequired ? null : "default", IsOptional = !isRequired, }); } }
parameters.Add(new ParameterDef { Type = "System.Threading.CancellationToken", Name = "cancellationToken", DefaultValue = "default", IsOptional = true, });
return parameters; }
/// <summary> /// Resolves a parameter definition to its C# type. /// </summary> internal static string ResolveParameterType(LexiconDefinition def, string currentNsid, TypeRegistry registry) { return def.Type switch { "boolean" => "bool", "integer" => "long", "string" => MapStringFormat(def), "array" => ResolveArrayParameterType(def, currentNsid, registry), "ref" when def.Ref != null => registry.ResolveToCSharpType(def.Ref, currentNsid), _ => "string", }; }
/// <summary> /// Maps a string type's format to a C# type for query parameters. /// </summary> private static string MapStringFormat(LexiconDefinition def) { if (def.Format == null) return "string";
return def.Format switch { "at-identifier" => "string", "at-uri" => "string", "cid" => "string", "datetime" => "string", "did" => "string", "handle" => "string", "nsid" => "string", "tid" => "string", "record-key" => "string", "uri" => "string", "language" => "string", _ => "string", }; }
/// <summary> /// Resolves an array parameter type. /// </summary> private static string ResolveArrayParameterType(LexiconDefinition def, string currentNsid, TypeRegistry registry) { if (def.Items == null) return "System.Collections.Generic.List<string>";
var itemType = ResolveParameterType(def.Items, currentNsid, registry); return $"System.Collections.Generic.List<{itemType}>"; }
/// <summary> /// Gets the return type for an endpoint. /// </summary> private static string GetReturnType(EndpointInfo endpoint, TypeRegistry registry, bool hasOutput) { if (hasOutput) { var outputType = ApiGenerator.ResolveOutputType( endpoint.Definition, endpoint.Nsid, endpoint.Namespace, endpoint.ClassName, registry); return $"Microsoft.AspNetCore.Http.HttpResults.Results<Microsoft.AspNetCore.Http.HttpResults.Ok<global::{outputType}>, CarpaNet.AspNetCore.ATErrorResult>"; } return "Microsoft.AspNetCore.Http.HttpResults.Results<Microsoft.AspNetCore.Http.HttpResults.Ok, CarpaNet.AspNetCore.ATErrorResult>"; }
/// <summary> /// Gets the method name from an NSID. Uses the last segment in PascalCase. /// For example, "app.bsky.actor.getProfile" returns "GetProfile". /// </summary> public static string GetMethodName(string nsid) { var parts = nsid.Split('.'); return NsidHelper.ToPascalCase(parts[parts.Length - 1]); }
/// <summary> /// Writes a parameter list inline. /// </summary> private static void WriteParameterList(SourceBuilder sb, List<ParameterDef> parameters) { if (parameters.Count == 0) return;
sb.Append("\n"); sb.Indent();
for (int i = 0; i < parameters.Count; i++) { var param = parameters[i]; sb.AppendIndent();
if (param.Attribute != null) { if (param.AttributeArgs != null) sb.Append($"[{param.Attribute}({param.AttributeArgs})] "); else sb.Append($"[{param.Attribute}] "); }
sb.Append($"{param.Type} {param.Name}");
if (param.DefaultValue != null) sb.Append($" = {param.DefaultValue}");
if (i < parameters.Count - 1) sb.Append(",");
sb.Append("\n"); }
sb.Unindent(); sb.AppendIndent(); }
/// <summary> /// Makes a type nullable by appending '?' if not already nullable. /// </summary> private static string MakeNullable(string type) { if (type.EndsWith("?")) return type;
// Reference types that are already nullable by convention if (type.StartsWith("System.Collections.Generic.List<")) return type + "?";
return type + "?"; }
/// <summary> /// Represents a method parameter to be emitted. /// </summary> internal sealed class ParameterDef { public string? Attribute { get; set; } public string? AttributeArgs { get; set; } public string Type { get; set; } = "object"; public string Name { get; set; } = "param"; public string? DefaultValue { get; set; } public bool IsOptional { get; set; } }
/// <summary> /// Represents a collected endpoint to generate. /// </summary> internal sealed class EndpointInfo { public string Nsid { get; set; } = ""; public string ClassName { get; set; } = ""; public LexiconDefinition Definition { get; set; } = new(); public string Namespace { get; set; } = ""; }}