Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619// <auto-generated />#nullable enable
using System;using System.Collections.Generic;using CarpaNet.Models;using CarpaNet.Utilities;
namespace CarpaNet.Generation;
/// <summary>/// Generates C# classes for Lexicon query, procedure, and subscription types./// </summary>public static class ApiGenerator{ /// <summary> /// Generates parameter class for a query or procedure. /// </summary> public static void GenerateParametersClass( SourceBuilder sb, string className, LexiconDefinition def, string currentNsid, TypeRegistry registry) { if (def.Parameters == null || def.Parameters.Properties == null) { return; }
var requiredProps = def.Parameters.Required ?? new List<string>(); var paramClassName = $"{className}Parameters";
// Generate inline union interfaces for union properties GenerateInlineUnionInterfaces(sb, paramClassName, def.Parameters.Properties, currentNsid, registry);
sb.WriteSummary($"Parameters for {NsidHelper.ToTypeName(currentNsid)}."); sb.AppendLine($"public partial class {paramClassName}"); sb.OpenBrace();
foreach (var prop in def.Parameters.Properties) { ObjectGenerator.GenerateProperty( sb, paramClassName, prop.Key, prop.Value, currentNsid, registry, requiredProps, new List<string>()); }
// Generate ToDictionary method for converting to query parameters GenerateToDictionaryMethod(sb, def.Parameters.Properties, requiredProps);
sb.CloseBrace(); }
/// <summary> /// Generates the ToDictionary method for a parameters class. /// </summary> private static void GenerateToDictionaryMethod( SourceBuilder sb, Dictionary<string, LexiconDefinition> properties, List<string> requiredProps) { sb.AppendLine(); sb.WriteSummary("Converts the parameters to a dictionary for query string serialization."); sb.AppendLine("public System.Collections.Generic.IReadOnlyDictionary<string, string> ToDictionary()"); sb.OpenBrace(); sb.AppendLine("var dict = new System.Collections.Generic.Dictionary<string, string>();"); sb.AppendLine();
foreach (var prop in properties) { var propName = NsidHelper.ToPascalCase(prop.Key); var jsonName = prop.Key; var isRequired = requiredProps.Contains(prop.Key); var propType = prop.Value.Type;
// Handle arrays if (propType == "array") { sb.AppendLine($"if ({propName} != null)"); sb.OpenBrace(); sb.AppendLine($"foreach (var item in {propName})"); sb.OpenBrace(); if (prop.Value.Items?.Type == "string") { sb.AppendLine($"dict.Add(\"{jsonName}\", item);"); } else { sb.AppendLine($"dict.Add(\"{jsonName}\", item?.ToString() ?? \"\");"); } sb.CloseBrace(); sb.CloseBrace(); } // Handle boolean else if (propType == "boolean") { if (isRequired) { sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.ToString().ToLowerInvariant();"); } else { sb.AppendLine($"if ({propName} != null)"); sb.OpenBrace(); sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.Value.ToString().ToLowerInvariant();"); sb.CloseBrace(); } } // Handle integer else if (propType == "integer") { if (isRequired) { sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.ToString();"); } else { sb.AppendLine($"if ({propName} != null)"); sb.OpenBrace(); sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.Value.ToString();"); sb.CloseBrace(); } } // Handle string type (may have special formats) else if (propType == "string") { var format = prop.Value.Format;
// datetime format maps to DateTimeOffset (value type) if (format == "datetime") { if (isRequired) { sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.ToString(\"o\")!;"); } else { sb.AppendLine($"if ({propName} != null)"); sb.OpenBrace(); sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.Value.ToString(\"o\")!;"); sb.CloseBrace(); } } // AT Protocol identifier formats map to reference types with ToString() else if (format == "at-identifier" || format == "at-uri" || format == "did" || format == "handle") { if (isRequired) { sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.ToString()!;"); } else { sb.AppendLine($"if ({propName} != null)"); sb.OpenBrace(); sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.ToString()!;"); sb.CloseBrace(); } } // All other formats (cid, nsid, tid, record-key, uri, language) map to plain string else { if (isRequired) { sb.AppendLine($"dict[\"{jsonName}\"] = {propName};"); } else { sb.AppendLine($"if ({propName} != null)"); sb.OpenBrace(); sb.AppendLine($"dict[\"{jsonName}\"] = {propName};"); sb.CloseBrace(); } } } // Handle other reference types (ATUri, ATDid, etc.) else { if (isRequired) { // Required reference type - ToString() is safe sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.ToString()!;"); } else { // Optional reference type - check for null first sb.AppendLine($"if ({propName} != null)"); sb.OpenBrace(); sb.AppendLine($"dict[\"{jsonName}\"] = {propName}.ToString()!;"); sb.CloseBrace(); } }
sb.AppendLine(); }
sb.AppendLine("return dict;"); sb.CloseBrace(); }
/// <summary> /// Generates input class for a procedure. /// </summary> public static void GenerateInputClass( SourceBuilder sb, string className, LexiconIO input, string currentNsid, TypeRegistry registry) { if (input.Schema == null) { return; }
// If the schema is a direct ref, the referenced type already exists — skip wrapper class. if (input.Schema.Type == "ref" && !string.IsNullOrEmpty(input.Schema.Ref)) { return; }
var inputClassName = $"{className}Input";
if (input.Schema.Properties != null) { // Generate inline union interfaces for union properties GenerateInlineUnionInterfaces(sb, inputClassName, input.Schema.Properties, currentNsid, registry); }
sb.WriteSummary(input.Description ?? $"Input for {className}."); sb.AppendLine($"public partial class {inputClassName}"); sb.OpenBrace();
if (input.Schema.Properties != null) { var requiredProps = input.Schema.Required ?? new List<string>(); var nullableProps = input.Schema.Nullable ?? new List<string>();
foreach (var prop in input.Schema.Properties) { ObjectGenerator.GenerateProperty( sb, inputClassName, prop.Key, prop.Value, currentNsid, registry, requiredProps, nullableProps); } }
sb.CloseBrace(); }
/// <summary> /// Generates output class for a query or procedure. /// </summary> public static void GenerateOutputClass( SourceBuilder sb, string className, LexiconIO output, string currentNsid, TypeRegistry registry) { if (output.Schema == null) { return; }
// If the schema is a direct ref, the referenced type already exists — skip wrapper class. if (output.Schema.Type == "ref" && !string.IsNullOrEmpty(output.Schema.Ref)) { return; }
var outputClassName = $"{className}Output";
if (output.Schema.Properties != null) { // Generate inline union interfaces for union properties GenerateInlineUnionInterfaces(sb, outputClassName, output.Schema.Properties, currentNsid, registry); }
sb.WriteSummary(output.Description ?? $"Output for {className}."); sb.AppendLine($"public partial class {outputClassName}"); sb.OpenBrace();
if (output.Schema.Properties != null) { var requiredProps = output.Schema.Required ?? new List<string>(); var nullableProps = output.Schema.Nullable ?? new List<string>();
foreach (var prop in output.Schema.Properties) { ObjectGenerator.GenerateProperty( sb, outputClassName, prop.Key, prop.Value, currentNsid, registry, requiredProps, nullableProps); } }
sb.CloseBrace(); }
/// <summary> /// Generates inline union interfaces for properties with union types. /// </summary> private static void GenerateInlineUnionInterfaces( SourceBuilder sb, string className, Dictionary<string, LexiconDefinition> properties, string currentNsid, TypeRegistry registry) { foreach (var prop in properties) { if (prop.Value.Type == "union" && prop.Value.Refs != null) { // Strip @ prefix from className if present (for escaped keywords) var cleanClassName = NsidHelper.StripEscapePrefix(className); var cleanPropertyName = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(prop.Key)); var interfaceName = $"I{cleanClassName}{cleanPropertyName}"; UnionGenerator.GenerateUnionInterface(sb, interfaceName, prop.Value, currentNsid, registry); sb.AppendLine(); }
// Also handle arrays of unions if (prop.Value.Type == "array" && prop.Value.Items?.Type == "union" && prop.Value.Items.Refs != null) { var cleanClassName = NsidHelper.StripEscapePrefix(className); var cleanPropertyName = NsidHelper.StripEscapePrefix(NsidHelper.ToPascalCase(prop.Key)); var interfaceName = $"I{cleanClassName}{cleanPropertyName}"; UnionGenerator.GenerateUnionInterface(sb, interfaceName, prop.Value.Items, currentNsid, registry); sb.AppendLine(); } } }
/// <summary> /// Generates error classes for a query, procedure, or subscription. /// </summary> public static void GenerateErrorClasses( SourceBuilder sb, string className, List<LexiconError>? errors, string currentNsid) { if (errors == null || errors.Count == 0) { return; }
sb.WriteSummary($"Error codes for {className}."); sb.AppendLine($"public static class {className}Errors"); sb.OpenBrace();
foreach (var error in errors) { if (!string.IsNullOrEmpty(error.Description)) { sb.WriteSummary(error.Description); } sb.AppendLine($"public const string {NsidHelper.ToPascalCase(error.Name)} = \"{error.Name}\";"); }
sb.CloseBrace(); }
/// <summary> /// Returns the fully qualified C# type for an output schema. /// If the schema is a direct ref, resolves to the referenced type. /// Otherwise returns "{namespace}.{className}Output". /// </summary> public static string ResolveOutputType(LexiconDefinition def, string currentNsid, string currentNamespace, string className, TypeRegistry registry) { if (def.Output?.Schema?.Type == "ref" && !string.IsNullOrEmpty(def.Output.Schema.Ref)) { return registry.ResolveToCSharpType(def.Output.Schema.Ref, currentNsid); } return $"{currentNamespace}.{className}Output"; }
/// <summary> /// Returns the fully qualified C# type for an input schema. /// If the schema is a direct ref, resolves to the referenced type. /// Otherwise returns "{namespace}.{className}Input". /// </summary> public static string ResolveInputType(LexiconDefinition def, string currentNsid, string currentNamespace, string className, TypeRegistry registry) { if (def.Input?.Schema?.Type == "ref" && !string.IsNullOrEmpty(def.Input.Schema.Ref)) { return registry.ResolveToCSharpType(def.Input.Schema.Ref, currentNsid); } return $"{currentNamespace}.{className}Input"; }
/// <summary> /// Returns true if the output schema is a direct ref (no wrapper class needed). /// </summary> public static bool IsOutputRef(LexiconDefinition def) { return def.Output?.Schema?.Type == "ref" && !string.IsNullOrEmpty(def.Output.Schema.Ref); }
/// <summary> /// Returns true if the input schema is a direct ref (no wrapper class needed). /// </summary> public static bool IsInputRef(LexiconDefinition def) { return def.Input?.Schema?.Type == "ref" && !string.IsNullOrEmpty(def.Input.Schema.Ref); }
/// <summary> /// Gets the proxy service DID for an NSID that requires proxying through the PDS. /// </summary> /// <param name="nsid">The NSID to check.</param> /// <returns>The proxy service DID constant, or null if no proxy is needed.</returns> private static string? GetProxyServiceDid(string nsid) { if (nsid.StartsWith("chat.bsky.", StringComparison.Ordinal)) return "CarpaNet.BlueskyServices.ChatServiceDid";
if (nsid.StartsWith("tools.ozone.", StringComparison.Ordinal)) return "CarpaNet.BlueskyServices.OzoneServiceDid";
return null; }
/// <summary> /// Generates extension method for a query. /// </summary> public static void GenerateQueryExtension( SourceBuilder sb, string className, LexiconDefinition def, string currentNsid, string currentNamespace, TypeRegistry registry) { var hasParameters = def.Parameters?.Properties != null && def.Parameters.Properties.Count > 0; var hasOutput = def.Output?.Schema != null; var proxyServiceDid = GetProxyServiceDid(currentNsid); var outputType = hasOutput ? ResolveOutputType(def, currentNsid, currentNamespace, className, registry) : "object"; // Use full namespace path in method name to avoid collisions var methodName = $"{currentNamespace.Replace(".", "")}{className}Async";
sb.WriteSummary(def.Description); sb.AppendLine($"public static async System.Threading.Tasks.Task<{outputType}> {methodName}("); sb.Indent(); sb.AppendLine("this CarpaNet.IATProtoClient client,");
if (hasParameters) { sb.AppendLine($"{currentNamespace}.{className}Parameters? parameters = null,"); }
sb.AppendLine("System.Threading.CancellationToken cancellationToken = default)"); sb.Unindent();
sb.OpenBrace();
if (proxyServiceDid != null) { // Use the proxy overload for services that require proxying sb.AppendLine($"return await client.GetAsync<{outputType}>("); sb.Indent(); sb.AppendLine($"\"{currentNsid}\","); sb.AppendLine($"{proxyServiceDid},"); sb.AppendLine(hasParameters ? "parameters?.ToDictionary()," : "null,"); sb.AppendLine("cancellationToken);"); sb.Unindent(); } else { sb.AppendLine($"return await client.GetAsync<{outputType}>("); sb.Indent(); sb.AppendLine($"\"{currentNsid}\","); sb.AppendLine(hasParameters ? "parameters?.ToDictionary()," : "null,"); sb.AppendLine("cancellationToken);"); sb.Unindent(); }
sb.CloseBrace(); }
/// <summary> /// Generates extension method for a procedure. /// </summary> public static void GenerateProcedureExtension( SourceBuilder sb, string className, LexiconDefinition def, string currentNsid, string currentNamespace, TypeRegistry registry) { var hasInput = def.Input?.Schema != null; var hasOutput = def.Output?.Schema != null; var proxyServiceDid = GetProxyServiceDid(currentNsid); // Use full namespace path in method name to avoid collisions var methodName = $"{currentNamespace.Replace(".", "")}{className}Async"; var returnType = hasOutput ? ResolveOutputType(def, currentNsid, currentNamespace, className, registry) : "object"; var inputType = hasInput ? ResolveInputType(def, currentNsid, currentNamespace, className, registry) : "object";
sb.WriteSummary(def.Description); sb.AppendLine($"public static async System.Threading.Tasks.Task<{returnType}> {methodName}("); sb.Indent(); sb.AppendLine("this CarpaNet.IATProtoClient client,");
if (hasInput) { sb.AppendLine($"{inputType} input,"); }
sb.AppendLine("System.Threading.CancellationToken cancellationToken = default)"); sb.Unindent();
sb.OpenBrace();
if (proxyServiceDid != null) { // Use the proxy overload for services that require proxying sb.AppendLine($"return await client.PostAsync<{inputType}, {returnType}>("); sb.Indent(); sb.AppendLine($"\"{currentNsid}\","); sb.AppendLine($"{proxyServiceDid},"); sb.AppendLine(hasInput ? "input," : "null,"); sb.AppendLine("cancellationToken);"); sb.Unindent(); } else { sb.AppendLine($"return await client.PostAsync<{inputType}, {returnType}>("); sb.Indent(); sb.AppendLine($"\"{currentNsid}\","); sb.AppendLine(hasInput ? "input," : "null,"); sb.AppendLine("cancellationToken);"); sb.Unindent(); }
sb.CloseBrace(); }
/// <summary> /// Generates subscription message interface only (no extension method). /// </summary> public static void GenerateSubscriptionMessageTypes( SourceBuilder sb, string className, LexiconDefinition def, string currentNsid, TypeRegistry registry) { if (def.Message?.Schema == null) { return; }
// Generate the message union interface var interfaceName = $"I{className}Message"; UnionGenerator.GenerateUnionInterface(sb, interfaceName, def.Message.Schema, currentNsid, registry); }
/// <summary> /// Generates extension method for a subscription. /// </summary> public static void GenerateSubscriptionExtension( SourceBuilder sb, string className, LexiconDefinition def, string currentNsid, string currentNamespace, TypeRegistry registry) { if (def.Message?.Schema == null) { return; }
var interfaceName = $"I{className}Message"; var hasParameters = def.Parameters?.Properties != null && def.Parameters.Properties.Count > 0; // Use full namespace path in method name to avoid collisions var methodName = $"{currentNamespace.Replace(".", "")}{className}Async";
sb.WriteSummary(def.Description); sb.AppendLine($"public static System.Collections.Generic.IAsyncEnumerable<{currentNamespace}.{interfaceName}> {methodName}("); sb.Indent(); sb.AppendLine("this CarpaNet.IATProtoClient client,");
if (hasParameters) { sb.AppendLine($"{currentNamespace}.{className}Parameters? parameters = null,"); }
sb.AppendLine("System.Threading.CancellationToken cancellationToken = default)"); sb.Unindent();
sb.OpenBrace(); sb.AppendLine($"return client.SubscribeAsync<{currentNamespace}.{interfaceName}>("); sb.Indent(); sb.AppendLine($"\"{currentNsid}\","); sb.AppendLine(hasParameters ? "parameters?.ToDictionary()," : "null,"); sb.AppendLine("cancellationToken);"); sb.Unindent(); sb.CloseBrace(); }}