//
#nullable enable
using System;
using System.Collections.Generic;
using CarpaNet.Models;
using CarpaNet.Utilities;
namespace CarpaNet.Generation;
///
/// Generates C# classes for Lexicon query, procedure, and subscription types.
///
public static class ApiGenerator
{
///
/// Generates parameter class for a query or procedure.
///
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();
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());
}
// Generate ToQueryParameters method for converting to query parameters
GenerateToQueryParametersMethod(sb, def.Parameters.Properties, requiredProps);
sb.CloseBrace();
}
///
/// Generates the ToQueryParameters method for a parameters class.
///
private static void GenerateToQueryParametersMethod(
SourceBuilder sb,
Dictionary properties,
List requiredProps)
{
sb.AppendLine();
sb.WriteSummary("Converts the parameters to a sequence of key/value pairs for query string serialization. " +
"Returns IEnumerable> rather than a dictionary so that array properties " +
"(e.g. uris on app.bsky.feed.getPosts) can emit repeated query parameters.");
sb.AppendLine("public System.Collections.Generic.IEnumerable> ToQueryParameters()");
sb.OpenBrace();
sb.AppendLine("var list = new System.Collections.Generic.List>();");
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($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", item));");
}
else
{
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", item?.ToString() ?? \"\"));");
}
sb.CloseBrace();
sb.CloseBrace();
}
// Handle boolean
else if (propType == "boolean")
{
if (isRequired)
{
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.ToString().ToLowerInvariant()));");
}
else
{
sb.AppendLine($"if ({propName} != null)");
sb.OpenBrace();
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.Value.ToString().ToLowerInvariant()));");
sb.CloseBrace();
}
}
// Handle integer
else if (propType == "integer")
{
if (isRequired)
{
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.ToString()));");
}
else
{
sb.AppendLine($"if ({propName} != null)");
sb.OpenBrace();
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{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($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.ToString(\"o\")!));");
}
else
{
sb.AppendLine($"if ({propName} != null)");
sb.OpenBrace();
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{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($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.ToString()!));");
}
else
{
sb.AppendLine($"if ({propName} != null)");
sb.OpenBrace();
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.ToString()!));");
sb.CloseBrace();
}
}
// All other formats (cid, nsid, tid, record-key, uri, language) map to plain string
else
{
if (isRequired)
{
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}));");
}
else
{
sb.AppendLine($"if ({propName} != null)");
sb.OpenBrace();
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}));");
sb.CloseBrace();
}
}
}
// Handle other reference types (ATUri, ATDid, etc.)
else
{
if (isRequired)
{
// Required reference type - ToString() is safe
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.ToString()!));");
}
else
{
// Optional reference type - check for null first
sb.AppendLine($"if ({propName} != null)");
sb.OpenBrace();
sb.AppendLine($"list.Add(new System.Collections.Generic.KeyValuePair(\"{jsonName}\", {propName}.ToString()!));");
sb.CloseBrace();
}
}
sb.AppendLine();
}
sb.AppendLine("return list;");
sb.CloseBrace();
}
///
/// Generates input class for a procedure.
///
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();
var nullableProps = input.Schema.Nullable ?? new List();
foreach (var prop in input.Schema.Properties)
{
ObjectGenerator.GenerateProperty(
sb,
inputClassName,
prop.Key,
prop.Value,
currentNsid,
registry,
requiredProps,
nullableProps);
}
}
sb.CloseBrace();
}
///
/// Generates output class for a query or procedure.
///
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();
var nullableProps = output.Schema.Nullable ?? new List();
foreach (var prop in output.Schema.Properties)
{
ObjectGenerator.GenerateProperty(
sb,
outputClassName,
prop.Key,
prop.Value,
currentNsid,
registry,
requiredProps,
nullableProps);
}
}
sb.CloseBrace();
}
///
/// Generates inline union interfaces for properties with union types.
///
private static void GenerateInlineUnionInterfaces(
SourceBuilder sb,
string className,
Dictionary 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();
}
}
}
///
/// Generates error classes for a query, procedure, or subscription.
///
public static void GenerateErrorClasses(
SourceBuilder sb,
string className,
List? 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();
}
///
/// 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".
///
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";
}
///
/// 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".
///
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";
}
///
/// Returns true if the output schema is a direct ref (no wrapper class needed).
///
public static bool IsOutputRef(LexiconDefinition def)
{
return def.Output?.Schema?.Type == "ref" && !string.IsNullOrEmpty(def.Output.Schema.Ref);
}
///
/// Returns true if the input schema is a direct ref (no wrapper class needed).
///
public static bool IsInputRef(LexiconDefinition def)
{
return def.Input?.Schema?.Type == "ref" && !string.IsNullOrEmpty(def.Input.Schema.Ref);
}
///
/// Gets the proxy service DID for an NSID that requires proxying through the PDS.
///
/// The NSID to check.
/// The proxy service DID constant, or null if no proxy is needed.
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;
}
///
/// Generates extension method for a query.
///
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?.ToQueryParameters()," : "null,");
sb.AppendLine("cancellationToken);");
sb.Unindent();
}
else
{
sb.AppendLine($"return await client.GetAsync<{outputType}>(");
sb.Indent();
sb.AppendLine($"\"{currentNsid}\",");
sb.AppendLine(hasParameters ? "parameters?.ToQueryParameters()," : "null,");
sb.AppendLine("cancellationToken);");
sb.Unindent();
}
sb.CloseBrace();
}
///
/// Generates extension method for a procedure.
///
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();
}
///
/// Generates subscription message interface only (no extension method).
///
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);
}
///
/// Generates extension method for a subscription.
///
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?.ToQueryParameters()," : "null,");
sb.AppendLine("cancellationToken);");
sb.Unindent();
sb.CloseBrace();
}
}