psfdx-development/psfdx-development.psm1

function Import-PsfdxSharedModule {
    [CmdletBinding()]
    param(
        [string] $ModuleName = 'psfdx-shared',
        [switch] $ForceImport
    )

    $forceImport = $ForceImport.IsPresent

    if (-not $forceImport -and (Get-Module -Name $ModuleName -ErrorAction SilentlyContinue)) {
        return
    }

    $candidates = @()

    $repoManifest = Join-Path -Path $PSScriptRoot -ChildPath (Join-Path '..' (Join-Path $ModuleName "$ModuleName.psd1"))
    $candidates += $repoManifest

    $moduleParent = Split-Path -Path $PSScriptRoot -Parent
    if ($moduleParent) {
        $siblingManifest = Join-Path -Path $moduleParent -ChildPath (Join-Path $ModuleName "$ModuleName.psd1")
        $candidates += $siblingManifest

        $moduleRoot = Split-Path -Path $moduleParent -Parent
        if ($moduleRoot) {
            $sharedBase = Join-Path -Path $moduleRoot -ChildPath $ModuleName
            if (Test-Path -LiteralPath $sharedBase) {
                try {
                    $versionDirectories = Get-ChildItem -Path $sharedBase -Directory -ErrorAction Stop | Sort-Object -Property Name -Descending
                    foreach ($dir in $versionDirectories) {
                        $candidates += Join-Path -Path $dir.FullName -ChildPath "$ModuleName.psd1"
                    }
                } catch {
                    # ignore directory inspection failures
                }
                $candidates += Join-Path -Path $sharedBase -ChildPath "$ModuleName.psd1"
            }
        }
    }

    $available = Get-Module -ListAvailable -Name $ModuleName -ErrorAction SilentlyContinue | Sort-Object -Property Version -Descending
    foreach ($item in $available) {
        if ($item.Path) {
            $candidates += $item.Path
        }
    }

    foreach ($candidate in $candidates | Where-Object { $_ } | Select-Object -Unique) {
        if (Test-Path -LiteralPath $candidate) {
            Import-Module -Name $candidate -ErrorAction Stop -Force:$forceImport
            return
        }
    }

    Import-Module -Name $ModuleName -ErrorAction Stop -Force:$forceImport
}

Import-PsfdxSharedModule

#region Projects & Config

function New-SalesforceProject {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Name,
        [Parameter(Mandatory = $false)][string][ValidateSet('standard', 'empty', 'analytics')] $Template = 'standard',
        [Parameter(Mandatory = $false)][string] $DefaultUserName = $null,

        [Parameter(Mandatory = $false)][string] $OutputDirectory,
        [Parameter(Mandatory = $false)][string] $DefaultPackageDirectory,
        [Parameter(Mandatory = $false)][string] $Namespace,
        [Parameter(Mandatory = $false)][switch] $GenerateManifest
    )
    $command = "sf project generate --name $Name"
    if ($OutputDirectory) {
        if (-not (Test-Path -LiteralPath $OutputDirectory)) {
            throw "Output directory '$OutputDirectory' does not exist."
        }
        $command += " --output-dir $OutputDirectory"
    }
    if ($DefaultPackageDirectory) { $command += " --default-package-dir $DefaultPackageDirectory" }
    if ($Namespace) { $command += " --namespace $Namespace" }
    if ($GenerateManifest) { $command += " --manifest" }
    $command += " --template $Template"
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    $result = Show-SalesforceResult -Result $result

    if (($null -ne $DefaultUserName) -and ($DefaultUserName -ne '')) {
        # 'sf config set target-org' writes to whichever project directory it runs in,
        # so set it from inside the newly generated project rather than passing a folder.
        $outputRoot = if ($result.outputDir) { $result.outputDir } else { (Get-Location).Path }
        $projectFolder = Join-Path -Path $outputRoot -ChildPath $Name
        if (-not (Test-Path -LiteralPath $projectFolder -PathType Container)) {
            throw "Generated project folder '$projectFolder' does not exist."
        }
        Push-Location -LiteralPath $projectFolder
        try {
            Set-SalesforceTargetOrg -Value $DefaultUserName @commonParams | Out-Null
        } finally {
            Pop-Location
        }
    }
    return $result
}

function Set-SalesforceTargetOrg {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Value,
        [Parameter(Mandatory = $false)][switch] $Global
    )
    $command = "sf config set target-org=$Value"
    if ($Global) { $command += " --global" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    return (Show-SalesforceResult -Result $result).successes
}

function Get-SalesforceTargetOrg {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][switch] $Global
    )
    # 'sf config get' has no --global flag. Every entry it returns says whether it is Local or Global, so -Global filters on that.
    $command = "sf config get target-org --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    $records = Show-SalesforceResult -Result $result
    if ($Global) { return @($records | Where-Object { $_.location -eq 'Global' }) }
    return $records
}

function Remove-SalesforceTargetOrg {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][switch] $Global
    )
    $command = "sf config unset target-org"
    if ($Global) { $command += " --global" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    return (Show-SalesforceResult -Result $result).successes
}

function Get-SalesforceConfig {
    [CmdletBinding()]
    Param()
    $command = "sf config list --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    Show-SalesforceResult -Result $result
}

function Set-SalesforceTargetDevHub {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Value,
        [Parameter(Mandatory = $false)][switch] $Global
    )

    $command = "sf config set target-dev-hub=$Value"
    if ($Global) { $command += " --global" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    return (Show-SalesforceResult -Result $result).successes
}

function Get-SalesforceTargetDevHub {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][switch] $Global
    )

    # 'sf config get' has no --global flag. Every entry it returns says whether it is Local or Global, so -Global filters on that.
    $command = "sf config get target-dev-hub --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    $records = Show-SalesforceResult -Result $result
    if ($Global) { return @($records | Where-Object { $_.location -eq 'Global' }) }
    return $records
}

function Remove-SalesforceTargetDevHub {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][switch] $Global
    )
    $command = "sf config unset target-dev-hub"
    if ($Global) { $command += " --global" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    return (Show-SalesforceResult -Result $result).successes
}

#endregion

#region Scratch Orgs

function Get-SalesforceScratchOrgs {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][switch] $SkipConnectionStatus,
        [Parameter(Mandatory = $false)][switch] $Last
    )

    $command = "sf org list --all"
    if ($SkipConnectionStatus) {
        $command += " --skip-connection-status"
    }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams

    $result = $result | ConvertFrom-Json
    $result = $result.result.scratchOrgs
    $result = $result | Select-Object orgId, instanceUrl, username, connectedStatus, isDevHub, lastUsed, alias
    if ($Last) {
        $result = $result | Sort-Object lastUsed -Descending | Select-Object -First 1
    }
    return $result
}

function New-SalesforceScratchOrg {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $TargetDevHub,
        [Parameter(Mandatory = $false)][switch] $SetDefault,
        [Parameter(Mandatory = $false)][int] $DurationDays,
        [Parameter(Mandatory = $false)][string] $DefinitionFile = 'config/project-scratch-def.json',
        [Parameter(Mandatory = $false)][int] $WaitMinutes,
        [Parameter(Mandatory = $false)][string][ValidateSet('developer', 'enterprise', 'group', 'professional', 'partner-developer', 'partner-enterprise', 'partner-group', 'partner-professional')] $Edition,
        [Parameter(Mandatory = $false)][string] $Snapshot,
        [Parameter(Mandatory = $false)][string] $AdminEmail,
        [Parameter(Mandatory = $false)][string] $Description,
        [Parameter(Mandatory = $false)][string] $Name,
        [Parameter(Mandatory = $false)][string][ValidateSet('preview', 'previous')] $Release,
        [Parameter(Mandatory = $false)][string] $SourceOrgId,
        [Parameter(Mandatory = $false)][string] $AdminUsername
    )
    $command = "sf org create scratch"
    if ($TargetDevHub) { $command += " --target-dev-hub $TargetDevHub" }
    if ($SetDefault) { $command += " --set-default" }
    if ($DurationDays) { $command += " --duration-days $DurationDays" }
    $command += " --definition-file $DefinitionFile"
    if ($WaitMinutes) { $command += " --wait $WaitMinutes" }
    if ($Edition) { $command += " --edition $Edition" }
    if ($Snapshot) { $command += " --snapshot $Snapshot" }
    if ($AdminEmail) { $command += " --admin-email $AdminEmail" }
    if ($Description) { $command += " --description `"$Description`"" }
    if ($Name) { $command += " --name `"$Name`"" }
    if ($Release) { $command += " --release $Release" }
    if ($SourceOrgId) { $command += " --source-org $SourceOrgId" }
    if ($AdminUsername) { $command += " --username $AdminUsername" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    Show-SalesforceResult -Result $result
}

function Remove-SalesforceScratchOrg {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $TargetOrg,
        [Parameter()][switch] $NoPrompt
    )
    $command = "sf org delete scratch --target-org $TargetOrg"
    if ($NoPrompt) {
        $command += " --no-prompt"
    }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command $command @commonParams
}

function Remove-SalesforceScratchOrgs {
    [CmdletBinding()]
    Param()

    $scratchOrgs = Get-SalesforceScratchOrgs
    foreach ($scratchOrg in $scratchOrgs) {
        Remove-SalesforceScratchOrg -TargetOrg ($scratchOrg.username) -NoPrompt
    }
}

#endregion

#region Apex Testing

function Test-SalesforceApex {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $ClassName,
        [Parameter(Mandatory = $false)][string] $TestName,

        [Parameter(Mandatory = $false)][string][ValidateSet('human', 'tap', 'junit', 'json')] $ResultFormat = 'json',

        [Parameter(Mandatory = $false)][switch] $Concise,
        [Parameter(Mandatory = $false)][switch] $CodeCoverage,
        [Parameter(Mandatory = $false)][switch] $CodeCoverageDetailed,
        [Parameter(Mandatory = $false)][int] $WaitMinutes = 10,

        [Parameter(Mandatory = $false)][string] $OutputDirectory,
        [Parameter(Mandatory = $false)][switch] $TestsInProject,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )

    $command = "sf apex run test"

    $command += Get-SalesforceCliApexTestParams -TestsInProject:$TestsInProject -ClassName $ClassName -TestName $TestName

    if ($OutputDirectory) {
        if (-not (Test-Path -LiteralPath $OutputDirectory)) {
            throw "Output directory '$OutputDirectory' does not exist."
        }
        $command += " --output-dir $OutputDirectory"
    }
    if ($WaitMinutes) { $command += " --wait $WaitMinutes" }

    if ($Concise) { $command += " --concise" }
    if ($CodeCoverage) { $command += " --code-coverage" }
    if ($CodeCoverageDetailed) { $command += " --detailed-coverage" }
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $command += " --result-format $ResultFormat"

    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters

    if ($ResultFormat -ne 'json') {
        Invoke-Salesforce -Command $command @commonParams
        return
    }
    $result = Invoke-Salesforce -Command $command @commonParams
    $result = $result | ConvertFrom-Json

    $summary = $result.result.summary
    if ($null -eq $summary) {
        Write-Debug ($result | ConvertTo-Json -Depth 10)
        throw "Salesforce CLI returned no test summary. $($result.message)".Trim()
    }

    $result.result.tests
    if ($summary.outcome -ne 'Passed') {
        throw ("$($summary.failing) Tests Failed")
    }

    if ((-not $CodeCoverage) -and (-not $CodeCoverageDetailed)) {
        return
    }

    [int]$codeCoverage = ($summary.testRunCoverage -replace '%')
    if ($codeCoverage -lt 75) {
        $result.result.coverage.coverage
        throw "Insufficient code coverage ${codeCoverage}%"
    }
}

function Get-SalesforceCliApexTestParams {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $ClassName,
        [Parameter(Mandatory = $false)][string] $TestName,
        [Parameter(Mandatory = $false)][switch] $TestsInProject
    )

    $value = ""
    if ($TestsInProject.IsPresent) {
        $testClassNames = Get-SalesforceApexTestClassNames
        if (-not (Get-Command -Name ConvertTo-SalesforceCliApexTestParams -ErrorAction SilentlyContinue)) {
            Import-PsfdxSharedModule -ForceImport
        }
        $value += ConvertTo-SalesforceCliApexTestParams -TestClassNames $testClassNames
    } elseif ($ClassName -and $TestName) {
        $value += " --tests $ClassName.$TestName" # Run specific Test in a Class
    } elseif ((-not $TestName) -and ($ClassName)) {
        $value += " --tests $ClassName"     # Run Test Class
    }
    return $value
}

function Get-SalesforceCodeCoverage {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $ApexClassOrTrigger = $null,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )
    $query = "SELECT ApexTestClass.Name, TestMethodName, ApexClassOrTrigger.Name, NumLinesUncovered, NumLinesCovered, Coverage "
    $query += "FROM ApexCodeCoverage "
    $results = Select-SalesforceRecords -Query $query -TargetOrg $TargetOrg -UseToolingApi
    if (($null -ne $ApexClassOrTrigger) -and ($ApexClassOrTrigger -ne '')) {
        $results = $results | Where-Object { $_.ApexClassOrTrigger.Name -eq $ApexClassOrTrigger -or $_.ApexTestClass.Name -eq $ApexClassOrTrigger }
    }

    $values = @()
    foreach ($item in $results) {
        $value = New-Object -TypeName PSObject
        $value | Add-Member -MemberType NoteProperty -Name 'ApexClassOrTrigger' -Value $item.ApexClassOrTrigger.Name
        $value | Add-Member -MemberType NoteProperty -Name 'ApexTestClass' -Value $item.ApexTestClass.Name
        $value | Add-Member -MemberType NoteProperty -Name 'TestMethodName' -Value $item.TestMethodName

        $codeCoverage = 0
        $codeLength = $item.NumLinesCovered + $item.NumLinesUncovered
        if ($codeLength -gt 0) {
            $codeCoverage = $item.NumLinesCovered / $codeLength
        }
        $value | Add-Member -MemberType NoteProperty -Name 'CodeCoverage' -Value $codeCoverage.toString("P")
        $codeCoverageOK = $false
        if ($codeCoverage -ge 0.75) { $codeCoverageOK = $true }

        $value | Add-Member -MemberType NoteProperty -Name 'CodeCoverageOK' -Value $codeCoverageOK
        $value | Add-Member -MemberType NoteProperty -Name 'NumLinesCovered' -Value $item.NumLinesCovered
        $value | Add-Member -MemberType NoteProperty -Name 'NumLinesUncovered' -Value $item.NumLinesUncovered
        $values += $value
    }

    return $values
}

function Watch-SalesforceApex {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $ProjectFolder,
        [Parameter(Mandatory = $false)][int] $CooldownMilliseconds = 300,
        [Parameter(Mandatory = $false)][switch] $IgnoreErrors
    )

    # Default to Current Folder
    if (-not $ProjectFolder) {
        $ProjectFolder = (Get-Location).Path
    }

    # Folder does not Exist
    if (-not (Test-Path -LiteralPath $ProjectFolder -PathType Container)) {
        throw "Project folder '$ProjectFolder' does not exist."
    }

    # Watch File System Changes
    $watcherInfo = Start-SalesforceApexWatcher -ProjectFolder $ProjectFolder
    $sourceIdentifiers = $watcherInfo.SourceIdentifiers
    $recentEvents = [System.Collections.Hashtable]::Synchronized(@{})

    try {
        Write-Host "Watching $($watcherInfo.Project) for Apex changes. Press Ctrl+C to stop." -ForegroundColor Cyan
        while ($true) {
            $apexChangeEvent = Receive-SalesforceApexWatcherEvent -SourceIdentifiers $sourceIdentifiers -TimeoutSeconds 1
            if (-not $apexChangeEvent) {
                continue
            }

            # On File Changed
            try {
                Invoke-SalesforceApexChangeEvent -ApexChangeEvent $apexChangeEvent -ProjectFolder $watcherInfo.Project -RecentEvents $recentEvents -CooldownMilliseconds $CooldownMilliseconds -IgnoreErrors:$IgnoreErrors.IsPresent
            } finally {
                Remove-Event -EventIdentifier $apexChangeEvent.EventIdentifier -ErrorAction SilentlyContinue
            }
        }
    } finally {
        Stop-SalesforceApexWatcher -SourceIdentifiers $sourceIdentifiers -Watcher $watcherInfo.Watcher
    }
}

#region "Salesforce Apex Watcher Helpers"

function Invoke-SalesforceApex {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $ApexFile,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )
    $command = "sf apex run --file $ApexFile"
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    $command += " --json"
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $result = Invoke-Salesforce -Command $command @commonParams
    return Show-SalesforceResult -Result $result
}

function New-SalesforceApexWatcher {
    Param(
        [Parameter(Mandatory = $true)][string] $ProjectFolder
    )

    $project = (Get-Item -LiteralPath $ProjectFolder).FullName
    Write-Verbose ("Watching Project Folder: " + $project)
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = $project
    $watcher.Filter = '*.*'
    $watcher.IncludeSubdirectories = $true
    $watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor [System.IO.NotifyFilters]::LastWrite
    $watcher.EnableRaisingEvents = $true

    return [pscustomobject]@{
        Project = $project
        Watcher = $watcher
    }
}

function Get-SalesforceApexEventPaths {
    Param(
        [Parameter(Mandatory = $true)][System.IO.FileSystemEventArgs] $EventArgs
    )

    return @($EventArgs.FullPath)
}

function Register-SalesforceApexWatcherEvents {
    Param(
        [Parameter(Mandatory = $true)][System.IO.FileSystemWatcher] $Watcher
    )

    $sourcePrefix = "Watch-SalesforceApex_$([guid]::NewGuid())"
    $sourceIdentifiers = @()
    foreach ($eventName in 'Changed', 'Created', 'Renamed') {
        $sourceId = "${sourcePrefix}:$eventName"
        Register-ObjectEvent -InputObject $Watcher -EventName $eventName -SourceIdentifier $sourceId | Out-Null
        $sourceIdentifiers += $sourceId
    }

    return $sourceIdentifiers
}

function Start-SalesforceApexWatcher {
    Param(
        [Parameter(Mandatory = $true)][string] $ProjectFolder
    )

    $watcherInfo = New-SalesforceApexWatcher -ProjectFolder $ProjectFolder
    $sourceIdentifiers = Register-SalesforceApexWatcherEvents -Watcher $watcherInfo.Watcher

    return [pscustomobject]@{
        Project = $watcherInfo.Project
        Watcher = $watcherInfo.Watcher
        SourceIdentifiers = $sourceIdentifiers
    }
}

function Stop-SalesforceApexWatcher {
    Param(
        [Parameter(Mandatory = $true)][string[]] $SourceIdentifiers,
        [Parameter(Mandatory = $true)][System.IO.FileSystemWatcher] $Watcher
    )

    foreach ($identifier in $SourceIdentifiers) {
        Unregister-Event -SourceIdentifier $identifier -ErrorAction SilentlyContinue
    }
    $Watcher.EnableRaisingEvents = $false
    $Watcher.Dispose()
}

function Receive-SalesforceApexWatcherEvent {
    Param(
        [Parameter(Mandatory = $true)][string[]] $SourceIdentifiers,
        [Parameter(Mandatory = $false)][int] $TimeoutSeconds = 1
    )

    $apexChangeEvent = Wait-Event -Timeout $TimeoutSeconds
    if (-not $apexChangeEvent) {
        return $null
    }

    if ($apexChangeEvent.SourceIdentifier -notin $SourceIdentifiers) {
        Remove-Event -EventIdentifier $apexChangeEvent.EventIdentifier -ErrorAction SilentlyContinue
        return $null
    }

    return $apexChangeEvent
}

function Invoke-SalesforceApexChangeEvent {
    Param(
        [Parameter(Mandatory = $true)][System.Management.Automation.PSEventArgs] $ApexChangeEvent,
        [Parameter(Mandatory = $true)][string] $ProjectFolder,
        [Parameter(Mandatory = $true)][System.Collections.Hashtable] $RecentEvents,
        [Parameter(Mandatory = $true)][int] $CooldownMilliseconds,
        [Parameter(Mandatory = $false)][switch] $IgnoreErrors
    )

    $paths = Get-SalesforceApexEventPaths -EventArgs $ApexChangeEvent.SourceEventArgs

    foreach ($path in $paths) {
        if (-not (Wait-SalesforceApexCooldown -Path $path -RecentEvents $RecentEvents -CooldownMilliseconds $CooldownMilliseconds)) {
            continue
        }

        Watch-SalesforceApexAction -FilePath $path -ProjectFolder $ProjectFolder -IgnoreErrors:$IgnoreErrors.IsPresent | Out-Null
        $RecentEvents[$path] = (Get-Date).AddMilliseconds($CooldownMilliseconds)
    }
}

function Wait-SalesforceApexCooldown {
    Param(
        [Parameter(Mandatory = $true)][string] $Path,
        [Parameter(Mandatory = $true)][System.Collections.Hashtable] $RecentEvents,
        [Parameter(Mandatory = $true)][int] $CooldownMilliseconds
    )

    $now = Get-Date
    $nextAllowed = $RecentEvents[$Path]
    if ($nextAllowed -and ($now -lt $nextAllowed)) {
        return $false
    }

    Start-Sleep -Milliseconds $CooldownMilliseconds
    return $true
}

function Test-SalesforceApexPath {
    Param(
        [Parameter(Mandatory = $true)][string] $Path,
        [Parameter(Mandatory = $true)][string[]] $Extensions
    )

    if ([string]::IsNullOrWhiteSpace($Path)) { return $false }

    $extension = [System.IO.Path]::GetExtension($Path)
    if (-not $extension) { return $false }

    $extension = $extension.ToLowerInvariant()
    if ($extension -notin $Extensions) { return $false }

    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }

    return $true
}

function Watch-SalesforceApexAction {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $FilePath,
        [Parameter(Mandatory = $false)][string] $ProjectFolder,
        [Parameter(Mandatory = $false)][switch] $IgnoreErrors
    )

    try {
        Write-Verbose ("Processing file: " + $FilePath)

        if (-not $ProjectFolder) {
            $ProjectFolder = (Get-Location).Path
        }

        $type = Get-SalesforceType -FileName $FilePath
        if (($type -ne 'ApexClass') -and ($type -ne 'ApexTrigger')) {
            return
        }

        $name = Get-SalesforceName -FileName $FilePath
        Write-Host "Deploying $type ${name}..." -ForegroundColor Cyan

        $command = "sf project deploy start"
        $command += " --metadata ${type}:${name}"
        $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
        $testClassNames = Get-SalesforceApexTestClassNames -FilePath $FilePath -ProjectFolder $ProjectFolder
        $testLevel = if ($testClassNames -and $testClassNames.Count -gt 0) { 'SpecificTests' } else { 'NoTests' }
        $command += Get-SalesforceApexCliTestParams @commonParams -TestLevel $testLevel -Tests $testClassNames
        $command += " --ignore-warnings"
        if ($IgnoreErrors) { $command += " --ignore-errors" }
        $command += " --json"
        $deployJson = Invoke-Salesforce -Command $command @commonParams
        Show-SalesforceResult -Result $deployJson

        $successMessage = "Deployed $type ${name}"
        if ($testClassNames -and $testClassNames.Count -gt 0) {
            $successMessage += " and successfully ran tests (" + ($testClassNames -join ', ') + ")"
        }
        $successMessage += "."
        Write-Host $successMessage -ForegroundColor Green
    }
    catch {
        Write-Error $_
    }
}

function Get-SalesforceType {
    [CmdletBinding()]
    Param([Parameter(Mandatory = $false)][string] $FileName)

    if ([string]::IsNullOrWhiteSpace($FileName)) {
        return ""
    }
    if ($FileName.EndsWith(".cls", [System.StringComparison]::OrdinalIgnoreCase)) {
        return "ApexClass"
    }
    if ($FileName.EndsWith(".trigger", [System.StringComparison]::OrdinalIgnoreCase)) {
        return "ApexTrigger"
    }
    return ""
}

function Get-SalesforceName {
    [CmdletBinding()]
    Param([Parameter(Mandatory = $false)][string] $FileName)

    if ([string]::IsNullOrWhiteSpace($FileName)) {
        return ""
    }
    # Parse the path rather than calling Get-Item: the watcher also fires for files that
    # have already been renamed or deleted by the time this runs.
    $name = [System.IO.Path]::GetFileNameWithoutExtension($FileName)
    Write-Verbose ("Apex Name: " + $name)
    return $name
}

#endregion

function Get-SalesforceApexTestClassNames {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][string] $FilePath,
        [Parameter(Mandatory = $false)][string] $ProjectFolder
    )

    if ($FilePath) {
        return Get-SalesforceApexTestClassNamesFromFile -FilePath $FilePath
    }

    if (!$ProjectFolder) {
        $ProjectFolder = (Get-Location).Path
    }
    if (-not (Test-Path -LiteralPath $ProjectFolder -PathType Container)) {
        throw "Project folder '$ProjectFolder' does not exist."
    }

    $testFiles = Get-ChildItem -Path $ProjectFolder -Recurse -Filter '*.cls' -File -ErrorAction SilentlyContinue
    $testFiles = $testFiles | Where-Object {
        Select-String -Path $_.FullName -Pattern '@isTest' -SimpleMatch -Quiet
    }

    $testClassNames = $testFiles | ForEach-Object {
        [System.IO.Path]::GetFileNameWithoutExtension($_.Name)
    } | Sort-Object -Unique

    return @($testClassNames)
}

function Get-SalesforceApexTestClassNamesFromFile {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $FilePath
    )

    if (-not (Test-Path -LiteralPath $FilePath -PathType Leaf)) {
        throw "File '$FilePath' does not exist."
    }

    $parentFolder = Split-Path -Path $FilePath -Parent
    $rootFolder = Split-Path -Path $parentFolder -Parent
    if ([string]::IsNullOrWhiteSpace($rootFolder)) {
        $rootFolder = $parentFolder
    }
    $rootFolder = (Get-Item -LiteralPath $rootFolder).FullName

    $className = [System.IO.Path]::GetFileNameWithoutExtension($FilePath)

    $testFiles = Get-ChildItem -Path $rootFolder -Recurse -Filter '*.cls' -File -ErrorAction SilentlyContinue
    $matchingTests = $testFiles | Where-Object {
        (Select-String -Path $_.FullName -Pattern '@isTest' -SimpleMatch -Quiet) -and
        (Test-SalesforceApexTestReference -Path $_.FullName -ClassName $className)
    }

    $matchingTests | ForEach-Object {
        [System.IO.Path]::GetFileNameWithoutExtension($_.Name)
    } | Sort-Object -Unique
}

function Get-SalesforceApexClass {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Name,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )
    $query = "SELECT Id, Name, Body FROM ApexClass WHERE Name = " + (ConvertTo-SalesforceSoqlLiteral -Value $Name) + " LIMIT 1"
    return Select-SalesforceRecords -Query $query -UseToolingApi -TargetOrg $TargetOrg
}

#endregion

#region Apex Scaffolding

function New-SalesforceApexClass {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Name,
        [Parameter(Mandatory = $false)][string]
            [ValidateSet('DefaultApexClass', 'ApexUnitTest', 'InboundEmailService')]
            $Template = 'DefaultApexClass',
        # No default: when omitted, --output-dir is left off so the CLI picks the
        # project's own default package directory.
        [Parameter(Mandatory = $false)][string] $OutputDirectory
    )
    $command = "sf apex generate class"
    $command += " --name $Name"
    $command += " --template $Template"
    if ($PSBoundParameters.ContainsKey('OutputDirectory') -and -not [string]::IsNullOrWhiteSpace($OutputDirectory)) {
        if (-not (Test-Path -LiteralPath $OutputDirectory)) {
            throw "Output directory '$OutputDirectory' does not exist."
        }
        $command += " --output-dir $OutputDirectory"
    }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command $command @commonParams
}

function New-SalesforceApexTrigger {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $Name,
        [Parameter(Mandatory = $false)][string]
            [ValidateSet('before insert', 'before update', 'before delete', 'after insert', 'after update', 'after delete', 'after undelete')]
            $Event = 'before insert',
        [Parameter(Mandatory = $false)][string] $SObject,
        # No default: when omitted, --output-dir is left off so the CLI picks the
        # project's own default package directory.
        [Parameter(Mandatory = $false)][string] $OutputDirectory
    )
    $command = "sf apex generate trigger"
    $command += " --name $Name"
    $command += " --event $Event"
    if ($SObject) { $command += " --sobject $SObject" }
    if ($PSBoundParameters.ContainsKey('OutputDirectory') -and -not [string]::IsNullOrWhiteSpace($OutputDirectory)) {
        if (-not (Test-Path -LiteralPath $OutputDirectory)) {
            throw "Output directory '$OutputDirectory' does not exist."
        }
        $command += " --output-dir $OutputDirectory"
    }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command $command @commonParams
}

#endregion

#region LWC Dev Server

function Install-SalesforceLwcDevServer {
    [CmdletBinding()]
    Param()
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command "sf plugins install @salesforce/plugin-lightning-dev" @commonParams
}

function Test-SalesforceLightningDevPluginInstalled {
    [CmdletBinding()]
    Param()
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    $raw = Invoke-Salesforce -Command "sf plugins --core --json" @commonParams
    $text = ($raw | Out-String)
    return ($text -match '@salesforce/plugin-lightning-dev')
}

function Start-SalesforceLwcDevServer {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $false)][ValidateSet('App', 'Component', 'Site')][string] $Mode = 'App',
        [Parameter(Mandatory = $false)][string] $Name,
        [Parameter(Mandatory = $false)][ValidateSet('ios', 'android')][string] $DeviceType,
        [Parameter(Mandatory = $false)][string] $TargetOrg
    )
    if ($PSBoundParameters.ContainsKey('DeviceType') -and $Mode -ne 'App') {
        throw "-DeviceType is only supported with -Mode App."
    }
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    if (-not (Test-SalesforceLightningDevPluginInstalled @commonParams)) {
        throw "The Salesforce CLI plugin '@salesforce/plugin-lightning-dev' is not installed. Run Install-SalesforceLwcDevServer, then try again."
    }
    $command = "sf lightning dev $($Mode.ToLowerInvariant())"
    if (-not [string]::IsNullOrWhiteSpace($Name)) {
        $escapedName = $Name -replace '"', '`"'
        $command += " --name `"$escapedName`""
    }
    if ($DeviceType) { $command += " --device-type $DeviceType" }
    if ($PSBoundParameters.ContainsKey('TargetOrg') -and -not [string]::IsNullOrWhiteSpace($TargetOrg)) { $command += " --target-org $TargetOrg" }
    Invoke-Salesforce -Command $command @commonParams
}

#endregion

#region LWC / Jest Testing

function Install-SalesforceJest {
    [CmdletBinding()]
    Param()
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    if (Get-Command yarn -ErrorAction SilentlyContinue) {
        Invoke-Salesforce -Command "yarn add -D @salesforce/sfdx-lwc-jest" @commonParams
    } else {
        Invoke-Salesforce -Command "npm install -D @salesforce/sfdx-lwc-jest" @commonParams
    }
}

function New-SalesforceJestTest {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)][string] $LwcName,
        [Parameter(Mandatory = $false)][string] $ProjectPath = '.',
        [Parameter(Mandatory = $false)][switch] $Force
    )
    # The legacy 'sf force lightning lwc test create' command was removed from the Salesforce CLI,
    # so the Jest test scaffold is written directly.
    if ($LwcName -notmatch '^[A-Za-z][A-Za-z0-9_]*$') {
        throw "LWC name '$LwcName' is not valid. Use letters, numbers and underscores, starting with a letter."
    }
    if (-not (Test-Path -LiteralPath $ProjectPath -PathType Container)) {
        throw "Project path '$ProjectPath' does not exist."
    }
    $lwcDir = Join-Path $ProjectPath (Join-Path 'force-app' (Join-Path 'main' (Join-Path 'default' (Join-Path 'lwc' $LwcName))))
    $componentFile = Join-Path $lwcDir "$LwcName.js"
    if (-not (Test-Path -LiteralPath $componentFile -PathType Leaf)) {
        throw "LWC component file '$componentFile' does not exist."
    }
    $testsDir = Join-Path $lwcDir '__tests__'
    $testFile = Join-Path $testsDir "$LwcName.test.js"
    if ((Test-Path -LiteralPath $testFile) -and -not $Force) {
        throw "Jest test '$testFile' already exists. Use -Force to overwrite it."
    }
    if (-not (Test-Path -LiteralPath $testsDir)) {
        New-Item -ItemType Directory -Path $testsDir | Out-Null
    }
    $tag = ($LwcName -creplace '([A-Z])', '-$1').ToLowerInvariant()
    $content = @"
import { createElement } from 'lwc';
import $LwcName from 'c/$LwcName';

describe('c-$tag', () => {
    afterEach(() => {
        // The jsdom instance is shared across test cases in a single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('renders', () => {
        const element = createElement('c-$tag', { is: $LwcName });
        document.body.appendChild(element);
        expect(element).not.toBeNull();
    });
});
"@

    $content = $content -replace "`r`n", "`n"
    $fullPath = Join-Path (Resolve-Path -LiteralPath $testsDir).ProviderPath "$LwcName.test.js"
    [System.IO.File]::WriteAllText($fullPath, $content, (New-Object System.Text.UTF8Encoding($false)))
    return Get-Item -LiteralPath $fullPath
}

function Test-SalesforceJest {
    [CmdletBinding()]
    Param()
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command "npm run test:unit" @commonParams
}

function Debug-SalesforceJest {
    [CmdletBinding()]
    Param()
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command "npm run test:unit:debug" @commonParams
}

function Watch-SalesforceJest {
    [CmdletBinding()]
    Param()
    $commonParams = Get-PsfdxCommonParameterSplat -BoundParameters $PSBoundParameters
    Invoke-Salesforce -Command "npm run test:unit:watch" @commonParams
}

#endregion