<# .SYNOPSIS 导出本地 OpenAPI 文档。 .DESCRIPTION 从本地已启动的服务获取 /v3/api-docs.yaml(或 JSON),写入 docs 目录。 默认同时生成面向 AI Agent 的接口索引 docs/openapi.index.md。 生成的 OpenAPI 快照已被 .gitignore 忽略;索引文件可按需提交或单独发送。 .PARAMETER BaseUrl 服务地址,默认 http://localhost:18092。 .PARAMETER OutFile 输出文件路径,默认 docs/openapi.local.yaml。 扩展名为 .json 时导出 JSON,否则导出 YAML。 .PARAMETER IndexFile 接口索引输出路径,默认 docs/openapi.index.md。 .PARAMETER NoIndex 跳过接口索引生成。 .EXAMPLE .\scripts\export-openapi.ps1 .EXAMPLE .\scripts\export-openapi.ps1 -BaseUrl http://192.168.1.10:18092 -OutFile docs/openapi.local.json .EXAMPLE .\scripts\export-openapi.ps1 -NoIndex #> param( [string]$BaseUrl = "http://localhost:18092", [string]$OutFile, [string]$IndexFile, [switch]$NoIndex ) $ErrorActionPreference = "Stop" $RootDir = Split-Path -Parent $PSScriptRoot if ([string]::IsNullOrWhiteSpace($OutFile)) { $OutFile = Join-Path $RootDir "docs\openapi.local.yaml" } if ([string]::IsNullOrWhiteSpace($IndexFile)) { $IndexFile = Join-Path $RootDir "docs\openapi.index.md" } $BaseUrl = $BaseUrl.TrimEnd("/") $OutFile = [System.IO.Path]::GetFullPath($OutFile) $IndexFile = [System.IO.Path]::GetFullPath($IndexFile) $OutDir = Split-Path -Parent $OutFile if (-not (Test-Path -LiteralPath $OutDir)) { New-Item -ItemType Directory -Path $OutDir -Force | Out-Null } if ([System.IO.Path]::GetExtension($OutFile) -ieq ".json") { $ApiPath = "/v3/api-docs" } else { $ApiPath = "/v3/api-docs.yaml" } $Url = "$BaseUrl$ApiPath" Write-Host "Fetching $Url" Invoke-WebRequest -Uri $Url -OutFile $OutFile -UseBasicParsing Write-Host "OpenAPI exported to $OutFile" if ($NoIndex) { exit 0 } if ($IndexFile -eq $OutFile) { Write-Warning "接口索引不能与 OpenAPI 输出文件相同,跳过接口索引生成。" exit 0 } $IndexScript = Join-Path $PSScriptRoot "openapi-index.py" if (-not (Test-Path -LiteralPath $IndexScript)) { Write-Warning "未找到 $IndexScript,跳过接口索引生成。" exit 0 } $Python = $null foreach ($Candidate in @("python", "python3")) { $Command = Get-Command $Candidate -ErrorAction SilentlyContinue if ($Command) { $Python = $Command.Source break } } if (-not $Python) { Write-Warning "未找到 Python,跳过接口索引生成。安装 Python 或使用 -NoIndex 关闭该提示。" exit 0 } $IndexDir = Split-Path -Parent $IndexFile if (-not (Test-Path -LiteralPath $IndexDir)) { New-Item -ItemType Directory -Path $IndexDir -Force | Out-Null } $IndexInput = $OutFile $TempIndexInput = $null if ([System.IO.Path]::GetExtension($OutFile) -ine ".json") { $TempIndexInput = [System.IO.Path]::GetTempFileName() try { Invoke-WebRequest -Uri "$BaseUrl/v3/api-docs" -OutFile $TempIndexInput -UseBasicParsing $IndexInput = $TempIndexInput } catch { Write-Warning "获取 OpenAPI JSON 失败,跳过接口索引生成:$($_.Exception.Message)" $IndexInput = $null } } if ($IndexInput) { & $Python $IndexScript $IndexInput $IndexFile if ($LASTEXITCODE -ne 0) { Write-Warning "接口索引生成失败(退出码 $LASTEXITCODE)。" } } if ($TempIndexInput -and (Test-Path -LiteralPath $TempIndexInput)) { Remove-Item -LiteralPath $TempIndexInput -Force }