| | | 1 | | using System.Reflection; |
| | | 2 | | using System.Text; |
| | | 3 | | |
| | | 4 | | namespace Kestrun.Runtime; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Exports OpenAPI component classes as PowerShell class definitions. |
| | | 8 | | /// </summary> |
| | | 9 | | public static class PowerShellOpenApiClassExporter |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Holds valid class names to be used as type in the OpenAPI function definitions. |
| | | 13 | | /// </summary> |
| | 7 | 14 | | public static List<string> ValidClassNames { get; } = []; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Exports OpenAPI component classes found in loaded assemblies |
| | | 18 | | /// as PowerShell class definitions. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <returns>The path to the temporary PowerShell script containing the class definitions.</returns> |
| | | 21 | | public static string ExportOpenApiClasses() |
| | | 22 | | { |
| | 59 | 23 | | var assemblies = AppDomain.CurrentDomain.GetAssemblies() |
| | 17916 | 24 | | .Where(a => a.FullName is not null && |
| | 17916 | 25 | | a.FullName.Contains("PowerShell Class Assembly")) |
| | 59 | 26 | | .ToArray(); |
| | 59 | 27 | | return ExportOpenApiClasses(assemblies); |
| | | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Exports OpenAPI component classes found in the specified assemblies |
| | | 32 | | /// as PowerShell class definitions |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="assemblies">The assemblies to scan for OpenAPI component classes.</param> |
| | | 35 | | /// <returns>The path to the temporary PowerShell script containing the class definitions.</returns> |
| | | 36 | | public static string ExportOpenApiClasses(Assembly[] assemblies) |
| | | 37 | | { |
| | | 38 | | // 1. Collect all component classes |
| | 60 | 39 | | var componentTypes = assemblies |
| | 1 | 40 | | .SelectMany(a => a.GetTypes()) |
| | 3 | 41 | | .Where(t => t.IsClass && !t.IsAbstract) |
| | 60 | 42 | | .Where(HasOpenApiComponentAttribute) |
| | 60 | 43 | | .ToList(); |
| | | 44 | | |
| | | 45 | | // For quick lookup when choosing type names |
| | 60 | 46 | | var componentSet = new HashSet<Type>(componentTypes); |
| | | 47 | | |
| | | 48 | | // 2. Topologically sort by "uses other component as property type" |
| | 60 | 49 | | var sorted = TopologicalSortByPropertyDependencies(componentTypes, componentSet); |
| | | 50 | | // nothing to export |
| | 60 | 51 | | if (sorted.Count == 0) |
| | | 52 | | { |
| | 59 | 53 | | return string.Empty; |
| | | 54 | | } |
| | | 55 | | // 3. Emit PowerShell classes |
| | 1 | 56 | | var sb = new StringBuilder(); |
| | | 57 | | |
| | 8 | 58 | | foreach (var type in sorted) |
| | | 59 | | { |
| | | 60 | | // Skip types without full name (should not happen) |
| | 3 | 61 | | if (type.FullName is null) |
| | | 62 | | { |
| | | 63 | | continue; |
| | | 64 | | } |
| | 3 | 65 | | if (ValidClassNames.Contains(type.FullName)) |
| | | 66 | | { |
| | | 67 | | // Already registered remove old entry |
| | 0 | 68 | | _ = ValidClassNames.Remove(type.FullName); |
| | | 69 | | } |
| | | 70 | | // Register valid class name |
| | 3 | 71 | | ValidClassNames.Add(type.FullName); |
| | | 72 | | // Emit class definition |
| | 3 | 73 | | AppendClass(type, componentSet, sb); |
| | 3 | 74 | | _ = sb.AppendLine(); // blank line between classes |
| | | 75 | | } |
| | | 76 | | // 4. Write to temp script file |
| | 1 | 77 | | return WriteOpenApiTempScript(sb.ToString()); |
| | | 78 | | } |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Determines if the specified type has an OpenAPI component attribute. |
| | | 82 | | /// </summary> |
| | | 83 | | /// <param name="t"></param> |
| | | 84 | | /// <returns></returns> |
| | | 85 | | private static bool HasOpenApiComponentAttribute(Type t) |
| | | 86 | | { |
| | 3 | 87 | | return t.GetCustomAttributes(inherit: true) |
| | 3 | 88 | | .Select(a => a.GetType().Name) |
| | 3 | 89 | | .Any(n => |
| | 6 | 90 | | n.Contains("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase) || |
| | 6 | 91 | | n.Contains("OpenApiRequestBodyComponent", StringComparison.OrdinalIgnoreCase)); |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// Appends the PowerShell class definition for the specified type to the StringBuilder. |
| | | 96 | | /// </summary> |
| | | 97 | | /// <param name="type"></param> |
| | | 98 | | /// <param name="componentSet"></param> |
| | | 99 | | /// <param name="sb"></param> |
| | | 100 | | private static void AppendClass(Type type, HashSet<Type> componentSet, StringBuilder sb) |
| | | 101 | | { |
| | | 102 | | // Detect base type (for parenting) |
| | 3 | 103 | | var baseType = type.BaseType; |
| | 3 | 104 | | var baseClause = string.Empty; |
| | | 105 | | |
| | 3 | 106 | | if (baseType != null && baseType != typeof(object)) |
| | | 107 | | { |
| | | 108 | | // Use PS-friendly type name for the base |
| | 1 | 109 | | var basePsName = ToPowerShellTypeName(baseType, componentSet); |
| | 1 | 110 | | baseClause = $" : {basePsName}"; |
| | | 111 | | } |
| | | 112 | | |
| | 3 | 113 | | _ = sb.AppendLine($"class {type.Name}{baseClause} {{"); |
| | | 114 | | |
| | | 115 | | // Only properties *declared* on this type (no inherited ones) |
| | 3 | 116 | | var props = type.GetProperties( |
| | 3 | 117 | | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); |
| | | 118 | | |
| | 14 | 119 | | foreach (var p in props) |
| | | 120 | | { |
| | 4 | 121 | | var psType = ToPowerShellTypeName(p.PropertyType, componentSet); |
| | 4 | 122 | | _ = sb.AppendLine($" [{psType}]${p.Name}"); |
| | | 123 | | } |
| | | 124 | | |
| | 3 | 125 | | _ = sb.AppendLine("}"); |
| | 3 | 126 | | } |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Converts a .NET type to a PowerShell type name. |
| | | 130 | | /// </summary> |
| | | 131 | | /// <param name="t"></param> |
| | | 132 | | /// <param name="componentSet"></param> |
| | | 133 | | /// <returns></returns> |
| | | 134 | | private static string ToPowerShellTypeName(Type t, HashSet<Type> componentSet) |
| | | 135 | | { |
| | | 136 | | // Nullable<T> |
| | 6 | 137 | | if (Nullable.GetUnderlyingType(t) is Type underlying) |
| | | 138 | | { |
| | 0 | 139 | | return $"Nullable[{ToPowerShellTypeName(underlying, componentSet)}]"; |
| | | 140 | | } |
| | | 141 | | |
| | | 142 | | // Primitive mappings |
| | 6 | 143 | | if (t == typeof(long)) |
| | | 144 | | { |
| | 0 | 145 | | return "long"; |
| | | 146 | | } |
| | | 147 | | |
| | 6 | 148 | | if (t == typeof(int)) |
| | | 149 | | { |
| | 1 | 150 | | return "int"; |
| | | 151 | | } |
| | | 152 | | |
| | 5 | 153 | | if (t == typeof(bool)) |
| | | 154 | | { |
| | 0 | 155 | | return "bool"; |
| | | 156 | | } |
| | | 157 | | |
| | 5 | 158 | | if (t == typeof(string)) |
| | | 159 | | { |
| | 2 | 160 | | return "string"; |
| | | 161 | | } |
| | | 162 | | |
| | 3 | 163 | | if (t == typeof(double)) |
| | | 164 | | { |
| | 0 | 165 | | return "double"; |
| | | 166 | | } |
| | | 167 | | |
| | 3 | 168 | | if (t == typeof(float)) |
| | | 169 | | { |
| | 0 | 170 | | return "single"; |
| | | 171 | | } |
| | | 172 | | |
| | 3 | 173 | | if (t == typeof(object)) |
| | | 174 | | { |
| | 0 | 175 | | return "object"; |
| | | 176 | | } |
| | | 177 | | |
| | | 178 | | // Arrays |
| | 3 | 179 | | if (t.IsArray) |
| | | 180 | | { |
| | 1 | 181 | | var element = ToPowerShellTypeName(t.GetElementType()!, componentSet); |
| | 1 | 182 | | return $"{element}[]"; |
| | | 183 | | } |
| | | 184 | | |
| | | 185 | | // If the property type is itself one of the OpenAPI component classes, |
| | | 186 | | // use its *simple* name (Pet, User, Tag, Category, etc.) |
| | 2 | 187 | | if (componentSet.Contains(t)) |
| | | 188 | | { |
| | 2 | 189 | | return t.Name; |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | // Fallback for other reference types (you can change to t.Name if you prefer) |
| | 0 | 193 | | return t.FullName ?? t.Name; |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | /// <summary> |
| | | 197 | | /// Topologically sort types so that dependencies (property types) |
| | | 198 | | /// appear before the types that reference them. |
| | | 199 | | /// </summary> |
| | | 200 | | /// <param name="types">The list of types to sort.</param> |
| | | 201 | | /// <param name="componentSet">Set of component types for quick lookup.</param> |
| | | 202 | | /// <returns>The sorted list of types.</returns> |
| | | 203 | | private static List<Type> TopologicalSortByPropertyDependencies( |
| | | 204 | | List<Type> types, |
| | | 205 | | HashSet<Type> componentSet) |
| | | 206 | | { |
| | 60 | 207 | | var result = new List<Type>(); |
| | 60 | 208 | | var visited = new Dictionary<Type, bool>(); // false = temp-mark, true = perm-mark |
| | | 209 | | |
| | 126 | 210 | | foreach (var t in types) |
| | | 211 | | { |
| | 3 | 212 | | Visit(t, componentSet, visited, result); |
| | | 213 | | } |
| | | 214 | | |
| | 60 | 215 | | return result; |
| | | 216 | | } |
| | | 217 | | |
| | | 218 | | /// <summary> |
| | | 219 | | /// Visits the type and its dependencies recursively for topological sorting. |
| | | 220 | | /// </summary> |
| | | 221 | | /// <param name="t">Type to visit</param> |
| | | 222 | | /// <param name="componentSet">Set of component types</param> |
| | | 223 | | /// <param name="visited">Dictionary tracking visited types and their mark status</param> |
| | | 224 | | /// <param name="result">List to accumulate the sorted types</param> |
| | | 225 | | private static void Visit( |
| | | 226 | | Type t, |
| | | 227 | | HashSet<Type> componentSet, |
| | | 228 | | Dictionary<Type, bool> visited, |
| | | 229 | | List<Type> result) |
| | | 230 | | { |
| | 5 | 231 | | if (visited.TryGetValue(t, out var perm)) |
| | | 232 | | { |
| | 2 | 233 | | if (!perm) |
| | | 234 | | { |
| | | 235 | | // cycle; ignore for now |
| | 2 | 236 | | return; |
| | | 237 | | } |
| | | 238 | | return; |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | // temp-mark |
| | 3 | 242 | | visited[t] = false; |
| | | 243 | | |
| | 3 | 244 | | var deps = new List<Type>(); |
| | | 245 | | |
| | | 246 | | // 1) Dependencies via property types (component properties) |
| | 3 | 247 | | var propDeps = t.GetProperties(BindingFlags.Public | BindingFlags.Instance) |
| | 5 | 248 | | .Select(p => GetComponentDependencyType(p.PropertyType, componentSet)) |
| | 5 | 249 | | .Where(dep => dep is not null) |
| | 1 | 250 | | .Select(dep => dep!) |
| | 3 | 251 | | .Distinct(); |
| | | 252 | | |
| | 3 | 253 | | deps.AddRange(propDeps); |
| | | 254 | | |
| | | 255 | | // 2) Dependency via base type (parenting) |
| | 3 | 256 | | var baseType = t.BaseType; |
| | 3 | 257 | | if (baseType != null && componentSet.Contains(baseType)) |
| | | 258 | | { |
| | 1 | 259 | | deps.Add(baseType); |
| | | 260 | | } |
| | | 261 | | |
| | 10 | 262 | | foreach (var dep in deps.Distinct()) |
| | | 263 | | { |
| | 2 | 264 | | Visit(dep, componentSet, visited, result); |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | // perm-mark |
| | 3 | 268 | | visited[t] = true; |
| | 3 | 269 | | result.Add(t); |
| | 3 | 270 | | } |
| | | 271 | | |
| | | 272 | | private static Type? GetComponentDependencyType(Type propertyType, HashSet<Type> componentSet) |
| | | 273 | | { |
| | | 274 | | // Unwrap Nullable |
| | 5 | 275 | | if (Nullable.GetUnderlyingType(propertyType) is Type underlying) |
| | | 276 | | { |
| | 0 | 277 | | propertyType = underlying; |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | // Unwrap arrays |
| | 5 | 281 | | if (propertyType.IsArray) |
| | | 282 | | { |
| | 1 | 283 | | propertyType = propertyType.GetElementType()!; |
| | | 284 | | } |
| | | 285 | | |
| | 5 | 286 | | return componentSet.Contains(propertyType) ? propertyType : null; |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | /// <summary> |
| | | 290 | | /// Writes the OpenAPI class definitions to a temporary PowerShell script file. |
| | | 291 | | /// </summary> |
| | | 292 | | /// <param name="openApiClasses">The OpenAPI class definitions as a string.</param> |
| | | 293 | | /// <returns>The path to the temporary PowerShell script file.</returns> |
| | | 294 | | public static string WriteOpenApiTempScript(string openApiClasses) |
| | | 295 | | { |
| | | 296 | | // Use a stable file name so multiple runspaces share the same script |
| | 1 | 297 | | var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".ps1"); |
| | | 298 | | |
| | | 299 | | // Ensure directory exists |
| | 1 | 300 | | _ = Directory.CreateDirectory(Path.GetDirectoryName(tempPath)!); |
| | | 301 | | |
| | | 302 | | // Build content with header |
| | 1 | 303 | | var sb = new StringBuilder() |
| | 1 | 304 | | .AppendLine("# ================================================") |
| | 1 | 305 | | .AppendLine("# Kestrun OpenAPI Autogenerated Class Definitions") |
| | 1 | 306 | | .AppendLine("# DO NOT EDIT - generated at runtime") |
| | 1 | 307 | | .Append("# Timestamp: ").Append(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")).Append('Z').AppendLine() |
| | 1 | 308 | | .AppendLine("# ================================================") |
| | 1 | 309 | | .AppendLine() |
| | 1 | 310 | | .AppendLine(openApiClasses); |
| | | 311 | | |
| | | 312 | | // Save using UTF-8 without BOM |
| | 1 | 313 | | File.WriteAllText(tempPath, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); |
| | | 314 | | |
| | 1 | 315 | | return tempPath; |
| | | 316 | | } |
| | | 317 | | } |