AutoRest.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\AutoRest.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName AutoRest.Import.DoDotSource -Fallback $false
if ($AutoRest_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName AutoRest.Import.IndividualFiles -Fallback $false
if ($AutoRest_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'AutoRest' -Language 'en-US'

enum ParameterType {
    Body
    Path
    Query
    Header
    Misc
}

class CommandParameter {
    [string]$Name
    [string]$SystemName
    [string]$Help = '<insert description here>'
    [string]$ParameterType = 'string'
    [string[]]$ParameterSet = @('default')
    [string[]]$Alias
    [bool]$Mandatory
    [bool]$ValueFromPipeline
    [int]$Weight = 1000
    [ParameterType]$Type

    [string]ToExample() {
        return '-{0} ${1}' -f $this.Name, $this.Name.ToLower()
    }

    [string]ToHelp() {
        return @'
.PARAMETER {0}
    {1}
'@
 -f $this.Name, $this.Help
    }

    [string]ToParam() {
        $sb = [System.Text.StringBuilder]::new()
        $mandatoryString = ''
        if ($this.Mandatory) { $mandatoryString = 'Mandatory = $true, ' }
        $pipelineString = ''
        if ($this.ValueFromPipeline) { $pipelineString = 'ValueFromPipeline = $true, ' }
        foreach ($set in $this.ParameterSet) {
            $null = $sb.AppendLine((" [Parameter({0}{1}ValueFromPipelineByPropertyName = `$true, ParameterSetName = '{2}')]" -f $mandatoryString, $pipelineString, $set))
        }
        if ($this.Alias) { $null = $sb.AppendLine(" [Alias($($this.Alias | Add-String "'" "'" | Join-String ','))]") }
        $typeName = $this.ParameterType
        if (-not $typeName) { $typeName = 'object' }
        $null = $sb.AppendLine(" [$typeName]")
        $null = $sb.Append(" `$$($this.Name)")
        return $sb.ToString()
    }

    CommandParameter() { }

    CommandParameter(
        [string]$Name
    ) {
        $this.SystemName = $Name
        $this.Name = $Name.Trim('$') | Split-String -Separator "\s" | ForEach-Object {
            $_.SubString(0, 1).ToUpper() + $_.Substring(1)
        } | Join-String -Separator ""
    }
    CommandParameter(
        [string]$Name,
        [string]$Help,
        [string]$ParameterType,
        [bool]$Mandatory,
        [ParameterType]$Type
    ) {
        $this.SystemName = $Name
        $this.Name = $Name.Trim('$') | Split-String -Separator "\s|-" | ForEach-Object {
            $_.SubString(0, 1).ToUpper() + $_.Substring(1)
        } | Join-String -Separator ""
        $this.Help = $Help
        $this.ParameterType = $ParameterType
        if ($Name -eq '$select' -and $ParameterType -eq 'string') {
            $this.ParameterType = 'string[]'
        }
        $this.Mandatory = $Mandatory
        $this.Type = $Type
    }
}

class Command {
    [string]$Name
    [string]$Synopsis
    [string]$Description
    [string]$DocumentationUrl = '<unknown>'

    [string]$Method
    [string]$EndpointUrl
    [string]$ServiceName
    [string[]]$Scopes = @()

    [Hashtable]$Parameters = @{ }
    [Hashtable]$ParameterSets = @{ }

    [string]$RestCommand
    [string]$ProcessorCommand

    [string]$ShouldProcess
    [string]$ShouldProcessTarget
    [string[]]$PssaRulesIgnored

    [string]$ConvertToHashtableCommand

    [string]ToExample() {
        $format = @'
.EXAMPLE
    PS C:\> {0}
 
    {1}
'@

        $sets = @{ }
        foreach ($set in $this.ParameterSets.Keys) {
            $sets[$set] = @()
        }
        foreach ($parameter in $this.Parameters.Values) {
            foreach ($set in $parameter.ParameterSet) {
                if ($sets[$set]) { continue }
                $sets[$set] = @()
            }
            if (-not $parameter.Mandatory) { continue }

            foreach ($set in $parameter.ParameterSet) {
                $sets[$set] += $parameter
            }
        }

        $texts = foreach ($set in $sets.Keys) {
            $descriptionText = '<insert description here>'
            if ($this.ParameterSets[$set]) { $descriptionText = $this.ParameterSets[$set] }

            $commandText = (@($this.Name) + @(($sets[$set] | ForEach-Object ToExample))) -join " "

            $format -f $commandText, $descriptionText
        }

        return $texts -join "`n`n"
    }

    [string]ToHelp() {
        $format = @'
<#
.SYNOPSIS
    {0}
 
.DESCRIPTION
    {1}
 
{2}
 
{3}
 
.LINK
    {4}
#>
'@

        $parameterHelp = $this.Parameters.Values | Sort-Object Weight | ForEach-Object ToHelp | Join-String -Separator "`n`n"
        if ($this.ShouldProcess) {
            $shouldPropcessHelp = @'
.PARAMETER Confirm
    If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
 
.PARAMETER WhatIf
    If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
'@

            $parameterHelp = $parameterHelp, $shouldPropcessHelp -join "`n`n"
        }
        $descriptionText = $this.Description
        if ($this.Scopes) { $descriptionText = $descriptionText, (' Scopes required (delegate auth): {0}' -f ($this.Scopes -join ", ")) -join "`n`n" }
        return $format -f $this.Synopsis, $descriptionText, $parameterHelp, $this.ToExample(), $this.DocumentationUrl
    }

    [string]ToParam() {
        if (-not $this.ShouldProcess -and $this.Name -match '^New-|^Remove-|^Set-') {
            $this.PssaRulesIgnored = @($this.PssaRulesIgnored) + @('PSUseShouldProcessForStateChangingFunctions')
        }
        $pssaString = ''
        foreach ($rule in $this.PssaRulesIgnored) {
            if (-not "$rule") { continue }
            $pssaString += @"
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('$rule', '')]
 
"@

        }
        
        $supportsShouldProcess = ''
        if ($this.ShouldProcess) { $supportsShouldProcess = ', SupportsShouldProcess = $true' }
        return @"
$pssaString [CmdletBinding(DefaultParameterSetName = 'default'$($supportsShouldProcess))]
    param (
$($this.Parameters.Values | Sort-Object Weight | ForEach-Object ToParam | Join-String ",`n`n")
    )
"@

    }

    [string]ToProcess() {
        $format = @'
        $__mapping = @{{
{9}
        }}
        $__body = $PSBoundParameters | {11} -Include {0} -Mapping $__mapping
        $__query = $PSBoundParameters | {11} -Include {1} -Mapping $__mapping
        $__header = $PSBoundParameters | {11} -Include {12} -Mapping $__mapping
        $__path = '{2}'{3}
{13}
        {4} -Path $__path -Method {5} -Body $__body -Query $__query -Header $__header{10}{6}{7}{8}
'@

        $bodyString = '@({0})' -f (($this.Parameters.Values | Where-Object Type -EQ Body).Name | Add-String "'" "'" | Join-String ",")
        $queryString = '@({0})' -f (($this.Parameters.Values | Where-Object Type -EQ Query).Name | Add-String "'" "'" | Join-String ",")
        $headerString = '@({0})' -f (($this.Parameters.Values | Where-Object Type -EQ Header).Name | Add-String "'" "'" | Join-String ",")
        [string]$pathReplacement = $this.Parameters.Values | Where-Object {
            $_.Type -eq 'Path' -and
            $this.EndpointUrl -like "*{$($_.SystemName)}*"
        } | Format-String -Format " -Replace '{{{0}}}',`${1}" -Property SystemName, Name | Join-String ""
        if ($optionalParameter = $this.Parameters.Values | Where-Object { $_.Type -eq 'Path' -and $this.EndpointUrl -notlike "*{$($_.SystemName)}*" }) {
            $pathReplacement = $pathReplacement + @'
 
        if (${0}) {{ $__path += "/${0}" }}
'@
 -f $optionalParameter.Name
        }
        $scopesString = ''
        if ($this.Scopes) { $scopesString = ' -RequiredScopes {0}' -f ($this.Scopes | Add-String "'" "'" | Join-String ',') }
        $processorString = ''
        if ($this.ProcessorCommand) { $processorString = " | $($this.ProcessorCommand)" }
        $serviceString = ''
        if ($this.ServiceName) { $serviceString = " -Service $($this.ServiceName)" }
        $mappingString = $this.Parameters.Values | Where-Object Type -NE Path | Format-String -Format " '{0}' = '{1}'" -Property Name, SystemName | Join-String "`n"
        $miscParameterString = $this.Parameters.Values | Where-Object Type -eq Misc | Format-String -Format ' -{0} ${1}' -Property SystemName, Name | Join-String " "
        $shouldProcessString = ''
        if ($this.ShouldProcess) {
            $target = $this.ShouldProcessTarget
            if (-not $target) { $target = '${0}' -f @(@($this.Parameters.Keys).Where{ $_ -like "*ID" })[0] }
            if ($target -eq '$') { $target = '<target>' }
            $shouldProcessString = ' if (-not $PSCmdlet.ShouldProcess("{0}","{1}")) {{ return }}' -f $target, $this.ShouldProcess
        }

        return $format -f $bodyString, $queryString, $this.EndpointUrl, $pathReplacement, $this.RestCommand, $this.Method, $scopesString, $serviceString, $processorString, $mappingString, $miscParameterString, $this.ConvertToHashtableCommand, $headerString, $shouldProcessString
    }

    [string]ToCommand([bool]$NoHelp = $false) {
        if ($NoHelp) {
            return @"
function $($this.Name) {
$($this.ToParam())
    process {
$($this.ToProcess())
    }
}
"@

        }
        return @"
function $($this.Name) {
$($this.ToHelp())
$($this.ToParam())
    process {
$($this.ToProcess())
    }
}
"@

    }
}

function ConvertFrom-ARSwagger {
    <#
    .SYNOPSIS
        Parse a swagger file and generate commands from it.
 
    .DESCRIPTION
        Parse a swagger file and generate commands from it.
        Only supports the JSON format of swagger file.
 
    .PARAMETER Path
        Path to the swagger file(s) to process.
 
    .PARAMETER TransformPath
        Path to a folder containing psd1 transform files.
        These can be used to override or add to individual entries from the swagger file.
        For example, you can add help URI, fix missing descriptions, add parameter help or attributes...
 
    .PARAMETER RestCommand
        Name of the command executing the respective REST queries.
        All autogenerated commands will call this command to execute.
 
    .PARAMETER ConvertToHashtableCommand
        In order to make it easier to include a version of `ConvertTo-Hashtable` you can rename the used
        function name by using this parameter. Defaults to `ConvertTo-Hashtable`.
 
    .PARAMETER ModulePrefix
        A prefix to add to all commands generated from this command.
 
    .PARAMETER PathPrefix
        Swagger files may include the same first uri segments in all endpoints.
        While this could be just passed through, you can also remove them using this parameter.
        It is then assumed, that the command used in the RestCommand is aware of this and adds it again to the request.
        Example:
        All endpoints in the swagger-file start with "/api/"
        "/api/users", "/api/machines", "/api/software", ...
        In that case, it could make sense to remove the "/api/" part from all commands and just include it in the invokation command.
 
    .PARAMETER ServiceName
        Adds the servicename to the commands generated.
        When exported, they will be hardcoded to execute as that service.
        This simplifies the configuration of the output, but prevents using multiple connections to different instances or under different privileges at the same time.
 
    .EXAMPLE
        PS C:\> Get-ChildItem .\swaggerfiles | ConvertFrom-ARSwagger -Transformpath .\transform -RestCommand Invoke-ARRestRequest -ModulePrefix Mg -PathPrefix '/api/'
 
        Picks up all items in the subfolder "swaggerfiles" and converts it to PowerShell command objects.
        Applies all transforms in the subfolder transform.
        Uses the "Invoke-ARRestRequest" command for all rest requests.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [PsfValidateScript('PSFramework.Validate.FSPath.File', ErrorString = 'PSFramework.Validate.FSPath.File')]
        [Alias('FullName')]
        [string]
        $Path,

        [PsfValidateScript('PSFramework.Validate.FSPath.Folder', ErrorString = 'PSFramework.Validate.FSPath.Folder')]
        [string]
        $TransformPath,

        [Parameter(Mandatory = $true)]
        [string]
        $RestCommand,

        [string]
        $ConvertToHashtableCommand = 'ConvertTo-Hashtable',

        [string]
        $ModulePrefix,

        [string]
        $PathPrefix,

        [string]
        $ServiceName
    )

    begin {
        #region Functions
        function Copy-ParameterConfig {
            [CmdletBinding()]
            param (
                [Hashtable]
                $Config,

                $Parameter
            )

            if ($Config.Help) { $Parameter.Help = $Config.Help }
            if ($Config.Name) { $Parameter.Name = $Config.Name }
            if ($Config.Alias) { $Parameter.Alias = $Config.Alias }
            if ($Config.Weight) { $Parameter.Weight = $Config.Weight }
            if ($Config.ParameterType) { $Parameter.ParameterType = $Config.ParameterType }
            if ($Config.ContainsKey('ValueFromPipeline')) { $Parameter.ValueFromPipeline = $Config.ValueFromPipeline }
            if ($Config.ParameterSet) { $Parameter.ParameterSet = $Config.ParameterSet }
        }

        function New-Parameter {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
            [CmdletBinding()]
            param (
                [string]
                $Name,

                [string]
                $Help,

                [string]
                $ParameterType,

                [AllowEmptyString()]
                [AllowNull()]
                [string]
                $ParameterFormat,

                [bool]
                $Mandatory,

                [ParameterType]
                $Type
            )

            $parameter = [CommandParameter]::new(
                $Name,
                $Help,
                $ParameterType,
                $Mandatory,
                $Type
            )
            if ($parameter.ParameterType -eq "integer") {
                $parameter.ParameterType = $ParameterFormat
            }
            $parameter
        }

        function Resolve-ParameterReference {
            [CmdletBinding()]
            param (
                [string]
                $Ref,

                $SwaggerObject
            )

            # "#/components/parameters/top"
            $segments = $Ref | Set-String -OldValue '^#/' | Split-String -Separator '/'
            $paramValue = $SwaggerObject
            foreach ($segment in $segments) {
                $paramValue = $paramValue.$segment
            }
            $paramValue
        }
        
        function Read-Parameters {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
            [CmdletBinding()]
            param (
                [Command]
                $CommandObject,
                
                $Parameters,
                
                $SwaggerObject,
                
                [PSFramework.Message.MessageLevel]
                $LogLevel,
                
                [string]
                $ParameterSet
            )
            
            foreach ($parameter in $Parameters) {
                if ($parameter.'$ref') {
                    $parameter = Resolve-ParameterReference -Ref $parameter.'$ref' -SwaggerObject $SwaggerObject
                    if (-not $parameter) {
                        Write-PSFMessage -Level Warning -Message " Unable to resolve referenced parameter $($parameter.'$ref')"
                        continue
                    }
                }
                if ($LogLevel -le [PSFramework.Message.MessageLevel]::Verbose) {
                    # This is on hot path. Checking if we should write the message in a cheap way.
                    Write-PSFMessage " Processing Parameter: $($parameter.Name) ($($parameter.in))"
                }
                switch ($parameter.in) {
                    #region Body
                    body {
                        foreach ($property in $parameter.schema.properties.PSObject.Properties) {
                            if ($ParameterSet -and $CommandObject.Parameters[$property.Value.title]) {
                                $CommandObject.Parameters[$property.Value.title].ParameterSet += @($ParameterSet)
                                continue
                            }
                            
                            $parameterParam = @{
                                Name            = $property.Value.title
                                Help            = $property.Value.description
                                ParameterType   = $property.Value.type
                                ParameterFormat = $property.Value.format
                                Mandatory       = $parameter.schema.required -contains $property.Value.title
                                Type            = 'Body'
                            }
                            $CommandObject.Parameters[$property.Value.title] = New-Parameter @parameterParam
                            if ($ParameterSet) {
                                $commandObject.Parameters[$property.Value.title].ParameterSet = @($ParameterSet)
                            }
                        }
                    }
                    #endregion Body
                    
                    #region Path
                    path {
                        if ($ParameterSet -and $CommandObject.Parameters[($parameter.name -replace '\s')]) {
                            $CommandObject.Parameters[($parameter.name -replace '\s')].ParameterSet += @($ParameterSet)
                            continue
                        }
                        
                        $parameterParam = @{
                            Name            = $parameter.Name -replace '\s'
                            Help            = $parameter.Description
                            ParameterType   = 'string'
                            ParameterFormat = $parameter.format
                            Mandatory       = $parameter.required -as [bool]
                            Type            = 'Path'
                        }
                        $CommandObject.Parameters[($parameter.name -replace '\s')] = New-Parameter @parameterParam
                        if ($ParameterSet) {
                            $CommandObject.Parameters[($parameter.name -replace '\s')].ParameterSet = @($ParameterSet)
                        }
                    }
                    #endregion Path
                    
                    #region Query
                    query {
                        if ($CommandObject.Parameters[$parameter.name]) {
                            $CommandObject.Parameters[$parameter.name].ParameterSet += @($parameterSetName)
                            continue
                        }
                        
                        $parameterType = $parameter.type
                        if (-not $parameterType -and $parameter.schema.type) {
                            $parameterType = $parameter.schema.type
                            if ($parameter.schema.type -eq "array" -and $parameter.schema.items.type) {
                                $parameterType = '{0}[]' -f $parameter.schema.items.type
                            }
                        }
                        
                        $parameterParam = @{
                            Name            = $parameter.Name
                            Help            = $parameter.Description
                            ParameterType   = $parameterType
                            ParameterFormat = $parameter.format
                            Mandatory       = $parameter.required -as [bool]
                            Type            = 'Query'
                        }
                        $CommandObject.Parameters[$parameter.name] = New-Parameter @parameterParam
                        if ($ParameterSet) {
                            $CommandObject.Parameters[$parameter.name].ParameterSet = @($ParameterSet)
                        }
                    }
                    #endregion Query
                
                    #region Header
                    header {
                        if ($commandObject.Parameters[$parameter.name]) {
                            $commandObject.Parameters[$parameter.name].ParameterSet += @($parameterSetName)
                            continue
                        }
                        $parameterType = $parameter.type
                        if (-not $parameterType -and $parameter.schema.type) {
                            $parameterType = $parameter.schema.type
                            if ($parameter.schema.type -eq "array" -and $parameter.schema.items.type) {
                                $parameterType = '{0}[]' -f $parameter.schema.items.type
                            }
                        }
                        $parameterParam = @{
                            Name            = $parameter.Name
                            Help            = $parameter.Description
                            ParameterType   = $parameterType
                            ParameterFormat = $parameter.format
                            Mandatory       = $parameter.required -as [bool]
                            Type            = 'header'
                        }
                        $commandObject.Parameters[$parameter.name] = New-Parameter @parameterParam
                        $commandObject.Parameters[$parameter.name].ParameterSet = @($parameterSetName)
                    }
                    #endregion Header
                }
            }
        }
        
        function Set-ParameterOverrides {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
            [CmdletBinding()]
            param (
                [hashtable]
                $Overrides,
                
                [Command]
                $CommandObject,
                
                [string]
                $CommandKey
            )
            
            foreach ($parameterName in $Overrides.globalParameters.Keys) {
                if (-not $CommandObject.Parameters[$parameterName]) { continue }
                
                Copy-ParameterConfig -Config $Overrides.globalParameters[$parameterName] -Parameter $CommandObject.Parameters[$parameterName]
            }
            foreach ($partialPath in $Overrides.scopedParameters.Keys) {
                if ($CommandObject.EndpointUrl -notlike $partialPath) { continue }
                foreach ($parameterPair in $Overrides.scopedParameters.$($partialPath).GetEnumerator()) {
                    if (-not $CommandObject.Parameters[$parameterPair.Name]) { continue }
                    
                    Copy-ParameterConfig -Parameter $CommandObject.Parameters[$parameterPair.Name] -Config $parameterPair.Value
                }
            }
            foreach ($parameterName in $Overrides.$CommandKey.Parameters.Keys) {
                if (-not $CommandObject.Parameters[$parameterName]) {
                    Write-PSFMessage -Level Warning -Message "Invalid override parameter: $parameterName - unable to find parameter on $($CommandObject.Name)" -Target $commandObject
                    continue
                }
                
                Copy-ParameterConfig -Config $Overrides.$CommandKey.Parameters[$parameterName] -Parameter $CommandObject.Parameters[$parameterName]
            }
        }
        
        function Set-CommandOverrides {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
            [CmdletBinding()]
            param (
                [hashtable]
                $Overrides,
                
                [Command]
                $CommandObject,
                
                [string]
                $CommandKey
            )
            
            $commandOverrides = $Overrides.$CommandKey
            
            # Apply Overrides
            foreach ($property in $CommandObject.PSObject.Properties) {
                if ($property.Name -eq 'Parameters') { continue }
                if ($property.Name -eq 'ParameterSets') {
                    foreach ($key in $commandOverrides.ParameterSets.Keys) {
                        $CommandObject.ParameterSets[$key] = $commandOverrides.ParameterSets.$key
                    }
                    continue
                }
                $propertyOverride = $commandOverrides.($property.Name)
                if ($propertyOverride) {
                    $property.Value = $propertyOverride
                }
            }
        }
        #endregion Functions

        $commands = @{ }
        $overrides = @{ }
        if ($TransformPath) {
            foreach ($file in Get-ChildItem -Path $TransformPath -Filter *.psd1) {
                $data = Import-PSFPowerShellDataFile -Path $file.FullName
                foreach ($key in $data.Keys) {
                    $overrides[$key] = $data.$key
                }
            }
        }

        $verbs = @{
            get    = "Get"
            put    = "New"
            post   = "Set"
            patch  = "Set"
            delete = "Remove"
            head   = "Invoke"
        }

        [PSFramework.Message.MessageLevel]$logLevel = Get-PSFConfigValue -FullName AutoRest.Logging.Level -Fallback "Warning"
    }
    process {
        #region Process Swagger file
        foreach ($file in Resolve-PSFPath -Path $Path) {
            $data = Get-Content -Path $file | ConvertFrom-Json
            foreach ($endpoint in $data.paths.PSObject.Properties | Sort-Object { $_.Name.Length }, Name) {
                $endpointPath = ($endpoint.Name -replace "^$PathPrefix" -replace '/{[\w\s\d+-]+}$').Trim("/")
                $effectiveEndpointPath = ($endpoint.Name -replace "^$PathPrefix" -replace '\s' ).Trim("/")
                foreach ($method in $endpoint.Value.PSObject.Properties) {
                    $commandKey = $endpointPath, $method.Name -join ":"
                    if ($logLevel -le [PSFramework.Message.MessageLevel]::Verbose) {
                        Write-PSFMessage "Processing Command: $($commandKey)"
                    }
                    #region Case: Existing Command
                    if ($commands[$commandKey]) {
                        $commandObject = $commands[$commandKey]
                        $parameterSetName = $method.Value.operationId
                        $commandObject.ParameterSets[$parameterSetName] = $method.Value.description

                        Read-Parameters -CommandObject $commandObject -Parameters $method.Value.parameters -SwaggerObject $data -LogLevel $logLevel -ParameterSet $parameterSetName
                    }
                    #endregion Case: Existing Command

                    #region Case: New Command
                    else {
                        $commandNouns = foreach ($element in $endpointPath -split "/") {
                            if ($element -like "{*}") { continue }
                            [cultureinfo]::CurrentUICulture.TextInfo.ToTitleCase($element) -replace 's$' -replace '\$'
                        }
                        $commandObject = [Command]@{
                            Name                      = "$($verbs[$method.Name])-$($ModulePrefix)$($commandNouns -join '')"
                            Synopsis                  = $method.Value.summary
                            Description               = $method.Value.description
                            Method                    = $method.Name
                            EndpointUrl               = $effectiveEndpointPath
                            RestCommand               = $RestCommand
                            ParameterSets             = @{
                                'default' = $method.Value.description
                            }
                            ConvertToHashtableCommand = $ConvertToHashtableCommand
                        }
                        if ($ServiceName) { $commandObject.ServiceName = $ServiceName }
                        $commands[$commandKey] = $commandObject

                        foreach ($property in $commands[$commandKey].PSObject.Properties) {
                            if ($property.Name -eq 'Parameters') { continue }
                            if ($overrides.$commandKey.$($property.Name)) { $commandObject.$($property.Name) = $overrides.$commandKey.$($property.Name) }
                        }

                        # Parameters
                        Read-Parameters -CommandObject $commandObject -Parameters $method.Value.parameters -SwaggerObject $data -LogLevel $logLevel
                    }
                    #endregion Case: New Command

                    if ($logLevel -le [PSFramework.Message.MessageLevel]::Verbose) {
                        Write-PSFMessage -Message "Finished processing $($endpointPath) : $($method.Name) --> $($commandObject.Name)" -Target $commandObject -Data @{
                            Overrides     = $overrides
                            CommandObject = $commandObject
                        } -Tag done
                    }
                }
            }
        }
        #endregion Process Swagger file
    }
    end {
        foreach ($pair in $commands.GetEnumerator()) {
            Set-ParameterOverrides -Overrides $overrides -CommandObject $pair.Value -CommandKey $pair.Key
            Set-CommandOverrides -Overrides $overrides -CommandObject $pair.Value -CommandKey $pair.Key
        }
        $commands.Values
    }
}

function Export-ARCommand {
    <#
    .SYNOPSIS
        Writes AutoRest Command objects to file as a function definition.
     
    .DESCRIPTION
        Writes AutoRest Command objects to file as a function definition.
         
        To generate AutoRest Command objects, use a parsing command such as ConvertFrom-ARSwagger.
     
    .PARAMETER Path
        The Path in which the resulting set of commands should be placed.
     
    .PARAMETER GroupByEndpoint
        By default, each command will be placed in the OutPath folder.
        Setting this parameter will instead create a folder for the first element in each endpoint path and group the output by that.
     
    .PARAMETER Force
        Overwrite existing files.
        By default, this command will skip files of commands that were already created.
        Setting the -Force parameter enforces those being overwritten, updating the command, but discarding any manual edits.
     
    .PARAMETER NoHelp
        Export commands without generating help.
     
    .PARAMETER Command
        The command object(s) to write to file.
        Can be generated using the ConvertFrom-ARSwagger command.
     
    .EXAMPLE
        PS C:\> $commands | Export-ARCommand
         
        Exports all the commands specified to the current folder.
     
    .EXAMPLE
        PS C:\> ConvertFrom-ARSwagger @param | Export-ARCommand -Path C:\Code\modules\MyApi\functions -GroupByEndpoint -Force
         
        Takes the output of ConvertFrom-ARSwagger and writes it to the specified folder, creating a subfolder for each top-level api endpoint node.
        Existing files will be overwritten.
#>

    [CmdletBinding()]
    param (
        [PsfValidateScript('PSFramework.Validate.FSPath.Folder', ErrorString = 'PSFramework.Validate.FSPath.Folder')]
        [string]
        $Path = '.',
        
        [switch]
        $GroupByEndpoint,
        
        [switch]
        $Force,
        
        [switch]
        $NoHelp,
        
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [PSFramework.Utility.TypeTransformationAttribute([Command])]
        [Command[]]
        $Command
    )
    
    begin {
        $encoding = [System.Text.UTF8Encoding]::new($true)
        $targetFolder = Resolve-PSFPath $Path
        [PSFramework.Message.MessageLevel]$logLevel = Get-PSFConfigValue -FullName AutoRest.Logging.Level -Fallback "Warning"
    }
    process {
        foreach ($commandObject in $Command) {
            $folder = if ($GroupByEndpoint) {
                Join-Path -Path (Resolve-PSFPath $Path) -ChildPath ($commandObject.EndpointUrl -split "/" | Select-Object -First 1)
            }
            else {
                $targetFolder
            }
            
            if (-not ([System.IO.Directory]::Exists($folder))) {
                $null = New-Item -Path $folder -ItemType Directory -Force
            }
            
            $filePath = Join-Path -Path $folder -ChildPath "$($commandObject.Name).ps1"
            if (-not $Force -and (Test-Path -Path $filePath)) {
                if ($logLevel -le [PSFramework.Message.MessageLevel]::Verbose) {
                    Write-PSFMessage -Message "Skipping $($commandObject.Name), as $filePath already exists." -Target $commandObject
                }
                continue
            }
            if ($logLevel -le [PSFramework.Message.MessageLevel]::Verbose) {
                Write-PSFMessage -Message "Writing $($commandObject.Name) to $filePath" -Target $commandObject
            }
            try { [System.IO.File]::WriteAllText($filePath, $commandObject.ToCommand($NoHelp.ToBool()), $encoding) }
            catch { Write-PSFMessage -Level Warning -Message $_ -ErrorRecord $_ -EnableException $true -PSCmdlet $PSCmdlet -Target $commandObject -Data @{ Path = $filePath } }
        }
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'AutoRest' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'AutoRest' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'AutoRest' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -Module 'AutoRest' -Name 'Author' -Value $env:USERNAME -Initialize -Validation string -Description 'The user running this module. Will be added to output metadata.'
Set-PSFConfig -Module 'AutoRest' -Name 'Company' -Value 'Contoso ltd.' -Initialize -Validation string -Description 'The company owning the output. Will be added to output metadata.'
Set-PSFConfig -Module 'AutoRest' -Name 'Logging.Level' -Value 'Warning' -Initialize -Validation string -Description 'The maximum level of logging when generating commands from swagger file. Corresponds to PSFramework message levels. Set this to "Critical" to have all actions logged. Enabling this logging costs performance when parsing swagger files, but helps with debugging.'

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'AutoRest.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "AutoRest.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name AutoRest.alcohol
#>


New-PSFLicense -Product 'AutoRest' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-06-17") -Text @"
Copyright (c) 2021 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code