| | | 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> |
| | 18 | 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 | | /// <param name="userCallbacks">Optional user-defined functions to include in the export.</param> |
| | | 21 | | /// <returns>The path to the temporary PowerShell script containing the class definitions.</returns> |
| | | 22 | | public static string ExportOpenApiClasses(Dictionary<string, string>? userCallbacks) |
| | | 23 | | { |
| | 59 | 24 | | var assemblies = AppDomain.CurrentDomain.GetAssemblies() |
| | 18369 | 25 | | .Where(a => a.FullName is not null && |
| | 18369 | 26 | | a.FullName.Contains("PowerShell Class Assembly")) |
| | 59 | 27 | | .ToArray(); |
| | 59 | 28 | | return ExportOpenApiClasses(assemblies: assemblies, userCallbacks: userCallbacks); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Exports OpenAPI component classes found in the specified assemblies |
| | | 33 | | /// as PowerShell class definitions |
| | | 34 | | /// </summary> |
| | | 35 | | /// <param name="assemblies">The assemblies to scan for OpenAPI component classes.</param> |
| | | 36 | | /// <param name="userCallbacks"> Optional user-defined functions to include in the export.</param> |
| | | 37 | | /// <returns>The path to the temporary PowerShell script containing the class definitions.</returns> |
| | | 38 | | public static string ExportOpenApiClasses(Assembly[] assemblies, Dictionary<string, string>? userCallbacks) |
| | | 39 | | { |
| | | 40 | | // 1. Collect all component classes |
| | 63 | 41 | | var componentTypes = assemblies |
| | 2 | 42 | | .SelectMany(a => a.GetTypes()) |
| | 1008 | 43 | | .Where(t => t.IsClass && !t.IsAbstract) |
| | 63 | 44 | | .Where(HasOpenApiComponentAttribute) |
| | 63 | 45 | | .ToList(); |
| | | 46 | | |
| | | 47 | | // Collect any enums required by the component graph. |
| | | 48 | | // If a class property uses an enum type constraint, that enum must exist in the session |
| | | 49 | | // before the class definition is parsed. |
| | 63 | 50 | | var enumTypes = CollectExportableEnums(componentTypes) |
| | 1 | 51 | | .OrderBy(t => t.Name, StringComparer.Ordinal) |
| | 63 | 52 | | .ToList(); |
| | | 53 | | |
| | | 54 | | // For quick lookup when choosing type names |
| | 63 | 55 | | var componentSet = new HashSet<Type>(componentTypes); |
| | | 56 | | |
| | | 57 | | // 2. Topologically sort by "uses other component as property type" |
| | 63 | 58 | | var sorted = TopologicalSortByPropertyDependencies(componentTypes, componentSet); |
| | 63 | 59 | | var hasCallbacks = userCallbacks is not null && userCallbacks.Count > 0; |
| | | 60 | | |
| | | 61 | | // nothing to export |
| | 63 | 62 | | if (sorted.Count == 0 && !hasCallbacks) |
| | | 63 | | { |
| | 59 | 64 | | return string.Empty; |
| | | 65 | | } |
| | | 66 | | |
| | | 67 | | // 3. Emit PowerShell classes (and optional callback functions) |
| | 4 | 68 | | var sb = new StringBuilder(); |
| | | 69 | | |
| | 4 | 70 | | if (enumTypes.Count > 0) |
| | | 71 | | { |
| | 1 | 72 | | _ = sb.AppendLine("# ================================================"); |
| | 1 | 73 | | _ = sb.AppendLine("# Kestrun OpenAPI Autogenerated Enum Definitions"); |
| | 1 | 74 | | _ = sb.AppendLine("# ================================================"); |
| | 1 | 75 | | _ = sb.AppendLine(); |
| | | 76 | | |
| | 4 | 77 | | foreach (var enumType in enumTypes) |
| | | 78 | | { |
| | 1 | 79 | | AppendEnum(enumType, sb); |
| | 1 | 80 | | _ = sb.AppendLine(); // blank line between enums |
| | | 81 | | } |
| | | 82 | | } |
| | | 83 | | |
| | 24 | 84 | | foreach (var type in sorted) |
| | | 85 | | { |
| | | 86 | | // Skip types without full name (should not happen) |
| | 8 | 87 | | if (type.FullName is null) |
| | | 88 | | { |
| | | 89 | | continue; |
| | | 90 | | } |
| | 8 | 91 | | if (ValidClassNames.Contains(type.FullName)) |
| | | 92 | | { |
| | | 93 | | // Already registered remove old entry |
| | 0 | 94 | | _ = ValidClassNames.Remove(type.FullName); |
| | | 95 | | } |
| | | 96 | | // Register valid class name |
| | 8 | 97 | | ValidClassNames.Add(type.FullName); |
| | | 98 | | // Emit class definition |
| | 8 | 99 | | AppendClass(type, componentSet, sb); |
| | 8 | 100 | | _ = sb.AppendLine(); // blank line between classes |
| | | 101 | | } |
| | | 102 | | |
| | 4 | 103 | | if (hasCallbacks) |
| | | 104 | | { |
| | 2 | 105 | | AppendCallback(sb, userCallbacks); |
| | | 106 | | } |
| | | 107 | | // 4. Write to temp script file |
| | 4 | 108 | | return WriteOpenApiTempScript(sb.ToString()); |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <summary> |
| | | 112 | | /// Appends user-defined callback functions to the PowerShell script. |
| | | 113 | | /// </summary> |
| | | 114 | | /// <param name="sb"> The StringBuilder to append the callback functions to. </param> |
| | | 115 | | /// <param name="userCallbacks"> The dictionary of user-defined callback functions, where the key is the function na |
| | | 116 | | private static void AppendCallback(StringBuilder sb, Dictionary<string, string>? userCallbacks) |
| | | 117 | | { |
| | 2 | 118 | | _ = sb.AppendLine("# ================================================"); |
| | 2 | 119 | | _ = sb.AppendLine("# Kestrun User Callback Functions"); |
| | 2 | 120 | | _ = sb.AppendLine("# ================================================"); |
| | 2 | 121 | | _ = sb.AppendLine(); |
| | | 122 | | |
| | 13 | 123 | | foreach (var kvp in userCallbacks!.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase)) |
| | | 124 | | { |
| | 3 | 125 | | var name = kvp.Key; |
| | 3 | 126 | | var definition = kvp.Value ?? string.Empty; |
| | | 127 | | |
| | | 128 | | // Emit a standardized callback function wrapper: |
| | | 129 | | // - keeps parameter type constraints |
| | | 130 | | // - strips OpenAPI/Parameter attributes |
| | | 131 | | // - builds $params and calls $Context.Response.AddCallbackParameters(...) |
| | 3 | 132 | | var functionScript = BuildCallbackFunctionStub(name, definition); |
| | 3 | 133 | | var normalized = NormalizeBlankLines(functionScript); |
| | 3 | 134 | | _ = sb.AppendLine(normalized); |
| | 3 | 135 | | _ = sb.AppendLine(); |
| | | 136 | | } |
| | 2 | 137 | | } |
| | | 138 | | |
| | | 139 | | /// <summary> |
| | | 140 | | /// Normalizes blank lines in the provided PowerShell script. |
| | | 141 | | /// </summary> |
| | | 142 | | /// <param name="script">The PowerShell script as a string.</param> |
| | | 143 | | /// <returns>A string with normalized blank lines.</returns> |
| | | 144 | | private static string NormalizeBlankLines(string script) |
| | | 145 | | { |
| | 6 | 146 | | if (string.IsNullOrWhiteSpace(script)) |
| | | 147 | | { |
| | 1 | 148 | | return string.Empty; |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | // Normalize newlines first |
| | 5 | 152 | | script = script.Replace("\r\n", "\n").Replace("\r", "\n"); |
| | | 153 | | |
| | 5 | 154 | | var lines = script.Split('\n'); |
| | 5 | 155 | | var sb = new StringBuilder(script.Length); |
| | | 156 | | |
| | 174 | 157 | | for (var idx = 0; idx < lines.Length; idx++) |
| | | 158 | | { |
| | 82 | 159 | | var line = lines[idx].TrimEnd(); |
| | 82 | 160 | | var isBlank = string.IsNullOrWhiteSpace(line); |
| | | 161 | | |
| | | 162 | | // For callback function export we want compact output: |
| | | 163 | | // drop ALL whitespace-only lines (attribute stripping leaves many single blank lines). |
| | 82 | 164 | | if (!isBlank) |
| | | 165 | | { |
| | 72 | 166 | | _ = sb.AppendLine(line); |
| | | 167 | | } |
| | | 168 | | } |
| | | 169 | | |
| | | 170 | | // Trim trailing newlines |
| | 5 | 171 | | return sb.ToString().TrimEnd(); |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | /// <summary> |
| | | 175 | | /// Builds a PowerShell function stub for a user-defined callback function. |
| | | 176 | | /// </summary> |
| | | 177 | | /// <param name="functionName"> The name of the callback function. </param> |
| | | 178 | | /// <param name="definition"> The PowerShell function definition as a string. </param> |
| | | 179 | | /// <returns>A string containing the standardized PowerShell function stub.</returns> |
| | | 180 | | private static string BuildCallbackFunctionStub(string functionName, string definition) |
| | | 181 | | { |
| | 3 | 182 | | var (paramBlock, paramNames, bodyParamName) = TryExtractParamInfo(definition); |
| | | 183 | | |
| | | 184 | | // Fall back to a no-param function if we can't parse anything. |
| | 3 | 185 | | var strippedParamBlock = StripPowerShellAttributeBlocks(paramBlock); |
| | 3 | 186 | | strippedParamBlock = NormalizeBlankLines(strippedParamBlock); |
| | | 187 | | |
| | | 188 | | // Ensure we always have a param(...) block for consistent output. |
| | 3 | 189 | | if (string.IsNullOrWhiteSpace(strippedParamBlock)) |
| | | 190 | | { |
| | 1 | 191 | | strippedParamBlock = "param()"; |
| | 1 | 192 | | paramNames = []; |
| | | 193 | | } |
| | | 194 | | |
| | 3 | 195 | | var sb = new StringBuilder(); |
| | 3 | 196 | | _ = sb.AppendLine($"function {functionName} {{"); |
| | | 197 | | |
| | | 198 | | // Normalize indentation: |
| | | 199 | | // - "param(" line: 4 spaces |
| | | 200 | | // - parameter lines: 8 spaces |
| | | 201 | | // - closing ")": 4 spaces |
| | 22 | 202 | | foreach (var rawLine in strippedParamBlock.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n')) |
| | | 203 | | { |
| | 8 | 204 | | var l = rawLine.Trim(); |
| | 8 | 205 | | if (l.Length == 0) |
| | | 206 | | { |
| | | 207 | | continue; |
| | | 208 | | } |
| | | 209 | | |
| | 8 | 210 | | if (l.Equals(")", StringComparison.Ordinal)) |
| | | 211 | | { |
| | 2 | 212 | | _ = sb.Append(" ").AppendLine(l); |
| | 2 | 213 | | continue; |
| | | 214 | | } |
| | | 215 | | |
| | 6 | 216 | | if (l.StartsWith("param", StringComparison.OrdinalIgnoreCase)) |
| | | 217 | | { |
| | 3 | 218 | | _ = sb.Append(" ").AppendLine(l); |
| | 3 | 219 | | continue; |
| | | 220 | | } |
| | | 221 | | |
| | 3 | 222 | | _ = sb.Append(" ").AppendLine(l); |
| | | 223 | | } |
| | | 224 | | |
| | 3 | 225 | | _ = sb.AppendLine(" $FunctionName = $MyInvocation.MyCommand.Name"); |
| | 3 | 226 | | _ = sb.AppendLine(" if ($null -eq $Context -or $null -eq $Context.Response) {"); |
| | 3 | 227 | | _ = sb.AppendLine(" if (Test-KrLogger) {"); |
| | 3 | 228 | | _ = sb.AppendLine(" Write-KrLog -Level Warning -Message '{function} must be called inside a route scr |
| | 3 | 229 | | _ = sb.AppendLine(" } else {"); |
| | 3 | 230 | | _ = sb.AppendLine(" Write-Warning -Message \"$FunctionName must be called inside a route script with |
| | 3 | 231 | | _ = sb.AppendLine(" }"); |
| | 3 | 232 | | _ = sb.AppendLine(" return"); |
| | 3 | 233 | | _ = sb.AppendLine(" }"); |
| | 3 | 234 | | _ = sb.AppendLine(" Write-KrLog -Level Information -Message 'Defined callback function {CallbackFunction}' -V |
| | 3 | 235 | | _ = sb.AppendLine(" $params = [System.Collections.Generic.Dictionary[string, object]]::new()"); |
| | | 236 | | |
| | 12 | 237 | | foreach (var p in paramNames) |
| | | 238 | | { |
| | | 239 | | // Use the exact casing captured from the param block; dictionary keys are case-insensitive in C#. |
| | 3 | 240 | | _ = sb.AppendLine($" $params['{p}'] = ${p}"); |
| | | 241 | | } |
| | | 242 | | |
| | 3 | 243 | | _ = sb.AppendLine(bodyParamName is { Length: > 0 } |
| | 3 | 244 | | ? $" $bodyParameterName = '{bodyParamName}'" |
| | 3 | 245 | | : " $bodyParameterName = $null"); |
| | | 246 | | |
| | 3 | 247 | | _ = sb.AppendLine(); |
| | 3 | 248 | | _ = sb.AppendLine(" $Context.Response.AddCallbackParameters("); |
| | 3 | 249 | | _ = sb.AppendLine(" $MyInvocation.MyCommand.Name,"); |
| | 3 | 250 | | _ = sb.AppendLine(" $bodyParameterName,"); |
| | 3 | 251 | | _ = sb.AppendLine(" $params)"); |
| | 3 | 252 | | _ = sb.AppendLine("}"); |
| | | 253 | | |
| | 3 | 254 | | return sb.ToString(); |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | private static (string ParamBlock, List<string> ParamNames, string? BodyParamName) TryExtractParamInfo(string defini |
| | | 258 | | { |
| | 3 | 259 | | if (string.IsNullOrWhiteSpace(definition)) |
| | | 260 | | { |
| | 0 | 261 | | return (string.Empty, [], null); |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | // Try to isolate the param(...) block from a FunctionInfo.Definition string. |
| | 3 | 265 | | var paramBlock = ExtractPowerShellParamBlock(definition); |
| | 3 | 266 | | if (string.IsNullOrWhiteSpace(paramBlock)) |
| | | 267 | | { |
| | 1 | 268 | | return (string.Empty, [], null); |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | // Identify the request body parameter name (prefer OpenApiRequestBody attribute if present) |
| | | 272 | | // Example: [OpenApiRequestBody(...)] [PaymentStatusChangedEvent]$Body |
| | 2 | 273 | | var bodyParamName = ExtractBodyParameterName(paramBlock); |
| | | 274 | | |
| | | 275 | | // Strip attribute blocks so we keep only type constraints + $paramName |
| | 2 | 276 | | var stripped = StripPowerShellAttributeBlocks(paramBlock); |
| | 2 | 277 | | var paramNames = ExtractParamNamesFromStrippedParamBlock(stripped); |
| | | 278 | | |
| | | 279 | | // If we didn't find OpenApiRequestBody, default to Body if present. |
| | 3 | 280 | | if (string.IsNullOrWhiteSpace(bodyParamName) && paramNames.Any(p => string.Equals(p, "Body", StringComparison.Or |
| | | 281 | | { |
| | 0 | 282 | | bodyParamName = paramNames.First(p => string.Equals(p, "Body", StringComparison.OrdinalIgnoreCase)); |
| | | 283 | | } |
| | | 284 | | |
| | 2 | 285 | | return (paramBlock, paramNames, bodyParamName); |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | /// <summary> |
| | | 289 | | /// States for scanning PowerShell script for quoted segments. |
| | | 290 | | /// </summary> |
| | | 291 | | private enum ScanState |
| | | 292 | | { |
| | | 293 | | /// <summary> |
| | | 294 | | /// Normal scanning state (not inside quotes). |
| | | 295 | | /// </summary> |
| | | 296 | | Normal, |
| | | 297 | | /// <summary> |
| | | 298 | | /// Inside single-quoted string segment. |
| | | 299 | | /// </summary> |
| | | 300 | | SingleQuoted, |
| | | 301 | | /// <summary> |
| | | 302 | | /// Inside double-quoted string segment. |
| | | 303 | | /// </summary> |
| | | 304 | | DoubleQuoted |
| | | 305 | | } |
| | | 306 | | |
| | | 307 | | /// <summary> |
| | | 308 | | /// Extracts the parameter block from a PowerShell function definition. |
| | | 309 | | /// </summary> |
| | | 310 | | /// <param name="definition"> The PowerShell function definition string. </param> |
| | | 311 | | /// <returns>The parameter block string including the 'param(...)' syntax; or an empty string if not found.</returns |
| | | 312 | | private static string ExtractPowerShellParamBlock(string definition) |
| | | 313 | | { |
| | 3 | 314 | | if (string.IsNullOrEmpty(definition)) |
| | | 315 | | { |
| | 0 | 316 | | return string.Empty; |
| | | 317 | | } |
| | | 318 | | |
| | 3 | 319 | | var idx = definition.IndexOf("param", StringComparison.OrdinalIgnoreCase); |
| | 3 | 320 | | if (idx < 0) |
| | | 321 | | { |
| | 0 | 322 | | return string.Empty; |
| | | 323 | | } |
| | | 324 | | |
| | 3 | 325 | | var open = definition.IndexOf('(', idx); |
| | 3 | 326 | | if (open < 0) |
| | | 327 | | { |
| | 1 | 328 | | return string.Empty; |
| | | 329 | | } |
| | | 330 | | |
| | 2 | 331 | | var depth = 0; |
| | 2 | 332 | | var state = ScanState.Normal; |
| | | 333 | | |
| | 534 | 334 | | for (var i = open; i < definition.Length; i++) |
| | | 335 | | { |
| | 267 | 336 | | if (TryConsumeQuoted(definition, ref i, ref state)) |
| | | 337 | | { |
| | | 338 | | continue; |
| | | 339 | | } |
| | | 340 | | |
| | 243 | 341 | | var ch = definition[i]; |
| | | 342 | | |
| | 243 | 343 | | if (ch == '(') |
| | | 344 | | { |
| | 5 | 345 | | depth++; |
| | 5 | 346 | | continue; |
| | | 347 | | } |
| | | 348 | | |
| | 238 | 349 | | if (ch == ')') |
| | | 350 | | { |
| | 5 | 351 | | depth--; |
| | 5 | 352 | | if (depth == 0) |
| | | 353 | | { |
| | 2 | 354 | | return definition.Substring(idx, i - idx + 1); |
| | | 355 | | } |
| | | 356 | | } |
| | | 357 | | } |
| | | 358 | | |
| | 0 | 359 | | return string.Empty; |
| | | 360 | | } |
| | | 361 | | |
| | | 362 | | /// <summary> |
| | | 363 | | /// Tries to consume a quoted segment in the PowerShell script. |
| | | 364 | | /// </summary> |
| | | 365 | | /// <param name="s"> The input string to scan. </param> |
| | | 366 | | /// <param name="i"> The current index in the string, passed by reference and updated as the quoted segment is consu |
| | | 367 | | /// <param name="state"> The current scanning state, passed by reference and updated based on quote handling. </para |
| | | 368 | | /// <returns>True if a quoted segment was consumed; otherwise, false.</returns> |
| | | 369 | | private static bool TryConsumeQuoted(string s, ref int i, ref ScanState state) |
| | | 370 | | { |
| | 267 | 371 | | var ch = s[i]; |
| | | 372 | | |
| | | 373 | | // Enter quote states |
| | 267 | 374 | | if (state == ScanState.Normal) |
| | | 375 | | { |
| | 249 | 376 | | if (ch == '\'') { state = ScanState.SingleQuoted; return true; } |
| | 243 | 377 | | if (ch == '"') { state = ScanState.DoubleQuoted; return true; } |
| | 243 | 378 | | return false; |
| | | 379 | | } |
| | | 380 | | |
| | | 381 | | // Inside single quotes: '' is an escaped single quote |
| | 22 | 382 | | if (state == ScanState.SingleQuoted) |
| | | 383 | | { |
| | 22 | 384 | | if (ch == '\'' && i + 1 < s.Length && s[i + 1] == '\'') |
| | | 385 | | { |
| | 0 | 386 | | i++; // consume second ' |
| | 0 | 387 | | return true; |
| | | 388 | | } |
| | | 389 | | |
| | 22 | 390 | | if (ch == '\'') |
| | | 391 | | { |
| | 2 | 392 | | state = ScanState.Normal; |
| | | 393 | | } |
| | | 394 | | |
| | 22 | 395 | | return true; |
| | | 396 | | } |
| | | 397 | | |
| | | 398 | | // Inside double quotes: backtick escapes the next char |
| | 0 | 399 | | if (state == ScanState.DoubleQuoted) |
| | | 400 | | { |
| | 0 | 401 | | if (ch == '`' && i + 1 < s.Length) |
| | | 402 | | { |
| | 0 | 403 | | i++; // skip escaped char |
| | 0 | 404 | | return true; |
| | | 405 | | } |
| | | 406 | | |
| | 0 | 407 | | if (ch == '"') |
| | | 408 | | { |
| | 0 | 409 | | state = ScanState.Normal; |
| | | 410 | | } |
| | | 411 | | |
| | 0 | 412 | | return true; |
| | | 413 | | } |
| | | 414 | | |
| | 0 | 415 | | return false; |
| | | 416 | | } |
| | | 417 | | |
| | | 418 | | /// <summary> |
| | | 419 | | /// Extracts the name of the body parameter from the parameter block, if annotated with [OpenApiRequestBody]. |
| | | 420 | | /// </summary> |
| | | 421 | | /// <param name="paramBlock"> The parameter block string to search within. </param> |
| | | 422 | | /// <returns>The name of the body parameter if found; otherwise, null.</returns> |
| | | 423 | | private static string? ExtractBodyParameterName(string paramBlock) |
| | | 424 | | { |
| | | 425 | | // Very targeted heuristic: if [OpenApiRequestBody(...)] is present, pick the following $name. |
| | | 426 | | // This keeps the exporter decoupled from PowerShell AST dependencies. |
| | 2 | 427 | | var marker = "OpenApiRequestBody"; |
| | 2 | 428 | | var idx = paramBlock.IndexOf(marker, StringComparison.OrdinalIgnoreCase); |
| | 2 | 429 | | if (idx < 0) |
| | | 430 | | { |
| | 1 | 431 | | return null; |
| | | 432 | | } |
| | | 433 | | |
| | | 434 | | // Search forward for '$' then capture identifier |
| | 180 | 435 | | for (var i = idx; i < paramBlock.Length; i++) |
| | | 436 | | { |
| | 90 | 437 | | if (paramBlock[i] != '$') |
| | | 438 | | { |
| | | 439 | | continue; |
| | | 440 | | } |
| | | 441 | | |
| | 1 | 442 | | var start = i + 1; |
| | 1 | 443 | | var end = start; |
| | 8 | 444 | | while (end < paramBlock.Length) |
| | | 445 | | { |
| | 8 | 446 | | var ch = paramBlock[end]; |
| | 8 | 447 | | if (!(char.IsLetterOrDigit(ch) || ch == '_')) |
| | | 448 | | { |
| | | 449 | | break; |
| | | 450 | | } |
| | 7 | 451 | | end++; |
| | | 452 | | } |
| | | 453 | | |
| | 1 | 454 | | if (end > start) |
| | | 455 | | { |
| | 1 | 456 | | return paramBlock[start..end]; |
| | | 457 | | } |
| | | 458 | | } |
| | | 459 | | |
| | 0 | 460 | | return null; |
| | | 461 | | } |
| | | 462 | | |
| | | 463 | | private static List<string> ExtractParamNamesFromStrippedParamBlock(string strippedParamBlock) |
| | | 464 | | { |
| | | 465 | | // Parse variable names only from within param(...) |
| | | 466 | | // We expect declarations like: [string]$paymentId, |
| | 2 | 467 | | if (string.IsNullOrWhiteSpace(strippedParamBlock)) |
| | | 468 | | { |
| | 0 | 469 | | return []; |
| | | 470 | | } |
| | | 471 | | |
| | 2 | 472 | | var names = new List<string>(); |
| | 2 | 473 | | var s = strippedParamBlock; |
| | | 474 | | |
| | 250 | 475 | | for (var i = 0; i < s.Length; i++) |
| | | 476 | | { |
| | 123 | 477 | | if (s[i] != '$') |
| | | 478 | | { |
| | | 479 | | continue; |
| | | 480 | | } |
| | | 481 | | |
| | 3 | 482 | | var start = i + 1; |
| | 3 | 483 | | var end = start; |
| | 3 | 484 | | if (start >= s.Length) |
| | | 485 | | { |
| | | 486 | | continue; |
| | | 487 | | } |
| | | 488 | | |
| | 3 | 489 | | if (!(char.IsLetter(s[start]) || s[start] == '_')) |
| | | 490 | | { |
| | | 491 | | continue; |
| | | 492 | | } |
| | | 493 | | |
| | 3 | 494 | | end++; |
| | 21 | 495 | | while (end < s.Length) |
| | | 496 | | { |
| | 21 | 497 | | var ch = s[end]; |
| | 21 | 498 | | if (!(char.IsLetterOrDigit(ch) || ch == '_')) |
| | | 499 | | { |
| | | 500 | | break; |
| | | 501 | | } |
| | 18 | 502 | | end++; |
| | | 503 | | } |
| | | 504 | | |
| | 3 | 505 | | var name = s[start..end]; |
| | 3 | 506 | | if (!names.Contains(name, StringComparer.OrdinalIgnoreCase)) |
| | | 507 | | { |
| | 3 | 508 | | names.Add(name); |
| | | 509 | | } |
| | | 510 | | |
| | 3 | 511 | | i = end - 1; |
| | | 512 | | } |
| | | 513 | | |
| | 2 | 514 | | return names; |
| | | 515 | | } |
| | | 516 | | |
| | | 517 | | private static string StripPowerShellAttributeBlocks(string script) |
| | | 518 | | { |
| | 5 | 519 | | if (string.IsNullOrWhiteSpace(script)) |
| | | 520 | | { |
| | 1 | 521 | | return string.Empty; |
| | | 522 | | } |
| | | 523 | | |
| | 4 | 524 | | var sb = new StringBuilder(script.Length); |
| | 4 | 525 | | var i = 0; |
| | 224 | 526 | | while (i < script.Length) |
| | | 527 | | { |
| | 220 | 528 | | var ch = script[i]; |
| | 220 | 529 | | if (ch != '[') |
| | | 530 | | { |
| | 208 | 531 | | _ = sb.Append(ch); |
| | 208 | 532 | | i++; |
| | 208 | 533 | | continue; |
| | | 534 | | } |
| | | 535 | | |
| | | 536 | | // Capture a full bracket block, handling nested [ ... ] (e.g. generic type constraints) |
| | 12 | 537 | | var start = i; |
| | 12 | 538 | | var depth = 0; |
| | 12 | 539 | | var j = i; |
| | 346 | 540 | | while (j < script.Length) |
| | | 541 | | { |
| | 346 | 542 | | var cj = script[j]; |
| | 346 | 543 | | if (cj == '[') |
| | | 544 | | { |
| | 12 | 545 | | depth++; |
| | | 546 | | } |
| | 334 | 547 | | else if (cj == ']') |
| | | 548 | | { |
| | 12 | 549 | | depth--; |
| | 12 | 550 | | if (depth == 0) |
| | | 551 | | { |
| | 12 | 552 | | j++; // include closing ']' |
| | 12 | 553 | | break; |
| | | 554 | | } |
| | | 555 | | } |
| | 334 | 556 | | j++; |
| | | 557 | | } |
| | | 558 | | |
| | | 559 | | // If unbalanced, just emit the rest |
| | 12 | 560 | | if (depth != 0) |
| | | 561 | | { |
| | 0 | 562 | | _ = sb.Append(script.AsSpan(i)); |
| | 0 | 563 | | break; |
| | | 564 | | } |
| | | 565 | | |
| | 12 | 566 | | var block = script.AsSpan(start, j - start); |
| | | 567 | | |
| | | 568 | | // Attribute blocks always include parentheses in our usage (e.g. [OpenApiPath(...)], [Parameter()]). |
| | | 569 | | // Keep type constraints like [string], [int], [MyType], [MyType[]], [List[string]]. |
| | 12 | 570 | | if (block.IndexOf('(') >= 0) |
| | | 571 | | { |
| | 6 | 572 | | i = j; |
| | 6 | 573 | | continue; |
| | | 574 | | } |
| | | 575 | | |
| | 6 | 576 | | _ = sb.Append(block); |
| | 6 | 577 | | i = j; |
| | | 578 | | } |
| | | 579 | | |
| | 4 | 580 | | return sb.ToString(); |
| | | 581 | | } |
| | | 582 | | |
| | | 583 | | /// <summary> |
| | | 584 | | /// Determines if the specified type has an OpenAPI component attribute. |
| | | 585 | | /// </summary> |
| | | 586 | | /// <param name="t"></param> |
| | | 587 | | /// <returns></returns> |
| | | 588 | | private static bool HasOpenApiComponentAttribute(Type t) |
| | | 589 | | { |
| | 631 | 590 | | return t.GetCustomAttributes(inherit: true) |
| | 733 | 591 | | .Select(a => a.GetType().Name) |
| | 631 | 592 | | .Any(n => |
| | 1364 | 593 | | n.Contains("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase)); |
| | | 594 | | } |
| | | 595 | | |
| | | 596 | | /// <summary> |
| | | 597 | | /// Appends the PowerShell class definition for the specified type to the StringBuilder. |
| | | 598 | | /// </summary> |
| | | 599 | | /// <param name="type"></param> |
| | | 600 | | /// <param name="componentSet"></param> |
| | | 601 | | /// <param name="sb"></param> |
| | | 602 | | private static void AppendClass(Type type, HashSet<Type> componentSet, StringBuilder sb) |
| | | 603 | | { |
| | | 604 | | // Detect base type (for parenting) |
| | 8 | 605 | | var baseType = type.BaseType; |
| | 8 | 606 | | var baseClause = string.Empty; |
| | | 607 | | |
| | 8 | 608 | | if (baseType != null && baseType != typeof(object)) |
| | | 609 | | { |
| | | 610 | | // Use PS-friendly type name for the base |
| | 4 | 611 | | var basePsName = ToPowerShellTypeName(baseType, componentSet, collapseToUnderlyingPrimitives: false); |
| | 4 | 612 | | baseClause = $" : {basePsName}"; |
| | | 613 | | } |
| | 8 | 614 | | _ = sb.AppendLine("[NoRunspaceAffinity()]"); |
| | 8 | 615 | | _ = sb.AppendLine($"class {type.Name}{baseClause} {{"); |
| | | 616 | | |
| | | 617 | | // Only properties *declared* on this type (no inherited ones) |
| | 8 | 618 | | var props = type.GetProperties( |
| | 8 | 619 | | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); |
| | | 620 | | |
| | 82 | 621 | | foreach (var p in props) |
| | | 622 | | { |
| | 33 | 623 | | var psType = ToPowerShellTypeName(p.PropertyType, componentSet, collapseToUnderlyingPrimitives: true); |
| | 33 | 624 | | _ = sb.AppendLine($" [{psType}]${p.Name}"); |
| | | 625 | | } |
| | | 626 | | |
| | | 627 | | // Add static XML metadata to guide XmlHelper without requiring PowerShell method invocation |
| | 8 | 628 | | AppendOpenApiXmlMetadataProperty(type, props, sb); |
| | | 629 | | |
| | 8 | 630 | | _ = sb.AppendLine("}"); |
| | 8 | 631 | | } |
| | | 632 | | |
| | | 633 | | /// <summary> |
| | | 634 | | /// Appends a static hashtable property containing OpenApiXml metadata for the class and its properties. |
| | | 635 | | /// </summary> |
| | | 636 | | /// <remarks> |
| | | 637 | | /// This is emitted as a static property (not a PowerShell class method) so that C# reflection can read the |
| | | 638 | | /// metadata without requiring a PowerShell execution context bound to the current thread. |
| | | 639 | | /// </remarks> |
| | | 640 | | /// <param name="type">The type to extract OpenApiXml metadata from.</param> |
| | | 641 | | /// <param name="props">The properties of the type.</param> |
| | | 642 | | /// <param name="sb">The StringBuilder to append to.</param> |
| | | 643 | | private static void AppendOpenApiXmlMetadataProperty(Type type, PropertyInfo[] props, StringBuilder sb) |
| | | 644 | | { |
| | 8 | 645 | | _ = sb.AppendLine(); |
| | 8 | 646 | | _ = sb.AppendLine(" # Static OpenApiXml metadata for this class"); |
| | 8 | 647 | | _ = sb.AppendLine(" static [hashtable] $XmlMetadata = @{"); |
| | 8 | 648 | | _ = sb.AppendLine(" ClassName = '" + type.Name + "'"); |
| | | 649 | | |
| | | 650 | | // Get class-level OpenApiXml attribute |
| | 8 | 651 | | var classXmlAttr = type.GetCustomAttributes(inherit: false) |
| | 18 | 652 | | .FirstOrDefault(a => a.GetType().Name == "OpenApiXmlAttribute"); |
| | | 653 | | |
| | 8 | 654 | | if (classXmlAttr != null) |
| | | 655 | | { |
| | 0 | 656 | | var classXml = BuildXmlMetadataHashtable(classXmlAttr, indent: 12); |
| | 0 | 657 | | if (!string.IsNullOrWhiteSpace(classXml)) |
| | | 658 | | { |
| | 0 | 659 | | _ = sb.AppendLine(" ClassXml = @{"); |
| | 0 | 660 | | _ = sb.AppendLine(classXml); |
| | 0 | 661 | | _ = sb.AppendLine(" }"); |
| | | 662 | | } |
| | | 663 | | } |
| | | 664 | | |
| | | 665 | | // Get property-level OpenApiXml attributes |
| | 8 | 666 | | if (props.Length > 0) |
| | | 667 | | { |
| | 5 | 668 | | _ = sb.AppendLine(" Properties = @{"); |
| | 5 | 669 | | var hasAnyPropertyXml = false; |
| | | 670 | | |
| | 76 | 671 | | foreach (var prop in props) |
| | | 672 | | { |
| | 33 | 673 | | var propXmlAttr = prop.GetCustomAttributes(inherit: false) |
| | 37 | 674 | | .FirstOrDefault(a => a.GetType().Name == "OpenApiXmlAttribute"); |
| | | 675 | | |
| | 33 | 676 | | if (propXmlAttr != null) |
| | | 677 | | { |
| | 0 | 678 | | var propXml = BuildXmlMetadataHashtable(propXmlAttr, indent: 16); |
| | 0 | 679 | | if (!string.IsNullOrWhiteSpace(propXml)) |
| | | 680 | | { |
| | 0 | 681 | | hasAnyPropertyXml = true; |
| | 0 | 682 | | _ = sb.AppendLine($" '{prop.Name}' = @{{"); |
| | 0 | 683 | | _ = sb.AppendLine(propXml); |
| | 0 | 684 | | _ = sb.AppendLine(" }"); |
| | | 685 | | } |
| | | 686 | | } |
| | | 687 | | } |
| | | 688 | | |
| | 5 | 689 | | if (!hasAnyPropertyXml) |
| | | 690 | | { |
| | 5 | 691 | | _ = sb.AppendLine(" # No property-level XML metadata"); |
| | | 692 | | } |
| | | 693 | | |
| | 5 | 694 | | _ = sb.AppendLine(" }"); |
| | | 695 | | } |
| | | 696 | | |
| | 8 | 697 | | _ = sb.AppendLine(" }"); |
| | 8 | 698 | | } |
| | | 699 | | |
| | | 700 | | /// <summary> |
| | | 701 | | /// Builds a PowerShell hashtable representation of OpenApiXml attribute properties. |
| | | 702 | | /// </summary> |
| | | 703 | | /// <param name="xmlAttr">The OpenApiXml attribute instance.</param> |
| | | 704 | | /// <param name="indent">Number of spaces to indent.</param> |
| | | 705 | | /// <returns>PowerShell hashtable string representation.</returns> |
| | | 706 | | private static string BuildXmlMetadataHashtable(object xmlAttr, int indent) |
| | | 707 | | { |
| | 0 | 708 | | var attrType = xmlAttr.GetType(); |
| | 0 | 709 | | var sb = new StringBuilder(); |
| | 0 | 710 | | var indentStr = new string(' ', indent); |
| | | 711 | | |
| | | 712 | | // Extract properties using reflection |
| | 0 | 713 | | var nameProp = attrType.GetProperty("Name"); |
| | 0 | 714 | | var namespaceProp = attrType.GetProperty("Namespace"); |
| | 0 | 715 | | var prefixProp = attrType.GetProperty("Prefix"); |
| | 0 | 716 | | var attributeProp = attrType.GetProperty("Attribute"); |
| | 0 | 717 | | var wrappedProp = attrType.GetProperty("Wrapped"); |
| | | 718 | | |
| | 0 | 719 | | var name = nameProp?.GetValue(xmlAttr) as string; |
| | 0 | 720 | | var ns = namespaceProp?.GetValue(xmlAttr) as string; |
| | 0 | 721 | | var prefix = prefixProp?.GetValue(xmlAttr) as string; |
| | 0 | 722 | | var isAttribute = attributeProp?.GetValue(xmlAttr) is bool b && b; |
| | 0 | 723 | | var isWrapped = wrappedProp?.GetValue(xmlAttr) is bool w && w; |
| | | 724 | | |
| | 0 | 725 | | if (!string.IsNullOrWhiteSpace(name)) |
| | | 726 | | { |
| | 0 | 727 | | _ = sb.AppendLine($"{indentStr}Name = '{EscapePowerShellString(name)}'"); |
| | | 728 | | } |
| | | 729 | | |
| | 0 | 730 | | if (!string.IsNullOrWhiteSpace(ns)) |
| | | 731 | | { |
| | 0 | 732 | | _ = sb.AppendLine($"{indentStr}Namespace = '{EscapePowerShellString(ns)}'"); |
| | | 733 | | } |
| | | 734 | | |
| | 0 | 735 | | if (!string.IsNullOrWhiteSpace(prefix)) |
| | | 736 | | { |
| | 0 | 737 | | _ = sb.AppendLine($"{indentStr}Prefix = '{EscapePowerShellString(prefix)}'"); |
| | | 738 | | } |
| | | 739 | | |
| | 0 | 740 | | if (isAttribute) |
| | | 741 | | { |
| | 0 | 742 | | _ = sb.AppendLine($"{indentStr}Attribute = $true"); |
| | | 743 | | } |
| | | 744 | | |
| | 0 | 745 | | if (isWrapped) |
| | | 746 | | { |
| | 0 | 747 | | _ = sb.AppendLine($"{indentStr}Wrapped = $true"); |
| | | 748 | | } |
| | | 749 | | |
| | 0 | 750 | | return sb.ToString().TrimEnd(); |
| | | 751 | | } |
| | | 752 | | |
| | | 753 | | /// <summary> |
| | | 754 | | /// Escapes single quotes in a string for PowerShell string literals. |
| | | 755 | | /// </summary> |
| | | 756 | | /// <param name="str">The string to escape.</param> |
| | | 757 | | /// <returns>Escaped string safe for PowerShell single-quoted strings.</returns> |
| | 0 | 758 | | private static string EscapePowerShellString(string str) => str.Replace("'", "''"); |
| | | 759 | | |
| | | 760 | | /// <summary> |
| | | 761 | | /// Converts a .NET type to a PowerShell type name. |
| | | 762 | | /// </summary> |
| | | 763 | | /// <param name="t"></param> |
| | | 764 | | /// <param name="componentSet"></param> |
| | | 765 | | /// <param name="collapseToUnderlyingPrimitives">When true, types derived from OpenApiValue<T> are emitted as |
| | | 766 | | /// <returns></returns> |
| | | 767 | | private static string ToPowerShellTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitives) |
| | | 768 | | { |
| | 48 | 769 | | return GetNullableTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 48 | 770 | | ?? GetOpenApiArrayWrapperTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 48 | 771 | | ?? GetCollapsedOpenApiPrimitiveTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 48 | 772 | | ?? GetEnumTypeName(t) |
| | 48 | 773 | | ?? GetPrimitiveTypeName(t) |
| | 48 | 774 | | ?? GetArrayTypeName(t, componentSet, collapseToUnderlyingPrimitives) |
| | 48 | 775 | | ?? FormatComponentOrFallbackName(t, componentSet); |
| | | 776 | | } |
| | | 777 | | |
| | | 778 | | /// <summary> |
| | | 779 | | /// Produces a PowerShell nullable type constraint (e.g. <c>Nullable[int]</c>) when the input is a <c>Nullable<T& |
| | | 780 | | /// </summary> |
| | | 781 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 782 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 783 | | /// <param name="collapseToUnderlyingPrimitives">Whether OpenAPI primitive wrapper types should be collapsed to prim |
| | | 784 | | /// <returns>The nullable type name, or <c>null</c> when <paramref name="t"/> is not nullable.</returns> |
| | | 785 | | private static string? GetNullableTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitives) |
| | | 786 | | { |
| | 48 | 787 | | return Nullable.GetUnderlyingType(t) is Type underlying |
| | 48 | 788 | | ? $"Nullable[{ToPowerShellTypeName(underlying, componentSet, collapseToUnderlyingPrimitives)}]" |
| | 48 | 789 | | : null; |
| | | 790 | | } |
| | | 791 | | |
| | | 792 | | /// <summary> |
| | | 793 | | /// Produces an element-array type constraint for OpenAPI schema component array wrapper types when appropriate. |
| | | 794 | | /// </summary> |
| | | 795 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 796 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 797 | | /// <param name="collapseToUnderlyingPrimitives">Whether OpenAPI primitive wrapper types should be collapsed to prim |
| | | 798 | | /// <returns>The array wrapper type name, or <c>null</c> when <paramref name="t"/> is not an OpenAPI array wrapper t |
| | | 799 | | private static string? GetOpenApiArrayWrapperTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingP |
| | 46 | 800 | | => ResolveElementArrayType(t, componentSet, collapseToUnderlyingPrimitives); |
| | | 801 | | |
| | | 802 | | /// <summary> |
| | | 803 | | /// Produces the underlying primitive PowerShell type name for OpenAPI primitive wrapper types (e.g. OpenApiString/O |
| | | 804 | | /// </summary> |
| | | 805 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 806 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 807 | | /// <param name="collapseToUnderlyingPrimitives">Whether collapsing is enabled.</param> |
| | | 808 | | /// <returns>The primitive name, or <c>null</c> when <paramref name="t"/> is not an OpenAPI wrapper type (or collaps |
| | | 809 | | /// <remarks> |
| | | 810 | | /// When <paramref name="collapseToUnderlyingPrimitives"/> is <c>true</c>, |
| | | 811 | | /// types derived from OpenApiValue<T> are emitted as their underlying primitive (e.g., string/double/bool/lon |
| | | 812 | | /// </remarks> |
| | | 813 | | private static string? GetCollapsedOpenApiPrimitiveTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnder |
| | 45 | 814 | | => collapseToUnderlyingPrimitives |
| | 45 | 815 | | && TryGetOpenApiValueUnderlyingType(t, out var underlying) |
| | 45 | 816 | | && underlying is not null |
| | 45 | 817 | | ? ToPowerShellTypeName(underlying, componentSet, collapseToUnderlyingPrimitives) |
| | 45 | 818 | | : null; |
| | | 819 | | |
| | | 820 | | /// <summary> |
| | | 821 | | /// Produces the simple name for enum types so PowerShell can bind against the emitted enum definition. |
| | | 822 | | /// </summary> |
| | | 823 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 824 | | /// <returns>The enum name, or <c>null</c> when <paramref name="t"/> is not an enum.</returns> |
| | | 825 | | private static string? GetEnumTypeName(Type t) |
| | 39 | 826 | | => t.IsEnum ? t.Name : null; |
| | | 827 | | |
| | | 828 | | /// <summary> |
| | | 829 | | /// Produces the PowerShell type name for well-known CLR primitives. |
| | | 830 | | /// </summary> |
| | | 831 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 832 | | /// <returns>The primitive name, or <c>null</c> when no primitive mapping exists.</returns> |
| | | 833 | | private static string? GetPrimitiveTypeName(Type t) |
| | 38 | 834 | | => ResolvePrimitiveTypeName(t); |
| | | 835 | | |
| | | 836 | | /// <summary> |
| | | 837 | | /// Produces a PowerShell element-array type constraint (e.g. <c>string[]</c>) for CLR array types. |
| | | 838 | | /// </summary> |
| | | 839 | | /// <param name="t">The CLR type to inspect.</param> |
| | | 840 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 841 | | /// <param name="collapseToUnderlyingPrimitives">Whether OpenAPI primitive wrapper types should be collapsed to prim |
| | | 842 | | /// <returns>The formatted array name, or <c>null</c> when <paramref name="t"/> is not an array.</returns> |
| | | 843 | | private static string? GetArrayTypeName(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitives) |
| | 8 | 844 | | => t.IsArray && t.GetElementType() is Type elementType |
| | 8 | 845 | | ? $"{ToPowerShellTypeName(elementType, componentSet, collapseToUnderlyingPrimitives)}[]" |
| | 8 | 846 | | : null; |
| | | 847 | | |
| | | 848 | | /// <summary> |
| | | 849 | | /// Formats a component type as its simple name or falls back to full name for other reference types. |
| | | 850 | | /// </summary> |
| | | 851 | | /// <param name="t">The CLR type to format.</param> |
| | | 852 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 853 | | /// <returns>A PowerShell-friendly type name.</returns> |
| | | 854 | | private static string FormatComponentOrFallbackName(Type t, HashSet<Type> componentSet) |
| | 6 | 855 | | => componentSet.Contains(t) || t.FullName is null |
| | 6 | 856 | | ? t.Name |
| | 6 | 857 | | : t.FullName; |
| | | 858 | | |
| | | 859 | | /// <summary> |
| | | 860 | | /// Collects enums referenced by component properties so they can be emitted before class definitions. |
| | | 861 | | /// </summary> |
| | | 862 | | /// <param name="componentTypes">Component classes to scan.</param> |
| | | 863 | | /// <returns>A de-duplicated list of enums to export.</returns> |
| | | 864 | | private static IEnumerable<Type> CollectExportableEnums(IEnumerable<Type> componentTypes) |
| | | 865 | | { |
| | 63 | 866 | | var enums = new HashSet<Type>(); |
| | | 867 | | |
| | 142 | 868 | | foreach (var componentType in componentTypes) |
| | | 869 | | { |
| | 82 | 870 | | foreach (var p in componentType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Dec |
| | | 871 | | { |
| | 68 | 872 | | foreach (var enumType in FindEnumsInType(p.PropertyType)) |
| | | 873 | | { |
| | 1 | 874 | | _ = enums.Add(enumType); |
| | | 875 | | } |
| | | 876 | | } |
| | | 877 | | } |
| | | 878 | | |
| | 63 | 879 | | return enums; |
| | | 880 | | } |
| | | 881 | | |
| | | 882 | | /// <summary> |
| | | 883 | | /// Finds any enum types within a possibly wrapped type (nullable/array/generic). |
| | | 884 | | /// </summary> |
| | | 885 | | /// <param name="t">Type to inspect.</param> |
| | | 886 | | /// <returns>Zero or more enum types found.</returns> |
| | | 887 | | private static IEnumerable<Type> FindEnumsInType(Type t) |
| | | 888 | | { |
| | | 889 | | // Nullable<T> |
| | 38 | 890 | | if (Nullable.GetUnderlyingType(t) is Type underlying) |
| | | 891 | | { |
| | 4 | 892 | | foreach (var e in FindEnumsInType(underlying)) |
| | | 893 | | { |
| | 0 | 894 | | yield return e; |
| | | 895 | | } |
| | 2 | 896 | | yield break; |
| | | 897 | | } |
| | | 898 | | |
| | | 899 | | // Arrays |
| | 36 | 900 | | if (t.IsArray) |
| | | 901 | | { |
| | 6 | 902 | | foreach (var e in FindEnumsInType(t.GetElementType()!)) |
| | | 903 | | { |
| | 0 | 904 | | yield return e; |
| | | 905 | | } |
| | 3 | 906 | | yield break; |
| | | 907 | | } |
| | | 908 | | |
| | | 909 | | // Generic arguments |
| | 33 | 910 | | if (t.IsGenericType) |
| | | 911 | | { |
| | 0 | 912 | | foreach (var arg in t.GetGenericArguments()) |
| | | 913 | | { |
| | 0 | 914 | | foreach (var e in FindEnumsInType(arg)) |
| | | 915 | | { |
| | 0 | 916 | | yield return e; |
| | | 917 | | } |
| | | 918 | | } |
| | | 919 | | } |
| | | 920 | | |
| | 33 | 921 | | if (t.IsEnum) |
| | | 922 | | { |
| | 1 | 923 | | yield return t; |
| | | 924 | | } |
| | 33 | 925 | | } |
| | | 926 | | |
| | | 927 | | /// <summary> |
| | | 928 | | /// Appends a PowerShell enum definition for the specified .NET enum type. |
| | | 929 | | /// </summary> |
| | | 930 | | /// <param name="enumType">Enum type to emit.</param> |
| | | 931 | | /// <param name="sb">Output StringBuilder.</param> |
| | | 932 | | private static void AppendEnum(Type enumType, StringBuilder sb) |
| | | 933 | | { |
| | 1 | 934 | | if (!enumType.IsEnum) |
| | | 935 | | { |
| | 0 | 936 | | return; |
| | | 937 | | } |
| | | 938 | | |
| | 1 | 939 | | var underlying = Enum.GetUnderlyingType(enumType); |
| | 1 | 940 | | var psUnderlying = ResolvePrimitiveTypeName(underlying) ?? underlying.FullName ?? "int"; |
| | | 941 | | |
| | 1 | 942 | | _ = sb.AppendLine($"enum {enumType.Name} {{"); |
| | | 943 | | |
| | 8 | 944 | | foreach (var name in Enum.GetNames(enumType)) |
| | | 945 | | { |
| | 3 | 946 | | var rawValue = Enum.Parse(enumType, name); |
| | 3 | 947 | | var numericValue = Convert.ChangeType(rawValue, underlying, provider: System.Globalization.CultureInfo.Invar |
| | | 948 | | |
| | | 949 | | // Always emit explicit values to preserve non-sequential enums. |
| | 3 | 950 | | _ = sb.AppendLine($" {name} = [{psUnderlying}]{numericValue}"); |
| | | 951 | | } |
| | | 952 | | |
| | 1 | 953 | | _ = sb.AppendLine("}"); |
| | 1 | 954 | | } |
| | | 955 | | |
| | | 956 | | /// <summary> |
| | | 957 | | /// Resolves the PowerShell type name for OpenAPI array wrapper components. |
| | | 958 | | /// </summary> |
| | | 959 | | /// <param name="t">The .NET type to resolve.</param> |
| | | 960 | | /// <param name="componentSet">The set of known OpenAPI component types.</param> |
| | | 961 | | /// <param name="collapseToUnderlyingPrimitives">When true, types derived from OpenApiValue<T> are emitted as |
| | | 962 | | /// <returns>The PowerShell type name for the array element if applicable; otherwise, null.</returns> |
| | | 963 | | private static string? ResolveElementArrayType(Type t, HashSet<Type> componentSet, bool collapseToUnderlyingPrimitiv |
| | | 964 | | { |
| | | 965 | | // OpenAPI schema component array wrappers: |
| | | 966 | | // Some PowerShell OpenAPI schemas are modeled as a component class with Array=$true, |
| | | 967 | | // typically inheriting from the element schema type (e.g. EventDates : Date). |
| | | 968 | | // When referenced as a property type, we want the PowerShell type constraint to be |
| | | 969 | | // the element array (e.g. [Date[]]) instead of the wrapper class ([EventDates]). |
| | | 970 | | // IMPORTANT: this must run before OpenApiValue<T> collapsing so wrappers don't lose their array-ness. |
| | 46 | 971 | | if (collapseToUnderlyingPrimitives && componentSet.Contains(t) && TryGetArrayComponentElementType(t, out var ele |
| | | 972 | | { |
| | | 973 | | // Guard against pathological self-references. |
| | 1 | 974 | | if (elementType == t) |
| | | 975 | | { |
| | 0 | 976 | | return t.Name; |
| | | 977 | | } |
| | | 978 | | |
| | 1 | 979 | | var elementPsName = ToPowerShellTypeName(elementType, componentSet, collapseToUnderlyingPrimitives); |
| | 1 | 980 | | return $"{elementPsName}[]"; |
| | | 981 | | } |
| | 45 | 982 | | return null; |
| | | 983 | | } |
| | | 984 | | |
| | | 985 | | // Mapping of .NET primitive types to PowerShell type names. |
| | 1 | 986 | | private static readonly Dictionary<Type, string> PrimitiveTypeAliases = |
| | 1 | 987 | | new() |
| | 1 | 988 | | { |
| | 1 | 989 | | [typeof(bool)] = "bool", |
| | 1 | 990 | | [typeof(byte)] = "byte", |
| | 1 | 991 | | [typeof(sbyte)] = "sbyte", |
| | 1 | 992 | | [typeof(short)] = "short", |
| | 1 | 993 | | [typeof(ushort)] = "ushort", |
| | 1 | 994 | | [typeof(int)] = "int", |
| | 1 | 995 | | [typeof(uint)] = "uint", |
| | 1 | 996 | | [typeof(long)] = "long", |
| | 1 | 997 | | [typeof(ulong)] = "ulong", |
| | 1 | 998 | | [typeof(float)] = "float", |
| | 1 | 999 | | [typeof(double)] = "double", |
| | 1 | 1000 | | [typeof(decimal)] = "decimal", |
| | 1 | 1001 | | [typeof(char)] = "char", |
| | 1 | 1002 | | [typeof(string)] = "string", |
| | 1 | 1003 | | [typeof(object)] = "object", |
| | 1 | 1004 | | [typeof(DateTime)] = "datetime", |
| | 1 | 1005 | | [typeof(Guid)] = "guid", |
| | 1 | 1006 | | [typeof(byte[])] = "byte[]" |
| | 1 | 1007 | | }; |
| | | 1008 | | |
| | | 1009 | | /// <summary> |
| | | 1010 | | /// Resolves the PowerShell type name for common .NET primitive types. |
| | | 1011 | | /// </summary> |
| | | 1012 | | /// <param name="t">The .NET type to resolve.</param> |
| | | 1013 | | /// <returns>The PowerShell type name if the type is a recognized primitive; otherwise, null.</returns> |
| | | 1014 | | private static string? ResolvePrimitiveTypeName(Type t) |
| | | 1015 | | { |
| | | 1016 | | // unwrap nullable if needed |
| | 39 | 1017 | | t = Nullable.GetUnderlyingType(t) ?? t; |
| | | 1018 | | |
| | 39 | 1019 | | return PrimitiveTypeAliases.TryGetValue(t, out var alias) ? alias : null; |
| | | 1020 | | } |
| | | 1021 | | |
| | | 1022 | | private static bool TryGetOpenApiValueUnderlyingType(Type t, out Type? underlyingType) |
| | | 1023 | | { |
| | 41 | 1024 | | underlyingType = null; |
| | | 1025 | | |
| | | 1026 | | // Walk base types looking for OpenApiScalar<T> (preferred) or OpenApiValue<T> (legacy) |
| | | 1027 | | // by name to avoid hard coupling. |
| | | 1028 | | // OpenApiScalar<T> lives in Kestrun.Annotations and is in the global namespace. |
| | 41 | 1029 | | var current = t; |
| | | 1030 | | |
| | 111 | 1031 | | while (current is not null && current != typeof(object)) |
| | | 1032 | | { |
| | 76 | 1033 | | if (current.IsGenericType) |
| | | 1034 | | { |
| | 6 | 1035 | | var def = current.GetGenericTypeDefinition(); |
| | 6 | 1036 | | if (string.Equals(def.Name, "OpenApiScalar`1", StringComparison.Ordinal) || |
| | 6 | 1037 | | string.Equals(def.Name, "OpenApiValue`1", StringComparison.Ordinal)) |
| | | 1038 | | { |
| | 6 | 1039 | | underlyingType = current.GetGenericArguments()[0]; |
| | 6 | 1040 | | return true; |
| | | 1041 | | } |
| | | 1042 | | } |
| | | 1043 | | |
| | 70 | 1044 | | current = current.BaseType; |
| | | 1045 | | } |
| | | 1046 | | |
| | 35 | 1047 | | return false; |
| | | 1048 | | } |
| | | 1049 | | |
| | | 1050 | | private static bool TryGetArrayComponentElementType(Type componentType, out Type? elementType) |
| | | 1051 | | { |
| | 4 | 1052 | | elementType = null; |
| | | 1053 | | |
| | | 1054 | | // We don't take a hard dependency on the annotation type here; this exporter |
| | | 1055 | | // may reflect PowerShell-generated assemblies. We detect the attribute by name |
| | | 1056 | | // and then read common properties via reflection. |
| | 4 | 1057 | | var attr = componentType |
| | 4 | 1058 | | .GetCustomAttributes(inherit: false) |
| | 8 | 1059 | | .FirstOrDefault(a => a.GetType().Name.Contains("OpenApiSchemaComponent", StringComparison.OrdinalIgnoreCase) |
| | | 1060 | | |
| | 4 | 1061 | | if (attr is null) |
| | | 1062 | | { |
| | 0 | 1063 | | return false; |
| | | 1064 | | } |
| | | 1065 | | |
| | 4 | 1066 | | var attrType = attr.GetType(); |
| | 4 | 1067 | | var arrayProp = attrType.GetProperty("Array"); |
| | 4 | 1068 | | if (arrayProp?.GetValue(attr) is not bool isArray || !isArray) |
| | | 1069 | | { |
| | 3 | 1070 | | return false; |
| | | 1071 | | } |
| | | 1072 | | |
| | | 1073 | | // Prefer explicit ItemsType if provided. |
| | 1 | 1074 | | var itemsTypeProp = attrType.GetProperty("ItemsType"); |
| | 1 | 1075 | | if (itemsTypeProp?.GetValue(attr) is Type itemsType) |
| | | 1076 | | { |
| | 0 | 1077 | | elementType = itemsType; |
| | 0 | 1078 | | return true; |
| | | 1079 | | } |
| | | 1080 | | |
| | | 1081 | | // Common PowerShell pattern: wrapper inherits from element schema. |
| | 1 | 1082 | | var baseType = componentType.BaseType; |
| | 1 | 1083 | | if (baseType is not null && baseType != typeof(object)) |
| | | 1084 | | { |
| | 1 | 1085 | | elementType = baseType; |
| | 1 | 1086 | | return true; |
| | | 1087 | | } |
| | | 1088 | | |
| | 0 | 1089 | | return false; |
| | | 1090 | | } |
| | | 1091 | | |
| | | 1092 | | /// <summary> |
| | | 1093 | | /// Topologically sort types so that dependencies (property types) |
| | | 1094 | | /// appear before the types that reference them. |
| | | 1095 | | /// </summary> |
| | | 1096 | | /// <param name="types">The list of types to sort.</param> |
| | | 1097 | | /// <param name="componentSet">Set of component types for quick lookup.</param> |
| | | 1098 | | /// <returns>The sorted list of types.</returns> |
| | | 1099 | | private static List<Type> TopologicalSortByPropertyDependencies( |
| | | 1100 | | List<Type> types, |
| | | 1101 | | HashSet<Type> componentSet) |
| | | 1102 | | { |
| | 63 | 1103 | | var result = new List<Type>(); |
| | 63 | 1104 | | var visited = new Dictionary<Type, bool>(); // false = temp-mark, true = perm-mark |
| | | 1105 | | |
| | 142 | 1106 | | foreach (var t in types) |
| | | 1107 | | { |
| | 8 | 1108 | | Visit(t, componentSet, visited, result); |
| | | 1109 | | } |
| | | 1110 | | |
| | 63 | 1111 | | return result; |
| | | 1112 | | } |
| | | 1113 | | |
| | | 1114 | | /// <summary> |
| | | 1115 | | /// Visits the type and its dependencies recursively for topological sorting. |
| | | 1116 | | /// </summary> |
| | | 1117 | | /// <param name="t">Type to visit</param> |
| | | 1118 | | /// <param name="componentSet">Set of component types</param> |
| | | 1119 | | /// <param name="visited">Dictionary tracking visited types and their mark status</param> |
| | | 1120 | | /// <param name="result">List to accumulate the sorted types</param> |
| | | 1121 | | private static void Visit( |
| | | 1122 | | Type t, |
| | | 1123 | | HashSet<Type> componentSet, |
| | | 1124 | | Dictionary<Type, bool> visited, |
| | | 1125 | | List<Type> result) |
| | | 1126 | | { |
| | 13 | 1127 | | if (visited.TryGetValue(t, out var perm)) |
| | | 1128 | | { |
| | 5 | 1129 | | if (!perm) |
| | | 1130 | | { |
| | | 1131 | | // cycle; ignore for now |
| | 5 | 1132 | | return; |
| | | 1133 | | } |
| | | 1134 | | return; |
| | | 1135 | | } |
| | | 1136 | | |
| | | 1137 | | // temp-mark |
| | 8 | 1138 | | visited[t] = false; |
| | | 1139 | | |
| | 8 | 1140 | | var deps = new List<Type>(); |
| | | 1141 | | |
| | | 1142 | | // 1) Dependencies via property types (component properties) |
| | 8 | 1143 | | var propDeps = t.GetProperties(BindingFlags.Public | BindingFlags.Instance) |
| | 40 | 1144 | | .Select(p => GetComponentDependencyType(p.PropertyType, componentSet)) |
| | 40 | 1145 | | .Where(dep => dep is not null) |
| | 3 | 1146 | | .Select(dep => dep!) |
| | 8 | 1147 | | .Distinct(); |
| | | 1148 | | |
| | 8 | 1149 | | deps.AddRange(propDeps); |
| | | 1150 | | |
| | | 1151 | | // 2) Dependency via base type (parenting) |
| | 8 | 1152 | | var baseType = t.BaseType; |
| | 8 | 1153 | | if (baseType != null && componentSet.Contains(baseType)) |
| | | 1154 | | { |
| | 2 | 1155 | | deps.Add(baseType); |
| | | 1156 | | } |
| | | 1157 | | |
| | 26 | 1158 | | foreach (var dep in deps.Distinct()) |
| | | 1159 | | { |
| | 5 | 1160 | | Visit(dep, componentSet, visited, result); |
| | | 1161 | | } |
| | | 1162 | | |
| | | 1163 | | // perm-mark |
| | 8 | 1164 | | visited[t] = true; |
| | 8 | 1165 | | result.Add(t); |
| | 8 | 1166 | | } |
| | | 1167 | | |
| | | 1168 | | private static Type? GetComponentDependencyType(Type propertyType, HashSet<Type> componentSet) |
| | | 1169 | | { |
| | | 1170 | | // Unwrap Nullable |
| | 40 | 1171 | | if (Nullable.GetUnderlyingType(propertyType) is Type underlying) |
| | | 1172 | | { |
| | 2 | 1173 | | propertyType = underlying; |
| | | 1174 | | } |
| | | 1175 | | |
| | | 1176 | | // Unwrap arrays |
| | 40 | 1177 | | if (propertyType.IsArray) |
| | | 1178 | | { |
| | 3 | 1179 | | propertyType = propertyType.GetElementType()!; |
| | | 1180 | | } |
| | | 1181 | | |
| | 40 | 1182 | | return componentSet.Contains(propertyType) ? propertyType : null; |
| | | 1183 | | } |
| | | 1184 | | |
| | | 1185 | | /// <summary> |
| | | 1186 | | /// Writes the OpenAPI class definitions to a temporary PowerShell script file. |
| | | 1187 | | /// </summary> |
| | | 1188 | | /// <param name="openApiClasses">The OpenAPI class definitions as a string.</param> |
| | | 1189 | | /// <returns>The path to the temporary PowerShell script file.</returns> |
| | | 1190 | | public static string WriteOpenApiTempScript(string openApiClasses) |
| | | 1191 | | { |
| | | 1192 | | // Use a stable file name so multiple runspaces share the same script |
| | 4 | 1193 | | var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".ps1"); |
| | | 1194 | | |
| | | 1195 | | // Ensure directory exists |
| | 4 | 1196 | | _ = Directory.CreateDirectory(Path.GetDirectoryName(tempPath)!); |
| | | 1197 | | |
| | | 1198 | | // Build content with header |
| | 4 | 1199 | | var sb = new StringBuilder() |
| | 4 | 1200 | | .AppendLine("# ================================================") |
| | 4 | 1201 | | .AppendLine("# Kestrun OpenAPI Autogenerated Class Definitions") |
| | 4 | 1202 | | .AppendLine("# DO NOT EDIT - generated at runtime") |
| | 4 | 1203 | | .Append("# Timestamp: ").Append(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")).Append('Z').AppendLine() |
| | 4 | 1204 | | .AppendLine("# ================================================") |
| | 4 | 1205 | | .AppendLine() |
| | 4 | 1206 | | .AppendLine("[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSProvideCommentHelp', '')]") |
| | 4 | 1207 | | .AppendLine("param()") |
| | 4 | 1208 | | .AppendLine(openApiClasses); |
| | | 1209 | | |
| | | 1210 | | // Save using UTF-8 without BOM |
| | 4 | 1211 | | File.WriteAllText(tempPath, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); |
| | | 1212 | | |
| | 4 | 1213 | | return tempPath; |
| | | 1214 | | } |
| | | 1215 | | } |