| | | 1 | | |
| | | 2 | | <# |
| | | 3 | | .SYNOPSIS |
| | | 4 | | Safely resolves a schema input to a .NET [Type], supporting generics and arrays. |
| | | 5 | | .DESCRIPTION |
| | | 6 | | This function takes a schema input that can be either a PowerShell type literal string (e.g., '[System.Collections.G |
| | | 7 | | or a [Type] object, and resolves it to a .NET [Type]. It includes validation to ensure the input is in the correct f |
| | | 8 | | .PARAMETER Schema |
| | | 9 | | The schema input to resolve, either as a PowerShell type literal string or a [Type] object. |
| | | 10 | | .OUTPUTS |
| | | 11 | | [Type] |
| | | 12 | | .EXAMPLE |
| | | 13 | | $type = Resolve-KrSchemaTypeLiteral -Schema '[System.Collections.Generic.List[System.String]]' |
| | | 14 | | This example resolves the schema string to the corresponding .NET [Type] for a list of strings. |
| | | 15 | | .NOTES |
| | | 16 | | This function is part of the Kestrun PowerShell module for working with OpenAPI specifications |
| | | 17 | | #> |
| | | 18 | | function Resolve-KrSchemaTypeLiteral { |
| | | 19 | | [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '')] |
| | | 20 | | [CmdletBinding()] |
| | | 21 | | param( |
| | | 22 | | [Parameter(Mandatory)] |
| | | 23 | | [object] $Schema |
| | | 24 | | ) |
| | | 25 | | |
| | 0 | 26 | | if ($Schema -is [type]) { |
| | 0 | 27 | | return $Schema |
| | 0 | 28 | | } elseif ($Schema -is [string]) { |
| | 0 | 29 | | $s = $Schema.Trim() |
| | | 30 | | |
| | | 31 | | # Require PowerShell type-literal form: [TypeName] or [Namespace.TypeName] |
| | | 32 | | # Disallow generics, arrays, scripts, whitespace, operators, etc. |
| | 0 | 33 | | if ($s -notmatch '^\[[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*\]$') { |
| | 0 | 34 | | throw "Invalid -Schema '$Schema'. Only type literals like '[OpenApiDate]' are allowed." |
| | | 35 | | } |
| | | 36 | | |
| | | 37 | | # Optional: reject some known-dangerous tokens defensively (belt + suspenders) |
| | 0 | 38 | | if ($s -match '[\s;|&`$(){}<>]') { |
| | 0 | 39 | | throw "Invalid -Schema '$Schema'. Disallowed characters detected." |
| | | 40 | | } |
| | | 41 | | |
| | 0 | 42 | | $Schema = Invoke-Expression $s |
| | | 43 | | |
| | 0 | 44 | | if ($Schema -isnot [type]) { |
| | 0 | 45 | | throw "Invalid -Schema '$Schema'. Evaluation did not produce a [Type]." |
| | | 46 | | } |
| | 0 | 47 | | return $Schema |
| | | 48 | | } else { |
| | 0 | 49 | | throw "Invalid -Schema type '$($Schema.GetType().FullName)'. Use ([string]) or 'System.String'." |
| | | 50 | | } |
| | | 51 | | } |